repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

prototypes/PLAN.md

Raw

Prototype Plan

Purpose: prove or invalidate high-risk ../docs/SPEC.md claims before production Rust exists.

Rules from CLAUDE.md apply:

Execution Order

  1. p02-lua-interface-descriptor
  2. p03-subagent-ecosystem-simulation
  3. p04-plugin-install-uninstall
  4. p05-provider-fetch-normalize
  5. p06-session-codec-recovery
  6. p07-streamfn-agent-loop
  7. p08-tui-testbackend
  8. p09-memory-arena-allocation
  9. p10-lua-plugin-heap-limit
  10. p11-plugin-memory-domain-reload

Run in order unless a later prototype is needed to answer an active SPEC dispute.

P02 — p02-lua-interface-descriptor

SPEC claims

Risk

Plain Lua may be too weak or too verbose for reliable interface conformance.

Minimal artifact

Lua-only or small Rust+mlua proof:

p02-lua-interface-descriptor/
  Cargo.toml
  interfaces/subagent.lua
  impl/good.lua
  impl/missing_fn.lua
  impl/bad_shape.lua
  src/main.rs

Descriptor defines required exports/events. Validator loads descriptor and implementations, then reports conformance errors.

Verify

cd prototypes/p02-lua-interface-descriptor
cargo run

Pass evidence

SPEC impact

If viable, SPEC can make Lua interface descriptors the mandatory plugin shape. If not, run P02b for Teal/typed Lua.

P03 — p03-subagent-ecosystem-simulation

SPEC claims

Risk

The idea may work in prose but fail under realistic plugin composition.

Minimal artifact

p03-subagent-ecosystem-simulation/
  Cargo.toml
  plugins/community-subagent-interface/
  plugins/alice-subagents/
  plugins/bob-agents/
  plugins/bob-to-subagent-adapter/
  plugins/fancy-subagent-ui/
  src/main.rs

Simulate plugin manager resolving community/subagent to selected impl.

Verify

cd prototypes/p03-subagent-ecosystem-simulation
cargo run -- alice
cargo run -- bob-adapted
cargo run -- bob-direct-fails

Pass evidence

SPEC impact

Clarify interface selection, adapter role, conformance test requirements, and user override syntax.

P04 — p04-plugin-install-uninstall

SPEC claims

Risk

Install semantics may require too much code execution, ambiguous path layout, or awkward namespace/data mapping.

Minimal artifact

p04-plugin-install-uninstall/
  Cargo.toml
  fixtures/good-plugin/smith-plugin.lua
  fixtures/bad-name/smith-plugin.lua
  fixtures/reserved-smith/smith-plugin.lua
  src/main.rs

Use temp dirs for fake data_dir and project dir. Git URL can be simulated with a local bare repo first; note whether gix is used or shelling out is required.

Verify

cd prototypes/p04-plugin-install-uninstall
cargo run -- install-local
cargo run -- install-git
cargo run -- reject-bad-name
cargo run -- reject-smith-namespace
cargo run -- uninstall-keeps-data
cargo run -- uninstall-purge-data

Pass evidence

Each command exits 0 and prints checked filesystem assertions.

SPEC impact

Clarify manifest filename, install layout, duplicate handling, --force, git implementation boundary, and data purge rules.

P05 — p05-provider-fetch-normalize

SPEC claims

Risk

Merge rules may be under-specified; generated data may silently corrupt provider metadata.

Minimal artifact

p05-provider-fetch-normalize/
  Cargo.toml
  fixtures/pi.json
  fixtures/catwalk.json
  fixtures/current-providers.json
  src/main.rs

No network. Use fake source shapes with overlapping models, missing costs, unknown fields, and conflicting metadata.

Verify

cd prototypes/p05-provider-fetch-normalize
cargo run -- generate
cargo run -- diff
cargo run -- conflict-fails

Pass evidence

SPEC impact

Clarify provider schema, conflict policy, and PR-agent workflow inputs/outputs.

P06 — p06-session-codec-recovery

SPEC claims

Risk

CBOR recovery behavior may be less precise than SPEC promises.

Minimal artifact

p06-session-codec-recovery/
  Cargo.toml
  src/main.rs

Encode sample entries, truncate bytes, inject corrupt frame, and include unknown variant representation if possible.

Verify

cd prototypes/p06-session-codec-recovery
cargo run

Pass evidence

Program asserts counts and diagnostics for normal/truncated/corrupt/unknown cases.

SPEC impact

Tighten exact recovery guarantees if corruption cannot be safely skipped.

P07 — p07-streamfn-agent-loop

SPEC claims

Risk

The proposed event/hook shape may be too complex or insufficiently typed.

Minimal artifact

p07-streamfn-agent-loop/
  Cargo.toml
  src/main.rs

Mock StreamFn emits deterministic text/tool/done events. Mock tool returns a result. Hook variants exercise allow/block/replace.

Verify

cd prototypes/p07-streamfn-agent-loop
cargo run -- basic
cargo run -- tool
cargo run -- hook-block
cargo run -- hook-replace

Pass evidence

Each scenario prints/compares expected event sequence.

SPEC impact

Clarify event ordering, hook return semantics, and session-entry conversion.

P08 — p08-tui-testbackend

SPEC claims

Risk

Snapshot output may be unstable or theming may require more structure.

Minimal artifact

p08-tui-testbackend/
  Cargo.toml
  src/main.rs

Render one status bar and one message/tool-result widget using a theme table. Print stable buffer text for assertion.

Verify

cd prototypes/p08-tui-testbackend
cargo run

Pass evidence

Output equals checked expected snapshot string.

SPEC impact

Clarify theme schema, widget test strategy, and snapshot normalization.

P09 — p09-memory-arena-allocation

SPEC claims

No current SPEC claim requires arenas. This prototype tests whether memory pressure justifies a future SPEC policy.

Candidate claims:

Empirical sizing target

Use ../docs/research/SMITH-MEMORY-ALLOCATION-PROFILE.md as the workload baseline. Pi sessions treated as Smith-shaped sessions showed:

Risk

Arena allocation may optimize the wrong layer. Persisted text dominates memory, while arenas mainly help repeated short-lived scratch allocation. Allocation count reduction alone is insufficient; the real win may be fewer global allocator calls, less allocator/syscall pressure, and more stable peak/RSS behavior. Arena use may still add lifetime complexity, skipped destructors, async/thread friction, and unnecessary dependency surface.

Minimal artifact

p09-memory-arena-allocation/
  Cargo.toml
  fixtures/session-small.jsonl
  fixtures/session-p95.jsonl
  fixtures/session-p99.jsonl
  fixtures/session-pathological.jsonl
  src/main.rs

Fixtures are synthetic and content-free but match measured shapes:

Implement five workloads:

  1. discover: scan 535 session headers/metadata without full load,
  2. load-replay: decode full sessions into Smith-like SessionEntry values,
  3. render-window: render visible rows from small/p95/p99/pathological sessions,
  4. request-build: assemble provider request near 250k token context,
  5. arena-scratch: compare baseline Vec/String vs bumpalo for render and request scratch only.

Use a counting global allocator. Measure allocations, allocated bytes, allocator calls, peak live bytes where feasible, post-warmup live-memory plateau, elapsed time, and Linux RSS via /proc/self/statm when available. Treat allocator calls as syscall-pressure proxy; optional local strace/malloc tracing may be noted but must not be required. Do not prototype arena-allocator; prior research flags it too sharp for Smith.

Verify

cd prototypes/p09-memory-arena-allocation
cargo run -- discover
cargo run -- load-replay
cargo run -- render-window
cargo run -- request-build
cargo run -- arena-scratch
cargo run -- all

Pass evidence

SPEC impact

If baseline is sufficient, record “no arena allocation in v1” and keep normal ownership.

If arenas win on allocator calls, elapsed time, or memory stability, add a SPEC policy:

If session discovery/load/render exceeds targets, SPEC must clarify lazy loading, virtual-scroll cache boundaries, max retained render state, and provider-request peak-memory behavior.

P10 — p10-lua-plugin-heap-limit

SPEC claims

Smith's Lua plugin sandbox can enforce per-plugin heap limits.

