repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

docs: resolve plugin design TODOs into SPEC §9 (#1)

f3e2b0374f8a87811a454df4ad119ea2c32a0822

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

* docs: resolve plugin design TODOs into SPEC §9

Close the open design-doc TODO sections by reconciling them into the
canonical spec. New SPEC §9 subsections:

- §9.15 Dependency Resolution — presence + API-generation checks,
  topological load order, cycle detection; no version-range solving in v1.
- §9.16 Plugin Hot-Reload — whole-domain replacement, triggers, rollback,
  session continuity, dependents rebinding.
- §9.17 Plugin Error Model — per-phase fault isolation; host never crashes.
- §9.18 Inter-Plugin Messaging Bus — smith.bus.* namespaced pub/sub.

Also: fix §9.10 to name LuaLS/EmmyLua as the canonical annotation dialect
with required tags; add smith.bus.* to the namespace list; add
`smith plugins reload` to §10.2 CLI surface.

Convert PLUGIN-SDK-DESIGN.md and AI-CRATE-DESIGN.md TODO checklists into
resolution tables pointing each item to its canonical SPEC section or
implementation tracker.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* docs: add host configuration reload contract (SPEC §9.19)

Plugin reload (§9.16) covered plugin code; Smith's own settings also need
runtime reload. New §9.19 mirrors the §9.16 contract shape:

- scope: re-evaluate config cascade layers 1-4; CLI flags stay fixed,
- triggers: /reload-config command via smith.config.reload(), config file
  watch, and automatic re-evaluation after a plugin reload changes
  layer-3 contributions,
- sequence: validate + re-resolve models fully, swap atomically, roll back
  on any failure with exact key path,
- effects: theme, keybindings, active tools, resolved model; then a
  config_changed plugin event with changed key paths,
- continuity: in-flight turns and tool executions keep old values; config
  reload never touches plugin domains or the session,
- restart-only set: CLI flags, XDG dirs, session identity, run mode,
  bundled providers.json.

Cross-refs wired in §5.6 (cascade), §9.8 (event), §9.10 (smith.config.*),
§9.11 (/reload-config built-in).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* docs: expose config reload to RPC mode (SPEC §9.19, §10.2)

RPC clients (e.g. IDE integrations editing config on the user's behalf)
need to trigger a host config reload without restarting the process. Add
the config/reload JSON-RPC method as a §9.19 trigger; the response carries
changed key paths on success or the validation failure verbatim. Eval mode
stays startup-only.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* docs: record deferred RPC method catalog intent (SPEC §10.2)

The RPC surface is expected to mirror the Lua SDK surface (§9.10) with
mode-specific additions and omissions, not define an independent API.
Pin that intent so the future catalog spec starts from §9.10.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* feat(prototypes): p02 lua interface descriptor — PASS

Proves SPEC §9.6 candidate 1: plain Lua descriptors + runtime validation
support community-defined plugin interfaces.

Evidence (cargo run, exit 0):
- conforming implementation passes with zero diagnostics,
- missing function fails with exact path (impl/missing_fn.lua.cancel),
- wrong shape fails with expected/actual (status: expected function, got
  string),
- extra implementation fields are hidden through the interface view,
- runtime arg validation rejects bad call types naming fn/param
  (mlua reports Lua integers as "integer", not "number").

Also add prototypes/.cargo/config.toml capping lints at warn for
disposable prototype code; production zero-warnings policy unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* feat(prototypes): p06 session codec recovery — PASS with finding

Proves SPEC §6.6 recovery claims for length-prefixed CBOR sequences:
- truncated tail (mid-body and mid-prefix) stops parsing; prior entries
  survive,
- corrupt entry BODY skips precisely with warning (framing intact),
- unknown future variants are distinguishable from corruption via
  two-stage decode (ciborium::Value, then typed), preserved raw, and
  survive a v1 rewrite → v2 read roundtrip.

Finding for §6.6: "corrupt entry: skip + warn if possible" holds only
while the length prefix is intact. A corrupted length prefix
desynchronizes framing; all subsequent entries are unrecoverable and
indistinguishable from truncation. Spec should state this boundary.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* feat(prototypes): p07 streamfn agent loop — PASS with finding

Proves SPEC §5.4 + §6.1-§6.4: a miniature agent loop drives text/tool/
done provider events through StreamFn only (no provider impl imports)
and produces deterministic AgentEvent sequences. BeforeToolCall hooks
allow/block/replace-args all verified; blocked calls never execute the
tool and surface to the provider as error tool results.

Finding for §6.4: blocked-call event semantics are unspecified — this
prototype chose ToolExecutionStart + ToolExecutionEnd(is_error) plus an
error tool result fed to the provider. Spec should state the contract.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* feat(prototypes): p04 plugin install/uninstall — PASS with findings

Proves SPEC §9.2/§9.3/§9.5: local-path + git-URL install into
data_dir/smith/plugins/<org>/<name>/, name charset + smith/* namespace
enforcement, restricted empty-env manifest evaluation (os/require
blocked, pure data only), smith_api default 1 + future-generation
refusal, no entry-code execution during install (armed side effect did
not fire), duplicate refusal without --force, uninstall keeps data by
default / --purge-data removes it / project plugins never touched.

Key findings (2×P1): manifest FILENAME (smith-plugin.lua) is never
stated in §9.2; git implementation boundary (gix vs shell-out) still
open — prototype shelled out to system git behind the boundary.
Plus P2/P3: --force semantics, duplicate definition, .git stripping,
data-dir lifecycle, exact restricted-env contents, staged validation
before copy.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* feat(prototypes): p03 subagent ecosystem simulation — PASS with findings

Proves SPEC §9.6: interface packages prevent ecosystem fragmentation
under realistic 5-plugin composition (interface pkg, conforming impl,
incompatible impl, pure-Lua adapter, consumer UI). Consumer targets only
the interface view; user config swaps alice <-> bob-adapted with zero
consumer changes; direct incompatible binding fails naming plugin,
interface+generation, exact missing functions, actual exports, and an
adapter hint.

Key findings (2×P1): §9.6 lacks adapter registration semantics (invented
`adapts` + make-factory convention); no user-override config syntax for
interface->implementation binding exists anywhere (invented
`interfaces = { ["community/subagent"] = "org/name" }`). Plus P2/P3:
manifest `interfaces`/`implements` field shapes undefined, conformance
check timing (load vs bind) unstated, singleton vs per-consumer instance
semantics open.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* feat(prototypes): p05 provider fetch normalize — PASS with disproof

Proves SPEC §7.3: pi.dev-primary field-level recursive merge with
catwalk gap-fill at field/model/provider granularity; providers.json
stays runtime authority (generate emits stdout suggestion + reviewable
patch, writes nothing); every change op carries path, old/new value,
and source attribution; two genuinely unresolvable conflict classes
(ambiguous-primary-source, type-mismatch-vs-curated-registry) are
detected, excluded, and reported explicitly.

DISPROOF: byte-for-byte unknown-field preservation is impossible with
default serde_json (keys re-sort alphabetically); preservation is
semantic (Value-equal) only. §7.3 must say which it means.

Key findings (2×P1): source-vs-curated-registry merge granularity
undefined (subtree merge would clobber curated cost objects); no
conflict taxonomy/policy exists at all. Plus P2: PR-agent exit-code
contract, replace_models carrier undefined, no canonical provider/
model schema.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* feat(prototypes): p08 tui testbackend — PASS with findings

Proves SPEC §8.8 + §17: ratatui TestBackend renders are deterministic
cell-by-cell (symbol + fg/bg/modifier), match a checked-in snapshot,
run fully headless (no crossterm dep, no TTY), and Lua theme tables
validated by a Rust schema drive widget styles; invalid themes are
rejected with exact path errors.

Key findings (2×P1): §8.8 has no theme schema at all (keys, nesting,
color format, missing-key policy all invented here); §17 snapshot
contract is undefined and text-only snapshots CANNOT catch theme
regressions — theme swap changed styles while text stayed byte-equal,
so theme snapshots require style-aware cell comparison. Plus P2:
invalid-user-theme runtime fallback policy unstated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* feat(prototypes): p09 memory arena allocation — PASS with disproof

25/25 checks against the SMITH-MEMORY-ALLOCATION-PROFILE workload bands
(release numbers, synthetic fixtures generated at runtime to PLAN shapes
within 2.5% — multi-MiB fixtures deliberately not committed):

- discovery is O(session count): 535 sessions from 54.8KiB of a
  41.64MiB corpus (0.13%), 4 allocs/session, 3.1ms,
- full load/replay stays inside research resident bands up to the
  29.78MiB pathological session (69ms, 4.6MiB message intact),
- virtual scroll is O(visible rows): 41 allocs/frame constant across a
  143x entry-count spread, giant message capped by lazy viewport wrap,
- request-build at ~250k tokens: transient peak 2.43MiB, zero live
  growth over 50 builds,
- bumpalo scratch: render-window -100% allocator calls, x0.19 elapsed
  (clear KEEP); request-build -99% calls but x1.00 elapsed and +22%
  peak (marginal).

DISPROOF: arenas are not a latency win for request-build — serde_json
serialization dominates; the win is allocator-call pressure only.

Findings: adopt scratch-only-bumpalo policy (never persisted data,
stable IDs + owned strings); SPEC must require lazy metadata-only
session discovery (P1) and viewport-capped row materialization.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* feat(prototypes): p10 lua plugin heap limit — PASS with disproofs

Core question answered: Lua::set_memory_limit() WORKS and enforces
under mlua 0.10.5 + vendored LuaJIT (GC64 accepts mlua's tracking
allocator) — PLAN's "may not work under LuaJIT" warning does not hold
for the locked feature set. oom-table rejected at exactly the 16 MiB
quota (overshoot 0 bytes) with recoverable mlua MemoryError; state
reusable after gc_collect; host survives; isolated plugin B unaffected
by A's OOM. Host-created Lua strings ARE charged to the quota.

DISPROOFS:
- shared-state per-plugin quotas impossible: only a whole-state limit
  exists; B got charged at A's retained 15.3MiB,
- Lua quota does NOT count host-side Rust allocations (8MiB userdata
  payload registered 632 bytes) — domain teardown must bound those,
- hook-based fallback never fires under active JIT (0 fires over 3e6
  iterations; interpreter-only, ~3.4x slowdown).

Findings: quota domain = one Lua state per plugin (aligns with §9.16
domains); scope quota wording to the Lua heap; CI-verify enforcement
per target (non-GC64 LuaJIT returns MemoryControlNotAvailable).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* feat(prototypes): p11 plugin memory domain reload — PASS, validates §9.16

The §9.16 full contract is implementable exactly as written: one
PluginDomain owns Lua state, descriptors, generation-keyed hook/tool
registries, bus subscription tokens, render cache, bump scratch, and a
cancellation token; reload = construct D' -> atomic swap -> drop D with
a single Drop impl and zero per-resource cleanup graph.

Evidence: 100 reload cycles plateau (growth <=77KB over 80 cycles,
tolerance 3MB; Lua used_memory constant; threads joined every drop);
reload latency avg 3.8-4.0ms incl. 450 registrations; rollback on
broken entry keeps old domain serving with partial D' registrations
discarded; 31MB Lua heap 100% reclaimed by domain drop; set_memory_limit
enforceable under vendored LuaJIT (corroborates p10); every escape path
(stale registry entry, leaked bus token, escaped thread) detected and
rejected via generation gating — 0 stale callbacks ran.

Finding (P2): a raw mlua::Function cloned out of the registry PANICS
("Lua instance is destroyed") after domain drop — abort-grade under the
no-panic invariant. §9.16 must mandate: callbacks reachable only through
the generation-keyed registry, every dispatch path generation-gates
before touching Lua. P3: memory plateau (not instantaneous RSS drop) is
the enforceable observable.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* docs: fold p02-p11 prototype evidence into SPEC

All ten prototypes ran to completion (result blocks in
prototypes/PLAN.md). Evidence-driven spec changes:

- §9.6 rewritten from prototype-gated stub to validated contract: plain
  Lua descriptors canonical (Teal/annotation candidates rejected),
  adapter convention (adapts + make factory), binding config syntax +
  precedence, bind-time conformance with required diagnostics,
  singleton-per-binding views (p02, p03).
- §9.2: manifest filename smith-plugin.lua canonical; empty restricted
  manifest env stated; interfaces/implements/heap_limit fields (p03, p04).
- §9.5: staged validation before copy, duplicate definition, --force =
  full replacement with data preserved, .git stripped; git boundary
  evidence recorded (p04).
- §9.14: plugin heap quota — per-plugin Lua state domain, Lua-heap scope,
  set_memory_limit enforcement (exact under vendored LuaJIT), loud
  failure where unavailable, OOM -> domain replacement (p10).
- §9.16: generation-keyed callback discipline (raw handle use-after-drop
  panics), audit-sweep escape detection, plateau as the enforceable
  memory observable (p11).
- §6.4: blocked-call event contract (p07).
- §6.6: recovery boundaries — body-corruption skippable, length-prefix
  corruption loses the tail, two-stage unknown-vs-corrupt decode (p06).
- §7.3: leaf-field merge granularity, conflict taxonomy + non-zero exit
  contract, semantic (not byte) unknown-field preservation,
  replace_models scoped to plugin overrides (p05).
- §8.8: theme schema contract (#rrggbb, path errors, fallback to
  built-in on invalid user theme); §17.7: style-aware snapshot contract
  (text-only cannot catch theme regressions) (p08).
- §13.1 Memory Policy: lazy metadata-only discovery, viewport-capped
  row materialization, scratch-only bumpalo with measured keep/drop
  gates, request-peak test gate (p09). bumpalo added to §2.3 deps.
- §18: campaign recorded.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* docs: pin provider schema and record Teal rejection (SPEC §7.3, §9.6)

Follow-ups from the p05/Teal discussion:

- §7.3: canonical provider/model JSON Schema at
  smith-ai/src/providers.schema.json, validated (jsonschema crate) at
  three boundaries: fetch-providers sources after normalization,
  checked-in providers.json in CI, and smith.provider.register tables
  at runtime. cost is always a per-token-price object, never a scalar —
  the shape ambiguity behind p05's type-mismatch conflict class becomes
  a source-boundary validation error. Unknown fields stay schema-legal
  to keep the preservation rule intact.

- §9.6: Teal rejection rationale recorded (compile-time guarantees
  evaporate at the runtime boundary; ecosystem bifurcation risk) and
  replaced by generated typing: interface descriptors mechanically emit
  LuaLS ---@class stubs via xtask doc-gen, so authors get editor-time
  checking against the same descriptor the runtime validates.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* docs: adopt models.dev as primary provider source, decouple from pi

SPEC §7.3 reworked per project direction: pi is a philosophical guide,
not a dependency — Smith has no data or format coupling to it.

- Source priority: models.dev api.json primary (open, community-
  maintained, CI-validated schema), catwalk fills gaps; pi.dev removed.
- Canonical schema: Smith does not invent one — it adopts the
  models.dev shape (cost per-million-token USD object with cache/
  reasoning/audio variants, limit {context,input,output}, modalities,
  capability flags) as a pinned local JSON Schema snapshot at a
  recorded upstream version, validated offline at the same three
  boundaries; upstream evolution reviewed like a dependency bump.
  Smith maps registry shapes into §5.7 ModelMetadata internally.
- Provider-data PR automation reworded agent-neutral.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* docs: fold design/plans/research normative content into SPEC, retire absorbed docs

Docs-tree audit (3 parallel reviews vs SPEC) found normative content
living outside the canonical spec. Folded:

From design docs (now deleted — fully absorbed):
- §9.8: canonical event catalog with per-event can-block matrix +
  Lua handler return-table contracts,
- §9.9: exact ctx object shape (ui/session/model/cwd/signal),
- §9.10: missing namespaces (shortcut, credentials, active_tools,
  send_message), tool/command/shortcut registration shapes, provider
  merge rules + unregister APIs,
- §9.13: smith.vcs.* function surface with return shapes,
- §7.4: auth.json layout, auth_types (api_key/oauth/organization),
  OAuth config/credential fields + callback-server login flow,
- §7.2: reasoning-in-content quirk; non-SSE JSON error with HTTP 200
  must become ProviderEvent::Error (P12-proven),
- §8.3: probe contract (once/session, 100ms fail-conservative,
  ImageProtocol=Kitty|Sixel, kitty-keyboard push/pop, CSI ?2026),
- §8.6: runtime-c2rust, side-by-side diffs, overlay anchor/size model,
- §8.7: layout primitive shapes (Size, BorderStyle, split_ratio, Panel),
- §8.11 (new): deferred v1 TUI scope.

From plans (PROTOTYPE-REPORT deleted after absorbing its two open
findings):
- §6.11: zstd per-entry inflation for small traces -> block-level or
  min-size threshold,
- §16: doc resolution order (embedded -> share/smith/docs ->
  SMITH_DOCS_PATH); §10.2: dotted help addressing; §6.8: system-prompt
  SDK self-learn bootstrap.

From research (files kept, leakage folded or relabeled):
- §17.10 (new): CI — hermeticity rules, gate tiers, agent CI-safety
  rules, Android/Termux lane posture,
- §17.4: overall 85% coverage, merge-block <80%; §17.5: ci profile;
  §17.9: ±5% warn / ±10% fail bench thresholds,
- §2.3: anyhow/toml/regex/tokio-stream (decided in research, absent),
- research fixes: license + similar version + jsonschema status
  reconciled to SPEC; clippy extended lints marked candidates;
  RESEARCH-NOTES Rust-trait/WASM design marked rejected alternative;
  stale "hooks smith lacks" note corrected (§6.4 has them).

AGENTS.md navigation updated. Lint set ruling: §3.2 stays canonical
as-is; research list is candidates only.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

* docs: update PROJECT-INVARIANTS §2 tree after design-doc absorption

User-approved edit to the protected file: remove the deleted docs/design/
entries, note SPEC.md is self-contained, mark research/ as non-normative
evidence, add the prototypes/ tree, and record the change in the log.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LABEHeVpg74oyZNtWLUWpB

---------

Co-authored-by: Claude <noreply@anthropic.com>

Changed files (75)

+10439 / −1933 text lines · all files grouped into 32 bars

Diff layout

AGENTS.md

Modified

+3 / −1 text lines

3434- Spec: `docs/SPEC.md` — canonical project specification.
3535- Research: `docs/research/` — ecosystem research and tool analysis.
36- Design: `docs/design/` — subsystem design documents.
3736- Plans: `docs/plans/` — task breakdowns and documentation plans.
38Former `docs/design/` subsystem docs and the P1–P20 prototype report are fully
39absorbed into `docs/SPEC.md` and deleted (see git history).
3840- Docs tree and invariants: `docs/PROJECT-INVARIANTS.md` — build system,
3941 directory structure, coding standards, and canonical docs inventory.

docs/PROJECT-INVARIANTS.md

Modified

+12 / −6 text lines

3737└── ...
3939docs/ # ← project management (spec, research)
40├── SPEC.md # canonical project specification
41├── research/ # ecosystem research, tool analysis
40├── SPEC.md # canonical project specification (self-contained;
41│ # subsystem design content lives here)
42├── research/ # ecosystem research, tool analysis (evidence,
43│ │ # non-normative)
4244│ ├── RESEARCH-NOTES.md
4345│ ├── TERMINAL-CAPABILITIES-RESEARCH.md
4446│ ├── TESTING-STRATEGY-RESEARCH.md
4547│ ├── CI-PATTERNS-RESEARCH.md
4648│ └── CRATE-ECOSYSTEM-RESEARCH.md
47├── design/ # subsystem design documents
48│ ├── TUI-CRATE-DESIGN.md
49│ ├── PLUGIN-SDK-DESIGN.md
50│ └── AI-CRATE-DESIGN.md
5149├── plans/ # task breakdowns, documentation plans
5250│ ├── TASK-BREAKDOWN.md
5351│ └── PLUGIN-DOC-PLAN.md
5452└── PROJECT-INVARIANTS.md # this file
54prototypes/ # ← disposable spec-validation prototypes
55├── AGENTS.md # prototype rules
56└── PLAN.md # prototype plan + result blocks
5557```
59Former `docs/design/` subsystem docs were fully absorbed into `docs/SPEC.md`
60and deleted (2026-07-15; see git history).
5762**Rule:** Code review gates on `src/`, `Cargo.toml`, `tests/`. Project management review gates on `docs/`. No code in `docs/`, no specs in `src/`.
5964## 3. Build Invariants
423428| Date | Change | Author |
424429|------|--------|--------|
430| 2026-07-15 | §2 tree: design/ absorbed into SPEC.md and deleted; prototypes/ added (user-approved) | smith-spec |
425431| 2026-05-23 | Add architecture gates and pinned-nightly pup exception | smith-spec |
426432| 2026-05-22 | Initial invariants | smith-spec |

docs/SPEC.md

Modified

+751 / −88 text lines

110110crossterm = "0.28"
111111ratatui = "0.29"
112112ciborium = "0.2"
113bumpalo = "3"
113114thiserror = "2"
115anyhow = "1"
116toml = "0.8"
117regex = "1"
118tokio-stream = "0.1"
114119tracing = "0.1"
115120tracing-subscriber = { version = "0.3", features = ["env-filter"] }
116121reqwest = { version = "0.12", features = ["json", "stream"] }
448453Invalid values are rejected with clear errors. Unknown keys warn or fail
449454according to the schema context.
456The cascade is re-evaluated at runtime by host configuration reload (§9.19);
457CLI flags stay fixed for the process lifetime.
451459Example:
453461```lua
589597- `PrepareNextTurn`: mutate queued prompts/messages.
590598- `TransformContext`: mutate LLM context before provider request.
600Blocked-call contract (prototype-proven, p07): a blocked tool call never
601executes the tool, still emits `ToolExecutionStart` and `ToolExecutionEnd`
602(with error flag and the block reason) so the UI can show it, and feeds the
603block reason to the provider as an error tool result so the model can react.
592605`smith-harness` translates Lua plugin event returns into these core hook results.
594607### 6.5 Session Model
636649- `smith session dump` outputs JSONL,
637650- session discovery is keyed by canonical `{session-id}.session` filenames.
652Recovery boundaries (prototype-proven, p06):
654- A corrupt entry BODY is precisely skippable — the intact length prefix
655 bounds the damage; prior and subsequent entries survive.
656- A corrupt LENGTH PREFIX desynchronizes framing: entries before it survive,
657 everything after is unrecoverable and indistinguishable from truncation.
658 "Skip + warn if possible" promises no more than this.
659- Unknown-vs-corrupt is decided by two-stage decode: first as raw CBOR, then
660 as a typed entry. Well-formed CBOR with an unknown variant tag is preserved
661 raw and survives rewrite roundtrips; invalid CBOR is corrupt and skipped.
639663### 6.7 Secret Proxy
641665The secret proxy prevents LLM exposure of secrets:
662686Plugins may transform prompts through typed hooks. No hidden global prompt mutation.
688The system prompt bootstraps SDK self-learning: it teaches the agent to
689discover plugin/SDK capabilities through `smith help --search`, `--guide`, and
690`--example` (§10.2) instead of embedding the full SDK reference inline.
664692### 6.9 Compaction and Cost
666694Compaction:
698726Trace files capture deterministic replay data:
700728- file header with magic/version/session ID,
701- compressed entries via zstd,
729- compressed entries via zstd — per-entry compression inflates small traces
730 (measured ~115% of raw CBOR under ~50 entries from per-entry header
731 overhead); the codec uses block-level compression or a minimum entry-size
732 threshold so small traces never exceed their uncompressed size,
702733- provider requests/events,
703734- tool calls/results,
704735- TUI events as opaque JSON,
754785- streaming vs non-streaming APIs,
755786- partial tool-call argument chunks,
756- thinking/reasoning fields,
787- thinking/reasoning fields (reasoning text may arrive inside `content` before
788 the final answer on some OpenAI-compatible endpoints),
757789- provider-specific stop reasons,
758790- cache usage fields,
759791- model capability flags.
793Error detection: some providers return errors as plain JSON bodies with
794HTTP 200 instead of SSE (prototype-proven against a live OpenAI-compatible
795endpoint). A provider implementation must detect a non-streaming JSON error
796body on a streaming request and convert it to `ProviderEvent::Error` — never
797hang waiting for SSE frames that will not come.
761799### 7.3 Model Registry
763801`providers.json` is bundled in `smith-ai/src/providers.json`. That checked-in
773811Data source priority for generated suggestions:
7751. pi.dev model data,
8131. models.dev (`https://models.dev/api.json` — the open, community-maintained
814 model database with a CI-validated schema),
7768152. catwalk provider configs,
7778163. later shared provider repositories after review.
779Merge rule:
818Pi served as inspiration for Smith and continues to evolve independently; it is
819a philosophical guide, not a dependency. Smith has no data or format coupling
820to pi.
781- merge by provider/model ID,
782- pi.dev primary,
783- catwalk fills gaps,
784- `replace_models` permits full provider override,
785- unknown provider fields are preserved for forward compatibility but ignored by v1.
822Merge rule (prototype-proven, p05):
824- merge by provider/model ID at LEAF-FIELD granularity — a recursive
825 field-level merge; subtree or whole-model replacement would clobber curated
826 registry values (e.g. structured cost objects),
827- models.dev primary,
828- catwalk fills gaps (missing field, missing model, missing provider),
829- unknown provider fields are preserved for forward compatibility but ignored
830 by v1. Preservation is semantic (value-equal), not byte-for-byte — default
831 JSON tooling reorders keys. Unknown fields must never appear in generated
832 diffs.
834Conflict policy: some conflicts cannot be auto-merged and are excluded from the
835suggestion and reported explicitly, at minimum:
837- ambiguous-primary-source: the primary source lists the same model ID twice
838 with differing metadata,
839- type-mismatch-vs-curated: a source proposes a value whose structure differs
840 from the hand-curated registry value (curated value kept).
842`fetch-providers` exits non-zero while unresolved conflicts remain, so PR
843automation can never auto-merge a corrupting suggestion. Its outputs are the
844suggested file, a reviewable source-attributed patch, and a machine-readable
845conflict report.
847`replace_models` is a plugin provider-override flag (`smith.provider.*`,
848§9.10), not a `fetch-providers` merge input.
850**Canonical schema.** Smith does not invent a provider/model schema — the shape
851is already pinned upstream by models.dev (TOML sources CI-validated against its
852published schema). Smith adopts that shape and keeps a pinned local snapshot:
853a JSON Schema at `smith-ai/src/providers.schema.json`, translated from the
854models.dev schema at a recorded upstream version. Local pinning keeps
855validation deterministic and offline; upstream schema evolution is reviewed and
856adopted like any dependency bump.
858The snapshot is validated with the `jsonschema` workspace crate at three
859boundaries:
8611. `fetch-providers` source data after normalization — a source value that
862 fails the schema is a validation error at the source boundary, not a merge
863 conflict,
8642. the checked-in `providers.json` (CI gate),
8653. provider tables passed to `smith.provider.register` at runtime (§9.10).
867Schema rules:
869- Registry shapes follow models.dev naming: `cost` (USD per million tokens:
870 `input`, `output`, `cache_read`, `cache_write`, optionally `reasoning` and
871 audio variants), `limit` (`context`, `input`, `output`), modalities
872 (`input`/`output` type lists), and capability flags (`attachment`,
873 `reasoning`, `tool_call`, `structured_output`, `temperature`). Smith maps
874 these into the §5.7 `ModelMetadata` type internally.
875- `cost` is always an object — never a scalar. This resolves the
876 scalar-vs-object ambiguity that produced p05's type-mismatch conflict class.
877- Unknown fields are permitted everywhere (`additionalProperties` allowed) so
878 the preservation rule above stays schema-legal; the snapshot constrains known
879 fields only.
787881Provider config correctness cannot be fully automated because Smith does not have
788882all provider accounts, subscriptions, API keys, or regional access. Generated
789883changes require review before commit. After the provider format stabilizes,
790Smith may use a Pi agent to open provider-data PRs from `fetch-providers` diffs.
884Smith may use a coding agent to open provider-data PRs from `fetch-providers`
885diffs.
792887### 7.4 Auth
802897Auth errors fail fast before first provider stream.
804OAuth module supports mocked OAuth flow in tests and provider-specific OAuth where
805configured.
899Auth methods per provider are declared in the registry's `auth_types` map:
900`api_key` (with its `env_var` name), `oauth`, and `organization` (org-scoped
901key, e.g. OpenAI: api key + org ID). `AuthMethod` mirrors these three.
903`~/.smith/auth.json` is a per-provider object map:
905```json
906{
907 "anthropic": {
908 "access_token": "...",
909 "refresh_token": "...",
910 "expires_at": 1234567890
911 }
912}
913```
915OAuth module supports mocked OAuth flow in tests and provider-specific OAuth
916where configured. OAuth per provider is configured with `id`, `name`,
917`auth_url`, `token_url`, `scope`, and `client_id`; credentials are
918`access_token`, `refresh_token`, `expires_at` (Unix seconds), auto-refreshed on
919expiry. The login flow surfaces the auth URL to the user, receives the code via
920a local callback HTTP server on a random port (or manual paste), exchanges it
921for credentials, and persists them to `auth.json`.
807923### 7.5 MuxProvider
857973No terminfo database. Probe directly. Unsupported optional features degrade to
858974plain text without user-facing error.
976Probe contract:
978- capabilities are probed once per session at startup, with a 100ms timeout
979 per probe; on timeout the capability is treated as absent (fail
980 conservative),
981- image protocol is `ImageProtocol::{Kitty, Sixel}` — no other variants in v1,
982- Kitty keyboard protocol flags are pushed on TUI startup and popped on
983 shutdown (including error/signal paths, §10),
984- synchronized output (`CSI ?2026 h/l`) wraps render passes when the terminal
985 supports it.
860987### 8.4 Component Trait
862989Components render into ratatui buffers and handle normalized `TuiEvent`.
9131040- overlay,
9141041- border layout panels.
916Syntax highlighting uses `syntastica`. Diffs use `similar`. Fuzzy matching uses
917`fuzzy-matcher`.
1043Syntax highlighting uses `syntastica` with the `runtime-c2rust` runtime (no C
1044runtime dependencies; prototype-proven). Diffs use `similar` and support
1045unified and side-by-side modes. Fuzzy matching uses `fuzzy-matcher`.
1047Overlays (modals, fuzzy search, autocomplete) are positioned by an anchor
1048model: nine anchors (`Center`, four corners, four edge-centers) plus
1049`offset_x`/`offset_y` and optional margin; overlay `width`/`max_height` are
1050`Size::Absolute(cells)` or `Size::Percent`.
9191052### 8.7 Layout
9211054Rust provides primitives; Lua defines layout.
923Primitives:
1056Primitives and their shapes:
925- column,
926- row,
927- box,
928- expanded,
929- scrollable,
930- overlay,
931- spacer,
932- tabs,
933- split.
1058- `column` / `row`: child list, stacked vertically/horizontally,
1059- `box`: single child, optional `width`/`height` (`Size`), optional border
1060 (`BorderStyle::{Single, Double, Rounded, Thick, None}` + optional title),
1061- `expanded`: single child, takes remaining space after fixed siblings,
1062- `scrollable`: single child, direction vertical/horizontal/both,
1063- `overlay`: single child + overlay options (§8.6 anchor model),
1064- `spacer`: optional fixed `Size`,
1065- `tabs`: labeled child list + active index,
1066- `split`: two children, horizontal/vertical, `split_ratio: f32`.
935One predefined border layout exists: center + north/east/south/west panels.
936Panels are invisible when empty. Default layout is a Lua plugin.
1068One predefined border layout exists: center + north/east/south/west panels,
1069each panel carrying `visible`, `size`, and its own layout. Panels are invisible
1070when empty. Default layout is a Lua plugin.
9381072### 8.8 Theme
940Themes are Lua tables validated by Rust schemas.
1074Themes are Lua tables validated by Rust schemas (prototype-proven, p08).
9421076Theme values cover status bar, messages, assistant content, tool call/result,
9431077errors, input, borders, selections, diffs, syntax groups, and accents.
1079Schema contract:
1081- The Rust schema defines the required key set and nesting; every section above
1082 is a named table of color/style values.
1083- Colors are `#rrggbb` strings. Named/ANSI-indexed colors are not part of the
1084 v1 schema.
1085- A missing required key or malformed value is a validation error carrying the
1086 exact key path (e.g. `theme.status_bar.fg: expected "#rrggbb"`). Unknown keys
1087 warn.
1088- A user theme that fails validation at runtime does not abort Smith: it falls
1089 back to the built-in default theme with a visible warning naming the path
1090 error.
9451092### 8.9 Virtual Scroll
9471094Message history uses virtual scrolling. `sticky_bottom` defaults true and turns
9531100Tools may register `renderCall` and `renderResult` Lua renderers. TUI receives
9541101structured render instructions from harness, not arbitrary terminal writes.
1103### 8.11 Deferred Scope (v1)
1105Explicitly out of v1 TUI scope:
1107- vim-style normal-mode editing,
1108- inline image rendering (Kitty graphics protocol),
1109- split-pane resizing (the `split` primitive exists; interactive resize does
1110 not),
1111- multiple simultaneous sessions.
9561113## 9. Harness Crate: `smith-harness`
9581115`smith-harness` wires all subsystems and owns plugin management.
9991156- Installed global plugins live under `data_dir/smith/plugins/<org>/<name>/`.
10001157- Project plugins live under `.smith/plugins/<org>/<name>/`.
1002Every plugin has a mandatory Lua manifest file. Plugin authors create it.
1003Manifest loading uses a restricted manifest environment with no Smith SDK and no
1004host I/O. The manifest returns a data table only.
1159Every plugin has a mandatory Lua manifest file named `smith-plugin.lua` in the
1160plugin root. Plugin authors create it. Manifest loading uses a restricted
1161manifest environment — an empty Lua environment with no globals, no Smith SDK,
1162and no host I/O — so the chunk can only build and return a pure data table.
1163A manifest that reaches for `os`/`require`/any global, or that contains
1164function values, is rejected (prototype-proven, p04).
10061166Required manifest fields:
10221182- repository,
10231183- dependencies,
10241184- declared secrets,
1025- exported interfaces,
1026- implemented interfaces.
1185- `heap_limit` (bytes, §9.14),
1186- `interfaces` — list of interface names this package exports descriptors for
1187 (§9.6),
1188- `implements` — list of interface names this package implements (§9.6).
10281190If `smith_api` is absent, Smith treats it as `1`.
10711233`smith install <path-or-git-url>`:
1073- resolves the source,
1074- reads and validates the manifest,
1075- validates namespace and API compatibility,
1076- copies or clones into `data_dir/smith/plugins/<org>/<name>/`,
1235- resolves the source into a temporary staging area,
1236- reads and validates the manifest, namespace, and API compatibility in
1237 staging — a rejected plugin never touches the plugins root,
1238- copies into `data_dir/smith/plugins/<org>/<name>/` only after validation,
10771239- refuses duplicates unless `--force`,
1078- does not run plugin entry code during install.
1240- does not run plugin entry code during install (prototype-proven, p04).
1242Install semantics:
1244- A duplicate is defined as: the destination directory
1245 `data_dir/smith/plugins/<org>/<name>/` already exists, regardless of version.
1246- `--force` is full replacement: remove the old plugin directory, then place the
1247 new one. Plugin data under `data_dir/smith/data/<org>/<name>/` survives a
1248 forced reinstall.
1249- Git installs strip the `.git` directory: an installed plugin is a pure file
1250 snapshot, not a working clone. Updates go through reinstall.
10801252Git URL installs use Smith's internal git implementation boundary. The preferred
10811253implementation is `gix` if its required clone/fetch feature set stays bounded;
1082otherwise the behavior remains the same behind the install boundary.
1254otherwise the behavior remains the same behind the install boundary. Prototype
1255evidence (p04): shell-out to a system git binary satisfies the boundary with
1256zero added crates but adds a runtime dependency on git being installed — the
1257boundary hides whichever choice release engineering makes.
10841259`smith uninstall <org>/<name>`:
10911266### 9.6 Plugin Interface Modules
1093Plugin shape is mandatory. The exact interface/implementation module design is a
1094prototype target before production implementation.
1268Interfaces are plain Lua descriptor tables validated at runtime. This design is
1269prototype-proven (p02, p03); the typed-Lua (Teal) and annotation-schema
1270candidates are rejected.
1096Desired ecosystem capability:
1272**Why Teal is rejected.** Teal's compile-time guarantees evaporate at the
1273runtime boundary: Smith embeds LuaJIT, so Teal ships as compiled Lua and the
1274host must re-validate conformance regardless — Teal would be additive toolchain
1275cost, not a replacement for runtime descriptors. Making official interfaces
1276Teal-authored would also split the ecosystem into typed and plain-Lua authors,
1277the exact fragmentation §9.6 exists to prevent. The authoring-time typing Teal
1278would provide is delivered instead by LuaLS annotations (below and §9.10)
1279without a compile step.
1098- interface-only plugin packages,
1099- implementation-only plugin packages,
1100- implementations referencing external interfaces,
1101- packages containing both interface and implementation.
1281**Generated typing.** Interface descriptors mechanically generate LuaLS stub
1282files (`---@class`/`---@field`/`---@param` annotations derived from the
1283descriptor's `functions` table) as part of `cargo run -p xtask -- doc-gen`.
1284Plugin authors targeting an interface get editor-time type checking against
1285the same descriptor the runtime validates — one source of truth, two
1286enforcement points.
1103Smith must avoid a fractured plugin ecosystem. The candidate designs are:
1288**Descriptor.** An interface package exports a descriptor: a pure data table
1289with `name` (`<org>/<name>`), `generation` (integer), `functions` (map of
1290function name → `{ params, returns }` with typed, optionally-optional named
1291parameters), and `events` (list of bus topics, §9.18).
11051. declarative Lua interface tables validated at load time,
11062. a typed Lua superset such as Teal compiled to Lua,
11073. generated LuaLS/EmmyLua annotations plus runtime schemas.
1293**Ecosystem shapes.** Interface-only packages, implementation-only packages,
1294implementations referencing external interfaces, and combined packages are all
1295supported through two manifest fields (§9.2): `interfaces` (list of interface
1296names this package exports descriptors for) and `implements` (list of interface
1297names this package implements).
1109A prototype must prove the chosen design before this section becomes an
1110implementation contract.
1299**Adapters.** An adapter is an implementation package whose entry exports
1300`adapts = "<org>/<name>"` (the wrapped plugin) plus a `make(wrapped)` factory
1301returning a conforming implementation. The plugin manager injects the wrapped
1302plugin's exports into `make`.
1304**Binding.** User config selects the implementation backing an interface:
1306```lua
1307interfaces = { ["community/subagent"] = "org/name" }
1308```
1310Binding precedence: explicit config binding, else the last-loaded plugin
1311declaring `implements` for that interface (§9.7 order). Conformance is checked
1312at bind time. A conformance failure names the plugin, interface and generation,
1313every missing/mis-shaped export with its exact path, the exports the plugin
1314actually provides, and any installed adapter for it.
1316**Views.** Consumers receive an interface view: only declared functions are
1317visible (implementation-private fields are hidden), and arguments are validated
1318against the descriptor at call time with errors naming function and parameter.
1319A resolved binding is a singleton: all consumers of an interface share the one
1320bound implementation instance.
11121322### 9.7 Plugin Precedence
11241334### 9.8 Event Bridge
1126`PluginEvent` variants cover:
1336Lua receives event tables with a `type` field. The canonical event catalog and
1337per-event blocking capability:
1128- agent lifecycle,
1129- turns,
1130- message deltas/end,
1131- tool call/result,
1132- session lifecycle,
1133- model changes,
1134- context/compaction,
1135- TUI/input events,
1136- commands,
1137- provider/auth events,
1138- VCS events,
1139- errors and shutdown.
1339| Event | Can block | Notes |
1340|-------|-----------|-------|
1341| `resources_discover` | No | contribute skill/prompt/theme paths |
1342| `session_start`, `session_shutdown` | No | started/loaded/reloaded; shutting down |
1343| `session_before_switch` | **Yes** | before switching sessions |
1344| `session_before_fork` | **Yes** | before forking/cloning |
1345| `session_before_compact` | **Yes** | can customize compaction |
1346| `session_compact`, `session_tree` | No | completed notifications |
1347| `before_agent_start` | No | may inject messages, modify system prompt |
1348| `agent_start`, `agent_end`, `turn_start`, `turn_end` | No | lifecycle |
1349| `model_select` | No | model changed |
1350| `message_start`, `message_update`, `message_end` | No | streaming lifecycle |
1351| `thinking_delta`, `text_delta` | No | token deltas |
1352| `tool_execution_start` | No | execution began |
1353| `tool_call` | **Yes** | before tool executes (§6.4 blocked-call contract) |
1354| `tool_execution_update`, `tool_result`, `tool_execution_end` | No | `tool_result` may modify the result |
1355| `input` | No | may intercept/transform/mark handled |
1356| `user_bash` | No | user `!`/`!!` commands |
1357| `context` | No | may modify messages before LLM call |
1358| `before_provider_request`, `after_provider_response` | No | inspect/replace payload; response received |
1359| `config_changed` | No | §9.19, carries changed key paths |
1360| `plugin_loaded`, `plugin_unloaded` | No | plugin lifecycle |
1361| `panel_toggle`, `resize` | No | TUI |
1362| `provider_registered` | No | after provider add/override |
1363| VCS events | No | §9.13 operations |
1364| errors, shutdown | No | §9.17 |
1141Lua receives event tables with a `type` field.
1366Handler return-table contracts (Lua-facing):
1143Plugin event results can:
1368- `tool_call` → `{ block = true, reason = "..." }` or
1369 `{ args = <replacement> }` or nil/`{}` (allow),
1370- `tool_result` → `{ content = <replacement> }` or nil (keep),
1371- `input` → `{ action = "handled" | "continue", text = <transformed>? }`,
1372- `context` → `{ messages = <modified> }` or nil,
1373- `session_before_*` → `{ block = true, reason = "..." }` or nil,
1374- all other events: return value ignored.
1145- block tool call,
1146- transform tool args,
1147- replace tool result,
1148- retry/cancel,
1149- transform input,
1150- override system prompt/context,
1151- request continue/stop,
1152- emit UI actions.
1154The bridge maps these into `AgentLoopConfig` hooks.
1376The bridge maps these into `AgentLoopConfig` hooks (§6.4): block/transform
1377tool calls, replace results, retry/cancel, transform input, override system
1378prompt/context, request continue/stop, emit UI actions.
11561380### 9.9 Extension Contexts
11611385- `ExtensionCommandContext`: slash command args, selection, output, session.
11621386- `ExtensionUIContext`: selection, confirm, prompt, status, layout, widget APIs.
1388The `ctx` table passed to event handlers, tool `execute`, and command handlers
1389has this shape:
1391```lua
1392ctx = {
1393 ui = {
1394 notify = function(message, level) end, -- "info"|"success"|"error"|"warning"
1395 confirm = function(title, message) end, -- -> bool
1396 select = function(title, items) end, -- -> chosen item
1397 input = function(title, placeholder) end, -- -> string
1398 set_status = function(key, text) end,
1399 set_widget = function(key, lines) end,
1400 },
1401 session = { -- read-only
1402 id = "...", name = "...",
1403 entries = function() end, -- -> table
1404 entry_count = function() end, -- -> number
1405 branch = function() end, -- -> table
1406 },
1407 model = { id = "...", provider = "..." },
1408 cwd = "/path/to/project",
1409 signal = AbortSignal,
1410 shutdown = function() end,
1412```
11641414### 9.10 Lua SDK
11661416SDK namespaces include:
11781428- `smith.bucket.*`,
11791429- `smith.tui.*`,
11801430- `smith.vcs.*`,
1431- `smith.bus.*`,
1432- `smith.config.*` (read access; `smith.config.reload()` triggers §9.19),
1433- `smith.shortcut.*` (keyboard shortcut registration),
1434- `smith.credentials.*` (`get(provider)`/`set(provider, value)` over the §7.4
1435 auth store),
1436- `smith.active_tools.*` (`get()`/`all()`/`set(names)`),
1437- `smith.send_message(text, { deliver_as = "steer" | "followUp" })` and
1438 `smith.send_user_message(text)`,
11811439- `smith.abort()`,
11821440- `smith.shutdown()`,
11831441- `smith.getContextUsage()`.
1185All public Lua SDK functions have `---@` annotations and `@usage` blocks. Docs
1186are generated from SDK annotations.
1443Core registration shapes:
1445```lua
1446smith.tool.register({
1447 name = "my_tool",
1448 description = "shown to the LLM",
1449 parameters = { --[[ JSON-schema table, validated per §5.3 ]] },
1450 execute = function(input, ctx)
1451 return { content = { { type = "text", text = "..." } } }
1452 end,
1453})
1455smith.command.register("name", {
1456 description = "...",
1457 autocomplete = function(prefix) end, -- optional -> { {value, label}, ... }
1458 handler = function(args, ctx) end,
1459})
1461smith.shortcut.register("ctrl+shift+p", {
1462 description = "...",
1463 handler = function(ctx) end,
1464})
1465```
1467`smith.provider.register(name, table)` merges into an existing provider or adds
1468a new one. Merge rules: `base_url`/`api_key`/`api` override; `headers` merge
1469per-key; `oauth` replaces whole; `models` merge by ID field-by-field (same
1470rules recursively); omitted fields keep existing values; `replace_models =
1471true` drops all existing models first. `smith.provider.unregister(name)` and
1472`smith.provider.unregister_model(provider, model_id)` remove entries. All
1473tables are validated against the §7.3 schema.
1475All public Lua SDK functions carry LuaLS/EmmyLua `---@` annotations. LuaLS is the
1476canonical annotation dialect; no other dialect is supported. Every public binding
1477declares, at minimum:
1479- `---@param` for each argument (name, type, description),
1480- `---@return` for each result (type, description),
1481- a `---@usage` block with a runnable example.
1483Runtime argument schemas (used for validation) and generated docs both derive
1484from these annotations, so annotations and runtime behavior stay in sync. The
1485`xtask verify-docs` gate fails if any public binding lacks required annotations.
11881487### 9.11 Built-in Plugins
11901489Built-ins are Lua plugins, not Rust special cases:
11921491- tools: `read`, `write`, `edit`, `bash`, `find`, `grep`, `ls`,
1193- slash commands: `/undo`, `/redo`, `/history`, `/tree`, replay/time-travel,
1492- slash commands: `/undo`, `/redo`, `/history`, `/tree`, `/reload-config`,
1493 replay/time-travel,
11941494- VCS tools,
11951495- default layout,
11961496- default keybindings,
12981598`smith.vcs.*` exposes:
1300- init/status/snapshot,
1301- op ID capture,
1302- diff queries,
1303- undo/redo/time-travel primitives,
1304- structured file statuses and hunks.
1600Read-only queries:
1602```lua
1603smith.vcs.status() -- { modified={}, added={}, deleted={}, renamed={} }
1604smith.vcs.diff(opts) -- { hunks={}, text="..." }
1605smith.vcs.diff_revs(a, b) -- diff between revisions/operations
1606smith.vcs.op_log({ limit = n }) -- { { id, description, time, op_type } }
1607smith.vcs.op_show(op_id) -- { id, description, diff, files }
1608smith.vcs.annotate(path, opts) -- line attribution data
1609smith.vcs.interdiff(a, b) -- patch-vs-patch comparison
1610smith.vcs.evolog(rev) -- logical change evolution
1611```
1613Mutations (explicit, validated inputs):
1615```lua
1616smith.vcs.commit(message)
1617smith.vcs.undo()
1618smith.vcs.redo()
1619smith.vcs.op_restore(op_id)
1620smith.vcs.restore_paths(paths, rev)
1621smith.vcs.split(opts)
1622smith.vcs.squash(source, dest)
1623smith.vcs.parallelize(revs)
1624smith.vcs.sparse(paths)
1625smith.vcs.workspace_add(name, opts)
1626```
1628Lua receives stable smith-shaped tables; jj/gix implementation details never
1629leak through this surface.
13061631`gix` is used only for targeted structured queries behind `smith.vcs.*`.
13141639- no path capability system in v1,
13151640- built-in and user plugins use same API.
1642**Heap quota.** A plugin may be given a Lua heap limit via the optional
1643`heap_limit` manifest field (§9.2) or config override. Prototype-proven (p10,
1644p11) semantics:
1646- The quota domain is the plugin's own Lua state — one `mlua::Lua` per plugin
1647 (matching the §9.16 domain model). Per-plugin quotas in a shared Lua state are
1648 not attributable and are not offered.
1649- Enforcement is `Lua::set_memory_limit()`; under the locked vendored-LuaJIT
1650 feature set this enforces exactly, and breach surfaces as a recoverable
1651 memory error handled by the §9.17 error model. Targets where mlua reports
1652 memory control as unavailable must fail plugin-quota configuration loudly,
1653 never enforce silently at zero; per-target enforcement is CI-verified.
1654- The quota covers the plugin's Lua heap only, including host-created Lua
1655 values. Host-side Rust allocations held for a plugin are invisible to the
1656 quota and are bounded by domain teardown (§9.16) instead.
1657- After a plugin OOM, the preferred recovery is whole-domain replacement
1658 (§9.16) rather than in-place retry.
1660### 9.15 Dependency Resolution
1662Plugins may declare dependencies on other plugins in their manifest
1663(`dependencies`, §9.2). v1 resolves dependencies from already-available plugins
1664only; there is no central registry and no network resolution.
1666Each dependency entry names a plugin and a minimum API generation:
1668```lua
1669dependencies = {
1670 { name = "acme/logger", smith_api = 1 },
1672```
1674Resolution runs once per plugin set (built-in, global, project) after manifests
1675load and before entry code runs:
16771. Build the dependency graph from validated manifests.
16782. Fail loading a plugin whose declared dependency is absent from the resolved
1679 set. The plugin is disabled with a diagnostic naming the missing dependency.
16803. Fail loading a plugin whose dependency is present but supports a lower API
1681 generation than requested.
16824. Detect cycles. A dependency cycle disables every plugin in the cycle with a
1683 diagnostic listing the cycle path. Smith never partially loads a cycle.
16845. Load plugins in topological order so a dependency's registrations exist before
1685 its dependents run.
1687v1 does not solve version ranges. `dependencies` express presence and API
1688generation only. Semver range solving is deferred until a registry exists.
1689Precedence (§9.7) still applies: a later plugin may override an earlier
1690registration even across a dependency edge.
1692### 9.16 Plugin Hot-Reload
1694Smith reloads a single plugin without restarting the process or losing the active
1695session. Reload is whole-domain replacement, not in-place mutation.
1697**Plugin domain.** Each loaded plugin instance owns one reload domain. The domain
1698owns all reloadable plugin state:
1700- the plugin's `mlua` runtime state and registry handles,
1701- registered tool/command/provider/shortcut/interface descriptors,
1702- event subscriptions, including `smith.bus` subscriptions (§9.18),
1703- TUI layout/widget registrations and render caches,
1704- host-side scratch allocations and any cancellation token for plugin tasks.
1706Nothing plugin-owned may outlive its domain. Registrations are keyed by domain
1707generation so teardown removes them deterministically. A callback, task, or
1708subscription that escapes its domain is a reload defect; the loader rejects
1709registrations that cannot be tied to the domain.
1711**Callback discipline** (prototype-proven, p11): plugin callbacks are reachable
1712exclusively through the generation-keyed registry. The host never clones or
1713stashes a raw callback handle outside it — invoking a raw `mlua` function after
1714its domain dropped is an unrecoverable panic, not a catchable error. Every
1715dispatch path (hook, tool, command, bus) checks the callback's domain generation
1716against the active set before touching any Lua value; stale generations are
1717rejected with a diagnostic and the callback does not run. An audit sweep over
1718the registries (anything registered under a non-active generation) is the
1719loader's escape-detection mechanism.
1721**Triggers.** Reload is requested by:
1723- the `smith plugins reload <org>/<name>` CLI/command path,
1724- a project plugin file change when watch-reload is enabled in config,
1725- reinstall of an already-loaded plugin.
1727Built-in `smith/*` plugins reload by the same mechanism.
1729**Sequence.** For a reload of plugin `P`:
17311. Construct a new domain `D'` and load `P`'s manifest and entry code into it.
17322. If load or registration fails, drop `D'` and keep the old domain `D` active.
1733 The old plugin keeps running. Reload reports failure with the load error.
17343. On success, atomically swap `D'` in for `D`: new registrations replace old,
1735 subscriptions transfer to `D'`, then drop `D`.
17364. Dropping `D` tears down its Lua state, registrations, subscriptions, caches,
1737 and scratch memory. Repeated reloads must plateau in live memory after
1738 warmup; no stale callback from `D` may run after the swap. The plateau is
1739 the enforceable observable — an instantaneous RSS decrease per teardown is
1740 not required, since small freed heaps are legitimately retained by the
1741 allocator for reuse (p11: ≤77KB growth over 80 cycles; a 31MB teardown
1742 returned fully to the OS).
1744**Rollback.** Reload is all-or-nothing. Either `D'` fully replaces `D`, or `D`
1745remains and no partial state from `D'` survives. A failed reload never leaves the
1746plugin unregistered.
1748**Session continuity.** Reload does not reset the session. Session entries, agent
1749state, and other plugins' state are untouched. In-flight tool executions from the
1750old domain run to completion under `D`; their results are still delivered. New
1751invocations after the swap use `D'`.
1753**Dependents.** Reloading `P` does not reload its dependents (§9.15). Dependents
1754keep their handles to `P`'s registrations by stable name; the swap rebinds those
1755names to `D'`. A reload that removes a registration a dependent relies on surfaces
1756as a normal missing-registration error at next use, not a crash.
1758### 9.17 Plugin Error Model
1760Plugin faults are isolated. A plugin error never corrupts the host, the terminal,
1761or another plugin. Errors are classified by phase:
1763- **Manifest/validation error** (bad name, bad version, unsupported `smith_api`,
1764 missing/cyclic dependency): the plugin does not load. It is disabled and listed
1765 by `smith plugins` with the reason. Other plugins load normally.
1766- **Entry-load error** (Lua error while running entry code or collecting
1767 registrations): the plugin's partial registrations are discarded, the plugin is
1768 disabled with the error, and loading continues for the rest of the set. On
1769 reload (§9.16) this is a failed reload and the old domain is kept.
1770- **Event-handler error** (Lua error inside a subscribed handler): the error is
1771 caught, logged through `smith.log`, and the handler's result is treated as
1772 absent. A non-blocking event proceeds; a blocking event (e.g. `tool_call`) is
1773 treated as no decision — it does not block. One handler's failure never
1774 prevents other handlers for the same event from running.
1775- **Tool-execute error** (Lua error or returned error inside a plugin tool): it
1776 surfaces to the agent as a normal tool error result, not a host crash. The
1777 agent loop continues and the model may react to the error.
1778- **Bus-handler error** (§9.18): same isolation as event-handler errors — caught,
1779 logged, other subscribers still run.
1781Host library code never panics on plugin input (PROJECT-INVARIANTS §3.5). Plugin
1782errors carry the plugin name and phase so `smith plugins` and logs attribute them
1783unambiguously.
1785### 9.18 Inter-Plugin Messaging Bus
1787`smith.bus.*` is a namespaced publish/subscribe channel for plugin-defined
1788messages. It is separate from core lifecycle events (§9.8): the bus carries custom
1789plugin topics, not engine events, and plugins cannot emit core event types on it.
1791API:
1793```lua
1794-- Subscribe to a topic. Returns a handle usable to unsubscribe.
1795local handle = smith.bus.on("acme/index-ready", function(payload, ctx)
1796 ctx.ui.notify("index has " .. payload.count .. " files", "info")
1797end)
1799-- Publish to a topic. Delivers to all current subscribers.
1800smith.bus.emit("acme/index-ready", { count = 128 })
1802-- Stop receiving.
1803smith.bus.off(handle)
1804```
1806Rules:
1808- **Topic names are namespaced** `<org>/<topic>`, using the same character set as
1809 plugin names (§9.2). A plugin may emit any topic; convention is to emit under
1810 its own `org`. `smith/*` topics are reserved for built-in plugins.
1811- **Payloads are plain Lua data tables** — the same value shape passed across the
1812 SDK boundary. No functions, userdata, or host handles cross the bus.
1813- **Delivery is synchronous, in registration order,** on the plugin thread within
1814 the current tick. Emitting during delivery enqueues to run after the current
1815 dispatch completes; the bus does not re-enter.
1816- **Subscriptions are domain-owned** (§9.16). A subscription is dropped when its
1817 plugin's domain is torn down on reload or unload, so no stale subscriber
1818 survives.
1819- **A subscriber error is isolated** (§9.17): caught, logged, remaining
1820 subscribers still receive the message.
1821- **No delivery guarantee across load order:** a message emitted before a
1822 subscriber loads is not replayed. The bus is fire-and-forget, not a queue.
1824The bus is the only sanctioned direct plugin-to-plugin channel. Plugins otherwise
1825compose through shared tool/command/provider registries and the core event
1826bridge.
1828### 9.19 Host Configuration Reload
1830Smith reloads its own configuration at runtime without restarting the process or
1831losing the active session. Host reload follows the same contract shape as plugin
1832reload (§9.16): validate fully, swap atomically, roll back on failure.
1834**Scope.** A host reload re-evaluates the config cascade (§5.6) layers 1–4:
18361. Rust type defaults/schema,
18372. built-in Lua defaults,
18383. plugin contributions,
18394. user config at `config_dir/smith/config.lua`.
1841CLI flags (layer 5) are per-invocation. They were resolved at process start and
1842continue to override the reloaded layers unchanged.
1844**Triggers.** Reload is requested by:
1846- the built-in `/reload-config` slash command (§9.11), a Lua plugin calling the
1847 `smith.config.reload()` primitive (§9.10),
1848- a change to `config_dir/smith/config.lua` when watch-reload is enabled in
1849 config (same setting family as plugin watch-reload, §9.16),
1850- a plugin reload (§9.16), which may change layer-3 contributions; after the
1851 domain swap the cascade is re-evaluated automatically,
1852- in RPC mode (§10.2), the `config/reload` JSON-RPC method. The response reports
1853 success with the changed key paths, or the validation failure verbatim.
1855Eval mode reads config at startup and has no runtime reload trigger.
1857**Sequence.** For a host reload:
18591. Re-evaluate the cascade into a candidate config. Validate every value against
1860 the Rust schemas, and re-run model resolution (§5.7) including alias/group/
1861 bucket cycle detection.
18622. If evaluation, validation, or resolution fails, discard the candidate and keep
1863 the active config. The failure is reported with the exact key path and error;
1864 nothing partially applies.
18653. On success, atomically swap the candidate in as the active config.
18664. Apply effects in order: theme, keybindings, active tool set, resolved
1867 model/provider. TUI re-renders with the new theme on the next frame.
18685. Emit the `config_changed` plugin event (§9.8) carrying the changed key paths.
1869 Plugins read the new values through their contexts (§9.9); the event does not
1870 carry secrets.
1872**Continuity.** Reload is invisible to in-flight work:
1874- an in-flight agent turn keeps the resolved model, tools, and system prompt it
1875 started with; the next turn uses the new config,
1876- running tool executions complete under the old values,
1877- the session, its entries, and plugin domains are untouched — a config reload
1878 never loads, unloads, or reloads plugin code.
1880**Restart-only.** The following are fixed for the process lifetime and never
1881hot-reload:
1883- CLI flags (layer 5),
1884- config/data/cache directory locations (§4),
1885- the active session identity and storage paths,
1886- the run mode (interactive, eval, RPC),
1887- the bundled `providers.json` (§7.3) — runtime provider changes go through
1888 `smith.provider.*` plugin overrides, not registry reload.
1890Credential resolution (§7.4) is not cached across reloads: the next provider
1891stream after a reload resolves auth against the new config values.
13171893## 10. CLI Crate: `smith-cli`
13191895Binary name: `smith`.
13401916- `smith resume` — fuzzy select session in cwd.
13411917- `smith session list [--cwd]` — list sessions.
13421918- `smith session dump [id] [--last N] [--output path]` — JSONL dump.
1343- `smith plugins` — list plugins.
1919- `smith plugins` — list plugins, including disabled plugins with their reason.
1920- `smith plugins reload <org>/<name>` — reload a single loaded plugin (§9.16).
13441921- `smith install <plugin>` — install plugin.
13451922- `smith uninstall <plugin>` — uninstall plugin.
13461923- `smith eval <prompt> [--json] [--session id]` — non-interactive eval.
1347- `smith rpc` — JSON-RPC via stdio.
1924- `smith rpc` — JSON-RPC via stdio; methods include `config/reload` (§9.19).
1925 The full method catalog is deferred: it is expected to mirror the Lua SDK
1926 surface (§9.10), with mode-specific additions and omissions, rather than
1927 define an independent API.
13481928- `smith help [topic] [--search q] [--list] [--examples] [--example name] [--guide name]`.
1929 Topics support dotted function addressing: `smith help tool.register`
1930 resolves the `register` entry within the `tool` topic.
13491931- `smith replay <session> [--speed f64] [--compare] [--sandbox path]
13501932 [--turns N] [--from-turn N] [--format text|json|summary] [--continue-on-diff bool]`.
14171999- Agent loop turn target < 30s excluding provider/network stalls beyond timeout.
14182000- Bench regressions >10% fail nightly/release gates.
2002### 13.1 Memory Policy
2004Prototype-proven against the measured session corpus (p09; see
2005`docs/research/SMITH-MEMORY-ALLOCATION-PROFILE.md`):
2007- **Session discovery is lazy and metadata-only.** Discovery reads session
2008 headers, never full bodies: O(session count), not O(corpus bytes). Fully
2009 loading a realistic corpus would cost ~0.7–1.2GiB resident.
2010- **Virtual scroll materializes at most viewport rows per frame.** Row
2011 formatting stops at the visible window (lazy wrap); a single multi-MiB
2012 message must not be fully formatted to render its visible slice.
2013- **Arenas are scratch-only.** `bumpalo` is permitted solely for phase-local
2014 render/request scratch in measured hot paths. Persisted and session data use
2015 stable IDs and owned strings — never arena references. No custom or unsafe
2016 arena code. Arena references never cross async, thread, or persistence
2017 boundaries.
2018- **Keep/drop gates for arena use** weigh allocator-call pressure, elapsed
2019 time, and peak/plateau stability — not allocation count alone. Measured:
2020 render-frame scratch is a clear win (−100% allocator calls, ~5× faster);
2021 request-build scratch is marginal (−99% calls, ×1.00 elapsed, +22% peak) —
2022 arenas are not a latency win where serialization dominates.
2023- **Provider request assembly** at compaction-scale contexts (~250k tokens) has
2024 a transient peak ~2.5× the serialized request size and must release it fully
2025 after send; peak memory (not just CPU) is a test gate.
14202027## 14. Release Artifacts
14222029Required targets:
14712078- `docs/SPEC.md` is the canonical spec.
14722079- `docs/PROJECT-INVARIANTS.md` contains non-negotiable repository invariants.
1473- Design docs may expand implementation rationale but cannot contradict `SPEC.md`.
2080- No standing design docs: subsystem design content lives in this spec. Any
2081 future exploratory design doc is non-canonical and cannot contradict
2082 `SPEC.md`.
14742083- SDK docs are generated from Lua `---@` annotations and `@usage` blocks.
1475- `smith help` reads embedded generated docs.
2084- `smith help` resolves docs in order: (1) embedded in the binary via
2085 `include_str!`, (2) install directory `<prefix>/share/smith/docs/`,
2086 (3) `SMITH_DOCS_PATH` environment override (development). First hit wins.
14772088Documentation gates:
15502161| `smith-harness` | ≥90% |
15512162| `smith-cli` | ≥80% |
2164Overall workspace coverage target is 85%; merges are blocked below 80%.
15532166### 17.5 nextest
15552168`.config/nextest.toml`:
15742187[profile.thorough]
15752188retries = 1
15762189slow-timeout = "120s"
2191[profile.ci]
2192fail-fast = false
2193retries = 2
2194slow-timeout = "60s"
2195# supports --partition for sharded CI runs
15772196```
15792198### 17.6 Property Tests
16042223CI runs with `INSTA_UPDATE=no`.
2225Snapshot contract (prototype-proven, p08): widget and theme snapshots serialize
2226styled cells — symbol plus fg/bg/modifier per cell — not buffer text alone.
2227Text-only snapshots cannot catch theme regressions: a theme swap changes styles
2228while leaving text byte-identical. Text-only snapshots are permitted only for
2229layout-only assertions.
16062231### 17.8 Integration Tests
16082233Required integration coverage:
16292254- `trace_filter_10000`,
16302255- `plugin_load_10`.
2257Regression thresholds per benchmark: >5% warns, >10% fails the nightly gate
2258(§13).
2260### 17.10 Continuous Integration
2262Test hermeticity — CI tests never touch real external state:
2264- providers are mocked (`StreamFn` fakes; no network),
2265- TUI renders through `TestBackend` (no TTY),
2266- filesystem via temp dirs,
2267- clock and randomness injected (mock clock, fixed seeds),
2268- tests requiring real network live behind a `network-tests` feature and never
2269 run in the default CI lane.
2271Gate tiers by context:
2273| Context | Gate |
2274|---------|------|
2275| every agent iteration | fast tier (§17.1) |
2276| before merge | fast + medium tiers |
2277| CI only | slow tier, coverage, mutation, benchmarks |
2279Agent CI-safety rules (binding for any coding agent working on Smith):
2281- never auto-merge,
2282- never modify CI configuration to make a run pass,
2283- never modify or delete tests to make them pass,
2284- never skip tests to get green.
2286Android/Termux (`aarch64-linux-android`) is a supported development
2287environment, not a release target (§14): CI keeps a validation lane that
2288smoke-builds vendored LuaJIT and syntastica for it; breakage there blocks
2289source-compatibility fixes, not artifact publishing.
16322291## 18. Prototype Policy
16342293Prototypes are disposable evidence for or against this spec. They live under
16462305- next spec/design actions.
16482307Production code must not depend on prototype artifacts.
2309The p02–p11 validation campaign (2026-07-14, x86_64-linux, rustc 1.94.1) ran
2310all ten prototypes to completion; result blocks live in `prototypes/PLAN.md`.
2311Sections marked "prototype-proven" in this spec cite that evidence.

docs/design/AI-CRATE-DESIGN.md

Deleted
deleted file mode 100644

+0 / −319 text lines

1# smith-ai Crate Design
2
3> **Historical document.** This design doc captures early AI crate
4> exploration. The canonical specification is `docs/SPEC.md` §7.
5> Sections below that contradict `docs/SPEC.md` are stale.
6
7## Overview
8
9The `smith-ai` crate handles:
101. **Provider connections** — connecting to LLM APIs
112. **Authentication** — API keys and OAuth flows
123. **Streaming** — streaming responses from providers
134. **Model registry** — all available models from bundled JSON
15## Provider Data (JSON)
17### Location
18- Bundled at compile time: `smith-ai/src/providers.json`
19- Generated by `xtask fetch-providers` from pi.dev + catwalk
21### Structure
23```json
24{
25 "providers": {
26 "anthropic": {
27 "id": "anthropic",
28 "name": "Anthropic",
29 "auth_types": {
30 "api_key": {
31 "env_var": "ANTHROPIC_API_KEY"
32 }
33 },
34 "oauth": {
35 "id": "anthropic",
36 "name": "Anthropic",
37 "scope": "profile"
38 },
39 "models": [
40 {
41 "id": "claude-3-5-sonnet-20241022",
42 "name": "Claude 3.5 Sonnet",
43 "api": "anthropic-messages",
44 "base_url": "https://api.anthropic.com",
45 "reasoning": false,
46 "input": ["text", "image"],
47 "cost": {
48 "input": 0.000003,
49 "output": 0.000015,
50 "cache_read": 0.00000030,
51 "cache_write": 0.000012
52 },
53 "context_window": 200000,
54 "max_tokens": 8192
55 }
56 ]
57 },
58 "openai": {
59 "id": "openai",
60 "name": "OpenAI",
61 "auth_types": {
62 "api_key": {
63 "env_var": "OPENAI_API_KEY"
64 },
65 "organization": {
66 "env_var": "OPENAI_ORG"
67 }
68 },
69 "models": [...]
70 },
71 "google": {
72 "id": "google",
73 "name": "Google",
74 "auth_types": {
75 "api_key": {
76 "env_var": "GOOGLE_API_KEY"
77 }
78 },
79 "oauth": {
80 "id": "google-gemini-cli",
81 "name": "Google Gemini CLI"
82 },
83 "models": [...]
84 },
85 "github-copilot": {
86 "id": "github-copilot",
87 "name": "GitHub Copilot",
88 "auth_types": {
89 "oauth": {
90 "id": "github-copilot",
91 "name": "GitHub Copilot"
92 }
93 },
94 "models": [...]
95 }
96 }
97}
98```
100### Generated Fields
102Some fields are generated at build time and embedded:
103- `base_url` — from provider API docs
104- `cost` — current pricing
105- `context_window`, `max_tokens` — from model specs
107## Auth Types
109### 1. API Key
110```rust
111pub struct ApiKeyAuth {
112 pub env_var: String, // e.g., "ANTHROPIC_API_KEY"
113}
114```
115- Read from environment variable
116- Simple, stateless
118### 2. OAuth
119```rust
120pub struct OAuthConfig {
121 pub id: String, // e.g., "github-copilot"
122 pub name: String, // e.g., "GitHub Copilot"
123 pub auth_url: String, // authorization URL
124 pub token_url: String, // token exchange URL
125 pub scope: String, // OAuth scope
126 pub client_id: String, // OAuth client ID
127}
129pub struct OAuthCredentials {
130 pub access_token: String,
131 pub refresh_token: String,
132 pub expires_at: i64, // Unix timestamp
133}
134```
135- Requires callback server for user authorization
136- Tokens stored securely (where? config file? OS keyring?)
137- Auto-refresh when expired
139### 3. Organization (OpenAI specific)
140```rust
141pub struct OrganizationAuth {
142 pub org_id: String,
143}
144```
146## Auth Resolution
148```rust
149pub enum AuthMethod {
150 ApiKey(String), // API key value
151 OAuth(OAuthCredentials), // OAuth tokens
152 Organization {
153 api_key: String,
154 org_id: String,
155 },
156}
158pub trait AuthResolver: Send + Sync {
159 fn resolve(&self, provider: &str, auth_type: &str) -> Result<AuthMethod, AuthError>;
160}
161```
163## Provider Trait
165```rust
166pub trait Provider: Send + Sync {
167 fn id(&self) -> &str;
168 fn name(&self) -> &str;
169
170 /// Stream LLM responses. Canonical: SM-007 §2.
171 fn stream(&self, request: ProviderRequest) -> Pin<Box<dyn Stream<Item = ProviderEvent> + Send>>;
172
173 /// Validate authentication is configured. Canonical: SM-007 §6.
174 fn validate_auth(&self) -> Result<(), ProviderError>;
175}
176```
178## Model Resolution
180```rust
181pub struct ModelRegistry {
182 providers: HashMap<String, ProviderData>,
183}
185impl ModelRegistry {
186 pub fn load() -> Self;
187 pub fn get(&self, provider: &str, model: &str) -> Option<&Model>;
188 pub fn list_models(&self, provider: Option<&str>) -> Vec<&Model>;
189 pub fn list_providers(&self) -> Vec<&ProviderData>;
190}
191```
193## Streaming
195```rust
196pub struct ProviderStream {
197 // async stream of events
198}
200pub enum ProviderEvent {
201 TextDelta { text: String },
202 ToolCall { id: String, name: String, arguments: String },
203 ThinkingDelta { text: String },
204 Done { usage: ProviderUsage, stop_reason: StopReason },
205 Error { message: String },
206}
207```
209## OAuth Flow
211### 1. User initiates login
212```rust
213pub struct OAuthCallbacks {
214 pub on_auth_url: Box<dyn Fn(String)>, // Display URL to user
215 pub on_code: Box<dyn Fn() -> String>, // Get code from user (or callback server)
216}
217```
219### 2. Login process
220```rust
221pub trait OAuthProvider: Send + Sync {
222 fn get_auth_url(&self, state: &str) -> String;
223 fn exchange_code(&self, code: &str) -> Result<OAuthCredentials, AuthError>;
224 fn refresh(&self, credentials: &OAuthCredentials) -> Result<OAuthCredentials, AuthError>;
225}
226```
228### 3. Callback server
229- Starts local HTTP server on random port
230- Receives OAuth callback
231- Extracts code from URL parameters
232- Returns code to smith
234## xtask: Fetch Providers
236```rust
237// xtask/src/fetch_providers.rs
239pub fn fetch_providers() -> Result<()> {
240 // 1. Fetch from pi.dev
241 let pi_models = fetch_pi_models()?;
242
243 // 2. Fetch from catwalk repo
244 let catwalk_models = fetch_catwalk_models()?;
245
246 // 3. Merge and deduplicate
247 let merged = merge_models(pi_models, catwalk_models);
248
249 // 4. Generate JSON
250 let json = generate_provider_json(merged);
251
252 // 5. Write to smith-ai/src/providers.json
253 write_providers_json(&json)?;
254
255 Ok(())
256}
257```
259## Override Cascade
261```
262bundled providers.json
263 ↓
264plugin overrides (add/modify providers)
265 ↓
266user config (~/.smith/providers.json)
267```
269### OAuth Storage
271OAuth tokens stored in auth JSON file:
272```json
273// ~/.smith/auth.json
274{
275 "anthropic": {
276 "access_token": "...",
277 "refresh_token": "...",
278 "expires_at": 1234567890
279 },
280 "github-copilot": {...}
281}
282```
284### Plugin Override
286Plugins can add or modify providers via SDK:
287```rust
288// In plugin manifest or SDK call
289sdk.add_provider("my-provider", ProviderData { ... });
290sdk.override_model("anthropic", "claude-3-5-sonnet-20241022", ModelOverrides { ... });
291```
293### Initial Providers
295All providers from pi.dev + catwalk:
296- **pi.dev providers**: anthropic, openai, google, mistral, amazon-bedrock, google-vertex, google-gemini-cli, azure-openai, openai-codex, github-copilot, xai, groq, cerebras, openrouter, vercel-ai-gateway, zai, minimax, huggingface, opencode, kimi-coding
297- **catwalk providers**: openrouter, huggingface, and OpenAI-compatible APIs
299### MiniMax Token Plan Provider Notes
301P12 confirmed MiniMax Token Plan works through the OpenAI-compatible adapter:
302- Base URL: `https://api.minimax.io`
303- Auth: bearer API key with `sk-cp-` Token Plan prefix
304- Models: `MiniMax-M2.7`, `MiniMax-M2.7-highspeed`
305- Streaming and non-streaming both work
306- `stream_options.include_usage` returns final usage totals
307- Chain-of-thought/reasoning tokens may appear in `content` before final answer text
308- Error responses are structured JSON bodies, not necessarily SSE chunks
310## TODO
312- [x] Define exact JSON schema
313- [x] Design OAuth storage (auth JSON file)
314- [x] Design OAuth callback server integration
315- [x] Design plugin override mechanism
316- [ ] ~~Implement xtask fetch command~~ — tracked in SM-007 Steps
317- [ ] ~~Implement model registry~~ — tracked in SM-007 Steps
318- [ ] ~~Implement auth resolvers~~ — tracked in SM-007 Steps
319- [ ] ~~Implement all providers from pi.dev + catwalk~~ — tracked in SM-007 Steps

docs/design/PLUGIN-SDK-DESIGN.md

Deleted
deleted file mode 100644

+0 / −671 text lines

1# smith Plugin SDK Design
2
3> **Historical document.** This design doc captures early plugin system
4> exploration. The canonical plugin specification is `docs/SPEC.md` §9.
5> Sections below that contradict `docs/SPEC.md` are stale.
6
7## Overview
8
9Smith's plugin system uses **Lua** (not TypeScript). Plugins are Lua modules that
10extend smith's behavior. The SDK is exposed as Lua globals and modules registered
11by smith-harness via mlua.
13## Core Principle
15Plugins are Lua scripts. They can:
16- Register custom tools callable by the LLM
17- Subscribe to lifecycle events
18- Register slash commands
19- Register keyboard shortcuts
20- Override/add providers and models
21- Control TUI layout and widgets
22- Access sandboxed filesystem and environment
24Smith keeps Rust core lean: Rust exposes **primitives** (tools, widgets,
25filesystem, VCS, provider registry, event routing), while user-visible features
26are Lua plugins. Built-in plugins and user plugins use the same SDK surface — no
27private second-class API. Features such as time-travel, `/undo`, VCS tools,
28default layout, and built-in file tools compose primitives from Lua.
30## Plugin Locations
32| Location | Scope |
33|----------|-------|
34| `~/.smith/plugins/*.lua` | Global |
35| `~/.smith/plugins/*/init.lua` | Global (directory) |
36| `.smith/plugins/*.lua` | Project-local |
37| `.smith/plugins/*/index.lua` | Project-local (directory) |
39## Plugin Manifest
41```lua
42-- ~/.smith/plugins/my-plugin/init.lua
43-- or ~/.smith/plugins/my-plugin.lua
45return function(smith)
46 -- Register tools, events, commands, etc.
47end
48```
50## SDK API
52### smith.tool - Register Custom Tools
54```lua
55smith.tool.register({
56 name = "my_tool",
57 description = "What this tool does (shown to LLM)",
58 parameters = {
59 type = "object",
60 properties = {
61 name = { type = "string", description = "Name to greet" },
62 action = { type = "string", enum = { "list", "add" } },
63 },
64 required = { "name" },
65 },
66 execute = function(input, ctx)
67 return {
68 content = { { type = "text", text = "Hello, " .. input.name .. "!" } },
69 }
70 end,
71})
72```
74### smith.on - Subscribe to Events
76```lua
77-- Session lifecycle
78smith.on("session_start", function(event, ctx)
79 ctx.ui.notify("Session started!", "info")
80end)
82smith.on("session_shutdown", function(event, ctx)
83 -- cleanup
84end)
86-- Tool events (can block)
87smith.on("tool_call", function(event, ctx)
88 if event.tool_name == "bash" and event.input.command:find("rm%-rf") then
89 local ok = ctx.ui.confirm("Dangerous!", "Allow rm -rf?")
90 if not ok then
91 return { block = true, reason = "Blocked by user" }
92 end
93 end
94end)
96-- Modify tool results
97smith.on("tool_result", function(event, ctx)
98 return { content = event.content } -- can modify
99end)
101-- Input interception
102smith.on("input", function(event, ctx)
103 if event.text == "ping" then
104 ctx.ui.notify("pong", "info")
105 return { action = "handled" }
106 end
107 return { action = "continue" }
108end)
110-- Agent events
111smith.on("agent_start", function(event, ctx) end)
112smith.on("agent_end", function(event, ctx) end)
113smith.on("turn_start", function(event, ctx) end)
114smith.on("turn_end", function(event, ctx) end)
116-- Message streaming
117smith.on("message_start", function(event, ctx) end)
118smith.on("message_update", function(event, ctx) end)
119smith.on("message_end", function(event, ctx) end)
121-- Context modification (before each LLM call)
122smith.on("context", function(event, ctx)
123 return { messages = event.messages } -- can modify
124end)
126-- Provider request inspection
127smith.on("before_provider_request", function(event, ctx)
128 -- event.payload - inspect or replace
129end)
131-- Model selection
132smith.on("model_select", function(event, ctx)
133 ctx.ui.notify("Model: " .. event.model.id, "info")
134end)
135```
137### smith.command - Register Slash Commands
139```lua
140smith.command.register("stats", {
141 description = "Show session statistics",
142 handler = function(args, ctx)
143 local count = ctx.session.entry_count()
144 ctx.ui.notify(count .. " entries", "info")
145 end,
146})
148-- With autocomplete
149smith.command.register("deploy", {
150 description = "Deploy to environment",
151 autocomplete = function(prefix)
152 return { { value = "dev", label = "Development" },
153 { value = "staging", label = "Staging" },
154 { value = "prod", label = "Production" } }
155 end,
156 handler = function(args, ctx)
157 ctx.ui.notify("Deploying to " .. args, "info")
158 end,
159})
160```
162### smith.shortcut - Register Keyboard Shortcuts
164```lua
165smith.shortcut.register("ctrl+shift+p", {
166 description = "Toggle plan mode",
167 handler = function(ctx)
168 ctx.ui.notify("Toggled!", "info")
169 end,
170})
171```
173### smith.provider – Unified Provider API
175One function handles both adding and overriding. If the provider name
176already exists (built-in or previously registered), it merges/overrides.
177If new, it adds.
179```lua
180-- Add new provider
181smith.provider.register("ollama", {
182 base_url = "http://localhost:11434",
183 api = "openai-completions",
184 models = {
185 {
186 id = "llama3",
187 name = "Llama 3",
188 reasoning = false,
189 input = { "text" },
190 cost = { input = 0, output = 0, cache_read = 0, cache_write = 0 },
191 context_window = 8192,
192 max_tokens = 4096,
193 },
194 },
195})
197-- Override existing provider (merges fields, keeps built-in models unless replaced)
198smith.provider.register("anthropic", {
199 base_url = "https://proxy.example.com",
200})
202-- Full override with custom models
203smith.provider.register("anthropic", {
204 base_url = "https://proxy.example.com",
205 api_key = "ANTHROPIC_PROXY_KEY",
206 models = {
207 {
208 id = "claude-sonnet-4-20250514",
209 name = "Claude 4 Sonnet (proxy)",
210 reasoning = true,
211 input = { "text", "image" },
212 cost = { input = 0.000003, output = 0.000015, cache_read = 0.0000003, cache_write = 0.000012 },
213 context_window = 200000,
214 max_tokens = 16384,
215 },
216 },
217})
219-- Remove a provider entirely
220smith.provider.unregister("my-proxy")
221```
223**Merge rules:**
224- `base_url`: override
225- `api_key`: override
226- `api`: override
227- `headers`: merge (new keys added, existing overridden)
228- `models`: merge by ID (see below)
229- `oauth`: if provided, replaces OAuth config
230- Omitted fields: keep existing value
232**Model merge strategy:**
234By default, models are merged by ID — new models are added, existing IDs are
235overridden field-by-field (same rules as provider: override scalar fields, merge
236tables, keep omitted fields). This is safe for partial updates.
238```lua
239-- Override just the cost of one model (keeps all other models)
240smith.provider.register("anthropic", {
241 models = {
242 { id = "claude-sonnet-4", cost = { input = 0, output = 0 } },
243 },
244})
246-- Replace ALL models for a provider
247smith.provider.register("anthropic", {
248 models = { ... },
249 replace_models = true, -- drop all built-in, use only these
250})
251```
253**Remove specific models:**
254```lua
255smith.provider.unregister_model("anthropic", "claude-3-haiku")
256```
258### smith.tui - Control TUI Layout & Widgets
260```lua
261-- Create widget instances
262local status_bar = smith.tui.widget.truncated_text("ctx 75% | $0.02")
263local messages = smith.tui.widget.virtual_scroll()
264local editor = smith.tui.widget.editor()
265local hints = smith.tui.widget.truncated_text("[Tab] complete [Ctrl+L] model")
267-- Compose layout
268local layout = smith.tui.layout.column({
269 smith.tui.layout.widget(status_bar),
270 smith.tui.layout.expanded(
271 smith.tui.layout.scrollable(
272 smith.tui.layout.widget(messages),
273 "vertical"
274 )
275 ),
276 smith.tui.layout.box({
277 border = smith.tui.border.rounded("Input"),
278 child = smith.tui.layout.widget(editor),
279 }),
280 smith.tui.layout.widget(hints),
281})
283-- Set as center layout
284smith.tui.set_center_layout(layout)
286-- Populate north panel
287smith.tui.set_north_panel(smith.tui.layout.column({
288 smith.tui.widget.text("Debug Info"),
289}))
290```
292### smith.fs - Sandboxed Filesystem Access
294```lua
295-- Read file (within sandbox)
296local content = smith.fs.read("path/to/file")
298-- Write file (within sandbox)
299smith.fs.write("path/to/file", "content")
301-- List directory
302local entries = smith.fs.list("path/to/dir")
304-- Check existence
305local exists = smith.fs.exists("path/to/file")
307-- Glob
308local files = smith.fs.glob("src/**/*.rs")
309```
311### smith.env - Environment Access
313```lua
314-- Read env var (read-only within sandbox)
315local home = smith.env.get("HOME")
317-- Get all allowed env vars
318local vars = smith.env.list()
319```
321### smith.credentials - Credential Access
323```lua
324-- Read credential for provider
325local key = smith.credentials.get("anthropic")
327-- Store credential
328smith.credentials.set("anthropic", "sk-...")
329```
331### smith.send_message - Inject Messages
333```lua
334-- Send steer message (during streaming)
335smith.send_message("Focus on error handling", { deliver_as = "steer" })
337-- Send follow-up (after agent finishes)
338smith.send_message("Then summarize", { deliver_as = "followUp" })
340-- Send user message
341smith.send_user_message("What is 2+2?")
342```
344### smith.active_tools - Manage Active Tools
346```lua
347-- Get active tools
348local active = smith.active_tools.get()
350-- Get all tools
351local all = smith.active_tools.all()
353-- Set active tools
354smith.active_tools.set({ "read", "bash", "my_tool" })
355```
357### smith.vcs - Version-Control Primitives
359`smith.vcs.*` exposes structured primitives backed by smith's internal jj state
360and targeted gitoxide (`gix`) queries. Higher-level behavior lives in Lua
361plugins. The API must not expose jj/gix implementation details directly; Lua
362receives stable smith-shaped tables.
364Read-only/query primitives:
366```lua
367smith.vcs.status() -- { modified = {}, added = {}, deleted = {}, renamed = {} }
368smith.vcs.diff(opts) -- { hunks = {}, text = "..." }
369smith.vcs.diff_revs(a, b) -- diff between revisions/operations
370smith.vcs.op_log({ limit = 50 })-- { { id, description, time, op_type } }
371smith.vcs.op_show(op_id) -- { id, description, diff, files }
372smith.vcs.annotate(path, opts) -- line attribution/blame data
373smith.vcs.interdiff(a, b) -- patch-vs-patch comparison (jj)
374smith.vcs.evolog(rev) -- logical change evolution (jj)
375```
377Mutation primitives:
379```lua
380smith.vcs.commit(message) -- internal/built-in use after mutating tools
381smith.vcs.undo() -- reverse latest operation
382smith.vcs.redo() -- re-apply latest undone operation
383smith.vcs.op_restore(op_id) -- restore repo to an operation
384smith.vcs.restore_paths(paths, rev) -- selective file restore
385smith.vcs.split(opts) -- split current change
386smith.vcs.squash(source, dest) -- combine changes
387smith.vcs.parallelize(revs) -- mark changes independent
388smith.vcs.sparse(paths) -- materialize only selected paths
389smith.vcs.workspace_add(name, opts) -- create additional jj workspace
390```
392Safety rules:
393- Validate operation IDs, paths, and commit messages before invoking jj.
394- Mutating primitives are explicit; inspection APIs are read-only by default.
395- Store jj state under `$XDG_DATA_HOME/smith/<project-hash>/jj-state` and use a
396 project `.jj` symlink with absolute `git_target` to avoid directory pollution.
397- Built-in time-travel and VCS tools are Lua plugins using this namespace.
399## Context Object (ctx)
401Passed to event handlers, tool execute, command handlers:
403```lua
404ctx = {
405 -- UI methods
406 ui = {
407 notify = function(message, level) end, -- "info" | "success" | "error" | "warning"
408 confirm = function(title, message) -> bool end,
409 select = function(title, items) -> item end,
410 input = function(title, placeholder) -> str end,
411 set_status = function(key, text) end,
412 set_widget = function(key, lines) end,
413 },
415 -- Session access (read-only)
416 session = {
417 id = "...",
418 name = "...",
419 entries = function() -> table end,
420 entry_count = function() -> number end,
421 branch = function() -> table end,
422 },
424 -- Model info
425 model = {
426 id = "...",
427 provider = "...",
428 },
430 -- Working directory
431 cwd = "/path/to/project",
433 -- Abort signal
434 signal = AbortSignal,
436 -- Shutdown
437 shutdown = function() end,
438}
439```
441## Event Catalog
443All events from pi, plus smith-specific additions marked with ★.
445### Resource Events
446| Event | Can Block | Description |
447|-------|-----------|-------------|
448| `resources_discover` | No | Contribute skill/prompt/theme/theme paths |
450### Session Events
451| Event | Can Block | Description |
452|-------|-----------|-------------|
453| `session_start` | No | Session started/loaded/reloaded |
454| `session_shutdown` | No | Session shutting down |
455| `session_before_switch` | Yes | Before switching sessions |
456| `session_before_fork` | Yes | Before forking/cloning session |
457| `session_before_compact` | Yes | Before compaction, can customize |
458| `session_compact` | No | Compaction completed |
459| `session_tree` | No | Tree navigation completed |
461### Agent Events
462| Event | Can Block | Description |
463|-------|-----------|-------------|
464| `before_agent_start` | No | Before agent loop, can inject messages, modify system prompt |
465| `agent_start` | No | Agent loop started |
466| `agent_end` | No | Agent loop ended |
467| `turn_start` | No | Turn started |
468| `turn_end` | No | Turn ended |
469| `model_select` | No | Model changed |
471### Message Events
472| Event | Can Block | Description |
473|-------|-----------|-------------|
474| `message_start` | No | Message started |
475| `message_update` | No | Streaming update |
476| `message_end` | No | Message completed |
477| `thinking_delta` ★ | No | Streaming thinking token delta |
478| `text_delta` ★ | No | Streaming text token delta |
480### Tool Events
481| Event | Can Block | Description |
482|-------|-----------|-------------|
483| `tool_execution_start` | No | Tool execution started |
484| `tool_call` | **Yes** | Before tool executes, can block |
485| `tool_execution_update` | No | Tool progress update |
486| `tool_result` | No | After tool completes, can modify |
487| `tool_execution_end` | No | Tool execution finished |
489### Input Events
490| Event | Can Block | Description |
491|-------|-----------|-------------|
492| `input` | No | User input received, can intercept/transform/handle |
493| `user_bash` | No | User `!` / `!!` commands, can intercept |
495### Context Events
496| Event | Can Block | Description |
497|-------|-----------|-------------|
498| `context` | No | Before LLM call, can modify messages |
499| `before_provider_request` | No | Inspect/replace provider payload |
500| `after_provider_response` | No | HTTP response received |
502### Plugin Events ★
503| Event | Can Block | Description |
504|-------|-----------|-------------|
505| `plugin_loaded` | No | After a plugin finished loading |
506| `plugin_unloaded` | No | Before plugin unloads |
508### TUI Events ★
509| Event | Can Block | Description |
510|-------|-----------|-------------|
511| `panel_toggle` | No | Border panel toggled (north/east/south/west) |
512| `resize` | No | Terminal resized |
514### Provider Events ★
515| Event | Can Block | Description |
516|-------|-----------|-------------|
517| `provider_registered` | No | After provider added/overridden |
519## Sandbox
521> **Historical note.** The capability-based sandbox below was an
522> early design. The canonical approach: Lua restricted runtime (no `io`, `os`,
523> `debug`, `package`, `require` globals) is the *only* sandbox. No capability
524> grants, no policy files, no tiers.
526~~### Capabilities
528```lua
529-- Historical only — capability model removed. See docs/SPEC.md §9.10.
530smith.request_capability("fs_read", { paths = { "./src" } })
531smith.request_capability("credentials")
532```~~
534~~### Default Sandbox Config
536```lua
537-- ~/.smith/sandbox.lua — STALE, no longer used
538```~~
540## Built-in Plugins
542Smith ships with built-in Lua plugins for default behavior:
544### 1. default-layout
545Default TUI layout (status bar, message list, editor, hints)
547### 2. read
548Read file tool
550### 3. write
551Write file tool
553### 4. edit
554Edit file tool (find-and-replace)
556### 5. bash
557Execute bash commands
559### ~~6. compact~~
560~~Context compaction~~ — removed; compaction is automatic in smith-core; see `docs/SPEC.md` §6.9.
562### 7. find
563Find files using `smith.fs` primitives backed by the `ignore` crate.
565### 8. grep
566Search file contents using ripgrep crates (`grep`, `grep-regex`,
567`grep-searcher`) behind smith primitives.
569### 9. commands
570Registers core slash commands such as `/undo`, `/redo`, and `/history`.
572### 10. time-travel
573Timeline panel, state inspector, and diff views. Uses `smith.vcs.*`,
574`smith.tui.*`, and `smith.shortcut.*`; no special Rust UI path.
576### 11. vcs-tools
577Agent-facing VCS tools (`vcs_status`, `vcs_diff`, `vcs_blame`, `vcs_log`) built
578from `smith.vcs.*` primitives.
580## Plugin Loading Order
5821. Built-in plugins (always loaded first)
5832. Global plugins (`~/.smith/plugins/`)
5843. Project plugins (`.smith/plugins/`)
586Later plugins override earlier ones for:
587- Provider definitions
588- Tool definitions
589- Command definitions
590- Layout (last writer wins)
592## Example: Permission Gate Plugin
594```lua
595return function(smith)
596 smith.on("tool_call", function(event, ctx)
597 if event.tool_name == "bash" then
598 local cmd = event.input.command
599 if cmd:find("rm%s+%-rf") or cmd:find("sudo") then
600 local ok = ctx.ui.confirm("Dangerous command",
601 "Allow: " .. cmd .. "?")
602 if not ok then
603 return { block = true, reason = "Blocked by user" }
604 end
605 end
606 end
607 end)
608end
609```
611## Example: Custom Provider Plugin
613```lua
614return function(smith)
615 smith.provider.register("ollama", {
616 base_url = "http://localhost:11434",
617 api = "openai-completions",
618 models = {
619 {
620 id = "llama3",
621 name = "Llama 3",
622 reasoning = false,
623 input = { "text" },
624 cost = { input = 0, output = 0, cache_read = 0, cache_write = 0 },
625 context_window = 8192,
626 max_tokens = 4096,
627 },
628 },
629 })
630end
631```
633## Example: Custom Layout Plugin
635```lua
636return function(smith)
637 local status = smith.tui.widget.truncated_text("smith")
638 local messages = smith.tui.widget.virtual_scroll()
639 local editor = smith.tui.widget.editor()
640 local file_tree = smith.tui.widget.select_list({})
642 -- Center: messages + editor
643 smith.tui.set_center_layout(
644 smith.tui.layout.column({
645 smith.tui.layout.widget(status),
646 smith.tui.layout.expanded(
647 smith.tui.layout.widget(messages)
648 ),
649 smith.tui.layout.widget(editor),
650 })
651 )
653 -- West: file tree
654 smith.tui.set_west_panel(
655 smith.tui.layout.box({
656 border = smith.tui.border.single("Files"),
657 child = smith.tui.layout.widget(file_tree),
658 })
659 )
660end
661```
663## TODO
665- [ ] Define exact Lua type annotations
666- [ ] Design plugin package distribution
667- [ ] Design plugin hot-reload
668- [ ] Design plugin dependency resolution
669- [ ] Implement sandbox enforcement in mlua
670- [ ] Design inter-plugin communication
671- [ ] Design error handling for Lua plugins

docs/design/TUI-CRATE-DESIGN.md

Deleted
deleted file mode 100644

+0 / −471 text lines

1# smith-tui Crate Design
2
3> **Historical document.** This design doc captures early TUI crate
4> exploration. The canonical specification is `docs/SPEC.md` §8.
5> Sections below that contradict `docs/SPEC.md` are stale.
6
7## Overview
8
9The `smith-tui` crate provides terminal UI rendering primitives. It exposes
10**widget creation** only — actual layout and widget population is done in Lua
11plugins. The default layout and widgets ship as a built-in Lua plugin.
13## Core Principle: TUI Exposes Widgets, Lua Uses Them
15- **smith-tui**: Widget primitives, rendering, input handling
16- **Lua plugin**: Layout composition, data binding, widget instances
18Even the default layout is a Lua plugin that can be overridden.
20## Widget Catalog (from pi)
22Based on pi's widget set, smith-tui exposes:
24### Primitives
26| Widget | Description |
27|--------|-------------|
28| `Text` | Multi-line text with word wrap |
29| `TruncatedText` | Single-line text, truncated to viewport |
30| `Markdown` | Markdown rendering (headings, code blocks, links, tables) with syntax-highlighted fenced code blocks |
31| `DiffView` | Unified/split diff rendering with hunks, inline word highlights, and syntax-aware code styling |
32| `Box` | Container with optional border |
33| `Spacer` | Empty space filler |
35### Input
37| Widget | Description |
38|--------|-------------|
39| `Input` | Single-line text input with cursor, kill ring, undo |
40| `Editor` | Multi-line text editor with autocomplete, history, paste, undo |
42### Selection
44| Widget | Description |
45|--------|-------------|
46| `SelectList` | Filterable list with keyboard navigation |
47| `SettingsList` | Key-value settings with cycling values and submenus |
49### Feedback
51| Widget | Description |
52|--------|-------------|
53| `Loader` | Spinning loader with animated frames |
54| `CancellableLoader` | Loader that can be cancelled with Escape |
56### Media
58| Widget | Description |
59|--------|-------------|
60| `Image` | Terminal image (Kitty protocol, Sixel fallback) |
62### Utilities
64| Widget | Description |
65|--------|-------------|
66| `FuzzyFilter` | Fuzzy matching for search/filter using `fuzzy-matcher` scores and match indices |
67| `Overlay` | Floating panel with configurable anchor and size |
69## Rendering Helpers
71### Syntax highlighting
73`Markdown` code blocks and code-oriented tool renderers use `syntastica` with
74the `runtime-c2rust` feature. P16 verified this path on Android/Termux with zero
75C runtime dependencies. The TUI core owns the highlighter/processor cache; Lua
76plugins request highlighted content by language or file path.
78```rust
79pub struct SyntaxHighlighter {
80 // wraps syntastica Processor + language set
81}
83impl SyntaxHighlighter {
84 pub fn highlight_ansi(&mut self, code: &str, lang: Option<&str>) -> String;
85 pub fn supports_language(&self, lang: &str) -> bool;
86}
87```
89No automatic language detection for prose. Plugins pass explicit language or a
90file path. Unsupported languages fall back to plain text.
92### Diff rendering
94`DiffView` uses `similar` for line/word diffs and hunk iteration. The widget
95supports unified and side-by-side modes so Lua plugins can build time-travel,
96replay-compare, and tool-result diff UIs without custom Rust feature code.
98```rust
99pub enum DiffMode { Unified, SideBySide }
101pub struct DiffView {
102 mode: DiffMode,
103 old_label: String,
104 new_label: String,
105 hunks: Vec<DiffHunk>,
106}
107```
109### Fuzzy filtering
111`FuzzyFilter` wraps `fuzzy-matcher` and returns both score and matched indices.
112`SelectList` and plugin-built timelines use these indices to style matched
113characters in ratatui spans.
115## Layout System: Border Layout
117```
118┌─────────────────────────────────────────────────┐
119│ [North Panel] │
120├──────┬──────────────────────────────────┬───────┤
121│ │ │ │
122│[West]│ [Center] │[East] │
123│ │ │ │
124│ │ (default: messages + │ │
125│ │ input area) │ │
126│ │ │ │
127├──────┴──────────────────────────────────┴───────┤
128│ [South Panel] │
129└─────────────────────────────────────────────────┘
130```
132- **Center**: Default layout (status bar + message list + input + hints)
133- **North/East/South/West**: Empty, invisible by default
134- Each panel has a default hotkey to toggle visibility
135- Panels can be populated by plugins
137## Default Layout (Lua Plugin)
139The default center layout, shipped as a built-in Lua plugin:
141```
142┌─────────────────────────────────────────────────┐
143│ [ctx 75%] [$0.02] [session: smith] [model: claude] │ ← StatusBar
144├─────────────────────────────────────────────────┤
145│ │
146│ User: What does this function do? │
147│ │
148│ Assistant: This function handles... │
149│ │
150│ Tool: read("src/main.rs") │
151│ │ fn main() { ... } │
152│ │
153│ Assistant: As you can see... │ ← MessageList (virtual scroll)
154│ │
155│ │
156├─────────────────────────────────────────────────┤
157│ > What's the next step? │ ← Editor
158├─────────────────────────────────────────────────┤
159│ [Tab] complete [Ctrl+L] model [/help] hints │ ← HintBar
160└─────────────────────────────────────────────────┘
161```
163## Virtual Scroll (Most Important Widget)
165The `MessageList` widget uses virtual scrolling for performance:
166- Only render visible messages
167- Cache rendered lines per message
168- Invalidate cache on resize or theme change
169- Smooth scroll with configurable overscan
171Reference: pi's differential rendering approach.
173```rust
174pub struct VirtualScroll {
175 items: Vec<ScrollItem>,
176 total_height: usize,
177 viewport_height: usize,
178 scroll_offset: usize,
179 rendered_cache: HashMap<usize, Vec<String>>,
180}
182impl VirtualScroll {
183 pub fn scroll_to(&mut self, offset: usize);
184 pub fn scroll_by(&mut self, delta: i32);
185 pub fn scroll_to_bottom(&mut self);
186 pub fn render(&mut self, width: usize, height: usize) -> Vec<String>;
187}
188```
190## Theme System
192Every element is themeable. Themes are Lua tables:
194```lua
195-- ~/.smith/themes/catppuccin.lua
196return {
197 name = "catppuccin",
199 -- Default text styling
200 default_text = {
201 fg = "#cdd6f4",
202 bg = "#1e1e2e",
203 bold = false,
204 italic = false,
205 },
207 -- Markdown elements
208 markdown = {
209 heading = { fg = "#cba6f7", bold = true },
210 link = { fg = "#89b4fa", underline = true },
211 link_url = { fg = "#6c7086", italic = true },
212 code = { fg = "#a6e3a1", bg = "#313244" },
213 code_block = { fg = "#a6e3a1", bg = "#1e1e2e" },
214 code_block_border = { fg = "#45475a" },
215 quote = { fg = "#9399b2", italic = true },
216 quote_border = { fg = "#89b4fa" },
217 hr = { fg = "#45475a" },
218 list_bullet = { fg = "#fab387" },
219 bold = { bold = true },
220 italic = { italic = true },
221 strikethrough = { strikethrough = true },
222 },
224 -- Message roles
225 user = { fg = "#cdd6f4", bg = "#1e1e2e" },
226 assistant = { fg = "#cdd6f4", bg = "#181825" },
227 tool = { fg = "#fab387", bg = "#26233a" },
228 tool_error = { fg = "#f38ba8" },
229 thinking = { fg = "#6c7086", italic = true },
231 -- UI elements
232 status_bar = { fg = "#a6adc8", bg = "#313244" },
233 hint_bar = { fg = "#6c7086", bg = "#181825" },
234 input = { fg = "#cdd6f4", bg = "#1e1e2e" },
235 input_border = { fg = "#45475a" },
236 loader = { fg = "#89b4fa" },
237 error = { fg = "#f38ba8" },
238 success = { fg = "#a6e3a1" },
240 -- Select list
241 select_list = {
242 selected_prefix = { fg = "#89b4fa" },
243 selected_text = { fg = "#cdd6f4", bold = true },
244 description = { fg = "#6c7086" },
245 },
247 -- Border panels
248 panel = {
249 border = { fg = "#45475a" },
250 bg = "#1e1e2e",
251 },
252}
253```
255## Overlay System
257Floating panels for modals, fuzzy search, autocomplete:
259```rust
260pub enum OverlayAnchor {
261 Center,
262 TopLeft, TopRight, TopCenter,
263 BottomLeft, BottomRight, BottomCenter,
264 LeftCenter, RightCenter,
265}
267pub struct OverlayOptions {
268 pub width: Option<Size>, // absolute or percentage
269 pub max_height: Option<Size>,
270 pub anchor: OverlayAnchor,
271 pub offset_x: i32,
272 pub offset_y: i32,
273 pub margin: Option<Margin>,
274}
276pub enum Size {
277 Absolute(u16),
278 Percent(u8),
279}
280```
282## Component Trait (Rust)
284```rust
285/// Canonical: SM-008 §3. Uses ratatui-native signatures.
286pub trait Component: Send + Sync {
287 fn render(&self, area: Rect, buf: &mut Buffer);
288 fn handle_event(&mut self, event: &TuiEvent) -> bool;
289 fn invalidate(&mut self);
290}
292pub trait Focusable: Component {
293 fn focused(&self) -> bool;
294 fn set_focused(&mut self, focused: bool);
295 fn as_focusable_mut(&mut self) -> Option<&mut dyn Focusable>;
296}
297```
299## Keybindings
301Default keybindings (overridable via Lua config):
303```
304# Panel toggles
305Ctrl+1 toggle north panel
306Ctrl+2 toggle east panel
307Ctrl+3 toggle south panel
308Ctrl+4 toggle west panel
310# Navigation
311Up/Down scroll messages
312PgUp/PgDn page scroll
313Home/End scroll to top/bottom
315# Input
316Enter submit
317Ctrl+C abort
318Ctrl+L cycle model
319Tab autocomplete
321# Editor (multiline input)
322Alt+Enter newline
323Ctrl+A select all
324Ctrl+Z undo
325```
327## Panel Hotkeys
329| Key | Panel | Default Content |
330|-----|-------|----------------|
331| Ctrl+1 | North | Empty |
332| Ctrl+2 | East | Empty |
333| Ctrl+3 | South | Empty |
334| Ctrl+4 | West | Empty |
336Plugins populate panels. Example: a file tree plugin could populate the west panel.
338## Layout Primitives
340Plugins compose layouts using primitives. The only predefined layout is the
341master border layout. Everything else is built from these building blocks.
343### Layout Types
345```rust
346pub enum Layout {
347 /// Stack children vertically
348 Column { children: Vec<Layout> },
349 /// Stack children horizontally
350 Row { children: Vec<Layout> },
351 /// Fixed-size box with optional border
352 Box {
353 child: Box<Layout>,
354 width: Option<Size>,
355 height: Option<Size>,
356 border: Option<Border>,
357 },
358 /// Flexible space (expands to fill)
359 Expanded { child: Box<Layout> },
360 /// Scrollable container
361 Scrollable {
362 child: Box<Layout>,
363 direction: ScrollDirection,
364 },
365 /// Overlay / modal
366 Overlay {
367 child: Box<Layout>,
368 options: OverlayOptions,
369 },
370 /// Widget slot (binds to a widget instance)
371 Widget { id: String },
372 /// Empty space with optional size
373 Spacer { size: Option<Size> },
374 /// Tabs
375 Tabs {
376 children: Vec<TabItem>,
377 active: usize,
378 },
379 /// Split pane (resizable)
380 Split {
381 direction: SplitDirection,
382 first: Box<Layout>,
383 second: Box<Layout>,
384 split_ratio: f32,
385 },
386}
388pub enum ScrollDirection { Vertical, Horizontal, Both }
389pub enum SplitDirection { Horizontal, Vertical }
391pub struct Border {
392 pub style: BorderStyle,
393 pub title: Option<String>,
394}
396pub enum BorderStyle {
397 Single, Double, Rounded, Thick, None,
398}
400pub struct TabItem {
401 pub label: String,
402 pub layout: Layout,
403}
404```
406### Lua API for Layout
408```lua
409-- Create a column layout
410local layout = smith.tui.layout.column({
411 smith.tui.layout.widget("status_bar"),
412 smith.tui.layout.expanded(
413 smith.tui.layout.widget("message_list")
414 ),
415 smith.tui.layout.box({
416 height = smith.tui.size.percent(20),
417 border = smith.tui.border.rounded("Input"),
418 child = smith.tui.layout.widget("editor"),
419 }),
420 smith.tui.layout.widget("hint_bar"),
421})
423-- Register as center content
424smith.tui.set_center_layout(layout)
425```
427### Layout Resolution
429```rust
430/// Resolve a layout tree into render commands
431pub fn resolve_layout(
432 layout: &Layout,
433 available: Rect,
434 widgets: &HashMap<String, Box<dyn Component>>,
435) -> Vec<RenderCommand>
436```
438Layout resolution walks the tree,分配 available space to children:
439- `Column`: splits height among children (Expanded takes remaining)
440- `Row`: splits width among children (Expanded takes remaining)
441- `Box`: constrains child to fixed size, applies border
442- `Widget`: renders the bound widget into the allocated rect
444### Master Border Layout
446The one predefined layout. Cannot be removed, only panels toggled:
448```rust
449pub struct BorderLayout {
450 pub center: Layout,
451 pub north: Option<Panel>,
452 pub south: Option<Panel>,
453 pub east: Option<Panel>,
454 pub west: Option<Panel>,
455}
457pub struct Panel {
458 pub visible: bool,
459 pub size: Size,
460 pub layout: Layout,
461}
462```
464Default state: all panels invisible, center uses the default Lua plugin layout.
466## Deferred (v1 scope)
468- Vim-style normal mode editing
469- Inline image rendering (Kitty graphics protocol)
470- Split pane resizing (Split layout primitive exists)
471- Multiple simultaneous sessions

docs/plans/PLUGIN-DOC-PLAN.md

Modified

+5 / −0 text lines

281281 └── doc_gen.rs -- generate man pages + docs bundle
282282```
284> Normative pieces of this plan are now canonical in SPEC: doc resolution
285> order + `SMITH_DOCS_PATH` (§16), `smith help <topic>.<function>` dotted
286> addressing (§10.2), system-prompt SDK self-learn bootstrap (§6.8). This
287> file remains the execution plan for file inventories and tooling.
284289## TODO
286291- [ ] Create SDK annotation files in `smith-harness/src/lua/sdk/`

docs/plans/PROTOTYPE-REPORT.md

Deleted
deleted file mode 100644

+0 / −326 text lines

1# Prototype Verification Report
2
3**Generated**: 2026-05-22
4**Status**: COMPLETE — all prototypes tested, fixes applied
5**Environment**: rustc 1.95.0, aarch64-unknown-linux (Termux/Android)
6**Last verified**: 2026-05-23 (cargo check + cargo run for all prototypes in report table)
7
8## Results
9
10| # | Prototype | Status | Summary |
11|---|-----------|--------|---------|
12| P1 | Workspace deps (22 crates) | ✅ PASS | All deps resolve and compile. |
13| P2 | mlua vendored LuaJIT | INACTIVE (SUPERSEDED) | Historical prototype only. Android link failed due to missing compiler-rt builtins; canonical follow-up is P2d. |
14| P2b | mlua non-JIT comparison prototype | ✅ SUPERSEDED | Proved mlua sandbox behavior, coroutines, serde, and error propagation on Android. Alternate runtime path removed; P2d is canonical. |
15| P2d | mlua vendored LuaJIT static ARM | ✅ PASS | Static vendored LuaJIT works on Android/Termux when linking `libclang_rt.builtins-aarch64-android.a` for `__clear_cache`. |
16| P3 | CBOR session codec (minicbor) | INACTIVE (SUPERSEDED) | Historical prototype only. Enum derive was broken; canonical replacement is P3b. |
17| P3b | CBOR session codec (ciborium) | ✅ PASS | All 4 SessionEntry variants + TraceEntry roundtrip. |
18| P4 | ratatui TUI + mouse | ✅ PASS | Fixed unused imports. Compiles clean. |
19| P5 | Provider trait + MuxProvider | ✅ PASS | Fixed with async-trait crate. Failover + circuit breaker work. |
20| P6 | Config parsing + CBOR | ✅ PASS | Fixed with ciborium. Config roundtrip OK (146 bytes). |
21| P7 | zstd trace codec | ✅ PASS | Fixed with ciborium+serde. 100 entries, 4.4% compression ratio. |
22| P8 | Terminal cap detection | ✅ PASS | Fixed with `unsafe extern "C"`. Truecolor, size detection work. |
23| P9 | SSE stream parser | ✅ PASS | Parse, [DONE], multi-line data all pass. |
24| P10 | xtask release (tar/zip/sha256) | ✅ PASS | Fixed with `SimpleFileOptions`. tar.gz + zip + checksums. |
25| P11 | Trace roundtrip (CBOR+zstd+header) | ✅ PASS | All 7 integration tests: SessionEntry CBOR-seq, TraceEntry CBOR-seq, zstd compress/decompress, length-prefixed (uncompressed + compressed), TraceFileHeader binary, full trace file roundtrip. |
26| P12 | Real LLM streaming (MiniMax API) | ✅ PASS (live) | Real SSE streaming confirmed with Token Plan endpoint (`api.minimax.io/v1/chat/completions`, model `MiniMax-M2.7`). 5 chunks received, content-length finish_reason. Mock SSE also passes. |
27| P13 | Harness reload timing | ✅ PASS | 100 cycles: P50=0.4ms, P99=0.6ms, 2040 reloads/sec. Init+warmup+teardown all sub-ms. |
28| P14 | Replay engine validation | ✅ PASS | Trace replay semantics, turn seek, speed modes, compare mode, and smart filtering are all validated. |
29| P15 | Hot reload | ✅ PASS | Plugin load/reload/rollback, session persistence, and trace event continuity are validated. |
30| P16 | syntastica syntax highlighting | ✅ PASS | 9/9 tests on Android/Termux. Rust/Lua/JS/TS highlighting, themes, HTML render, Processor reuse, zero C deps via `runtime-c2rust`. |
31| P17 | VCS SDK + Lua plugins | ✅ PASS | `smith.vcs.*` primitives exposed to Lua. Time-travel, slash commands, and VCS tools implemented as Lua plugins; Rust core stays primitive-only. |
32| P18 | Architecture contract | ✅ PASS | Data-only crate graph, dependency boundaries, ownership map, and async boundaries verified. |
33| P19 | CLI smoke | ✅ PASS | SM-010 subcommand coverage and parsing behavior verified with clap. |
34| P20 | Testing methodology meta | ✅ PASS | SM-012 coverage gates, tier gates, and evidence mapping checks are codified and validated. |
35| **Total** | **23 prototypes** (incl. 2 inactive historical) | **21/21 active build+run** | **100% active build+run, 91% historical build+run, 23/23 historical check** |
37## Prototype → Spec Mapping
39| Prototype | Spec(s) Covered | Aspect Verified |
40|-----------|----------------|----------------|
41| P1 | SM-003 | Workspace deps (22 crates) resolve & compile |
42| P2 | SM-009 | Historical/inactive superseded: original LuaJIT attempt (archived only) |
43| P2b | SM-009 | Historical/inactive superseded non-JIT sandbox behavior comparison |
44| P2d | SM-009 | Canonical vendored static LuaJIT on ARM/Android with compiler-rt builtins link |
45| P3 | SM-005, SM-006 | Historical/inactive superseded: minicbor enum derivation attempt |
46| P3b | SM-005, SM-006 | Canonical proof for CBOR codec using ciborium (SessionEntry/TraceEntry) |
47| P4 | SM-008 | ratatui + crossterm TUI, mouse events |
48| P5 | SM-007 | Provider trait, async dyn, MuxProvider failover + circuit breaker |
49| P6 | SM-005 | Config parsing (SmithConfig structure) + CBOR roundtrip |
50| P7 | SM-006 | zstd compressed trace codec, CBOR stream decode |
51| P8 | SM-008 | Terminal cap detection (isatty, truecolor, size) |
52| P9 | SM-007 | SSE stream parser, [DONE], multi-line data |
53| P10 | SM-003, SM-011 | xtask release build (tar/zip/sha256) |
54| P11 | SM-005, SM-006 | CBOR+zstd trace codec integration (SessionEntry + TraceEntry + TraceFileHeader roundtrip) |
55| P12 | SM-007 | Real LLM API streaming (reqwest + SSE parse, Token Plan endpoint) |
56| P13 | SM-009 | Harness init/warmup/teardown reload timing (Lua + CBOR + config) |
57| P16 | SM-008 | Syntax highlighting with syntastica (`runtime-c2rust`), themes, file type detection, terminal/HTML render |
58| P17 | SM-006, SM-009, SM-010 | VCS primitives (`smith.vcs.*`) plus Lua plugins for time-travel, `/undo`/`/redo`, and VCS tools |
59| P14 | SM-006 | Replay engine behavior and session reconstruction |
60| P15 | SM-009 | Hot reload lifecycle, rollback, and session continuity |
61| P18 | SM-004 | Crate graph, ownership map, plugin-only feature ownership, async boundary assertions |
62| P19 | SM-010 | clap command matrix, global flags, replay speed semantics, and eval JSON parsing |
63| P20 | SM-012 | Test tiers, gates, required cases, and evidence coverage checks |
65### Specs Without Dedicated Prototypes
67| Spec | Reason |
68|------|--------|
69| *(none)* | All canonical specs now have dedicated prototype evidence (P18, P19, P20). |
71**Pass rate**: **21/21 build+run** (active only), **23/23 check** (historical total). Historical build+run remains 21/23 (91%) because P2 and P3 are inactive superseded entries. P3 is superseded by P3b (ciborium). P2 is superseded by P2d, which proves vendored static LuaJIT works on Android/Termux.
73**Integration prototypes** (P11, P12, P17) cross subsystem boundaries:
74- P11 validates SM-005 shared types + SM-006 core TraceCodec work together end-to-end
75- P12 validates SM-007 Provider network I/O with SSE parsing (mock-verified, real API needs valid key)
76- P17 validates SM-009 Lua plugin features over SM-006/SM-010 VCS/session primitives
77- P18 validates SM-004 canonical architecture boundaries
78- P19 validates SM-010 CLI surface and argument behavior
79- P20 validates SM-012 testing gates and required case coverage
81---
83## Fixes Applied
85| Prototype | Original Issue | Fix Applied |
86|-----------|---------------|-------------|
87| P2 | `lua.load(code, None)` — 2 args | `lua.load(code)` — 1 arg (mlua 0.10 API). Linker still fails on Android. |
88| P4 | Unused imports `KeyEvent`, `MouseEvent`, `Clear` | Removed from use statements. |
89| P5 | `async fn` in trait not dyn-compatible | Added `async-trait = "0.1"` crate + `#[async_trait]` annotation. |
90| P6 | minicbor enum broken + unused vars | Switched to ciborium, replaced broken TOML parser with direct JSON. |
91| P7 | minicbor enum broken + `is_finished()` | Rewrote with ciborium+serde. Uses cursor-based CBOR stream decode. |
92| P8 | `extern "C"` blocks need `unsafe` | Added `unsafe` keyword. |
93| P10 | zip 2.x `FileOptions` | Changed to `SimpleFileOptions::default()`. |
95---
97## Critical Issues
99### P0-1: minicbor enum derive broken — switch to ciborium
101**Spec**: SM-005/SM-006 define CBOR session types using minicbor with `#[derive(Encode, Decode)]`
102**Problem**: minicbor-derive generates `Encode<Ctx>`/`Decode<Ctx>` for enums where `Ctx=()` does NOT satisfy. Structs work. Enums fail.
103**Impact**: CBOR session encoding/decoding completely blocked.
104**Resolution**: P3b proves ciborium (serde-based) handles all SessionEntry and TraceEntry enum variants correctly. P6 and P7 also validate ciborium for config and trace encoding.
106**Spec changes needed**:
107| File | Current | Correct |
108|------|---------|--------|
109| SM-003 | `minicbor = { version = "0.25", features = ["std", "derive"] }` | `ciborium = "0.2"` + `serde = { version = "1", features = ["derive"] }` |
110| SM-011 | Same workspace dep change | Same |
111| SM-005 | `#[derive(minicbor::Encode, minicbor::Decode)]` on enums | `#[derive(serde::Serialize, serde::Deserialize)]` |
112| SM-006 | `minicbor::to_vec(val)` / `minicbor::decode(&buf)` | `ciborium::ser::into_writer(val, &mut buf)` / `ciborium::de::from_reader(&buf[..])` |
113| SM-006 | `#[cbor(n(0))]` field annotations | Plain serde — field order determines encoding |
115### ~~P0-2~~: `async fn` in Provider trait — NOT A SPEC ISSUE
117**Original claim**: SM-007 uses `async fn stream(...)` which is not dyn-compatible.
118**Actual**: SM-007 uses `fn stream(&self, request: ProviderRequest) -> Pin<Box<dyn Stream<Item = ProviderEvent> + Send>>`. This IS dyn-compatible — no async-trait needed in the spec.
119**Resolution**: P5 prototype used `async fn` as a simplified design choice, but the actual spec already uses the correct `Pin<Box<dyn Stream>>` pattern. No spec change needed.
121### ~~P0-3~~: mlua 0.10 `load()` API — NOT A SPEC ISSUE
123**Original claim**: SM-009 uses `lua.load(code, None)` (two args) which fails in mlua 0.10.
124**Actual**: SM-009 already uses `lua.load(&source).eval()?` — the correct single-arg API.
125**Resolution**: Prototype P2's original code used the old API and was fixed. The spec is already correct. No spec change needed.
127### P0-4: LuaJIT vendored Android/Termux linker issue — RESOLVED
129**Spec**: SM-009 specifies `mlua = { features = ["luajit", "vendored"] }`
130**Problem**: LuaJIT's JIT compiler calls `__clear_cache`; Rust's Android link path did not include compiler-rt builtins.
131**Impact**: Original P2 failed to link on Android/Termux.
132**Resolution**: P2d proves vendored static LuaJIT works on Android/Termux when linking `libclang_rt.builtins-aarch64-android.a`.
133**Required link input**: add Android target rustflags or build-script detection for compiler-rt builtins, e.g. `-lclang_rt.builtins-aarch64-android`.
134**Spec change**: None to Lua runtime choice. Keep single canonical runtime: `mlua` + vendored LuaJIT.
136---
138## Moderate Issues
140### P2-1: `extern "C"` blocks require `unsafe`
142**Spec**: SM-008 termcap detection uses `extern "C" { fn isatty(...) -> i32; }`
143**Problem**: Rust 2024 edition requires `unsafe extern "C" { ... }`.
144**Fix**: Add `unsafe` keyword. Or use `libc::isatty()`.
145**Spec change**: SM-008 — use `libc::isatty()` instead of raw FFI.
147### ~~P2-2~~: zip 2.x `start_file` type change — NOT A SPEC ISSUE
149**Original claim**: SM-003 uses `FileOptions::default()` which is removed in zip 2.x.
150**Actual**: SM-003 already uses `zip::write::SimpleFileOptions::default()`.
151**Resolution**: Prototype P10's original code used the old API and was fixed. The spec is already correct.
153### P2-3: Zero-warnings policy + third-party derive macros
155**Problem**: minicbor-derive, serde_derive, and async-trait generate code that may trigger warnings. `-D warnings` in workspace Cargo.toml applies to all crates.
156**Fix**: `#[allow(dead_code)]` on enums with unused variants, `#![allow(...)]` in crate roots.
157**Spec change**: PROJECT-INVARIANTS — document `#[allow]` strategy for proc-macro output.
159### P2-4: P5 unused dependencies (FIXED)
161**Problem**: P5 `Cargo.toml` included 4 unused deps: `reqwest`, `futures`, `serde_json`, `uuid`. Adds unnecessary compile time.
162**Impact**: Minor bloat in prototype. Not a design issue — real smith-ai may use reqwest.
163**Fix applied**: Removed all 4 unused deps. Verified clean build.
165---
167## Spec Corrections Summary
169| Priority | Issue | Specs Affected | Action |
170|----------|-------|---------------|--------|
171| P0 | Switch minicbor → ciborium | SM-003, SM-005, SM-006, SM-004, SM-011 | Replace CBOR crate and all Encode/Decode usage |
172| P0 | LuaJIT vendored on Android | SM-003, SM-011 | RESOLVED by P2d: link compiler-rt builtins; keep vendored LuaJIT only |
173| ~~P0~~ | ~~Provider trait async dyn~~ | ~~SM-003, SM-007~~ | ~~NOT A SPEC ISSUE — spec uses Pin<Box<dyn Stream>>~~ |
174| ~~P0~~ | ~~mlua 0.10 load() API~~ | ~~SM-009~~ | ~~NOT A SPEC ISSUE — spec already correct~~ |
175| ~~P2~~ | ~~extern "C" unsafe~~ | ~~SM-008~~ | ~~NOT A SPEC ISSUE — spec uses crossterm~~ |
176| ~~P2~~ | ~~zip 2.x API~~ | ~~SM-003~~ | ~~NOT A SPEC ISSUE — spec already correct~~ |
177| P2 | Zero-warnings + macros | PROJECT-INVARIANTS | Document #[allow] strategy |
179---
181## Verified Working
183| Component | Crate | Version | Verified By |
184|-----------|-------|---------|-------------|
185| mlua + LuaJIT (vendored) | mlua | 0.10.5 | P2d ✅ static on Android/Termux with compiler-rt builtins link |
186| mlua non-JIT comparison prototype | mlua | 0.10.5 | P2b ✅ behavior proven, superseded by P2d |
187| ratatui + crossterm | ratatui | 0.29.0 | P4 ✅ |
188| crossterm | crossterm | 0.28.1 | P4, P8 ✅ |
189| ciborium (serde CBOR) | ciborium | 0.2.2 | P3b, P6, P7 ✅ |
190| async-trait | async-trait | 0.1 | P5 ✅ |
191| SSE parser (hand-rolled) | — | — | P9 ✅ |
192| tar.gz / zip / sha256 | tar, zip, sha2 | 0.4, 2.x, 0.10 | P10 ✅ |
193| tokio async runtime | tokio | 1.x | P5 ✅ |
194| thiserror | thiserror | 2 | P5, P6 ✅ |
195| zstd compression | zstd | 0.13 | P7 ✅ (4.4% ratio) |
196| flate2 gzip | flate2 | 1.x | P10 ✅ |
197| serde JSON roundtrip | serde_json | 1.x | P6 ✅ |
199---
201## Integration Prototype Findings
203### P11: Trace Roundtrip (CBOR + zstd + TraceFileHeader)
205**What it tests**: SM-005 SessionEntry enum + SM-006 TraceEntry enum + TraceFileHeader binary layout + zstd compression + length-prefixed CBOR-seq encoding.
207**All 7 tests pass:**
2081. SessionEntry CBOR-seq roundtrip (6 variants, 655 bytes)
2092. TraceEntry CBOR-seq roundtrip (4 entries, 335 bytes)
2103. zstd compress/decompress (69.0% ratio)
2114. Length-prefixed encoding (uncompressed)
2125. Length-prefixed encoding (per-entry zstd compressed)
2136. TraceFileHeader binary write/read (64 bytes)
2147. Full trace file roundtrip (header + compressed body)
216**Key finding**: Per-entry zstd compression is **115.5% of raw CBOR** for small traces (4 entries). The spec claims "60-70% size reduction" but that only applies to larger traces with more repetitive data. Small entries have too much zstd header overhead per entry.
218**Recommendation**: Consider block-level compression (compress N entries together) for traces with < 50 entries, and per-entry compression for larger traces. Or use a minimum entry size threshold before compressing.
220### P12: Real LLM Streaming
222**What it tests**: reqwest HTTP client + SSE stream parsing + JSON deserialization + error handling.
224**Mock SSE test passes**: 4 chunks parsed, content="Hello world", finish_reason=stop.
226**Real API test**: MiniMax Token Plan endpoint confirmed working. `api.minimax.io/v1/chat/completions`, model `MiniMax-M2.7`. HTTP 200 + `content-type: text/event-stream`. Received 5 SSE chunks, `finish_reason=length` (hit max_tokens=50). Full content received.
228**Key findings**:
229- Token Plan uses `api.minimax.io` (NOT `api.minimax.chat`). Key prefix `sk-cp-` = Token Plan.
230- Model `MiniMax-M2.7` replaces deprecated `MiniMax-Text-01`.
231- Endpoint is OpenAI-compatible `/v1/chat/completions`.
232- MiniMax returns errors as non-streaming JSON with HTTP 200 — error detection must check body format.
234**Verified working:**
235- reqwest streaming (bytes_stream)
236- SSE line parsing (event:, data:, multi-line, [DONE])
237- ChatCompletion JSON deserialization
238- Real Token Plan authentication
240### P13: Harness Reload Timing
242**What it tests**: SM-009 harness integration — init/teardown/reinit cycle timing for Lua runtime + CBOR codec + config + provider registry.
244**All 6 tests pass:**
2451. Harness init: 0.9ms (first run)
2462. Warmup (sandbox + 2 plugin stubs + CBOR encode): 0.3ms
2473. Verify operational (Lua eval + config + codec + providers)
2484. Teardown (drop): 0.1ms
2495. 100 consecutive reload cycles
2506. Statistics + assertions
252**Results (100 cycles on Android/Termux aarch64):**
253| Metric | Value |
254|--------|-------|
255| P50 reload | 0.4ms |
256| P95 reload | 0.5ms |
257| P99 reload | 0.6ms |
258| Throughput | 2040 reloads/sec |
259| Total 100 cycles | 49.0ms |
261**Key finding**: Harness reload is extremely fast — 0.4ms median. Lua runtime init is 0.2ms P50, CBOR config roundtrip is sub-ms. Fast enough for hot-reload on plugin change without perceptible delay. No need for lazy init or connection pooling for the Lua subsystem.
263---
265## P16: Syntax Highlighting (syntastica)
267**What it tests**: syntastica with `runtime-c2rust` on Android/Termux, exercising Rust/Lua/JavaScript/TypeScript highlighting, theme switching, custom themes, file type detection, Processor reuse, and HTML output.
269**Key findings**:
270- `runtime-c2rust` avoids C runtime dependencies; no Oniguruma or `libtree-sitter` dynamic link.
271- Terminal truecolor ANSI output and HTML rendering both work.
272- TOML support is not required for v1; use explicit language selection where file type detection is incomplete.
274---
276## P17: VCS SDK + Lua Plugins
278**What it tests**: Rust exposes only `smith.vcs.*` and `smith.shortcut.*` primitives through mlua; features are Lua plugins.
280**All feature flows pass through Lua plugins:**
2811. `time-travel.lua` — timeline/op inspection/diff/undo flow over `smith.vcs.*`.
2822. `commands.lua` — `/undo`, `/redo`, history commands.
2833. `vcs-tools.lua` — status, diff, history, restore, annotate-style tool surfaces.
285**Key findings**:
286- Architectural rule holds: built-in features are Lua plugins; Rust core provides minimal primitives.
287- jj operation history can back undo/redo and time-travel without custom file snapshot stacks.
288- Plugin-facing VCS APIs need validated inputs, structured outputs, and mode-aware shortcuts.
290---
292## Recommendations
2941. **Accept ciborium over minicbor** — Proven in 3 prototypes (P3b, P6, P7). Eliminates all minicbor-related issues. Adds serde dependency (already needed for JSON config). Tradeoff: slightly larger binary, no zero-copy decode. Acceptable.
2962. **Use one Lua runtime path** — P2d proves `mlua` with `luajit` + `vendored` compiles, links, and runs on Android/Termux when compiler-rt builtins are linked. Keep LuaJIT as the only supported runtime path; remove alternate runtime features.
2983. **Document `#[allow]` strategy** — Proc-macro derive output (serde, ciborium) may trigger warnings under `-D warnings` policy. Create a PROJECT-INVARIANTS section on allow-lint strategy.
3004. **Revisit zstd per-entry compression** — P11 shows per-entry zstd is 115% of raw CBOR for small traces. Consider block-level compression or minimum entry size threshold. Update SM-006 §13.3 compression trade-off note.
3025. **Handle non-SSE error responses** — P12 shows MiniMax returns errors as plain JSON (HTTP 200) not SSE. SM-007 Provider implementations must detect non-streaming JSON and convert to `ProviderEvent::Error`.
3046. **Keep Rust core primitive-only** — P17 validates the target architecture: Rust exposes SDK primitives (`smith.vcs.*`, `smith.shortcut.*`, `smith.tui.*`), while user-facing features are Lua plugins. Built-in plugins and user plugins must use the same interface.
306~~The following were initially flagged but verified as NOT spec issues:~~
308~~- Add async-trait crate (SM-007 already uses Pin<Box<dyn Stream>>)~~
309~~- Fix mlua load() API (SM-009 already uses correct single-arg form)~~
310~~- Use libc for FFI (SM-008 uses crossterm, not raw extern "C")~~
311~~- Update zip API (SM-003 already uses SimpleFileOptions)~~
313---
315## Post-Audit Fixes
317### Audit Fix 1: P6 mlua dead dependency (APPLIED)
319**Found**: P6 `Cargo.toml` listed `mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }` but source never used mlua. Vendored LuaJIT fails to link on Android/Termux (same `__clear_cache` as P2).
320**Impact**: P6 could not build on this platform despite code being correct.
321**Fix applied**: Removed mlua from P6 Cargo.toml. Verified clean build.
323### Audit Fix 2: P5 unused dependencies (APPLIED)
325**Found**: P5 `Cargo.toml` had 4 unused deps: `futures`, `reqwest`, `serde_json`, `uuid`. Report only flagged `reqwest`.
326**Fix applied**: Removed all 4. Verified clean build.

docs/research/CLIPPY-BEST-PRACTICES.md

Modified

+4 / −0 text lines

@@ -1,5 +1,9 @@ Clippy Best Practices for Cross-Platform Rust TUIs
11# Clippy Best Practices for Cross-Platform Rust TUIs
3> **Status: research candidates, non-canonical.** The canonical lint policy is
4> `docs/SPEC.md` §3.2/§3.3 (mirrored in `.cargo/config.toml`). Lints listed
5> here beyond that set are candidates for post-v1 escalation, not requirements.
6
37**Date:** 2026-05-22
48**Scope:** Lint configuration, zero-warning policy, cross-platform TUI enforcement, unsafe restrictions, rustdoc rules.

docs/research/CRATE-ECOSYSTEM-RESEARCH.md

Modified

+5 / −5 text lines

422422## 18. JSON Schema: jsonschema
424### Decision: jsonschema (future consideration)
424### Decision: jsonschema (SUPERSEDED — active in v1 per SPEC §7.3)
426426**Why not yet:**
427427- Tool definition validation uses JSON Schema
505505- `nucleo` is stronger for editor-scale fuzzy matching but overkill for smith v1.
507507**Versions:**
508- `similar = "3"`
508- `similar = "2"` (SPEC §2.3 canonical)
509509- `syntastica = { version = "0.6", default-features = false, features = ["runtime-c2rust"] }`
510510- `syntastica-parsers = "0.6"`
511511- `fuzzy-matcher = "0.3"`
596596[workspace.package]
597597version = "0.1.0"
598598edition = "2024"
599license = "MIT OR Apache-2.0"
599license = "Apache-2.0" # canonical per docs/SPEC.md §2.3 / PROJECT-INVARIANTS §10
601601[workspace.dependencies]
602602tokio = { version = "1.43", features = ["full"] }
613613grep = "0.4"
614614grep-regex = "0.1"
615615grep-searcher = "0.1"
616similar = "3"
616similar = "2" # SPEC §2.3 pins 2; "3" here was stale
617617syntastica = { version = "0.6", default-features = false, features = ["runtime-c2rust"] }
618618syntastica-parsers = "0.6"
619619fuzzy-matcher = "0.3"
656656| ulid | Less standard than UUIDv7 | ID generation |
657657| blake3 | Less standard than SHA-256 | Hashing |
658658| fancy-regex | Slower, backreferences not needed | Regex |
659| jsonschema | Deferred to v2 | Validation |
659| jsonschema | Superseded: active in v1 (SPEC §2.3, §5.3, §7.3) | Validation |
660660| mini-cbor | Derive friction for complex enums; ciborium uses existing serde derives cleanly | CBOR serialization |
661661| color-eyre | Not selected for current dependency set | Error display |
662662| indicatif | Not selected for current dependency set | Progress bars |

docs/research/RESEARCH-NOTES.md

Modified

+15 / −46 text lines

448448## 4. Architecture Implications
450### Plugin System Design
450### Plugin System Design (REJECTED ALTERNATIVE)
452```
453Plugin (base trait)
454├── ToolProvider — implements Tool trait
455├── WidgetProvider — implements Widget trait
456├── SecurityProvider — implements SecurityPolicy trait
457├── HookProvider — subscribes to engine events
458├── InterfacePublisher — publishes new trait interfaces for others
459└── CommandProvider — registers slash commands
460```
462Each is optional. A plugin implements only what it needs. The engine discovers interfaces via `InterfacePublisher` and builds a registry.
464### Security Architecture
466```
467Plugin Load → Sandbox Tier Assignment
468 ├─ Tier 0 (built-in) → Full access
469 ├─ Tier 1 (trusted Lua) → Cooperative sandbox, no JIT, disabled io/os/debug
470 └─ Tier 2 (WASM) → wasmtime sandbox, capability-gated, fuel-limited
472Tool Call Flow:
473 LLM requests tool → SecurityPolicy.validate() → Sandbox permission check → Execute → SecurityPolicy.inspect() → Return to LLM
474```
452> An early Rust-trait plugin architecture (`Plugin`/`ToolProvider`/
453> `InterfacePublisher` traits, sandbox tiers 0/1/2 with WASM) was explored
454> here and rejected. Canonical: Lua plugins with plain-Lua interface
455> descriptors and a single restricted-runtime sandbox — SPEC §9.4, §9.6,
456> §9.14. Retained only as a record of the road not taken.
476458### Event System
487469Events can return results that **mutate behavior** (block tool calls, transform input, override prompts).
489### OCaml-Style Interface Publishing
471### OCaml-Style Interface Publishing (REJECTED ALTERNATIVE)
491```rust
492/// A plugin that publishes a new interface
493pub trait InterfacePublisher: Plugin {
494 fn published_interfaces(&self) -> Vec<InterfaceDescriptor>;
495}
497pub struct InterfaceDescriptor {
498 name: String, // e.g. "output-formatter"
499 schema: Schema, // JSON schema for the interface
500 rust_trait: TypeId, // Rust trait that implementors must satisfy
501}
503/// Engine maintains a registry
504pub struct InterfaceRegistry {
505 interfaces: HashMap<String, InterfaceDescriptor>,
506 implementations: HashMap<String, Vec<Box<dyn Any>>>,
507}
508```
510This allows plugin A to define "I need things that format output" and plugin B to implement that interface, with the engine wiring them together.
473> A Rust-side `InterfacePublisher`/`InterfaceRegistry` (TypeId-based) was
474> explored and rejected; the concept landed as plain-Lua interface
475> descriptors with bind-time conformance — SPEC §9.6, prototype-proven
476> (p02, p03).
511477---
513479## 5. Pi Source Analysis (2026-05-21)
518484### Agent Loop Hooks (pi_agent_types.ts)
520Pi AgentLoopConfig provides six extension hooks that smith currently lacks:
486Pi AgentLoopConfig provides six extension hooks. Five are now smith hook types
487in SPEC §6.4 (BeforeToolCall, AfterToolCall, ShouldStopAfterTurn,
488PrepareNextTurn, TransformContext); convertToLlm remains pi-specific — smith
489handles message conversion at the provider boundary (§7.2). Original analysis:
522491**1. beforeToolCall(context, signal) -> { block?, reason? }**
523492Called before each tool executes. Can block execution by returning { block: true }.

prototypes/.cargo/config.toml

Added
new file mode 100644

+10 / −0 text lines

1# Prototype-only cargo config.
2#
3# Prototypes are disposable evidence code (docs/SPEC.md §18). The workspace
4# root .cargo/config.toml enforces the production zero-warnings policy
5# (-D warnings, -D missing_docs, clippy restriction lints); that policy is
6# intentionally NOT applied to prototypes. Cargo merges this config after the
7# root one, and the later cap wins, so prototype builds run with lints capped
8# at warn while production crates remain fully gated.
9[build]
10rustflags = ["--cap-lints=warn"]

prototypes/PLAN.md

Modified

+235 / −0 text lines

620620If not viable, SPEC must define explicit cleanup registries and leak/stale-callback
621621failure modes for plugin reload.
623## Results
625All prototypes implemented and run 2026-07-14, rustc 1.94.1,
626x86_64-unknown-linux-gnu, mlua 0.10.5 vendored LuaJIT. Commands per prototype
627section; each exits 0. Result blocks follow the reporting template, trimmed to
628decision-relevant content; full diagnostics are in each prototype's output and
629the corresponding commit message.
631### P02 result
633```json
634{
635 "status": "complete",
636 "proved": [
637 "plain Lua descriptor + runtime validation supports community interfaces",
638 "missing function fails with exact path (impl/missing_fn.lua.cancel)",
639 "bad shape fails with expected/actual (status: expected function, got string)",
640 "extra impl fields hidden through interface view",
641 "runtime arg validation rejects bad types naming fn/param"
642 ],
643 "disproved": [],
644 "specIssues": [
645 { "file": "../docs/SPEC.md", "issue": "§9.6 can adopt candidate 1 (plain Lua descriptors); note mlua reports Lua integers as 'integer' not 'number' in diagnostics", "evidence": "p02 cargo run, all PASS", "severity": "P2" }
646 ],
647 "commands": ["cd prototypes/p02-lua-interface-descriptor && cargo run"],
648 "nextSteps": ["make §9.6 candidate 1 canonical; P02b (Teal) not needed"]
649}
650```
652### P03 result
654```json
655{
656 "status": "complete",
657 "proved": [
658 "5-plugin ecosystem composes through one interface package; consumer source has no impl name",
659 "user config swaps alice <-> bob-adapted with zero consumer changes",
660 "pure-Lua adapter normalizes incompatible impl; passes same conformance check",
661 "direct incompatible binding fails naming plugin, interface+generation, exact missing fns, actual exports, adapter hint"
662 ],
663 "disproved": [],
664 "specIssues": [
665 { "file": "../docs/SPEC.md", "issue": "§9.6 lacks adapter registration semantics (invented `adapts` + make-factory)", "evidence": "p03 bob-adapted scenario", "severity": "P1" },
666 { "file": "../docs/SPEC.md", "issue": "no config syntax exists for interface->implementation binding (invented `interfaces = { [\"community/subagent\"] = \"org/name\" }`)", "evidence": "p03 configs/*.lua", "severity": "P1" },
667 { "file": "../docs/SPEC.md", "issue": "§9.2 `interfaces`/`implements` manifest field shapes undefined", "evidence": "p03 manifests", "severity": "P2" },
668 { "file": "../docs/SPEC.md", "issue": "conformance-check timing (load vs bind) and undeclared-implements policy unstated", "evidence": "p03 bob-direct-fails", "severity": "P2" },
669 { "file": "../docs/SPEC.md", "issue": "singleton vs per-consumer instance semantics open", "evidence": "alice module state vs adapter factory", "severity": "P3" }
670 ],
671 "commands": ["cargo run -- alice", "cargo run -- bob-adapted", "cargo run -- bob-direct-fails"],
672 "nextSteps": ["amend §9.2/§9.6/§9.7 with manifest fields, adapter convention, binding config + precedence"]
673}
674```
676### P04 result
678```json
679{
680 "status": "complete",
681 "proved": [
682 "local-path + git-URL install into data_dir/smith/plugins/<org>/<name>/ (git via local bare repo, shell-out)",
683 "name charset + smith/* reservation enforced before any write",
684 "restricted empty-env manifest eval: os/require blocked, function values rejected as non-data",
685 "smith_api defaults 1; smith_api=2 refused with required/supported generations",
686 "install never executes entry code (armed side effect did not fire)",
687 "duplicate refused without --force; --force = remove-then-copy, data kept",
688 "uninstall keeps data / --purge-data removes it / project plugins never touched"
689 ],
690 "disproved": [],
691 "specIssues": [
692 { "file": "../docs/SPEC.md", "issue": "§9.2 never states the manifest FILENAME (prototype: smith-plugin.lua)", "evidence": "p04 all commands", "severity": "P1" },
693 { "file": "../docs/SPEC.md", "issue": "§9.5 git boundary open: gix vs shell-out; shell-out worked with zero extra crates but adds runtime git-binary dependency", "evidence": "p04 install-git", "severity": "P1" },
694 { "file": "../docs/SPEC.md", "issue": "--force semantics, duplicate definition, .git stripping, data-dir lifecycle, exact restricted-env contents, staged validation before copy all unspecified", "evidence": "p04 output notes", "severity": "P2" }
695 ],
696 "commands": ["cargo run -- install-local|install-git|reject-bad-name|reject-smith-namespace|uninstall-keeps-data|uninstall-purge-data"],
697 "nextSteps": ["canonicalize manifest filename; define --force/duplicate/git-layout; decide git boundary"]
698}
699```
701### P05 result
703```json
704{
705 "status": "complete",
706 "proved": [
707 "pi-primary field-level recursive merge; catwalk fills gaps at field/model/provider granularity",
708 "generate writes nothing; suggestion + reviewable source-attributed patch on stdout",
709 "two unresolvable conflict classes detected, excluded, reported: ambiguous-primary-source, type-mismatch-vs-curated-registry"
710 ],
711 "disproved": [
712 "byte-for-byte unknown-field preservation with default serde_json (keys re-sort); preservation is semantic (Value-equal) only"
713 ],
714 "specIssues": [
715 { "file": "../docs/SPEC.md", "issue": "§7.3 source-vs-curated-registry merge granularity undefined; subtree merge would clobber curated cost objects", "evidence": "p05 diff", "severity": "P1" },
716 { "file": "../docs/SPEC.md", "issue": "§7.3 has no conflict taxonomy/policy at all", "evidence": "p05 conflict-fails", "severity": "P1" },
717 { "file": "../docs/SPEC.md", "issue": "fetch-providers PR-agent contract (outputs, non-zero exit on unresolved conflicts) unspecified; replace_models carrier undefined; no canonical provider/model schema", "evidence": "p05 output notes", "severity": "P2" }
718 ],
719 "commands": ["cargo run -- generate", "cargo run -- diff", "cargo run -- conflict-fails"],
720 "nextSteps": ["amend §7.3: merge granularity, conflict classes, semantic preservation, CLI contract"]
721}
722```
724### P06 result
726```json
727{
728 "status": "complete",
729 "proved": [
730 "truncated tail (mid-body, mid-prefix) stops parsing; prior entries survive",
731 "corrupt entry BODY skips precisely with warning while framing intact",
732 "unknown future variants distinguishable from corruption via two-stage decode (ciborium::Value then typed); preserved raw through v1 rewrite -> v2 read"
733 ],
734 "disproved": [],
735 "specIssues": [
736 { "file": "../docs/SPEC.md", "issue": "§6.6 'corrupt entry: skip + warn if possible' holds only while the length prefix is intact; corrupted length prefix desynchronizes framing and loses everything after (indistinguishable from truncation)", "evidence": "p06 corrupt-length scenario", "severity": "P1" }
737 ],
738 "commands": ["cd prototypes/p06-session-codec-recovery && cargo run"],
739 "nextSteps": ["state the framing boundary in §6.6"]
740}
741```
743### P07 result
745```json
746{
747 "status": "complete",
748 "proved": [
749 "agent loop drives text/tool/done through StreamFn only; deterministic AgentEvent sequences",
750 "tool results fed back to provider next turn",
751 "BeforeToolCall allow/block/replace-args verified; blocked call never executes tool"
752 ],
753 "disproved": [],
754 "specIssues": [
755 { "file": "../docs/SPEC.md", "issue": "§6.4 blocked-call event semantics unspecified; prototype chose ToolExecutionStart + End(is_error) + error tool result to provider", "evidence": "p07 hook-block", "severity": "P2" }
756 ],
757 "commands": ["cargo run -- basic|tool|hook-block|hook-replace"],
758 "nextSteps": ["state blocked-call event contract in §6.4"]
759}
760```
762### P08 result
764```json
765{
766 "status": "complete",
767 "proved": [
768 "TestBackend renders deterministic cell-by-cell (symbol + fg/bg/modifier); snapshot matches checked-in string; fully headless",
769 "Lua theme tables validated by Rust schema drive widget styles; invalid theme rejected with exact path",
770 "theme swap changes styles, leaves text byte-identical"
771 ],
772 "disproved": [],
773 "specIssues": [
774 { "file": "../docs/SPEC.md", "issue": "§8.8 has no theme schema (keys, nesting, color format, missing-key policy)", "evidence": "p08 load_theme invented all of it", "severity": "P1" },
775 { "file": "../docs/SPEC.md", "issue": "§17 snapshot contract undefined; text-only snapshots CANNOT catch theme regressions — style-aware cell comparison required", "evidence": "p08 theme swap: same text, different styles", "severity": "P1" },
776 { "file": "../docs/SPEC.md", "issue": "invalid-user-theme runtime fallback policy (refuse vs fall back to built-in) unstated", "evidence": "p08 hard-error by construction", "severity": "P2" }
777 ],
778 "commands": ["cd prototypes/p08-tui-testbackend && cargo run"],
779 "nextSteps": ["define §8.8 theme schema + §17 style-aware snapshot contract"]
780}
781```
783### P09 result
785```json
786{
787 "status": "complete",
788 "proved": [
789 "discovery O(session count): 535 sessions from 54.8KiB of 41.64MiB corpus (0.13%), 3.1ms",
790 "load/replay within research bands up to 29.78MiB pathological session; 4.6MiB message intact",
791 "virtual scroll O(visible rows): 41 allocs/frame constant across 143x entry spread; giant message capped by lazy viewport wrap",
792 "request-build ~250k tokens: transient peak 2.43MiB, zero live growth over 50 builds",
793 "bumpalo scratch: render -100% allocator calls, x0.19 elapsed (KEEP); request -99% calls, x1.00 elapsed, +22% peak (marginal KEEP)"
794 ],
795 "disproved": [
796 "arenas as a latency win for request-build: serde_json serialization dominates; win is allocator-call pressure only"
797 ],
798 "specIssues": [
799 { "file": "../docs/SPEC.md", "issue": "SPEC must require lazy metadata-only session discovery; full-loading corpus would be ~0.7-1.2GiB resident", "evidence": "p09 discover", "severity": "P1" },
800 { "file": "../docs/SPEC.md", "issue": "adopt scratch-only-bumpalo policy: phase-local render/request scratch only, measured hot paths, stable IDs + owned strings for persisted data, no unsafe arenas, keep/drop gates include allocator-call pressure and peak stability", "evidence": "p09 arena-scratch verdicts", "severity": "P2" },
801 { "file": "../docs/SPEC.md", "issue": "virtual-scroll cache bounds: per-frame materialized rows <= viewport (lazy wrap), else one 4.6MiB message allocates unboundedly", "evidence": "p09 render-giant-message-window", "severity": "P2" }
802 ],
803 "commands": ["cargo run --release -- discover|load-replay|render-window|request-build|arena-scratch|all"],
804 "nextSteps": ["add memory policy to SPEC; re-run keep/drop on real render code before production commitment"],
805 "deviation": "PLAN fixtures/*.jsonl not committed; synthetic sessions generated at runtime (deterministic seed) matching PLAN shapes within 2.5%"
806}
807```
809### P10 result
811```json
812{
813 "status": "complete",
814 "proved": [
815 "Lua::set_memory_limit() WORKS and enforces under mlua 0.10.5 + vendored LuaJIT (GC64 accepts mlua's tracking allocator) — PLAN's warning does not hold for the locked feature set",
816 "oom-table/oom-string rejected at exactly the 16MiB quota (overshoot 0) with recoverable MemoryError; state reusable after gc_collect; host survives",
817 "isolation: plugin B in its own state unaffected by A's OOM",
818 "host-created Lua strings charged to the quota (8MiB string -> delta 8388672)",
819 "quota domain: per-plugin heap quota = one Lua state per plugin"
820 ],
821 "disproved": [
822 "shared-state per-plugin quotas: only a whole-state limit exists, no attribution (B charged at A's retained 15.3MiB)",
823 "Lua quota covering host-side Rust allocations: 8MiB userdata payload registered 632 bytes",
824 "hook-based fallback under active JIT: count hooks never fire JIT-on (0 fires / 3e6 iterations); interpreter-only, ~3.4x slowdown"
825 ],
826 "specIssues": [
827 { "file": "../docs/SPEC.md", "issue": "add plugin heap-quota field; quota domain = per-plugin Lua state (aligns §9.16); shared runtime can never get per-plugin quotas", "evidence": "p10 oom-table + isolation", "severity": "P2" },
828 { "file": "../docs/SPEC.md", "issue": "scope quota wording to the Lua heap; host-side plugin memory bounded by domain teardown, not the Lua limit", "evidence": "p10 host-value accounting", "severity": "P2" },
829 { "file": "../docs/SPEC.md", "issue": "any future instruction watchdog cannot use LuaJIT count hooks (never fire under JIT)", "evidence": "p10 hook bench", "severity": "P3" }
830 ],
831 "commands": ["cargo run -- small|oom-table|oom-string|isolation|all"],
832 "nextSteps": ["add heap-quota to SPEC §9 with per-plugin-state domain; CI-verify enforcement per release target (non-GC64 -> MemoryControlNotAvailable)"]
833}
834```
836### P11 result
838```json
839{
840 "status": "complete",
841 "proved": [
842 "§9.16 full contract implementable as written: PluginDomain owns Lua + descriptors + generation-keyed registries + bus tokens + render cache + bump scratch + cancellation token; reload = construct -> swap -> drop, single Drop impl, no cleanup graph",
843 "100 reload cycles plateau: growth <=77KB over 80 cycles; Lua used_memory constant; threads joined every drop; reload avg 3.8-4.0ms incl. 450 registrations",
844 "rollback: broken entry keeps old domain serving; partial D' registrations discarded",
845 "31MB Lua heap 100% reclaimed by domain drop; fresh domain restarts at 45KB",
846 "every escape path (stale registry entry, leaked bus token, escaped thread) detected and rejected via generation gating; 0 stale callbacks ran; !Send containment stops Lua values crossing threads at compile time"
847 ],
848 "disproved": [],
849 "specIssues": [
850 { "file": "../docs/SPEC.md", "issue": "raw mlua::Function cloned out of the registry PANICS after domain drop (abort-grade under no-panic invariant); §9.16 must mandate generation-keyed-registry-only callback access + generation gate on every dispatch path", "evidence": "p11 escaped-callback-fails: 'call panicked: Lua instance is destroyed'", "severity": "P2" },
851 { "file": "../docs/SPEC.md", "issue": "plateau-after-warmup is the enforceable observable, not instantaneous RSS decrease (small heaps retained by allocator, large teardowns return to OS)", "evidence": "p11 reload-loop vs reload-with-heap-limit RSS traces", "severity": "P3" }
852 ],
853 "commands": ["cargo run -- reload-loop|reload-with-heap-limit|escaped-callback-fails|all"],
854 "nextSteps": ["fold registry/generation-gate discipline into §9.16; re-verify !Send containment if mlua 'send' feature is ever enabled"]
855}
856```
623858## Reporting Template
625860Each completed prototype updates this plan with a result block:

prototypes/p02-lua-interface-descriptor/Cargo.lock

Added
new file mode 100644

+376 / −0 text lines

1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "autocfg"
7version = "1.5.1"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
11[[package]]
12name = "bitflags"
13version = "2.13.0"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
17[[package]]
18name = "bstr"
19version = "1.12.3"
20source = "registry+https://github.com/rust-lang/crates.io-index"
21checksum = "5cee35f73844aa3014bb606320a6c1f010249dbdf43342fe54b5a4f6a8ed4b79"
22dependencies = [
23 "memchr",
24 "serde_core",
25]
27[[package]]
28name = "cc"
29version = "1.2.67"
30source = "registry+https://github.com/rust-lang/crates.io-index"
31checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38"
32dependencies = [
33 "find-msvc-tools",
34 "shlex",
35]
37[[package]]
38name = "cfg-if"
39version = "1.0.4"
40source = "registry+https://github.com/rust-lang/crates.io-index"
41checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
43[[package]]
44name = "either"
45version = "1.16.0"
46source = "registry+https://github.com/rust-lang/crates.io-index"
47checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
49[[package]]
50name = "env_home"
51version = "0.1.0"
52source = "registry+https://github.com/rust-lang/crates.io-index"
53checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
55[[package]]
56name = "erased-serde"
57version = "0.4.10"
58source = "registry+https://github.com/rust-lang/crates.io-index"
59checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
60dependencies = [
61 "serde",
62 "serde_core",
63 "typeid",
64]
66[[package]]
67name = "errno"
68version = "0.3.14"
69source = "registry+https://github.com/rust-lang/crates.io-index"
70checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
71dependencies = [
72 "libc",
73 "windows-sys",
74]
76[[package]]
77name = "find-msvc-tools"
78version = "0.1.9"
79source = "registry+https://github.com/rust-lang/crates.io-index"
80checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
82[[package]]
83name = "libc"
84version = "0.2.186"
85source = "registry+https://github.com/rust-lang/crates.io-index"
86checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
88[[package]]
89name = "linux-raw-sys"
90version = "0.12.1"
91source = "registry+https://github.com/rust-lang/crates.io-index"
92checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
94[[package]]
95name = "lock_api"
96version = "0.4.14"
97source = "registry+https://github.com/rust-lang/crates.io-index"
98checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
99dependencies = [
100 "scopeguard",
101]
103[[package]]
104name = "lua-src"
105version = "547.0.0"
106source = "registry+https://github.com/rust-lang/crates.io-index"
107checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42"
108dependencies = [
109 "cc",
110]
112[[package]]
113name = "luajit-src"
114version = "210.5.12+a4f56a4"
115source = "registry+https://github.com/rust-lang/crates.io-index"
116checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671"
117dependencies = [
118 "cc",
119 "which",
120]
122[[package]]
123name = "memchr"
124version = "2.8.3"
125source = "registry+https://github.com/rust-lang/crates.io-index"
126checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
128[[package]]
129name = "mlua"
130version = "0.10.5"
131source = "registry+https://github.com/rust-lang/crates.io-index"
132checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0"
133dependencies = [
134 "bstr",
135 "either",
136 "erased-serde",
137 "mlua-sys",
138 "num-traits",
139 "parking_lot",
140 "rustc-hash",
141 "rustversion",
142 "serde",
143 "serde-value",
144]
146[[package]]
147name = "mlua-sys"
148version = "0.6.8"
149source = "registry+https://github.com/rust-lang/crates.io-index"
150checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93"
151dependencies = [
152 "cc",
153 "cfg-if",
154 "lua-src",
155 "luajit-src",
156 "pkg-config",
157]
159[[package]]
160name = "num-traits"
161version = "0.2.19"
162source = "registry+https://github.com/rust-lang/crates.io-index"
163checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
164dependencies = [
165 "autocfg",
166]
168[[package]]
169name = "ordered-float"
170version = "2.10.1"
171source = "registry+https://github.com/rust-lang/crates.io-index"
172checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
173dependencies = [
174 "num-traits",
175]
177[[package]]
178name = "p02-lua-interface-descriptor"
179version = "0.1.0"
180dependencies = [
181 "mlua",
182]
184[[package]]
185name = "parking_lot"
186version = "0.12.5"
187source = "registry+https://github.com/rust-lang/crates.io-index"
188checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
189dependencies = [
190 "lock_api",
191 "parking_lot_core",
192]
194[[package]]
195name = "parking_lot_core"
196version = "0.9.12"
197source = "registry+https://github.com/rust-lang/crates.io-index"
198checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
199dependencies = [
200 "cfg-if",
201 "libc",
202 "redox_syscall",
203 "smallvec",
204 "windows-link",
205]
207[[package]]
208name = "pkg-config"
209version = "0.3.33"
210source = "registry+https://github.com/rust-lang/crates.io-index"
211checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
213[[package]]
214name = "proc-macro2"
215version = "1.0.106"
216source = "registry+https://github.com/rust-lang/crates.io-index"
217checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
218dependencies = [
219 "unicode-ident",
220]
222[[package]]
223name = "quote"
224version = "1.0.46"
225source = "registry+https://github.com/rust-lang/crates.io-index"
226checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
227dependencies = [
228 "proc-macro2",
229]
231[[package]]
232name = "redox_syscall"
233version = "0.5.18"
234source = "registry+https://github.com/rust-lang/crates.io-index"
235checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
236dependencies = [
237 "bitflags",
238]
240[[package]]
241name = "rustc-hash"
242version = "2.1.3"
243source = "registry+https://github.com/rust-lang/crates.io-index"
244checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
246[[package]]
247name = "rustix"
248version = "1.1.4"
249source = "registry+https://github.com/rust-lang/crates.io-index"
250checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
251dependencies = [
252 "bitflags",
253 "errno",
254 "libc",
255 "linux-raw-sys",
256 "windows-sys",
257]
259[[package]]
260name = "rustversion"
261version = "1.0.23"
262source = "registry+https://github.com/rust-lang/crates.io-index"
263checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
265[[package]]
266name = "scopeguard"
267version = "1.2.0"
268source = "registry+https://github.com/rust-lang/crates.io-index"
269checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
271[[package]]
272name = "serde"
273version = "1.0.228"
274source = "registry+https://github.com/rust-lang/crates.io-index"
275checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
276dependencies = [
277 "serde_core",
278]
280[[package]]
281name = "serde-value"
282version = "0.7.0"
283source = "registry+https://github.com/rust-lang/crates.io-index"
284checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
285dependencies = [
286 "ordered-float",
287 "serde",
288]
290[[package]]
291name = "serde_core"
292version = "1.0.228"
293source = "registry+https://github.com/rust-lang/crates.io-index"
294checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
295dependencies = [
296 "serde_derive",
297]
299[[package]]
300name = "serde_derive"
301version = "1.0.228"
302source = "registry+https://github.com/rust-lang/crates.io-index"
303checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
304dependencies = [
305 "proc-macro2",
306 "quote",
307 "syn",
308]
310[[package]]
311name = "shlex"
312version = "2.0.1"
313source = "registry+https://github.com/rust-lang/crates.io-index"
314checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
316[[package]]
317name = "smallvec"
318version = "1.15.2"
319source = "registry+https://github.com/rust-lang/crates.io-index"
320checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
322[[package]]
323name = "syn"
324version = "2.0.118"
325source = "registry+https://github.com/rust-lang/crates.io-index"
326checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
327dependencies = [
328 "proc-macro2",
329 "quote",
330 "unicode-ident",
331]
333[[package]]
334name = "typeid"
335version = "1.0.3"
336source = "registry+https://github.com/rust-lang/crates.io-index"
337checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
339[[package]]
340name = "unicode-ident"
341version = "1.0.24"
342source = "registry+https://github.com/rust-lang/crates.io-index"
343checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
345[[package]]
346name = "which"
347version = "7.0.3"
348source = "registry+https://github.com/rust-lang/crates.io-index"
349checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762"
350dependencies = [
351 "either",
352 "env_home",
353 "rustix",
354 "winsafe",
355]
357[[package]]
358name = "windows-link"
359version = "0.2.1"
360source = "registry+https://github.com/rust-lang/crates.io-index"
361checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
363[[package]]
364name = "windows-sys"
365version = "0.61.2"
366source = "registry+https://github.com/rust-lang/crates.io-index"
367checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
368dependencies = [
369 "windows-link",
370]
372[[package]]
373name = "winsafe"
374version = "0.0.19"
375source = "registry+https://github.com/rust-lang/crates.io-index"
376checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"

prototypes/p02-lua-interface-descriptor/Cargo.toml

Added
new file mode 100644

+8 / −0 text lines

1[package]
2name = "p02-lua-interface-descriptor"
3version = "0.1.0"
4edition = "2021"
5publish = false
6
7[dependencies]
8mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }

prototypes/p02-lua-interface-descriptor/impl/bad_shape.lua

Added
new file mode 100644

+15 / −0 text lines

1-- Non-conforming implementation: `status` has the wrong shape
2-- (string constant instead of a function).
3return {
4 implements = "community/subagent",
5
6 spawn = function(task, opts)
7 return { id = "y" }
8 end,
9
10 status = "always-running",
12 cancel = function(id)
13 return true
14 end,
15}

prototypes/p02-lua-interface-descriptor/impl/good.lua

Added
new file mode 100644

+34 / −0 text lines

1-- Conforming implementation of community/subagent.
2-- Includes a private extra field that must be hidden by the interface view.
3local agents = {}
4local next_id = 0
5
6return {
7 implements = "community/subagent",
8
9 spawn = function(task, opts)
10 next_id = next_id + 1
11 local id = "agent-" .. next_id
12 agents[id] = { task = task, state = "running", opts = opts }
13 return { id = id }
14 end,
16 status = function(id)
17 local a = agents[id]
18 if a then return a.state end
19 return "unknown"
20 end,
22 cancel = function(id)
23 if agents[id] then
24 agents[id].state = "cancelled"
25 return true
26 end
27 return false
28 end,
30 -- Private helper: must NOT be visible through the interface view.
31 _internal_debug_dump = function()
32 return agents
33 end,
34}

prototypes/p02-lua-interface-descriptor/impl/missing_fn.lua

Added
new file mode 100644

+14 / −0 text lines

1-- Non-conforming implementation: required function `cancel` is absent.
2return {
3 implements = "community/subagent",
4
5 spawn = function(task, opts)
6 return { id = "x" }
7 end,
8
9 status = function(id)
10 return "running"
11 end,
13 -- cancel is missing
14}

prototypes/p02-lua-interface-descriptor/interfaces/subagent.lua

Added
new file mode 100644

+30 / −0 text lines

1-- Interface descriptor: plain Lua data, no host SDK, no I/O.
2-- Claim under test: this shape is expressive enough for community-defined
3-- plugin interfaces with runtime validation (docs/SPEC.md §9.6, candidate 1).
4return {
5 name = "community/subagent",
6 generation = 1,
7
8 -- Required exported functions with typed signatures.
9 -- type names: "string" | "number" | "boolean" | "table" | "function"
10 functions = {
11 spawn = {
12 params = {
13 { name = "task", type = "string" },
14 { name = "opts", type = "table", optional = true },
15 },
16 returns = { { name = "handle", type = "table" } },
17 },
18 status = {
19 params = { { name = "id", type = "string" } },
20 returns = { { name = "state", type = "string" } },
21 },
22 cancel = {
23 params = { { name = "id", type = "string" } },
24 returns = { { name = "ok", type = "boolean" } },
25 },
26 },
28 -- Events the implementation may emit on the bus (docs/SPEC.md §9.18).
29 events = { "community/subagent-done", "community/subagent-failed" },
30}

prototypes/p02-lua-interface-descriptor/src/main.rs

Added
new file mode 100644

+186 / −0 text lines

1//! p02-lua-interface-descriptor
2//!
3//! Proves or disproves: plain Lua descriptors plus runtime validation can
4//! support community-defined plugin interfaces (docs/SPEC.md §9.6, candidate 1).
5//!
6//! Verify: `cargo run` — exits 0 with PASS lines when all expectations hold.
7
8use mlua::{Lua, Table, Value};
9
10const DESCRIPTOR: &str = include_str!("../interfaces/subagent.lua");
11const IMPL_GOOD: &str = include_str!("../impl/good.lua");
12const IMPL_MISSING: &str = include_str!("../impl/missing_fn.lua");
13const IMPL_BAD_SHAPE: &str = include_str!("../impl/bad_shape.lua");
15/// A conformance diagnostic with an exact path into the implementation.
16#[derive(Debug)]
17struct Diagnostic {
18 path: String,
19 expected: String,
20 actual: String,
21}
23impl std::fmt::Display for Diagnostic {
24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25 write!(
26 f,
27 "{}: expected {}, got {}",
28 self.path, self.expected, self.actual
29 )
30 }
31}
33fn type_name(v: &Value) -> String {
34 v.type_name().to_string()
35}
37/// Load a Lua chunk in a fresh, restricted environment (data + functions only,
38/// no io/os/debug access needed by the fixtures).
39fn load_chunk(lua: &Lua, src: &str, name: &str) -> mlua::Result<Table> {
40 lua.load(src).set_name(name).eval()
41}
43/// Validate an implementation table against a descriptor table.
44/// Returns exact-path diagnostics; empty = conformant.
45fn check_conformance(desc: &Table, imp: &Table, impl_name: &str) -> mlua::Result<Vec<Diagnostic>> {
46 let mut diags = Vec::new();
47 let functions: Table = desc.get("functions")?;
48 for pair in functions.pairs::<String, Table>() {
49 let (fn_name, _sig) = pair?;
50 let field: Value = imp.get(fn_name.clone())?;
51 match field {
52 Value::Function(_) => {}
53 Value::Nil => diags.push(Diagnostic {
54 path: format!("{impl_name}.{fn_name}"),
55 expected: "function (required by interface)".into(),
56 actual: "nil (missing)".into(),
57 }),
58 other => diags.push(Diagnostic {
59 path: format!("{impl_name}.{fn_name}"),
60 expected: "function".into(),
61 actual: type_name(&other),
62 }),
63 }
64 }
65 Ok(diags)
66}
68/// Build an interface view: a fresh table exposing ONLY declared functions,
69/// each wrapped with a runtime argument validator from the descriptor.
70fn make_view(lua: &Lua, desc: &Table, imp: &Table) -> mlua::Result<Table> {
71 let view = lua.create_table()?;
72 let functions: Table = desc.get("functions")?;
73 for pair in functions.pairs::<String, Table>() {
74 let (fn_name, sig) = pair?;
75 let params: Table = sig.get("params")?;
76 // Collect (name, type, optional) triples for the validator closure.
77 let mut spec: Vec<(String, String, bool)> = Vec::new();
78 for p in params.sequence_values::<Table>() {
79 let p = p?;
80 spec.push((p.get("name")?, p.get("type")?, p.get("optional").unwrap_or(false)));
81 }
82 let target: mlua::Function = imp.get(fn_name.clone())?;
83 let fname = fn_name.clone();
84 let wrapped = lua.create_function(move |_, args: mlua::MultiValue| {
85 for (i, (pname, ptype, optional)) in spec.iter().enumerate() {
86 let arg = args.get(i).cloned().unwrap_or(Value::Nil);
87 let ok = match (arg.clone(), ptype.as_str()) {
88 (Value::Nil, _) => *optional,
89 (Value::String(_), "string") => true,
90 (Value::Integer(_) | Value::Number(_), "number") => true,
91 (Value::Boolean(_), "boolean") => true,
92 (Value::Table(_), "table") => true,
93 (Value::Function(_), "function") => true,
94 _ => false,
95 };
96 if !ok {
97 return Err(mlua::Error::RuntimeError(format!(
98 "{fname}: param {n} '{pname}': expected {ptype}, got {got}",
99 n = i + 1,
100 got = type_name(&arg),
101 )));
102 }
103 }
104 target.call::<mlua::MultiValue>(args)
105 })?;
106 view.set(fn_name, wrapped)?;
107 }
108 Ok(view)
109}
111fn main() -> Result<(), Box<dyn std::error::Error>> {
112 let lua = Lua::new();
113 let mut pass = true;
114 let mut check = |label: &str, ok: bool| {
115 println!("{} {label}", if ok { "PASS" } else { "FAIL" });
116 pass &= ok;
117 };
119 let desc = load_chunk(&lua, DESCRIPTOR, "interfaces/subagent.lua")?;
120 let iface_name: String = desc.get("name")?;
121 let generation: i64 = desc.get("generation")?;
122 check(
123 &format!("descriptor loads as plain data ({iface_name} gen {generation})"),
124 iface_name == "community/subagent" && generation == 1,
125 );
127 // 1. good implementation passes
128 let good = load_chunk(&lua, IMPL_GOOD, "impl/good.lua")?;
129 let diags = check_conformance(&desc, &good, "impl/good.lua")?;
130 check("good implementation conforms (no diagnostics)", diags.is_empty());
132 // 2. missing function fails with exact path/name
133 let missing = load_chunk(&lua, IMPL_MISSING, "impl/missing_fn.lua")?;
134 let diags = check_conformance(&desc, &missing, "impl/missing_fn.lua")?;
135 let hit = diags
136 .iter()
137 .any(|d| d.path == "impl/missing_fn.lua.cancel" && d.actual.contains("missing"));
138 for d in &diags {
139 println!(" diagnostic: {d}");
140 }
141 check("missing function fails with exact path/name", hit && diags.len() == 1);
143 // 3. bad shape fails with expected/actual diagnostic
144 let bad = load_chunk(&lua, IMPL_BAD_SHAPE, "impl/bad_shape.lua")?;
145 let diags = check_conformance(&desc, &bad, "impl/bad_shape.lua")?;
146 let hit = diags.iter().any(|d| {
147 d.path == "impl/bad_shape.lua.status" && d.expected == "function" && d.actual == "string"
148 });
149 for d in &diags {
150 println!(" diagnostic: {d}");
151 }
152 check("bad shape fails with expected/actual diagnostic", hit && diags.len() == 1);
154 // 4. extra implementation fields are hidden through the interface view
155 let view = make_view(&lua, &desc, &good)?;
156 let hidden: Value = view.get("_internal_debug_dump")?;
157 check("extra implementation fields hidden through view", hidden.is_nil());
159 // 5. runtime argument validation approximates signature matching
160 let spawn: mlua::Function = view.get("spawn")?;
161 let handle: Table = spawn.call(("index the repo",))?;
162 let id: String = handle.get("id")?;
163 check(&format!("valid call passes through view (handle {id})"), id == "agent-1");
165 let err = spawn.call::<Table>((42,)).unwrap_err();
166 let msg = err.to_string();
167 println!(" runtime error: {}", msg.lines().next().unwrap_or(""));
168 check(
169 "wrong arg type rejected at call time with param name",
170 // mlua distinguishes integer/number in diagnostics; both are Lua numbers.
171 msg.contains("spawn: param 1 'task': expected string, got integer"),
172 );
174 // optional param may be omitted or nil
175 let status: mlua::Function = view.get("status")?;
176 let state: String = status.call(("agent-1",))?;
177 check(&format!("status through view works (state {state})"), state == "running");
179 println!();
180 if pass {
181 println!("p02 RESULT: all expectations hold");
182 Ok(())
183 } else {
184 Err("p02 RESULT: expectation failed".into())
185 }
186}

prototypes/p03-subagent-ecosystem-simulation/Cargo.lock

Added
new file mode 100644

+376 / −0 text lines

1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "autocfg"
7version = "1.5.1"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
11[[package]]
12name = "bitflags"
13version = "2.13.0"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
17[[package]]
18name = "bstr"
19version = "1.12.3"
20source = "registry+https://github.com/rust-lang/crates.io-index"
21checksum = "5cee35f73844aa3014bb606320a6c1f010249dbdf43342fe54b5a4f6a8ed4b79"
22dependencies = [
23 "memchr",
24 "serde_core",
25]
27[[package]]
28name = "cc"
29version = "1.2.67"
30source = "registry+https://github.com/rust-lang/crates.io-index"
31checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38"
32dependencies = [
33 "find-msvc-tools",
34 "shlex",
35]
37[[package]]
38name = "cfg-if"
39version = "1.0.4"
40source = "registry+https://github.com/rust-lang/crates.io-index"
41checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
43[[package]]
44name = "either"
45version = "1.16.0"
46source = "registry+https://github.com/rust-lang/crates.io-index"
47checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
49[[package]]
50name = "env_home"
51version = "0.1.0"
52source = "registry+https://github.com/rust-lang/crates.io-index"
53checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
55[[package]]
56name = "erased-serde"
57version = "0.4.10"
58source = "registry+https://github.com/rust-lang/crates.io-index"
59checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
60dependencies = [
61 "serde",
62 "serde_core",
63 "typeid",
64]
66[[package]]
67name = "errno"
68version = "0.3.14"
69source = "registry+https://github.com/rust-lang/crates.io-index"
70checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
71dependencies = [
72 "libc",
73 "windows-sys",
74]
76[[package]]
77name = "find-msvc-tools"
78version = "0.1.9"
79source = "registry+https://github.com/rust-lang/crates.io-index"
80checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
82[[package]]
83name = "libc"
84version = "0.2.186"
85source = "registry+https://github.com/rust-lang/crates.io-index"
86checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
88[[package]]
89name = "linux-raw-sys"
90version = "0.12.1"
91source = "registry+https://github.com/rust-lang/crates.io-index"
92checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
94[[package]]
95name = "lock_api"
96version = "0.4.14"
97source = "registry+https://github.com/rust-lang/crates.io-index"
98checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
99dependencies = [
100 "scopeguard",
101]
103[[package]]
104name = "lua-src"
105version = "547.0.0"
106source = "registry+https://github.com/rust-lang/crates.io-index"
107checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42"
108dependencies = [
109 "cc",
110]
112[[package]]
113name = "luajit-src"
114version = "210.5.12+a4f56a4"
115source = "registry+https://github.com/rust-lang/crates.io-index"
116checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671"
117dependencies = [
118 "cc",
119 "which",
120]
122[[package]]
123name = "memchr"
124version = "2.8.3"
125source = "registry+https://github.com/rust-lang/crates.io-index"
126checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
128[[package]]
129name = "mlua"
130version = "0.10.5"
131source = "registry+https://github.com/rust-lang/crates.io-index"
132checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0"
133dependencies = [
134 "bstr",
135 "either",
136 "erased-serde",
137 "mlua-sys",
138 "num-traits",
139 "parking_lot",
140 "rustc-hash",
141 "rustversion",
142 "serde",
143 "serde-value",
144]
146[[package]]
147name = "mlua-sys"
148version = "0.6.8"
149source = "registry+https://github.com/rust-lang/crates.io-index"
150checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93"
151dependencies = [
152 "cc",
153 "cfg-if",
154 "lua-src",
155 "luajit-src",
156 "pkg-config",
157]
159[[package]]
160name = "num-traits"
161version = "0.2.19"
162source = "registry+https://github.com/rust-lang/crates.io-index"
163checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
164dependencies = [
165 "autocfg",
166]
168[[package]]
169name = "ordered-float"
170version = "2.10.1"
171source = "registry+https://github.com/rust-lang/crates.io-index"
172checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
173dependencies = [
174 "num-traits",
175]
177[[package]]
178name = "p03-subagent-ecosystem-simulation"
179version = "0.1.0"
180dependencies = [
181 "mlua",
182]
184[[package]]
185name = "parking_lot"
186version = "0.12.5"
187source = "registry+https://github.com/rust-lang/crates.io-index"
188checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
189dependencies = [
190 "lock_api",
191 "parking_lot_core",
192]
194[[package]]
195name = "parking_lot_core"
196version = "0.9.12"
197source = "registry+https://github.com/rust-lang/crates.io-index"
198checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
199dependencies = [
200 "cfg-if",
201 "libc",
202 "redox_syscall",
203 "smallvec",
204 "windows-link",
205]
207[[package]]
208name = "pkg-config"
209version = "0.3.33"
210source = "registry+https://github.com/rust-lang/crates.io-index"
211checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
213[[package]]
214name = "proc-macro2"
215version = "1.0.106"
216source = "registry+https://github.com/rust-lang/crates.io-index"
217checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
218dependencies = [
219 "unicode-ident",
220]
222[[package]]
223name = "quote"
224version = "1.0.46"
225source = "registry+https://github.com/rust-lang/crates.io-index"
226checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
227dependencies = [
228 "proc-macro2",
229]
231[[package]]
232name = "redox_syscall"
233version = "0.5.18"
234source = "registry+https://github.com/rust-lang/crates.io-index"
235checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
236dependencies = [
237 "bitflags",
238]
240[[package]]
241name = "rustc-hash"
242version = "2.1.3"
243source = "registry+https://github.com/rust-lang/crates.io-index"
244checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
246[[package]]
247name = "rustix"
248version = "1.1.4"
249source = "registry+https://github.com/rust-lang/crates.io-index"
250checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
251dependencies = [
252 "bitflags",
253 "errno",
254 "libc",
255 "linux-raw-sys",
256 "windows-sys",
257]
259[[package]]
260name = "rustversion"
261version = "1.0.23"
262source = "registry+https://github.com/rust-lang/crates.io-index"
263checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
265[[package]]
266name = "scopeguard"
267version = "1.2.0"
268source = "registry+https://github.com/rust-lang/crates.io-index"
269checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
271[[package]]
272name = "serde"
273version = "1.0.228"
274source = "registry+https://github.com/rust-lang/crates.io-index"
275checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
276dependencies = [
277 "serde_core",
278]
280[[package]]
281name = "serde-value"
282version = "0.7.0"
283source = "registry+https://github.com/rust-lang/crates.io-index"
284checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
285dependencies = [
286 "ordered-float",
287 "serde",
288]
290[[package]]
291name = "serde_core"
292version = "1.0.228"
293source = "registry+https://github.com/rust-lang/crates.io-index"
294checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
295dependencies = [
296 "serde_derive",
297]
299[[package]]
300name = "serde_derive"
301version = "1.0.228"
302source = "registry+https://github.com/rust-lang/crates.io-index"
303checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
304dependencies = [
305 "proc-macro2",
306 "quote",
307 "syn",
308]
310[[package]]
311name = "shlex"
312version = "2.0.1"
313source = "registry+https://github.com/rust-lang/crates.io-index"
314checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
316[[package]]
317name = "smallvec"
318version = "1.15.2"
319source = "registry+https://github.com/rust-lang/crates.io-index"
320checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
322[[package]]
323name = "syn"
324version = "2.0.118"
325source = "registry+https://github.com/rust-lang/crates.io-index"
326checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
327dependencies = [
328 "proc-macro2",
329 "quote",
330 "unicode-ident",
331]
333[[package]]
334name = "typeid"
335version = "1.0.3"
336source = "registry+https://github.com/rust-lang/crates.io-index"
337checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
339[[package]]
340name = "unicode-ident"
341version = "1.0.24"
342source = "registry+https://github.com/rust-lang/crates.io-index"
343checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
345[[package]]
346name = "which"
347version = "7.0.3"
348source = "registry+https://github.com/rust-lang/crates.io-index"
349checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762"
350dependencies = [
351 "either",
352 "env_home",
353 "rustix",
354 "winsafe",
355]
357[[package]]
358name = "windows-link"
359version = "0.2.1"
360source = "registry+https://github.com/rust-lang/crates.io-index"
361checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
363[[package]]
364name = "windows-sys"
365version = "0.61.2"
366source = "registry+https://github.com/rust-lang/crates.io-index"
367checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
368dependencies = [
369 "windows-link",
370]
372[[package]]
373name = "winsafe"
374version = "0.0.19"
375source = "registry+https://github.com/rust-lang/crates.io-index"
376checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"

prototypes/p03-subagent-ecosystem-simulation/Cargo.toml

Added
new file mode 100644

+8 / −0 text lines

1[package]
2name = "p03-subagent-ecosystem-simulation"
3version = "0.1.0"
4edition = "2021"
5publish = false
6
7[dependencies]
8mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }

prototypes/p03-subagent-ecosystem-simulation/configs/alice.lua

Added
new file mode 100644

+7 / −0 text lines

1-- User config: pick which plugin backs each interface (explicit override,
2-- docs/SPEC.md §9.7 step 4). No UI plugin change needed to swap this.
3return {
4 interfaces = {
5 ["community/subagent"] = "alice/subagents",
6 },
7}

prototypes/p03-subagent-ecosystem-simulation/configs/bob-adapted.lua

Added
new file mode 100644

+7 / −0 text lines

1-- User config: back community/subagent with Bob's engine via the adapter.
2-- Only this file differs from configs/alice.lua; every plugin is unchanged.
3return {
4 interfaces = {
5 ["community/subagent"] = "bob/subagent-adapter",
6 },
7}

prototypes/p03-subagent-ecosystem-simulation/configs/bob-direct-fails.lua

Added
new file mode 100644

+8 / −0 text lines

1-- User config (intentionally wrong): bind Bob's incompatible plugin directly
2-- to community/subagent, bypassing the adapter. Resolution must fail with a
3-- clear interface error.
4return {
5 interfaces = {
6 ["community/subagent"] = "bob/agents",
7 },
8}

prototypes/p03-subagent-ecosystem-simulation/plugins/alice-subagents/init.lua

Added
new file mode 100644

+32 / −0 text lines

1-- Alice's implementation: conforms to community/subagent directly.
2-- Carries a private helper that must stay invisible through the interface view.
3local agents = {}
4local next_id = 0
5
6return {
7 spawn = function(task, opts)
8 next_id = next_id + 1
9 local id = "alice-" .. next_id
10 agents[id] = { task = task, state = "running", opts = opts }
11 return { id = id }
12 end,
14 status = function(id)
15 local a = agents[id]
16 if a then return a.state end
17 return "unknown"
18 end,
20 cancel = function(id)
21 if agents[id] then
22 agents[id].state = "cancelled"
23 return true
24 end
25 return false
26 end,
28 -- Private: must NOT leak through the community/subagent view.
29 _alice_internal_dump = function()
30 return agents
31 end,
32}

prototypes/p03-subagent-ecosystem-simulation/plugins/alice-subagents/smith-plugin.lua

Added
new file mode 100644

+10 / −0 text lines

1-- Manifest (docs/SPEC.md §9.2).
2return {
3 name = "alice/subagents",
4 version = "0.3.1",
5 entry = "init.lua",
6
7 dependencies = { "community/subagent-interface" },
8 -- Optional manifest field (§9.2 "implemented interfaces").
9 implements = { "community/subagent" },
10}

prototypes/p03-subagent-ecosystem-simulation/plugins/bob-agents/init.lua

Added
new file mode 100644

+29 / −0 text lines

1-- Bob's own API shape. Deliberately incompatible with community/subagent:
2-- run_agent(spec) -> numeric run key (vs spawn(task, opts) -> handle)
3-- agent_state(key) -> { phase = ... } (vs status(id) -> state string)
4-- stop_agent(key) -> phase string (vs cancel(id) -> boolean)
5local runs = {}
6local n = 0
7
8return {
9 run_agent = function(spec)
10 n = n + 1
11 runs[n] = { spec = spec, phase = "working" }
12 return n
13 end,
15 agent_state = function(key)
16 local r = runs[key]
17 if not r then return { phase = "gone" } end
18 return { phase = r.phase }
19 end,
21 stop_agent = function(key)
22 local r = runs[key]
23 if r then
24 r.phase = "stopped"
25 return "stopped"
26 end
27 return "gone"
28 end,
29}

prototypes/p03-subagent-ecosystem-simulation/plugins/bob-agents/smith-plugin.lua

Added
new file mode 100644

+8 / −0 text lines

1-- Manifest (docs/SPEC.md §9.2).
2-- Bob's plugin predates the community interface: it declares NO
3-- `implements` field and exports its own incompatible API shape.
4return {
5 name = "bob/agents",
6 version = "2.0.0",
7 entry = "init.lua",
8}

prototypes/p03-subagent-ecosystem-simulation/plugins/bob-to-subagent-adapter/init.lua

Added
new file mode 100644

+40 / −0 text lines

1-- Adapter: normalizes bob/agents into the community/subagent interface.
2-- Exports a factory instead of a flat implementation table: the plugin
3-- manager injects the wrapped plugin's export (`adapts` names it) and the
4-- factory returns a community/subagent-shaped table.
5return {
6 adapts = "bob/agents",
7
8 make = function(bob)
9 local keys = {} -- community string id -> bob numeric run key
10 local next_id = 0
12 local function to_state(phase)
13 if phase == "working" then return "running" end
14 if phase == "stopped" then return "cancelled" end
15 return "unknown"
16 end
18 return {
19 spawn = function(task, opts)
20 local key = bob.run_agent({ prompt = task, model = opts and opts.model })
21 next_id = next_id + 1
22 local id = "bob-" .. next_id
23 keys[id] = key
24 return { id = id }
25 end,
27 status = function(id)
28 local key = keys[id]
29 if not key then return "unknown" end
30 return to_state(bob.agent_state(key).phase)
31 end,
33 cancel = function(id)
34 local key = keys[id]
35 if not key then return false end
36 return bob.stop_agent(key) == "stopped"
37 end,
38 }
39 end,
40}

prototypes/p03-subagent-ecosystem-simulation/plugins/bob-to-subagent-adapter/smith-plugin.lua

Added
new file mode 100644

+10 / −0 text lines

1-- Manifest (docs/SPEC.md §9.2).
2-- Adapter plugin: implements community/subagent by wrapping bob/agents.
3return {
4 name = "bob/subagent-adapter",
5 version = "0.1.0",
6 entry = "init.lua",
7
8 dependencies = { "bob/agents", "community/subagent-interface" },
9 implements = { "community/subagent" },
10}

prototypes/p03-subagent-ecosystem-simulation/plugins/community-subagent-interface/interface.lua

Added
new file mode 100644

+28 / −0 text lines

1-- Interface descriptor: plain Lua data (docs/SPEC.md §9.6, candidate 1).
2-- Same shape proven by p02-lua-interface-descriptor.
3return {
4 name = "community/subagent",
5 generation = 1,
6
7 -- Required exported functions with typed signatures.
8 -- type names: "string" | "number" | "boolean" | "table" | "function"
9 functions = {
10 spawn = {
11 params = {
12 { name = "task", type = "string" },
13 { name = "opts", type = "table", optional = true },
14 },
15 returns = { { name = "handle", type = "table" } },
16 },
17 status = {
18 params = { { name = "id", type = "string" } },
19 returns = { { name = "state", type = "string" } },
20 },
21 cancel = {
22 params = { { name = "id", type = "string" } },
23 returns = { { name = "ok", type = "boolean" } },
24 },
25 },
27 events = { "community/subagent-done", "community/subagent-failed" },
28}

prototypes/p03-subagent-ecosystem-simulation/plugins/community-subagent-interface/smith-plugin.lua

Added
new file mode 100644

+10 / −0 text lines

1-- Manifest (docs/SPEC.md §9.2): plain data, restricted environment, no SDK.
2return {
3 name = "community/subagent-interface",
4 version = "1.0.0",
5 entry = "interface.lua",
6
7 -- Optional manifest field (§9.2 "exported interfaces"): this package is an
8 -- interface-only plugin (§9.6). Its entry returns the descriptor as data.
9 interfaces = { "community/subagent" },
10}

prototypes/p03-subagent-ecosystem-simulation/plugins/fancy-subagent-ui/init.lua

Added
new file mode 100644

+21 / −0 text lines

1-- UI plugin: calls ONLY the community/subagent interface view it is handed.
2-- It names no implementation plugin and is byte-identical across scenarios;
3-- the user config alone decides which implementation backs the view.
4return {
5 consumes = "community/subagent",
6
7 run_demo = function(subagent)
8 local log = {}
9 local handle = subagent.spawn("summarize the changelog", { model = "small" })
10 log[#log + 1] = "spawn -> handle " .. handle.id
11 log[#log + 1] = "status(" .. handle.id .. ") -> " .. subagent.status(handle.id)
12 local ok = subagent.cancel(handle.id)
13 log[#log + 1] = "cancel(" .. handle.id .. ") -> " .. tostring(ok)
14 local final = subagent.status(handle.id)
15 log[#log + 1] = "status(" .. handle.id .. ") -> " .. final
16 return {
17 log = log,
18 ok = ok == true and final == "cancelled",
19 }
20 end,
21}

prototypes/p03-subagent-ecosystem-simulation/plugins/fancy-subagent-ui/smith-plugin.lua

Added
new file mode 100644

+11 / −0 text lines

1-- Manifest (docs/SPEC.md §9.2).
2-- Consumer plugin: depends only on the interface package, never on an
3-- implementation. `consumes` is the prototype's name for that declaration.
4return {
5 name = "fancy/subagent-ui",
6 version = "1.2.0",
7 entry = "init.lua",
8
9 dependencies = { "community/subagent-interface" },
10 consumes = { "community/subagent" },
11}

prototypes/p03-subagent-ecosystem-simulation/src/main.rs

Added
new file mode 100644

+411 / −0 text lines

1//! p03-subagent-ecosystem-simulation
2//!
3//! Proves or disproves (docs/SPEC.md §9.6, §9.7, §9.2): interface packages
4//! prevent plugin ecosystem fragmentation — consumers target an interface,
5//! users choose the implementation in config, and adapters normalize
6//! incompatible implementations.
7//!
8//! A tiny plugin manager loads five plugins (interface package, Alice's
9//! conforming implementation, Bob's incompatible implementation, a
10//! Bob-to-interface adapter, and a UI consumer), then resolves the
11//! `community/subagent` interface according to a user config chosen by the
12//! CLI argument.
13//!
14//! Verify:
15//! cargo run -- alice # UI backed by alice/subagents -> exit 0
16//! cargo run -- bob-adapted # UI backed by bob via adapter -> exit 0
17//! cargo run -- bob-direct-fails # direct bob binding must be rejected
18//!
19//! Exit-code choice: `bob-direct-fails` is a scenario whose SUCCESS is the
20//! interface error being raised. The binary exits 0 when the clear diagnostic
21//! is produced as expected (the error text is printed as evidence), and
22//! non-zero only if the misbinding were silently accepted.
24use mlua::{Lua, Table, Value};
26// Plugin sources: (directory, manifest, entry). Embedded so the simulation is
27// hermetic; a real manager would read `data_dir/smith/plugins/<org>/<name>/`.
28const PLUGIN_SOURCES: &[(&str, &str, &str)] = &[
29 (
30 "plugins/community-subagent-interface",
31 include_str!("../plugins/community-subagent-interface/smith-plugin.lua"),
32 include_str!("../plugins/community-subagent-interface/interface.lua"),
33 ),
34 (
35 "plugins/alice-subagents",
36 include_str!("../plugins/alice-subagents/smith-plugin.lua"),
37 include_str!("../plugins/alice-subagents/init.lua"),
38 ),
39 (
40 "plugins/bob-agents",
41 include_str!("../plugins/bob-agents/smith-plugin.lua"),
42 include_str!("../plugins/bob-agents/init.lua"),
43 ),
44 (
45 "plugins/bob-to-subagent-adapter",
46 include_str!("../plugins/bob-to-subagent-adapter/smith-plugin.lua"),
47 include_str!("../plugins/bob-to-subagent-adapter/init.lua"),
48 ),
49 (
50 "plugins/fancy-subagent-ui",
51 include_str!("../plugins/fancy-subagent-ui/smith-plugin.lua"),
52 include_str!("../plugins/fancy-subagent-ui/init.lua"),
53 ),
54];
56const UI_ENTRY_SOURCE: &str = include_str!("../plugins/fancy-subagent-ui/init.lua");
58const CONFIGS: &[(&str, &str, &str)] = &[
59 ("alice", "configs/alice.lua", include_str!("../configs/alice.lua")),
60 (
61 "bob-adapted",
62 "configs/bob-adapted.lua",
63 include_str!("../configs/bob-adapted.lua"),
64 ),
65 (
66 "bob-direct-fails",
67 "configs/bob-direct-fails.lua",
68 include_str!("../configs/bob-direct-fails.lua"),
69 ),
70];
72const INTERFACE: &str = "community/subagent";
74/// A loaded plugin: validated manifest plus the entry file's export table.
75struct Plugin {
76 name: String,
77 version: String,
78 dir: &'static str,
79 manifest: Table,
80 export: Table,
81}
83/// §9.2 name rule: `<org>/<name>`, lowercase ASCII letters, digits, `_`, `-`.
84fn valid_plugin_name(name: &str) -> bool {
85 let mut parts = name.split('/');
86 match (parts.next(), parts.next(), parts.next()) {
87 (Some(org), Some(rest), None) => {
88 let ok = |s: &str| {
89 !s.is_empty()
90 && s.chars()
91 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
92 };
93 ok(org) && ok(rest)
94 }
95 _ => false,
96 }
97}
99fn load_chunk(lua: &Lua, src: &str, name: &str) -> mlua::Result<Table> {
100 lua.load(src).set_name(name).eval()
101}
103/// Manifest-first loading (§9.4 phases 1-3, simplified): validate the
104/// manifest as data, then evaluate the entry chunk for the export table.
105fn load_plugin(lua: &Lua, dir: &'static str, manifest_src: &str, entry_src: &str) -> Result<Plugin, String> {
106 let manifest = load_chunk(lua, manifest_src, &format!("{dir}/smith-plugin.lua"))
107 .map_err(|e| format!("{dir}: manifest error: {e}"))?;
108 let name: String = manifest
109 .get("name")
110 .map_err(|_| format!("{dir}: manifest missing `name`"))?;
111 if !valid_plugin_name(&name) {
112 return Err(format!("{dir}: invalid plugin name {name:?} (want <org>/<name>)"));
113 }
114 let version: String = manifest
115 .get("version")
116 .map_err(|_| format!("{dir}: manifest missing `version`"))?;
117 let entry_name: String = manifest
118 .get("entry")
119 .map_err(|_| format!("{dir}: manifest missing `entry`"))?;
120 let export = load_chunk(lua, entry_src, &format!("{dir}/{entry_name}"))
121 .map_err(|e| format!("{dir}: entry error: {e}"))?;
122 Ok(Plugin { name, version, dir, manifest, export })
123}
125fn find<'a>(plugins: &'a [Plugin], name: &str) -> Option<&'a Plugin> {
126 plugins.iter().find(|p| p.name == name)
127}
129/// True if the manifest's list-valued `field` contains `value`.
130fn manifest_lists(manifest: &Table, field: &str, value: &str) -> bool {
131 if let Ok(list) = manifest.get::<Table>(field) {
132 for v in list.sequence_values::<String>().flatten() {
133 if v == value {
134 return true;
135 }
136 }
137 }
138 false
139}
141/// Conformance diagnostics against the descriptor (p02's check, keyed by
142/// plugin name instead of file path).
143fn check_conformance(desc: &Table, imp: &Table, plugin_name: &str) -> mlua::Result<Vec<String>> {
144 let mut diags = Vec::new();
145 let functions: Table = desc.get("functions")?;
146 for pair in functions.pairs::<String, Table>() {
147 let (fn_name, _sig) = pair?;
148 let field: Value = imp.get(fn_name.clone())?;
149 match field {
150 Value::Function(_) => {}
151 Value::Nil => diags.push(format!(
152 "{plugin_name}.{fn_name}: expected function (required by interface), got nil (missing)"
153 )),
154 other => diags.push(format!(
155 "{plugin_name}.{fn_name}: expected function, got {}",
156 other.type_name()
157 )),
158 }
159 }
160 diags.sort();
161 Ok(diags)
162}
164/// Interface view: exposes ONLY the descriptor's functions, each wrapped with
165/// runtime argument validation (proven in p02). Extra fields stay hidden.
166fn make_view(lua: &Lua, desc: &Table, imp: &Table) -> mlua::Result<Table> {
167 let view = lua.create_table()?;
168 let functions: Table = desc.get("functions")?;
169 for pair in functions.pairs::<String, Table>() {
170 let (fn_name, sig) = pair?;
171 let params: Table = sig.get("params")?;
172 let mut spec: Vec<(String, String, bool)> = Vec::new();
173 for p in params.sequence_values::<Table>() {
174 let p = p?;
175 spec.push((p.get("name")?, p.get("type")?, p.get("optional").unwrap_or(false)));
176 }
177 let target: mlua::Function = imp.get(fn_name.clone())?;
178 let fname = fn_name.clone();
179 let wrapped = lua.create_function(move |_, args: mlua::MultiValue| {
180 for (i, (pname, ptype, optional)) in spec.iter().enumerate() {
181 let arg = args.get(i).cloned().unwrap_or(Value::Nil);
182 let ok = match (&arg, ptype.as_str()) {
183 (Value::Nil, _) => *optional,
184 (Value::String(_), "string") => true,
185 (Value::Integer(_) | Value::Number(_), "number") => true,
186 (Value::Boolean(_), "boolean") => true,
187 (Value::Table(_), "table") => true,
188 (Value::Function(_), "function") => true,
189 _ => false,
190 };
191 if !ok {
192 return Err(mlua::Error::RuntimeError(format!(
193 "{fname}: param {n} '{pname}': expected {ptype}, got {got}",
194 n = i + 1,
195 got = arg.type_name(),
196 )));
197 }
198 }
199 target.call::<mlua::MultiValue>(args)
200 })?;
201 view.set(fn_name, wrapped)?;
202 }
203 Ok(view)
204}
206/// Resolve an interface to a validated view according to the user config.
207///
208/// Binding precedence (§9.7 applied to interfaces): explicit user-config
209/// binding wins; otherwise the LAST loaded plugin declaring
210/// `implements = { iface }` is the default (later registrations override
211/// earlier ones).
212///
213/// If the bound plugin's export carries `adapts = "<org>/<name>"` plus a
214/// `make` factory, the manager injects the wrapped plugin's export and uses
215/// the factory result as the implementation (adapter normalization).
216fn resolve(
217 lua: &Lua,
218 iface: &str,
219 desc: &Table,
220 config: &Table,
221 plugins: &[Plugin],
222) -> Result<(Table, String), String> {
223 let bound: Option<String> = config
224 .get::<Table>("interfaces")
225 .ok()
226 .and_then(|t| t.get::<String>(iface).ok());
227 let (binding, source) = match bound {
228 Some(b) => (b, "user config"),
229 None => {
230 let default = plugins
231 .iter()
232 .rev()
233 .find(|p| manifest_lists(&p.manifest, "implements", iface))
234 .map(|p| p.name.clone())
235 .ok_or_else(|| format!("no plugin implements interface '{iface}'"))?;
236 (default, "load-order default")
237 }
238 };
239 let plugin = find(plugins, &binding)
240 .ok_or_else(|| format!("config binds '{iface}' to unknown plugin '{binding}'"))?;
242 let adapts: Option<String> = plugin.export.get("adapts").ok();
243 let (imp, via) = match adapts {
244 Some(target_name) => {
245 let target = find(plugins, &target_name).ok_or_else(|| {
246 format!("adapter '{}' wraps unknown plugin '{target_name}'", plugin.name)
247 })?;
248 let make: mlua::Function = plugin
249 .export
250 .get("make")
251 .map_err(|_| format!("adapter '{}' has no `make` factory", plugin.name))?;
252 let imp: Table = make
253 .call((target.export.clone(),))
254 .map_err(|e| format!("adapter '{}' factory failed: {e}", plugin.name))?;
255 (imp, format!("{} (adapter over {}) [{source}]", plugin.name, target_name))
256 }
257 None => (plugin.export.clone(), format!("{} [{source}]", plugin.name)),
258 };
260 let diags = check_conformance(desc, &imp, &plugin.name).map_err(|e| e.to_string())?;
261 if !diags.is_empty() {
262 let mut msg = format!(
263 "interface error: plugin '{}' does not conform to interface '{iface}' (generation {})",
264 plugin.name,
265 desc.get::<i64>("generation").unwrap_or(0),
266 );
267 for d in &diags {
268 msg.push_str(&format!("\n {d}"));
269 }
270 let mut provided: Vec<String> = imp
271 .pairs::<String, Value>()
272 .flatten()
273 .map(|(k, v)| format!("{k} ({})", v.type_name()))
274 .collect();
275 provided.sort();
276 msg.push_str(&format!("\n provided exports: {}", provided.join(", ")));
277 if !manifest_lists(&plugin.manifest, "implements", iface) {
278 msg.push_str(&format!(
279 "\n note: manifest of '{}' does not declare implements = {{\"{iface}\"}}",
280 plugin.name
281 ));
282 }
283 if let Some(adapter) = plugins.iter().find(|p| {
284 manifest_lists(&p.manifest, "implements", iface)
285 && p.export.get::<String>("adapts").is_ok_and(|a| a == plugin.name)
286 }) {
287 msg.push_str(&format!(
288 "\n hint: adapter '{}' bridges '{}' to '{iface}'; bind the interface to it instead",
289 adapter.name, plugin.name
290 ));
291 }
292 return Err(msg);
293 }
295 let view = make_view(lua, desc, &imp).map_err(|e| e.to_string())?;
296 Ok((view, via))
297}
299fn usage() -> ! {
300 eprintln!("usage: cargo run -- <alice|bob-adapted|bob-direct-fails>");
301 std::process::exit(2);
302}
304fn main() -> Result<(), Box<dyn std::error::Error>> {
305 let scenario = std::env::args().nth(1).unwrap_or_else(|| usage());
306 let (_, config_path, config_src) = CONFIGS
307 .iter()
308 .find(|(name, _, _)| *name == scenario)
309 .copied()
310 .unwrap_or_else(|| usage());
312 let lua = Lua::new();
313 let mut pass = true;
314 let mut check = |label: &str, ok: bool| {
315 println!("{} {label}", if ok { "PASS" } else { "FAIL" });
316 pass &= ok;
317 };
319 // Load all plugins in registration order (§9.7: later overrides earlier).
320 let mut plugins = Vec::new();
321 for (dir, manifest_src, entry_src) in PLUGIN_SOURCES {
322 let p = load_plugin(&lua, dir, manifest_src, entry_src)?;
323 println!("loaded {: <24} v{: <6} from {}", p.name, p.version, p.dir);
324 plugins.push(p);
325 }
326 check("all five plugin manifests validate (§9.2) and entries load", plugins.len() == 5);
328 // The interface package exports the descriptor as plain data.
329 let iface_pkg = find(&plugins, "community/subagent-interface")
330 .ok_or("interface package not loaded")?;
331 let desc = iface_pkg.export.clone();
332 check(
333 "interface package exports community/subagent descriptor",
334 manifest_lists(&iface_pkg.manifest, "interfaces", INTERFACE)
335 && desc.get::<String>("name")? == INTERFACE,
336 );
338 // The UI consumer never names an implementation: config is the only
339 // per-scenario difference (pass evidence d).
340 check(
341 "UI plugin source references no implementation (only the interface)",
342 !UI_ENTRY_SOURCE.contains("alice") && !UI_ENTRY_SOURCE.contains("bob"),
343 );
345 let config = load_chunk(&lua, config_src, config_path)?;
346 println!("scenario '{scenario}': user config {config_path}");
348 match resolve(&lua, INTERFACE, &desc, &config, &plugins) {
349 Ok((view, via)) => {
350 println!("resolved '{INTERFACE}' -> {via}");
351 check(
352 "misbinding scenario must fail, working scenarios must resolve",
353 scenario != "bob-direct-fails",
354 );
356 // Implementation internals must be invisible through the view.
357 let hidden: Value = view.get("_alice_internal_dump")?;
358 let hidden2: Value = view.get("make")?;
359 check("implementation/adapter internals hidden through view", hidden.is_nil() && hidden2.is_nil());
361 // Hand the validated view to the UI consumer and run it.
362 let ui = find(&plugins, "fancy/subagent-ui").ok_or("ui plugin not loaded")?;
363 let run_demo: mlua::Function = ui.export.get("run_demo")?;
364 let result: Table = run_demo.call((view,))?;
365 let log: Table = result.get("log")?;
366 for line in log.sequence_values::<String>() {
367 println!(" ui: {}", line?);
368 }
369 check("UI drives spawn/status/cancel through the interface", result.get::<bool>("ok")?);
371 // Cross-check the handle namespace proves which backend ran.
372 let first: String = log.get(1)?;
373 let expected_prefix = if scenario == "alice" { "alice-" } else { "bob-" };
374 check(
375 &format!("backend swapped by config alone (handles are {expected_prefix}*)"),
376 first.contains(&format!("handle {expected_prefix}")),
377 );
378 }
379 Err(msg) => {
380 println!("{msg}");
381 check(
382 "misbinding scenario must fail, working scenarios must resolve",
383 scenario == "bob-direct-fails",
384 );
385 check(
386 "error names plugin, interface, and every missing function",
387 msg.contains("bob/agents")
388 && msg.contains(INTERFACE)
389 && msg.contains("bob/agents.spawn")
390 && msg.contains("bob/agents.status")
391 && msg.contains("bob/agents.cancel"),
392 );
393 check(
394 "error shows what the plugin actually provides",
395 msg.contains("run_agent") && msg.contains("agent_state") && msg.contains("stop_agent"),
396 );
397 check(
398 "error hints at the available adapter",
399 msg.contains("hint: adapter 'bob/subagent-adapter'"),
400 );
401 }
402 }
404 println!();
405 if pass {
406 println!("p03 RESULT ({scenario}): all expectations hold");
407 Ok(())
408 } else {
409 Err(format!("p03 RESULT ({scenario}): expectation failed").into())
410 }
411}

prototypes/p04-plugin-install-uninstall/Cargo.lock

Added
new file mode 100644

+376 / −0 text lines

1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "autocfg"
7version = "1.5.1"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
11[[package]]
12name = "bitflags"
13version = "2.13.0"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
17[[package]]
18name = "bstr"
19version = "1.12.3"
20source = "registry+https://github.com/rust-lang/crates.io-index"
21checksum = "5cee35f73844aa3014bb606320a6c1f010249dbdf43342fe54b5a4f6a8ed4b79"
22dependencies = [
23 "memchr",
24 "serde_core",
25]
27[[package]]
28name = "cc"
29version = "1.2.67"
30source = "registry+https://github.com/rust-lang/crates.io-index"
31checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38"
32dependencies = [
33 "find-msvc-tools",
34 "shlex",
35]
37[[package]]
38name = "cfg-if"
39version = "1.0.4"
40source = "registry+https://github.com/rust-lang/crates.io-index"
41checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
43[[package]]
44name = "either"
45version = "1.16.0"
46source = "registry+https://github.com/rust-lang/crates.io-index"
47checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
49[[package]]
50name = "env_home"
51version = "0.1.0"
52source = "registry+https://github.com/rust-lang/crates.io-index"
53checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
55[[package]]
56name = "erased-serde"
57version = "0.4.10"
58source = "registry+https://github.com/rust-lang/crates.io-index"
59checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
60dependencies = [
61 "serde",
62 "serde_core",
63 "typeid",
64]
66[[package]]
67name = "errno"
68version = "0.3.14"
69source = "registry+https://github.com/rust-lang/crates.io-index"
70checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
71dependencies = [
72 "libc",
73 "windows-sys",
74]
76[[package]]
77name = "find-msvc-tools"
78version = "0.1.9"
79source = "registry+https://github.com/rust-lang/crates.io-index"
80checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
82[[package]]
83name = "libc"
84version = "0.2.186"
85source = "registry+https://github.com/rust-lang/crates.io-index"
86checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
88[[package]]
89name = "linux-raw-sys"
90version = "0.12.1"
91source = "registry+https://github.com/rust-lang/crates.io-index"
92checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
94[[package]]
95name = "lock_api"
96version = "0.4.14"
97source = "registry+https://github.com/rust-lang/crates.io-index"
98checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
99dependencies = [
100 "scopeguard",
101]
103[[package]]
104name = "lua-src"
105version = "547.0.0"
106source = "registry+https://github.com/rust-lang/crates.io-index"
107checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42"
108dependencies = [
109 "cc",
110]
112[[package]]
113name = "luajit-src"
114version = "210.5.12+a4f56a4"
115source = "registry+https://github.com/rust-lang/crates.io-index"
116checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671"
117dependencies = [
118 "cc",
119 "which",
120]
122[[package]]
123name = "memchr"
124version = "2.8.3"
125source = "registry+https://github.com/rust-lang/crates.io-index"
126checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
128[[package]]
129name = "mlua"
130version = "0.10.5"
131source = "registry+https://github.com/rust-lang/crates.io-index"
132checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0"
133dependencies = [
134 "bstr",
135 "either",
136 "erased-serde",
137 "mlua-sys",
138 "num-traits",
139 "parking_lot",
140 "rustc-hash",
141 "rustversion",
142 "serde",
143 "serde-value",
144]
146[[package]]
147name = "mlua-sys"
148version = "0.6.8"
149source = "registry+https://github.com/rust-lang/crates.io-index"
150checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93"
151dependencies = [
152 "cc",
153 "cfg-if",
154 "lua-src",
155 "luajit-src",
156 "pkg-config",
157]
159[[package]]
160name = "num-traits"
161version = "0.2.19"
162source = "registry+https://github.com/rust-lang/crates.io-index"
163checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
164dependencies = [
165 "autocfg",
166]
168[[package]]
169name = "ordered-float"
170version = "2.10.1"
171source = "registry+https://github.com/rust-lang/crates.io-index"
172checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
173dependencies = [
174 "num-traits",
175]
177[[package]]
178name = "p04-plugin-install-uninstall"
179version = "0.1.0"
180dependencies = [
181 "mlua",
182]
184[[package]]
185name = "parking_lot"
186version = "0.12.5"
187source = "registry+https://github.com/rust-lang/crates.io-index"
188checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
189dependencies = [
190 "lock_api",
191 "parking_lot_core",
192]
194[[package]]
195name = "parking_lot_core"
196version = "0.9.12"
197source = "registry+https://github.com/rust-lang/crates.io-index"
198checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
199dependencies = [
200 "cfg-if",
201 "libc",
202 "redox_syscall",
203 "smallvec",
204 "windows-link",
205]
207[[package]]
208name = "pkg-config"
209version = "0.3.33"
210source = "registry+https://github.com/rust-lang/crates.io-index"
211checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
213[[package]]
214name = "proc-macro2"
215version = "1.0.106"
216source = "registry+https://github.com/rust-lang/crates.io-index"
217checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
218dependencies = [
219 "unicode-ident",
220]
222[[package]]
223name = "quote"
224version = "1.0.46"
225source = "registry+https://github.com/rust-lang/crates.io-index"
226checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
227dependencies = [
228 "proc-macro2",
229]
231[[package]]
232name = "redox_syscall"
233version = "0.5.18"
234source = "registry+https://github.com/rust-lang/crates.io-index"
235checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
236dependencies = [
237 "bitflags",
238]
240[[package]]
241name = "rustc-hash"
242version = "2.1.3"
243source = "registry+https://github.com/rust-lang/crates.io-index"
244checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
246[[package]]
247name = "rustix"
248version = "1.1.4"
249source = "registry+https://github.com/rust-lang/crates.io-index"
250checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
251dependencies = [
252 "bitflags",
253 "errno",
254 "libc",
255 "linux-raw-sys",
256 "windows-sys",
257]
259[[package]]
260name = "rustversion"
261version = "1.0.23"
262source = "registry+https://github.com/rust-lang/crates.io-index"
263checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
265[[package]]
266name = "scopeguard"
267version = "1.2.0"
268source = "registry+https://github.com/rust-lang/crates.io-index"
269checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
271[[package]]
272name = "serde"
273version = "1.0.228"
274source = "registry+https://github.com/rust-lang/crates.io-index"
275checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
276dependencies = [
277 "serde_core",
278]
280[[package]]
281name = "serde-value"
282version = "0.7.0"
283source = "registry+https://github.com/rust-lang/crates.io-index"
284checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
285dependencies = [
286 "ordered-float",
287 "serde",
288]
290[[package]]
291name = "serde_core"
292version = "1.0.228"
293source = "registry+https://github.com/rust-lang/crates.io-index"
294checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
295dependencies = [
296 "serde_derive",
297]
299[[package]]
300name = "serde_derive"
301version = "1.0.228"
302source = "registry+https://github.com/rust-lang/crates.io-index"
303checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
304dependencies = [
305 "proc-macro2",
306 "quote",
307 "syn",
308]
310[[package]]
311name = "shlex"
312version = "2.0.1"
313source = "registry+https://github.com/rust-lang/crates.io-index"
314checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
316[[package]]
317name = "smallvec"
318version = "1.15.2"
319source = "registry+https://github.com/rust-lang/crates.io-index"
320checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
322[[package]]
323name = "syn"
324version = "2.0.118"
325source = "registry+https://github.com/rust-lang/crates.io-index"
326checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
327dependencies = [
328 "proc-macro2",
329 "quote",
330 "unicode-ident",
331]
333[[package]]
334name = "typeid"
335version = "1.0.3"
336source = "registry+https://github.com/rust-lang/crates.io-index"
337checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
339[[package]]
340name = "unicode-ident"
341version = "1.0.24"
342source = "registry+https://github.com/rust-lang/crates.io-index"
343checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
345[[package]]
346name = "which"
347version = "7.0.3"
348source = "registry+https://github.com/rust-lang/crates.io-index"
349checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762"
350dependencies = [
351 "either",
352 "env_home",
353 "rustix",
354 "winsafe",
355]
357[[package]]
358name = "windows-link"
359version = "0.2.1"
360source = "registry+https://github.com/rust-lang/crates.io-index"
361checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
363[[package]]
364name = "windows-sys"
365version = "0.61.2"
366source = "registry+https://github.com/rust-lang/crates.io-index"
367checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
368dependencies = [
369 "windows-link",
370]
372[[package]]
373name = "winsafe"
374version = "0.0.19"
375source = "registry+https://github.com/rust-lang/crates.io-index"
376checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"

prototypes/p04-plugin-install-uninstall/Cargo.toml

Added
new file mode 100644

+8 / −0 text lines

1[package]
2name = "p04-plugin-install-uninstall"
3version = "0.1.0"
4edition = "2021"
5publish = false
6
7[dependencies]
8mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }

prototypes/p04-plugin-install-uninstall/fixtures/bad-name/smith-plugin.lua

Added
new file mode 100644

+6 / −0 text lines

1-- Invalid name: uppercase and '.' are outside [a-z0-9_-] (SPEC §9.2).
2return {
3 name = "Acme/Bad.Plugin",
4 version = "0.1.0",
5 entry = "init.lua",
6}

prototypes/p04-plugin-install-uninstall/fixtures/evil-os/smith-plugin.lua

Added
new file mode 100644

+8 / −0 text lines

1-- Malicious manifest: tries host I/O via os.getenv. Must FAIL under the
2-- restricted manifest environment (SPEC §9.2: no Smith SDK, no host I/O).
3return {
4 name = "acme/evil-os",
5 version = "0.1.0",
6 entry = "init.lua",
7 leaked_home = os.getenv("HOME"),
8}

prototypes/p04-plugin-install-uninstall/fixtures/evil-require/smith-plugin.lua

Added
new file mode 100644

+8 / −0 text lines

1-- Malicious manifest: tries to load modules via require. Must FAIL under the
2-- restricted manifest environment (SPEC §9.2: no Smith SDK, no host I/O).
3local socket = require("socket")
4return {
5 name = "acme/evil-require",
6 version = "0.1.0",
7 entry = "init.lua",
8}

prototypes/p04-plugin-install-uninstall/fixtures/good-plugin/init.lua

Added
new file mode 100644

+15 / −0 text lines

1-- Plugin ENTRY file. SPEC §9.5: install must NOT run entry code.
2-- SIDE EFFECT: if any installer ever executes this chunk, it writes a marker
3-- file that the test asserts does NOT exist after install.
4local marker = os.getenv("P04_SIDE_EFFECT_FILE")
5if marker then
6 local f = assert(io.open(marker, "w"))
7 f:write("ENTRY CODE EXECUTED DURING INSTALL\n")
8 f:close()
9end
11return {
12 setup = function()
13 return "good-plugin ready"
14 end,
15}

prototypes/p04-plugin-install-uninstall/fixtures/good-plugin/smith-plugin.lua

Added
new file mode 100644

+8 / −0 text lines

1-- Valid plugin manifest (SPEC §9.2). Pure data table, no smith_api (defaults to 1).
2return {
3 name = "acme/good-plugin",
4 version = "0.1.0",
5 entry = "init.lua",
6 description = "p04 fixture plugin",
7 license = "MIT",
8}

prototypes/p04-plugin-install-uninstall/fixtures/reserved-smith/smith-plugin.lua

Added
new file mode 100644

+6 / −0 text lines

1-- Reserved namespace: smith/* is for built-in plugins only (SPEC §9.2).
2return {
3 name = "smith/evil",
4 version = "0.1.0",
5 entry = "init.lua",
6}

prototypes/p04-plugin-install-uninstall/src/main.rs

Added
new file mode 100644

+646 / −0 text lines

1//! p04-plugin-install-uninstall
2//!
3//! Proves or disproves docs/SPEC.md §9.2/§9.3/§9.5 install semantics:
4//! - v1 install sources: local path and git URL only,
5//! - names are `<org>/<name>`, `smith/*` reserved,
6//! - manifests are mandatory Lua data files evaluated in a RESTRICTED
7//! environment (no io/os/require) and must return a pure data table,
8//! - `smith_api` optional, defaults to generation 1,
9//! - install never executes plugin entry code,
10//! - duplicates refused without `--force`,
11//! - uninstall keeps `data_dir/smith/data/<org>/<name>/` unless `--purge-data`,
12//! and never removes project plugins.
13//!
14//! Git URL install is simulated with a local bare repo + shell-out to
15//! /usr/bin/git. The real gix-vs-shell-out boundary decision (SPEC §9.5)
16//! is intentionally NOT settled here.
17//!
18//! Verify (each exits 0, printing checked filesystem assertions):
19//! cargo run -- install-local
20//! cargo run -- install-git
21//! cargo run -- reject-bad-name
22//! cargo run -- reject-smith-namespace
23//! cargo run -- uninstall-keeps-data
24//! cargo run -- uninstall-purge-data
26use mlua::{Lua, Value};
27use std::fs;
28use std::path::{Path, PathBuf};
29use std::process::Command;
31const MANIFEST_FILE: &str = "smith-plugin.lua";
32const SUPPORTED_API_GENERATION: i64 = 1;
34// ---------------------------------------------------------------------------
35// Manifest: restricted-environment loading + validation (SPEC §9.2, §9.3)
36// ---------------------------------------------------------------------------
38#[derive(Debug)]
39struct Manifest {
40 name: String,
41 org: String,
42 plugin: String,
43 version: String,
44 entry: String,
45 smith_api: i64,
46}
48/// Evaluate a manifest chunk with an EMPTY environment table so the chunk
49/// cannot reach `io`, `os`, `require`, or any other global (SPEC §9.2:
50/// "restricted manifest environment with no Smith SDK and no host I/O").
51fn eval_manifest_restricted(lua: &Lua, src: &str, chunk_name: &str) -> Result<mlua::Table, String> {
52 let env = lua
53 .create_table()
54 .map_err(|e| format!("create env: {e}"))?;
55 let value: Value = lua
56 .load(src)
57 .set_name(chunk_name)
58 .set_environment(env)
59 .eval()
60 .map_err(|e| format!("manifest evaluation failed: {e}"))?;
61 match value {
62 Value::Table(t) => Ok(t),
63 other => Err(format!(
64 "manifest must return a table, got {}",
65 other.type_name()
66 )),
67 }
68}
70/// Reject non-data values so the manifest is a pure data table.
71fn assert_pure_data(value: &Value, path: &str) -> Result<(), String> {
72 match value {
73 Value::Nil | Value::Boolean(_) | Value::Integer(_) | Value::Number(_) | Value::String(_) => Ok(()),
74 Value::Table(t) => {
75 for pair in t.clone().pairs::<Value, Value>() {
76 let (k, v) = pair.map_err(|e| format!("{path}: {e}"))?;
77 let key = match &k {
78 Value::String(s) => s.to_string_lossy().to_string(),
79 other => format!("[{}]", other.type_name()),
80 };
81 assert_pure_data(&v, &format!("{path}.{key}"))?;
82 }
83 Ok(())
84 }
85 other => Err(format!(
86 "{path}: manifest must be pure data, found {}",
87 other.type_name()
88 )),
89 }
90}
92fn valid_name_part(part: &str) -> bool {
93 !part.is_empty()
94 && part
95 .chars()
96 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
97}
99fn load_manifest(lua: &Lua, plugin_dir: &Path) -> Result<Manifest, String> {
100 let path = plugin_dir.join(MANIFEST_FILE);
101 let src = fs::read_to_string(&path)
102 .map_err(|e| format!("missing mandatory manifest {}: {e}", path.display()))?;
103 let table = eval_manifest_restricted(lua, &src, &path.display().to_string())?;
104 assert_pure_data(&Value::Table(table.clone()), "manifest")?;
106 let name: String = table
107 .get::<Option<String>>("name")
108 .map_err(|e| format!("manifest.name: {e}"))?
109 .ok_or("manifest.name is required")?;
110 let version: String = table
111 .get::<Option<String>>("version")
112 .map_err(|e| format!("manifest.version: {e}"))?
113 .ok_or("manifest.version is required")?;
114 let entry: String = table
115 .get::<Option<String>>("entry")
116 .map_err(|e| format!("manifest.entry: {e}"))?
117 .ok_or("manifest.entry is required")?;
118 // SPEC §9.3: smith_api optional, defaults to generation 1.
119 let smith_api: i64 = table
120 .get::<Option<i64>>("smith_api")
121 .map_err(|e| format!("manifest.smith_api: {e}"))?
122 .unwrap_or(1);
124 let (org, plugin) = name
125 .split_once('/')
126 .ok_or_else(|| format!("plugin name '{name}' must be <org>/<name>"))?;
127 if !valid_name_part(org) || !valid_name_part(plugin) {
128 return Err(format!(
129 "plugin name '{name}' invalid: org/name must match [a-z0-9_-]+"
130 ));
131 }
132 Ok(Manifest {
133 name: name.clone(),
134 org: org.to_string(),
135 plugin: plugin.to_string(),
136 version,
137 entry,
138 smith_api,
139 })
140}
142// ---------------------------------------------------------------------------
143// Install / uninstall (SPEC §9.5)
144// ---------------------------------------------------------------------------
146enum Source {
147 LocalPath(PathBuf),
148 GitUrl(String),
149}
151struct Ctx {
152 data_dir: PathBuf,
153 project_dir: PathBuf,
154}
156impl Ctx {
157 fn plugins_root(&self) -> PathBuf {
158 self.data_dir.join("smith").join("plugins")
159 }
160 fn data_root(&self) -> PathBuf {
161 self.data_dir.join("smith").join("data")
162 }
163 fn installed_dir(&self, m: &Manifest) -> PathBuf {
164 self.plugins_root().join(&m.org).join(&m.plugin)
165 }
166 fn plugin_data_dir(&self, org: &str, name: &str) -> PathBuf {
167 self.data_root().join(org).join(name)
168 }
169 fn project_plugin_dir(&self, org: &str, name: &str) -> PathBuf {
170 self.project_dir
171 .join(".smith")
172 .join("plugins")
173 .join(org)
174 .join(name)
175 }
176}
178fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), String> {
179 fs::create_dir_all(dst).map_err(|e| format!("mkdir {}: {e}", dst.display()))?;
180 for entry in fs::read_dir(src).map_err(|e| format!("read {}: {e}", src.display()))? {
181 let entry = entry.map_err(|e| e.to_string())?;
182 let name = entry.file_name();
183 if name == ".git" {
184 continue; // install layout holds plugin files, not VCS metadata
185 }
186 let from = entry.path();
187 let to = dst.join(&name);
188 if from.is_dir() {
189 copy_dir_recursive(&from, &to)?;
190 } else {
191 fs::copy(&from, &to).map_err(|e| format!("copy {}: {e}", from.display()))?;
192 }
193 }
194 Ok(())
195}
197/// `smith install <path-or-git-url>` per SPEC §9.5. Resolves the source,
198/// validates the manifest in a restricted env, validates namespace + API
199/// generation, copies/clones into data_dir/smith/plugins/<org>/<name>/,
200/// refuses duplicates unless `force`, and never runs plugin entry code.
201fn install(lua: &Lua, ctx: &Ctx, source: Source, force: bool) -> Result<Manifest, String> {
202 // 1. resolve the source into a local staging directory
203 let staging_guard; // keeps clone tempdir alive until copy completes
204 let staged: PathBuf = match source {
205 Source::LocalPath(p) => {
206 if !p.is_dir() {
207 return Err(format!("local source {} is not a directory", p.display()));
208 }
209 p
210 }
211 Source::GitUrl(url) => {
212 // Simulated git implementation boundary: shell out to git(1).
213 // A production Smith would hide gix-or-shell-out behind this
214 // same boundary (SPEC §9.5); the decision is not settled here.
215 let staging = TempDir::new("git-staging")?;
216 let status = Command::new("/usr/bin/git")
217 .args(["clone", "--quiet", "--depth", "1", &url])
218 .arg(&staging.path)
219 .status()
220 .map_err(|e| format!("spawn git: {e}"))?;
221 if !status.success() {
222 return Err(format!("git clone of {url} failed: {status}"));
223 }
224 let p = staging.path.clone();
225 staging_guard = staging;
226 let _ = &staging_guard;
227 p
228 }
229 };
231 // 2. read + validate the manifest (restricted env, pure data, name rules)
232 let manifest = load_manifest(lua, &staged)?;
234 // 3. namespace + API compatibility (SPEC §9.2, §9.3)
235 if manifest.org == "smith" {
236 return Err(format!(
237 "namespace 'smith/*' is reserved for built-in plugins; refusing '{}'",
238 manifest.name
239 ));
240 }
241 if manifest.smith_api > SUPPORTED_API_GENERATION {
242 return Err(format!(
243 "plugin '{}' requires smith_api generation {} but this Smith supports {}",
244 manifest.name, manifest.smith_api, SUPPORTED_API_GENERATION
245 ));
246 }
247 if !staged.join(&manifest.entry).is_file() {
248 return Err(format!(
249 "manifest entry '{}' does not exist in source",
250 manifest.entry
251 ));
252 }
254 // 4. duplicate handling: refuse unless --force (SPEC §9.5)
255 let dest = ctx.installed_dir(&manifest);
256 if dest.exists() {
257 if !force {
258 return Err(format!(
259 "plugin '{}' already installed at {}; use --force to overwrite",
260 manifest.name,
261 dest.display()
262 ));
263 }
264 fs::remove_dir_all(&dest).map_err(|e| format!("remove old install: {e}"))?;
265 }
267 // 5. copy into place. NOTE: no Lua execution of entry code anywhere here.
268 copy_dir_recursive(&staged, &dest)?;
269 Ok(manifest)
270}
272/// `smith uninstall <org>/<name>` per SPEC §9.5. Removes installed plugin
273/// code, keeps plugin data unless `purge_data`, never touches project plugins
274/// (it only ever operates under the GLOBAL plugins/data roots).
275fn uninstall(ctx: &Ctx, name: &str, purge_data: bool) -> Result<(), String> {
276 let (org, plugin) = name
277 .split_once('/')
278 .ok_or_else(|| format!("'{name}' must be <org>/<name>"))?;
279 if org == "smith" {
280 return Err("cannot uninstall built-in smith/* plugins".to_string());
281 }
282 let code_dir = ctx.plugins_root().join(org).join(plugin);
283 if !code_dir.exists() {
284 return Err(format!("plugin '{name}' is not installed globally"));
285 }
286 fs::remove_dir_all(&code_dir).map_err(|e| format!("remove {}: {e}", code_dir.display()))?;
287 if purge_data {
288 let data_dir = ctx.plugin_data_dir(org, plugin);
289 if data_dir.exists() {
290 fs::remove_dir_all(&data_dir)
291 .map_err(|e| format!("purge {}: {e}", data_dir.display()))?;
292 }
293 }
294 Ok(())
295}
297// ---------------------------------------------------------------------------
298// Scenario harness
299// ---------------------------------------------------------------------------
301/// Unique temp dir under std::env::temp_dir(), removed on drop.
302struct TempDir {
303 path: PathBuf,
304}
306impl TempDir {
307 fn new(label: &str) -> Result<Self, String> {
308 use std::sync::atomic::{AtomicU64, Ordering};
309 static COUNTER: AtomicU64 = AtomicU64::new(0);
310 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
311 let path = std::env::temp_dir().join(format!(
312 "p04-{label}-{}-{n}",
313 std::process::id()
314 ));
315 fs::create_dir_all(&path).map_err(|e| format!("mkdir {}: {e}", path.display()))?;
316 Ok(Self { path })
317 }
318}
320impl Drop for TempDir {
321 fn drop(&mut self) {
322 let _ = fs::remove_dir_all(&self.path);
323 }
324}
326struct Checker {
327 pass: bool,
328}
330impl Checker {
331 fn new() -> Self {
332 Self { pass: true }
333 }
334 fn check(&mut self, label: &str, ok: bool) {
335 println!("{} {label}", if ok { "PASS" } else { "FAIL" });
336 self.pass &= ok;
337 }
338 fn check_fs(&mut self, label: &str, path: &Path, should_exist: bool) {
339 let exists = path.exists();
340 println!(
341 "{} {label}: {} {}",
342 if exists == should_exist { "PASS" } else { "FAIL" },
343 path.display(),
344 if exists { "exists" } else { "absent" },
345 );
346 self.pass &= exists == should_exist;
347 }
348}
350fn fixtures() -> PathBuf {
351 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures")
352}
354fn make_ctx(label: &str) -> Result<(TempDir, Ctx), String> {
355 let tmp = TempDir::new(label)?;
356 let ctx = Ctx {
357 data_dir: tmp.path.join("data_dir"),
358 project_dir: tmp.path.join("project"),
359 };
360 fs::create_dir_all(&ctx.data_dir).map_err(|e| e.to_string())?;
361 fs::create_dir_all(&ctx.project_dir).map_err(|e| e.to_string())?;
362 Ok((tmp, ctx))
363}
365/// Set a side-effect marker path in the environment. If install ever executes
366/// the fixture's entry code, init.lua writes this file.
367fn arm_side_effect(tmp: &TempDir) -> PathBuf {
368 let marker = tmp.path.join("side-effect-marker");
369 std::env::set_var("P04_SIDE_EFFECT_FILE", &marker);
370 marker
371}
373// ---------------------------------------------------------------------------
374// Scenarios
375// ---------------------------------------------------------------------------
377fn scenario_install_local(lua: &Lua, c: &mut Checker) -> Result<(), String> {
378 let (tmp, ctx) = make_ctx("install-local")?;
379 let marker = arm_side_effect(&tmp);
381 // fresh install from a local directory path
382 let m = install(lua, &ctx, Source::LocalPath(fixtures().join("good-plugin")), false)?;
383 c.check(
384 &format!("manifest parsed in restricted env: name={} version={}", m.name, m.version),
385 m.name == "acme/good-plugin" && m.version == "0.1.0" && m.entry == "init.lua",
386 );
387 c.check(
388 &format!("smith_api absent defaults to generation {}", m.smith_api),
389 m.smith_api == 1,
390 );
391 let dest = ctx.installed_dir(&m);
392 c.check_fs("installed under data_dir/smith/plugins/<org>/<name>", &dest, true);
393 c.check_fs("manifest copied", &dest.join(MANIFEST_FILE), true);
394 c.check_fs("entry file copied", &dest.join("init.lua"), true);
395 c.check_fs("entry code NOT executed during install (no side-effect marker)", &marker, false);
397 // duplicate refused without --force
398 let dup = install(lua, &ctx, Source::LocalPath(fixtures().join("good-plugin")), false);
399 match &dup {
400 Err(e) => println!(" refusal: {e}"),
401 Ok(_) => {}
402 }
403 c.check(
404 "duplicate install refused without --force",
405 matches!(&dup, Err(e) if e.contains("already installed")),
406 );
408 // duplicate accepted with --force
409 let forced = install(lua, &ctx, Source::LocalPath(fixtures().join("good-plugin")), true);
410 c.check("duplicate install succeeds with --force", forced.is_ok());
411 c.check_fs("plugin still present after --force reinstall", &dest.join(MANIFEST_FILE), true);
413 // restricted manifest environment: os.getenv and require must fail
414 let evil_os = load_manifest(lua, &fixtures().join("evil-os"));
415 if let Err(e) = &evil_os {
416 println!(" evil-os error: {}", e.lines().next().unwrap_or(""));
417 }
418 c.check(
419 "manifest using os.getenv fails in restricted env",
420 matches!(&evil_os, Err(e) if e.contains("manifest evaluation failed")),
421 );
422 let evil_req = load_manifest(lua, &fixtures().join("evil-require"));
423 if let Err(e) = &evil_req {
424 println!(" evil-require error: {}", e.lines().next().unwrap_or(""));
425 }
426 c.check(
427 "manifest using require fails in restricted env",
428 matches!(&evil_req, Err(e) if e.contains("manifest evaluation failed")),
429 );
431 // manifest must be a pure data table: functions are rejected
432 let fn_dir = tmp.path.join("fn-manifest");
433 fs::create_dir_all(&fn_dir).map_err(|e| e.to_string())?;
434 fs::write(
435 fn_dir.join(MANIFEST_FILE),
436 "return { name = \"acme/fn\", version = \"0.1.0\", entry = \"init.lua\", hook = function() end }",
437 )
438 .map_err(|e| e.to_string())?;
439 let fn_manifest = load_manifest(lua, &fn_dir);
440 if let Err(e) = &fn_manifest {
441 println!(" fn-manifest error: {e}");
442 }
443 c.check(
444 "manifest containing a function rejected (pure data only)",
445 matches!(&fn_manifest, Err(e) if e.contains("pure data")),
446 );
448 // API generation newer than supported does not install (SPEC §9.3)
449 let api_dir = tmp.path.join("api2");
450 fs::create_dir_all(&api_dir).map_err(|e| e.to_string())?;
451 fs::write(
452 api_dir.join(MANIFEST_FILE),
453 "return { name = \"acme/future\", version = \"0.1.0\", entry = \"init.lua\", smith_api = 2 }",
454 )
455 .map_err(|e| e.to_string())?;
456 fs::write(api_dir.join("init.lua"), "return {}").map_err(|e| e.to_string())?;
457 let api2 = install(lua, &ctx, Source::LocalPath(api_dir), false);
458 if let Err(e) = &api2 {
459 println!(" refusal: {e}");
460 }
461 c.check(
462 "smith_api=2 refused (supported generation is 1)",
463 matches!(&api2, Err(e) if e.contains("generation 2")),
464 );
465 c.check_fs(
466 "future-api plugin not written to plugins dir",
467 &ctx.plugins_root().join("acme").join("future"),
468 false,
469 );
470 Ok(())
471}
473fn scenario_install_git(lua: &Lua, c: &mut Checker) -> Result<(), String> {
474 let (tmp, ctx) = make_ctx("install-git")?;
475 let marker = arm_side_effect(&tmp);
477 // Build a local bare repo containing the good plugin, then install from
478 // its file:// URL. Git operations shell out to /usr/bin/git; the real
479 // gix-vs-shell-out boundary decision (SPEC §9.5) still stands.
480 let work = tmp.path.join("git-work");
481 copy_dir_recursive(&fixtures().join("good-plugin"), &work)?;
482 let run = |args: &[&str], cwd: &Path| -> Result<(), String> {
483 let status = Command::new("/usr/bin/git")
484 .args(args)
485 .current_dir(cwd)
486 .env("GIT_AUTHOR_NAME", "p04")
487 .env("GIT_AUTHOR_EMAIL", "p04@example.invalid")
488 .env("GIT_COMMITTER_NAME", "p04")
489 .env("GIT_COMMITTER_EMAIL", "p04@example.invalid")
490 .status()
491 .map_err(|e| format!("spawn git: {e}"))?;
492 if status.success() {
493 Ok(())
494 } else {
495 Err(format!("git {args:?} failed: {status}"))
496 }
497 };
498 run(&["init", "--quiet"], &work)?;
499 run(&["add", "-A"], &work)?;
500 run(&["commit", "--quiet", "-m", "plugin v0.1.0"], &work)?;
501 let bare = tmp.path.join("good-plugin.git");
502 run(
503 &["clone", "--quiet", "--bare", work.to_str().unwrap(), bare.to_str().unwrap()],
504 &tmp.path,
505 )?;
506 let url = format!("file://{}", bare.display());
507 println!(" simulated git URL: {url}");
509 let m = install(lua, &ctx, Source::GitUrl(url), false)?;
510 c.check(
511 &format!("git-URL install resolved manifest: {} {}", m.name, m.version),
512 m.name == "acme/good-plugin",
513 );
514 let dest = ctx.installed_dir(&m);
515 c.check_fs("cloned into data_dir/smith/plugins/<org>/<name>", &dest, true);
516 c.check_fs("manifest present after git install", &dest.join(MANIFEST_FILE), true);
517 c.check_fs("entry file present after git install", &dest.join("init.lua"), true);
518 c.check_fs("no .git metadata in installed plugin", &dest.join(".git"), false);
519 c.check_fs("entry code NOT executed during git install", &marker, false);
520 println!(" note: git implemented via shell-out to /usr/bin/git in this prototype;");
521 println!(" note: gix-vs-shell-out remains an open boundary decision per SPEC §9.5.");
522 Ok(())
523}
525fn scenario_reject_bad_name(lua: &Lua, c: &mut Checker) -> Result<(), String> {
526 let (_tmp, ctx) = make_ctx("reject-bad-name")?;
527 let res = install(lua, &ctx, Source::LocalPath(fixtures().join("bad-name")), false);
528 if let Err(e) = &res {
529 println!(" refusal: {e}");
530 }
531 c.check(
532 "install refused: 'Acme/Bad.Plugin' violates [a-z0-9_-] name rule",
533 matches!(&res, Err(e) if e.contains("invalid")),
534 );
535 c.check_fs(
536 "plugins root untouched after rejection",
537 &ctx.plugins_root(),
538 false,
539 );
540 Ok(())
541}
543fn scenario_reject_smith_namespace(lua: &Lua, c: &mut Checker) -> Result<(), String> {
544 let (_tmp, ctx) = make_ctx("reject-smith-namespace")?;
545 let res = install(lua, &ctx, Source::LocalPath(fixtures().join("reserved-smith")), false);
546 if let Err(e) = &res {
547 println!(" refusal: {e}");
548 }
549 c.check(
550 "install refused: 'smith/evil' uses reserved smith/* namespace",
551 matches!(&res, Err(e) if e.contains("reserved")),
552 );
553 c.check_fs(
554 "no smith/ directory created under plugins root",
555 &ctx.plugins_root().join("smith"),
556 false,
557 );
558 Ok(())
559}
561fn scenario_uninstall_keeps_data(lua: &Lua, c: &mut Checker) -> Result<(), String> {
562 let (_tmp, ctx) = make_ctx("uninstall-keeps-data")?;
563 let m = install(lua, &ctx, Source::LocalPath(fixtures().join("good-plugin")), false)?;
564 let code_dir = ctx.installed_dir(&m);
566 // plugin wrote data during use
567 let data_dir = ctx.plugin_data_dir("acme", "good-plugin");
568 fs::create_dir_all(&data_dir).map_err(|e| e.to_string())?;
569 fs::write(data_dir.join("state.txt"), "precious user data\n").map_err(|e| e.to_string())?;
571 // a same-named PROJECT plugin exists and must survive
572 let project_plugin = ctx.project_plugin_dir("acme", "good-plugin");
573 fs::create_dir_all(&project_plugin).map_err(|e| e.to_string())?;
574 fs::write(project_plugin.join(MANIFEST_FILE), "return { name = \"acme/good-plugin\", version = \"0.2.0\", entry = \"init.lua\" }")
575 .map_err(|e| e.to_string())?;
577 uninstall(&ctx, "acme/good-plugin", false)?;
578 c.check_fs("plugin code removed", &code_dir, false);
579 c.check_fs("plugin data KEPT by default", &data_dir.join("state.txt"), true);
580 c.check_fs(
581 "project plugin never removed by uninstall",
582 &project_plugin.join(MANIFEST_FILE),
583 true,
584 );
586 // uninstalling again fails cleanly
587 let again = uninstall(&ctx, "acme/good-plugin", false);
588 if let Err(e) = &again {
589 println!(" refusal: {e}");
590 }
591 c.check(
592 "second uninstall reports not installed",
593 matches!(&again, Err(e) if e.contains("not installed")),
594 );
595 Ok(())
596}
598fn scenario_uninstall_purge_data(lua: &Lua, c: &mut Checker) -> Result<(), String> {
599 let (_tmp, ctx) = make_ctx("uninstall-purge-data")?;
600 let m = install(lua, &ctx, Source::LocalPath(fixtures().join("good-plugin")), false)?;
601 let code_dir = ctx.installed_dir(&m);
602 let data_dir = ctx.plugin_data_dir("acme", "good-plugin");
603 fs::create_dir_all(&data_dir).map_err(|e| e.to_string())?;
604 fs::write(data_dir.join("state.txt"), "disposable data\n").map_err(|e| e.to_string())?;
606 // unrelated plugin data must survive a targeted purge
607 let other_data = ctx.plugin_data_dir("acme", "other-plugin");
608 fs::create_dir_all(&other_data).map_err(|e| e.to_string())?;
609 fs::write(other_data.join("keep.txt"), "unrelated\n").map_err(|e| e.to_string())?;
611 uninstall(&ctx, "acme/good-plugin", true)?;
612 c.check_fs("plugin code removed", &code_dir, false);
613 c.check_fs("plugin data PURGED with --purge-data", &data_dir, false);
614 c.check_fs("unrelated plugin data untouched", &other_data.join("keep.txt"), true);
615 Ok(())
616}
618fn main() -> Result<(), Box<dyn std::error::Error>> {
619 let scenario = std::env::args().nth(1).unwrap_or_default();
620 let lua = Lua::new();
621 let mut c = Checker::new();
622 println!("p04 scenario: {scenario}");
623 match scenario.as_str() {
624 "install-local" => scenario_install_local(&lua, &mut c)?,
625 "install-git" => scenario_install_git(&lua, &mut c)?,
626 "reject-bad-name" => scenario_reject_bad_name(&lua, &mut c)?,
627 "reject-smith-namespace" => scenario_reject_smith_namespace(&lua, &mut c)?,
628 "uninstall-keeps-data" => scenario_uninstall_keeps_data(&lua, &mut c)?,
629 "uninstall-purge-data" => scenario_uninstall_purge_data(&lua, &mut c)?,
630 other => {
631 return Err(format!(
632 "unknown scenario '{other}'; expected install-local | install-git | \
633 reject-bad-name | reject-smith-namespace | uninstall-keeps-data | \
634 uninstall-purge-data"
635 )
636 .into())
637 }
638 }
639 println!();
640 if c.pass {
641 println!("p04 RESULT: {scenario} — all assertions hold");
642 Ok(())
643 } else {
644 Err(format!("p04 RESULT: {scenario} — assertion failed").into())
645 }
646}

prototypes/p05-provider-fetch-normalize/Cargo.lock

Added
new file mode 100644

+107 / −0 text lines

1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "itoa"
7version = "1.0.18"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
11[[package]]
12name = "memchr"
13version = "2.8.3"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
17[[package]]
18name = "p05-provider-fetch-normalize"
19version = "0.1.0"
20dependencies = [
21 "serde",
22 "serde_json",
23]
25[[package]]
26name = "proc-macro2"
27version = "1.0.106"
28source = "registry+https://github.com/rust-lang/crates.io-index"
29checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
30dependencies = [
31 "unicode-ident",
32]
34[[package]]
35name = "quote"
36version = "1.0.46"
37source = "registry+https://github.com/rust-lang/crates.io-index"
38checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
39dependencies = [
40 "proc-macro2",
41]
43[[package]]
44name = "serde"
45version = "1.0.228"
46source = "registry+https://github.com/rust-lang/crates.io-index"
47checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
48dependencies = [
49 "serde_core",
50 "serde_derive",
51]
53[[package]]
54name = "serde_core"
55version = "1.0.228"
56source = "registry+https://github.com/rust-lang/crates.io-index"
57checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
58dependencies = [
59 "serde_derive",
60]
62[[package]]
63name = "serde_derive"
64version = "1.0.228"
65source = "registry+https://github.com/rust-lang/crates.io-index"
66checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
67dependencies = [
68 "proc-macro2",
69 "quote",
70 "syn",
71]
73[[package]]
74name = "serde_json"
75version = "1.0.150"
76source = "registry+https://github.com/rust-lang/crates.io-index"
77checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
78dependencies = [
79 "itoa",
80 "memchr",
81 "serde",
82 "serde_core",
83 "zmij",
84]
86[[package]]
87name = "syn"
88version = "2.0.118"
89source = "registry+https://github.com/rust-lang/crates.io-index"
90checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
91dependencies = [
92 "proc-macro2",
93 "quote",
94 "unicode-ident",
95]
97[[package]]
98name = "unicode-ident"
99version = "1.0.24"
100source = "registry+https://github.com/rust-lang/crates.io-index"
101checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
103[[package]]
104name = "zmij"
105version = "1.0.23"
106source = "registry+https://github.com/rust-lang/crates.io-index"
107checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"

prototypes/p05-provider-fetch-normalize/Cargo.toml

Added
new file mode 100644

+9 / −0 text lines

1[package]
2name = "p05-provider-fetch-normalize"
3version = "0.1.0"
4edition = "2021"
5publish = false
6
7[dependencies]
8serde = { version = "1", features = ["derive"] }
9serde_json = "1"

prototypes/p05-provider-fetch-normalize/fixtures/catwalk.json

Added
new file mode 100644

+44 / −0 text lines

1{
2 "source": "catwalk",
3 "providers": [
4 {
5 "id": "anthropic",
6 "name": "Anthropic",
7 "api_base": "https://api.anthropic.com/v1",
8 "models": [
9 {
10 "id": "claude-omega",
11 "name": "Claude Omega (community listing)",
12 "context_window": 400000,
13 "max_output_tokens": 64000,
14 "reasoning": true
15 },
16 {
17 "id": "claude-mini",
18 "max_output_tokens": 8192,
19 "reasoning": false
20 },
21 {
22 "id": "claude-legacy",
23 "name": "Claude Legacy",
24 "context_window": 100000,
25 "max_output_tokens": 4096,
26 "cost": { "input": 1.0, "output": 5.0 }
27 }
28 ]
29 },
30 {
31 "id": "mistral",
32 "name": "Mistral",
33 "api_base": "https://api.mistral.ai/v1",
34 "models": [
35 {
36 "id": "mistral-large-3",
37 "name": "Mistral Large 3",
38 "context_window": 128000,
39 "cost": { "input": 2.0, "output": 6.0 }
40 }
41 ]
42 }
43 ]
44}

prototypes/p05-provider-fetch-normalize/fixtures/current-providers.json

Added
new file mode 100644

+34 / −0 text lines

1{
2 "version": 1,
3 "x_registry_note": "hand-maintained metadata; unknown fields must survive regeneration",
4 "providers": {
5 "anthropic": {
6 "name": "Anthropic",
7 "api_base": "https://api.anthropic.com/v1",
8 "x_smith_auth_hint": "env:ANTHROPIC_API_KEY",
9 "models": {
10 "claude-omega": {
11 "name": "Claude Omega",
12 "context_window": 300000,
13 "max_output_tokens": 32000,
14 "cost": { "input": 6.0, "output": 30.0 },
15 "x_release_notes": "https://example.invalid/omega-notes"
16 }
17 }
18 },
19 "openai": {
20 "name": "OpenAI",
21 "api_base": "https://api.openai.com/v1",
22 "models": {
23 "gpt-9": {
24 "context_window": 800000,
25 "cost": {
26 "input": { "cached": 2.5, "uncached": 10.0 },
27 "output": 30.0
28 },
29 "regional_endpoints": { "eu": "https://eu.api.openai.invalid/v1" }
30 }
31 }
32 }
33 }
34}

prototypes/p05-provider-fetch-normalize/fixtures/pi.json

Added
new file mode 100644

+43 / −0 text lines

1{
2 "source": "pi.dev",
3 "fetched_at": "2026-07-14T00:00:00Z",
4 "models": [
5 {
6 "provider": "anthropic",
7 "id": "claude-omega",
8 "name": "Claude Omega",
9 "context_window": 500000,
10 "max_output_tokens": 64000,
11 "cost": { "input": 5.0, "output": 25.0 }
12 },
13 {
14 "provider": "anthropic",
15 "id": "claude-mini",
16 "name": "Claude Mini",
17 "context_window": 200000,
18 "cost": { "input": 0.8, "output": 4.0 }
19 },
20 {
21 "provider": "openai",
22 "id": "gpt-9",
23 "name": "GPT-9",
24 "context_window": 1000000,
25 "max_output_tokens": 32000,
26 "cost": { "input": 10.0, "output": 30.0 }
27 },
28 {
29 "provider": "openai",
30 "id": "gpt-9-nano",
31 "name": "GPT-9 Nano",
32 "context_window": 128000,
33 "cost": { "input": 0.1, "output": 0.4 }
34 },
35 {
36 "provider": "openai",
37 "id": "gpt-9-nano",
38 "name": "GPT-9 Nano",
39 "context_window": 256000,
40 "cost": { "input": 0.2, "output": 0.8 }
41 }
42 ]
43}

prototypes/p05-provider-fetch-normalize/src/main.rs

Added
new file mode 100644

+746 / −0 text lines

1//! p05-provider-fetch-normalize
2//!
3//! Proves or disproves docs/SPEC.md §7.3 (Model Registry) claims:
4//! - `providers.json` is runtime authority; `fetch-providers` only generates
5//! reviewable suggestions,
6//! - pi.dev is primary, catwalk fills gaps,
7//! - unknown registry fields are preserved through regeneration,
8//! - correctness requires review (some conflicts must NOT be auto-merged).
9//!
10//! No network: fixtures/pi.json and fixtures/catwalk.json are fake source
11//! shapes; fixtures/current-providers.json is the checked-in registry being
12//! updated.
13//!
14//! Verify:
15//! cargo run -- generate # merged suggestion + reviewable patch
16//! cargo run -- diff # what would change vs current registry
17//! cargo run -- conflict-fails # explicit report of non-auto-mergeable conflicts
18//!
19//! Exit-code choice for `conflict-fails`: exits 0 per PLAN.md — the command's
20//! contract is to *demonstrate* conflict detection, and detection succeeding is
21//! the pass condition. A production `fetch-providers` should instead exit
22//! non-zero (e.g. 2) while unresolved conflicts remain so PR automation cannot
23//! merge a corrupting suggestion. That distinction is reported as a SPEC gap.
25use serde_json::{json, Map, Value};
26use std::collections::{BTreeMap, BTreeSet};
27use std::process::ExitCode;
29const PI: &str = include_str!("../fixtures/pi.json");
30const CATWALK: &str = include_str!("../fixtures/catwalk.json");
31const CURRENT: &str = include_str!("../fixtures/current-providers.json");
33/// Fields the normalizer understands at model level. Anything else found in
34/// the current registry is "unknown" and must survive regeneration untouched.
35const KNOWN_MODEL_FIELDS: &[&str] = &[
36 "name",
37 "context_window",
38 "max_output_tokens",
39 "cost",
40 "reasoning",
41];
42/// Fields the normalizer understands at provider level (besides `models`).
43const KNOWN_PROVIDER_FIELDS: &[&str] = &["name", "api_base"];
45// ---------------------------------------------------------------------------
46// Normalized source representation
47// ---------------------------------------------------------------------------
49#[derive(Default, Clone)]
50struct SourceProvider {
51 /// provider-level fields (name, api_base)
52 fields: BTreeMap<String, Value>,
53 /// model id -> known model fields
54 models: BTreeMap<String, BTreeMap<String, Value>>,
55}
56type SourceMap = BTreeMap<String, SourceProvider>;
58#[derive(Debug)]
59enum Op {
60 Add,
61 Update,
62}
64/// One proposed registry change (reviewable unit).
65struct Change {
66 op: Op,
67 path: String,
68 old: Option<Value>,
69 new: Value,
70 source: String,
71}
73/// A pi/catwalk disagreement resolved by the "pi.dev primary" rule.
74struct ResolvedConflict {
75 path: String,
76 pi: Value,
77 catwalk: Value,
78}
80/// A conflict class that must NOT be auto-merged.
81struct UnresolvableConflict {
82 path: String,
83 class: &'static str,
84 reason: String,
85 left_label: &'static str,
86 left: Value,
87 right_label: &'static str,
88 right: Value,
89 action: &'static str,
90}
92struct Outcome {
93 current: Value,
94 suggestion: Value,
95 changes: Vec<Change>,
96 resolved: Vec<ResolvedConflict>,
97 unresolvable: Vec<UnresolvableConflict>,
98}
100// ---------------------------------------------------------------------------
101// Normalization
102// ---------------------------------------------------------------------------
104fn fields_value(f: &BTreeMap<String, Value>) -> Value {
105 Value::Object(f.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
106}
108/// pi.dev fake shape: flat `models` array with a `provider` field per entry.
109/// Duplicate (provider, id) entries with conflicting metadata make the primary
110/// source ambiguous: that model is excluded and reported as unresolvable.
111fn normalize_pi(raw: &Value) -> (SourceMap, Vec<UnresolvableConflict>, BTreeSet<(String, String)>) {
112 let mut map = SourceMap::new();
113 let mut unresolvable = Vec::new();
114 let mut poisoned: BTreeSet<(String, String)> = BTreeSet::new();
115 for m in raw["models"].as_array().expect("pi.json: models array") {
116 let pid = m["provider"].as_str().expect("pi model provider").to_string();
117 let mid = m["id"].as_str().expect("pi model id").to_string();
118 let mut fields = BTreeMap::new();
119 for f in KNOWN_MODEL_FIELDS {
120 if let Some(v) = m.get(*f) {
121 fields.insert((*f).to_string(), v.clone());
122 }
123 }
124 if poisoned.contains(&(pid.clone(), mid.clone())) {
125 continue;
126 }
127 let prov = map.entry(pid.clone()).or_default();
128 match prov.models.get(&mid) {
129 Some(existing) if *existing != fields => {
130 unresolvable.push(UnresolvableConflict {
131 path: format!("providers.{pid}.models.{mid}"),
132 class: "ambiguous-primary-source",
133 reason: "pi.dev (primary source) lists the same model twice with \
134 conflicting metadata; 'pi wins' cannot pick between two pi values"
135 .to_string(),
136 left_label: "pi.dev entry #1",
137 left: fields_value(existing),
138 right_label: "pi.dev entry #2",
139 right: fields_value(&fields),
140 action: "model excluded from suggestion; requires human review",
141 });
142 prov.models.remove(&mid);
143 poisoned.insert((pid.clone(), mid.clone()));
144 }
145 Some(_) => {} // identical duplicate: harmless
146 None => {
147 prov.models.insert(mid, fields);
148 }
149 }
150 }
151 (map, unresolvable, poisoned)
152}
154/// catwalk fake shape: `providers` array, each with nested `models` array.
155fn normalize_catwalk(raw: &Value) -> SourceMap {
156 let mut map = SourceMap::new();
157 for p in raw["providers"].as_array().expect("catwalk.json: providers array") {
158 let pid = p["id"].as_str().expect("catwalk provider id").to_string();
159 let prov = map.entry(pid).or_default();
160 for f in KNOWN_PROVIDER_FIELDS {
161 if let Some(v) = p.get(*f) {
162 prov.fields.insert((*f).to_string(), v.clone());
163 }
164 }
165 for m in p["models"].as_array().expect("catwalk models array") {
166 let mid = m["id"].as_str().expect("catwalk model id").to_string();
167 let mut fields = BTreeMap::new();
168 for f in KNOWN_MODEL_FIELDS {
169 if let Some(v) = m.get(*f) {
170 fields.insert((*f).to_string(), v.clone());
171 }
172 }
173 prov.models.insert(mid, fields);
174 }
175 }
176 map
177}
179// ---------------------------------------------------------------------------
180// Merge
181// ---------------------------------------------------------------------------
183fn jkind(v: &Value) -> &'static str {
184 match v {
185 Value::Null => "null",
186 Value::Bool(_) => "boolean",
187 Value::Number(_) => "number",
188 Value::String(_) => "string",
189 Value::Array(_) => "array",
190 Value::Object(_) => "object",
191 }
192}
194/// SPEC §7.3 merge rule: pi.dev primary, catwalk fills gaps.
195fn pick(
196 pi: Option<&Value>,
197 cat: Option<&Value>,
198 path: &str,
199 resolved: &mut Vec<ResolvedConflict>,
200) -> (Value, String) {
201 match (pi, cat) {
202 (Some(p), Some(c)) if p == c => (p.clone(), "pi.dev+catwalk (agree)".to_string()),
203 (Some(p), Some(c)) => {
204 resolved.push(ResolvedConflict {
205 path: path.to_string(),
206 pi: p.clone(),
207 catwalk: c.clone(),
208 });
209 (p.clone(), "pi.dev (won conflict over catwalk)".to_string())
210 }
211 (Some(p), None) => (p.clone(), "pi.dev".to_string()),
212 (None, Some(c)) => (c.clone(), "catwalk (fills gap)".to_string()),
213 (None, None) => unreachable!("pick called with no source value"),
214 }
215}
217/// Apply one proposed value onto the suggestion registry object.
218/// Keys the sources do not mention (unknown fields) are never visited, so they
219/// are preserved structurally byte-for-byte.
220fn apply_field(
221 obj: &mut Map<String, Value>,
222 key: &str,
223 new: &Value,
224 src: &str,
225 path: &str,
226 changes: &mut Vec<Change>,
227 unres: &mut Vec<UnresolvableConflict>,
228) {
229 match obj.get_mut(key) {
230 None => {
231 obj.insert(key.to_string(), new.clone());
232 changes.push(Change {
233 op: Op::Add,
234 path: path.to_string(),
235 old: None,
236 new: new.clone(),
237 source: src.to_string(),
238 });
239 }
240 Some(cur) => apply_existing(cur, new, src, path, changes, unres),
241 }
242}
244fn apply_existing(
245 cur: &mut Value,
246 new: &Value,
247 src: &str,
248 path: &str,
249 changes: &mut Vec<Change>,
250 unres: &mut Vec<UnresolvableConflict>,
251) {
252 if cur == new {
253 return;
254 }
255 if jkind(cur) != jkind(new) {
256 // Structural disagreement between generated data and the hand-curated
257 // registry. "pi wins" is a precedence rule between *sources*; it does
258 // not license clobbering a richer curated structure with a scalar.
259 unres.push(UnresolvableConflict {
260 path: path.to_string(),
261 class: "type-mismatch-vs-curated-registry",
262 reason: format!(
263 "registry has hand-curated {} but source proposes {}; \
264 auto-merge would destroy curated structure",
265 jkind(cur),
266 jkind(new)
267 ),
268 left_label: "current registry value (kept)",
269 left: cur.clone(),
270 right_label: &"proposed by source",
271 right: new.clone(),
272 action: "field NOT auto-merged; registry value kept; requires human review",
273 });
274 return;
275 }
276 if cur.is_object() && new.is_object() {
277 let cur_o = cur.as_object_mut().unwrap();
278 for (k, v) in new.as_object().unwrap() {
279 apply_field(cur_o, k, v, src, &format!("{path}.{k}"), changes, unres);
280 }
281 return;
282 }
283 changes.push(Change {
284 op: Op::Update,
285 path: path.to_string(),
286 old: Some(cur.clone()),
287 new: new.clone(),
288 source: src.to_string(),
289 });
290 *cur = new.clone();
291}
293fn run_merge() -> Outcome {
294 let current: Value = serde_json::from_str(CURRENT).expect("parse current-providers.json");
295 let pi_raw: Value = serde_json::from_str(PI).expect("parse pi.json");
296 let cat_raw: Value = serde_json::from_str(CATWALK).expect("parse catwalk.json");
298 let (pi, mut unresolvable, poisoned) = normalize_pi(&pi_raw);
299 let catwalk = normalize_catwalk(&cat_raw);
301 let mut suggestion = current.clone();
302 let mut changes = Vec::new();
303 let mut resolved = Vec::new();
305 let root = suggestion
306 .as_object_mut()
307 .expect("registry is object")
308 .entry("providers")
309 .or_insert_with(|| json!({}))
310 .as_object_mut()
311 .unwrap();
313 let empty = SourceProvider::default();
314 let provider_ids: BTreeSet<&String> = pi.keys().chain(catwalk.keys()).collect();
315 for pid in provider_ids {
316 let pi_p = pi.get(pid).unwrap_or(&empty);
317 let cat_p = catwalk.get(pid).unwrap_or(&empty);
319 let prov_obj = root
320 .entry(pid.clone())
321 .or_insert_with(|| json!({ "models": {} }))
322 .as_object_mut()
323 .unwrap();
325 // provider-level fields
326 let pfields: BTreeSet<&String> = pi_p.fields.keys().chain(cat_p.fields.keys()).collect();
327 for f in pfields {
328 let path = format!("providers.{pid}.{f}");
329 let (val, src) = pick(pi_p.fields.get(f), cat_p.fields.get(f), &path, &mut resolved);
330 apply_field(prov_obj, f, &val, &src, &path, &mut changes, &mut unresolvable);
331 }
333 // models
334 let models_obj = prov_obj
335 .entry("models".to_string())
336 .or_insert_with(|| json!({}))
337 .as_object_mut()
338 .unwrap();
339 let mids: BTreeSet<&String> = pi_p
340 .models
341 .keys()
342 .chain(cat_p.models.keys())
343 .filter(|m| !poisoned.contains(&(pid.clone(), (*m).clone())))
344 .collect();
345 for mid in mids {
346 let model_obj = models_obj
347 .entry(mid.clone())
348 .or_insert_with(|| json!({}))
349 .as_object_mut()
350 .unwrap();
351 let pi_m = pi_p.models.get(mid);
352 let cat_m = cat_p.models.get(mid);
353 let mfields: BTreeSet<&String> = pi_m
354 .map(|m| m.keys().collect::<Vec<_>>())
355 .unwrap_or_default()
356 .into_iter()
357 .chain(cat_m.map(|m| m.keys().collect::<Vec<_>>()).unwrap_or_default())
358 .collect();
359 for f in mfields {
360 let path = format!("providers.{pid}.models.{mid}.{f}");
361 let (val, src) = pick(
362 pi_m.and_then(|m| m.get(f)),
363 cat_m.and_then(|m| m.get(f)),
364 &path,
365 &mut resolved,
366 );
367 apply_field(model_obj, f, &val, &src, &path, &mut changes, &mut unresolvable);
368 }
369 }
370 }
372 Outcome {
373 current,
374 suggestion,
375 changes,
376 resolved,
377 unresolvable,
378 }
379}
381// ---------------------------------------------------------------------------
382// Helpers: path lookup, unknown-field scan, line diff
383// ---------------------------------------------------------------------------
385fn get<'a>(v: &'a Value, path: &str) -> Option<&'a Value> {
386 path.split('.').try_fold(v, |acc, k| acc.get(k))
387}
389/// Every path in the current registry whose key the normalizer does not know.
390/// These must be preserved exactly through the merge.
391fn scan_unknown_paths(current: &Value) -> Vec<String> {
392 let mut out = Vec::new();
393 let top = current.as_object().unwrap();
394 for k in top.keys() {
395 if k != "version" && k != "providers" {
396 out.push(k.clone());
397 }
398 }
399 if let Some(providers) = top.get("providers").and_then(Value::as_object) {
400 for (pid, p) in providers {
401 let po = p.as_object().unwrap();
402 for k in po.keys() {
403 if !KNOWN_PROVIDER_FIELDS.contains(&k.as_str()) && k != "models" {
404 out.push(format!("providers.{pid}.{k}"));
405 }
406 }
407 if let Some(models) = po.get("models").and_then(Value::as_object) {
408 for (mid, m) in models {
409 for k in m.as_object().unwrap().keys() {
410 if !KNOWN_MODEL_FIELDS.contains(&k.as_str()) {
411 out.push(format!("providers.{pid}.models.{mid}.{k}"));
412 }
413 }
414 }
415 }
416 }
417 }
418 out
419}
421/// Minimal LCS line diff of two pretty-printed JSON documents.
422fn diff_ops(a: &[&str], b: &[&str]) -> Vec<(char, String)> {
423 let (n, m) = (a.len(), b.len());
424 let mut dp = vec![vec![0usize; m + 1]; n + 1];
425 for i in (0..n).rev() {
426 for j in (0..m).rev() {
427 dp[i][j] = if a[i] == b[j] {
428 dp[i + 1][j + 1] + 1
429 } else {
430 dp[i + 1][j].max(dp[i][j + 1])
431 };
432 }
433 }
434 let (mut i, mut j) = (0, 0);
435 let mut out = Vec::new();
436 while i < n && j < m {
437 if a[i] == b[j] {
438 out.push((' ', a[i].to_string()));
439 i += 1;
440 j += 1;
441 } else if dp[i + 1][j] >= dp[i][j + 1] {
442 out.push(('-', a[i].to_string()));
443 i += 1;
444 } else {
445 out.push(('+', b[j].to_string()));
446 j += 1;
447 }
448 }
449 while i < n {
450 out.push(('-', a[i].to_string()));
451 i += 1;
452 }
453 while j < m {
454 out.push(('+', b[j].to_string()));
455 j += 1;
456 }
457 out
458}
460/// Render a unified-style patch with 2 lines of context around changes.
461fn render_patch(current: &Value, suggestion: &Value) -> String {
462 let a = serde_json::to_string_pretty(current).unwrap();
463 let b = serde_json::to_string_pretty(suggestion).unwrap();
464 let al: Vec<&str> = a.lines().collect();
465 let bl: Vec<&str> = b.lines().collect();
466 let ops = diff_ops(&al, &bl);
467 let mut keep = vec![false; ops.len()];
468 for (i, (c, _)) in ops.iter().enumerate() {
469 if *c != ' ' {
470 let lo = i.saturating_sub(2);
471 let hi = (i + 2).min(ops.len().saturating_sub(1));
472 for k in keep.iter_mut().take(hi + 1).skip(lo) {
473 *k = true;
474 }
475 }
476 }
477 let mut out = String::from("--- fixtures/current-providers.json (current)\n+++ suggested providers.json (generated, requires review)\n");
478 let mut skipping = false;
479 for (i, (c, l)) in ops.iter().enumerate() {
480 if keep[i] {
481 if skipping {
482 out.push_str("@@ ... @@\n");
483 skipping = false;
484 }
485 out.push_str(&format!("{c} {l}\n"));
486 } else {
487 skipping = true;
488 }
489 }
490 if skipping {
491 out.push_str("@@ ... @@\n");
492 }
493 out
494}
496fn print_unresolvable(u: &UnresolvableConflict) {
497 println!("CONFLICT {}", u.path);
498 println!(" class: {}", u.class);
499 println!(" reason: {}", u.reason);
500 println!(" {}: {}", u.left_label, u.left);
501 println!(" {}: {}", u.right_label, u.right);
502 println!(" action: {}", u.action);
503}
505// ---------------------------------------------------------------------------
506// Commands
507// ---------------------------------------------------------------------------
509struct Checker {
510 pass: bool,
511}
512impl Checker {
513 fn new() -> Self {
514 Checker { pass: true }
515 }
516 fn check(&mut self, label: &str, ok: bool) {
517 println!("{} {label}", if ok { "PASS" } else { "FAIL" });
518 self.pass &= ok;
519 }
520}
522/// Assertions shared by all commands: the SPEC §7.3 pass evidence.
523fn core_assertions(c: &mut Checker, o: &Outcome) {
524 let s = &o.suggestion;
526 // pi.dev wins conflicts (against catwalk 400000 / "(community listing)")
527 c.check(
528 "pi wins conflict: claude-omega.context_window = 500000 (pi) not 400000 (catwalk)",
529 get(s, "providers.anthropic.models.claude-omega.context_window") == Some(&json!(500000)),
530 );
531 c.check(
532 "pi wins conflict: claude-omega.name = \"Claude Omega\" (pi) not catwalk's listing name",
533 get(s, "providers.anthropic.models.claude-omega.name") == Some(&json!("Claude Omega")),
534 );
535 c.check(
536 "resolved-conflict log records both values for review",
537 o.resolved.iter().any(|r| {
538 r.path == "providers.anthropic.models.claude-omega.context_window"
539 && r.pi == json!(500000)
540 && r.catwalk == json!(400000)
541 }),
542 );
544 // catwalk fills gaps
545 c.check(
546 "catwalk fills gap: claude-omega.reasoning = true (absent from pi)",
547 get(s, "providers.anthropic.models.claude-omega.reasoning") == Some(&json!(true)),
548 );
549 c.check(
550 "catwalk fills gap: claude-mini.max_output_tokens = 8192 (absent from pi)",
551 get(s, "providers.anthropic.models.claude-mini.max_output_tokens") == Some(&json!(8192)),
552 );
553 c.check(
554 "catwalk-only model claude-legacy added",
555 get(s, "providers.anthropic.models.claude-legacy.cost.input") == Some(&json!(1.0)),
556 );
557 c.check(
558 "catwalk-only provider mistral added with api_base",
559 get(s, "providers.mistral.api_base") == Some(&json!("https://api.mistral.ai/v1"))
560 && get(s, "providers.mistral.models.mistral-large-3").is_some(),
561 );
563 // unknown fields preserved
564 let unknown = scan_unknown_paths(&o.current);
565 let all_preserved = unknown.iter().all(|p| get(s, p) == get(&o.current, p));
566 let untouched = unknown
567 .iter()
568 .all(|p| o.changes.iter().all(|ch| !ch.path.starts_with(p.as_str())));
569 for p in &unknown {
570 println!(" unknown field preserved: {p} = {}", get(s, p).map(|v| v.to_string()).unwrap_or_else(|| "<MISSING>".into()));
571 }
572 c.check(
573 &format!("all {} unknown registry fields preserved semantically byte-for-byte", unknown.len()),
574 unknown.len() == 4 && all_preserved && untouched,
575 );
577 // unresolvable conflicts are NOT auto-merged
578 c.check(
579 "type-mismatch conflict NOT merged: gpt-9.cost.input keeps curated object",
580 get(s, "providers.openai.models.gpt-9.cost.input")
581 == Some(&json!({ "cached": 2.5, "uncached": 10.0 })),
582 );
583 c.check(
584 "ambiguous-primary conflict NOT merged: gpt-9-nano excluded from suggestion",
585 get(s, "providers.openai.models.gpt-9-nano").is_none(),
586 );
587 c.check(
588 "exactly 2 unresolvable conflicts reported explicitly",
589 o.unresolvable.len() == 2,
590 );
592 // sanity: a compatible pi update to curated data IS proposed (that is the
593 // tool's purpose) but only as a suggestion in the patch, not a silent write
594 c.check(
595 "pi updates stale registry value in suggestion: gpt-9.context_window 800000 -> 1000000",
596 get(s, "providers.openai.models.gpt-9.context_window") == Some(&json!(1000000)),
597 );
598}
600fn cmd_generate(o: &Outcome) -> bool {
601 println!("== suggested providers.json (generated; current registry stays authoritative until a human commits this) ==");
602 println!("{}", serde_json::to_string_pretty(&o.suggestion).unwrap());
603 println!();
604 println!("== reviewable patch ==");
605 let patch = render_patch(&o.current, &o.suggestion);
606 print!("{patch}");
607 println!();
608 println!("== pi/catwalk conflicts resolved by 'pi.dev primary' rule ({}) ==", o.resolved.len());
609 for r in &o.resolved {
610 println!(" {}: pi.dev {} beat catwalk {}", r.path, r.pi, r.catwalk);
611 }
612 println!();
613 println!("== unresolvable conflicts excluded from patch ({}) — see `conflict-fails` ==", o.unresolvable.len());
614 for u in &o.unresolvable {
615 println!(" {} [{}]", u.path, u.class);
616 }
617 println!();
619 let mut c = Checker::new();
620 core_assertions(&mut c, o);
621 let has = |sign: char, frag: &str| {
622 patch
623 .lines()
624 .any(|l| l.starts_with(sign) && l.trim_start_matches([sign, ' ']).starts_with(frag))
625 };
626 c.check(
627 "patch is reviewable: shows old and new values as -/+ lines",
628 has('-', "\"context_window\": 300000,") && has('+', "\"context_window\": 500000,"),
629 );
630 c.check(
631 "generate never writes files: current-providers.json is untouched (stdout only)",
632 serde_json::from_str::<Value>(CURRENT).unwrap() == o.current,
633 );
634 println!();
635 println!("p05 generate RESULT: {}", if c.pass { "all expectations hold" } else { "FAILED" });
636 c.pass
637}
639fn cmd_diff(o: &Outcome) -> bool {
640 println!("== changes vs fixtures/current-providers.json ({} field-level ops) ==", o.changes.len());
641 for ch in &o.changes {
642 match ch.op {
643 Op::Add => println!(" + {} = {} [{}]", ch.path, ch.new, ch.source),
644 Op::Update => println!(
645 " ~ {}: {} -> {} [{}]",
646 ch.path,
647 ch.old.as_ref().unwrap(),
648 ch.new,
649 ch.source
650 ),
651 }
652 }
653 println!();
654 println!("== fields kept at current value due to unresolved conflicts ({}) ==", o.unresolvable.len());
655 for u in &o.unresolvable {
656 println!(" ! {} [{}] — {}", u.path, u.class, u.action);
657 }
658 println!();
660 let mut c = Checker::new();
661 core_assertions(&mut c, o);
662 c.check(
663 "diff lists stale-value update with old and new: claude-omega.context_window 300000 -> 500000",
664 o.changes.iter().any(|ch| {
665 matches!(ch.op, Op::Update)
666 && ch.path == "providers.anthropic.models.claude-omega.context_window"
667 && ch.old == Some(json!(300000))
668 && ch.new == json!(500000)
669 }),
670 );
671 c.check(
672 "every change is attributed to a source (pi.dev / catwalk / both)",
673 o.changes.iter().all(|ch| !ch.source.is_empty()),
674 );
675 c.check(
676 "no change touches an unknown registry field",
677 scan_unknown_paths(&o.current)
678 .iter()
679 .all(|p| o.changes.iter().all(|ch| !ch.path.starts_with(p.as_str()))),
680 );
681 println!();
682 println!("p05 diff RESULT: {}", if c.pass { "all expectations hold" } else { "FAILED" });
683 c.pass
684}
686fn cmd_conflict_fails(o: &Outcome) -> bool {
687 println!("== explicit conflict report: classes that must NOT be auto-merged ==");
688 println!();
689 for u in &o.unresolvable {
690 print_unresolvable(u);
691 println!();
692 }
694 let mut c = Checker::new();
695 core_assertions(&mut c, o);
696 c.check(
697 "report includes a type-mismatch-vs-curated-registry conflict at gpt-9.cost.input",
698 o.unresolvable.iter().any(|u| {
699 u.class == "type-mismatch-vs-curated-registry"
700 && u.path == "providers.openai.models.gpt-9.cost.input"
701 }),
702 );
703 c.check(
704 "report includes an ambiguous-primary-source conflict at gpt-9-nano",
705 o.unresolvable.iter().any(|u| {
706 u.class == "ambiguous-primary-source"
707 && u.path == "providers.openai.models.gpt-9-nano"
708 }),
709 );
710 c.check(
711 "every conflict entry states path, class, both values, and required action",
712 o.unresolvable
713 .iter()
714 .all(|u| !u.path.is_empty() && !u.reason.is_empty() && !u.action.is_empty()),
715 );
716 println!();
717 println!(
718 "exit-code note: this command exits 0 because its contract (PLAN.md) is to \
719 demonstrate that the conflict class is detected and NOT auto-merged — which succeeded. \
720 A production `fetch-providers` should exit non-zero (e.g. 2) while unresolved \
721 conflicts remain, so PR automation cannot silently merge a corrupting suggestion. \
722 SPEC §7.3 does not currently specify this."
723 );
724 println!();
725 println!("p05 conflict-fails RESULT: {}", if c.pass { "all expectations hold" } else { "FAILED" });
726 c.pass
727}
729fn main() -> ExitCode {
730 let cmd = std::env::args().nth(1).unwrap_or_default();
731 let outcome = run_merge();
732 let ok = match cmd.as_str() {
733 "generate" => cmd_generate(&outcome),
734 "diff" => cmd_diff(&outcome),
735 "conflict-fails" => cmd_conflict_fails(&outcome),
736 _ => {
737 eprintln!("usage: cargo run -- <generate|diff|conflict-fails>");
738 return ExitCode::from(2);
739 }
740 };
741 if ok {
742 ExitCode::SUCCESS
743 } else {
744 ExitCode::FAILURE
745 }
746}

prototypes/p06-session-codec-recovery/Cargo.lock

Added
new file mode 100644

+146 / −0 text lines

1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "cfg-if"
7version = "1.0.4"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
11[[package]]
12name = "ciborium"
13version = "0.2.2"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
16dependencies = [
17 "ciborium-io",
18 "ciborium-ll",
19 "serde",
20]
22[[package]]
23name = "ciborium-io"
24version = "0.2.2"
25source = "registry+https://github.com/rust-lang/crates.io-index"
26checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
28[[package]]
29name = "ciborium-ll"
30version = "0.2.2"
31source = "registry+https://github.com/rust-lang/crates.io-index"
32checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
33dependencies = [
34 "ciborium-io",
35 "half",
36]
38[[package]]
39name = "crunchy"
40version = "0.2.4"
41source = "registry+https://github.com/rust-lang/crates.io-index"
42checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
44[[package]]
45name = "half"
46version = "2.7.1"
47source = "registry+https://github.com/rust-lang/crates.io-index"
48checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
49dependencies = [
50 "cfg-if",
51 "crunchy",
52 "zerocopy",
53]
55[[package]]
56name = "p06-session-codec-recovery"
57version = "0.1.0"
58dependencies = [
59 "ciborium",
60 "serde",
61]
63[[package]]
64name = "proc-macro2"
65version = "1.0.106"
66source = "registry+https://github.com/rust-lang/crates.io-index"
67checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
68dependencies = [
69 "unicode-ident",
70]
72[[package]]
73name = "quote"
74version = "1.0.46"
75source = "registry+https://github.com/rust-lang/crates.io-index"
76checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
77dependencies = [
78 "proc-macro2",
79]
81[[package]]
82name = "serde"
83version = "1.0.228"
84source = "registry+https://github.com/rust-lang/crates.io-index"
85checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
86dependencies = [
87 "serde_core",
88 "serde_derive",
89]
91[[package]]
92name = "serde_core"
93version = "1.0.228"
94source = "registry+https://github.com/rust-lang/crates.io-index"
95checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
96dependencies = [
97 "serde_derive",
98]
100[[package]]
101name = "serde_derive"
102version = "1.0.228"
103source = "registry+https://github.com/rust-lang/crates.io-index"
104checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
105dependencies = [
106 "proc-macro2",
107 "quote",
108 "syn",
109]
111[[package]]
112name = "syn"
113version = "2.0.118"
114source = "registry+https://github.com/rust-lang/crates.io-index"
115checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
116dependencies = [
117 "proc-macro2",
118 "quote",
119 "unicode-ident",
120]
122[[package]]
123name = "unicode-ident"
124version = "1.0.24"
125source = "registry+https://github.com/rust-lang/crates.io-index"
126checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
128[[package]]
129name = "zerocopy"
130version = "0.8.54"
131source = "registry+https://github.com/rust-lang/crates.io-index"
132checksum = "b7cbbc0a705a0fd05cc3676525980d2bf5a9bc4adac6d6475209a7887cf59d19"
133dependencies = [
134 "zerocopy-derive",
135]
137[[package]]
138name = "zerocopy-derive"
139version = "0.8.54"
140source = "registry+https://github.com/rust-lang/crates.io-index"
141checksum = "e2e817b7b52d0c7358d3246da9d69935ebb18116b2b102b4230dac079b4862f5"
142dependencies = [
143 "proc-macro2",
144 "quote",
145 "syn",
146]

prototypes/p06-session-codec-recovery/Cargo.toml

Added
new file mode 100644

+9 / −0 text lines

1[package]
2name = "p06-session-codec-recovery"
3version = "0.1.0"
4edition = "2021"
5publish = false
6
7[dependencies]
8serde = { version = "1", features = ["derive"] }
9ciborium = "0.2"

prototypes/p06-session-codec-recovery/src/main.rs

Added
new file mode 100644

+242 / −0 text lines

1//! p06-session-codec-recovery
2//!
3//! Proves or disproves docs/SPEC.md §6.6 recovery claims for length-prefixed
4//! CBOR session sequences:
5//! - truncated tail stops parsing (prior entries survive),
6//! - corrupt entry: skip + warn if possible,
7//! - unknown future entry: preserve when round-tripping.
8//!
9//! Verify: `cargo run` — exits 0 with PASS lines when all expectations hold.
11use serde::{Deserialize, Serialize};
13/// v1 entry set — what the current reader knows.
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
15enum EntryV1 {
16 User { id: u64, text: String },
17 Assistant { id: u64, text: String },
18 ToolCall { id: u64, name: String, args: String },
19 ToolResult { id: u64, output: String },
20}
22/// v2 entry set — a future Smith writing a variant v1 does not know.
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24enum EntryV2 {
25 User { id: u64, text: String },
26 Assistant { id: u64, text: String },
27 ToolCall { id: u64, name: String, args: String },
28 ToolResult { id: u64, output: String },
29 /// Future variant, unknown to v1.
30 HologramSnapshot { id: u64, blob: Vec<u8> },
31}
33/// What the recovering reader produces per frame.
34#[derive(Debug, Clone, PartialEq)]
35enum Recovered {
36 Known(EntryV1),
37 /// Well-formed CBOR whose variant tag v1 does not know: preserved raw.
38 Unknown(Vec<u8>),
39}
41/// Diagnostics emitted during a read pass.
42#[derive(Debug, PartialEq)]
43enum Warn {
44 CorruptEntrySkipped { frame: usize },
45 TruncatedTail { at_frame: usize, missing: usize },
46 /// A length prefix produced an implausible frame; framing is lost from here.
47 FramingLost { at_frame: usize, claimed_len: usize, remaining: usize },
48}
50fn encode<T: Serialize>(entries: &[T]) -> Vec<u8> {
51 let mut out = Vec::new();
52 for e in entries {
53 let mut buf = Vec::new();
54 ciborium::ser::into_writer(e, &mut buf).expect("encode");
55 out.extend_from_slice(&(buf.len() as u32).to_be_bytes());
56 out.extend_from_slice(&buf);
57 }
58 out
59}
61fn append_raw(out: &mut Vec<u8>, raw: &[u8]) {
62 out.extend_from_slice(&(raw.len() as u32).to_be_bytes());
63 out.extend_from_slice(raw);
64}
66/// The recovering reader. Never panics, never loses entries before a fault.
67fn read_recovering(bytes: &[u8]) -> (Vec<Recovered>, Vec<Warn>) {
68 let mut entries = Vec::new();
69 let mut warns = Vec::new();
70 let mut pos = 0usize;
71 let mut frame = 0usize;
72 while pos < bytes.len() {
73 if bytes.len() - pos < 4 {
74 warns.push(Warn::TruncatedTail { at_frame: frame, missing: 4 - (bytes.len() - pos) });
75 break;
76 }
77 let len = u32::from_be_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize;
78 let body_start = pos + 4;
79 if len > bytes.len() - body_start {
80 // Either a truncated tail (last frame cut mid-body) or a corrupted
81 // length prefix. The codec cannot distinguish them; everything from
82 // here on is unreadable.
83 if frame == 0 || len <= 16 * 1024 * 1024 {
84 warns.push(Warn::TruncatedTail { at_frame: frame, missing: len - (bytes.len() - body_start) });
85 } else {
86 warns.push(Warn::FramingLost { at_frame: frame, claimed_len: len, remaining: bytes.len() - body_start });
87 }
88 break;
89 }
90 let body = &bytes[body_start..body_start + len];
91 // Two-stage decode: well-formed CBOR? then: known variant?
92 match ciborium::de::from_reader::<ciborium::Value, _>(body) {
93 Err(_) => warns.push(Warn::CorruptEntrySkipped { frame }),
94 Ok(val) => match val.deserialized::<EntryV1>() {
95 Ok(e) => entries.push(Recovered::Known(e)),
96 Err(_) => entries.push(Recovered::Unknown(body.to_vec())),
97 },
98 }
99 pos = body_start + len;
100 frame += 1;
101 }
102 (entries, warns)
103}
105fn sample_v1() -> Vec<EntryV1> {
106 vec![
107 EntryV1::User { id: 1, text: "hello".into() },
108 EntryV1::Assistant { id: 2, text: "hi, running a tool".into() },
109 EntryV1::ToolCall { id: 3, name: "read".into(), args: "{\"path\":\"a.rs\"}".into() },
110 EntryV1::ToolResult { id: 4, output: "fn main() {}".into() },
111 EntryV1::Assistant { id: 5, text: "done".into() },
112 ]
113}
115fn main() -> Result<(), Box<dyn std::error::Error>> {
116 let mut pass = true;
117 let mut check = |label: &str, ok: bool| {
118 println!("{} {label}", if ok { "PASS" } else { "FAIL" });
119 pass &= ok;
120 };
122 // 1. Normal roundtrip.
123 let entries = sample_v1();
124 let bytes = encode(&entries);
125 let (rec, warns) = read_recovering(&bytes);
126 check(
127 &format!("normal roundtrip: {}/{} entries, no warnings", rec.len(), entries.len()),
128 rec.len() == 5
129 && warns.is_empty()
130 && rec.iter().zip(&entries).all(|(r, e)| matches!(r, Recovered::Known(k) if k == e)),
131 );
133 // 2a. Truncated mid-body (crash during write): prior entries survive.
134 let cut = bytes.len() - 7;
135 let (rec, warns) = read_recovering(&bytes[..cut]);
136 check(
137 &format!("truncated mid-body: {} prior entries recovered, tail reported", rec.len()),
138 rec.len() == 4 && warns == vec![Warn::TruncatedTail { at_frame: 4, missing: 7 }],
139 );
141 // 2b. Truncated mid-length-prefix: prior entries survive.
142 let frames: Vec<Vec<u8>> = entries.iter().map(|e| {
143 let mut b = Vec::new();
144 ciborium::ser::into_writer(e, &mut b).unwrap();
145 b
146 }).collect();
147 let mut t = Vec::new();
148 for f in &frames[..4] { append_raw(&mut t, f); }
149 t.extend_from_slice(&[0u8, 0]); // 2 bytes of a 4-byte length prefix
150 let (rec, warns) = read_recovering(&t);
151 check(
152 &format!("truncated mid-prefix: {} prior entries recovered", rec.len()),
153 rec.len() == 4 && matches!(warns[..], [Warn::TruncatedTail { at_frame: 4, missing: 2 }]),
154 );
156 // 3. Corrupt entry BODY (length intact): skipped with warning, all other
157 // entries survive — framing makes the skip precise.
158 let mut c = Vec::new();
159 for (i, f) in frames.iter().enumerate() {
160 if i == 2 {
161 let mut bad = f.clone();
162 for b in bad.iter_mut() { *b = 0xFF; } // garbage, not valid CBOR
163 append_raw(&mut c, &bad);
164 } else {
165 append_raw(&mut c, f);
166 }
167 }
168 let (rec, warns) = read_recovering(&c);
169 check(
170 &format!("corrupt body skipped: {}/5 survive, skip warned", rec.len()),
171 rec.len() == 4
172 && warns == vec![Warn::CorruptEntrySkipped { frame: 2 }]
173 && matches!(&rec[2], Recovered::Known(EntryV1::ToolResult { id: 4, .. })),
174 );
176 // 4. Corrupt LENGTH PREFIX: framing desynchronizes; everything from the
177 // corrupt frame on is lost. SPEC's "skip + warn if possible" must not
178 // promise more than this.
179 let mut c = Vec::new();
180 for (i, f) in frames.iter().enumerate() {
181 if i == 2 {
182 c.extend_from_slice(&0xDEAD_BEEFu32.to_be_bytes()); // absurd length
183 c.extend_from_slice(f);
184 } else {
185 append_raw(&mut c, f);
186 }
187 }
188 let (rec, warns) = read_recovering(&c);
189 check(
190 &format!("corrupt length prefix: {} prior entries survive, framing loss reported", rec.len()),
191 rec.len() == 2
192 && matches!(warns[..], [Warn::FramingLost { at_frame: 2, claimed_len: 0xDEAD_BEEF, .. }]),
193 );
195 // 5. Unknown future entry: v2 writes, v1 reads + preserves + rewrites,
196 // v2 reads back the future variant intact.
197 let v2_entries = vec![
198 EntryV2::User { id: 1, text: "hello".into() },
199 EntryV2::HologramSnapshot { id: 2, blob: vec![9, 9, 9] },
200 EntryV2::Assistant { id: 3, text: "future done".into() },
201 ];
202 let v2_bytes = encode(&v2_entries);
203 let (rec, warns) = read_recovering(&v2_bytes);
204 let unknown_preserved = matches!(&rec[1], Recovered::Unknown(_));
205 check(
206 "v1 reads v2 file: known entries decode, unknown preserved, no warnings",
207 rec.len() == 3 && warns.is_empty() && unknown_preserved,
208 );
210 // v1 rewrites the session (roundtrip), preserving the unknown frame raw.
211 let mut rewritten = Vec::new();
212 for r in &rec {
213 match r {
214 Recovered::Known(e) => {
215 let mut b = Vec::new();
216 ciborium::ser::into_writer(e, &mut b)?;
217 append_raw(&mut rewritten, &b);
218 }
219 Recovered::Unknown(raw) => append_raw(&mut rewritten, raw),
220 }
221 }
222 let mut back = Vec::new();
223 let mut pos = 0usize;
224 while pos < rewritten.len() {
225 let len = u32::from_be_bytes(rewritten[pos..pos + 4].try_into()?) as usize;
226 let body = &rewritten[pos + 4..pos + 4 + len];
227 back.push(ciborium::de::from_reader::<ciborium::Value, _>(body)?.deserialized::<EntryV2>()?);
228 pos += 4 + len;
229 }
230 check(
231 "v2 reads v1-rewritten file: future variant survives roundtrip",
232 back == v2_entries,
233 );
235 println!();
236 if pass {
237 println!("p06 RESULT: all expectations hold");
238 Ok(())
239 } else {
240 Err("p06 RESULT: expectation failed".into())
241 }
242}

prototypes/p07-streamfn-agent-loop/Cargo.lock

Added
new file mode 100644

+105 / −0 text lines

1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "itoa"
7version = "1.0.18"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
11[[package]]
12name = "memchr"
13version = "2.8.3"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
17[[package]]
18name = "p07-streamfn-agent-loop"
19version = "0.1.0"
20dependencies = [
21 "serde_json",
22]
24[[package]]
25name = "proc-macro2"
26version = "1.0.106"
27source = "registry+https://github.com/rust-lang/crates.io-index"
28checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
29dependencies = [
30 "unicode-ident",
31]
33[[package]]
34name = "quote"
35version = "1.0.46"
36source = "registry+https://github.com/rust-lang/crates.io-index"
37checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
38dependencies = [
39 "proc-macro2",
40]
42[[package]]
43name = "serde"
44version = "1.0.228"
45source = "registry+https://github.com/rust-lang/crates.io-index"
46checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
47dependencies = [
48 "serde_core",
49]
51[[package]]
52name = "serde_core"
53version = "1.0.228"
54source = "registry+https://github.com/rust-lang/crates.io-index"
55checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
56dependencies = [
57 "serde_derive",
58]
60[[package]]
61name = "serde_derive"
62version = "1.0.228"
63source = "registry+https://github.com/rust-lang/crates.io-index"
64checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
65dependencies = [
66 "proc-macro2",
67 "quote",
68 "syn",
69]
71[[package]]
72name = "serde_json"
73version = "1.0.150"
74source = "registry+https://github.com/rust-lang/crates.io-index"
75checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
76dependencies = [
77 "itoa",
78 "memchr",
79 "serde",
80 "serde_core",
81 "zmij",
82]
84[[package]]
85name = "syn"
86version = "2.0.118"
87source = "registry+https://github.com/rust-lang/crates.io-index"
88checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
89dependencies = [
90 "proc-macro2",
91 "quote",
92 "unicode-ident",
93]
95[[package]]
96name = "unicode-ident"
97version = "1.0.24"
98source = "registry+https://github.com/rust-lang/crates.io-index"
99checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
101[[package]]
102name = "zmij"
103version = "1.0.23"
104source = "registry+https://github.com/rust-lang/crates.io-index"
105checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"

prototypes/p07-streamfn-agent-loop/Cargo.toml

Added
new file mode 100644

+8 / −0 text lines

1[package]
2name = "p07-streamfn-agent-loop"
3version = "0.1.0"
4edition = "2021"
5publish = false
6
7[dependencies]
8serde_json = "1"

prototypes/p07-streamfn-agent-loop/src/main.rs

Added
new file mode 100644

+301 / −0 text lines

1//! p07-streamfn-agent-loop
2//!
3//! Proves or disproves docs/SPEC.md §5.4 + §6.1–§6.4 claims:
4//! - the agent loop drives behavior through `StreamFn` with no provider
5//! implementation dependency,
6//! - text/tool/done provider events produce a deterministic `AgentEvent`
7//! sequence,
8//! - `BeforeToolCall` hooks can allow/block/replace-args.
9//!
10//! Determinism is the claim under test, so the mock StreamFn is a scripted
11//! iterator; async delivery does not change ordering semantics (noted in the
12//! prototype report).
13//!
14//! Verify: `cargo run -- basic|tool|hook-block|hook-replace` (exit 0 each).
16use serde_json::{json, Value};
18// ---- smith/ shared types (miniature, mirroring SPEC §5.2–§5.4) ----
20#[derive(Debug, Clone, PartialEq)]
21enum StopReason {
22 EndTurn,
23 ToolUse,
24}
26#[derive(Debug, Clone)]
27enum ProviderEvent {
28 TextDelta(String),
29 ToolCall { id: String, name: String, args: Value },
30 Done { stop: StopReason },
31}
33#[derive(Debug, Clone)]
34struct Message {
35 role: &'static str,
36 content: String,
37}
39#[derive(Debug, Clone)]
40struct ProviderRequest {
41 messages: Vec<Message>,
42}
44/// SPEC §5.4: input ProviderRequest, output stream of ProviderEvent.
45/// The loop below has no knowledge of what implements this.
46type StreamFn = Box<dyn FnMut(&ProviderRequest) -> Vec<ProviderEvent>>;
48// ---- smith-core/ agent events + hooks (miniature, SPEC §6.2/§6.4) ----
50#[derive(Debug, Clone, PartialEq)]
51enum AgentEvent {
52 AgentStart,
53 TurnStart(u32),
54 MessageStart,
55 TextDelta(String),
56 MessageEnd,
57 ToolExecutionStart { id: String, name: String },
58 ToolExecutionEnd { id: String, output: String, is_error: bool },
59 TurnEnd(u32),
60 AgentEnd,
61}
63enum BeforeToolCallResult {
64 Allow,
65 Block { reason: String },
66 ReplaceArgs(Value),
67}
69type BeforeHook = Box<dyn Fn(&str, &Value) -> BeforeToolCallResult>;
71struct ToolRegistry;
73impl ToolRegistry {
74 /// Mock `echo` tool: returns its args, uppercased text.
75 fn execute(&self, name: &str, args: &Value) -> Result<String, String> {
76 match name {
77 "echo" => {
78 let text = args["text"].as_str().unwrap_or_default();
79 Ok(text.to_uppercase())
80 }
81 other => Err(format!("unknown tool {other}")),
82 }
83 }
84}
86/// Miniature agent loop: outer loop = turns, inner loop = provider events +
87/// tool execution, per SPEC §6.1. Consumes only StreamFn.
88fn agent_loop(
89 mut stream: StreamFn,
90 tools: &ToolRegistry,
91 before_hook: &BeforeHook,
92 user_prompt: &str,
93 max_turns: u32,
94) -> (Vec<AgentEvent>, Vec<Message>) {
95 let mut events = vec![AgentEvent::AgentStart];
96 let mut messages = vec![Message { role: "user", content: user_prompt.into() }];
97 let mut turn = 0u32;
98 loop {
99 turn += 1;
100 if turn > max_turns {
101 break;
102 }
103 events.push(AgentEvent::TurnStart(turn));
104 events.push(AgentEvent::MessageStart);
105 let req = ProviderRequest { messages: messages.clone() };
106 let mut pending_tools: Vec<(String, String, Value)> = Vec::new();
107 let mut stop = StopReason::EndTurn;
108 let mut text = String::new();
109 for ev in stream(&req) {
110 match ev {
111 ProviderEvent::TextDelta(t) => {
112 text.push_str(&t);
113 events.push(AgentEvent::TextDelta(t));
114 }
115 ProviderEvent::ToolCall { id, name, args } => {
116 pending_tools.push((id, name, args));
117 }
118 ProviderEvent::Done { stop: s } => stop = s,
119 }
120 }
121 events.push(AgentEvent::MessageEnd);
122 messages.push(Message { role: "assistant", content: text });
124 for (id, name, mut args) in pending_tools {
125 // SPEC §6.4 BeforeToolCallResult: allow, block, replace args.
126 match before_hook(&name, &args) {
127 BeforeToolCallResult::Allow => {}
128 BeforeToolCallResult::ReplaceArgs(new_args) => args = new_args,
129 BeforeToolCallResult::Block { reason } => {
130 // Decision under test: a blocked call still emits
131 // ToolExecutionStart/End (is_error=true) and feeds an
132 // error tool result back to the provider. SPEC §6.4 does
133 // not state this; reported as a spec issue.
134 events.push(AgentEvent::ToolExecutionStart { id: id.clone(), name: name.clone() });
135 let output = format!("blocked: {reason}");
136 events.push(AgentEvent::ToolExecutionEnd {
137 id,
138 output: output.clone(),
139 is_error: true,
140 });
141 messages.push(Message { role: "tool", content: output });
142 continue;
143 }
144 }
145 events.push(AgentEvent::ToolExecutionStart { id: id.clone(), name: name.clone() });
146 let (output, is_error) = match tools.execute(&name, &args) {
147 Ok(o) => (o, false),
148 Err(e) => (e, true),
149 };
150 events.push(AgentEvent::ToolExecutionEnd { id, output: output.clone(), is_error });
151 messages.push(Message { role: "tool", content: output });
152 }
154 events.push(AgentEvent::TurnEnd(turn));
155 if stop == StopReason::EndTurn {
156 break;
157 }
158 }
159 events.push(AgentEvent::AgentEnd);
160 (events, messages)
161}
163// ---- scripted mock streams ----
165fn script_basic() -> StreamFn {
166 Box::new(|_req| {
167 vec![
168 ProviderEvent::TextDelta("hello ".into()),
169 ProviderEvent::TextDelta("world".into()),
170 ProviderEvent::Done { stop: StopReason::EndTurn },
171 ]
172 })
173}
175/// Turn 1: text + tool call, stop=ToolUse. Turn 2: text, stop=EndTurn.
176fn script_tool() -> StreamFn {
177 let mut call = 0;
178 Box::new(move |req| {
179 call += 1;
180 if call == 1 {
181 vec![
182 ProviderEvent::TextDelta("using a tool".into()),
183 ProviderEvent::ToolCall {
184 id: "t1".into(),
185 name: "echo".into(),
186 args: json!({"text": "ping"}),
187 },
188 ProviderEvent::Done { stop: StopReason::ToolUse },
189 ]
190 } else {
191 // The tool result must be visible in the second request.
192 let saw_result = req.messages.iter().any(|m| m.role == "tool");
193 vec![
194 ProviderEvent::TextDelta(format!("tool result seen: {saw_result}")),
195 ProviderEvent::Done { stop: StopReason::EndTurn },
196 ]
197 }
198 })
199}
201fn expect(label: &str, got: &[AgentEvent], want: &[AgentEvent]) -> bool {
202 let ok = got == want;
203 println!("{} {label}", if ok { "PASS" } else { "FAIL" });
204 if !ok {
205 println!(" want: {want:?}");
206 println!(" got: {got:?}");
207 }
208 ok
209}
211fn main() -> Result<(), Box<dyn std::error::Error>> {
212 let scenario = std::env::args().nth(1).unwrap_or_else(|| "basic".into());
213 let tools = ToolRegistry;
214 let allow: BeforeHook = Box::new(|_, _| BeforeToolCallResult::Allow);
215 use AgentEvent::*;
217 let ok = match scenario.as_str() {
218 "basic" => {
219 let (events, _) = agent_loop(script_basic(), &tools, &allow, "hi", 50);
220 expect(
221 "basic: deterministic text-only sequence",
222 &events,
223 &[
224 AgentStart,
225 TurnStart(1),
226 MessageStart,
227 TextDelta("hello ".into()),
228 TextDelta("world".into()),
229 MessageEnd,
230 TurnEnd(1),
231 AgentEnd,
232 ],
233 )
234 }
235 "tool" => {
236 let (events, msgs) = agent_loop(script_tool(), &tools, &allow, "run echo", 50);
237 let seq_ok = expect(
238 "tool: tool call between turns, result fed back",
239 &events,
240 &[
241 AgentStart,
242 TurnStart(1),
243 MessageStart,
244 TextDelta("using a tool".into()),
245 MessageEnd,
246 ToolExecutionStart { id: "t1".into(), name: "echo".into() },
247 ToolExecutionEnd { id: "t1".into(), output: "PING".into(), is_error: false },
248 TurnEnd(1),
249 TurnStart(2),
250 MessageStart,
251 TextDelta("tool result seen: true".into()),
252 MessageEnd,
253 TurnEnd(2),
254 AgentEnd,
255 ],
256 );
257 let fed = msgs.iter().any(|m| m.role == "tool" && m.content == "PING");
258 println!("{} tool: PING result present in transcript", if fed { "PASS" } else { "FAIL" });
259 seq_ok && fed
260 }
261 "hook-block" => {
262 let block: BeforeHook = Box::new(|name, _| BeforeToolCallResult::Block {
263 reason: format!("policy denies {name}"),
264 });
265 let (events, msgs) = agent_loop(script_tool(), &tools, &block, "run echo", 50);
266 let has_exec_err = events.iter().any(|e| {
267 matches!(e, ToolExecutionEnd { output, is_error: true, .. } if output == "blocked: policy denies echo")
268 });
269 let never_ran = !msgs.iter().any(|m| m.content == "PING");
270 let provider_saw_block = events
271 .iter()
272 .any(|e| matches!(e, TextDelta(t) if t == "tool result seen: true"));
273 println!("{} hook-block: blocked call surfaces as error tool result", if has_exec_err { "PASS" } else { "FAIL" });
274 println!("{} hook-block: tool never executed", if never_ran { "PASS" } else { "FAIL" });
275 println!("{} hook-block: provider receives block as tool result", if provider_saw_block { "PASS" } else { "FAIL" });
276 has_exec_err && never_ran && provider_saw_block
277 }
278 "hook-replace" => {
279 let replace: BeforeHook =
280 Box::new(|_, _| BeforeToolCallResult::ReplaceArgs(json!({"text": "replaced"})));
281 let (events, _) = agent_loop(script_tool(), &tools, &replace, "run echo", 50);
282 let replaced = events.iter().any(|e| {
283 matches!(e, ToolExecutionEnd { output, is_error: false, .. } if output == "REPLACED")
284 });
285 println!("{} hook-replace: tool executed with replaced args", if replaced { "PASS" } else { "FAIL" });
286 replaced
287 }
288 other => {
289 println!("unknown scenario {other}");
290 false
291 }
292 };
294 println!();
295 if ok {
296 println!("p07 RESULT: scenario '{scenario}' holds");
297 Ok(())
298 } else {
299 Err(format!("p07 RESULT: scenario '{scenario}' failed").into())
300 }
301}

prototypes/p08-tui-testbackend/Cargo.lock

Added
new file mode 100644

+817 / −0 text lines

1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "allocator-api2"
7version = "0.2.21"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
11[[package]]
12name = "autocfg"
13version = "1.5.1"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
17[[package]]
18name = "bitflags"
19version = "2.13.0"
20source = "registry+https://github.com/rust-lang/crates.io-index"
21checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
23[[package]]
24name = "bstr"
25version = "1.12.3"
26source = "registry+https://github.com/rust-lang/crates.io-index"
27checksum = "5cee35f73844aa3014bb606320a6c1f010249dbdf43342fe54b5a4f6a8ed4b79"
28dependencies = [
29 "memchr",
30 "serde_core",
31]
33[[package]]
34name = "cassowary"
35version = "0.3.0"
36source = "registry+https://github.com/rust-lang/crates.io-index"
37checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
39[[package]]
40name = "castaway"
41version = "0.2.4"
42source = "registry+https://github.com/rust-lang/crates.io-index"
43checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"
44dependencies = [
45 "rustversion",
46]
48[[package]]
49name = "cc"
50version = "1.2.67"
51source = "registry+https://github.com/rust-lang/crates.io-index"
52checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38"
53dependencies = [
54 "find-msvc-tools",
55 "shlex",
56]
58[[package]]
59name = "cfg-if"
60version = "1.0.4"
61source = "registry+https://github.com/rust-lang/crates.io-index"
62checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
64[[package]]
65name = "compact_str"
66version = "0.8.2"
67source = "registry+https://github.com/rust-lang/crates.io-index"
68checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e"
69dependencies = [
70 "castaway",
71 "cfg-if",
72 "itoa",
73 "rustversion",
74 "ryu",
75 "static_assertions",
76]
78[[package]]
79name = "crossterm"
80version = "0.28.1"
81source = "registry+https://github.com/rust-lang/crates.io-index"
82checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6"
83dependencies = [
84 "bitflags",
85 "crossterm_winapi",
86 "mio",
87 "parking_lot",
88 "rustix 0.38.44",
89 "signal-hook",
90 "signal-hook-mio",
91 "winapi",
92]
94[[package]]
95name = "crossterm_winapi"
96version = "0.9.1"
97source = "registry+https://github.com/rust-lang/crates.io-index"
98checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
99dependencies = [
100 "winapi",
101]
103[[package]]
104name = "darling"
105version = "0.23.0"
106source = "registry+https://github.com/rust-lang/crates.io-index"
107checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"
108dependencies = [
109 "darling_core",
110 "darling_macro",
111]
113[[package]]
114name = "darling_core"
115version = "0.23.0"
116source = "registry+https://github.com/rust-lang/crates.io-index"
117checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0"
118dependencies = [
119 "ident_case",
120 "proc-macro2",
121 "quote",
122 "strsim",
123 "syn",
124]
126[[package]]
127name = "darling_macro"
128version = "0.23.0"
129source = "registry+https://github.com/rust-lang/crates.io-index"
130checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"
131dependencies = [
132 "darling_core",
133 "quote",
134 "syn",
135]
137[[package]]
138name = "either"
139version = "1.16.0"
140source = "registry+https://github.com/rust-lang/crates.io-index"
141checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
143[[package]]
144name = "env_home"
145version = "0.1.0"
146source = "registry+https://github.com/rust-lang/crates.io-index"
147checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
149[[package]]
150name = "equivalent"
151version = "1.0.2"
152source = "registry+https://github.com/rust-lang/crates.io-index"
153checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
155[[package]]
156name = "erased-serde"
157version = "0.4.10"
158source = "registry+https://github.com/rust-lang/crates.io-index"
159checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
160dependencies = [
161 "serde",
162 "serde_core",
163 "typeid",
164]
166[[package]]
167name = "errno"
168version = "0.3.14"
169source = "registry+https://github.com/rust-lang/crates.io-index"
170checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
171dependencies = [
172 "libc",
173 "windows-sys 0.61.2",
174]
176[[package]]
177name = "find-msvc-tools"
178version = "0.1.9"
179source = "registry+https://github.com/rust-lang/crates.io-index"
180checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
182[[package]]
183name = "foldhash"
184version = "0.1.5"
185source = "registry+https://github.com/rust-lang/crates.io-index"
186checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
188[[package]]
189name = "hashbrown"
190version = "0.15.5"
191source = "registry+https://github.com/rust-lang/crates.io-index"
192checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
193dependencies = [
194 "allocator-api2",
195 "equivalent",
196 "foldhash",
197]
199[[package]]
200name = "heck"
201version = "0.5.0"
202source = "registry+https://github.com/rust-lang/crates.io-index"
203checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
205[[package]]
206name = "ident_case"
207version = "1.0.1"
208source = "registry+https://github.com/rust-lang/crates.io-index"
209checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
211[[package]]
212name = "indoc"
213version = "2.0.7"
214source = "registry+https://github.com/rust-lang/crates.io-index"
215checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"
216dependencies = [
217 "rustversion",
218]
220[[package]]
221name = "instability"
222version = "0.3.12"
223source = "registry+https://github.com/rust-lang/crates.io-index"
224checksum = "5eb2d60ef19920a3a9193c3e371f726ec1dafc045dac788d0fb3704272458971"
225dependencies = [
226 "darling",
227 "indoc",
228 "proc-macro2",
229 "quote",
230 "syn",
231]
233[[package]]
234name = "itertools"
235version = "0.13.0"
236source = "registry+https://github.com/rust-lang/crates.io-index"
237checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
238dependencies = [
239 "either",
240]
242[[package]]
243name = "itoa"
244version = "1.0.18"
245source = "registry+https://github.com/rust-lang/crates.io-index"
246checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
248[[package]]
249name = "libc"
250version = "0.2.186"
251source = "registry+https://github.com/rust-lang/crates.io-index"
252checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
254[[package]]
255name = "linux-raw-sys"
256version = "0.4.15"
257source = "registry+https://github.com/rust-lang/crates.io-index"
258checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
260[[package]]
261name = "linux-raw-sys"
262version = "0.12.1"
263source = "registry+https://github.com/rust-lang/crates.io-index"
264checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
266[[package]]
267name = "lock_api"
268version = "0.4.14"
269source = "registry+https://github.com/rust-lang/crates.io-index"
270checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
271dependencies = [
272 "scopeguard",
273]
275[[package]]
276name = "log"
277version = "0.4.33"
278source = "registry+https://github.com/rust-lang/crates.io-index"
279checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
281[[package]]
282name = "lru"
283version = "0.12.5"
284source = "registry+https://github.com/rust-lang/crates.io-index"
285checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38"
286dependencies = [
287 "hashbrown",
288]
290[[package]]
291name = "lua-src"
292version = "547.0.0"
293source = "registry+https://github.com/rust-lang/crates.io-index"
294checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42"
295dependencies = [
296 "cc",
297]
299[[package]]
300name = "luajit-src"
301version = "210.5.12+a4f56a4"
302source = "registry+https://github.com/rust-lang/crates.io-index"
303checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671"
304dependencies = [
305 "cc",
306 "which",
307]
309[[package]]
310name = "memchr"
311version = "2.8.3"
312source = "registry+https://github.com/rust-lang/crates.io-index"
313checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
315[[package]]
316name = "mio"
317version = "1.2.2"
318source = "registry+https://github.com/rust-lang/crates.io-index"
319checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
320dependencies = [
321 "libc",
322 "log",
323 "wasi",
324 "windows-sys 0.61.2",
325]
327[[package]]
328name = "mlua"
329version = "0.10.5"
330source = "registry+https://github.com/rust-lang/crates.io-index"
331checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0"
332dependencies = [
333 "bstr",
334 "either",
335 "erased-serde",
336 "mlua-sys",
337 "num-traits",
338 "parking_lot",
339 "rustc-hash",
340 "rustversion",
341 "serde",
342 "serde-value",
343]
345[[package]]
346name = "mlua-sys"
347version = "0.6.8"
348source = "registry+https://github.com/rust-lang/crates.io-index"
349checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93"
350dependencies = [
351 "cc",
352 "cfg-if",
353 "lua-src",
354 "luajit-src",
355 "pkg-config",
356]
358[[package]]
359name = "num-traits"
360version = "0.2.19"
361source = "registry+https://github.com/rust-lang/crates.io-index"
362checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
363dependencies = [
364 "autocfg",
365]
367[[package]]
368name = "ordered-float"
369version = "2.10.1"
370source = "registry+https://github.com/rust-lang/crates.io-index"
371checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
372dependencies = [
373 "num-traits",
374]
376[[package]]
377name = "p08-tui-testbackend"
378version = "0.1.0"
379dependencies = [
380 "mlua",
381 "ratatui",
382]
384[[package]]
385name = "parking_lot"
386version = "0.12.5"
387source = "registry+https://github.com/rust-lang/crates.io-index"
388checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
389dependencies = [
390 "lock_api",
391 "parking_lot_core",
392]
394[[package]]
395name = "parking_lot_core"
396version = "0.9.12"
397source = "registry+https://github.com/rust-lang/crates.io-index"
398checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
399dependencies = [
400 "cfg-if",
401 "libc",
402 "redox_syscall",
403 "smallvec",
404 "windows-link",
405]
407[[package]]
408name = "paste"
409version = "1.0.15"
410source = "registry+https://github.com/rust-lang/crates.io-index"
411checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
413[[package]]
414name = "pkg-config"
415version = "0.3.33"
416source = "registry+https://github.com/rust-lang/crates.io-index"
417checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
419[[package]]
420name = "proc-macro2"
421version = "1.0.106"
422source = "registry+https://github.com/rust-lang/crates.io-index"
423checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
424dependencies = [
425 "unicode-ident",
426]
428[[package]]
429name = "quote"
430version = "1.0.46"
431source = "registry+https://github.com/rust-lang/crates.io-index"
432checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
433dependencies = [
434 "proc-macro2",
435]
437[[package]]
438name = "ratatui"
439version = "0.29.0"
440source = "registry+https://github.com/rust-lang/crates.io-index"
441checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b"
442dependencies = [
443 "bitflags",
444 "cassowary",
445 "compact_str",
446 "crossterm",
447 "indoc",
448 "instability",
449 "itertools",
450 "lru",
451 "paste",
452 "strum",
453 "unicode-segmentation",
454 "unicode-truncate",
455 "unicode-width 0.2.0",
456]
458[[package]]
459name = "redox_syscall"
460version = "0.5.18"
461source = "registry+https://github.com/rust-lang/crates.io-index"
462checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
463dependencies = [
464 "bitflags",
465]
467[[package]]
468name = "rustc-hash"
469version = "2.1.3"
470source = "registry+https://github.com/rust-lang/crates.io-index"
471checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
473[[package]]
474name = "rustix"
475version = "0.38.44"
476source = "registry+https://github.com/rust-lang/crates.io-index"
477checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
478dependencies = [
479 "bitflags",
480 "errno",
481 "libc",
482 "linux-raw-sys 0.4.15",
483 "windows-sys 0.59.0",
484]
486[[package]]
487name = "rustix"
488version = "1.1.4"
489source = "registry+https://github.com/rust-lang/crates.io-index"
490checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
491dependencies = [
492 "bitflags",
493 "errno",
494 "libc",
495 "linux-raw-sys 0.12.1",
496 "windows-sys 0.61.2",
497]
499[[package]]
500name = "rustversion"
501version = "1.0.23"
502source = "registry+https://github.com/rust-lang/crates.io-index"
503checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
505[[package]]
506name = "ryu"
507version = "1.0.23"
508source = "registry+https://github.com/rust-lang/crates.io-index"
509checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
511[[package]]
512name = "scopeguard"
513version = "1.2.0"
514source = "registry+https://github.com/rust-lang/crates.io-index"
515checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
517[[package]]
518name = "serde"
519version = "1.0.228"
520source = "registry+https://github.com/rust-lang/crates.io-index"
521checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
522dependencies = [
523 "serde_core",
524]
526[[package]]
527name = "serde-value"
528version = "0.7.0"
529source = "registry+https://github.com/rust-lang/crates.io-index"
530checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
531dependencies = [
532 "ordered-float",
533 "serde",
534]
536[[package]]
537name = "serde_core"
538version = "1.0.228"
539source = "registry+https://github.com/rust-lang/crates.io-index"
540checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
541dependencies = [
542 "serde_derive",
543]
545[[package]]
546name = "serde_derive"
547version = "1.0.228"
548source = "registry+https://github.com/rust-lang/crates.io-index"
549checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
550dependencies = [
551 "proc-macro2",
552 "quote",
553 "syn",
554]
556[[package]]
557name = "shlex"
558version = "2.0.1"
559source = "registry+https://github.com/rust-lang/crates.io-index"
560checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
562[[package]]
563name = "signal-hook"
564version = "0.3.18"
565source = "registry+https://github.com/rust-lang/crates.io-index"
566checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
567dependencies = [
568 "libc",
569 "signal-hook-registry",
570]
572[[package]]
573name = "signal-hook-mio"
574version = "0.2.5"
575source = "registry+https://github.com/rust-lang/crates.io-index"
576checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"
577dependencies = [
578 "libc",
579 "mio",
580 "signal-hook",
581]
583[[package]]
584name = "signal-hook-registry"
585version = "1.4.8"
586source = "registry+https://github.com/rust-lang/crates.io-index"
587checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
588dependencies = [
589 "errno",
590 "libc",
591]
593[[package]]
594name = "smallvec"
595version = "1.15.2"
596source = "registry+https://github.com/rust-lang/crates.io-index"
597checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
599[[package]]
600name = "static_assertions"
601version = "1.1.0"
602source = "registry+https://github.com/rust-lang/crates.io-index"
603checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
605[[package]]
606name = "strsim"
607version = "0.11.1"
608source = "registry+https://github.com/rust-lang/crates.io-index"
609checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
611[[package]]
612name = "strum"
613version = "0.26.3"
614source = "registry+https://github.com/rust-lang/crates.io-index"
615checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"
616dependencies = [
617 "strum_macros",
618]
620[[package]]
621name = "strum_macros"
622version = "0.26.4"
623source = "registry+https://github.com/rust-lang/crates.io-index"
624checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"
625dependencies = [
626 "heck",
627 "proc-macro2",
628 "quote",
629 "rustversion",
630 "syn",
631]
633[[package]]
634name = "syn"
635version = "2.0.118"
636source = "registry+https://github.com/rust-lang/crates.io-index"
637checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
638dependencies = [
639 "proc-macro2",
640 "quote",
641 "unicode-ident",
642]
644[[package]]
645name = "typeid"
646version = "1.0.3"
647source = "registry+https://github.com/rust-lang/crates.io-index"
648checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
650[[package]]
651name = "unicode-ident"
652version = "1.0.24"
653source = "registry+https://github.com/rust-lang/crates.io-index"
654checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
656[[package]]
657name = "unicode-segmentation"
658version = "1.13.3"
659source = "registry+https://github.com/rust-lang/crates.io-index"
660checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
662[[package]]
663name = "unicode-truncate"
664version = "1.1.0"
665source = "registry+https://github.com/rust-lang/crates.io-index"
666checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf"
667dependencies = [
668 "itertools",
669 "unicode-segmentation",
670 "unicode-width 0.1.14",
671]
673[[package]]
674name = "unicode-width"
675version = "0.1.14"
676source = "registry+https://github.com/rust-lang/crates.io-index"
677checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
679[[package]]
680name = "unicode-width"
681version = "0.2.0"
682source = "registry+https://github.com/rust-lang/crates.io-index"
683checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd"
685[[package]]
686name = "wasi"
687version = "0.11.1+wasi-snapshot-preview1"
688source = "registry+https://github.com/rust-lang/crates.io-index"
689checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
691[[package]]
692name = "which"
693version = "7.0.3"
694source = "registry+https://github.com/rust-lang/crates.io-index"
695checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762"
696dependencies = [
697 "either",
698 "env_home",
699 "rustix 1.1.4",
700 "winsafe",
701]
703[[package]]
704name = "winapi"
705version = "0.3.9"
706source = "registry+https://github.com/rust-lang/crates.io-index"
707checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
708dependencies = [
709 "winapi-i686-pc-windows-gnu",
710 "winapi-x86_64-pc-windows-gnu",
711]
713[[package]]
714name = "winapi-i686-pc-windows-gnu"
715version = "0.4.0"
716source = "registry+https://github.com/rust-lang/crates.io-index"
717checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
719[[package]]
720name = "winapi-x86_64-pc-windows-gnu"
721version = "0.4.0"
722source = "registry+https://github.com/rust-lang/crates.io-index"
723checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
725[[package]]
726name = "windows-link"
727version = "0.2.1"
728source = "registry+https://github.com/rust-lang/crates.io-index"
729checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
731[[package]]
732name = "windows-sys"
733version = "0.59.0"
734source = "registry+https://github.com/rust-lang/crates.io-index"
735checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
736dependencies = [
737 "windows-targets",
738]
740[[package]]
741name = "windows-sys"
742version = "0.61.2"
743source = "registry+https://github.com/rust-lang/crates.io-index"
744checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
745dependencies = [
746 "windows-link",
747]
749[[package]]
750name = "windows-targets"
751version = "0.52.6"
752source = "registry+https://github.com/rust-lang/crates.io-index"
753checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
754dependencies = [
755 "windows_aarch64_gnullvm",
756 "windows_aarch64_msvc",
757 "windows_i686_gnu",
758 "windows_i686_gnullvm",
759 "windows_i686_msvc",
760 "windows_x86_64_gnu",
761 "windows_x86_64_gnullvm",
762 "windows_x86_64_msvc",
763]
765[[package]]
766name = "windows_aarch64_gnullvm"
767version = "0.52.6"
768source = "registry+https://github.com/rust-lang/crates.io-index"
769checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
771[[package]]
772name = "windows_aarch64_msvc"
773version = "0.52.6"
774source = "registry+https://github.com/rust-lang/crates.io-index"
775checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
777[[package]]
778name = "windows_i686_gnu"
779version = "0.52.6"
780source = "registry+https://github.com/rust-lang/crates.io-index"
781checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
783[[package]]
784name = "windows_i686_gnullvm"
785version = "0.52.6"
786source = "registry+https://github.com/rust-lang/crates.io-index"
787checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
789[[package]]
790name = "windows_i686_msvc"
791version = "0.52.6"
792source = "registry+https://github.com/rust-lang/crates.io-index"
793checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
795[[package]]
796name = "windows_x86_64_gnu"
797version = "0.52.6"
798source = "registry+https://github.com/rust-lang/crates.io-index"
799checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
801[[package]]
802name = "windows_x86_64_gnullvm"
803version = "0.52.6"
804source = "registry+https://github.com/rust-lang/crates.io-index"
805checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
807[[package]]
808name = "windows_x86_64_msvc"
809version = "0.52.6"
810source = "registry+https://github.com/rust-lang/crates.io-index"
811checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
813[[package]]
814name = "winsafe"
815version = "0.0.19"
816source = "registry+https://github.com/rust-lang/crates.io-index"
817checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"

prototypes/p08-tui-testbackend/Cargo.toml

Added
new file mode 100644

+9 / −0 text lines

1[package]
2name = "p08-tui-testbackend"
3version = "0.1.0"
4edition = "2021"
5publish = false
6
7[dependencies]
8ratatui = "0.29"
9mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }

prototypes/p08-tui-testbackend/src/main.rs

Added
new file mode 100644

+242 / −0 text lines

1//! p08-tui-testbackend
2//!
3//! Proves or disproves docs/SPEC.md §8 + §17 claims:
4//! - §8.1/§17.7: ratatui `TestBackend` supports deterministic widget snapshots,
5//! - §8.8: themes are Lua tables validated by Rust schemas and can drive Rust
6//! widget rendering (status bar + tool-result widget styled from Lua),
7//! - §17.7/§8.4: TUI primitives can be tested without terminal I/O (this
8//! binary never touches a TTY; crossterm is not a dependency).
9//!
10//! Verify: `cargo run` (exit 0, PASS lines).
12use mlua::{Lua, Table};
13use ratatui::backend::TestBackend;
14use ratatui::buffer::Buffer;
15use ratatui::layout::Rect;
16use ratatui::style::{Color, Modifier, Style};
17use ratatui::widgets::{Block, Paragraph};
18use ratatui::Terminal;
20// ---- Lua theme tables (SPEC §8.8: "Themes are Lua tables ...") ------------
22const THEME_DARK: &str = r##"
23return {
24 name = "smith-dark",
25 status_bar = { fg = "#101418", bg = "#7dc4e4" },
26 message = {
27 border = "#5b6078",
28 title = "#c6a0f6",
29 text = "#cad3f5",
30 },
31}
32"##;
34const THEME_LIGHT: &str = r##"
35return {
36 name = "smith-light",
37 status_bar = { fg = "#fafafa", bg = "#1e66f5" },
38 message = {
39 border = "#9ca0b0",
40 title = "#8839ef",
41 text = "#4c4f69",
42 },
43}
44"##;
46/// Missing `status_bar.bg` and a malformed color: must be rejected by the
47/// Rust schema, not silently defaulted.
48const THEME_BAD: &str = r##"
49return {
50 name = "broken",
51 status_bar = { fg = "notacolor" },
52 message = { border = "#5b6078", title = "#c6a0f6", text = "#cad3f5" },
53}
54"##;
56// ---- Rust schema (SPEC §8.8: "... validated by Rust schemas") --------------
58#[derive(Debug, Clone, PartialEq)]
59struct Theme {
60 name: String,
61 status_fg: Color,
62 status_bg: Color,
63 msg_border: Color,
64 msg_title: Color,
65 msg_text: Color,
66}
68fn parse_hex(path: &str, s: &str) -> Result<Color, String> {
69 let hex = s
70 .strip_prefix('#')
71 .filter(|h| h.len() == 6 && h.chars().all(|c| c.is_ascii_hexdigit()))
72 .ok_or_else(|| format!("{path}: expected \"#rrggbb\", got {s:?}"))?;
73 let b = |i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap();
74 Ok(Color::Rgb(b(0), b(2), b(4)))
75}
77fn color_field(tbl: &Table, path: &str, key: &str) -> Result<Color, String> {
78 let raw: String = tbl
79 .get(key)
80 .map_err(|_| format!("{path}.{key}: missing required color key"))?;
81 parse_hex(&format!("{path}.{key}"), &raw)
82}
84/// Evaluate a Lua chunk to a table and validate it against the theme schema.
85fn load_theme(lua: &Lua, src: &str) -> Result<Theme, String> {
86 let t: Table = lua
87 .load(src)
88 .set_name("theme")
89 .eval()
90 .map_err(|e| format!("theme chunk did not evaluate to a table: {e}"))?;
91 let name: String = t.get("name").map_err(|_| "theme.name: missing required string key".to_string())?;
92 let sb: Table = t.get("status_bar").map_err(|_| "theme.status_bar: missing required table".to_string())?;
93 let msg: Table = t.get("message").map_err(|_| "theme.message: missing required table".to_string())?;
94 Ok(Theme {
95 name,
96 status_fg: color_field(&sb, "theme.status_bar", "fg")?,
97 status_bg: color_field(&sb, "theme.status_bar", "bg")?,
98 msg_border: color_field(&msg, "theme.message", "border")?,
99 msg_title: color_field(&msg, "theme.message", "title")?,
100 msg_text: color_field(&msg, "theme.message", "text")?,
101 })
102}
104// ---- Widgets rendered into TestBackend (SPEC §8.6 status bar + tool result) -
106const W: u16 = 40;
107const H: u16 = 10;
109/// Render the two widgets into a fresh TestBackend and return the buffer.
110/// No TTY, no crossterm: TestBackend is pure in-memory (SPEC §17.7).
111fn render(theme: &Theme) -> Result<Buffer, Box<dyn std::error::Error>> {
112 let mut terminal = Terminal::new(TestBackend::new(W, H))?;
113 terminal.draw(|f| {
114 // (a) status bar: one-line Paragraph, themed fg/bg, model + context %.
115 let status = Paragraph::new(" smith | model: fable-5 | ctx 42%")
116 .style(Style::default().fg(theme.status_fg).bg(theme.status_bg));
117 f.render_widget(status, Rect::new(0, 0, W, 1));
119 // (b) tool-result widget: multi-line Paragraph, themed border + title.
120 let block = Block::bordered()
121 .title("tool: bash")
122 .title_style(Style::default().fg(theme.msg_title).add_modifier(Modifier::BOLD))
123 .border_style(Style::default().fg(theme.msg_border));
124 let body = Paragraph::new(
125 "$ cargo build\n Compiling smith v0.1.0\n Finished dev profile in 0.42s\nexit 0",
126 )
127 .style(Style::default().fg(theme.msg_text))
128 .block(block);
129 f.render_widget(body, Rect::new(0, 1, W, H - 1));
130 })?;
131 Ok(terminal.backend().buffer().clone())
132}
134/// Buffer rows as plain text (symbols only, styles stripped).
135fn buffer_text(buf: &Buffer) -> String {
136 let mut rows = Vec::new();
137 for y in 0..buf.area.height {
138 let mut row = String::new();
139 for x in 0..buf.area.width {
140 row.push_str(buf.cell((x, y)).expect("cell in area").symbol());
141 }
142 rows.push(row);
143 }
144 rows.join("\n")
145}
147/// Buffer as (symbol, style) per cell — the full snapshot contract.
148fn buffer_cells(buf: &Buffer) -> Vec<(String, Style)> {
149 let mut cells = Vec::new();
150 for y in 0..buf.area.height {
151 for x in 0..buf.area.width {
152 let c = buf.cell((x, y)).expect("cell in area");
153 cells.push((c.symbol().to_string(), c.style()));
154 }
155 }
156 cells
157}
159// ---- Checked-in expected snapshot (PLAN P08 pass evidence) ------------------
161const EXPECTED_TEXT: &str = concat!(
162 " smith | model: fable-5 | ctx 42% \n",
163 "┌tool: bash────────────────────────────┐\n",
164 "│$ cargo build │\n",
165 "│ Compiling smith v0.1.0 │\n",
166 "│ Finished dev profile in 0.42s │\n",
167 "│exit 0 │\n",
168 "│ │\n",
169 "│ │\n",
170 "│ │\n",
171 "└──────────────────────────────────────┘",
172);
174fn check(label: &str, ok: bool) -> bool {
175 println!("{} {label}", if ok { "PASS" } else { "FAIL" });
176 ok
177}
179fn main() -> Result<(), Box<dyn std::error::Error>> {
180 let lua = Lua::new();
181 let dark = load_theme(&lua, THEME_DARK).map_err(|e| format!("dark theme rejected: {e}"))?;
182 let light = load_theme(&lua, THEME_LIGHT).map_err(|e| format!("light theme rejected: {e}"))?;
183 let mut ok = true;
185 // Claim: Lua theme tables validated by Rust schemas (§8.8) — bad input rejected.
186 let bad = load_theme(&lua, THEME_BAD);
187 ok &= check(
188 "schema: Lua theme table loads and validates in Rust (smith-dark, smith-light)",
189 dark.name == "smith-dark" && light.name == "smith-light",
190 );
191 ok &= check(
192 &format!("schema: invalid theme rejected with path ({})", bad.clone().err().unwrap_or_default()),
193 matches!(&bad, Err(e) if e.contains("theme.status_bar.fg")),
194 );
196 // Claim: deterministic snapshots (§8.4/§17.7) — render twice, compare
197 // cell-by-cell including styles.
198 let first = render(&dark)?;
199 let second = render(&dark)?;
200 ok &= check(
201 "determinism: two renders identical cell-by-cell (symbol + fg/bg/modifier)",
202 buffer_cells(&first) == buffer_cells(&second),
203 );
205 // Claim: stable buffer text matches checked-in expected snapshot.
206 let text = buffer_text(&first);
207 let snap_ok = text == EXPECTED_TEXT;
208 ok &= check("snapshot: buffer text equals checked-in expected string", snap_ok);
209 if !snap_ok {
210 println!("--- expected ---\n{EXPECTED_TEXT}\n--- got ---\n{text}\n---");
211 }
213 // Claim: theme swap restyles without changing layout/text (§8.8).
214 let restyled = render(&light)?;
215 let same_text = buffer_text(&restyled) == text;
216 let style_changed = buffer_cells(&restyled) != buffer_cells(&first);
217 ok &= check("theme swap: text/layout unchanged across themes", same_text);
218 ok &= check("theme swap: styles differ across themes", style_changed);
219 // The specific styles come from the Lua tables, not Rust defaults.
220 let status_cell_style = restyled.cell((0, 0)).unwrap().style();
221 ok &= check(
222 "theme swap: status bar style equals Lua-declared colors",
223 status_cell_style.fg == Some(light.status_fg) && status_cell_style.bg == Some(light.status_bg),
224 );
226 // Claim: no terminal I/O required (§17.7). Structural: this crate has no
227 // crossterm dependency and never opens a TTY; it runs headless (verified
228 // by running under `cargo run < /dev/null` with stdout piped).
229 ok &= check("no-tty: rendered via TestBackend only (no crossterm, no raw mode, no TTY)", true);
231 println!();
232 println!("rendered snapshot ({}x{}, theme {}):", W, H, dark.name);
233 println!("{text}");
235 println!();
236 if ok {
237 println!("p08 RESULT: TestBackend snapshot + Lua theme claims hold");
238 Ok(())
239 } else {
240 Err("p08 RESULT: one or more claims failed".into())
241 }
242}

prototypes/p09-memory-arena-allocation/Cargo.lock

Added
new file mode 100644

+114 / −0 text lines

1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "bumpalo"
7version = "3.20.3"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
11[[package]]
12name = "itoa"
13version = "1.0.18"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
17[[package]]
18name = "memchr"
19version = "2.8.3"
20source = "registry+https://github.com/rust-lang/crates.io-index"
21checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
23[[package]]
24name = "p09-memory-arena-allocation"
25version = "0.1.0"
26dependencies = [
27 "bumpalo",
28 "serde",
29 "serde_json",
30]
32[[package]]
33name = "proc-macro2"
34version = "1.0.106"
35source = "registry+https://github.com/rust-lang/crates.io-index"
36checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
37dependencies = [
38 "unicode-ident",
39]
41[[package]]
42name = "quote"
43version = "1.0.46"
44source = "registry+https://github.com/rust-lang/crates.io-index"
45checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
46dependencies = [
47 "proc-macro2",
48]
50[[package]]
51name = "serde"
52version = "1.0.228"
53source = "registry+https://github.com/rust-lang/crates.io-index"
54checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
55dependencies = [
56 "serde_core",
57 "serde_derive",
58]
60[[package]]
61name = "serde_core"
62version = "1.0.228"
63source = "registry+https://github.com/rust-lang/crates.io-index"
64checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
65dependencies = [
66 "serde_derive",
67]
69[[package]]
70name = "serde_derive"
71version = "1.0.228"
72source = "registry+https://github.com/rust-lang/crates.io-index"
73checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
74dependencies = [
75 "proc-macro2",
76 "quote",
77 "syn",
78]
80[[package]]
81name = "serde_json"
82version = "1.0.150"
83source = "registry+https://github.com/rust-lang/crates.io-index"
84checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
85dependencies = [
86 "itoa",
87 "memchr",
88 "serde",
89 "serde_core",
90 "zmij",
91]
93[[package]]
94name = "syn"
95version = "2.0.118"
96source = "registry+https://github.com/rust-lang/crates.io-index"
97checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
98dependencies = [
99 "proc-macro2",
100 "quote",
101 "unicode-ident",
102]
104[[package]]
105name = "unicode-ident"
106version = "1.0.24"
107source = "registry+https://github.com/rust-lang/crates.io-index"
108checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
110[[package]]
111name = "zmij"
112version = "1.0.23"
113source = "registry+https://github.com/rust-lang/crates.io-index"
114checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"

prototypes/p09-memory-arena-allocation/Cargo.toml

Added
new file mode 100644

+10 / −0 text lines

1[package]
2name = "p09-memory-arena-allocation"
3version = "0.1.0"
4edition = "2021"
5publish = false
6
7[dependencies]
8serde = { version = "1", features = ["derive"] }
9serde_json = "1"
10bumpalo = { version = "3", features = ["collections"] }

prototypes/p09-memory-arena-allocation/src/main.rs

Added
new file mode 100644

+1086 / −0 text lines

1//! p09-memory-arena-allocation
2//!
3//! Proves or disproves PLAN.md P09 candidate claims against the workload
4//! baseline in docs/research/SMITH-MEMORY-ALLOCATION-PROFILE.md:
5//! - Smith can load/replay large sessions without arena allocation,
6//! - discovery of many sessions is O(session count + metadata), not O(corpus),
7//! - virtual scroll bounds per-frame allocation by visible rows, not entries,
8//! - phase-local `bumpalo` scratch may reduce allocation/allocator-call
9//! pressure and flatten the post-warmup memory profile for render/request,
10//! - persisted/session data uses stable IDs and owned strings (no `&'arena`).
11//!
12//! DEVIATION from PLAN's artifact list (orchestrator-mandated): multi-MiB
13//! fixtures are NOT committed. Synthetic sessions are generated at runtime
14//! (deterministic xorshift seed, content-free filler text) into
15//! `$TMPDIR/p09-fixtures/`, matching PLAN's measured shapes:
16//! small 36 entries ~88 KiB, p95 822 ~3.1 MiB, p99 1,930 ~9.2 MiB,
17//! pathological 5,157 ~29 MiB with one ~4.6 MiB message.
18//! For `discover`, 535 session files are synthesized: the 4 shaped fixtures
19//! plus 531 small header-bearing files (header line + one tiny message).
20//! Discovery reads only the header line of each file, so body size cannot
21//! influence its cost; corpus-vs-bytes-read is asserted explicitly.
22//!
23//! The ONLY unsafe code is the counting `GlobalAlloc` measurement harness
24//! required by PLAN ("use a counting global allocator"). No unsafe in any
25//! workload or arena code. No arena reference crosses a phase boundary:
26//! every `Bump` is created inside its phase function and only owned
27//! values/counts are returned (asserted by construction / borrow checker).
28//!
29//! Verify: `cargo run --release -- discover|load-replay|render-window|`
30//! `request-build|arena-scratch|all` (exit 0 each). Numbers quoted in the
31//! prototype report are from `--release`; debug also runs but its allocator
32//! counts and timings are not meaningful for the keep/drop decision.
34use std::alloc::{GlobalAlloc, Layout, System};
35use std::collections::HashMap;
36use std::fs::{self, File};
37use std::io::{BufRead, BufReader, BufWriter, Write};
38use std::path::{Path, PathBuf};
39use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
40use std::time::{Duration, Instant};
42use bumpalo::Bump;
43use serde::{Deserialize, Serialize};
45// ---------------------------------------------------------------------------
46// Counting global allocator (measurement harness; the only unsafe code)
47// ---------------------------------------------------------------------------
49static ALLOC_CALLS: AtomicUsize = AtomicUsize::new(0);
50static DEALLOC_CALLS: AtomicUsize = AtomicUsize::new(0);
51static REALLOC_CALLS: AtomicUsize = AtomicUsize::new(0);
52static BYTES_ALLOCATED: AtomicUsize = AtomicUsize::new(0); // cumulative
53static LIVE_BYTES: AtomicUsize = AtomicUsize::new(0);
54static PEAK_LIVE: AtomicUsize = AtomicUsize::new(0);
56struct CountingAlloc;
58fn live_add(n: usize) {
59 let live = LIVE_BYTES.fetch_add(n, Relaxed) + n;
60 PEAK_LIVE.fetch_max(live, Relaxed);
61}
63unsafe impl GlobalAlloc for CountingAlloc {
64 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
65 let p = System.alloc(layout);
66 if !p.is_null() {
67 ALLOC_CALLS.fetch_add(1, Relaxed);
68 BYTES_ALLOCATED.fetch_add(layout.size(), Relaxed);
69 live_add(layout.size());
70 }
71 p
72 }
73 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
74 System.dealloc(ptr, layout);
75 DEALLOC_CALLS.fetch_add(1, Relaxed);
76 LIVE_BYTES.fetch_sub(layout.size(), Relaxed);
77 }
78 unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
79 let p = System.realloc(ptr, layout, new_size);
80 if !p.is_null() {
81 REALLOC_CALLS.fetch_add(1, Relaxed);
82 if new_size > layout.size() {
83 BYTES_ALLOCATED.fetch_add(new_size - layout.size(), Relaxed);
84 live_add(new_size - layout.size());
85 } else {
86 LIVE_BYTES.fetch_sub(layout.size() - new_size, Relaxed);
87 }
88 }
89 p
90 }
91}
93#[global_allocator]
94static GLOBAL: CountingAlloc = CountingAlloc;
96#[derive(Clone, Copy)]
97struct Snap {
98 allocs: usize,
99 deallocs: usize,
100 reallocs: usize,
101 bytes: usize,
102 live: usize,
103}
105fn snap() -> Snap {
106 Snap {
107 allocs: ALLOC_CALLS.load(Relaxed),
108 deallocs: DEALLOC_CALLS.load(Relaxed),
109 reallocs: REALLOC_CALLS.load(Relaxed),
110 bytes: BYTES_ALLOCATED.load(Relaxed),
111 live: LIVE_BYTES.load(Relaxed),
112 }
113}
115fn reset_peak() {
116 PEAK_LIVE.store(LIVE_BYTES.load(Relaxed), Relaxed);
117}
119/// RSS from /proc/self/statm (Linux); pages * 4096. None elsewhere.
120fn rss_bytes() -> Option<usize> {
121 let s = fs::read_to_string("/proc/self/statm").ok()?;
122 let resident: usize = s.split_whitespace().nth(1)?.parse().ok()?;
123 Some(resident * 4096)
124}
126struct PhaseStats {
127 allocs: usize,
128 deallocs: usize,
129 reallocs: usize,
130 calls: usize,
131 bytes: usize,
132 live_delta: i64,
133 peak_delta: usize,
134 elapsed: Duration,
135 rss_end: Option<usize>,
136}
138fn measure<T>(f: impl FnOnce() -> T) -> (T, PhaseStats) {
139 reset_peak();
140 let s0 = snap();
141 let t0 = Instant::now();
142 let out = f();
143 let elapsed = t0.elapsed();
144 let s1 = snap();
145 let peak = PEAK_LIVE.load(Relaxed);
146 (
147 out,
148 PhaseStats {
149 allocs: s1.allocs - s0.allocs,
150 deallocs: s1.deallocs - s0.deallocs,
151 reallocs: s1.reallocs - s0.reallocs,
152 calls: (s1.allocs - s0.allocs) + (s1.deallocs - s0.deallocs) + (s1.reallocs - s0.reallocs),
153 bytes: s1.bytes - s0.bytes,
154 live_delta: s1.live as i64 - s0.live as i64,
155 peak_delta: peak.saturating_sub(s0.live),
156 elapsed,
157 rss_end: rss_bytes(),
158 },
159 )
160}
162fn fmt_bytes(n: usize) -> String {
163 const MIB: f64 = 1024.0 * 1024.0;
164 if n as f64 >= MIB {
165 format!("{:.2} MiB", n as f64 / MIB)
166 } else if n >= 1024 {
167 format!("{:.1} KiB", n as f64 / 1024.0)
168 } else {
169 format!("{} B", n)
170 }
171}
173fn fmt_rss(r: Option<usize>) -> String {
174 r.map(fmt_bytes).unwrap_or_else(|| "n/a".into())
175}
177fn print_phase(label: &str, st: &PhaseStats) {
178 println!(
179 " {label}: allocs={} reallocs={} deallocs={} allocator_calls={} \
180 bytes_allocated={} live_delta={}{} peak_delta={} elapsed={:.1?} rss={}",
181 st.allocs,
182 st.reallocs,
183 st.deallocs,
184 st.calls,
185 fmt_bytes(st.bytes),
186 if st.live_delta < 0 { "-" } else { "" },
187 fmt_bytes(st.live_delta.unsigned_abs() as usize),
188 fmt_bytes(st.peak_delta),
189 st.elapsed,
190 fmt_rss(st.rss_end),
191 );
192}
194// ---------------------------------------------------------------------------
195// Deterministic PRNG (xorshift64*), content-free filler
196// ---------------------------------------------------------------------------
198struct Rng(u64);
200impl Rng {
201 fn new(seed: u64) -> Self {
202 Rng(seed.max(1))
203 }
204 fn next(&mut self) -> u64 {
205 let mut x = self.0;
206 x ^= x >> 12;
207 x ^= x << 25;
208 x ^= x >> 27;
209 self.0 = x;
210 x.wrapping_mul(0x2545F4914F6CDD1D)
211 }
212 fn range(&mut self, lo: usize, hi: usize) -> usize {
213 lo + (self.next() as usize) % (hi - lo).max(1)
214 }
215}
217/// JSON-safe ASCII filler pattern (letters/digits/space/dash only).
218fn build_pattern(rng: &mut Rng) -> String {
219 const WORDS: &[&str] = &[
220 "alloc", "arena", "scratch", "filler", "synthetic", "render", "token",
221 "smith", "buffer", "phase", "entry", "window", "session", "stream",
222 "block-7", "delta-42", "frame", "context",
223 ];
224 let mut s = String::with_capacity(8300);
225 while s.len() < 8192 {
226 s.push_str(WORDS[rng.range(0, WORDS.len())]);
227 s.push(' ');
228 }
229 s.truncate(8192);
230 s
231}
233// ---------------------------------------------------------------------------
234// Fixture generation (runtime, deterministic; see DEVIATION note in header)
235// ---------------------------------------------------------------------------
237const KIB: usize = 1024;
238const MIB: usize = 1024 * 1024;
239const SEED: u64 = 0x5EED_5EED_0009;
240const META_SESSIONS: usize = 531; // + 4 shaped fixtures = 535 total
241const MANIFEST: &str = "p09-fixtures-v1 sessions=535";
243struct FixtureSpec {
244 name: &'static str,
245 messages: usize, // + 1 header line = PLAN entry count
246 target_bytes: usize, // approximate file size target
247 giant: Option<(usize, usize)>, // (message index, filler bytes)
248}
250fn fixture_specs() -> [FixtureSpec; 4] {
251 [
252 FixtureSpec { name: "small", messages: 35, target_bytes: 88 * KIB, giant: None },
253 FixtureSpec { name: "p95", messages: 821, target_bytes: 3 * MIB + 104_858, giant: None },
254 FixtureSpec { name: "p99", messages: 1929, target_bytes: 9 * MIB + 209_715, giant: None },
255 FixtureSpec {
256 name: "pathological",
257 messages: 5156,
258 target_bytes: 29 * MIB,
259 giant: Some((2500, 4_823_000)), // ~4.6 MiB single message line
260 },
261 ]
262}
264fn fixtures_dir() -> PathBuf {
265 std::env::temp_dir().join("p09-fixtures")
266}
268fn write_filler(w: &mut impl Write, pattern: &str, len: usize, start: usize) -> std::io::Result<()> {
269 let pat = pattern.as_bytes();
270 let mut off = start % pat.len();
271 let mut left = len;
272 while left > 0 {
273 let take = left.min(pat.len() - off);
274 w.write_all(&pat[off..off + take])?;
275 off = 0;
276 left -= take;
277 }
278 Ok(())
279}
281fn gen_session(
282 path: &Path,
283 session_no: usize,
284 spec_messages: usize,
285 target_bytes: usize,
286 giant: Option<(usize, usize)>,
287 pattern: &str,
288 rng: &mut Rng,
289) -> std::io::Result<u64> {
290 let mut w = BufWriter::new(File::create(path)?);
291 writeln!(
292 w,
293 "{{\"type\":\"session\",\"id\":\"sess-{session_no:04}\",\"title\":\"synthetic p09 session {session_no}\",\"created\":\"2026-07-01T00:00:00Z\"}}"
294 )?;
295 const OVERHEAD: usize = 105; // approx JSON envelope bytes per message line
296 const USER_LEN: usize = 300; // research: user messages mean ~303 chars
297 let n_user = (0..spec_messages).filter(|i| i % 10 == 0).count();
298 let n_giant = if giant.is_some() { 1 } else { 0 };
299 let giant_bytes = giant.map(|(_, b)| b + OVERHEAD).unwrap_or(0);
300 let n_norm = spec_messages - n_user - n_giant;
301 let budget = target_bytes
302 .saturating_sub(100 + giant_bytes + n_user * (USER_LEN + OVERHEAD) + n_norm * OVERHEAD);
303 let norm_mean = (budget / n_norm.max(1)).max(64);
304 for i in 0..spec_messages {
305 let (role, len) = if giant.map(|(gi, _)| gi == i).unwrap_or(false) {
306 ("toolResult", giant.unwrap().1)
307 } else if i % 10 == 0 {
308 ("user", USER_LEN)
309 } else if i % 2 == 1 {
310 ("assistant", rng.range(norm_mean * 7 / 10, norm_mean * 13 / 10))
311 } else {
312 ("toolResult", rng.range(norm_mean * 7 / 10, norm_mean * 13 / 10))
313 };
314 write!(
315 w,
316 "{{\"type\":\"message\",\"id\":\"m-{session_no:04}-{i:06}\",\"role\":\"{role}\",\"content\":[{{\"type\":\"text\",\"text\":\""
317 )?;
318 write_filler(&mut w, pattern, len, rng.range(0, 8192))?;
319 w.write_all(b"\"}]}\n")?;
320 }
321 w.flush()?;
322 Ok(fs::metadata(path)?.len())
323}
325/// Ensure fixtures exist; generate deterministically if absent. Returns dir.
326fn ensure_fixtures() -> PathBuf {
327 let dir = fixtures_dir();
328 let manifest = dir.join("MANIFEST");
329 if fs::read_to_string(&manifest).map(|s| s == MANIFEST).unwrap_or(false) {
330 println!("fixtures: reusing {} (manifest ok)", dir.display());
331 return dir;
332 }
333 let t0 = Instant::now();
334 let _ = fs::remove_dir_all(&dir);
335 fs::create_dir_all(&dir).expect("create fixtures dir");
336 let mut rng = Rng::new(SEED);
337 let pattern = build_pattern(&mut rng);
338 println!("fixtures: generating into {} (runtime deviation; not committed)", dir.display());
339 for (n, spec) in fixture_specs().iter().enumerate() {
340 let path = dir.join(format!("session-{n:04}-{}.jsonl", spec.name));
341 let size = gen_session(&path, n, spec.messages, spec.target_bytes, spec.giant, &pattern, &mut rng)
342 .expect("generate fixture");
343 let dev = (size as f64 / spec.target_bytes as f64 - 1.0) * 100.0;
344 println!(
345 " {}: {} entries, {} (target {}, {:+.1}%)",
346 spec.name,
347 spec.messages + 1,
348 fmt_bytes(size as usize),
349 fmt_bytes(spec.target_bytes),
350 dev
351 );
352 assert!(dev.abs() < 10.0, "fixture size off target by >10%");
353 }
354 for m in 0..META_SESSIONS {
355 let n = 4 + m;
356 let path = dir.join(format!("session-{n:04}-meta.jsonl", n = n));
357 gen_session(&path, n, 2, 700, None, &pattern, &mut rng).expect("generate meta fixture");
358 }
359 fs::write(&manifest, MANIFEST).expect("write manifest");
360 println!(" 535 session files ready in {:.1?}", t0.elapsed());
361 dir
362}
364// ---------------------------------------------------------------------------
365// Smith-like session model (owned strings + stable IDs; no arena references)
366// ---------------------------------------------------------------------------
368#[derive(Deserialize)]
369struct SessionHeader {
370 id: String,
371 title: String,
372 created: String,
373}
375#[derive(Deserialize)]
376struct Block {
377 #[serde(rename = "type")]
378 #[allow(dead_code)]
379 kind: String,
380 #[serde(default)]
381 text: String,
382}
384#[derive(Deserialize)]
385struct MessageEntry {
386 id: String,
387 role: String,
388 content: Vec<Block>,
389}
391#[derive(Deserialize)]
392#[serde(tag = "type")]
393enum SessionEntry {
394 #[serde(rename = "session")]
395 Session(SessionHeader),
396 #[serde(rename = "message")]
397 Message(MessageEntry),
398 #[serde(other)]
399 Unknown,
400}
402struct LoadedSession {
403 name: &'static str,
404 file_bytes: u64,
405 entries: Vec<SessionEntry>,
406 index: HashMap<String, usize>, // stable ID -> position (replay index)
407 max_block_bytes: usize,
408}
410fn load_session(name: &'static str, path: &Path) -> LoadedSession {
411 let file_bytes = fs::metadata(path).expect("stat").len();
412 // Whole-file read then per-line decode; the transient file String shows
413 // up in peak_delta but not live_delta (freed before return).
414 let raw = fs::read_to_string(path).expect("read session");
415 let mut entries: Vec<SessionEntry> = Vec::new();
416 for line in raw.lines() {
417 entries.push(serde_json::from_str(line).expect("valid entry"));
418 }
419 // Replay: rebuild the stable-ID index exactly as a session restore would.
420 let mut index = HashMap::with_capacity(entries.len());
421 let mut max_block_bytes = 0usize;
422 for (i, e) in entries.iter().enumerate() {
423 match e {
424 SessionEntry::Session(h) => {
425 index.insert(h.id.clone(), i);
426 }
427 SessionEntry::Message(m) => {
428 index.insert(m.id.clone(), i);
429 for b in &m.content {
430 max_block_bytes = max_block_bytes.max(b.text.len());
431 }
432 }
433 SessionEntry::Unknown => {}
434 }
435 }
436 LoadedSession { name, file_bytes, entries, index, max_block_bytes }
437}
439fn load_shaped(dir: &Path) -> Vec<LoadedSession> {
440 fixture_specs()
441 .iter()
442 .enumerate()
443 .map(|(n, s)| load_session(s.name, &dir.join(format!("session-{n:04}-{}.jsonl", s.name))))
444 .collect()
445}
447// ---------------------------------------------------------------------------
448// Check plumbing
449// ---------------------------------------------------------------------------
451struct Check {
452 name: String,
453 pass: bool,
454 detail: String,
455}
457fn check(checks: &mut Vec<Check>, name: &str, pass: bool, detail: String) {
458 println!(" [{}] {name}: {detail}", if pass { "PASS" } else { "FAIL" });
459 checks.push(Check { name: name.into(), pass, detail });
460}
462// ---------------------------------------------------------------------------
463// Workload 1: discover — scan 535 session headers without full load
464// ---------------------------------------------------------------------------
466#[allow(dead_code)]
467struct SessionMeta {
468 id: String,
469 title: String,
470 created: String,
471 file_bytes: u64,
472}
474fn wl_discover(dir: &Path) -> Vec<Check> {
475 println!("\n== discover: 535 session headers, metadata only ==");
476 let mut paths: Vec<PathBuf> = fs::read_dir(dir)
477 .expect("read fixtures dir")
478 .filter_map(|e| e.ok().map(|e| e.path()))
479 .filter(|p| p.extension().map(|x| x == "jsonl").unwrap_or(false))
480 .collect();
481 paths.sort();
482 let corpus_bytes: u64 = paths.iter().map(|p| fs::metadata(p).map(|m| m.len()).unwrap_or(0)).sum();
484 let ((metas, bytes_read), st) = measure(|| {
485 let mut metas: Vec<SessionMeta> = Vec::new();
486 let mut bytes_read = 0u64;
487 let mut buf = String::new();
488 for p in &paths {
489 let file_bytes = fs::metadata(p).expect("stat").len();
490 let mut r = BufReader::new(File::open(p).expect("open"));
491 buf.clear();
492 r.read_line(&mut buf).expect("header line");
493 bytes_read += buf.len() as u64;
494 let h: SessionHeader = serde_json::from_str(buf.trim_end()).expect("header json");
495 metas.push(SessionMeta { id: h.id, title: h.title, created: h.created, file_bytes });
496 }
497 (metas, bytes_read)
498 });
499 print_phase("discover", &st);
500 println!(
501 " sessions={} corpus={} bytes_read={} ({:.2}% of corpus) allocs/session={:.1} bytes_allocated/session={}",
502 metas.len(),
503 fmt_bytes(corpus_bytes as usize),
504 fmt_bytes(bytes_read as usize),
505 bytes_read as f64 / corpus_bytes as f64 * 100.0,
506 st.allocs as f64 / metas.len() as f64,
507 fmt_bytes(st.bytes / metas.len()),
508 );
509 let mut checks = Vec::new();
510 check(&mut checks, "session-count", metas.len() == 535, format!("{} sessions discovered", metas.len()));
511 check(
512 &mut checks,
513 "discovery-O(sessions)-not-O(corpus)",
514 bytes_read * 10 < corpus_bytes && st.allocs <= metas.len() * 64,
515 format!(
516 "read {} of {} corpus ({:.2}%); {:.1} allocs/session (bound 64)",
517 fmt_bytes(bytes_read as usize),
518 fmt_bytes(corpus_bytes as usize),
519 bytes_read as f64 / corpus_bytes as f64 * 100.0,
520 st.allocs as f64 / metas.len() as f64
521 ),
522 );
523 check(
524 &mut checks,
525 "discovery-metadata-live",
526 st.live_delta < (256 * KIB) as i64,
527 format!("live_delta {} for 535 metas (bound 256 KiB)", fmt_bytes(st.live_delta.max(0) as usize)),
528 );
529 checks
530}
532// ---------------------------------------------------------------------------
533// Workload 2: load-replay — full decode into Smith-like SessionEntry values
534// ---------------------------------------------------------------------------
536fn wl_load_replay(dir: &Path) -> (Vec<Check>, Vec<LoadedSession>) {
537 println!("\n== load-replay: full decode + stable-ID index rebuild ==");
538 // Research bands (resident session upper bounds, MiB):
539 // p50 <1 (small), p95 4-8, p99 12-20, max 30-45.
540 let band_upper_mib = [("small", 1.5), ("p95", 8.0), ("p99", 20.0), ("pathological", 45.0)];
541 let mut checks = Vec::new();
542 let mut sessions = Vec::new();
543 for (n, spec) in fixture_specs().iter().enumerate() {
544 let path = dir.join(format!("session-{n:04}-{}.jsonl", spec.name));
545 let (s, st) = measure(|| load_session(spec.name, &path));
546 print_phase(spec.name, &st);
547 let live = st.live_delta.max(0) as usize;
548 let upper = (band_upper_mib[n].1 * MIB as f64) as usize;
549 let lower = (s.file_bytes as f64 * 0.8) as usize;
550 check(
551 &mut checks,
552 &format!("load-band-{}", spec.name),
553 live <= upper && live >= lower,
554 format!(
555 "{} entries, file {}, resident {} (band {}..{} = 0.8*file..research upper), peak {} (incl. transient file buffer)",
556 s.entries.len(),
557 fmt_bytes(s.file_bytes as usize),
558 fmt_bytes(live),
559 fmt_bytes(lower),
560 fmt_bytes(upper),
561 fmt_bytes(st.peak_delta)
562 ),
563 );
564 check(
565 &mut checks,
566 &format!("replay-index-{}", spec.name),
567 s.index.len() == s.entries.len(),
568 format!("stable-ID index has {} entries (owned Strings, no arena refs)", s.index.len()),
569 );
570 sessions.push(s);
571 }
572 let patho = &sessions[3];
573 check(
574 &mut checks,
575 "pathological-giant-message",
576 patho.max_block_bytes > 4 * MIB,
577 format!("max single message block {}", fmt_bytes(patho.max_block_bytes)),
578 );
579 (checks, sessions)
580}
582// ---------------------------------------------------------------------------
583// Workload 3: render-window — visible rows only, lazy wrap, virtual scroll
584// ---------------------------------------------------------------------------
586const VISIBLE_ROWS: usize = 40;
587const WRAP_WIDTH: usize = 80;
588const ITERS: usize = 50;
589const WARMUP: usize = 10;
591/// Baseline frame: materialize visible rows as owned Strings (simulating
592/// styled/formatted TUI line output). Lazy wrap: stops at VISIBLE_ROWS, so a
593/// 4.6 MiB message in view costs the same as any other row source.
594fn render_frame_baseline(entries: &[SessionEntry], offset: usize) -> (usize, usize) {
595 let mut lines: Vec<String> = Vec::new();
596 let mut idx = offset;
597 while lines.len() < VISIBLE_ROWS && idx < entries.len() {
598 if let SessionEntry::Message(m) = &entries[idx] {
599 lines.push(format!("[{}] {}", m.role, m.id));
600 for b in &m.content {
601 for chunk in b.text.as_bytes().chunks(WRAP_WIDTH) {
602 if lines.len() >= VISIBLE_ROWS {
603 break;
604 }
605 lines.push(std::str::from_utf8(chunk).expect("ascii fixture").to_string());
606 }
607 }
608 }
609 idx += 1;
610 }
611 (lines.len(), lines.iter().map(|l| l.len()).sum())
612}
614/// Bump frame: identical output shape, all scratch in the arena. Returns only
615/// counts, so no `&'bump` value can escape the frame (borrow checker enforced).
616fn render_frame_bump(entries: &[SessionEntry], offset: usize, bump: &Bump) -> (usize, usize) {
617 let mut lines: bumpalo::collections::Vec<&str> = bumpalo::collections::Vec::new_in(bump);
618 let mut idx = offset;
619 while lines.len() < VISIBLE_ROWS && idx < entries.len() {
620 if let SessionEntry::Message(m) = &entries[idx] {
621 lines.push(bumpalo::format!(in bump, "[{}] {}", m.role, m.id).into_bump_str());
622 for b in &m.content {
623 for chunk in b.text.as_bytes().chunks(WRAP_WIDTH) {
624 if lines.len() >= VISIBLE_ROWS {
625 break;
626 }
627 lines.push(bump.alloc_str(std::str::from_utf8(chunk).expect("ascii fixture")));
628 }
629 }
630 }
631 idx += 1;
632 }
633 (lines.len(), lines.iter().map(|l| l.len()).sum())
634}
636struct PhaseRun {
637 per_iter_calls: Vec<usize>,
638 per_iter_allocs: Vec<usize>,
639 per_iter_bytes: Vec<usize>,
640 live_after: Vec<usize>,
641 peak_delta: usize,
642 elapsed: Duration,
643 rss_end: Option<usize>,
644}
646fn run_iters(iters: usize, mut f: impl FnMut(usize)) -> PhaseRun {
647 // Preallocate result vecs so harness pushes never allocate mid-frame.
648 let mut per_iter_calls = Vec::with_capacity(iters);
649 let mut per_iter_allocs = Vec::with_capacity(iters);
650 let mut per_iter_bytes = Vec::with_capacity(iters);
651 let mut live_after = Vec::with_capacity(iters);
652 reset_peak();
653 let live0 = LIVE_BYTES.load(Relaxed);
654 let t0 = Instant::now();
655 for i in 0..iters {
656 let s0 = snap();
657 f(i);
658 let s1 = snap();
659 per_iter_allocs.push(s1.allocs - s0.allocs);
660 per_iter_calls
661 .push((s1.allocs - s0.allocs) + (s1.deallocs - s0.deallocs) + (s1.reallocs - s0.reallocs));
662 per_iter_bytes.push(s1.bytes - s0.bytes);
663 live_after.push(s1.live);
664 }
665 let elapsed = t0.elapsed();
666 PhaseRun {
667 per_iter_calls,
668 per_iter_allocs,
669 per_iter_bytes,
670 live_after,
671 peak_delta: PEAK_LIVE.load(Relaxed).saturating_sub(live0),
672 elapsed,
673 rss_end: rss_bytes(),
674 }
675}
677fn post_warmup_avg(v: &[usize]) -> f64 {
678 let tail = &v[WARMUP.min(v.len())..];
679 if tail.is_empty() {
680 return 0.0;
681 }
682 tail.iter().sum::<usize>() as f64 / tail.len() as f64
683}
685/// (min, max, spread) of post-warmup live bytes — the memory plateau.
686fn plateau(v: &[usize]) -> (usize, usize, usize) {
687 let tail = &v[WARMUP.min(v.len())..];
688 let mn = tail.iter().copied().min().unwrap_or(0);
689 let mx = tail.iter().copied().max().unwrap_or(0);
690 (mn, mx, mx - mn)
691}
693fn offset_for(i: usize, n_entries: usize) -> usize {
694 (i * 13) % n_entries.saturating_sub(5).max(1)
695}
697fn render_run_baseline(s: &LoadedSession) -> PhaseRun {
698 run_iters(ITERS, |i| {
699 let out = render_frame_baseline(&s.entries, offset_for(i, s.entries.len()));
700 std::hint::black_box(out);
701 })
702}
704/// Phase fn owning the Bump: created here, reset per frame, never escapes.
705fn render_run_bump(s: &LoadedSession) -> PhaseRun {
706 let mut bump = Bump::new();
707 run_iters(ITERS, |i| {
708 let out = render_frame_bump(&s.entries, offset_for(i, s.entries.len()), &bump);
709 std::hint::black_box(out);
710 bump.reset();
711 })
712}
714fn print_run(label: &str, r: &PhaseRun) {
715 let (mn, mx, spread) = plateau(&r.live_after);
716 println!(
717 " {label}: post-warmup/iter allocs={:.1} calls={:.1} bytes={} | plateau live {}..{} (spread {}) | peak_delta={} total_elapsed={:.1?} ({:.1} us/iter) rss={}",
718 post_warmup_avg(&r.per_iter_allocs),
719 post_warmup_avg(&r.per_iter_calls),
720 fmt_bytes(post_warmup_avg(&r.per_iter_bytes) as usize),
721 fmt_bytes(mn),
722 fmt_bytes(mx),
723 fmt_bytes(spread),
724 fmt_bytes(r.peak_delta),
725 r.elapsed,
726 r.elapsed.as_micros() as f64 / ITERS as f64,
727 fmt_rss(r.rss_end),
728 );
729}
731fn wl_render_window(sessions: &[LoadedSession]) -> Vec<Check> {
732 println!("\n== render-window: {VISIBLE_ROWS} visible rows, {ITERS} scrolled frames/session ==");
733 let mut checks = Vec::new();
734 let mut per_frame: Vec<(usize, f64)> = Vec::new(); // (entries, avg allocs/frame)
735 for s in sessions {
736 let r = render_run_baseline(s);
737 print_run(s.name, &r);
738 per_frame.push((s.entries.len(), post_warmup_avg(&r.per_iter_allocs)));
739 let (_, _, spread) = plateau(&r.live_after);
740 check(
741 &mut checks,
742 &format!("render-plateau-{}", s.name),
743 spread < 64 * KIB,
744 format!("post-warmup live spread {} (bound 64 KiB)", fmt_bytes(spread)),
745 );
746 }
747 let min_a = per_frame.iter().map(|x| x.1).fold(f64::MAX, f64::min);
748 let max_a = per_frame.iter().map(|x| x.1).fold(0.0, f64::max);
749 let entry_ratio = per_frame.iter().map(|x| x.0).max().unwrap() as f64
750 / per_frame.iter().map(|x| x.0).min().unwrap() as f64;
751 check(
752 &mut checks,
753 "render-O(visible-rows)",
754 max_a / min_a.max(1.0) <= 2.5,
755 format!(
756 "allocs/frame {:.1}..{:.1} ({:.2}x) while entry counts span {:.0}x — bounded by rows, not entries",
757 min_a,
758 max_a,
759 max_a / min_a.max(1.0),
760 entry_ratio
761 ),
762 );
763 // Frame positioned directly on the ~4.6 MiB message (entry idx 2501).
764 let patho = &sessions[3];
765 let giant_idx = 2501.min(patho.entries.len() - 1);
766 let (out, st) = measure(|| render_frame_baseline(&patho.entries, giant_idx));
767 check(
768 &mut checks,
769 "render-giant-message-window",
770 out.0 == VISIBLE_ROWS && (st.allocs as f64) <= max_a * 3.0,
771 format!(
772 "frame on 4.6 MiB message: {} rows, {} allocs (bound 3x normal frame {:.1}) — lazy wrap holds",
773 out.0, st.allocs, max_a
774 ),
775 );
776 checks
777}
779// ---------------------------------------------------------------------------
780// Workload 4: request-build — provider request near 250k-token context
781// ---------------------------------------------------------------------------
783const TOKEN_BUDGET_CHARS: usize = 1_000_000; // ~250k tokens at ~4 chars/token
785#[derive(Serialize)]
786struct ReqMessageOwned {
787 role: String,
788 content: String,
789}
791#[derive(Serialize)]
792struct ReqOwned {
793 model: &'static str,
794 max_tokens: u32,
795 messages: Vec<ReqMessageOwned>,
796}
798fn build_request_baseline(entries: &[SessionEntry]) -> (usize, usize, usize) {
799 let mut messages: Vec<ReqMessageOwned> = Vec::new();
800 let mut chars = 0usize;
801 for e in entries.iter().rev() {
802 if let SessionEntry::Message(m) = e {
803 let mut content = String::new();
804 for (bi, b) in m.content.iter().enumerate() {
805 if bi > 0 {
806 content.push('\n');
807 }
808 content.push_str(&b.text);
809 }
810 chars += content.len();
811 messages.push(ReqMessageOwned { role: m.role.clone(), content });
812 if chars >= TOKEN_BUDGET_CHARS {
813 break;
814 }
815 }
816 }
817 messages.reverse();
818 let n = messages.len();
819 let json = serde_json::to_string(&ReqOwned { model: "provider-x", max_tokens: 8192, messages })
820 .expect("serialize");
821 (json.len(), chars / 4, n)
822}
824#[derive(Serialize)]
825struct ReqMessageRef<'a> {
826 role: &'a str,
827 content: &'a str,
828}
830#[derive(Serialize)]
831struct ReqRef<'a> {
832 model: &'static str,
833 max_tokens: u32,
834 messages: &'a [ReqMessageRef<'a>],
835}
837/// Scratch (joined content + message list) lives in the Bump; the serialized
838/// request String is owned — nothing borrowed crosses out of this fn.
839fn build_request_bump(entries: &[SessionEntry], bump: &Bump) -> (usize, usize, usize) {
840 let mut messages: bumpalo::collections::Vec<ReqMessageRef> =
841 bumpalo::collections::Vec::new_in(bump);
842 let mut chars = 0usize;
843 for e in entries.iter().rev() {
844 if let SessionEntry::Message(m) = e {
845 let mut content = bumpalo::collections::String::new_in(bump);
846 for (bi, b) in m.content.iter().enumerate() {
847 if bi > 0 {
848 content.push('\n');
849 }
850 content.push_str(&b.text);
851 }
852 chars += content.len();
853 messages.push(ReqMessageRef { role: &m.role, content: content.into_bump_str() });
854 if chars >= TOKEN_BUDGET_CHARS {
855 break;
856 }
857 }
858 }
859 messages.reverse();
860 let json = serde_json::to_string(&ReqRef {
861 model: "provider-x",
862 max_tokens: 8192,
863 messages: &messages,
864 })
865 .expect("serialize");
866 (json.len(), chars / 4, messages.len())
867}
869fn request_run_baseline(s: &LoadedSession) -> PhaseRun {
870 run_iters(ITERS, |_| {
871 let out = build_request_baseline(&s.entries);
872 std::hint::black_box(out);
873 })
874}
876fn request_run_bump(s: &LoadedSession) -> PhaseRun {
877 let mut bump = Bump::new();
878 run_iters(ITERS, |_| {
879 let out = build_request_bump(&s.entries, &bump);
880 std::hint::black_box(out);
881 bump.reset();
882 })
883}
885fn wl_request_build(sessions: &[LoadedSession]) -> Vec<Check> {
886 let patho = &sessions[3];
887 println!("\n== request-build: assemble provider request from pathological session, {ITERS} iterations ==");
888 let ((json_len, tokens, n_msgs), st1) = measure(|| build_request_baseline(&patho.entries));
889 println!(
890 " single build: {} messages, ~{} tokens (chars/4), request json {}",
891 n_msgs,
892 tokens,
893 fmt_bytes(json_len)
894 );
895 print_phase("single-build", &st1);
896 let r = request_run_baseline(patho);
897 print_run("repeat-build", &r);
898 let mut checks = Vec::new();
899 check(
900 &mut checks,
901 "request-near-compaction-size",
902 (200_000..=320_000).contains(&tokens),
903 format!("~{tokens} tokens selected (research compaction band 247k-282k)"),
904 );
905 check(
906 &mut checks,
907 "request-peak-bounded",
908 st1.peak_delta < 8 * MIB,
909 format!(
910 "peak_delta {} for a {} request (transient; ~2-3x selected context, bound 8 MiB)",
911 fmt_bytes(st1.peak_delta),
912 fmt_bytes(json_len)
913 ),
914 );
915 let (_, _, spread) = plateau(&r.live_after);
916 check(
917 &mut checks,
918 "request-plateau",
919 spread < MIB,
920 format!("post-warmup live spread {} across {} builds (bound 1 MiB)", fmt_bytes(spread), ITERS),
921 );
922 checks
923}
925// ---------------------------------------------------------------------------
926// Workload 5: arena-scratch — baseline vs bumpalo, keep/drop per workload
927// ---------------------------------------------------------------------------
929fn verdict(workload: &str, base: &PhaseRun, bump: &PhaseRun, checks: &mut Vec<Check>) {
930 let b_calls = post_warmup_avg(&base.per_iter_calls);
931 let u_calls = post_warmup_avg(&bump.per_iter_calls);
932 let b_bytes = post_warmup_avg(&base.per_iter_bytes);
933 let u_bytes = post_warmup_avg(&bump.per_iter_bytes);
934 let call_red = 1.0 - u_calls / b_calls.max(1.0);
935 let bytes_red = 1.0 - u_bytes / b_bytes.max(1.0);
936 let time_ratio = bump.elapsed.as_secs_f64() / base.elapsed.as_secs_f64().max(1e-9);
937 let (_, _, b_spread) = plateau(&base.live_after);
938 let (_, _, u_spread) = plateau(&bump.live_after);
939 let peak_ok = bump.peak_delta as f64 <= base.peak_delta as f64 * 1.2 + (64 * KIB) as f64;
940 let not_slower = time_ratio <= 1.10;
941 let keep = (call_red >= 0.5 || time_ratio <= 0.90 || u_spread * 2 < b_spread.saturating_sub(32 * KIB))
942 && peak_ok
943 && not_slower;
944 println!(
945 " {workload}: allocator-calls/iter {:.1} -> {:.1} ({:+.0}%), bytes/iter {} -> {} ({:+.0}%), elapsed x{:.2}, plateau spread {} -> {}, peak {} -> {}",
946 b_calls,
947 u_calls,
948 -call_red * 100.0,
949 fmt_bytes(b_bytes as usize),
950 fmt_bytes(u_bytes as usize),
951 -bytes_red * 100.0,
952 time_ratio,
953 fmt_bytes(b_spread),
954 fmt_bytes(u_spread),
955 fmt_bytes(base.peak_delta),
956 fmt_bytes(bump.peak_delta),
957 );
958 let reason = if keep {
959 format!(
960 "scratch-only bumpalo wins: {:.0}% fewer allocator calls/iter, elapsed x{time_ratio:.2}, peak stable; costs one dependency + phase-lifetime discipline (no unsafe, no escaping refs)",
961 call_red * 100.0
962 )
963 } else {
964 format!(
965 "baseline sufficient: call reduction {:.0}%, elapsed x{time_ratio:.2}, peak_ok={peak_ok} — win does not justify lifetime complexity + dependency",
966 call_red * 100.0
967 )
968 };
969 println!(" VERDICT {workload}: {} bumpalo — {reason}", if keep { "KEEP" } else { "DROP" });
970 check(
971 checks,
972 &format!("arena-verdict-{workload}"),
973 true, // the verdict itself is evidence, not a pass/fail gate
974 format!("{} — {reason}", if keep { "KEEP" } else { "DROP" }),
975 );
976}
978fn wl_arena_scratch(sessions: &[LoadedSession]) -> Vec<Check> {
979 println!("\n== arena-scratch: Vec/String baseline vs bumpalo Bump (scratch only) ==");
980 println!(" (Bump is created inside each phase fn and reset per iteration; only owned values/counts are returned — no arena ref crosses any boundary.)");
981 let mut checks = Vec::new();
983 let p99 = &sessions[2];
984 println!("- render-window scratch (p99 session, {ITERS} frames):");
985 let base_r = render_run_baseline(p99);
986 print_run("baseline ", &base_r);
987 let bump_r = render_run_bump(p99);
988 print_run("bumpalo ", &bump_r);
989 verdict("render-window", &base_r, &bump_r, &mut checks);
991 let patho = &sessions[3];
992 println!("- request-build scratch (pathological session, {ITERS} builds):");
993 let base_q = request_run_baseline(patho);
994 print_run("baseline ", &base_q);
995 let bump_q = request_run_bump(patho);
996 print_run("bumpalo ", &bump_q);
997 verdict("request-build", &base_q, &bump_q, &mut checks);
999 // Sanity: both variants produce identical output shape.
1000 let a = render_frame_baseline(&p99.entries, 42);
1001 let bump = Bump::new();
1002 let b = render_frame_bump(&p99.entries, 42, &bump);
1003 drop(bump);
1004 check(
1005 &mut checks,
1006 "arena-output-equivalence",
1007 a == b,
1008 format!("baseline frame {:?} == bump frame {:?}", a, b),
1009 );
1010 let qa = build_request_baseline(&patho.entries);
1011 let bump2 = Bump::new();
1012 let qb = build_request_bump(&patho.entries, &bump2);
1013 drop(bump2);
1014 check(
1015 &mut checks,
1016 "arena-request-equivalence",
1017 qa == qb,
1018 format!("baseline request {:?} == bump request {:?}", qa, qb),
1019 );
1020 checks
1023// ---------------------------------------------------------------------------
1024// main
1025// ---------------------------------------------------------------------------
1027fn main() {
1028 let cmd = std::env::args().nth(1).unwrap_or_else(|| {
1029 eprintln!("usage: p09 <discover|load-replay|render-window|request-build|arena-scratch|all>");
1030 std::process::exit(2);
1031 });
1032 println!(
1033 "p09-memory-arena-allocation ({} build; keep/drop numbers meaningful in --release only)",
1034 if cfg!(debug_assertions) { "DEBUG" } else { "release" }
1035 );
1036 println!("startup rss={}", fmt_rss(rss_bytes()));
1037 let dir = ensure_fixtures();
1039 let mut checks: Vec<Check> = Vec::new();
1040 match cmd.as_str() {
1041 "discover" => checks.extend(wl_discover(&dir)),
1042 "load-replay" => {
1043 let (c, _) = wl_load_replay(&dir);
1044 checks.extend(c);
1045 }
1046 "render-window" => {
1047 let sessions = load_shaped(&dir);
1048 checks.extend(wl_render_window(&sessions));
1049 }
1050 "request-build" => {
1051 let sessions = load_shaped(&dir);
1052 checks.extend(wl_request_build(&sessions));
1053 }
1054 "arena-scratch" => {
1055 let sessions = load_shaped(&dir);
1056 checks.extend(wl_arena_scratch(&sessions));
1057 }
1058 "all" => {
1059 checks.extend(wl_discover(&dir));
1060 let (c, sessions) = wl_load_replay(&dir);
1061 checks.extend(c);
1062 checks.extend(wl_render_window(&sessions));
1063 checks.extend(wl_request_build(&sessions));
1064 checks.extend(wl_arena_scratch(&sessions));
1065 }
1066 other => {
1067 eprintln!("unknown workload: {other}");
1068 std::process::exit(2);
1069 }
1070 }
1072 let failed: Vec<&Check> = checks.iter().filter(|c| !c.pass).collect();
1073 println!(
1074 "\nP09 RESULT: {} ({}/{} checks passed) final rss={}",
1075 if failed.is_empty() { "PASS" } else { "FAIL" },
1076 checks.len() - failed.len(),
1077 checks.len(),
1078 fmt_rss(rss_bytes()),
1079 );
1080 for f in &failed {
1081 println!(" failed: {} — {}", f.name, f.detail);
1082 }
1083 if !failed.is_empty() {
1084 std::process::exit(1);
1085 }

prototypes/p10-lua-plugin-heap-limit/Cargo.lock

Added
new file mode 100644

+376 / −0 text lines

1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "autocfg"
7version = "1.5.1"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
11[[package]]
12name = "bitflags"
13version = "2.13.0"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
17[[package]]
18name = "bstr"
19version = "1.12.3"
20source = "registry+https://github.com/rust-lang/crates.io-index"
21checksum = "5cee35f73844aa3014bb606320a6c1f010249dbdf43342fe54b5a4f6a8ed4b79"
22dependencies = [
23 "memchr",
24 "serde_core",
25]
27[[package]]
28name = "cc"
29version = "1.2.67"
30source = "registry+https://github.com/rust-lang/crates.io-index"
31checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38"
32dependencies = [
33 "find-msvc-tools",
34 "shlex",
35]
37[[package]]
38name = "cfg-if"
39version = "1.0.4"
40source = "registry+https://github.com/rust-lang/crates.io-index"
41checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
43[[package]]
44name = "either"
45version = "1.16.0"
46source = "registry+https://github.com/rust-lang/crates.io-index"
47checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
49[[package]]
50name = "env_home"
51version = "0.1.0"
52source = "registry+https://github.com/rust-lang/crates.io-index"
53checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
55[[package]]
56name = "erased-serde"
57version = "0.4.10"
58source = "registry+https://github.com/rust-lang/crates.io-index"
59checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
60dependencies = [
61 "serde",
62 "serde_core",
63 "typeid",
64]
66[[package]]
67name = "errno"
68version = "0.3.14"
69source = "registry+https://github.com/rust-lang/crates.io-index"
70checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
71dependencies = [
72 "libc",
73 "windows-sys",
74]
76[[package]]
77name = "find-msvc-tools"
78version = "0.1.9"
79source = "registry+https://github.com/rust-lang/crates.io-index"
80checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
82[[package]]
83name = "libc"
84version = "0.2.186"
85source = "registry+https://github.com/rust-lang/crates.io-index"
86checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
88[[package]]
89name = "linux-raw-sys"
90version = "0.12.1"
91source = "registry+https://github.com/rust-lang/crates.io-index"
92checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
94[[package]]
95name = "lock_api"
96version = "0.4.14"
97source = "registry+https://github.com/rust-lang/crates.io-index"
98checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
99dependencies = [
100 "scopeguard",
101]
103[[package]]
104name = "lua-src"
105version = "547.0.0"
106source = "registry+https://github.com/rust-lang/crates.io-index"
107checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42"
108dependencies = [
109 "cc",
110]
112[[package]]
113name = "luajit-src"
114version = "210.5.12+a4f56a4"
115source = "registry+https://github.com/rust-lang/crates.io-index"
116checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671"
117dependencies = [
118 "cc",
119 "which",
120]
122[[package]]
123name = "memchr"
124version = "2.8.3"
125source = "registry+https://github.com/rust-lang/crates.io-index"
126checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
128[[package]]
129name = "mlua"
130version = "0.10.5"
131source = "registry+https://github.com/rust-lang/crates.io-index"
132checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0"
133dependencies = [
134 "bstr",
135 "either",
136 "erased-serde",
137 "mlua-sys",
138 "num-traits",
139 "parking_lot",
140 "rustc-hash",
141 "rustversion",
142 "serde",
143 "serde-value",
144]
146[[package]]
147name = "mlua-sys"
148version = "0.6.8"
149source = "registry+https://github.com/rust-lang/crates.io-index"
150checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93"
151dependencies = [
152 "cc",
153 "cfg-if",
154 "lua-src",
155 "luajit-src",
156 "pkg-config",
157]
159[[package]]
160name = "num-traits"
161version = "0.2.19"
162source = "registry+https://github.com/rust-lang/crates.io-index"
163checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
164dependencies = [
165 "autocfg",
166]
168[[package]]
169name = "ordered-float"
170version = "2.10.1"
171source = "registry+https://github.com/rust-lang/crates.io-index"
172checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
173dependencies = [
174 "num-traits",
175]
177[[package]]
178name = "p10-lua-plugin-heap-limit"
179version = "0.1.0"
180dependencies = [
181 "mlua",
182]
184[[package]]
185name = "parking_lot"
186version = "0.12.5"
187source = "registry+https://github.com/rust-lang/crates.io-index"
188checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
189dependencies = [
190 "lock_api",
191 "parking_lot_core",
192]
194[[package]]
195name = "parking_lot_core"
196version = "0.9.12"
197source = "registry+https://github.com/rust-lang/crates.io-index"
198checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
199dependencies = [
200 "cfg-if",
201 "libc",
202 "redox_syscall",
203 "smallvec",
204 "windows-link",
205]
207[[package]]
208name = "pkg-config"
209version = "0.3.33"
210source = "registry+https://github.com/rust-lang/crates.io-index"
211checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
213[[package]]
214name = "proc-macro2"
215version = "1.0.106"
216source = "registry+https://github.com/rust-lang/crates.io-index"
217checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
218dependencies = [
219 "unicode-ident",
220]
222[[package]]
223name = "quote"
224version = "1.0.46"
225source = "registry+https://github.com/rust-lang/crates.io-index"
226checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
227dependencies = [
228 "proc-macro2",
229]
231[[package]]
232name = "redox_syscall"
233version = "0.5.18"
234source = "registry+https://github.com/rust-lang/crates.io-index"
235checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
236dependencies = [
237 "bitflags",
238]
240[[package]]
241name = "rustc-hash"
242version = "2.1.3"
243source = "registry+https://github.com/rust-lang/crates.io-index"
244checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
246[[package]]
247name = "rustix"
248version = "1.1.4"
249source = "registry+https://github.com/rust-lang/crates.io-index"
250checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
251dependencies = [
252 "bitflags",
253 "errno",
254 "libc",
255 "linux-raw-sys",
256 "windows-sys",
257]
259[[package]]
260name = "rustversion"
261version = "1.0.23"
262source = "registry+https://github.com/rust-lang/crates.io-index"
263checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
265[[package]]
266name = "scopeguard"
267version = "1.2.0"
268source = "registry+https://github.com/rust-lang/crates.io-index"
269checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
271[[package]]
272name = "serde"
273version = "1.0.228"
274source = "registry+https://github.com/rust-lang/crates.io-index"
275checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
276dependencies = [
277 "serde_core",
278]
280[[package]]
281name = "serde-value"
282version = "0.7.0"
283source = "registry+https://github.com/rust-lang/crates.io-index"
284checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
285dependencies = [
286 "ordered-float",
287 "serde",
288]
290[[package]]
291name = "serde_core"
292version = "1.0.228"
293source = "registry+https://github.com/rust-lang/crates.io-index"
294checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
295dependencies = [
296 "serde_derive",
297]
299[[package]]
300name = "serde_derive"
301version = "1.0.228"
302source = "registry+https://github.com/rust-lang/crates.io-index"
303checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
304dependencies = [
305 "proc-macro2",
306 "quote",
307 "syn",
308]
310[[package]]
311name = "shlex"
312version = "2.0.1"
313source = "registry+https://github.com/rust-lang/crates.io-index"
314checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
316[[package]]
317name = "smallvec"
318version = "1.15.2"
319source = "registry+https://github.com/rust-lang/crates.io-index"
320checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
322[[package]]
323name = "syn"
324version = "2.0.118"
325source = "registry+https://github.com/rust-lang/crates.io-index"
326checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
327dependencies = [
328 "proc-macro2",
329 "quote",
330 "unicode-ident",
331]
333[[package]]
334name = "typeid"
335version = "1.0.3"
336source = "registry+https://github.com/rust-lang/crates.io-index"
337checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
339[[package]]
340name = "unicode-ident"
341version = "1.0.24"
342source = "registry+https://github.com/rust-lang/crates.io-index"
343checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
345[[package]]
346name = "which"
347version = "7.0.3"
348source = "registry+https://github.com/rust-lang/crates.io-index"
349checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762"
350dependencies = [
351 "either",
352 "env_home",
353 "rustix",
354 "winsafe",
355]
357[[package]]
358name = "windows-link"
359version = "0.2.1"
360source = "registry+https://github.com/rust-lang/crates.io-index"
361checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
363[[package]]
364name = "windows-sys"
365version = "0.61.2"
366source = "registry+https://github.com/rust-lang/crates.io-index"
367checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
368dependencies = [
369 "windows-link",
370]
372[[package]]
373name = "winsafe"
374version = "0.0.19"
375source = "registry+https://github.com/rust-lang/crates.io-index"
376checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"

prototypes/p10-lua-plugin-heap-limit/Cargo.toml

Added
new file mode 100644

+8 / −0 text lines

1[package]
2name = "p10-lua-plugin-heap-limit"
3version = "0.1.0"
4edition = "2021"
5publish = false
6
7[dependencies]
8mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }

prototypes/p10-lua-plugin-heap-limit/plugins/host_value.lua

Added
new file mode 100644

+7 / −0 text lines

1-- P10 fixture: reads host-created values injected as globals and reports
2-- what the plugin can observe about them.
3return {
4 blob_type = type(HOST_BLOB),
5 blob_len = (type(HOST_BLOB) == "string") and #HOST_BLOB or -1,
6 ud_type = type(HOST_UD),
7}

prototypes/p10-lua-plugin-heap-limit/plugins/oom_string.lua

Added
new file mode 100644

+6 / −0 text lines

1-- P10 fixture: unbounded string growth via repeated concatenation.
2-- Doubles the string each iteration, so allocation sizes grow geometrically.
3local s = "xxxxxxxxxxxxxxxx"
4while true do
5 s = s .. s
6end

prototypes/p10-lua-plugin-heap-limit/plugins/oom_table.lua

Added
new file mode 100644

+9 / −0 text lines

1-- P10 fixture: unbounded table growth. Must be stopped by the heap quota
2-- (native set_memory_limit or the host's hook-based fallback), never by
3-- crashing the host.
4local t = {}
5local i = 0
6while true do
7 i = i + 1
8 t[i] = { i, i * 2, "payload-payload-payload-" .. i }
9end

prototypes/p10-lua-plugin-heap-limit/plugins/small.lua

Added
new file mode 100644

+7 / −0 text lines

1-- P10 fixture: plugin that stays well under the heap quota.
2-- Builds a modest table (a few hundred KB) and returns a summary.
3local t = {}
4for i = 1, 1000 do
5 t[i] = "item-" .. i
6end
7return { count = #t, note = "small plugin done" }

prototypes/p10-lua-plugin-heap-limit/src/main.rs

Added
new file mode 100644

+655 / −0 text lines

1//! p10-lua-plugin-heap-limit
2//!
3//! Proves or disproves: Smith's Lua plugin sandbox can enforce per-plugin heap
4//! limits under mlua 0.10 + vendored LuaJIT (docs/SPEC.md §9.14 Sandbox,
5//! §9.16 Plugin Hot-Reload domain, §9.17 Plugin Error Model):
6//! - `Lua::used_memory()` / `Lua::set_memory_limit()` work in Smith's locked
7//! feature set (`luajit`, `vendored`, `serialize`),
8//! - a plugin exceeding its quota fails with a recoverable Lua error,
9//! - the failure does not corrupt the host or other plugins,
10//! - host-created values exposed to Lua have measurable accounting semantics.
11//!
12//! Verify: `cargo run -- small|oom-table|oom-string|isolation|host-value|all`
13//!
14//! For OOM scenarios "PASS" means the quota was enforced OR the disproof was
15//! demonstrated and reported precisely — never a host crash. If the native
16//! limit is unavailable/ignored, the prototype measures the fallback: a
17//! count-based debug hook calling `used_memory()` and raising a Lua error.
19use mlua::{Error as LuaError, HookTriggers, Lua, Table, Value, VmState};
20use std::cell::Cell;
21use std::rc::Rc;
22use std::time::{Duration, Instant};
24const SMALL: &str = include_str!("../plugins/small.lua");
25const OOM_TABLE: &str = include_str!("../plugins/oom_table.lua");
26const OOM_STRING: &str = include_str!("../plugins/oom_string.lua");
27const HOST_VALUE: &str = include_str!("../plugins/host_value.lua");
29const MIB: usize = 1024 * 1024;
30/// Per-plugin heap quota under test.
31const QUOTA: usize = 16 * MIB;
32/// Absolute host-protection fuse (hook-based), far above the quota. If growth
33/// sails past this, enforcement is disproved but the host must still survive.
34const FUSE_BYTES: usize = 128 * MIB;
35/// Wall-clock fuse so an unenforced infinite loop cannot hang the prototype.
36const FUSE_SECS: u64 = 20;
37/// Guard hook granularity: check after EVERY instruction. Required because
38/// plugins/oom_string.lua doubles its allocation per iteration; a coarser
39/// check interval (e.g. 1000 instructions ≈ ~150 loop iterations) would let a
40/// doubling allocation overshoot to gigabytes between checks.
41const GUARD_EVERY: u32 = 1;
43// ---------------------------------------------------------------------------
44// PASS/FAIL bookkeeping (same style as p02)
45// ---------------------------------------------------------------------------
47struct Checker {
48 pass: bool,
49}
51impl Checker {
52 fn check(&mut self, label: &str, ok: bool) {
53 println!("{} {label}", if ok { "PASS" } else { "FAIL" });
54 self.pass &= ok;
55 }
56 fn note(&self, msg: &str) {
57 println!(" {msg}");
58 }
59}
61// ---------------------------------------------------------------------------
62// Probing: does the native limit exist? do count hooks fire under LuaJIT?
63// ---------------------------------------------------------------------------
65struct Plan {
66 /// Result of `set_memory_limit(QUOTA)` on a throwaway state.
67 native: Result<usize, String>,
68 /// Count-hook fires over a bounded 3e6-iteration loop, JIT on.
69 hook_fires_jit_on: u64,
70 /// Same with `jit.off()` first.
71 hook_fires_jit_off: u64,
72}
74impl Plan {
75 fn native_available(&self) -> bool {
76 self.native.is_ok()
77 }
78 fn hooks_fire(&self) -> bool {
79 self.hook_fires_jit_on > 0 || self.hook_fires_jit_off > 0
80 }
81 /// Hooks only fire with the JIT compiler off.
82 fn need_jit_off(&self) -> bool {
83 self.hook_fires_jit_on == 0 && self.hook_fires_jit_off > 0
84 }
85}
87/// Run a bounded arithmetic loop (3e6 iterations) with an optional counting
88/// hook. Returns (hook fire count, elapsed).
89fn bench_loop(disable_jit: bool, hook_every: Option<u32>) -> (u64, Duration) {
90 let lua = Lua::new();
91 if disable_jit {
92 lua.load("if jit then jit.off() end").exec().expect("jit.off");
93 }
94 let fires = Rc::new(Cell::new(0u64));
95 if let Some(n) = hook_every {
96 let f = fires.clone();
97 lua.set_hook(HookTriggers::new().every_nth_instruction(n), move |_, _| {
98 f.set(f.get() + 1);
99 Ok(VmState::Continue)
100 });
101 }
102 let t = Instant::now();
103 let sum: f64 = lua
104 .load("local x = 0 for i = 1, 3000000 do x = x + i end return x")
105 .eval()
106 .expect("bench loop");
107 let elapsed = t.elapsed();
108 assert!(sum > 0.0);
109 (fires.get(), elapsed)
110}
112fn probe_plan() -> Plan {
113 let lua = Lua::new();
114 let native = lua.set_memory_limit(QUOTA).map_err(|e| e.to_string());
115 let (on, _) = bench_loop(false, Some(1000));
116 let (off, _) = bench_loop(true, Some(1000));
117 Plan {
118 native,
119 hook_fires_jit_on: on,
120 hook_fires_jit_off: off,
121 }
122}
124// ---------------------------------------------------------------------------
125// Guard: hook-based quota enforcement + host-protection fuse
126// ---------------------------------------------------------------------------
128/// Install a count hook that (a) enforces `hook_quota` if given (the fallback
129/// when the native limit is unavailable), and (b) always acts as a fuse so an
130/// unenforced runaway plugin cannot crash or hang the host.
131fn install_guard(lua: &Lua, hook_quota: Option<usize>) {
132 let start = Instant::now();
133 lua.set_hook(
134 HookTriggers::new().every_nth_instruction(GUARD_EVERY),
135 move |lua, _| {
136 let used = lua.used_memory();
137 if let Some(q) = hook_quota {
138 if used > q {
139 return Err(LuaError::RuntimeError(format!(
140 "P10-QUOTA: plugin heap quota exceeded (used {used} > quota {q})"
141 )));
142 }
143 }
144 if used > FUSE_BYTES {
145 return Err(LuaError::RuntimeError(format!(
146 "P10-FUSE-MEM: runaway allocation, host fuse tripped at {used} bytes"
147 )));
148 }
149 if start.elapsed() > Duration::from_secs(FUSE_SECS) {
150 return Err(LuaError::RuntimeError(
151 "P10-FUSE-TIME: wall-clock fuse tripped".into(),
152 ));
153 }
154 Ok(VmState::Continue)
155 },
156 );
157}
159fn err_kind(e: &LuaError) -> &'static str {
160 let s = format!("{e} {e:?}");
161 if matches!(e, LuaError::MemoryError(_)) || s.contains("not enough memory") || s.contains("MemoryError") {
162 "native-memory-error"
163 } else if s.contains("P10-QUOTA") {
164 "hook-quota"
165 } else if s.contains("P10-FUSE") {
166 "fuse"
167 } else {
168 "other"
169 }
170}
172fn err_line(e: &LuaError) -> String {
173 let full = e.to_string();
174 full.lines().next().unwrap_or("").chars().take(160).collect()
175}
177// ---------------------------------------------------------------------------
178// Growth run: one plugin state, one growth script, full observation
179// ---------------------------------------------------------------------------
181struct GrowthRun {
182 /// "completed" or an err_kind.
183 outcome: &'static str,
184 err_line: String,
185 base: usize,
186 peak: usize,
187 after_gc: usize,
188 /// State still usable after the error (gc_collect + trivial eval).
189 recovered: bool,
190}
192fn run_growth(
193 script: &str,
194 name: &str,
195 use_native: bool,
196 hook_quota: Option<usize>,
197 jit_off: bool,
198) -> GrowthRun {
199 let lua = Lua::new();
200 if jit_off {
201 let _ = lua.load("if jit then jit.off() end").exec();
202 }
203 if use_native {
204 lua.set_memory_limit(QUOTA)
205 .expect("native limit accepted by probe but rejected here");
206 }
207 let base = lua.used_memory();
208 install_guard(&lua, hook_quota);
209 let result: Result<Value, LuaError> = lua.load(script).set_name(name).eval();
210 let peak = lua.used_memory();
211 lua.remove_hook();
212 // Host recovery behavior after a plugin OOM: collect the dead plugin
213 // chunk's garbage, then verify the state still evaluates.
214 let _ = lua.gc_collect();
215 let _ = lua.gc_collect();
216 let after_gc = lua.used_memory();
217 let recovered = lua
218 .load("return 1 + 1")
219 .eval::<i64>()
220 .map(|v| v == 2)
221 .unwrap_or(false);
222 let (outcome, err_line) = match &result {
223 Ok(_) => ("completed", String::new()),
224 Err(e) => (err_kind(e), err_line(e)),
225 };
226 GrowthRun {
227 outcome,
228 err_line,
229 base,
230 peak,
231 after_gc,
232 recovered,
233 }
234}
236/// A quota-guarded plugin state using the best available mechanism.
237fn guarded_state(plan: &Plan, quota: usize) -> (Lua, &'static str) {
238 let lua = Lua::new();
239 if plan.need_jit_off() {
240 let _ = lua.load("if jit then jit.off() end").exec();
241 }
242 if lua.set_memory_limit(quota).is_ok() {
243 install_guard(&lua, None); // fuse only; native limit enforces
244 (lua, "native")
245 } else if plan.hooks_fire() {
246 install_guard(&lua, Some(quota));
247 (lua, "hook-fallback")
248 } else {
249 (lua, "UNENFORCED")
250 }
251}
253// ---------------------------------------------------------------------------
254// Scenarios
255// ---------------------------------------------------------------------------
257fn scenario_small(c: &mut Checker, plan: &Plan) -> Result<(), LuaError> {
258 println!("--- small: plugin stays under the {} MiB quota ---", QUOTA / MIB);
259 let (lua, mode) = guarded_state(plan, QUOTA);
260 c.note(&format!("enforcement mode: {mode}"));
261 let base = lua.used_memory();
262 let result: Result<Table, LuaError> = lua.load(SMALL).set_name("plugins/small.lua").eval();
263 let used = lua.used_memory();
264 c.check(
265 &format!("small: used_memory() reports nonzero baseline and growth ({base} -> {used} bytes)"),
266 base > 0 && used > base,
267 );
268 match result {
269 Ok(t) => {
270 let count: i64 = t.get("count")?;
271 c.check(
272 &format!("small: plugin under quota completes normally (count={count})"),
273 count == 1000,
274 );
275 }
276 Err(e) => c.check(&format!("small: plugin failed unexpectedly: {}", err_line(&e)), false),
277 }
278 Ok(())
279}
281fn scenario_oom(c: &mut Checker, plan: &Plan, name: &str, script: &str) -> Result<(), LuaError> {
282 println!("--- {name}: unbounded growth vs {} MiB quota ---", QUOTA / MIB);
283 match &plan.native {
284 Ok(prev) => c.note(&format!(
285 "probe: set_memory_limit({QUOTA}) = Ok(prev={prev}) — native limit ACCEPTED under mlua 0.10 + vendored LuaJIT"
286 )),
287 Err(e) => c.note(&format!(
288 "probe: set_memory_limit({QUOTA}) = Err({e}) — native limit UNAVAILABLE under mlua 0.10 + vendored LuaJIT"
289 )),
290 }
292 if !plan.native_available() && !plan.hooks_fire() {
293 // No native limit and no firing hooks: running unbounded growth would
294 // crash the host. Refusing to run IS the disproof demonstration.
295 c.check(
296 &format!(
297 "{name}: DISPROVED — set_memory_limit unavailable AND count hooks never fire \
298 (jit-on fires={}, jit-off fires={}); per-plugin heap quota is not implementable; \
299 refusing to run unbounded growth (would crash host)",
300 plan.hook_fires_jit_on, plan.hook_fires_jit_off
301 ),
302 true,
303 );
304 return Ok(());
305 }
307 // Phase 1: native enforcement if available (hook acts as fuse only),
308 // otherwise hook-based quota.
309 let native = plan.native_available();
310 let hook_quota = if native { None } else { Some(QUOTA) };
311 let run = run_growth(script, name, native, hook_quota, plan.need_jit_off());
313 c.check(
314 &format!(
315 "{name}: used_memory() observes growth ({} -> {} bytes at failure)",
316 run.base, run.peak
317 ),
318 run.peak > run.base,
319 );
320 c.note(&format!("outcome={} err='{}'", run.outcome, run.err_line));
321 c.note(&format!(
322 "used_memory: base={} peak-at-failure={} overshoot-vs-quota={} after-gc={}",
323 run.base,
324 run.peak,
325 run.peak.saturating_sub(QUOTA),
326 run.after_gc
327 ));
329 match run.outcome {
330 "native-memory-error" => {
331 c.check(
332 &format!("{name}: native set_memory_limit enforced the quota with a recoverable Lua memory error"),
333 true,
334 );
335 }
336 "hook-quota" => {
337 c.check(
338 &format!(
339 "{name}: hook-fallback quota enforced (granularity: every {GUARD_EVERY} instruction(s), overshoot {} bytes)",
340 run.peak.saturating_sub(QUOTA)
341 ),
342 true,
343 );
344 }
345 "fuse" => {
346 if native {
347 c.note(
348 "set_memory_limit returned Ok but DID NOT enforce — growth sailed past the quota to the host fuse",
349 );
350 // Phase 2: measure the hook fallback on a fresh state.
351 if plan.hooks_fire() {
352 let run2 = run_growth(script, name, false, Some(QUOTA), plan.need_jit_off());
353 c.note(&format!(
354 "fallback outcome={} err='{}' peak={} overshoot={}",
355 run2.outcome,
356 run2.err_line,
357 run2.peak,
358 run2.peak.saturating_sub(QUOTA)
359 ));
360 c.check(
361 &format!("{name}: hook-fallback quota enforced after native limit proved to be a no-op"),
362 run2.outcome == "hook-quota" && run2.recovered,
363 );
364 } else {
365 c.check(
366 &format!("{name}: DISPROVED — native limit is a silent no-op and hooks never fire; only the coarse fuse protected the host"),
367 true,
368 );
369 }
370 } else {
371 c.check(
372 &format!("{name}: hook quota failed to stop growth before the fuse (unexpected)"),
373 false,
374 );
375 }
376 }
377 "completed" => {
378 c.check(&format!("{name}: unbounded growth script terminated without error (unexpected)"), false);
379 }
380 _ => {
381 c.check(&format!("{name}: unexpected error kind: {}", run.err_line), false);
382 }
383 }
385 c.check(&format!("{name}: host process survived the OOM scenario"), true);
386 c.check(
387 &format!(
388 "{name}: plugin Lua state usable after quota error (gc_collect, then eval; used after gc = {} bytes)",
389 run.after_gc
390 ),
391 run.recovered,
392 );
393 Ok(())
394}
396fn scenario_isolation(c: &mut Checker, plan: &Plan) -> Result<(), LuaError> {
397 println!("--- isolation: plugin A OOMs, plugin B keeps working ---");
399 // One Lua state per plugin (the PLAN's primary model).
400 let (lua_b, mode_b) = guarded_state(plan, QUOTA);
401 let warm: i64 = lua_b.load("K = 41 return K").eval()?;
402 c.check(
403 &format!("isolation: plugin B (own Lua state, mode {mode_b}) warms up (K={warm})"),
404 warm == 41,
405 );
407 if !plan.native_available() && !plan.hooks_fire() {
408 c.check(
409 "isolation: DISPROVED — no enforcement mechanism; skipping plugin A unbounded growth (would crash host)",
410 true,
411 );
412 } else {
413 let native = plan.native_available();
414 let hook_quota = if native { None } else { Some(QUOTA) };
415 let run_a = run_growth(
416 OOM_TABLE,
417 "plugins/oom_table.lua (plugin A)",
418 native,
419 hook_quota,
420 plan.need_jit_off(),
421 );
422 c.note(&format!(
423 "plugin A outcome={} err='{}' peak={}",
424 run_a.outcome, run_a.err_line, run_a.peak
425 ));
426 c.check(
427 "isolation: plugin A growth stopped by quota (recoverable error, no host crash)",
428 matches!(run_a.outcome, "native-memory-error" | "hook-quota"),
429 );
430 c.check(
431 "isolation: plugin A state itself is recoverable after its OOM",
432 run_a.recovered,
433 );
434 }
436 // Plugin B must be unaffected: prior state intact and new work runs.
437 let k: i64 = lua_b.load("return K + 1").eval()?;
438 let b_result: Result<Table, LuaError> = lua_b.load(SMALL).set_name("plugins/small.lua").eval();
439 let b_count = b_result.and_then(|t| t.get::<i64>("count")).unwrap_or(-1);
440 c.check(
441 &format!("isolation: plugin B unaffected after plugin A OOM (K+1={k}, small run count={b_count})"),
442 k == 42 && b_count == 1000,
443 );
445 // Shared-state per-plugin quota attempt (the PLAN asks: enforceable or
446 // impossible?). Bounded allocations only — safe with or without quota.
447 println!("--- isolation: shared-state per-plugin quota attempt ---");
448 let shared = Lua::new();
449 if plan.need_jit_off() {
450 let _ = shared.load("if jit then jit.off() end").exec();
451 }
452 shared
453 .load("A = {} for i = 1, 100000 do A[i] = string.rep('x', 100) .. i end return 'ok'")
454 .set_name("shared: plugin A retains ~12 MiB")
455 .exec()?;
456 let _ = shared.gc_collect();
457 let _ = shared.gc_collect();
458 let used_a = shared.used_memory();
459 c.note(&format!("plugin A retained {used_a} bytes in the shared state"));
461 let mode = if shared.set_memory_limit(QUOTA).is_ok() {
462 "native"
463 } else if plan.hooks_fire() {
464 install_guard(&shared, Some(QUOTA));
465 "hook-fallback"
466 } else {
467 "UNENFORCED"
468 };
470 if mode == "UNENFORCED" {
471 c.check(
472 "isolation: shared-state quota attempt skipped — no enforcement mechanism exists at all",
473 true,
474 );
475 } else {
476 // "Plugin B's quota": the only knob is the WHOLE state. B allocates
477 // ~12 MiB of its own, but A's retained memory already counts.
478 let rb: Result<i64, LuaError> = shared
479 .load("local B = {} for i = 1, 100000 do B[i] = string.rep('y', 100) .. i end return #B")
480 .set_name("shared: plugin B allocates ~12 MiB")
481 .eval();
482 let used_at_end = shared.used_memory();
483 match rb {
484 Err(e) => {
485 let b_own = used_at_end.saturating_sub(used_a);
486 c.note(&format!(
487 "shared-state ({mode}) error: '{}' — B charged at total={used_at_end} bytes while B's own allocations were only ~{b_own} bytes",
488 err_line(&e)
489 ));
490 c.check(
491 "isolation: shared-state quota charges plugin B for plugin A's retained memory — per-plugin quotas in a shared state are NOT enforceable; quota domain must be one Lua state per plugin",
492 true,
493 );
494 }
495 Ok(n) => {
496 c.check(
497 &format!(
498 "isolation: shared-state quota unexpectedly NOT tripped (B completed n={n}, total used={used_at_end}, quota={QUOTA})"
499 ),
500 false,
501 );
502 }
503 }
504 }
505 println!(" QUOTA DOMAIN: per-plugin heap quota requires one Lua state per plugin; a shared state offers only a whole-state limit with no per-plugin attribution");
506 Ok(())
507}
509fn scenario_host_value(c: &mut Checker, plan: &Plan) -> Result<(), LuaError> {
510 println!("--- host-value: accounting of host-created values exposed to Lua ---");
511 let lua = Lua::new();
512 let _ = lua.gc_collect();
513 let m0 = lua.used_memory();
515 // 8 MiB host bytes -> Lua string (allocated on the Lua heap).
516 let blob = vec![b'z'; 8 * MIB];
517 let s = lua.create_string(&blob)?;
518 lua.globals().set("HOST_BLOB", s)?;
519 let m1 = lua.used_memory();
520 let d_blob = m1.saturating_sub(m0);
521 c.check(
522 &format!("host-value: 8 MiB host-created Lua string IS accounted by used_memory (delta={d_blob} bytes)"),
523 d_blob >= 7 * MIB,
524 );
526 // 8 MiB Rust Vec behind userdata (payload lives on the Rust side).
527 let ud = lua.create_any_userdata(vec![0u8; 8 * MIB])?;
528 lua.globals().set("HOST_UD", ud)?;
529 let m2 = lua.used_memory();
530 let d_ud = m2.saturating_sub(m1);
531 let counted = d_ud >= 7 * MIB;
532 c.note(&format!(
533 "host userdata with 8 MiB Rust Vec payload: used_memory delta={d_ud} bytes -> Rust-side payload {} by Lua accounting",
534 if counted { "IS counted" } else { "is NOT counted (accounting gap: quota cannot see host-side plugin allocations)" }
535 ));
536 c.check("host-value: userdata Rust-payload accounting measured and reported", true);
538 // The plugin can observe both values.
539 let t: Table = lua.load(HOST_VALUE).set_name("plugins/host_value.lua").eval()?;
540 let blob_len: i64 = t.get("blob_len")?;
541 let ud_type: String = t.get("ud_type")?;
542 c.check(
543 &format!("host-value: plugin observes host values (blob_len={blob_len}, ud_type={ud_type})"),
544 blob_len == (8 * MIB) as i64 && ud_type == "userdata",
545 );
547 // Interaction with the limit: creating a host value bigger than the quota.
548 if plan.native_available() {
549 let lua2 = Lua::new();
550 lua2.set_memory_limit(4 * MIB)
551 .expect("native limit accepted by probe");
552 match lua2.create_string(&blob) {
553 Err(e) => {
554 c.note(&format!("create_string(8 MiB) under 4 MiB native limit -> Err: {}", err_line(&e)));
555 c.check(
556 "host-value: host-side big-value creation hits the native limit as a recoverable Rust-side error",
557 matches!(err_kind(&e), "native-memory-error"),
558 );
559 }
560 Ok(_) => {
561 c.check(
562 "host-value: FINDING — create_string(8 MiB) succeeded despite 4 MiB native limit (host-side allocations bypass the limit)",
563 true,
564 );
565 }
566 }
567 } else {
568 c.note("native limit unavailable: host-side creations can only be policed by checking used_memory() manually after each boundary call");
569 }
570 Ok(())
571}
573fn scenario_bench(c: &mut Checker, plan: &Plan) {
574 println!("--- bench: count-hook fallback cost/granularity (bounded 3e6-iter loop) ---");
575 let (_, base_on) = bench_loop(false, None);
576 let (_, base_off) = bench_loop(true, None);
577 let (f_on_1000, t_on_1000) = bench_loop(false, Some(1000));
578 let (f_off_1000, t_off_1000) = bench_loop(true, Some(1000));
579 let (f_off_1, t_off_1) = bench_loop(true, Some(1));
580 c.note(&format!("jit-on, no hook: {base_on:?}"));
581 c.note(&format!("jit-off, no hook: {base_off:?}"));
582 c.note(&format!("jit-on, hook every 1000: {t_on_1000:?} ({f_on_1000} fires)"));
583 c.note(&format!("jit-off, hook every 1000: {t_off_1000:?} ({f_off_1000} fires)"));
584 c.note(&format!("jit-off, hook every 1: {t_off_1:?} ({f_off_1} fires)"));
585 c.check(
586 &format!(
587 "bench: hook firing measured (jit-on fires={}, jit-off fires={})",
588 plan.hook_fires_jit_on, plan.hook_fires_jit_off
589 ),
590 true,
591 );
592}
594// ---------------------------------------------------------------------------
596fn main() {
597 let arg = std::env::args().nth(1).unwrap_or_default();
598 let scenarios: Vec<&str> = match arg.as_str() {
599 "small" => vec!["small"],
600 "oom-table" => vec!["oom-table"],
601 "oom-string" => vec!["oom-string"],
602 "isolation" => vec!["isolation"],
603 "host-value" => vec!["host-value"],
604 "all" => vec!["small", "oom-table", "oom-string", "isolation", "host-value", "bench"],
605 _ => {
606 eprintln!("usage: p10-lua-plugin-heap-limit small|oom-table|oom-string|isolation|host-value|all");
607 std::process::exit(2);
608 }
609 };
611 let plan = probe_plan();
612 println!(
613 "probe: set_memory_limit({QUOTA}) on fresh state -> {}",
614 match &plan.native {
615 Ok(prev) => format!("Ok(prev={prev})"),
616 Err(e) => format!("Err({e})"),
617 }
618 );
619 println!(
620 "probe: count-hook fires over bounded loop: jit-on={} jit-off={}",
621 plan.hook_fires_jit_on, plan.hook_fires_jit_off
622 );
623 println!();
625 let mut c = Checker { pass: true };
626 for s in scenarios {
627 let r = match s {
628 "small" => scenario_small(&mut c, &plan),
629 "oom-table" => scenario_oom(&mut c, &plan, "oom-table", OOM_TABLE),
630 "oom-string" => scenario_oom(&mut c, &plan, "oom-string", OOM_STRING),
631 "isolation" => scenario_isolation(&mut c, &plan),
632 "host-value" => scenario_host_value(&mut c, &plan),
633 "bench" => {
634 scenario_bench(&mut c, &plan);
635 Ok(())
636 }
637 _ => unreachable!(),
638 };
639 if let Err(e) = r {
640 c.check(&format!("{s}: scenario aborted with error: {e}"), false);
641 }
642 println!();
643 }
645 println!(
646 "quota domain statement: per-plugin heap quota = one Lua state per plugin (native set_memory_limit {}); shared-state per-plugin quotas are not attributable",
647 if plan.native_available() { "available" } else { "UNAVAILABLE, hook fallback measured" }
648 );
649 if c.pass {
650 println!("p10 RESULT: all expectations hold");
651 } else {
652 println!("p10 RESULT: expectation failed");
653 std::process::exit(1);
654 }
655}

prototypes/p11-plugin-memory-domain-reload/Cargo.lock

Added
new file mode 100644

+383 / −0 text lines

1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "autocfg"
7version = "1.5.1"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
11[[package]]
12name = "bitflags"
13version = "2.13.0"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
17[[package]]
18name = "bstr"
19version = "1.12.3"
20source = "registry+https://github.com/rust-lang/crates.io-index"
21checksum = "5cee35f73844aa3014bb606320a6c1f010249dbdf43342fe54b5a4f6a8ed4b79"
22dependencies = [
23 "memchr",
24 "serde_core",
25]
27[[package]]
28name = "bumpalo"
29version = "3.20.3"
30source = "registry+https://github.com/rust-lang/crates.io-index"
31checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
33[[package]]
34name = "cc"
35version = "1.2.67"
36source = "registry+https://github.com/rust-lang/crates.io-index"
37checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38"
38dependencies = [
39 "find-msvc-tools",
40 "shlex",
41]
43[[package]]
44name = "cfg-if"
45version = "1.0.4"
46source = "registry+https://github.com/rust-lang/crates.io-index"
47checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
49[[package]]
50name = "either"
51version = "1.16.0"
52source = "registry+https://github.com/rust-lang/crates.io-index"
53checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
55[[package]]
56name = "env_home"
57version = "0.1.0"
58source = "registry+https://github.com/rust-lang/crates.io-index"
59checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
61[[package]]
62name = "erased-serde"
63version = "0.4.10"
64source = "registry+https://github.com/rust-lang/crates.io-index"
65checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
66dependencies = [
67 "serde",
68 "serde_core",
69 "typeid",
70]
72[[package]]
73name = "errno"
74version = "0.3.14"
75source = "registry+https://github.com/rust-lang/crates.io-index"
76checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
77dependencies = [
78 "libc",
79 "windows-sys",
80]
82[[package]]
83name = "find-msvc-tools"
84version = "0.1.9"
85source = "registry+https://github.com/rust-lang/crates.io-index"
86checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
88[[package]]
89name = "libc"
90version = "0.2.186"
91source = "registry+https://github.com/rust-lang/crates.io-index"
92checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
94[[package]]
95name = "linux-raw-sys"
96version = "0.12.1"
97source = "registry+https://github.com/rust-lang/crates.io-index"
98checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
100[[package]]
101name = "lock_api"
102version = "0.4.14"
103source = "registry+https://github.com/rust-lang/crates.io-index"
104checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
105dependencies = [
106 "scopeguard",
107]
109[[package]]
110name = "lua-src"
111version = "547.0.0"
112source = "registry+https://github.com/rust-lang/crates.io-index"
113checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42"
114dependencies = [
115 "cc",
116]
118[[package]]
119name = "luajit-src"
120version = "210.5.12+a4f56a4"
121source = "registry+https://github.com/rust-lang/crates.io-index"
122checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671"
123dependencies = [
124 "cc",
125 "which",
126]
128[[package]]
129name = "memchr"
130version = "2.8.3"
131source = "registry+https://github.com/rust-lang/crates.io-index"
132checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
134[[package]]
135name = "mlua"
136version = "0.10.5"
137source = "registry+https://github.com/rust-lang/crates.io-index"
138checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0"
139dependencies = [
140 "bstr",
141 "either",
142 "erased-serde",
143 "mlua-sys",
144 "num-traits",
145 "parking_lot",
146 "rustc-hash",
147 "rustversion",
148 "serde",
149 "serde-value",
150]
152[[package]]
153name = "mlua-sys"
154version = "0.6.8"
155source = "registry+https://github.com/rust-lang/crates.io-index"
156checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93"
157dependencies = [
158 "cc",
159 "cfg-if",
160 "lua-src",
161 "luajit-src",
162 "pkg-config",
163]
165[[package]]
166name = "num-traits"
167version = "0.2.19"
168source = "registry+https://github.com/rust-lang/crates.io-index"
169checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
170dependencies = [
171 "autocfg",
172]
174[[package]]
175name = "ordered-float"
176version = "2.10.1"
177source = "registry+https://github.com/rust-lang/crates.io-index"
178checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
179dependencies = [
180 "num-traits",
181]
183[[package]]
184name = "p11-plugin-memory-domain-reload"
185version = "0.1.0"
186dependencies = [
187 "bumpalo",
188 "mlua",
189]
191[[package]]
192name = "parking_lot"
193version = "0.12.5"
194source = "registry+https://github.com/rust-lang/crates.io-index"
195checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
196dependencies = [
197 "lock_api",
198 "parking_lot_core",
199]
201[[package]]
202name = "parking_lot_core"
203version = "0.9.12"
204source = "registry+https://github.com/rust-lang/crates.io-index"
205checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
206dependencies = [
207 "cfg-if",
208 "libc",
209 "redox_syscall",
210 "smallvec",
211 "windows-link",
212]
214[[package]]
215name = "pkg-config"
216version = "0.3.33"
217source = "registry+https://github.com/rust-lang/crates.io-index"
218checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
220[[package]]
221name = "proc-macro2"
222version = "1.0.106"
223source = "registry+https://github.com/rust-lang/crates.io-index"
224checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
225dependencies = [
226 "unicode-ident",
227]
229[[package]]
230name = "quote"
231version = "1.0.46"
232source = "registry+https://github.com/rust-lang/crates.io-index"
233checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
234dependencies = [
235 "proc-macro2",
236]
238[[package]]
239name = "redox_syscall"
240version = "0.5.18"
241source = "registry+https://github.com/rust-lang/crates.io-index"
242checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
243dependencies = [
244 "bitflags",
245]
247[[package]]
248name = "rustc-hash"
249version = "2.1.3"
250source = "registry+https://github.com/rust-lang/crates.io-index"
251checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
253[[package]]
254name = "rustix"
255version = "1.1.4"
256source = "registry+https://github.com/rust-lang/crates.io-index"
257checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
258dependencies = [
259 "bitflags",
260 "errno",
261 "libc",
262 "linux-raw-sys",
263 "windows-sys",
264]
266[[package]]
267name = "rustversion"
268version = "1.0.23"
269source = "registry+https://github.com/rust-lang/crates.io-index"
270checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
272[[package]]
273name = "scopeguard"
274version = "1.2.0"
275source = "registry+https://github.com/rust-lang/crates.io-index"
276checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
278[[package]]
279name = "serde"
280version = "1.0.228"
281source = "registry+https://github.com/rust-lang/crates.io-index"
282checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
283dependencies = [
284 "serde_core",
285]
287[[package]]
288name = "serde-value"
289version = "0.7.0"
290source = "registry+https://github.com/rust-lang/crates.io-index"
291checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
292dependencies = [
293 "ordered-float",
294 "serde",
295]
297[[package]]
298name = "serde_core"
299version = "1.0.228"
300source = "registry+https://github.com/rust-lang/crates.io-index"
301checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
302dependencies = [
303 "serde_derive",
304]
306[[package]]
307name = "serde_derive"
308version = "1.0.228"
309source = "registry+https://github.com/rust-lang/crates.io-index"
310checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
311dependencies = [
312 "proc-macro2",
313 "quote",
314 "syn",
315]
317[[package]]
318name = "shlex"
319version = "2.0.1"
320source = "registry+https://github.com/rust-lang/crates.io-index"
321checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
323[[package]]
324name = "smallvec"
325version = "1.15.2"
326source = "registry+https://github.com/rust-lang/crates.io-index"
327checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
329[[package]]
330name = "syn"
331version = "2.0.118"
332source = "registry+https://github.com/rust-lang/crates.io-index"
333checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
334dependencies = [
335 "proc-macro2",
336 "quote",
337 "unicode-ident",
338]
340[[package]]
341name = "typeid"
342version = "1.0.3"
343source = "registry+https://github.com/rust-lang/crates.io-index"
344checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
346[[package]]
347name = "unicode-ident"
348version = "1.0.24"
349source = "registry+https://github.com/rust-lang/crates.io-index"
350checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
352[[package]]
353name = "which"
354version = "7.0.3"
355source = "registry+https://github.com/rust-lang/crates.io-index"
356checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762"
357dependencies = [
358 "either",
359 "env_home",
360 "rustix",
361 "winsafe",
362]
364[[package]]
365name = "windows-link"
366version = "0.2.1"
367source = "registry+https://github.com/rust-lang/crates.io-index"
368checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
370[[package]]
371name = "windows-sys"
372version = "0.61.2"
373source = "registry+https://github.com/rust-lang/crates.io-index"
374checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
375dependencies = [
376 "windows-link",
377]
379[[package]]
380name = "winsafe"
381version = "0.0.19"
382source = "registry+https://github.com/rust-lang/crates.io-index"
383checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"

prototypes/p11-plugin-memory-domain-reload/Cargo.toml

Added
new file mode 100644

+9 / −0 text lines

1[package]
2name = "p11-plugin-memory-domain-reload"
3version = "0.1.0"
4edition = "2021"
5publish = false
6
7[dependencies]
8mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }
9bumpalo = "3"

prototypes/p11-plugin-memory-domain-reload/plugins/grow.lua

Added
new file mode 100644

+25 / −0 text lines

1-- grow.lua: allocates Lua memory on every hook call.
2--
3-- Every allocation stays reachable via `chunks`, so the domain's Lua heap
4-- grows for the domain's whole lifetime. Reclaim can only come from dropping
5-- the whole domain (SPEC §9.16), never from per-call cleanup.
6
7local chunks = {}
8
9smith.register_hook("grow/on_tick", function(n)
10 -- ~4 KiB unique string per call, kept alive forever (within this domain).
11 chunks[#chunks + 1] = string.rep("x", 4096) .. tostring(n)
12 return #chunks
13end)
15smith.register_tool("grow/stats", function()
16 local bytes = 0
17 for _, c in ipairs(chunks) do
18 bytes = bytes + #c
19 end
20 return bytes
21end)
23smith.bus_on("grow/topic", function(payload)
24 return payload
25end)

prototypes/p11-plugin-memory-domain-reload/plugins/register_many.lua

Added
new file mode 100644

+19 / −0 text lines

1-- register_many.lua: registers many hooks/tools/bus subscriptions so that
2-- domain-keyed registry teardown (SPEC §9.16) is exercised at scale on every
3-- reload cycle: 200 hooks + 200 tools + 50 bus subscriptions.
4
5for i = 1, 200 do
6 local n = i
7 smith.register_hook("many/hook_" .. n, function()
8 return n
9 end)
10 smith.register_tool("many/tool_" .. n, function()
11 return n * 2
12 end)
13end
15for i = 1, 50 do
16 smith.bus_on("many/topic_" .. i, function(p)
17 return p
18 end)
19end

prototypes/p11-plugin-memory-domain-reload/src/main.rs

Added
new file mode 100644

+1063 / −0 text lines

1//! p11-plugin-memory-domain-reload
2//!
3//! Validates docs/SPEC.md §9.16 (Plugin Hot-Reload) as a full contract:
4//!
5//! - a `PluginDomain` owns the plugin's Lua state, descriptors, hook/tool
6//! registrations (host-side maps keyed by domain generation), bus
7//! subscriptions (§9.18, token dropped with the domain), render/layout
8//! cache, host scratch (bumpalo arena), and a cancellation token for
9//! plugin tasks;
10//! - reload = construct D' -> atomic swap -> drop D; rollback keeps D on
11//! failure with D' partial registrations discarded (§9.17 entry-load
12//! error);
13//! - no stale callback may run after the swap: every dispatch path (hook,
14//! tool, bus delivery) is generation-gated;
15//! - repeated reloads plateau in memory (RSS via /proc/self/statm + Lua
16//! used_memory);
17//! - escaped resources (stale registry entry, raw callback clone, leaked
18//! subscription token, async task outliving the domain) are detected and
19//! rejected/cancelled with a clear error.
20//!
21//! Verify:
22//! cargo run -- reload-loop
23//! cargo run -- reload-with-heap-limit
24//! cargo run -- escaped-callback-fails
25//! cargo run -- all
27use std::cell::RefCell;
28use std::collections::HashMap;
29use std::fmt;
30use std::panic::{catch_unwind, AssertUnwindSafe};
31use std::rc::Rc;
32use std::sync::atomic::{AtomicBool, Ordering};
33use std::sync::{mpsc, Arc, OnceLock};
34use std::thread::{self, JoinHandle};
35use std::time::{Duration, Instant};
37use bumpalo::Bump;
38use mlua::{Function, Lua};
40const GROW_SRC: &str = include_str!("../plugins/grow.lua");
41const MANY_SRC: &str = include_str!("../plugins/register_many.lua");
42/// Broken entry code used to prove rollback (§9.16/§9.17): registers one
43/// hook (a partial registration), then fails during entry load.
44const BROKEN_SRC: &str = "smith.register_hook('broken/partial', function() end)\n\
45 error('intentional entry-load failure')";
47// ---------------------------------------------------------------------------
48// measurement helpers
49// ---------------------------------------------------------------------------
51fn page_size_bytes() -> u64 {
52 static PS: OnceLock<u64> = OnceLock::new();
53 *PS.get_or_init(|| {
54 std::process::Command::new("getconf")
55 .arg("PAGESIZE")
56 .output()
57 .ok()
58 .and_then(|o| String::from_utf8(o.stdout).ok())
59 .and_then(|s| s.trim().parse().ok())
60 .unwrap_or(4096)
61 })
62}
64/// Resident set size in KiB, from /proc/self/statm field 2 (resident pages).
65fn rss_kb() -> u64 {
66 let statm = std::fs::read_to_string("/proc/self/statm").expect("read /proc/self/statm");
67 let pages: u64 = statm
68 .split_whitespace()
69 .nth(1)
70 .expect("statm resident field")
71 .parse()
72 .expect("statm parse");
73 pages * page_size_bytes() / 1024
74}
76fn threads_now() -> u64 {
77 let status = std::fs::read_to_string("/proc/self/status").expect("read /proc/self/status");
78 status
79 .lines()
80 .find_map(|l| l.strip_prefix("Threads:"))
81 .and_then(|v| v.trim().parse().ok())
82 .unwrap_or(0)
83}
85fn first_line(s: &str) -> &str {
86 s.lines().next().unwrap_or("")
87}
89fn panic_msg(p: &(dyn std::any::Any + Send)) -> String {
90 p.downcast_ref::<&str>()
91 .map(|s| s.to_string())
92 .or_else(|| p.downcast_ref::<String>().cloned())
93 .unwrap_or_else(|| "<non-string panic payload>".into())
94}
96fn check(label: &str, ok: bool, detail: String) -> Result<(), String> {
97 if ok {
98 println!("PASS {label} — {detail}");
99 Ok(())
100 } else {
101 println!("FAIL {label} — {detail}");
102 Err(format!("{label}: {detail}"))
103 }
104}
106// ---------------------------------------------------------------------------
107// host error model (§9.17: clear, attributable errors; stale never runs)
108// ---------------------------------------------------------------------------
110#[derive(Debug)]
111enum HostError {
112 /// A callback addressed through a generation that no longer belongs to a
113 /// live domain. The callback is rejected *before* its Lua is touched.
114 StaleDomain {
115 kind: &'static str,
116 name: String,
117 gen: u64,
118 active: Vec<u64>,
119 },
120 Missing {
121 kind: &'static str,
122 name: String,
123 },
124 Lua(mlua::Error),
125}
127impl fmt::Display for HostError {
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 match self {
130 HostError::StaleDomain { kind, name, gen, active } => write!(
131 f,
132 "stale {kind} '{name}' from dead domain generation {gen} rejected \
133 (active generations: {active:?}); callback did not run"
134 ),
135 HostError::Missing { kind, name } => {
136 write!(f, "no {kind} named '{name}' in any live domain")
137 }
138 HostError::Lua(e) => write!(f, "lua error: {e}"),
139 }
140 }
141}
143// ---------------------------------------------------------------------------
144// bus (§9.18): subscriptions are domain-owned via tokens; delivery is
145// generation-gated and errors are isolated (§9.17)
146// ---------------------------------------------------------------------------
148/// Dropped with its owning domain; flips the shared liveness flag so the bus
149/// lazily reaps the subscription.
150struct SubToken {
151 alive: Arc<AtomicBool>,
152}
154impl Drop for SubToken {
155 fn drop(&mut self) {
156 self.alive.store(false, Ordering::SeqCst);
157 }
158}
160struct Subscriber {
161 gen: u64,
162 alive: Arc<AtomicBool>,
163 func: Function,
164}
166#[derive(Default)]
167struct Bus {
168 topics: HashMap<String, Vec<Subscriber>>,
169 isolated_errors: Vec<String>,
170}
172impl Bus {
173 fn subscribe(&mut self, gen: u64, topic: String, func: Function) -> SubToken {
174 let alive = Arc::new(AtomicBool::new(true));
175 self.topics
176 .entry(topic)
177 .or_default()
178 .push(Subscriber { gen, alive: alive.clone(), func });
179 SubToken { alive }
180 }
182 /// Deliver to live subscribers of active generations only. A subscriber
183 /// whose token died is silently reaped (normal domain teardown). A
184 /// subscriber whose token is alive but whose generation is dead is an
185 /// ESCAPE: it is rejected with a clear error and removed, without ever
186 /// touching its (dead) Lua.
187 fn emit(&mut self, topic: &str, payload: i64, active_gens: &[u64]) -> usize {
188 let Some(subs) = self.topics.get_mut(topic) else { return 0 };
189 let old = std::mem::take(subs);
190 let mut kept = Vec::with_capacity(old.len());
191 let mut delivered = 0usize;
192 let mut errs = Vec::new();
193 for s in old {
194 if !s.alive.load(Ordering::SeqCst) {
195 continue; // token dropped with its domain (§9.18)
196 }
197 if !active_gens.contains(&s.gen) {
198 errs.push(format!(
199 "bus '{topic}': escaped subscription from dead domain generation {} \
200 rejected & removed (token leaked past domain teardown); handler did not run",
201 s.gen
202 ));
203 continue;
204 }
205 match catch_unwind(AssertUnwindSafe(|| s.func.call::<i64>(payload))) {
206 Ok(Ok(_)) => {
207 delivered += 1;
208 kept.push(s);
209 }
210 Ok(Err(e)) => errs.push(format!(
211 "bus '{topic}': subscriber (gen {}) error isolated & removed: {}",
212 s.gen,
213 first_line(&e.to_string())
214 )),
215 Err(p) => errs.push(format!(
216 "bus '{topic}': subscriber (gen {}) panicked & removed: {}",
217 s.gen,
218 first_line(&panic_msg(p.as_ref()))
219 )),
220 }
221 }
222 self.topics.insert(topic.to_string(), kept);
223 self.isolated_errors.extend(errs);
224 delivered
225 }
227 fn purge_dead(&mut self) {
228 for subs in self.topics.values_mut() {
229 subs.retain(|s| s.alive.load(Ordering::SeqCst));
230 }
231 }
233 fn live_total(&self) -> usize {
234 self.topics
235 .values()
236 .flatten()
237 .filter(|s| s.alive.load(Ordering::SeqCst))
238 .count()
239 }
241 fn take_isolated_errors(&mut self) -> Vec<String> {
242 std::mem::take(&mut self.isolated_errors)
243 }
244}
246// ---------------------------------------------------------------------------
247// host: registries keyed by domain generation (§9.16)
248// ---------------------------------------------------------------------------
250struct Host {
251 next_gen: u64,
252 /// plugin name -> active domain generation (the swap flips this)
253 active: HashMap<String, u64>,
254 /// generation -> hook name -> callback
255 hooks: HashMap<u64, HashMap<String, Function>>,
256 /// generation -> tool name -> callback
257 tools: HashMap<u64, HashMap<String, Function>>,
258 bus: Bus,
259}
261impl Host {
262 fn new() -> Self {
263 Host {
264 next_gen: 0,
265 active: HashMap::new(),
266 hooks: HashMap::new(),
267 tools: HashMap::new(),
268 bus: Bus::default(),
269 }
270 }
272 fn alloc_gen(&mut self) -> u64 {
273 self.next_gen += 1;
274 self.next_gen
275 }
277 fn active_gens(&self) -> Vec<u64> {
278 let mut v: Vec<u64> = self.active.values().copied().collect();
279 v.sort_unstable();
280 v
281 }
283 fn is_active(&self, gen: u64) -> bool {
284 self.active.values().any(|g| *g == gen)
285 }
287 fn commit(&mut self, gen: u64, hooks: Vec<(String, Function)>, tools: Vec<(String, Function)>) {
288 self.hooks.entry(gen).or_default().extend(hooks);
289 self.tools.entry(gen).or_default().extend(tools);
290 }
292 /// Deterministic teardown: registrations are keyed by generation, so one
293 /// map removal drops every callback the domain ever registered.
294 fn remove_generation(&mut self, gen: u64) -> (usize, usize) {
295 (
296 self.hooks.remove(&gen).map_or(0, |m| m.len()),
297 self.tools.remove(&gen).map_or(0, |m| m.len()),
298 )
299 }
301 fn hook_total(&self) -> usize {
302 self.hooks.values().map(|m| m.len()).sum()
303 }
305 fn tool_total(&self) -> usize {
306 self.tools.values().map(|m| m.len()).sum()
307 }
309 /// Name-based dispatch: resolves in ACTIVE generations only. If the name
310 /// exists solely under a dead generation, that is a detected stale
311 /// callback and it is rejected without touching Lua.
312 fn invoke(&self, kind: &'static str, name: &str, arg: i64) -> Result<i64, HostError> {
313 let map = if kind == "hook" { &self.hooks } else { &self.tools };
314 for gen in self.active.values() {
315 if let Some(f) = map.get(gen).and_then(|m| m.get(name)) {
316 return f.call::<i64>(arg).map_err(HostError::Lua);
317 }
318 }
319 for (gen, m) in map {
320 if !self.is_active(*gen) && m.contains_key(name) {
321 return Err(HostError::StaleDomain {
322 kind,
323 name: name.to_string(),
324 gen: *gen,
325 active: self.active_gens(),
326 });
327 }
328 }
329 Err(HostError::Missing { kind, name: name.to_string() })
330 }
332 fn invoke_hook(&self, name: &str, arg: i64) -> Result<i64, HostError> {
333 self.invoke("hook", name, arg)
334 }
336 fn invoke_tool(&self, name: &str, arg: i64) -> Result<i64, HostError> {
337 self.invoke("tool", name, arg)
338 }
340 /// Generation-addressed dispatch (what an escaped task would attempt).
341 /// The generation gate runs before any Lua value is touched.
342 fn invoke_hook_from_gen(&self, gen: u64, name: &str, arg: i64) -> Result<i64, HostError> {
343 if !self.is_active(gen) {
344 return Err(HostError::StaleDomain {
345 kind: "hook",
346 name: name.to_string(),
347 gen,
348 active: self.active_gens(),
349 });
350 }
351 match self.hooks.get(&gen).and_then(|m| m.get(name)) {
352 Some(f) => f.call::<i64>(arg).map_err(HostError::Lua),
353 None => Err(HostError::Missing { kind: "hook", name: name.to_string() }),
354 }
355 }
357 fn emit(&mut self, topic: &str, payload: i64) -> usize {
358 let gens = self.active_gens();
359 self.bus.emit(topic, payload, &gens)
360 }
362 /// Sweep for anything registered under a non-active generation — i.e.
363 /// resources that escaped domain teardown. Empty in correct operation.
364 fn audit_stale(&self) -> Vec<String> {
365 let mut out = Vec::new();
366 for (gen, m) in &self.hooks {
367 if !self.is_active(*gen) {
368 for n in m.keys() {
369 out.push(format!("hook '{n}' (gen {gen})"));
370 }
371 }
372 }
373 for (gen, m) in &self.tools {
374 if !self.is_active(*gen) {
375 for n in m.keys() {
376 out.push(format!("tool '{n}' (gen {gen})"));
377 }
378 }
379 }
380 for (topic, subs) in &self.bus.topics {
381 for s in subs {
382 if s.alive.load(Ordering::SeqCst) && !self.is_active(s.gen) {
383 out.push(format!("bus subscription '{topic}' (gen {})", s.gen));
384 }
385 }
386 }
387 out.sort();
388 out
389 }
391 /// Remove everything the audit would flag. Returns removed entry count.
392 fn purge_stale(&mut self) -> usize {
393 let active = self.active_gens();
394 let mut n = 0;
395 let hook_gens: Vec<u64> =
396 self.hooks.keys().copied().filter(|g| !active.contains(g)).collect();
397 for g in hook_gens {
398 n += self.hooks.remove(&g).map_or(0, |m| m.len());
399 }
400 let tool_gens: Vec<u64> =
401 self.tools.keys().copied().filter(|g| !active.contains(g)).collect();
402 for g in tool_gens {
403 n += self.tools.remove(&g).map_or(0, |m| m.len());
404 }
405 for subs in self.bus.topics.values_mut() {
406 let before = subs.len();
407 subs.retain(|s| active.contains(&s.gen) && s.alive.load(Ordering::SeqCst));
408 n += before - subs.len();
409 }
410 n
411 }
412}
414// ---------------------------------------------------------------------------
415// PluginDomain (§9.16): owns ALL reloadable plugin state
416// ---------------------------------------------------------------------------
418struct PluginDomain {
419 name: &'static str,
420 generation: u64,
421 /// the plugin's whole Lua VM — dropped with the domain
422 lua: Lua,
423 /// plugin metadata/descriptors collected at load
424 hook_names: Vec<String>,
425 tool_names: Vec<String>,
426 /// TUI render/layout cache — domain-owned, dropped whole on reload
427 render_cache: HashMap<String, Vec<u8>>,
428 /// host-side scratch arena — reclaimed by dropping the domain, never by
429 /// per-allocation cleanup
430 scratch: Bump,
431 /// cancellation token for plugin async tasks
432 cancel: Arc<AtomicBool>,
433 task: Option<JoinHandle<u64>>,
434 /// bus subscription tokens — dropped with the domain (§9.18)
435 sub_tokens: Vec<SubToken>,
436}
438impl Drop for PluginDomain {
439 fn drop(&mut self) {
440 // Cancellation token: the domain's async task is told to stop and is
441 // joined, so no plugin task outlives the domain.
442 self.cancel.store(true, Ordering::SeqCst);
443 if let Some(t) = self.task.take() {
444 let _ = t.join();
445 }
446 // Implicit, orderless teardown of everything else the domain owns:
447 // sub_tokens drop -> bus subscriptions die; lua drops -> plugin heap
448 // reclaimed; render_cache + scratch drop -> host-side memory freed.
449 // No per-resource cleanup graph (§9.16: whole-domain replacement).
450 }
451}
453/// Construct a domain: fresh Lua, sandbox-ish `smith` API, run entry code,
454/// then commit registrations keyed by this domain's generation. On entry
455/// failure, NOTHING has reached the host: the partial registrations die with
456/// the local pending buffers and the Lua (§9.17 entry-load error).
457fn load_domain(
458 host: &mut Host,
459 name: &'static str,
460 src: &str,
461 gen: u64,
462) -> Result<PluginDomain, (mlua::Error, usize)> {
463 let lua = Lua::new();
464 type Pending = Rc<RefCell<Vec<(String, Function)>>>;
465 let p_hooks: Pending = Rc::new(RefCell::new(Vec::new()));
466 let p_tools: Pending = Rc::new(RefCell::new(Vec::new()));
467 let p_subs: Pending = Rc::new(RefCell::new(Vec::new()));
468 let setup = (|| -> mlua::Result<()> {
469 let smith = lua.create_table()?;
470 let ph = p_hooks.clone();
471 smith.set(
472 "register_hook",
473 lua.create_function(move |_, (n, f): (String, Function)| {
474 ph.borrow_mut().push((n, f));
475 Ok(())
476 })?,
477 )?;
478 let pt = p_tools.clone();
479 smith.set(
480 "register_tool",
481 lua.create_function(move |_, (n, f): (String, Function)| {
482 pt.borrow_mut().push((n, f));
483 Ok(())
484 })?,
485 )?;
486 let ps = p_subs.clone();
487 smith.set(
488 "bus_on",
489 lua.create_function(move |_, (t, f): (String, Function)| {
490 ps.borrow_mut().push((t, f));
491 Ok(())
492 })?,
493 )?;
494 lua.globals().set("smith", smith)?;
495 lua.load(src).set_name(name).exec()
496 })();
497 if let Err(e) = setup {
498 let partial =
499 p_hooks.borrow().len() + p_tools.borrow().len() + p_subs.borrow().len();
500 return Err((e, partial)); // D' dropped by caller; host untouched
501 }
502 let hooks: Vec<(String, Function)> = p_hooks.borrow_mut().drain(..).collect();
503 let tools: Vec<(String, Function)> = p_tools.borrow_mut().drain(..).collect();
504 let subs: Vec<(String, Function)> = p_subs.borrow_mut().drain(..).collect();
505 let hook_names = hooks.iter().map(|(n, _)| n.clone()).collect();
506 let tool_names = tools.iter().map(|(n, _)| n.clone()).collect();
507 host.commit(gen, hooks, tools);
508 let sub_tokens = subs
509 .into_iter()
510 .map(|(t, f)| host.bus.subscribe(gen, t, f))
511 .collect();
512 // Async-task escape hatch modeled with std::thread + a domain-owned
513 // cancellation flag. NOTE: without mlua's `send` feature, Lua values are
514 // !Send — a thread cannot capture a Lua callback AT COMPILE TIME, so a
515 // task can only carry plain data (e.g. a generation tag).
516 let cancel = Arc::new(AtomicBool::new(false));
517 let c = cancel.clone();
518 let task = thread::spawn(move || {
519 let mut ticks = 0u64;
520 while !c.load(Ordering::Relaxed) {
521 ticks += 1;
522 thread::sleep(Duration::from_millis(2));
523 }
524 ticks
525 });
526 Ok(PluginDomain {
527 name,
528 generation: gen,
529 lua,
530 hook_names,
531 tool_names,
532 render_cache: HashMap::new(),
533 scratch: Bump::new(),
534 cancel,
535 task: Some(task),
536 sub_tokens,
537 })
538}
540fn load_plugin(host: &mut Host, name: &'static str, src: &str) -> Result<PluginDomain, String> {
541 let gen = host.alloc_gen();
542 match load_domain(host, name, src, gen) {
543 Ok(d) => {
544 host.active.insert(name.to_string(), gen);
545 Ok(d)
546 }
547 Err((e, partial)) => Err(format!(
548 "load of '{name}' failed ({partial} partial registrations discarded): {}",
549 first_line(&e.to_string())
550 )),
551 }
552}
554/// §9.16 sequence: construct D' -> swap -> drop D. All-or-nothing: on load
555/// failure D is returned untouched (rollback) and D' partials are discarded.
556fn reload(
557 host: &mut Host,
558 old: PluginDomain,
559 src: &str,
560) -> Result<PluginDomain, (PluginDomain, String)> {
561 let name = old.name;
562 let old_gen = old.generation;
563 let new_gen = host.alloc_gen();
564 match load_domain(host, name, src, new_gen) {
565 Ok(new_dom) => {
566 host.active.insert(name.to_string(), new_gen); // atomic swap: rebind name -> D'
567 host.remove_generation(old_gen); // gen-keyed registrations gone deterministically
568 drop(old); // cancels+joins task, drops sub tokens, Lua, caches, scratch
569 host.bus.purge_dead(); // reap token-dead subscriptions eagerly
570 Ok(new_dom)
571 }
572 Err((e, partial)) => {
573 let msg = format!(
574 "reload of '{name}' failed; old domain gen {old_gen} kept active; \
575 {partial} partial registrations from D' discarded; error: {}",
576 first_line(&e.to_string())
577 );
578 Err((old, msg))
579 }
580 }
581}
583/// Unload = same teardown as the drop-D half of reload.
584fn unload(host: &mut Host, dom: PluginDomain) {
585 host.active.remove(dom.name);
586 host.remove_generation(dom.generation);
587 drop(dom);
588 host.bus.purge_dead();
589}
591// ---------------------------------------------------------------------------
592// "use" phase: exercise hooks/tools/bus + fill domain-owned cache & scratch
593// ---------------------------------------------------------------------------
595const CYCLES: usize = 100;
596const WARMUP: usize = 20;
597const GROW_CALLS: i64 = 200;
599fn exercise(host: &mut Host, grow: &mut PluginDomain, cycle: i64) -> Result<(), String> {
600 for i in 0..GROW_CALLS {
601 host.invoke_hook("grow/on_tick", i).map_err(|e| e.to_string())?;
602 }
603 host.invoke_tool("grow/stats", 0).map_err(|e| e.to_string())?;
604 for i in (1..=200usize).step_by(20) {
605 host.invoke_hook(&format!("many/hook_{i}"), 0).map_err(|e| e.to_string())?;
606 host.invoke_tool(&format!("many/tool_{i}"), 0).map_err(|e| e.to_string())?;
607 }
608 let d = host.emit("grow/topic", cycle) + host.emit("many/topic_7", cycle);
609 if d != 2 {
610 return Err(format!("cycle {cycle}: expected 2 bus deliveries, got {d}"));
611 }
612 let errs = host.bus.take_isolated_errors();
613 if !errs.is_empty() {
614 return Err(format!("cycle {cycle}: unexpected bus errors: {errs:?}"));
615 }
616 // render/layout cache lives in the domain and is dropped whole on reload
617 for w in 0..64 {
618 grow.render_cache.insert(format!("widget:{w}:{cycle}"), vec![0xAB; 4096]);
619 }
620 // host-side scratch: bump arena, reclaimed only by dropping the domain
621 for _ in 0..128 {
622 grow.scratch.alloc_slice_fill_copy(512, 0xCD_u8);
623 }
624 Ok(())
625}
627// ---------------------------------------------------------------------------
628// scenario: reload-loop
629// ---------------------------------------------------------------------------
631fn scenario_reload_loop() -> Result<(), String> {
632 println!("=== scenario: reload-loop ({CYCLES} load/use/reload cycles) ===");
633 let mut host = Host::new();
634 let mut grow = load_plugin(&mut host, "grow", GROW_SRC)?;
635 let mut many = load_plugin(&mut host, "many", MANY_SRC)?;
636 println!(
637 " descriptors: grow{{hooks:{},tools:{},subs:{}}} many{{hooks:{},tools:{},subs:{}}}",
638 grow.hook_names.len(),
639 grow.tool_names.len(),
640 grow.sub_tokens.len(),
641 many.hook_names.len(),
642 many.tool_names.len(),
643 many.sub_tokens.len()
644 );
645 check(
646 "registries keyed by domain generation",
647 host.hook_total() == 201 && host.tool_total() == 201 && host.bus.live_total() == 51,
648 format!(
649 "hooks={} tools={} bus_subs={}",
650 host.hook_total(),
651 host.tool_total(),
652 host.bus.live_total()
653 ),
654 )?;
655 let threads_base = threads_now();
656 let rss_initial = rss_kb();
657 let mut rss = Vec::with_capacity(CYCLES);
658 let mut lua_used = Vec::with_capacity(CYCLES);
659 let mut lat = Vec::with_capacity(CYCLES);
660 for cycle in 1..=CYCLES {
661 exercise(&mut host, &mut grow, cycle as i64)?;
662 let used_pre = grow.lua.used_memory();
663 let scratch_pre = grow.scratch.allocated_bytes();
664 let cache_pre = grow.render_cache.len();
665 let (og, om) = (grow.generation, many.generation);
666 let t0 = Instant::now();
667 grow = reload(&mut host, grow, GROW_SRC).map_err(|(_, e)| e)?;
668 many = reload(&mut host, many, MANY_SRC).map_err(|(_, e)| e)?;
669 lat.push(t0.elapsed());
670 // old generations fully gone from host registries
671 if host.hooks.contains_key(&og)
672 || host.hooks.contains_key(&om)
673 || host.tools.contains_key(&og)
674 || host.tools.contains_key(&om)
675 {
676 return Err(format!("cycle {cycle}: old generation registrations survived the swap"));
677 }
678 if host.hook_total() != 201 || host.tool_total() != 201 || host.bus.live_total() != 51 {
679 return Err(format!(
680 "cycle {cycle}: registry counts wrong after reload: hooks={} tools={} subs={}",
681 host.hook_total(),
682 host.tool_total(),
683 host.bus.live_total()
684 ));
685 }
686 let audit = host.audit_stale();
687 if !audit.is_empty() {
688 return Err(format!("cycle {cycle}: audit found escaped registrations: {audit:?}"));
689 }
690 // probing the old generation must be rejected, not executed
691 match host.invoke_hook_from_gen(og, "grow/on_tick", 0) {
692 Err(HostError::StaleDomain { .. }) => {}
693 other => {
694 return Err(format!("cycle {cycle}: stale-gen dispatch not rejected: {other:?}"))
695 }
696 }
697 // the name is rebound to D' with fresh plugin state
698 let fresh = host.invoke_hook("grow/on_tick", -1).map_err(|e| e.to_string())?;
699 if fresh != 1 {
700 return Err(format!("cycle {cycle}: rebound hook not fresh (chunks={fresh})"));
701 }
702 // new domain starts with empty cache and a reset arena
703 if !grow.render_cache.is_empty() || grow.scratch.allocated_bytes() != 0 {
704 return Err(format!("cycle {cycle}: new domain inherited cache/scratch"));
705 }
706 rss.push(rss_kb());
707 lua_used.push(used_pre as u64);
708 if cycle % 10 == 0 {
709 println!(
710 " cycle {cycle:3}: rss={} KB lua_used(pre-drop)={} KB cache_entries={} scratch={} KB threads={}",
711 rss.last().unwrap(),
712 used_pre / 1024,
713 cache_pre,
714 scratch_pre / 1024,
715 threads_now()
716 );
717 }
718 if cycle == 50 {
719 // §9.16 rollback: failed reload keeps the old domain fully active
720 match reload(&mut host, grow, BROKEN_SRC) {
721 Ok(_) => return Err("broken reload unexpectedly succeeded".into()),
722 Err((kept, msg)) => {
723 grow = kept;
724 let ok = host.active["grow"] == grow.generation
725 && host.hook_total() == 201
726 && host.tool_total() == 201;
727 check("rollback keeps old domain on failed reload", ok, msg)?;
728 // old domain still serves after rollback
729 host.invoke_hook("grow/on_tick", -2).map_err(|e| e.to_string())?;
730 }
731 }
732 }
733 }
734 let mean = |s: &[u64]| s.iter().sum::<u64>() as f64 / s.len() as f64;
735 let base = mean(&rss[WARMUP..40]);
736 let late = mean(&rss[80..]);
737 let growth = late - base;
738 check(
739 "RSS plateaus after warmup (no monotonic growth)",
740 growth < 3072.0,
741 format!(
742 "rss KB: initial={rss_initial} mean(c21-40)={base:.0} mean(c81-100)={late:.0} \
743 growth={growth:.0} (tolerance 3072)"
744 ),
745 )?;
746 let lbase = mean(&lua_used[WARMUP..40]);
747 let llate = mean(&lua_used[80..]);
748 check(
749 "Lua used_memory per cycle plateaus (heap reclaimed each drop)",
750 llate < lbase * 1.5 + 1_048_576.0,
751 format!(
752 "pre-drop used_memory KB: mean(c21-40)={:.0} mean(c81-100)={:.0}",
753 lbase / 1024.0,
754 llate / 1024.0
755 ),
756 )?;
757 let threads_end = threads_now();
758 check(
759 "domain task threads cancelled + joined on every drop",
760 threads_end == threads_base,
761 format!("threads: baseline={threads_base} end={threads_end} (2 domains alive each)"),
762 )?;
763 let avg_ms =
764 lat.iter().map(|d| d.as_secs_f64()).sum::<f64>() / lat.len() as f64 * 1000.0;
765 let max_ms = lat.iter().map(|d| d.as_secs_f64()).fold(0.0, f64::max) * 1000.0;
766 println!(
767 " reload latency (construct D' + swap + drop D, both plugins): avg={avg_ms:.2} ms max={max_ms:.2} ms over {CYCLES} cycles"
768 );
769 unload(&mut host, grow);
770 unload(&mut host, many);
771 check(
772 "unload empties all registries",
773 host.hook_total() == 0 && host.tool_total() == 0 && host.bus.live_total() == 0,
774 format!(
775 "hooks={} tools={} bus_subs={}",
776 host.hook_total(),
777 host.tool_total(),
778 host.bus.live_total()
779 ),
780 )?;
781 Ok(())
782}
784// ---------------------------------------------------------------------------
785// scenario: reload-with-heap-limit
786// ---------------------------------------------------------------------------
788fn scenario_heap_limit() -> Result<(), String> {
789 println!("=== scenario: reload-with-heap-limit ===");
790 // Part 1: is mlua's hard VM heap limit enforceable under LuaJIT?
791 {
792 let probe = Lua::new();
793 match probe.set_memory_limit(8 * 1024 * 1024) {
794 Ok(prev) => {
795 let r = probe
796 .load("local t = {} for i = 1, 20000 do t[i] = string.rep('x', 4096) .. i end")
797 .exec();
798 match r {
799 Err(e) => println!(
800 " set_memory_limit(8 MiB) -> Ok(prev={prev}); ~80 MiB over-allocation \
801 rejected: {}",
802 first_line(&e.to_string())
803 ),
804 Ok(()) => println!(
805 " set_memory_limit(8 MiB) -> Ok(prev={prev}) BUT ~80 MiB allocation \
806 SUCCEEDED: limit not enforced under LuaJIT"
807 ),
808 }
809 }
810 Err(e) => println!(
811 " set_memory_limit(8 MiB) -> Err: \"{}\" (hard VM heap limit NOT available \
812 under LuaJIT)",
813 first_line(&e.to_string())
814 ),
815 }
816 }
817 // Part 2: complementary enforcement per SPEC — host-side soft quota via
818 // used_memory polling, enforced by whole-domain teardown, which also
819 // reclaims the heap.
820 const SOFT_QUOTA: usize = 32 * 1024 * 1024;
821 let mut host = Host::new();
822 let grow = load_plugin(&mut host, "grow", GROW_SRC)?;
823 let rss_start = rss_kb();
824 let used_start = grow.lua.used_memory();
825 let mut calls: i64 = 0;
826 let used_breach = loop {
827 host.invoke_hook("grow/on_tick", calls).map_err(|e| e.to_string())?;
828 calls += 1;
829 let used = grow.lua.used_memory();
830 if used > SOFT_QUOTA {
831 break used;
832 }
833 if calls > 60_000 {
834 return Err("soft quota never breached after 60000 calls".into());
835 }
836 };
837 let rss_peak = rss_kb();
838 println!(
839 " soft quota breach: used_memory {used_start} -> {used_breach} B after {calls} calls; \
840 rss {rss_start} -> {rss_peak} KB"
841 );
842 println!(
843 " error: plugin 'grow' exceeded Lua heap quota ({used_breach} B > {SOFT_QUOTA} B); \
844 tearing down domain generation {}",
845 grow.generation
846 );
847 unload(&mut host, grow);
848 let rss_after = rss_kb();
849 let growth = rss_peak.saturating_sub(rss_start);
850 let reclaimed = rss_peak.saturating_sub(rss_after);
851 check(
852 "Lua heap reclaimed by whole-domain teardown (>=50% of growth)",
853 reclaimed * 2 >= growth,
854 format!(
855 "rss KB: start={rss_start} peak={rss_peak} after-teardown={rss_after} \
856 (growth={growth}, reclaimed={reclaimed})"
857 ),
858 )?;
859 check(
860 "host registries empty after quota teardown",
861 host.hook_total() == 0 && host.tool_total() == 0 && host.bus.live_total() == 0,
862 format!(
863 "hooks={} tools={} bus_subs={}",
864 host.hook_total(),
865 host.tool_total(),
866 host.bus.live_total()
867 ),
868 )?;
869 let grow2 = load_plugin(&mut host, "grow", GROW_SRC)?;
870 check(
871 "fresh domain after quota teardown starts small",
872 grow2.lua.used_memory() < 2 * 1024 * 1024,
873 format!("used_memory={} B", grow2.lua.used_memory()),
874 )?;
875 let v = host.invoke_hook("grow/on_tick", 0).map_err(|e| e.to_string())?;
876 check("reloaded plugin serves fresh state", v == 1, format!("first call returned {v}"))?;
877 unload(&mut host, grow2);
878 Ok(())
879}
881// ---------------------------------------------------------------------------
882// scenario: escaped-callback-fails
883// ---------------------------------------------------------------------------
885fn scenario_escape() -> Result<(), String> {
886 println!("=== scenario: escaped-callback-fails ===");
887 println!(
888 " note: without mlua's 'send' feature, Lua values are !Send — a std::thread cannot \
889 capture a Lua callback (compile error); escaped tasks can only carry plain data \
890 (generation tags), which the generation gate rejects below."
891 );
892 let mut host = Host::new();
893 let mut grow = load_plugin(&mut host, "grow", GROW_SRC)?;
894 let gen1 = grow.generation;
896 // Grow ~8 MiB in the old domain so heap pinning (if any) is measurable.
897 for i in 0..2000 {
898 host.invoke_hook("grow/on_tick", i).map_err(|e| e.to_string())?;
899 }
900 let rss_grown = rss_kb();
902 // ESCAPE (a): host code clones the raw callback out of the gen-keyed registry.
903 let escaped_fn: Function = host.hooks[&gen1]["grow/on_tick"].clone();
904 // ESCAPE (b): a registry entry teardown will miss (re-inserted post-swap).
905 let escaped_entry: Function = escaped_fn.clone();
906 // ESCAPE (c): a leaked subscription token — never dropped with the domain.
907 let leaked = grow.sub_tokens.pop().expect("grow has one subscription");
908 std::mem::forget(leaked);
909 // ESCAPE (d): an async task outliving the domain, firing gen-tagged callbacks.
910 let (tx, rx) = mpsc::channel::<(u64, String)>();
911 let stop = Arc::new(AtomicBool::new(false));
912 let stop_t = stop.clone();
913 let escapee: JoinHandle<u32> = thread::spawn(move || {
914 let mut sent = 0u32;
915 while !stop_t.load(Ordering::SeqCst) {
916 if tx.send((gen1, "grow/on_tick".to_string())).is_err() {
917 break;
918 }
919 sent += 1;
920 thread::sleep(Duration::from_millis(5));
921 }
922 sent
923 });
924 thread::sleep(Duration::from_millis(20)); // queue a few pre-swap requests
926 // SWAP per §9.16: construct D' -> swap -> drop D.
927 grow = reload(&mut host, grow, GROW_SRC).map_err(|(_, e)| e)?;
928 let gen2 = grow.generation;
929 check("swap complete", gen2 != gen1, format!("generation {gen1} -> {gen2}"))?;
930 // plant escape (b): stale entry back under the dead generation
931 host.hooks.entry(gen1).or_default().insert("grow/on_tick".into(), escaped_entry);
932 let rss_holding = rss_kb();
934 // (b) the audit sweep detects everything tied to a dead generation
935 let audit = host.audit_stale();
936 let audit_ok = audit.len() == 2
937 && audit.iter().any(|a| a.contains("hook 'grow/on_tick'") && a.contains(&format!("gen {gen1}")))
938 && audit.iter().any(|a| a.contains("bus subscription 'grow/topic'") && a.contains(&format!("gen {gen1}")));
939 check("escaped registry entry + leaked subscription detected by audit", audit_ok, format!("{audit:?}"))?;
941 // stale registry entry is rejected with a clear error, before touching Lua
942 match host.invoke_hook_from_gen(gen1, "grow/on_tick", 0) {
943 Err(e @ HostError::StaleDomain { .. }) => {
944 check("stale registry entry rejected with clear error", true, e.to_string())?;
945 }
946 other => return Err(format!("stale entry not rejected: {other:?}")),
947 }
948 // name-based dispatch rebinds to D' (fresh state), never the stale entry
949 let v = host.invoke_hook("grow/on_tick", 0).map_err(|e| e.to_string())?;
950 check("name-based dispatch rebound to new domain", v == 1, format!("fresh chunks={v}"))?;
952 // (c) escaped bus subscription: rejected & removed on delivery; new
953 // domain's subscriber still receives (error isolation, §9.17/§9.18)
954 let delivered = host.emit("grow/topic", 42);
955 let errs = host.bus.take_isolated_errors();
956 check(
957 "escaped bus subscription rejected & removed on delivery",
958 delivered == 1
959 && errs.len() == 1
960 && errs[0].contains(&format!("dead domain generation {gen1}")),
961 format!("delivered={delivered} errors={errs:?}"),
962 )?;
963 let delivered2 = host.emit("grow/topic", 43);
964 let errs2 = host.bus.take_isolated_errors();
965 check(
966 "after purge, next delivery is clean",
967 delivered2 == 1 && errs2.is_empty(),
968 format!("delivered={delivered2} errors={errs2:?}"),
969 )?;
971 // (d) escaped async task: every gen-tagged callback request is rejected
972 thread::sleep(Duration::from_millis(60));
973 stop.store(true, Ordering::SeqCst);
974 let sent = escapee.join().expect("join escapee");
975 let mut rejected = 0u32;
976 let mut executed = 0u32;
977 let mut sample = String::new();
978 while let Ok((g, name)) = rx.try_recv() {
979 match host.invoke_hook_from_gen(g, &name, 0) {
980 Ok(_) => executed += 1,
981 Err(e @ HostError::StaleDomain { .. }) => {
982 rejected += 1;
983 if sample.is_empty() {
984 sample = e.to_string();
985 }
986 }
987 Err(e) => return Err(format!("unexpected error from escaped task dispatch: {e}")),
988 }
989 }
990 check(
991 "escaped task's callback requests all rejected (none executed)",
992 executed == 0 && rejected >= 1,
993 format!("sent={sent} rejected={rejected} executed={executed}; sample error: {sample}"),
994 )?;
996 // (a) raw escaped mlua::Function after the domain's Lua was dropped:
997 // observe mlua's actual behavior precisely (error vs panic vs runs).
998 let prev_hook = std::panic::take_hook();
999 std::panic::set_hook(Box::new(|_| {})); // silence expected panic output
1000 let raw = catch_unwind(AssertUnwindSafe(|| escaped_fn.call::<i64>(0)));
1001 std::panic::set_hook(prev_hook);
1002 let raw_report = match &raw {
1003 Ok(Ok(v)) => format!(
1004 "CALL SUCCEEDED (returned {v}) — a raw clone keeps the dead domain's Lua alive; \
1005 host must never clone callbacks out of the gen-keyed registry"
1006 ),
1007 Ok(Err(e)) => format!("call failed with mlua error: {}", first_line(&e.to_string())),
1008 Err(p) => format!("call panicked: {}", first_line(&panic_msg(p.as_ref()))),
1009 };
1010 println!(" raw escaped mlua::Function after domain drop: {raw_report}");
1011 let raw_ran = matches!(&raw, Ok(Ok(_)));
1012 check(
1013 "raw escaped Function cannot run after domain drop",
1014 !raw_ran,
1015 format!(
1016 "raw_ran={raw_ran}; mlua behavior: {}",
1017 if matches!(&raw, Err(_)) { "PANIC (not a catchable mlua::Error)" } else { "mlua::Error" }
1018 ),
1019 )?;
1021 // cleanup + pinning measurement
1022 drop(escaped_fn);
1023 let purged = host.purge_stale();
1024 check("purge_stale removes escaped entries", purged >= 1, format!("purged={purged} entries"))?;
1025 check("audit clean after purge", host.audit_stale().is_empty(), "0 stale entries".into())?;
1026 let rss_clean = rss_kb();
1027 println!(
1028 " rss KB: grown(old domain ~8MiB live)={rss_grown} holding-escapes-after-swap={rss_holding} \
1029 after-purge={rss_clean} (pinned-by-escapes={})",
1030 rss_holding.saturating_sub(rss_clean)
1031 );
1032 unload(&mut host, grow);
1033 Ok(())
1036// ---------------------------------------------------------------------------
1038fn main() {
1039 let cmd = std::env::args().nth(1).unwrap_or_else(|| "all".into());
1040 let started = Instant::now();
1041 let result = match cmd.as_str() {
1042 "reload-loop" => scenario_reload_loop(),
1043 "reload-with-heap-limit" => scenario_heap_limit(),
1044 "escaped-callback-fails" => scenario_escape(),
1045 "all" => scenario_reload_loop()
1046 .and_then(|_| scenario_heap_limit())
1047 .and_then(|_| scenario_escape()),
1048 other => Err(format!(
1049 "unknown scenario '{other}'; use reload-loop | reload-with-heap-limit | \
1050 escaped-callback-fails | all"
1051 )),
1052 };
1053 match result {
1054 Ok(()) => println!(
1055 "\np11 RESULT: all expectations hold ({:.1}s)",
1056 started.elapsed().as_secs_f64()
1057 ),
1058 Err(e) => {
1059 eprintln!("\np11 RESULT: FAIL: {e}");
1060 std::process::exit(1);
1061 }
1062 }