Candidate claims:

Risk

Lua heap accounting may not include all host-side allocations, may behave differently under LuaJIT, or may make plugin isolation require one Lua state per quota domain. Shared Lua state + per-plugin quota may be impossible.

Minimal artifact

p10-lua-plugin-heap-limit/
  Cargo.toml
  plugins/small.lua
  plugins/oom_table.lua
  plugins/oom_string.lua
  plugins/host_value.lua
  src/main.rs

Use Smith's planned mlua = { features = ["luajit", "vendored", "serialize"] } shape.

Implement four scenarios:

  1. small: plugin stays below limit,
  2. oom-table: table growth hits limit,
  3. oom-string: string/buffer growth hits limit,
  4. isolation: one plugin OOMs, another plugin still runs.

Test one-state-per-plugin first. If shared-state quotas are attempted, report whether they are enforceable or impossible.

Verify

cd prototypes/p10-lua-plugin-heap-limit
cargo run -- small
cargo run -- oom-table
cargo run -- oom-string
cargo run -- isolation
cargo run -- all

Pass evidence

SPEC impact

If viable, SPEC should add plugin heap quota fields and define quota domain: per-plugin Lua state or shared runtime.

If not viable, SPEC should avoid promising plugin heap limits and instead define coarser process/session limits.

P11 — p11-plugin-memory-domain-reload

SPEC claims

Smith can make plugin reload/unload memory management simple by assigning each plugin instance a memory domain and dropping the whole domain on reload.

Candidate claims:

Risk

Some plugin resources may escape the domain through async tasks, event bus subscriptions, registry keys, UI caches, or shared host registries. If escape is possible, reload can leak memory or leave stale callbacks even with an arena.

Minimal artifact

p11-plugin-memory-domain-reload/
  Cargo.toml
  plugins/grow.lua
  plugins/register_many.lua
  src/main.rs

Model a PluginDomain that owns:

Run repeated load/use/reload cycles. Include one intentionally escaped resource scenario that must fail validation.

Verify

cd prototypes/p11-plugin-memory-domain-reload
cargo run -- reload-loop
cargo run -- reload-with-heap-limit
cargo run -- escaped-callback-fails
cargo run -- all

Pass evidence

SPEC impact

If viable, SPEC should define PluginDomain/reload ownership:

If not viable, SPEC must define explicit cleanup registries and leak/stale-callback failure modes for plugin reload.

Results

All prototypes implemented and run 2026-07-14, rustc 1.94.1, x86_64-unknown-linux-gnu, mlua 0.10.5 vendored LuaJIT. Commands per prototype section; each exits 0. Result blocks follow the reporting template, trimmed to decision-relevant content; full diagnostics are in each prototype's output and the corresponding commit message.

P02 result

{
  "status": "complete",
  "proved": [
    "plain Lua descriptor + runtime validation supports community interfaces",
    "missing function fails with exact path (impl/missing_fn.lua.cancel)",
    "bad shape fails with expected/actual (status: expected function, got string)",
    "extra impl fields hidden through interface view",
    "runtime arg validation rejects bad types naming fn/param"
  ],
  "disproved": [],
  "specIssues": [
    { "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" }
  ],
  "commands": ["cd prototypes/p02-lua-interface-descriptor && cargo run"],
  "nextSteps": ["make §9.6 candidate 1 canonical; P02b (Teal) not needed"]
}

P03 result

{
  "status": "complete",
  "proved": [
    "5-plugin ecosystem composes through one interface package; consumer source has no impl name",
    "user config swaps alice <-> bob-adapted with zero consumer changes",
    "pure-Lua adapter normalizes incompatible impl; passes same conformance check",
    "direct incompatible binding fails naming plugin, interface+generation, exact missing fns, actual exports, adapter hint"
  ],
  "disproved": [],
  "specIssues": [
    { "file": "../docs/SPEC.md", "issue": "§9.6 lacks adapter registration semantics (invented `adapts` + make-factory)", "evidence": "p03 bob-adapted scenario", "severity": "P1" },
    { "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" },
    { "file": "../docs/SPEC.md", "issue": "§9.2 `interfaces`/`implements` manifest field shapes undefined", "evidence": "p03 manifests", "severity": "P2" },
    { "file": "../docs/SPEC.md", "issue": "conformance-check timing (load vs bind) and undeclared-implements policy unstated", "evidence": "p03 bob-direct-fails", "severity": "P2" },
    { "file": "../docs/SPEC.md", "issue": "singleton vs per-consumer instance semantics open", "evidence": "alice module state vs adapter factory", "severity": "P3" }
  ],
  "commands": ["cargo run -- alice", "cargo run -- bob-adapted", "cargo run -- bob-direct-fails"],
  "nextSteps": ["amend §9.2/§9.6/§9.7 with manifest fields, adapter convention, binding config + precedence"]
}

P04 result

{
  "status": "complete",
  "proved": [
    "local-path + git-URL install into data_dir/smith/plugins/<org>/<name>/ (git via local bare repo, shell-out)",
    "name charset + smith/* reservation enforced before any write",
    "restricted empty-env manifest eval: os/require blocked, function values rejected as non-data",
    "smith_api defaults 1; smith_api=2 refused with required/supported generations",
    "install never executes entry code (armed side effect did not fire)",
    "duplicate refused without --force; --force = remove-then-copy, data kept",
    "uninstall keeps data / --purge-data removes it / project plugins never touched"
  ],
  "disproved": [],
  "specIssues": [
    { "file": "../docs/SPEC.md", "issue": "§9.2 never states the manifest FILENAME (prototype: smith-plugin.lua)", "evidence": "p04 all commands", "severity": "P1" },
    { "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" },
    { "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" }
  ],
  "commands": ["cargo run -- install-local|install-git|reject-bad-name|reject-smith-namespace|uninstall-keeps-data|uninstall-purge-data"],
  "nextSteps": ["canonicalize manifest filename; define --force/duplicate/git-layout; decide git boundary"]
}

P05 result

{
  "status": "complete",
  "proved": [
    "pi-primary field-level recursive merge; catwalk fills gaps at field/model/provider granularity",
    "generate writes nothing; suggestion + reviewable source-attributed patch on stdout",
    "two unresolvable conflict classes detected, excluded, reported: ambiguous-primary-source, type-mismatch-vs-curated-registry"
  ],
  "disproved": [
    "byte-for-byte unknown-field preservation with default serde_json (keys re-sort); preservation is semantic (Value-equal) only"
  ],
  "specIssues": [
    { "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" },
    { "file": "../docs/SPEC.md", "issue": "§7.3 has no conflict taxonomy/policy at all", "evidence": "p05 conflict-fails", "severity": "P1" },
    { "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" }
  ],
  "commands": ["cargo run -- generate", "cargo run -- diff", "cargo run -- conflict-fails"],
  "nextSteps": ["amend §7.3: merge granularity, conflict classes, semantic preservation, CLI contract"]
}

P06 result

{
  "status": "complete",
  "proved": [
    "truncated tail (mid-body, mid-prefix) stops parsing; prior entries survive",
    "corrupt entry BODY skips precisely with warning while framing intact",
    "unknown future variants distinguishable from corruption via two-stage decode (ciborium::Value then typed); preserved raw through v1 rewrite -> v2 read"
  ],
  "disproved": [],
  "specIssues": [
    { "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" }
  ],
  "commands": ["cd prototypes/p06-session-codec-recovery && cargo run"],
  "nextSteps": ["state the framing boundary in §6.6"]
}

P07 result

{
  "status": "complete",
  "proved": [
    "agent loop drives text/tool/done through StreamFn only; deterministic AgentEvent sequences",
    "tool results fed back to provider next turn",
    "BeforeToolCall allow/block/replace-args verified; blocked call never executes tool"
  ],
  "disproved": [],
  "specIssues": [
    { "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" }
  ],
  "commands": ["cargo run -- basic|tool|hook-block|hook-replace"],
  "nextSteps": ["state blocked-call event contract in §6.4"]
}

P08 result

{
  "status": "complete",
  "proved": [
    "TestBackend renders deterministic cell-by-cell (symbol + fg/bg/modifier); snapshot matches checked-in string; fully headless",
    "Lua theme tables validated by Rust schema drive widget styles; invalid theme rejected with exact path",
    "theme swap changes styles, leaves text byte-identical"
  ],
  "disproved": [],
  "specIssues": [
    { "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" },
    { "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" },
    { "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" }
  ],
  "commands": ["cd prototypes/p08-tui-testbackend && cargo run"],
  "nextSteps": ["define §8.8 theme schema + §17 style-aware snapshot contract"]
}

P09 result

{
  "status": "complete",
  "proved": [
    "discovery O(session count): 535 sessions from 54.8KiB of 41.64MiB corpus (0.13%), 3.1ms",
    "load/replay within research bands up to 29.78MiB pathological session; 4.6MiB message intact",
    "virtual scroll O(visible rows): 41 allocs/frame constant across 143x entry spread; giant message capped by lazy viewport wrap",
    "request-build ~250k tokens: transient peak 2.43MiB, zero live growth over 50 builds",
    "bumpalo scratch: render -100% allocator calls, x0.19 elapsed (KEEP); request -99% calls, x1.00 elapsed, +22% peak (marginal KEEP)"
  ],
  "disproved": [
    "arenas as a latency win for request-build: serde_json serialization dominates; win is allocator-call pressure only"
  ],
  "specIssues": [
    { "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" },
    { "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" },
    { "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" }
  ],
  "commands": ["cargo run --release -- discover|load-replay|render-window|request-build|arena-scratch|all"],
  "nextSteps": ["add memory policy to SPEC; re-run keep/drop on real render code before production commitment"],
  "deviation": "PLAN fixtures/*.jsonl not committed; synthetic sessions generated at runtime (deterministic seed) matching PLAN shapes within 2.5%"
}

P10 result

{
  "status": "complete",
  "proved": [
    "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",
    "oom-table/oom-string rejected at exactly the 16MiB quota (overshoot 0) with recoverable MemoryError; state reusable after gc_collect; host survives",
    "isolation: plugin B in its own state unaffected by A's OOM",
    "host-created Lua strings charged to the quota (8MiB string -> delta 8388672)",
    "quota domain: per-plugin heap quota = one Lua state per plugin"
  ],
  "disproved": [
    "shared-state per-plugin quotas: only a whole-state limit exists, no attribution (B charged at A's retained 15.3MiB)",
    "Lua quota covering host-side Rust allocations: 8MiB userdata payload registered 632 bytes",
    "hook-based fallback under active JIT: count hooks never fire JIT-on (0 fires / 3e6 iterations); interpreter-only, ~3.4x slowdown"
  ],
  "specIssues": [
    { "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" },
    { "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" },
    { "file": "../docs/SPEC.md", "issue": "any future instruction watchdog cannot use LuaJIT count hooks (never fire under JIT)", "evidence": "p10 hook bench", "severity": "P3" }
  ],
  "commands": ["cargo run -- small|oom-table|oom-string|isolation|all"],
  "nextSteps": ["add heap-quota to SPEC §9 with per-plugin-state domain; CI-verify enforcement per release target (non-GC64 -> MemoryControlNotAvailable)"]
}

P11 result

{
  "status": "complete",
  "proved": [
    "§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",
    "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",
    "rollback: broken entry keeps old domain serving; partial D' registrations discarded",
    "31MB Lua heap 100% reclaimed by domain drop; fresh domain restarts at 45KB",
    "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"
  ],
  "disproved": [],
  "specIssues": [
    { "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" },
    { "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" }
  ],
  "commands": ["cargo run -- reload-loop|reload-with-heap-limit|escaped-callback-fails|all"],
  "nextSteps": ["fold registry/generation-gate discipline into §9.16; re-verify !Send containment if mlua 'send' feature is ever enabled"]
}

Campaign 2 — new contracts from the readiness passes

The 2026-07-15/16 readiness passes added contracts to ../docs/SPEC.md (§5.1/§5.8, §6.1, §6.5, §6.7, §6.9) that lack prototype evidence. P12–P14 validate their risky cores.

P12 — p12-session-tree-fold

SPEC claims

Risk

Path folding may be ill-defined at edges: a summary entry whose covered span crosses a fork point, nested summaries (summary covering a summary), or a leaf-switch entry inside a covered span.

Minimal artifact

p12-session-tree-fold/
  Cargo.toml        (serde, ciborium — §6.6 length-prefixed format)
  src/main.rs

Verify

cd prototypes/p12-session-tree-fold
cargo run -- tree
cargo run -- leaf-persist
cargo run -- fold
cargo run -- branch-past-compaction
cargo run -- all

Pass evidence

SPEC impact

Tighten §6.9 with whatever edge rules the fold needs (e.g. spans may not cross fork points; summaries may nest or may not).

P13 — p13-secret-proxy-mechanics

SPEC claims

Risk

The hook-then-scan ordering may be racy or ambiguous when a hook both transforms content and registers a secret found in the pre-transform text. Exact-substring masking may corrupt content when one secret is a substring of another or of a placeholder.

Minimal artifact

p13-secret-proxy-mechanics/
  Cargo.toml        (mlua luajit vendored, serde, ciborium)
  plugins/detector.lua   (input/tool_result hook registering found values)
  src/main.rs

Verify

cd prototypes/p13-secret-proxy-mechanics
cargo run -- ingest
cargo run -- hook-order
cargo run -- rehydrate
cargo run -- resume
cargo run -- all

Pass evidence

SPEC impact

Define masking order for overlapping secrets (e.g. longest-match-first) and any hook/transform ordering rule §6.7 needs beyond "scan after hooks".

P14 — p14-steering-queue

SPEC claims

Risk

Boundary delivery may interleave badly with parallel tool execution (§5.3 ToolExecutionMode) — "currently executing tool finishes" is ambiguous when three run concurrently. Synthetic results for skipped calls may need exact ordering relative to real results.

Minimal artifact

p14-steering-queue/
  Cargo.toml        (serde_json only; extends the p07 loop pattern)
  src/main.rs

Verify

cd prototypes/p14-steering-queue
cargo run -- steer-mid-stream
cargo run -- steer-mid-tools
cargo run -- steer-parallel-tools
cargo run -- followup
cargo run -- abort-keeps-queue
cargo run -- all

Pass evidence

SPEC impact

Pin the parallel-execution boundary rule in §6.1 and the ordering of synthetic skipped results relative to completed results.

Campaign 2 Results

Run 2026-07-16, rustc 1.94.1, x86_64-unknown-linux-gnu. All three complete; findings folded into SPEC (§6.1, §6.5, §6.7, §6.9).

P12 result

{
  "status": "complete",
  "proved": [
    "tree ops per §6.5 incl. implicit fork points; leaf-switch persistence under §6.6 recovery",
    "fold: span collapse at path position, trim stubs, byte-identical storage through every fold/switch/compaction",
    "branch-past-compaction: pre-compaction switch sees full history, re-compacts as SIBLING summary; post-compaction branches inherit the mask",
    "edges: cross-fork spans detectable + safely ignored; nested summaries inevitable, outermost-wins; leaf-switch inside covered span folds away (leaf replay reads raw storage)"
  ],
  "disproved": [
    "§6.5 literal leaf-load rule ('last switch target, else last append') — stale leaf whenever appends follow a switch; correct rule is replay-in-file-order (last surviving entry decides)"
  ],
  "specIssues": [
    { "file": "../docs/SPEC.md", "issue": "leaf-load rule false as written", "evidence": "leaf-persist: literal=Some(2) vs replay=Some(6)", "severity": "P1" },
    { "file": "../docs/SPEC.md", "issue": "§6.9 'registrations survive verbatim' x §6.7 'provider carries placeholders only' contradiction — structural survival + masked provider rendering required", "evidence": "fold: hoist-secret#2 with plaintext intact", "severity": "P1" },
    { "file": "../docs/SPEC.md", "issue": "span well-formedness, nested-summary outermost-wins, trim-ladder scoping of 'survives verbatim', orphan/dangling recovery rules, metadata foldability all needed", "evidence": "fold + branch-past-compaction + leaf-persist diagnostics", "severity": "P2" }
  ],
  "commands": ["cargo run -- tree|leaf-persist|fold|branch-past-compaction|all"],
  "nextSteps": ["all folded into §6.5/§6.9 (2026-07-16)"]
}

P13 result

{
  "status": "complete",
  "proved": [
    "plaintext bytes exist exactly once in the file (registration entry) — byte-scan verified",
    "hook-then-scan ordering: Lua detector registering during a hook masks the surfacing content",
    "rehydration is a view at tool execution only (Rust + Lua); provider view masked; unknown ids pass through",
    "resume rebuilds table with original ids; allocator resumes past max id",
    "longest-match-first single-pass masking correct; naive order provably leaks overlap residue"
  ],
  "disproved": [],
  "specIssues": [
    { "file": "../docs/SPEC.md", "issue": "masking order must be longest-match-first single-pass never rescanning placeholders", "evidence": "ingest overlap scenario residue leak", "severity": "P1" },
    { "file": "../docs/SPEC.md", "issue": "placeholder-grammar registered values alias placeholders; single-pass rehydration load-bearing; reject such registrations", "evidence": "ingest placeholder-shaped scenario", "severity": "P2" },
    { "file": "../docs/SPEC.md", "issue": "scan is post-transform only (re-encoding hook launders secrets) — stated limit; allocator resume, idempotent re-registration, maximal-digit-run parsing", "evidence": "hook-order + resume + rehydrate scenarios", "severity": "P2" }
  ],
  "commands": ["cargo run -- ingest|hook-order|rehydrate|resume|all"],
  "nextSteps": ["all folded into §6.7 (2026-07-16)"]
}

P14 result

{
  "status": "complete",
  "proved": [
    "boundary delivery (stream end / in-flight completion), synthetic skipped results for every unexecuted call, FIFO steer drain, follow-up-instead-of-agent_end, delivery-time-only entry recording, abort keeps queues intact",
    "parallel mode: wait-for-all-in-flight workable — no new call starts after a steer queues, started calls complete, never-started skip",
    "transcript rule: reals first (completion order), synthetics in original call order, steers follow"
  ],
  "disproved": [],
  "specIssues": [
    { "file": "../docs/SPEC.md", "issue": "'currently executing tool finishes' ill-defined with N in flight — pin wait-for-all-in-flight", "evidence": "steer-parallel-tools", "severity": "P1" },
    { "file": "../docs/SPEC.md", "issue": "synthetics-after-reals ordering must be stated (reals may be completion-ordered)", "evidence": "steer-mid-tools + steer-parallel-tools transcripts", "severity": "P1" },
    { "file": "../docs/SPEC.md", "issue": "mid-stream steer skips ALL calls; skipped calls emit §6.4-style events; abort leaves dangling tool-call tail — resume must repair", "evidence": "steer-mid-stream + abort-keeps-queue", "severity": "P2" }
  ],
  "commands": ["cargo run -- steer-mid-stream|steer-mid-tools|steer-parallel-tools|followup|abort-keeps-queue|all"],
  "nextSteps": ["all folded into §6.1 (2026-07-16); re-verify wait-for-all under real tokio timing when the loop lands"]
}

Reporting Template

Each completed prototype updates this plan with a result block in the Markdown shape required by prototypes/CLAUDE.md (canonical: .claude/skills/pioneer/SKILL.md). Result blocks recorded before 2026-07-16 use the earlier JSON shape and stand as historical records.

Markdown source
File outline
# Prototype Plan

Purpose: prove or invalidate high-risk `../docs/SPEC.md` claims before production
Rust exists.

Rules from `CLAUDE.md` apply:

- one prototype = one claim/risk,
- minimal runnable proof,
- every prototype has a verifying command,
- evidence drives SPEC changes,
- prototypes are disposable.

## Execution Order

1. `p02-lua-interface-descriptor`
2. `p03-subagent-ecosystem-simulation`
3. `p04-plugin-install-uninstall`
4. `p05-provider-fetch-normalize`
5. `p06-session-codec-recovery`
6. `p07-streamfn-agent-loop`
7. `p08-tui-testbackend`
8. `p09-memory-arena-allocation`
9. `p10-lua-plugin-heap-limit`
10. `p11-plugin-memory-domain-reload`

Run in order unless a later prototype is needed to answer an active SPEC dispute.

## P02 — `p02-lua-interface-descriptor`

### SPEC claims

- Smith can support community-defined plugin interfaces without core authors
  predicting all future features.
- Plain Lua descriptors plus runtime validation might approximate signature
  matching.

### Risk

Plain Lua may be too weak or too verbose for reliable interface conformance.

### Minimal artifact

Lua-only or small Rust+mlua proof:

```text
p02-lua-interface-descriptor/
  Cargo.toml
  interfaces/subagent.lua
  impl/good.lua
  impl/missing_fn.lua
  impl/bad_shape.lua
  src/main.rs
```

Descriptor defines required exports/events. Validator loads descriptor and
implementations, then reports conformance errors.

### Verify

```bash
cd prototypes/p02-lua-interface-descriptor
cargo run
```

### Pass evidence

- good implementation passes,
- missing function fails with exact path/name,
- bad shape fails with expected/actual diagnostic,
- extra implementation fields are hidden/ignored when viewed through interface.

### SPEC impact

If viable, SPEC can make Lua interface descriptors the mandatory plugin shape.
If not, run P02b for Teal/typed Lua.

## P03 — `p03-subagent-ecosystem-simulation`

### SPEC claims

- Interface packages can prevent plugin ecosystem fragmentation.
- Consumers can target an interface while users choose implementation.
- Adapters can normalize incompatible implementations.

### Risk

The idea may work in prose but fail under realistic plugin composition.

### Minimal artifact

```text
p03-subagent-ecosystem-simulation/
  Cargo.toml
  plugins/community-subagent-interface/
  plugins/alice-subagents/
  plugins/bob-agents/
  plugins/bob-to-subagent-adapter/
  plugins/fancy-subagent-ui/
  src/main.rs
```

Simulate plugin manager resolving `community/subagent` to selected impl.

### Verify

```bash
cd prototypes/p03-subagent-ecosystem-simulation
cargo run -- alice
cargo run -- bob-adapted
cargo run -- bob-direct-fails
```

### Pass evidence

- UI plugin works with Alice implementation,
- UI plugin works with Bob only through adapter,
- direct incompatible Bob usage fails with clear interface error,
- user config swaps implementation without UI plugin change.

### SPEC impact

Clarify interface selection, adapter role, conformance test requirements, and
user override syntax.

## P04 — `p04-plugin-install-uninstall`

### SPEC claims

- v1 plugin install supports local path and git URL only.
- Plugin names are `<org>/<name>`.
- `smith/*` namespace is reserved.
- Manifests are mandatory Lua data files.
- `smith_api` is optional and defaults to generation `1`.
- Uninstall keeps data unless `--purge-data`.

### Risk

Install semantics may require too much code execution, ambiguous path layout, or
awkward namespace/data mapping.

### Minimal artifact

```text
p04-plugin-install-uninstall/
  Cargo.toml
  fixtures/good-plugin/smith-plugin.lua
  fixtures/bad-name/smith-plugin.lua
  fixtures/reserved-smith/smith-plugin.lua
  src/main.rs
```

Use temp dirs for fake `data_dir` and project dir. Git URL can be simulated with
a local bare repo first; note whether gix is used or shelling out is required.

### Verify

```bash
cd prototypes/p04-plugin-install-uninstall
cargo run -- install-local
cargo run -- install-git
cargo run -- reject-bad-name
cargo run -- reject-smith-namespace
cargo run -- uninstall-keeps-data
cargo run -- uninstall-purge-data
```

### Pass evidence

Each command exits 0 and prints checked filesystem assertions.

### SPEC impact

Clarify manifest filename, install layout, duplicate handling, `--force`, git
implementation boundary, and data purge rules.

## P05 — `p05-provider-fetch-normalize`

### SPEC claims

- `providers.json` is runtime authority.
- `fetch-providers` is only bootstrap/maintenance suggestion generator.
- pi.dev is primary, catwalk fills gaps.
- Unknown fields are preserved.
- Correctness requires review.

### Risk

Merge rules may be under-specified; generated data may silently corrupt provider
metadata.

### Minimal artifact

```text
p05-provider-fetch-normalize/
  Cargo.toml
  fixtures/pi.json
  fixtures/catwalk.json
  fixtures/current-providers.json
  src/main.rs
```

No network. Use fake source shapes with overlapping models, missing costs,
unknown fields, and conflicting metadata.

### Verify

```bash
cd prototypes/p05-provider-fetch-normalize
cargo run -- generate
cargo run -- diff
cargo run -- conflict-fails
```

### Pass evidence

- pi.dev wins conflicts,
- catwalk fills missing fields,
- unknown fields preserved,
- conflict report is explicit,
- generated patch is reviewable.

### SPEC impact

Clarify provider schema, conflict policy, and PR-agent workflow inputs/outputs.

## P06 — `p06-session-codec-recovery`

### SPEC claims

- Length-prefixed CBOR sequence supports crash recovery.
- Truncated tail stops parsing.
- Corrupt entries are skipped or reported without losing prior entries.
- Unknown future entries can be preserved where possible.

### Risk

CBOR recovery behavior may be less precise than SPEC promises.

### Minimal artifact

```text
p06-session-codec-recovery/
  Cargo.toml
  src/main.rs
```

Encode sample entries, truncate bytes, inject corrupt frame, and include unknown
variant representation if possible.

### Verify

```bash
cd prototypes/p06-session-codec-recovery
cargo run
```

### Pass evidence

Program asserts counts and diagnostics for normal/truncated/corrupt/unknown
cases.

### SPEC impact

Tighten exact recovery guarantees if corruption cannot be safely skipped.

## P07 — `p07-streamfn-agent-loop`

### SPEC claims

- `smith-core` can drive agent behavior through `StreamFn` without depending on
  `smith-ai`.
- Text, tool call, tool result, and done events can produce deterministic
  `AgentEvent` sequence.
- Tool execution hooks can block/replace/retry.

### Risk

The proposed event/hook shape may be too complex or insufficiently typed.

### Minimal artifact

```text
p07-streamfn-agent-loop/
  Cargo.toml
  src/main.rs
```

Mock StreamFn emits deterministic text/tool/done events. Mock tool returns a
result. Hook variants exercise allow/block/replace.

### Verify

```bash
cd prototypes/p07-streamfn-agent-loop
cargo run -- basic
cargo run -- tool
cargo run -- hook-block
cargo run -- hook-replace
```

### Pass evidence

Each scenario prints/compares expected event sequence.

### SPEC impact

Clarify event ordering, hook return semantics, and session-entry conversion.

## P08 — `p08-tui-testbackend`

### SPEC claims

- ratatui `TestBackend` supports deterministic widget snapshots.
- Theme tables can drive Rust widget rendering.
- TUI primitives can be tested without terminal I/O.

### Risk

Snapshot output may be unstable or theming may require more structure.

### Minimal artifact

```text
p08-tui-testbackend/
  Cargo.toml
  src/main.rs
```

Render one status bar and one message/tool-result widget using a theme table.
Print stable buffer text for assertion.

### Verify

```bash
cd prototypes/p08-tui-testbackend
cargo run
```

### Pass evidence

Output equals checked expected snapshot string.

### SPEC impact

Clarify theme schema, widget test strategy, and snapshot normalization.

## P09 — `p09-memory-arena-allocation`

### SPEC claims

No current SPEC claim requires arenas. This prototype tests whether memory
pressure justifies a future SPEC policy.

Candidate claims:

- Smith can load/replay large sessions without arena allocation.
- Smith can discover many sessions without fully loading them.
- Virtual scroll bounds per-frame allocations by visible rows, not total entries.
- Phase-local scratch allocation may reduce render/request allocation pressure.
- Phase-local scratch allocation may reduce allocator-call/syscall pressure.
- Phase-local scratch allocation may produce a flatter post-warmup memory profile.
- `bumpalo` can support scratch buffers without unsafe project code if measured
  wins justify it.
- Persisted/session data must use stable IDs, not `&'arena` references.

### Empirical sizing target

Use `../docs/research/SMITH-MEMORY-ALLOCATION-PROFILE.md` as the workload
baseline. Pi sessions treated as Smith-shaped sessions showed:

- 535 sessions, 395 MiB JSONL total,
- p50 session 88 KiB / 36 entries,
- p95 session 3.1 MiB / 822 entries,
- p99 session 9.2 MiB / 1,930 entries,
- max session 29.2 MiB / 5,157 entries,
- max single message line 4.6 MiB,
- compaction around 247k–282k tokens,
- dominant bytes: tool results + assistant/thinking text.

### Risk

Arena allocation may optimize the wrong layer. Persisted text dominates memory,
while arenas mainly help repeated short-lived scratch allocation. Allocation
count reduction alone is insufficient; the real win may be fewer global allocator
calls, less allocator/syscall pressure, and more stable peak/RSS behavior. Arena
use may still add lifetime complexity, skipped destructors, async/thread
friction, and unnecessary dependency surface.

### Minimal artifact

```text
p09-memory-arena-allocation/
  Cargo.toml
  fixtures/session-small.jsonl
  fixtures/session-p95.jsonl
  fixtures/session-p99.jsonl
  fixtures/session-pathological.jsonl
  src/main.rs
```

Fixtures are synthetic and content-free but match measured shapes:

- small: 36 entries, 88 KiB,
- p95: 822 entries, 3.1 MiB,
- p99: 1,930 entries, 9.2 MiB,
- pathological: 5,157 entries, 29 MiB, one 4.6 MiB message.

Implement five workloads:

1. `discover`: scan 535 session headers/metadata without full load,
2. `load-replay`: decode full sessions into Smith-like `SessionEntry` values,
3. `render-window`: render visible rows from small/p95/p99/pathological sessions,
4. `request-build`: assemble provider request near 250k token context,
5. `arena-scratch`: compare baseline `Vec`/`String` vs `bumpalo` for render and
   request scratch only.

Use a counting global allocator. Measure allocations, allocated bytes, allocator
calls, peak live bytes where feasible, post-warmup live-memory plateau, elapsed
time, and Linux RSS via `/proc/self/statm` when available. Treat allocator calls
as syscall-pressure proxy; optional local strace/malloc tracing may be noted but
must not be required. Do not prototype `arena-allocator`; prior research flags it
too sharp for Smith.

### Verify

```bash
cd prototypes/p09-memory-arena-allocation
cargo run -- discover
cargo run -- load-replay
cargo run -- render-window
cargo run -- request-build
cargo run -- arena-scratch
cargo run -- all
```

### Pass evidence

- discovery allocation is O(session count + metadata), not O(total corpus bytes),
- full-load memory estimates stay within target bands from research,
- render-window allocation is O(visible rows) for p95/p99/pathological sessions,
- request-build reports peak allocation near compaction-size contexts,
- post-warmup render/request memory profile is reported across repeated phases,
- `bumpalo` keep/drop decision considers allocated bytes, allocation count,
  allocator calls, elapsed time, RSS/peak-live stability, and complexity,
- no arena reference crosses async/thread/persistent boundaries,
- output prints keep/drop recommendation for `bumpalo` per workload.

### SPEC impact

If baseline is sufficient, record “no arena allocation in v1” and keep normal
ownership.

If arenas win on allocator calls, elapsed time, or memory stability, add a SPEC
policy:

- arenas only for phase-local scratch memory,
- `bumpalo` allowed only in measured hot paths,
- keep/drop gates include allocator-call pressure and stable memory profile, not
  only allocation reduction,
- persisted/session data uses stable IDs and owned bytes/strings,
- no custom unsafe arena implementation.

If session discovery/load/render exceeds targets, SPEC must clarify lazy loading,
virtual-scroll cache boundaries, max retained render state, and provider-request
peak-memory behavior.

## P10 — `p10-lua-plugin-heap-limit`

### SPEC claims

Smith's Lua plugin sandbox can enforce per-plugin heap limits.

Candidate claims:

- `mlua + LuaJIT` supports `Lua::used_memory()` and `Lua::set_memory_limit()` in
  Smith's locked feature set.
- A plugin exceeding its configured heap limit fails with a recoverable Lua
  memory error.
- Heap limit failure does not corrupt the host runtime or other plugins.
- Host-created values exposed to Lua have clear accounting semantics.

### Risk

Lua heap accounting may not include all host-side allocations, may behave
differently under LuaJIT, or may make plugin isolation require one Lua state per
quota domain. Shared Lua state + per-plugin quota may be impossible.

### Minimal artifact

```text
p10-lua-plugin-heap-limit/
  Cargo.toml
  plugins/small.lua
  plugins/oom_table.lua
  plugins/oom_string.lua
  plugins/host_value.lua
  src/main.rs
```

Use Smith's planned `mlua = { features = ["luajit", "vendored", "serialize"] }`
shape.

Implement four scenarios:

1. `small`: plugin stays below limit,
2. `oom-table`: table growth hits limit,
3. `oom-string`: string/buffer growth hits limit,
4. `isolation`: one plugin OOMs, another plugin still runs.

Test one-state-per-plugin first. If shared-state quotas are attempted, report
whether they are enforceable or impossible.

### Verify

```bash
cd prototypes/p10-lua-plugin-heap-limit
cargo run -- small
cargo run -- oom-table
cargo run -- oom-string
cargo run -- isolation
cargo run -- all
```

### Pass evidence

- `used_memory()` reports nonzero growth,
- `set_memory_limit()` rejects table/string growth with recoverable error,
- host process survives OOM scenario,
- isolated plugin state still works after another plugin OOMs,
- output states whether per-plugin quota requires one Lua state per plugin.

### SPEC impact

If viable, SPEC should add plugin heap quota fields and define quota domain:
per-plugin Lua state or shared runtime.

If not viable, SPEC should avoid promising plugin heap limits and instead define
coarser process/session limits.

## P11 — `p11-plugin-memory-domain-reload`

### SPEC claims

Smith can make plugin reload/unload memory management simple by assigning each
plugin instance a memory domain and dropping the whole domain on reload.

Candidate claims:

- A plugin runtime can own all reloadable plugin state behind one domain object:
  Lua state, registry handles, hook/tool descriptors, render caches, interface
  adapters, and host-side plugin scratch memory.
- Reload is `drop(old_domain) -> construct(new_domain)` with no per-resource
  cleanup graph.
- Arena-backed or domain-owned host allocations produce stable memory behavior
  across repeated reloads.
- Plugin heap quota and plugin memory-domain teardown are complementary: Lua heap
  limit bounds VM allocations; domain teardown bounds/reclaims host-side plugin
  allocations.

### Risk

Some plugin resources may escape the domain through async tasks, event bus
subscriptions, registry keys, UI caches, or shared host registries. If escape is
possible, reload can leak memory or leave stale callbacks even with an arena.

### Minimal artifact

```text
p11-plugin-memory-domain-reload/
  Cargo.toml
  plugins/grow.lua
  plugins/register_many.lua
  src/main.rs
```

Model a `PluginDomain` that owns:

- one `mlua::Lua`,
- plugin metadata/descriptors,
- hook/tool registries,
- render/layout cache,
- host scratch/domain arena or bump allocator,
- cancellation token for async tasks,
- subscription tokens dropped with the domain.

Run repeated load/use/reload cycles. Include one intentionally escaped resource
scenario that must fail validation.

### Verify

```bash
cd prototypes/p11-plugin-memory-domain-reload
cargo run -- reload-loop
cargo run -- reload-with-heap-limit
cargo run -- escaped-callback-fails
cargo run -- all
```

### Pass evidence

- repeated reloads plateau in RSS/live bytes after warmup,
- old hooks/tools/render caches disappear after reload,
- Lua heap is reclaimed by dropping the domain,
- domain arena/scratch is reclaimed or reset on reload,
- escaped callback/task/subscription is rejected or cancelled with clear error,
- no stale plugin callback can run after reload.

### SPEC impact

If viable, SPEC should define `PluginDomain`/reload ownership:

- one reloadable domain per plugin instance,
- all plugin-owned host memory/resources live inside that domain,
- reload is whole-domain replacement,
- no plugin callback/resource may outlive its domain,
- optional per-domain arena for host-side plugin state,
- Lua heap limit remains separate quota enforcement.

If not viable, SPEC must define explicit cleanup registries and leak/stale-callback
failure modes for plugin reload.

## Results

All prototypes implemented and run 2026-07-14, rustc 1.94.1,
x86_64-unknown-linux-gnu, mlua 0.10.5 vendored LuaJIT. Commands per prototype
section; each exits 0. Result blocks follow the reporting template, trimmed to
decision-relevant content; full diagnostics are in each prototype's output and
the corresponding commit message.

### P02 result

```json
{
  "status": "complete",
  "proved": [
    "plain Lua descriptor + runtime validation supports community interfaces",
    "missing function fails with exact path (impl/missing_fn.lua.cancel)",
    "bad shape fails with expected/actual (status: expected function, got string)",
    "extra impl fields hidden through interface view",
    "runtime arg validation rejects bad types naming fn/param"
  ],
  "disproved": [],
  "specIssues": [
    { "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" }
  ],
  "commands": ["cd prototypes/p02-lua-interface-descriptor && cargo run"],
  "nextSteps": ["make §9.6 candidate 1 canonical; P02b (Teal) not needed"]
}
```

### P03 result

```json
{
  "status": "complete",
  "proved": [
    "5-plugin ecosystem composes through one interface package; consumer source has no impl name",
    "user config swaps alice <-> bob-adapted with zero consumer changes",
    "pure-Lua adapter normalizes incompatible impl; passes same conformance check",
    "direct incompatible binding fails naming plugin, interface+generation, exact missing fns, actual exports, adapter hint"
  ],
  "disproved": [],
  "specIssues": [
    { "file": "../docs/SPEC.md", "issue": "§9.6 lacks adapter registration semantics (invented `adapts` + make-factory)", "evidence": "p03 bob-adapted scenario", "severity": "P1" },
    { "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" },
    { "file": "../docs/SPEC.md", "issue": "§9.2 `interfaces`/`implements` manifest field shapes undefined", "evidence": "p03 manifests", "severity": "P2" },
    { "file": "../docs/SPEC.md", "issue": "conformance-check timing (load vs bind) and undeclared-implements policy unstated", "evidence": "p03 bob-direct-fails", "severity": "P2" },
    { "file": "../docs/SPEC.md", "issue": "singleton vs per-consumer instance semantics open", "evidence": "alice module state vs adapter factory", "severity": "P3" }
  ],
  "commands": ["cargo run -- alice", "cargo run -- bob-adapted", "cargo run -- bob-direct-fails"],
  "nextSteps": ["amend §9.2/§9.6/§9.7 with manifest fields, adapter convention, binding config + precedence"]
}
```

### P04 result

```json
{
  "status": "complete",
  "proved": [
    "local-path + git-URL install into data_dir/smith/plugins/<org>/<name>/ (git via local bare repo, shell-out)",
    "name charset + smith/* reservation enforced before any write",
    "restricted empty-env manifest eval: os/require blocked, function values rejected as non-data",
    "smith_api defaults 1; smith_api=2 refused with required/supported generations",
    "install never executes entry code (armed side effect did not fire)",
    "duplicate refused without --force; --force = remove-then-copy, data kept",
    "uninstall keeps data / --purge-data removes it / project plugins never touched"
  ],
  "disproved": [],
  "specIssues": [
    { "file": "../docs/SPEC.md", "issue": "§9.2 never states the manifest FILENAME (prototype: smith-plugin.lua)", "evidence": "p04 all commands", "severity": "P1" },
    { "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" },
    { "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" }
  ],
  "commands": ["cargo run -- install-local|install-git|reject-bad-name|reject-smith-namespace|uninstall-keeps-data|uninstall-purge-data"],
  "nextSteps": ["canonicalize manifest filename; define --force/duplicate/git-layout; decide git boundary"]
}
```

### P05 result

```json
{
  "status": "complete",
  "proved": [
    "pi-primary field-level recursive merge; catwalk fills gaps at field/model/provider granularity",
    "generate writes nothing; suggestion + reviewable source-attributed patch on stdout",
    "two unresolvable conflict classes detected, excluded, reported: ambiguous-primary-source, type-mismatch-vs-curated-registry"
  ],
  "disproved": [
    "byte-for-byte unknown-field preservation with default serde_json (keys re-sort); preservation is semantic (Value-equal) only"
  ],
  "specIssues": [
    { "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" },
    { "file": "../docs/SPEC.md", "issue": "§7.3 has no conflict taxonomy/policy at all", "evidence": "p05 conflict-fails", "severity": "P1" },
    { "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" }
  ],
  "commands": ["cargo run -- generate", "cargo run -- diff", "cargo run -- conflict-fails"],
  "nextSteps": ["amend §7.3: merge granularity, conflict classes, semantic preservation, CLI contract"]
}
```

### P06 result

```json
{
  "status": "complete",
  "proved": [
    "truncated tail (mid-body, mid-prefix) stops parsing; prior entries survive",
    "corrupt entry BODY skips precisely with warning while framing intact",
    "unknown future variants distinguishable from corruption via two-stage decode (ciborium::Value then typed); preserved raw through v1 rewrite -> v2 read"
  ],
  "disproved": [],
  "specIssues": [
    { "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" }
  ],
  "commands": ["cd prototypes/p06-session-codec-recovery && cargo run"],
  "nextSteps": ["state the framing boundary in §6.6"]
}
```

### P07 result

```json
{
  "status": "complete",
  "proved": [
    "agent loop drives text/tool/done through StreamFn only; deterministic AgentEvent sequences",
    "tool results fed back to provider next turn",
    "BeforeToolCall allow/block/replace-args verified; blocked call never executes tool"
  ],
  "disproved": [],
  "specIssues": [
    { "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" }
  ],
  "commands": ["cargo run -- basic|tool|hook-block|hook-replace"],
  "nextSteps": ["state blocked-call event contract in §6.4"]
}
```

### P08 result

```json
{
  "status": "complete",
  "proved": [
    "TestBackend renders deterministic cell-by-cell (symbol + fg/bg/modifier); snapshot matches checked-in string; fully headless",
    "Lua theme tables validated by Rust schema drive widget styles; invalid theme rejected with exact path",
    "theme swap changes styles, leaves text byte-identical"
  ],
  "disproved": [],
  "specIssues": [
    { "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" },
    { "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" },
    { "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" }
  ],
  "commands": ["cd prototypes/p08-tui-testbackend && cargo run"],
  "nextSteps": ["define §8.8 theme schema + §17 style-aware snapshot contract"]
}
```

### P09 result

```json
{
  "status": "complete",
  "proved": [
    "discovery O(session count): 535 sessions from 54.8KiB of 41.64MiB corpus (0.13%), 3.1ms",
    "load/replay within research bands up to 29.78MiB pathological session; 4.6MiB message intact",
    "virtual scroll O(visible rows): 41 allocs/frame constant across 143x entry spread; giant message capped by lazy viewport wrap",
    "request-build ~250k tokens: transient peak 2.43MiB, zero live growth over 50 builds",
    "bumpalo scratch: render -100% allocator calls, x0.19 elapsed (KEEP); request -99% calls, x1.00 elapsed, +22% peak (marginal KEEP)"
  ],
  "disproved": [
    "arenas as a latency win for request-build: serde_json serialization dominates; win is allocator-call pressure only"
  ],
  "specIssues": [
    { "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" },
    { "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" },
    { "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" }
  ],
  "commands": ["cargo run --release -- discover|load-replay|render-window|request-build|arena-scratch|all"],
  "nextSteps": ["add memory policy to SPEC; re-run keep/drop on real render code before production commitment"],
  "deviation": "PLAN fixtures/*.jsonl not committed; synthetic sessions generated at runtime (deterministic seed) matching PLAN shapes within 2.5%"
}
```

### P10 result

```json
{
  "status": "complete",
  "proved": [
    "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",
    "oom-table/oom-string rejected at exactly the 16MiB quota (overshoot 0) with recoverable MemoryError; state reusable after gc_collect; host survives",
    "isolation: plugin B in its own state unaffected by A's OOM",
    "host-created Lua strings charged to the quota (8MiB string -> delta 8388672)",
    "quota domain: per-plugin heap quota = one Lua state per plugin"
  ],
  "disproved": [
    "shared-state per-plugin quotas: only a whole-state limit exists, no attribution (B charged at A's retained 15.3MiB)",
    "Lua quota covering host-side Rust allocations: 8MiB userdata payload registered 632 bytes",
    "hook-based fallback under active JIT: count hooks never fire JIT-on (0 fires / 3e6 iterations); interpreter-only, ~3.4x slowdown"
  ],
  "specIssues": [
    { "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" },
    { "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" },
    { "file": "../docs/SPEC.md", "issue": "any future instruction watchdog cannot use LuaJIT count hooks (never fire under JIT)", "evidence": "p10 hook bench", "severity": "P3" }
  ],
  "commands": ["cargo run -- small|oom-table|oom-string|isolation|all"],
  "nextSteps": ["add heap-quota to SPEC §9 with per-plugin-state domain; CI-verify enforcement per release target (non-GC64 -> MemoryControlNotAvailable)"]
}
```

### P11 result

```json
{
  "status": "complete",
  "proved": [
    "§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",
    "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",
    "rollback: broken entry keeps old domain serving; partial D' registrations discarded",
    "31MB Lua heap 100% reclaimed by domain drop; fresh domain restarts at 45KB",
    "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"
  ],
  "disproved": [],
  "specIssues": [
    { "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" },
    { "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" }
  ],
  "commands": ["cargo run -- reload-loop|reload-with-heap-limit|escaped-callback-fails|all"],
  "nextSteps": ["fold registry/generation-gate discipline into §9.16; re-verify !Send containment if mlua 'send' feature is ever enabled"]
}
```

## Campaign 2 — new contracts from the readiness passes

The 2026-07-15/16 readiness passes added contracts to `../docs/SPEC.md`
(§5.1/§5.8, §6.1, §6.5, §6.7, §6.9) that lack prototype evidence. P12–P14
validate their risky cores.

## P12 — `p12-session-tree-fold`

### SPEC claims

- §6.5: branches are emergent paths; append at a non-leaf entry creates a
  fork point implicitly; leaf switches persist as append-only metadata
  entries; effective leaf on load = last leaf-switch target or last append.
- §6.9: compaction is an assembly-time fold — a summary entry covering a span
  collapses that span; trim masks collapse content into stubs; storage never
  changes.
- §6.5×§6.9: switching the leaf to a pre-compaction entry yields a path
  without the summary (full history visible, re-compactable); branches
  created after the compaction point inherit the mask.
- Recency window and secret registrations survive folding verbatim.

### Risk

Path folding may be ill-defined at edges: a summary entry whose covered span
crosses a fork point, nested summaries (summary covering a summary), or a
leaf-switch entry inside a covered span.

### Minimal artifact

```text
p12-session-tree-fold/
  Cargo.toml        (serde, ciborium — §6.6 length-prefixed format)
  src/main.rs
```

### Verify

```bash
cd prototypes/p12-session-tree-fold
cargo run -- tree
cargo run -- leaf-persist
cargo run -- fold
cargo run -- branch-past-compaction
cargo run -- all
```

### Pass evidence

- append/switch/read-path behave per §6.5 including implicit fork points,
- write file, truncate/corrupt tail, reload: effective leaf matches the
  §6.5 rule under §6.6 recovery,
- folded path collapses covered spans + trim stubs; raw entries untouched,
- pre-compaction leaf switch sees full history; post-compaction branch
  inherits the mask,
- edge findings reported: span×fork crossings, nested summaries, leaf-switch
  entries inside covered spans.

### SPEC impact

Tighten §6.9 with whatever edge rules the fold needs (e.g. spans may not
cross fork points; summaries may nest or may not).

## P13 — `p13-secret-proxy-mechanics`

### SPEC claims

- §6.7: plaintext exists only in secret-registration entries; ingestion
  masks all other content; ingestion scan runs AFTER plugin
  input/tool_result hooks (a hook-registered value is masked in the very
  content that surfaced it); rehydration only at tool execution; resume
  rebuilds the table by backward scan; unknown placeholder ids pass through.

### Risk

The hook-then-scan ordering may be racy or ambiguous when a hook both
transforms content and registers a secret found in the pre-transform text.
Exact-substring masking may corrupt content when one secret is a substring
of another or of a placeholder.

### Minimal artifact

```text
p13-secret-proxy-mechanics/
  Cargo.toml        (mlua luajit vendored, serde, ciborium)
  plugins/detector.lua   (input/tool_result hook registering found values)
  src/main.rs
```

### Verify

```bash
cd prototypes/p13-secret-proxy-mechanics
cargo run -- ingest
cargo run -- hook-order
cargo run -- rehydrate
cargo run -- resume
cargo run -- all
```

### Pass evidence

- registered values masked at ingestion; registration entry holds plaintext;
  every other entry stores placeholders,
- Lua detector hook registers a value from content; the same content lands
  masked,
- tool execution receives rehydrated args; provider-request view stays
  masked; unknown ids untouched,
- reload from file rebuilds table; masking works immediately,
- findings on overlapping-secret and secret-inside-placeholder edge cases.

### SPEC impact

Define masking order for overlapping secrets (e.g. longest-match-first) and
any hook/transform ordering rule §6.7 needs beyond "scan after hooks".

## P14 — `p14-steering-queue`

### SPEC claims

- §6.1: steers deliver at the next safe boundary (stream end / current tool
  completion); pending tool calls resolve as synthetic error results
  (`skipped: user steered`); queued steers drain FIFO before the next
  provider call; follow-ups dequeue instead of `agent_end`; entries recorded
  on delivery only; abort leaves the remainder queued.

### Risk

Boundary delivery may interleave badly with parallel tool execution
(§5.3 ToolExecutionMode) — "currently executing tool finishes" is ambiguous
when three run concurrently. Synthetic results for skipped calls may need
exact ordering relative to real results.

### Minimal artifact

```text
p14-steering-queue/
  Cargo.toml        (serde_json only; extends the p07 loop pattern)
  src/main.rs
```

### Verify

```bash
cd prototypes/p14-steering-queue
cargo run -- steer-mid-stream
cargo run -- steer-mid-tools
cargo run -- steer-parallel-tools
cargo run -- followup
cargo run -- abort-keeps-queue
cargo run -- all
```

### Pass evidence

- deterministic AgentEvent sequences for each scenario (p07 style),
- steer during tool batch: running tool completes, remaining calls resolve
  skipped-with-error, steer message precedes next provider request,
- parallel mode: boundary semantics reported (all in-flight finish vs first
  finish),
- follow-up consumed instead of agent_end; FIFO order held,
- abort ends run, queue contents intact and reported,
- session-entry recording happens at delivery time only.

### SPEC impact

Pin the parallel-execution boundary rule in §6.1 and the ordering of
synthetic skipped results relative to completed results.

## Campaign 2 Results

Run 2026-07-16, rustc 1.94.1, x86_64-unknown-linux-gnu. All three complete;
findings folded into SPEC (§6.1, §6.5, §6.7, §6.9).

### P12 result

```json
{
  "status": "complete",
  "proved": [
    "tree ops per §6.5 incl. implicit fork points; leaf-switch persistence under §6.6 recovery",
    "fold: span collapse at path position, trim stubs, byte-identical storage through every fold/switch/compaction",
    "branch-past-compaction: pre-compaction switch sees full history, re-compacts as SIBLING summary; post-compaction branches inherit the mask",
    "edges: cross-fork spans detectable + safely ignored; nested summaries inevitable, outermost-wins; leaf-switch inside covered span folds away (leaf replay reads raw storage)"
  ],
  "disproved": [
    "§6.5 literal leaf-load rule ('last switch target, else last append') — stale leaf whenever appends follow a switch; correct rule is replay-in-file-order (last surviving entry decides)"
  ],
  "specIssues": [
    { "file": "../docs/SPEC.md", "issue": "leaf-load rule false as written", "evidence": "leaf-persist: literal=Some(2) vs replay=Some(6)", "severity": "P1" },
    { "file": "../docs/SPEC.md", "issue": "§6.9 'registrations survive verbatim' x §6.7 'provider carries placeholders only' contradiction — structural survival + masked provider rendering required", "evidence": "fold: hoist-secret#2 with plaintext intact", "severity": "P1" },
    { "file": "../docs/SPEC.md", "issue": "span well-formedness, nested-summary outermost-wins, trim-ladder scoping of 'survives verbatim', orphan/dangling recovery rules, metadata foldability all needed", "evidence": "fold + branch-past-compaction + leaf-persist diagnostics", "severity": "P2" }
  ],
  "commands": ["cargo run -- tree|leaf-persist|fold|branch-past-compaction|all"],
  "nextSteps": ["all folded into §6.5/§6.9 (2026-07-16)"]
}
```

### P13 result

```json
{
  "status": "complete",
  "proved": [
    "plaintext bytes exist exactly once in the file (registration entry) — byte-scan verified",
    "hook-then-scan ordering: Lua detector registering during a hook masks the surfacing content",
    "rehydration is a view at tool execution only (Rust + Lua); provider view masked; unknown ids pass through",
    "resume rebuilds table with original ids; allocator resumes past max id",
    "longest-match-first single-pass masking correct; naive order provably leaks overlap residue"
  ],
  "disproved": [],
  "specIssues": [
    { "file": "../docs/SPEC.md", "issue": "masking order must be longest-match-first single-pass never rescanning placeholders", "evidence": "ingest overlap scenario residue leak", "severity": "P1" },
    { "file": "../docs/SPEC.md", "issue": "placeholder-grammar registered values alias placeholders; single-pass rehydration load-bearing; reject such registrations", "evidence": "ingest placeholder-shaped scenario", "severity": "P2" },
    { "file": "../docs/SPEC.md", "issue": "scan is post-transform only (re-encoding hook launders secrets) — stated limit; allocator resume, idempotent re-registration, maximal-digit-run parsing", "evidence": "hook-order + resume + rehydrate scenarios", "severity": "P2" }
  ],
  "commands": ["cargo run -- ingest|hook-order|rehydrate|resume|all"],
  "nextSteps": ["all folded into §6.7 (2026-07-16)"]
}
```

### P14 result

```json
{
  "status": "complete",
  "proved": [
    "boundary delivery (stream end / in-flight completion), synthetic skipped results for every unexecuted call, FIFO steer drain, follow-up-instead-of-agent_end, delivery-time-only entry recording, abort keeps queues intact",
    "parallel mode: wait-for-all-in-flight workable — no new call starts after a steer queues, started calls complete, never-started skip",
    "transcript rule: reals first (completion order), synthetics in original call order, steers follow"
  ],
  "disproved": [],
  "specIssues": [
    { "file": "../docs/SPEC.md", "issue": "'currently executing tool finishes' ill-defined with N in flight — pin wait-for-all-in-flight", "evidence": "steer-parallel-tools", "severity": "P1" },
    { "file": "../docs/SPEC.md", "issue": "synthetics-after-reals ordering must be stated (reals may be completion-ordered)", "evidence": "steer-mid-tools + steer-parallel-tools transcripts", "severity": "P1" },
    { "file": "../docs/SPEC.md", "issue": "mid-stream steer skips ALL calls; skipped calls emit §6.4-style events; abort leaves dangling tool-call tail — resume must repair", "evidence": "steer-mid-stream + abort-keeps-queue", "severity": "P2" }
  ],
  "commands": ["cargo run -- steer-mid-stream|steer-mid-tools|steer-parallel-tools|followup|abort-keeps-queue|all"],
  "nextSteps": ["all folded into §6.1 (2026-07-16); re-verify wait-for-all under real tokio timing when the loop lands"]
}
```

## Reporting Template

Each completed prototype updates this plan with a result block in the
Markdown shape required by `prototypes/CLAUDE.md` (canonical:
`.claude/skills/pioneer/SKILL.md`). Result blocks recorded before
2026-07-16 use the earlier JSON shape and stand as historical records.