repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

docs: close readiness gaps with prototype-validated contracts (§5, §6.1, §6.5, §6.7, §6.9) (#3)

26d6f6ae86cc569aeed22ec189402e91e335badc

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

* docs: close §5 readiness gaps — role model, thinking round-trip, error taxonomy

First readiness-gap pass (user decisions applied):

- §5.1 Role slimmed to System|User|Assistant|Tool. ContentBlock is the
  authoritative content representation: tool results are Tool-role
  messages carrying ToolResult blocks; the ToolResult/Custom/
  BashExecution roles are gone. Roles say who speaks; SessionEntry
  kinds say what happened — bash executions become a §6.5 entry kind.
- §5.1 Thinking gains opaque provider_metadata (preserved, never
  consumed) so signed thinking round-trips across turns (§7.2
  adapters attach and replay it).
- §5.2 ProviderEvent payload shapes pinned; ToolCall events are
  assembled-complete at the provider boundary. ProviderError kinds
  (RateLimit, AuthFailed, Network, ServerError, InvalidRequest,
  ModelNotFound, Timeout) declared — §7.5's failover matrix was
  spec'd against undeclared types; now keyed to §5.2.
- §5.8 rewritten as the error umbrella: names the wrapped domain
  errors at their subsystems and defines the recoverable-vs-fatal
  rule (recoverable surfaces as content and the loop continues;
  fatal restores the terminal and exits nonzero).
- §6.5 notes new entry kinds are forward-compatible via §6.6
  unknown-variant preservation.

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

* docs: define session tree operations (SPEC §6.5)

Second readiness-gap pass (user decisions applied). §6.5 had the data
structure (parent pointers, current leaf) and evidence of operations
(session_before_fork event, fork tests) but never defined them:

- branches are emergent (root->leaf paths), never stored or named;
  append-only immutability stated precisely,
- operations: append (implicit fork points at non-leaf appends),
  switch leaf, read path, fork (clone-to-new-session, distinct from
  in-tree branching),
- LLM context = current path only; sibling branches invisible,
- leaf persistence: leaf switches append a metadata entry (new §6.5
  entry kind) — effective leaf on load = last switch or last append;
  rides §6.6 append-only recovery, leaf history replayable,
- leaf switches never touch the working tree: filesystem time travel
  is time-travel-plugin policy via smith.vcs.op_restore + stored
  VcsOpId; conversation navigation alone is never destructive,
- no branch deletion in v1; single writer per session.

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

* docs: define compaction contract (SPEC §6.9)

Third readiness-gap pass (user decisions applied). Compaction falls out
of the §6.5 immutability decisions: it cannot rewrite history, so it is
a context-assembly-time mask, not a storage mutation.

- storage never shrinks; a pass appends a summary entry recording the
  covered span + summary + token estimates,
- context assembly folds the path: covered spans collapse into their
  summary, trimmed content into stubs; the file is untouched,
- branching needs no special case: pre-compaction leaf switches see
  full history (eligible to re-compact); post-compaction branches
  inherit the mask,
- trigger: estimated folded-path tokens exceed a named config threshold
  (fraction of context window minus output reserve; reloadable),
- trim ladder: old tool-result bodies -> old thinking blocks -> LLM
  summarization of the oldest span,
- summarization model: active model unless compaction_model config key
  overrides (resolved via §5.7); usage tracked as normal cost,
- survives verbatim: secret registrations, system prompt snapshot,
  prior summaries, and a token-budget recency window (fraction of the
  context window, adapting to model size),
- session_before_compact may veto/adjust span/replace prompt.

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

* docs: define secret proxy contract (SPEC §6.7)

Fourth readiness-gap pass (user decisions applied): registry-only
detection, masked display, detection mechanisms are plugin territory.

- core owns masking mechanics only; detection mechanisms (pattern-based
  or otherwise) are plugins using smith.secret.register through the
  §9.8 input/tool_result hooks,
- ordering mechanic that enables detection plugins: the ingestion scan
  runs after plugin hooks, so values registered while inspecting
  content are masked in that same content,
- registration paths: auto (auth resolver credentials; manifest
  declared-secrets read via SDK), explicit (/secret built-in), plugins
  (smith.secret.* — list() returns labels/ids, never plaintext),
- plaintext lives in exactly one entry kind (secret registration);
  all other content stores smith:sec:N placeholders from ingestion,
- rehydration at exactly one layer: immediately before tool execution;
  provider requests/traces/events stay masked; replay-compare
  rehydrates from registration entries; unknown ids pass through,
- TUI renders placeholders masked with label,
- limits stated: unregistered secrets are unprotected by design (§11).

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

* docs: define steering/follow-up semantics and input queue UX (SPEC §6.1, §8.11)

Fifth readiness-gap pass (user's UX design applied). Core semantics
(§6.1):

- follow-up: FIFO, consulted instead of agent_end — dequeues as a
  fresh user message and starts a new turn cycle,
- steering: delivers at the next safe boundary (stream end or current
  tool completion); pending tool calls resolve as synthetic
  error-flagged "skipped: user steered" results so every wire call has
  a result; queued steers drain FIFO before the next provider call,
- input during a run steers by default, modifier submits follow-up;
  plugins override via the input hook / smith.send_message,
- queues are ephemeral: entries recorded on delivery only; compaction
  neither consumes nor drops queues; after an abort the remainder
  stays queued for the user to send, edit, or discard.

Input queue UX (new §8.11; deferred scope bumped to §8.12):

- one visually combined queue, follow-ups above steers (steers nearest
  the input — they deliver soonest), oldest-to-newest per kind,
  visually distinct kinds,
- promote/demote toggles a message between steer and follow-up,
- Up-arrow cycles the queue; editing temporarily removes the message,
  re-send returns it to its previous position (best effort), re-send
  empty deletes it,
- cancel keys pop queued messages newest-to-oldest instead of their
  default action while the queue is non-empty; abort only on empty
  queue.

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

* docs: add prototype plan for campaign 2 (p12-p14)

The readiness passes added contracts (§5, §6.1, §6.5, §6.7, §6.9)
without prototype evidence. New targets validate their risky cores:

- p12 session-tree-fold: emergent branches, leaf-switch persistence
  under §6.6 recovery, assembly-time compaction folding, and the
  branch-past-compaction property; hunts fold edge cases (spans
  crossing fork points, nested summaries),
- p13 secret-proxy-mechanics: ingestion masking, hook-then-scan
  ordering with a real Lua detector plugin, tool-boundary rehydration,
  resume rebuild; hunts overlapping-secret edge cases,
- p14 steering-queue: boundary delivery, synthetic skipped results,
  FIFO drain, follow-up-instead-of-agent_end, abort-keeps-queue;
  reports the parallel-tool boundary ambiguity.

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

* feat(prototypes): p13 secret proxy mechanics — PASS with findings

Proves SPEC §6.7: ingestion masking (plaintext bytes exist exactly once
in the file — in the registration entry, byte-scan verified), hook-then-
scan ordering with a real Lua detector plugin (value registered during
a tool_result hook is masked in the content that surfaced it),
rehydration as a view at the tool-execution boundary only (Rust and Lua
alike), unknown-id passthrough, resume rebuild with original ids.

Findings for §6.7 (1×P1, 3×P2):
- masking order MUST be longest-match-first, single left-to-right pass
  never rescanning emitted placeholders — naive order provably leaks a
  '-123' residue of the longer secret (P1),
- placeholder-grammar registered values alias legit placeholders;
  single-pass rehydration is load-bearing (a second pass exposes an
  unrelated secret's plaintext),
- scan is post-transform only: a hook that re-encodes a secret launders
  it past exact matching — deliberate limit, must be stated,
- resume must restore the id allocator past max-seen (reuse would
  alias), duplicate registration is idempotent, placeholder ids parse
  as maximal digit runs (smith:sec:12 != id 1 + '2').

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

* feat(prototypes): p14 steering queue — PASS with findings

Proves SPEC §6.1: boundary delivery (stream end / current tool
completion, never interrupting), synthetic skipped results for every
unexecuted call, FIFO steer drain before the next provider call,
follow-up-instead-of-agent_end, delivery-time-only entry recording,
abort-keeps-queue with intact snapshots.

Findings for §6.1 (2×P1, 2×P2, 1×P3):
- parallel boundary must be WAIT-FOR-ALL-IN-FLIGHT: once a steer is
  queued no new call starts, started calls run to completion,
  never-started calls skip — "currently executing tool" is ill-defined
  with N in flight (P1),
- transcript rule: synthetics sort AFTER all real results (which may be
  in completion order), synthetics themselves in original call order,
  steer messages follow (P1),
- mid-stream steer: ALL calls of that assistant message skip, none
  executes — the coherent reading, but must be stated,
- skipped calls emit §6.4-style Start/End(is_error) events,
- abort leaves a dangling tool-call tail in the session; resume must
  tolerate or repair it.

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

* feat(prototypes): p12 session tree fold — PASS with disproof

Proves SPEC §6.5/§6.9 composite: tree ops (implicit fork points),
append-only leaf-switch persistence under §6.6 recovery, assembly-time
folding (span collapse, trim stubs, byte-identical storage), and
branch-past-compaction (pre-compaction switch sees full history and
re-compacts as a SIBLING summary; post-compaction branches inherit the
mask).

DISPROOF (P1): §6.5's literal leaf-load rule ("last leaf-switch target,
else last append") yields a stale leaf whenever appends follow the last
switch. Correct rule: replay entries in file order — append moves the
leaf to itself, switch to its target; last surviving entry decides;
dangling switch targets ignored.

Findings:
- §6.9×§6.7 contradiction (P1): registrations hold plaintext, so
  "survives verbatim" must mean structural survival (hoisted from
  collapsed spans) with masked/excluded provider rendering,
- span well-formedness: contiguous ancestor segment; violations are
  file damage — ignore summary, show raw, diagnose,
- nested summaries are inevitable (re-compaction covers the prior
  summary); outermost-wins; "survives verbatim" scopes to the trim
  ladder only,
- §6.6 corrupt-skip can orphan children / dangle switches: detach-and-
  report orphans, ignore dangling switches on replay,
- metadata entries inside covered spans fold away safely (leaf replay
  reads raw storage, never the fold).

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

* docs: fold campaign-2 prototype evidence into SPEC

All three campaign-2 prototypes complete (result blocks in PLAN.md).
Evidence-driven fixes:

§6.5 (p12): leaf-load rule CORRECTED — the shipped rule was disproven
(stale leaf when appends follow a switch); now replay-in-file-order,
last surviving entry decides, dangling switch targets ignored. Orphan/
dangling recovery rules added (detach-and-report, never silently graft).

§6.9 (p12): fold rules pinned — span well-formedness (contiguous
ancestor segment; violations ignored with diagnostic, never partial
collapse), nested summaries outermost-wins (nesting is inevitable via
re-compaction), metadata entries fold away safely, sibling summaries on
re-compacted branches. "Survives verbatim" rescoped to the trim ladder;
secret registrations survive STRUCTURALLY but are masked in provider
rendering — fixes the §6.9x§6.7 plaintext-to-LLM contradiction (P1).

§6.7 (p13): longest-match-first single-pass masking (any other order
leaks overlap residue — P1), single-pass rehydration, placeholder-
grammar registrations rejected, idempotent re-registration, maximal-
digit-run parsing, allocator resume past max id, post-transform-only
scan limit stated.

§6.1 (p14): parallel steering boundary pinned to wait-for-all-in-flight
(P1), transcript ordering reals-then-synthetics-then-steers (P1),
mid-stream steer skips all calls, skipped calls emit §6.4-style events,
dangling tool-call tail after abort repaired at next request assembly.

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 (12)

+3354 / −34 text lines

Diff layout

docs/SPEC.md

Modified

+265 / −34 text lines

364364- `SessionId(String)`.
365365- `SecretId(String)`.
366366- `VcsOpId(String)`.
367- `Role`: `System`, `User`, `Assistant`, `Tool`, `ToolResult`, `Custom`, `BashExecution`.
368- `ContentBlock`:
367- `Role`: `System`, `User`, `Assistant`, `Tool`.
368- `ContentBlock` — the authoritative content representation:
369369 - `Text(String)`,
370370 - `Image { data, media_type }`,
371 - `ToolCall { id, name, arguments }`,
371 - `ToolCall { id, name, arguments (JSON) }`,
372372 - `ToolResult { id, result, is_error }`,
373 - `Thinking { content }`.
374- `Message { role, content }`.
373 - `Thinking { content, provider_metadata? }` — `provider_metadata` is opaque
374 and preserved, never consumed by Smith; provider adapters attach it (e.g.
375 thinking signatures) and replay it on later requests (§7.2), so signed
376 thinking round-trips across turns.
377- `Message { role, content: list of ContentBlock }`.
379Roles say who speaks; entry kinds say what happened. Tool results are
380`Tool`-role messages carrying `ToolResult` blocks — there is no tool-result
381role. Events like user bash executions are `SessionEntry` kinds (§6.5), not
382roles.
376384### 5.2 Provider Types
379387- `StopReason`: `EndTurn`, `ToolUse`, `OverMaxTokens`, `Aborted`, `StopSequence`, `Error`.
380388- `ThinkingLevel`: `Off`, `Minimal`, `Low`, `Medium`, `High`, `XHigh`.
381389- `ProviderEvent`:
382 - `TextDelta`,
383 - `ToolCall`,
384 - `ThinkingDelta`,
385 - `Done`,
386 - `Error`.
390 - `TextDelta { text }`,
391 - `ThinkingDelta { text }`,
392 - `ToolCall { id, name, arguments }` — assembled and complete; partial
393 argument chunks are joined at the provider boundary (§7.2),
394 - `Done { usage, stop_reason }`,
395 - `Error(ProviderError)`.
396- `ProviderError` kinds — the failover-relevant classification consumed by
397 `MuxProvider` (§7.5), each carrying a message: `RateLimit`, `AuthFailed`,
398 `Network`, `ServerError`, `InvalidRequest`, `ModelNotFound`, `Timeout`.
387399- `ProviderRequest` contains messages, system prompt, model/provider IDs, tool
388400 definitions, thinking level, token limit, and stop sequences.
500512### 5.8 Errors
502`SmithError` is the shared recoverable error enum. It wraps provider, auth, tool,
503config, Lua, I/O, CBOR, and resolver errors.
514`SmithError` is the shared error enum. It wraps the domain errors defined at
515their subsystems: `ProviderError` (§5.2), auth (§7.4), tool errors including
516the §9.12 codes, config validation (§5.6), Lua (§5.5), I/O, session/trace
517codec (§6.6, §6.11), and model resolution (§5.7).
505Internal impossible states use assertions during development but shipped library
506code must not panic for external failures.
519Recoverability is the load-bearing property of every error path:
521- **Recoverable** (the default): the failure surfaces to the user and/or the
522 LLM as content — error tool results (§6.4), UI notifications, plugin
523 diagnostics (§9.17) — and the loop continues. Provider failures (§7.5),
524 tool errors, plugin faults and OOM (§9.14, §9.17), and rejected config
525 reloads (§9.19) are all recoverable.
526- **Fatal**: the process cannot continue safely — unrecoverable terminal
527 state, invalid startup config, providers exhausted in non-interactive eval.
528 Fatal paths restore the terminal (§10) and exit nonzero with a diagnostic.
530Shipped library code never panics for external failures; internal impossible
531states use debug assertions.
508533## 6. Core Crate: `smith-core`
526551- handles steering/follow-up messages,
527552- repeats until stop criteria.
554Steering and follow-up semantics:
556- **Follow-up**: FIFO queue consulted when the run would otherwise end —
557 instead of `agent_end`, the loop dequeues the next follow-up as a fresh
558 user message and starts a new turn cycle.
559- **Steering**: delivers at the next safe boundary — after the current
560 provider stream completes, or after in-flight tool execution finishes.
561 Never-started tool calls from the current assistant message resolve as
562 error-flagged synthetic results (`skipped: user steered`) so every call
563 has a result on the wire; the model re-plans with the steer visible. All
564 queued steers drain FIFO as user messages before the next provider call.
565 Prototype-proven boundary rules (p14):
566 - parallel execution (§5.3): **wait-for-all-in-flight** — once a steer is
567 queued, no new call starts; every already-started call runs to
568 completion; only never-started calls skip,
569 - steer arriving mid-stream: no call of that assistant message has
570 started, so ALL of them skip — none executes,
571 - transcript ordering: real results first (completion order in parallel
572 mode), then synthetics in original call order, then the drained steers,
573 - skipped calls emit `ToolExecutionStart`/`ToolExecutionEnd` with error
574 flag and reason, per the §6.4 blocked-call contract.
575- Interactive input during an active run is a steer by default; a modifier
576 submits it as a follow-up (§8.11). Plugins override default user-message
577 behavior through the `input` hook (§9.8) and send programmatically via
578 `smith.send_message` (§9.10).
579- Queues are ephemeral process state: queued messages become session entries
580 when delivered, never when queued — the session records only what the model
581 saw. Compaction (§6.9) neither consumes nor drops the queues.
582- Cancel keys pop the queue before they abort: see §8.11. A delivered abort
583 (§12) ends the run; whatever remains queued stays queued and is surfaced by
584 the TUI for the user to send, edit, or discard. An abort can leave the
585 session tail with an assistant message whose tool calls have no results
586 (no next request exists to carry synthetics); request assembly after
587 resume must repair such a dangling tail by synthesizing aborted-results
588 for the unanswered calls (p14).
529590The loop uses two nested loops:
531592- outer loop: turns and follow-up messages,
599660- current leaf,
600661- created/updated timestamps.
602Sessions are branching trees. Branches are immutable once created. `/tree` and
603history/time-travel features are Lua plugins over this core state.
663Sessions are branching trees. A branch is emergent, not stored: the path from
664root to a leaf. `ctx.session.branch()` (§9.9) returns the current path.
665"Immutable once created" means entries are append-only and never rewritten —
666working from an older point creates a new child, never edits history. `/tree`
667and history/time-travel features are Lua plugins over this core state.
669Tree operations:
671- **append**: adds an entry as a child of the current leaf; the leaf advances
672 to it. Appending while the leaf sits on a non-leaf entry creates a fork
673 point implicitly — there is no explicit branch operation.
674- **switch leaf**: moves the current leaf to any entry, recorded by appending
675 a leaf-switch metadata entry. On load, the leaf is resolved by replaying
676 surviving entries in file order: an append moves the leaf to itself, a
677 leaf-switch moves it to its target — the last surviving entry decides
678 (prototype-proven, p12; the naive "last switch target" rule yields a stale
679 leaf once appends follow a switch). A leaf-switch whose target was lost to
680 §6.6 recovery is ignored on replay. Leaf state rides the append-only
681 recovery guarantees, and leaf history is replayable for free.
682- **read path**: returns the root→leaf path. The LLM context is built from
683 the current path only (through compaction, §6.9); sibling branches are
684 invisible to the model.
685- **fork**: clones entries up to a given entry into a new `SessionId` and
686 session file (the `session_before_fork` event, §9.8). Distinct from in-tree
687 branching, which stays in one file.
689No branch deletion or pruning exists in v1. A session has a single writer:
690one agent loop appends to it at a time.
692Recovery meets the tree (p12): a §6.6-skipped entry can be a parent or a
693switch target. Orphaned subtrees (parent missing) are detached and reported —
694unreachable from the root, never silently grafted; dangling leaf-switches are
695ignored during leaf replay.
697Leaf switches never touch the working tree. Filesystem time travel is plugin
698policy, not core behavior: the time-travel plugin (§9.11) pairs leaf switches
699with `smith.vcs.op_restore` using the `VcsOpId` stored in entries.
700Conversation navigation alone is never destructive.
605702`SessionEntry` variants include:
613710- secret registration,
614711- model/provider change,
615712- VCS operation,
713- user bash execution (`!`/`!!` commands and their output),
714- leaf switch (tree navigation),
616715- metadata entries needed for migration and replay.
618Every entry has a stable `EntryId`, optional parent, and timestamp.
717Every entry has a stable `EntryId`, optional parent, and timestamp. New entry
718kinds are forward-compatible by construction: readers preserve unknown
719variants (§6.6), so adding a kind never breaks older sessions or readers.
620721### 6.6 Session Format
641742### 6.7 Secret Proxy
643The secret proxy prevents LLM exposure of secrets:
744The secret proxy prevents LLM exposure of registered secrets. Smith provides
745the masking mechanics only; secret *detection* mechanisms are out of scope
746for core and belong to plugins.
645- scans user messages and tool outputs for secrets,
646- replaces secrets with `smith:sec:N`,
647- stores plaintext translation entries locally,
648- rehydrates tool arguments before local execution,
649- rebuilds table on resume by scanning session entries backward.
748**Registry.** The proxy holds a table of `SecretId → plaintext + label`.
749Registration paths:
651Secrets are stored as local plaintext; the trust model is §11's.
751- automatic: every credential the auth resolver loads (§7.4) — provider keys
752 can never enter context, even via a tool reading a config file,
753- automatic: values of a plugin's `declared secrets` (§9.2) when read through
754 the SDK,
755- explicit: the built-in `/secret` command (§9.11),
756- plugins: `smith.secret.register(value, label)` (§9.10). Detection plugins
757 (pattern-based or otherwise) inspect content through the §9.8 `input` /
758 `tool_result` hooks and register what they find; the mechanism is theirs,
759 the mechanics are Smith's.
761**Masking at ingestion.** Scanning is exact substring matching against
762registered values — no heuristics in core. Content is masked to `smith:sec:N`
763placeholders *before* it becomes a session entry. Plaintext exists in exactly
764one entry kind: the secret-registration entry (preserved structurally by
765compaction but masked in provider rendering, §6.9). The ingestion scan runs
766after plugin `input`/`tool_result` hooks, so a value registered during those
767hooks is masked in the very content that surfaced it. On resume, the table
768rebuilds by scanning session entries backward for registration entries, and
769the `SecretId` allocator resumes past the highest id seen — a reused id would
770silently alias older placeholders (p13).
772Masking and rehydration rules (prototype-proven, p13):
774- masking is **longest-match-first** in a single left-to-right pass that
775 never rescans emitted placeholder text — any other order provably leaks
776 residue of an overlapping secret,
777- rehydration is likewise single-pass; produced plaintext is never rescanned,
778- registration rejects values matching the placeholder grammar
779 (`smith:sec:<digits>`) with a diagnostic — accepting them aliases
780 legitimate placeholders,
781- re-registering identical plaintext is idempotent and returns the existing
782 id (detector hooks re-see the same token on every occurrence),
783- placeholder ids parse as the maximal digit run (`smith:sec:12` is id 12,
784 never id 1 followed by `2`).
786**Rehydration.** Placeholders turn back into plaintext at exactly one layer:
787immediately before tool execution (subprocess and tool `execute`, Rust and
788Lua alike). Session content, provider requests, traces, and events carry
789placeholders only. Replay with compare (§6.11) re-executes tools and
790therefore rehydrates from the session's registration entries; trace files
791themselves stay masked. A placeholder whose ID is not registered passes
792through untouched — never rehydrated, never an error.
794**Display.** The TUI renders placeholders masked with their label
795(`‹secret: github-token›`); display matches context content. The local user
796can recover plaintext from registration entries via `smith session dump`.
798**Limits.** An unregistered secret is not protected — by design. The scan
799applies to post-transform content only, with exact case- and
800encoding-sensitive matching: a hook that re-encodes a secret while
801transforming (§9.8) launders the derived form past the scan (p13) —
802pre-transform text is never persisted, so this is a stated boundary, not a
803bug. The protection target is the remote LLM; the trust model is §11's, and
804core does no best-effort guessing.
653806### 6.8 System Prompt
670823### 6.9 Compaction and Cost
672Compaction:
825Compaction never rewrites history. Entries are append-only (§6.5), so
826compaction is a mask applied at context-assembly time, not a storage
827mutation:
674- uses `AgentLoopConfig.model_metadata.context_window`,
675- starts with old non-essential/redundant entries,
676- runs summarization when trimming is insufficient,
677- repeats until context fits or configured iteration limit reached,
678- preserves secret registrations and necessary lineage.
829- **Storage never shrinks.** The session file keeps every entry verbatim;
830 memory stays bounded by lazy loading (§13.1).
831- **A compaction pass appends a summary entry** to the current path,
832 recording the covered span (from/to `EntryId`), the summary text, and
833 before/after token estimates.
834- **Context assembly folds the path** (§6.5 read path): spans covered by a
835 summary entry collapse into the summary; trim-masked content collapses
836 into stubs. What the model sees is the folded path; the file is untouched.
838Because the summary rides the path like any entry, branching needs no
839special case: switching the leaf to a pre-compaction entry yields a path
840without the summary — full history visible again, eligible to re-compact
841(producing a sibling summary on that branch) — and branches created after
842the compaction point inherit the mask.
844Fold rules (prototype-proven, p12):
846- **Span well-formedness**: a covered span is a contiguous ancestor segment
847 of the path the summary was appended to (`from` an ancestor of `to`; `to`
848 an ancestor of the summary entry). Well-formed compaction cannot produce a
849 span crossing a fork point; a violating span is file damage — the fold
850 ignores that summary, shows the span raw, and diagnoses. Never a partial
851 collapse.
852- **Summaries nest**: re-compaction on an already-compacted path always
853 covers the prior summary entry. The fold applies the outermost (latest)
854 covering span; inner summaries are subsumed.
855- **Metadata entries inside a covered span fold away** with the span — leaf
856 resolution and replay read raw storage (§6.5), never the folded path, so
857 nothing is lost.
859Trigger: before each provider request, when the estimated folded-path tokens
860exceed the configured threshold — by default a fraction of
861`AgentLoopConfig.model_metadata.context_window` minus the output-token
862reserve. The threshold is a named config key (§5.6; reloadable per §9.19).
864Trim ladder, cheapest first, repeated until the context fits or the
865configured iteration limit is reached:
8671. mask old tool-result bodies to stubs (dominant bytes per the memory
868 profile),
8692. mask old thinking blocks,
8703. LLM-summarize the oldest span. Summarization uses the active model unless
871 the `compaction_model` config key selects another (resolved via §5.7, so
872 aliases/groups work); its usage is tracked as normal cost.
874Survives the trim ladder (never stubbed or discarded by a compaction round —
875distinct from escaping a later covering span at fold time, which nothing
876does):
878- secret registrations (§6.7) — these survive *structurally*: hoisted out of
879 collapsed spans so resume and rehydration keep working, but they hold
880 plaintext, so the provider rendering masks/excludes them (§6.7 — a
881 verbatim-to-provider reading would ship plaintext to the LLM),
882- the system prompt snapshot,
883- existing compaction summary entries (they are summarizer input),
884- the recency window: the most recent entries up to a configured fraction of
885 the context window (token-budget based, so it adapts to model size).
887`session_before_compact` (§9.8, blockable) may veto the round, adjust the
888span, or replace the summarization prompt; `session_compact` reports the
889result.
680891Token estimator:
9041115`MuxProvider` wraps multiple providers/accounts for resolved groups and buckets.
906Behavior:
1117Behavior, keyed by the `ProviderError` kinds (§5.2):
9081119- `RateLimit`: immediate failover,
9091120- `AuthFailed`, `Network`, `ServerError`: retry configured count then failover,
9591170 conservative),
9601171- image protocol is `ImageProtocol::{Kitty, Sixel}`; the capability is
9611172 detected but has no v1 consumer — inline image rendering is deferred
962 (§8.11),
1173 (§8.12),
9631174- Kitty keyboard protocol flags are pushed on TUI startup and popped on
9641175 shutdown (including error/signal paths, §10),
9651176- synchronized output (`CSI ?2026 h/l`) wraps render passes when the terminal
10811292Tools may register `renderCall` and `renderResult` Lua renderers. TUI receives
10821293structured render instructions from harness, not arbitrary terminal writes.
1084### 8.11 Deferred Scope (v1)
1295### 8.11 Input Queue
1297Queued steering and follow-up messages (§6.1) appear in one visually combined
1298queue between message history and input:
1300- follow-ups render above steers; within each kind, oldest to newest — steers
1301 sit nearest the input because they deliver soonest,
1302- the two kinds are visually distinct within the shared queue,
1303- a promote/demote action toggles a queued message between steer and
1304 follow-up,
1305- Up-arrow cycles through the queued messages; selecting one edits it. While
1306 edited, the message temporarily leaves the queue; re-sending returns it to
1307 its previous position (best effort). Re-sending it empty removes it,
1308- while the queue is non-empty, the cancel keys (Ctrl+C/Esc by default,
1309 rebindable §9.11) remove queued messages newest-to-oldest *instead of*
1310 their default action; only with an empty queue do they abort the run
1311 (§12).
1313### 8.12 Deferred Scope (v1)
10861315Explicitly out of v1 TUI scope:
14121641- `smith.vcs.*`,
14131642- `smith.bus.*`,
14141643- `smith.config.*` (read access; `smith.config.reload()` triggers §9.19),
1644- `smith.secret.*` (`register(value, label)`, `list()` — labels/ids only,
1645 never plaintext; §6.7),
14151646- `smith.shortcut.*` (keyboard shortcut registration),
14161647- `smith.credentials.*` (`get(provider)`/`set(provider, value)` over the §7.4
14171648 auth store),
14731704- tools: `read`, `write`, `edit`, `bash`, `find`, `grep`, `ls`,
14741705- slash commands: `/undo`, `/redo`, `/history`, `/tree`, `/reload-config`,
1475 replay/time-travel,
1706 `/secret` (§6.7), replay/time-travel,
14761707- VCS tools,
14771708- default layout,
14781709- default keybindings,

prototypes/PLAN.md

Modified

+241 / −0 text lines

856856```
858## Campaign 2 — new contracts from the readiness passes
860The 2026-07-15/16 readiness passes added contracts to `../docs/SPEC.md`
861(§5.1/§5.8, §6.1, §6.5, §6.7, §6.9) that lack prototype evidence. P12–P14
862validate their risky cores.
864## P12 — `p12-session-tree-fold`
866### SPEC claims
868- §6.5: branches are emergent paths; append at a non-leaf entry creates a
869 fork point implicitly; leaf switches persist as append-only metadata
870 entries; effective leaf on load = last leaf-switch target or last append.
871- §6.9: compaction is an assembly-time fold — a summary entry covering a span
872 collapses that span; trim masks collapse content into stubs; storage never
873 changes.
874- §6.5×§6.9: switching the leaf to a pre-compaction entry yields a path
875 without the summary (full history visible, re-compactable); branches
876 created after the compaction point inherit the mask.
877- Recency window and secret registrations survive folding verbatim.
879### Risk
881Path folding may be ill-defined at edges: a summary entry whose covered span
882crosses a fork point, nested summaries (summary covering a summary), or a
883leaf-switch entry inside a covered span.
885### Minimal artifact
887```text
888p12-session-tree-fold/
889 Cargo.toml (serde, ciborium — §6.6 length-prefixed format)
890 src/main.rs
891```
893### Verify
895```bash
896cd prototypes/p12-session-tree-fold
897cargo run -- tree
898cargo run -- leaf-persist
899cargo run -- fold
900cargo run -- branch-past-compaction
901cargo run -- all
902```
904### Pass evidence
906- append/switch/read-path behave per §6.5 including implicit fork points,
907- write file, truncate/corrupt tail, reload: effective leaf matches the
908 §6.5 rule under §6.6 recovery,
909- folded path collapses covered spans + trim stubs; raw entries untouched,
910- pre-compaction leaf switch sees full history; post-compaction branch
911 inherits the mask,
912- edge findings reported: span×fork crossings, nested summaries, leaf-switch
913 entries inside covered spans.
915### SPEC impact
917Tighten §6.9 with whatever edge rules the fold needs (e.g. spans may not
918cross fork points; summaries may nest or may not).
920## P13 — `p13-secret-proxy-mechanics`
922### SPEC claims
924- §6.7: plaintext exists only in secret-registration entries; ingestion
925 masks all other content; ingestion scan runs AFTER plugin
926 input/tool_result hooks (a hook-registered value is masked in the very
927 content that surfaced it); rehydration only at tool execution; resume
928 rebuilds the table by backward scan; unknown placeholder ids pass through.
930### Risk
932The hook-then-scan ordering may be racy or ambiguous when a hook both
933transforms content and registers a secret found in the pre-transform text.
934Exact-substring masking may corrupt content when one secret is a substring
935of another or of a placeholder.
937### Minimal artifact
939```text
940p13-secret-proxy-mechanics/
941 Cargo.toml (mlua luajit vendored, serde, ciborium)
942 plugins/detector.lua (input/tool_result hook registering found values)
943 src/main.rs
944```
946### Verify
948```bash
949cd prototypes/p13-secret-proxy-mechanics
950cargo run -- ingest
951cargo run -- hook-order
952cargo run -- rehydrate
953cargo run -- resume
954cargo run -- all
955```
957### Pass evidence
959- registered values masked at ingestion; registration entry holds plaintext;
960 every other entry stores placeholders,
961- Lua detector hook registers a value from content; the same content lands
962 masked,
963- tool execution receives rehydrated args; provider-request view stays
964 masked; unknown ids untouched,
965- reload from file rebuilds table; masking works immediately,
966- findings on overlapping-secret and secret-inside-placeholder edge cases.
968### SPEC impact
970Define masking order for overlapping secrets (e.g. longest-match-first) and
971any hook/transform ordering rule §6.7 needs beyond "scan after hooks".
973## P14 — `p14-steering-queue`
975### SPEC claims
977- §6.1: steers deliver at the next safe boundary (stream end / current tool
978 completion); pending tool calls resolve as synthetic error results
979 (`skipped: user steered`); queued steers drain FIFO before the next
980 provider call; follow-ups dequeue instead of `agent_end`; entries recorded
981 on delivery only; abort leaves the remainder queued.
983### Risk
985Boundary delivery may interleave badly with parallel tool execution
986(§5.3 ToolExecutionMode) — "currently executing tool finishes" is ambiguous
987when three run concurrently. Synthetic results for skipped calls may need
988exact ordering relative to real results.
990### Minimal artifact
992```text
993p14-steering-queue/
994 Cargo.toml (serde_json only; extends the p07 loop pattern)
995 src/main.rs
996```
998### Verify
1000```bash
1001cd prototypes/p14-steering-queue
1002cargo run -- steer-mid-stream
1003cargo run -- steer-mid-tools
1004cargo run -- steer-parallel-tools
1005cargo run -- followup
1006cargo run -- abort-keeps-queue
1007cargo run -- all
1008```
1010### Pass evidence
1012- deterministic AgentEvent sequences for each scenario (p07 style),
1013- steer during tool batch: running tool completes, remaining calls resolve
1014 skipped-with-error, steer message precedes next provider request,
1015- parallel mode: boundary semantics reported (all in-flight finish vs first
1016 finish),
1017- follow-up consumed instead of agent_end; FIFO order held,
1018- abort ends run, queue contents intact and reported,
1019- session-entry recording happens at delivery time only.
1021### SPEC impact
1023Pin the parallel-execution boundary rule in §6.1 and the ordering of
1024synthetic skipped results relative to completed results.
1026## Campaign 2 Results
1028Run 2026-07-16, rustc 1.94.1, x86_64-unknown-linux-gnu. All three complete;
1029findings folded into SPEC (§6.1, §6.5, §6.7, §6.9).
1031### P12 result
1033```json
1035 "status": "complete",
1036 "proved": [
1037 "tree ops per §6.5 incl. implicit fork points; leaf-switch persistence under §6.6 recovery",
1038 "fold: span collapse at path position, trim stubs, byte-identical storage through every fold/switch/compaction",
1039 "branch-past-compaction: pre-compaction switch sees full history, re-compacts as SIBLING summary; post-compaction branches inherit the mask",
1040 "edges: cross-fork spans detectable + safely ignored; nested summaries inevitable, outermost-wins; leaf-switch inside covered span folds away (leaf replay reads raw storage)"
1041 ],
1042 "disproved": [
1043 "§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)"
1044 ],
1045 "specIssues": [
1046 { "file": "../docs/SPEC.md", "issue": "leaf-load rule false as written", "evidence": "leaf-persist: literal=Some(2) vs replay=Some(6)", "severity": "P1" },
1047 { "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" },
1048 { "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" }
1049 ],
1050 "commands": ["cargo run -- tree|leaf-persist|fold|branch-past-compaction|all"],
1051 "nextSteps": ["all folded into §6.5/§6.9 (2026-07-16)"]
1053```
1055### P13 result
1057```json
1059 "status": "complete",
1060 "proved": [
1061 "plaintext bytes exist exactly once in the file (registration entry) — byte-scan verified",
1062 "hook-then-scan ordering: Lua detector registering during a hook masks the surfacing content",
1063 "rehydration is a view at tool execution only (Rust + Lua); provider view masked; unknown ids pass through",
1064 "resume rebuilds table with original ids; allocator resumes past max id",
1065 "longest-match-first single-pass masking correct; naive order provably leaks overlap residue"
1066 ],
1067 "disproved": [],
1068 "specIssues": [
1069 { "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" },
1070 { "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" },
1071 { "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" }
1072 ],
1073 "commands": ["cargo run -- ingest|hook-order|rehydrate|resume|all"],
1074 "nextSteps": ["all folded into §6.7 (2026-07-16)"]
1076```
1078### P14 result
1080```json
1082 "status": "complete",
1083 "proved": [
1084 "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",
1085 "parallel mode: wait-for-all-in-flight workable — no new call starts after a steer queues, started calls complete, never-started skip",
1086 "transcript rule: reals first (completion order), synthetics in original call order, steers follow"
1087 ],
1088 "disproved": [],
1089 "specIssues": [
1090 { "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" },
1091 { "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" },
1092 { "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" }
1093 ],
1094 "commands": ["cargo run -- steer-mid-stream|steer-mid-tools|steer-parallel-tools|followup|abort-keeps-queue|all"],
1095 "nextSteps": ["all folded into §6.1 (2026-07-16); re-verify wait-for-all under real tokio timing when the loop lands"]
1097```
8581099## Reporting Template
8601101Each completed prototype updates this plan with a result block:

prototypes/p12-session-tree-fold/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 = "p12-session-tree-fold"
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.119"
114source = "registry+https://github.com/rust-lang/crates.io-index"
115checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
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/p12-session-tree-fold/Cargo.toml

Added
new file mode 100644

+9 / −0 text lines

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

prototypes/p12-session-tree-fold/src/main.rs

Added
new file mode 100644

+730 / −0 text lines

1//! p12-session-tree-fold
2//!
3//! Proves or disproves docs/SPEC.md §6.5 (session tree: implicit fork points,
4//! leaf-switch metadata entries, effective-leaf-on-load) and §6.9 (compaction
5//! as an assembly-time fold: span collapse, trim stubs, recency window,
6//! verbatim survivors), including their interaction across branches and the
7//! §6.6 recovery boundaries (p06 codec pattern).
8//!
9//! Edge hunting (the point of this prototype):
10//! (a) a summary whose covered span crosses a fork point,
11//! (b) nested summaries (a later summary covering an earlier one),
12//! (c) a leaf-switch entry inside a covered span.
13//!
14//! Verify:
15//! cargo run -- tree
16//! cargo run -- leaf-persist
17//! cargo run -- fold
18//! cargo run -- branch-past-compaction
19//! cargo run -- all
20//! Each exits 0 with PASS lines when expectations hold.
22use serde::{Deserialize, Serialize};
23use std::collections::{BTreeMap, BTreeSet};
25type EntryId = u64;
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28struct SessionEntry {
29 id: EntryId,
30 parent: Option<EntryId>,
31 kind: Kind,
32}
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35enum Kind {
36 User { text: String },
37 Assistant { text: String },
38 ToolCall { name: String },
39 ToolResult { output: String },
40 /// §6.5 tree navigation, recorded append-only.
41 LeafSwitch { target: EntryId },
42 /// §6.9 fold marker: collapses [from..to] on any path running through it.
43 CompactionSummary { from: EntryId, to: EntryId, summary: String },
44 /// §6.7: the one entry kind holding plaintext; survives folding verbatim.
45 SecretRegistration { label: String, plaintext: String },
46}
48fn tag(k: &Kind) -> &'static str {
49 match k {
50 Kind::User { .. } => "user",
51 Kind::Assistant { .. } => "asst",
52 Kind::ToolCall { .. } => "call",
53 Kind::ToolResult { .. } => "result",
54 Kind::LeafSwitch { .. } => "switch",
55 Kind::CompactionSummary { .. } => "summary",
56 Kind::SecretRegistration { .. } => "secret",
57 }
58}
60fn user(t: &str) -> Kind { Kind::User { text: t.into() } }
61fn asst(t: &str) -> Kind { Kind::Assistant { text: t.into() } }
62fn call(name: &str) -> Kind { Kind::ToolCall { name: name.into() } }
63fn result(out: &str) -> Kind { Kind::ToolResult { output: out.into() } }
65// ---------------------------------------------------------------- session
67#[derive(Default)]
68struct Session {
69 entries: Vec<SessionEntry>,
70 leaf: Option<EntryId>,
71 next_id: EntryId,
72}
74impl Session {
75 /// §6.5 append: child of the current leaf; leaf advances. Appending while
76 /// the leaf sits on a non-leaf entry IS the implicit fork — same code path,
77 /// no explicit branch operation exists.
78 fn append(&mut self, kind: Kind) -> EntryId {
79 self.next_id += 1;
80 let id = self.next_id;
81 self.entries.push(SessionEntry { id, parent: self.leaf, kind });
82 self.leaf = Some(id);
83 id
84 }
86 /// §6.5 switch leaf: recorded by appending a leaf-switch metadata entry
87 /// (child of the branch tip being left), then the leaf moves to the target.
88 fn switch_leaf(&mut self, target: EntryId) -> EntryId {
89 assert!(self.get(target).is_some(), "switch target must exist");
90 let sw = self.append(Kind::LeafSwitch { target });
91 self.leaf = Some(target);
92 sw
93 }
95 fn get(&self, id: EntryId) -> Option<&SessionEntry> {
96 self.entries.iter().find(|e| e.id == id)
97 }
99 fn children(&self, id: EntryId) -> Vec<EntryId> {
100 self.entries.iter().filter(|e| e.parent == Some(id)).map(|e| e.id).collect()
101 }
103 fn path_to(&self, id: EntryId) -> Vec<EntryId> {
104 let mut p = Vec::new();
105 let mut cur = Some(id);
106 while let Some(c) = cur {
107 p.push(c);
108 cur = self.get(c).expect("path entry exists").parent;
109 }
110 p.reverse();
111 p
112 }
114 /// §6.5 read path: root→leaf. Sibling branches are invisible.
115 fn path(&self) -> Vec<EntryId> {
116 self.leaf.map(|l| self.path_to(l)).unwrap_or_default()
117 }
119 /// Rebuild from loaded entries. Effective leaf by REPLAY in file order:
120 /// a normal entry moves the leaf to itself (it was an append), a
121 /// leaf-switch moves it to its target. Net effect: the last surviving
122 /// entry decides. This is NOT the literal §6.5 wording — see
123 /// `spec_literal_leaf` and the leaf-persist scenario.
124 fn from_loaded(entries: Vec<SessionEntry>) -> (Self, Vec<String>) {
125 let mut diags = Vec::new();
126 let known: BTreeSet<EntryId> = entries.iter().map(|e| e.id).collect();
127 for e in &entries {
128 if let Some(p) = e.parent {
129 if !known.contains(&p) {
130 diags.push(format!("entry {} ORPHANED: parent {} missing (skipped/corrupt frame)", e.id, p));
131 }
132 }
133 }
134 let mut leaf = None;
135 for e in &entries {
136 match e.kind {
137 Kind::LeafSwitch { target } => {
138 if known.contains(&target) {
139 leaf = Some(target);
140 } else {
141 diags.push(format!(
142 "leaf-switch {} DANGLING: target {} missing; switch ignored on replay",
143 e.id, target
144 ));
145 }
146 }
147 _ => leaf = Some(e.id),
148 }
149 }
150 let next_id = entries.iter().map(|e| e.id).max().unwrap_or(0);
151 (Session { entries, leaf, next_id }, diags)
152 }
153}
155/// The LITERAL §6.5 load rule: "the last leaf-switch entry's target, or the
156/// last appended entry if none exists". Wrong whenever appends follow the
157/// last switch — kept here to demonstrate the wording defect.
158fn spec_literal_leaf(entries: &[SessionEntry]) -> Option<EntryId> {
159 entries
160 .iter()
161 .rev()
162 .find_map(|e| if let Kind::LeafSwitch { target } = e.kind { Some(target) } else { None })
163 .or_else(|| entries.last().map(|e| e.id))
164}
166// ------------------------------------------------------------------ codec
167// §6.6 length-prefixed CBOR (p06 pattern): u32 BE len | CBOR entry bytes | ...
169fn cbor(e: &SessionEntry) -> Vec<u8> {
170 let mut b = Vec::new();
171 ciborium::ser::into_writer(e, &mut b).expect("encode");
172 b
173}
175fn append_raw(out: &mut Vec<u8>, raw: &[u8]) {
176 out.extend_from_slice(&(raw.len() as u32).to_be_bytes());
177 out.extend_from_slice(raw);
178}
180fn encode(entries: &[SessionEntry]) -> Vec<u8> {
181 let mut out = Vec::new();
182 for e in entries {
183 append_raw(&mut out, &cbor(e));
184 }
185 out
186}
188#[derive(Debug, PartialEq)]
189enum Warn {
190 CorruptEntrySkipped { frame: usize },
191 TruncatedTail { at_frame: usize },
192}
194/// Recovering reader (p06-proven boundaries): truncated tail stops parsing,
195/// a corrupt BODY under an intact prefix is skipped precisely with a warning.
196fn load_recovering(bytes: &[u8]) -> (Vec<SessionEntry>, Vec<Warn>) {
197 let mut entries = Vec::new();
198 let mut warns = Vec::new();
199 let mut pos = 0usize;
200 let mut frame = 0usize;
201 while pos < bytes.len() {
202 if bytes.len() - pos < 4 {
203 warns.push(Warn::TruncatedTail { at_frame: frame });
204 break;
205 }
206 let len = u32::from_be_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize;
207 let body_start = pos + 4;
208 if len > bytes.len() - body_start {
209 warns.push(Warn::TruncatedTail { at_frame: frame });
210 break;
211 }
212 let body = &bytes[body_start..body_start + len];
213 // Two-stage decode per §6.6; unknown-variant preservation is p06's
214 // subject, so typed-decode failure counts as corrupt here.
215 match ciborium::de::from_reader::<ciborium::Value, _>(body)
216 .ok()
217 .and_then(|v| v.deserialized::<SessionEntry>().ok())
218 {
219 Some(e) => entries.push(e),
220 None => warns.push(Warn::CorruptEntrySkipped { frame }),
221 }
222 pos = body_start + len;
223 frame += 1;
224 }
225 (entries, warns)
226}
228// ------------------------------------------------------------------- fold
229// §6.9: compaction is a mask applied at context-assembly time. Storage never
230// changes; the fold walks the read path and collapses covered spans.
232#[derive(Debug)]
233enum FoldItem<'a> {
234 /// On the path, shown to the model as-is.
235 Verbatim(&'a SessionEntry),
236 /// Verbatim survivor pulled out of a collapsed span (secret registration).
237 Hoisted(&'a SessionEntry),
238 /// A covered span rendered as its summary, at the span's path position.
239 Summary { id: EntryId, from: EntryId, to: EntryId, text: &'a str },
240 /// Trim ladder step 1: old tool-result body outside the recency window.
241 Stub { id: EntryId, elided_bytes: usize },
242}
244/// Fold a root→leaf path. `recency` = number of most-recent folded items that
245/// survive verbatim (stand-in for §6.9's token-budget recency window).
246fn fold_path<'a>(
247 s: &'a Session,
248 path: &[EntryId],
249 recency: usize,
250) -> (Vec<FoldItem<'a>>, Vec<String>) {
251 let pos: BTreeMap<EntryId, usize> = path.iter().enumerate().map(|(i, &e)| (e, i)).collect();
252 let n = path.len();
253 // cover[i] = path index of the summary entry that swallows path[i].
254 // Later summaries overwrite earlier ones → on nesting, outermost wins.
255 let mut cover: Vec<Option<usize>> = vec![None; n];
256 let mut applied: BTreeSet<usize> = BTreeSet::new();
257 let mut dropped: BTreeSet<usize> = BTreeSet::new();
258 let mut diags = Vec::new();
260 for (pi, &eid) in path.iter().enumerate() {
261 let entry = s.get(eid).expect("path entry exists");
262 if let Kind::CompactionSummary { from, to, .. } = entry.kind {
263 match (pos.get(&from), pos.get(&to)) {
264 (Some(&fi), Some(&ti)) if fi <= ti && ti < pi => {
265 for c in &mut cover[fi..=ti] {
266 *c = Some(pi);
267 }
268 applied.insert(pi);
269 }
270 (Some(_), Some(_)) => {
271 diags.push(format!(
272 "summary {eid} IGNORED: span [{from}..{to}] is not an ancestor segment preceding it on the path"
273 ));
274 dropped.insert(pi);
275 }
276 _ => {
277 diags.push(format!(
278 "summary {eid} IGNORED: span [{from}..{to}] endpoint(s) not on this path — span crosses a fork point; history shown raw"
279 ));
280 dropped.insert(pi);
281 }
282 }
283 }
284 }
285 for &pi in &applied {
286 if let Some(outer) = cover[pi] {
287 diags.push(format!(
288 "summary {} SUBSUMED by later summary {} (nested spans; outermost wins)",
289 path[pi], path[outer]
290 ));
291 }
292 }
294 let mut out: Vec<FoldItem> = Vec::new();
295 let mut emitted: BTreeSet<usize> = BTreeSet::new();
296 for i in 0..n {
297 if let Some(spos) = cover[i] {
298 if emitted.insert(spos) {
299 // §6.9 "survives verbatim, always": hoist secret registrations
300 // out of the whole covered region, ahead of the summary.
301 for j in i..n {
302 if cover[j] == Some(spos) {
303 let e = s.get(path[j]).expect("path entry exists");
304 if matches!(e.kind, Kind::SecretRegistration { .. }) {
305 out.push(FoldItem::Hoisted(e));
306 }
307 }
308 }
309 let se = s.get(path[spos]).expect("summary entry exists");
310 if let Kind::CompactionSummary { from, to, ref summary } = se.kind {
311 out.push(FoldItem::Summary { id: se.id, from, to, text: summary });
312 }
313 }
314 continue; // covered cell collapses into its summary
315 }
316 if applied.contains(&i) {
317 continue; // summary entry already rendered at its span's position
318 }
319 if dropped.contains(&i) {
320 continue; // inapplicable summary: dropped from context, diagnosed
321 }
322 out.push(FoldItem::Verbatim(s.get(path[i]).expect("path entry exists")));
323 }
325 // Trim ladder step 1: stub old tool-result bodies outside the recency
326 // window. Summaries, hoisted secrets, and the window survive untouched.
327 let cut = out.len().saturating_sub(recency);
328 for item in out.iter_mut().take(cut) {
329 let repl = if let FoldItem::Verbatim(e) = &*item {
330 if let Kind::ToolResult { output } = &e.kind { Some((e.id, output.len())) } else { None }
331 } else {
332 None
333 };
334 if let Some((id, bytes)) = repl {
335 diags.push(format!("tool-result {id} outside recency window: stubbed ({bytes} bytes elided)"));
336 *item = FoldItem::Stub { id, elided_bytes: bytes };
337 }
338 }
339 (out, diags)
340}
342fn sig(items: &[FoldItem]) -> Vec<String> {
343 items
344 .iter()
345 .map(|it| match it {
346 FoldItem::Verbatim(e) => format!("{}#{}", tag(&e.kind), e.id),
347 FoldItem::Hoisted(e) => format!("hoist-{}#{}", tag(&e.kind), e.id),
348 FoldItem::Summary { id, from, to, .. } => format!("summary#{id}[{from}..{to}]"),
349 FoldItem::Stub { id, elided_bytes } => format!("stub#{id}({elided_bytes}B)"),
350 })
351 .collect()
352}
354fn show(label: &str, items: &[FoldItem], diags: &[String]) {
355 println!(" {label}: {}", sig(items).join(" | "));
356 for it in items {
357 if let FoldItem::Summary { id, text, .. } = it {
358 println!(" summary#{id} text: \"{text}\"");
359 }
360 }
361 for d in diags {
362 println!(" diag: {d}");
363 }
364}
366// -------------------------------------------------------------- scenarios
368struct Checker {
369 pass: bool,
370}
372impl Checker {
373 fn check(&mut self, label: &str, ok: bool) {
374 println!("{} {label}", if ok { "PASS" } else { "FAIL" });
375 self.pass &= ok;
376 }
377}
379fn scenario_tree(c: &mut Checker) {
380 println!("== tree: §6.5 append / implicit fork / switch-leaf / read-path ==");
381 let mut s = Session::default();
382 let e1 = s.append(user("A"));
383 let e2 = s.append(asst("B"));
384 let e3 = s.append(user("C"));
385 c.check(
386 "append advances leaf; read path = root→leaf",
387 s.leaf == Some(e3) && s.path() == vec![e1, e2, e3],
388 );
390 let s1 = s.switch_leaf(e2);
391 let sw = s.get(s1).unwrap().clone();
392 c.check(
393 "switch-leaf appends a leaf-switch metadata entry (append-only) and moves the leaf",
394 s.entries.len() == 4
395 && sw.parent == Some(e3)
396 && matches!(sw.kind, Kind::LeafSwitch { target } if target == e2)
397 && s.leaf == Some(e2),
398 );
400 let e4 = s.append(user("C'"));
401 c.check(
402 "append at non-leaf entry forks implicitly: e2 gains a second child, no explicit branch op",
403 s.get(e4).unwrap().parent == Some(e2) && s.children(e2) == vec![e3, e4],
404 );
405 c.check(
406 "read path follows the new branch; sibling branch (incl. its leaf-switch entry) invisible",
407 s.path() == vec![e1, e2, e4],
408 );
409 c.check(
410 "history immutable: all 5 entries retained append-only, ids monotone",
411 s.entries.len() == 5 && s.entries.windows(2).all(|w| w[0].id < w[1].id),
412 );
413 println!();
414}
416fn scenario_leaf_persist(c: &mut Checker) {
417 println!("== leaf-persist: §6.5 effective leaf on load × §6.6 recovery ==");
418 // Case A: appends AFTER the last leaf-switch.
419 let mut s = Session::default();
420 let _e1 = s.append(user("A"));
421 let e2 = s.append(asst("B"));
422 let _e3 = s.append(user("C"));
423 let _s1 = s.switch_leaf(e2);
424 let _e4 = s.append(asst("B' (regenerated)"));
425 let e5 = s.append(user("ok"));
427 let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/target");
428 std::fs::create_dir_all(dir).expect("mkdir target");
429 let file = format!("{dir}/p12-leaf.session");
430 let bytes = encode(&s.entries);
431 std::fs::write(&file, &bytes).expect("write session file");
432 let rb = std::fs::read(&file).expect("read session file");
434 let (loaded, warns) = load_recovering(&rb);
435 let (ls, diags) = Session::from_loaded(loaded);
436 c.check(
437 "persist + reload roundtrip: 6 entries, no warnings, no diagnostics",
438 ls.entries.len() == 6 && warns.is_empty() && diags.is_empty(),
439 );
440 c.check(
441 "effective leaf on load = last append AFTER the switch (replay rule: last entry decides)",
442 ls.leaf == Some(e5),
443 );
444 let literal = spec_literal_leaf(&ls.entries);
445 c.check(
446 "DEFECT §6.5: literal wording 'last leaf-switch entry's target' yields the WRONG leaf (e2, not e5) once appends follow a switch",
447 literal == Some(e2) && literal != ls.leaf,
448 );
449 println!(
450 " note: literal-rule leaf = {:?}, replay-rule leaf = {:?} — §6.5 must say 'replay appends and switches in file order' (equivalently: the last surviving entry decides).",
451 literal, ls.leaf
452 );
454 // Case B: file ENDS in a leaf-switch — both rules agree.
455 let mut t = Session::default();
456 let _f1 = t.append(user("A"));
457 let f2 = t.append(asst("B"));
458 let f3 = t.append(user("C"));
459 let _sw = t.switch_leaf(f2);
460 let tbytes = encode(&t.entries);
461 let (tl, twarns) = load_recovering(&tbytes);
462 let (ts, _) = Session::from_loaded(tl);
463 c.check(
464 "file ending in a leaf-switch: effective leaf = switch target",
465 twarns.is_empty() && ts.leaf == Some(f2) && spec_literal_leaf(&ts.entries) == Some(f2),
466 );
468 // Case C: tail truncated MID-FRAME (crash during the switch's write).
469 let cutbytes = &tbytes[..tbytes.len() - 3];
470 let (cl, cwarns) = load_recovering(cutbytes);
471 let (cs, cdiags) = Session::from_loaded(cl);
472 c.check(
473 "tail truncated mid-frame (§6.6): switch entry lost, prior entries survive, leaf falls back to last surviving append",
474 cs.entries.len() == 3
475 && matches!(cwarns[..], [Warn::TruncatedTail { at_frame: 3 }])
476 && cdiags.is_empty()
477 && cs.leaf == Some(f3),
478 );
480 // Case D: corrupt BODY of an entry that is both a parent and a switch
481 // target (§6.6 precise skip × §6.5 tree integrity).
482 let frames: Vec<Vec<u8>> = t.entries.iter().map(cbor).collect();
483 let mut cb = Vec::new();
484 for (i, f) in frames.iter().enumerate() {
485 if i == 1 {
486 append_raw(&mut cb, &vec![0xFF; f.len()]); // garbage, not valid CBOR
487 } else {
488 append_raw(&mut cb, f);
489 }
490 }
491 let (dl, dwarns) = load_recovering(&cb);
492 let (ds, ddiags) = Session::from_loaded(dl);
493 c.check(
494 "corrupt BODY of a switch target (§6.6 skip): orphaned child + dangling switch detected; replay leaf falls back to last intact append",
495 ds.entries.len() == 3
496 && matches!(dwarns[..], [Warn::CorruptEntrySkipped { frame: 1 }])
497 && ddiags.len() == 2
498 && ds.leaf == Some(f3),
499 );
500 for d in &ddiags {
501 println!(" diag: {d}");
502 }
503 println!(" note: §6.6's precise corrupt-entry skip breaks §6.5 tree integrity — SPEC defines no rule for orphaned children or dangling leaf-switch targets.");
504 println!();
505}
507fn scenario_fold(c: &mut Checker) {
508 println!("== fold: §6.9 assembly-time fold — span collapse, verbatim survivors, trim stubs ==");
509 let mut s = Session::default();
510 let e1 = s.append(user("investigate the flaky test"));
511 let e2 = s.append(Kind::SecretRegistration { label: "github-token".into(), plaintext: "ghp_XYZ".into() });
512 let _e3 = s.append(asst("reading the test file"));
513 let _e4 = s.append(call("read"));
514 let e5 = s.append(result(&"x".repeat(2000)));
515 let e6 = s.append(asst("found a race in setup"));
516 let e7 = s.append(user("fix it"));
517 let sum1 = s.append(Kind::CompactionSummary {
518 from: e1,
519 to: e5,
520 summary: "user asked to investigate a flaky test; test file read; race found in setup".into(),
521 });
522 let e8 = s.append(call("edit"));
523 let e9 = s.append(result(&"y".repeat(500)));
524 let e10 = s.append(asst("patched"));
525 let e11 = s.append(user("run the tests"));
527 let raw_before = encode(&s.entries);
528 let (folded, diags) = fold_path(&s, &s.path(), 2);
529 let raw_after = encode(&s.entries);
530 show("folded", &folded, &diags);
532 c.check(
533 "storage untouched by fold: session bytes identical, all 12 entries verbatim on disk",
534 raw_before == raw_after && s.entries.len() == 12,
535 );
536 let expected = vec![
537 format!("hoist-secret#{e2}"),
538 format!("summary#{sum1}[{e1}..{e5}]"),
539 format!("asst#{e6}"),
540 format!("user#{e7}"),
541 format!("call#{e8}"),
542 format!("stub#{e9}(500B)"),
543 format!("asst#{e10}"),
544 format!("user#{e11}"),
545 ];
546 c.check(
547 "covered span [e1..e5] collapses into the summary at the span's path position; summary entry not duplicated at path end",
548 sig(&folded) == expected,
549 );
550 c.check(
551 "secret registration inside the covered span survives verbatim (hoisted ahead of the summary, plaintext+label intact)",
552 matches!(&folded[0], FoldItem::Hoisted(e)
553 if matches!(&e.kind, Kind::SecretRegistration { label, plaintext }
554 if label == "github-token" && plaintext == "ghp_XYZ")),
555 );
556 c.check(
557 "old tool-result outside the recency window stubbed; window (last 2) verbatim; 2000B result inside the span swallowed by it, not stubbed",
558 matches!(folded[5], FoldItem::Stub { id, elided_bytes: 500 } if id == e9)
559 && !sig(&folded).iter().any(|t| t == &format!("result#{e5}") || t == &format!("stub#{e5}(2000B)")),
560 );
561 println!(" note: §6.9 'secret registrations survive verbatim' is a §6.7 CONTRADICTION if the folded path is provider-visible as-is: the registration entry holds plaintext. Provider rendering must mask/exclude it; the fold preserves it structurally.");
563 // Edge (c): a leaf-switch entry INSIDE a covered span.
564 println!("-- edge (c): leaf-switch entry inside a covered span --");
565 let mut t = Session::default();
566 let g1 = t.append(user("start"));
567 let g2 = t.append(asst("step 1"));
568 let g3 = t.append(user("go on"));
569 let _g4 = t.append(asst("step 2"));
570 let _g5 = t.append(user("hmm"));
571 let sw1 = t.switch_leaf(g3); // child of g5, leaf → g3
572 let _sw2 = t.switch_leaf(sw1); // child of g3, leaf → sw1: a switch entry becomes path material
573 let g6 = t.append(asst("continuing from the navigation point"));
574 let tsum = t.append(Kind::CompactionSummary { from: g2, to: sw1, summary: "steps 1-2 done, user navigated".into() });
575 let (tf, tdiags) = fold_path(&t, &t.path(), 10);
576 show("folded", &tf, &tdiags);
577 c.check(
578 "edge (c): leaf-switch entry inside the covered span folds away like content (no special case, no residue)",
579 sig(&tf) == vec![format!("user#{g1}"), format!("summary#{tsum}[{g2}..{sw1}]"), format!("asst#{g6}")],
580 );
581 let (tl, _) = Session::from_loaded(load_recovering(&encode(&t.entries)).0);
582 c.check(
583 "edge (c): leaf replay reads RAW storage, never the folded path — swallowing the switch is harmless to leaf resolution",
584 tl.leaf == Some(tsum),
585 );
586 println!(" note: RULE for §6.9 — leaf-switch (and other metadata) entries inside a covered span are foldable; §6.5 leaf resolution operates on raw entries only.");
588 // Edge (a): a summary whose span crosses a fork point.
589 println!("-- edge (a): covered span crossing a fork point --");
590 let mut u = Session::default();
591 let h1 = u.append(user("root"));
592 let h2 = u.append(asst("branch A work"));
593 let _h3 = u.append(user("more branch A"));
594 let _usw = u.switch_leaf(h1);
595 let h4 = u.append(asst("branch B work")); // implicit fork at h1
596 let bad = u.append(Kind::CompactionSummary { from: h2, to: h4, summary: "bogus cross-fork span".into() });
597 let (uf, udiags) = fold_path(&u, &u.path(), 10);
598 show("folded", &uf, &udiags);
599 c.check(
600 "edge (a): span with an endpoint on a sibling branch is DETECTED and the summary ignored — raw history shown, diagnostic emitted",
601 sig(&uf) == vec![format!("user#{h1}"), format!("asst#{h4}")]
602 && udiags.iter().any(|d| d.contains(&format!("summary {bad} IGNORED")) && d.contains("fork")),
603 );
604 println!(" note: RULE for §6.9 — a covered span MUST be a contiguous ancestor segment of the appending path (from ancestor-of to, to ancestor-of the summary entry). Well-formed compaction cannot create a cross-fork span (a summary's ancestors always include its span), so violations are file damage: fold must ignore the summary with a diagnostic, never guess.");
605 println!();
606}
608fn scenario_branch_past_compaction(c: &mut Checker) {
609 println!("== branch-past-compaction: §6.5 × §6.9 — masks ride the path ==");
610 let mut s = Session::default();
611 let e1 = s.append(user("goal: refactor the parser"));
612 let e2 = s.append(asst("looking at the grammar"));
613 let e3 = s.append(call("read"));
614 let e4 = s.append(result(&"g".repeat(800)));
615 let _e5 = s.append(asst("grammar is LL(1)"));
616 let e6 = s.append(user("proceed"));
617 let e7 = s.append(asst("refactoring"));
618 let e8 = s.append(user("status?"));
619 let sum1 = s.append(Kind::CompactionSummary {
620 from: e1,
621 to: e6,
622 summary: "user wants parser refactor; grammar read, it is LL(1); user said proceed".into(),
623 });
624 let e9 = s.append(asst("halfway done"));
625 let raw_before = encode(&s.entries);
627 let (f1, d1) = fold_path(&s, &s.path(), 10);
628 show("compaction branch", &f1, &d1);
629 c.check(
630 "fold on the compaction branch masks the covered span",
631 sig(&f1) == vec![
632 format!("summary#{sum1}[{e1}..{e6}]"),
633 format!("asst#{e7}"),
634 format!("user#{e8}"),
635 format!("asst#{e9}"),
636 ],
637 );
639 // Switch the leaf to a PRE-compaction entry (inside the covered span).
640 let _sw1 = s.switch_leaf(e4);
641 let (f2, d2) = fold_path(&s, &s.path(), 10);
642 show("pre-compaction leaf", &f2, &d2);
643 c.check(
644 "leaf switched to a pre-compaction entry: folded path is FULL history — no summary on the path, nothing masked",
645 sig(&f2) == vec![
646 format!("user#{e1}"),
647 format!("asst#{e2}"),
648 format!("call#{e3}"),
649 format!("result#{e4}"),
650 ] && d2.is_empty(),
651 );
653 // Branch there and RE-compact: produces a sibling summary, not a nested one.
654 let e10 = s.append(asst("alternate approach: recursive descent"));
655 let sum2 = s.append(Kind::CompactionSummary {
656 from: e1,
657 to: e4,
658 summary: "parser refactor goal; grammar read".into(),
659 });
660 let (f3, d3) = fold_path(&s, &s.path(), 10);
661 show("re-compacted pre-branch", &f3, &d3);
662 c.check(
663 "pre-compaction branch is independently re-compactable: new summary lives on the new branch (SIBLING, not nested)",
664 sig(&f3) == vec![format!("summary#{sum2}[{e1}..{e4}]"), format!("asst#{e10}")],
665 );
667 // Branch created AFTER the compaction point inherits the mask.
668 let _sw2 = s.switch_leaf(e9);
669 let e11 = s.append(user("new question on the compacted branch")); // implicit fork at e9
670 let (f4, d4) = fold_path(&s, &s.path(), 10);
671 show("post-compaction branch", &f4, &d4);
672 c.check(
673 "branch created after the compaction point inherits the mask (summary rides the shared path prefix)",
674 sig(&f4) == vec![
675 format!("summary#{sum1}[{e1}..{e6}]"),
676 format!("asst#{e7}"),
677 format!("user#{e8}"),
678 format!("asst#{e9}"),
679 format!("user#{e11}"),
680 ],
681 );
683 // Edge (b): NESTED summaries — re-compaction on the SAME branch must cover
684 // the earlier summary entry (it sits inside any older span).
685 println!("-- edge (b): nested summaries (re-compaction on the same branch) --");
686 let sum3 = s.append(Kind::CompactionSummary {
687 from: e1,
688 to: e9,
689 summary: "parser refactor: grammar analyzed, refactor halfway done".into(),
690 });
691 let (f5, d5) = fold_path(&s, &s.path(), 10);
692 show("nested fold", &f5, &d5);
693 c.check(
694 "edge (b): later summary covering the earlier summary folds OUTERMOST-WINS; inner summary subsumed with diagnostic",
695 sig(&f5) == vec![format!("summary#{sum3}[{e1}..{e9}]"), format!("user#{e11}")]
696 && d5.iter().any(|d| d.contains(&format!("summary {sum1} SUBSUMED by later summary {sum3}"))),
697 );
698 println!(" note: RULE for §6.9 — summaries DO nest: re-compaction on an already-compacted path always covers the prior summary entry. Fold rule: outermost (latest) span wins; 'existing compaction summary entries survive verbatim' can only mean they survive the TRIM LADDER (they are summarizer input), not that they escape a later covering span at fold time. Re-compaction after a pre-compaction leaf-switch instead yields a SIBLING summary on the new branch (no nesting).");
700 let raw_now = encode(&s.entries);
701 c.check(
702 "storage grew append-only through every fold/switch/compaction: original bytes are a strict prefix of the file",
703 raw_now.len() > raw_before.len() && raw_now[..raw_before.len()] == raw_before[..],
704 );
705 println!();
706}
708fn main() -> Result<(), Box<dyn std::error::Error>> {
709 let arg = std::env::args().nth(1).unwrap_or_else(|| "all".into());
710 let mut c = Checker { pass: true };
711 match arg.as_str() {
712 "tree" => scenario_tree(&mut c),
713 "leaf-persist" => scenario_leaf_persist(&mut c),
714 "fold" => scenario_fold(&mut c),
715 "branch-past-compaction" => scenario_branch_past_compaction(&mut c),
716 "all" => {
717 scenario_tree(&mut c);
718 scenario_leaf_persist(&mut c);
719 scenario_fold(&mut c);
720 scenario_branch_past_compaction(&mut c);
721 }
722 other => return Err(format!("unknown scenario: {other} (use tree|leaf-persist|fold|branch-past-compaction|all)").into()),
723 }
724 if c.pass {
725 println!("p12 RESULT: all expectations hold");
726 Ok(())
727 } else {
728 Err("p12 RESULT: expectation failed".into())
729 }
730}

prototypes/p13-secret-proxy-mechanics/Cargo.lock

Added
new file mode 100644

+443 / −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.1"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
17[[package]]
18name = "bstr"
19version = "1.13.0"
20source = "registry+https://github.com/rust-lang/crates.io-index"
21checksum = "1f7dc094d718f2e1c1559ad110e27eeaae14a5465d3d56dd6dbd793079fbd530"
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 = "ciborium"
45version = "0.2.2"
46source = "registry+https://github.com/rust-lang/crates.io-index"
47checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
48dependencies = [
49 "ciborium-io",
50 "ciborium-ll",
51 "serde",
52]
54[[package]]
55name = "ciborium-io"
56version = "0.2.2"
57source = "registry+https://github.com/rust-lang/crates.io-index"
58checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
60[[package]]
61name = "ciborium-ll"
62version = "0.2.2"
63source = "registry+https://github.com/rust-lang/crates.io-index"
64checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
65dependencies = [
66 "ciborium-io",
67 "half",
68]
70[[package]]
71name = "crunchy"
72version = "0.2.4"
73source = "registry+https://github.com/rust-lang/crates.io-index"
74checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
76[[package]]
77name = "either"
78version = "1.16.0"
79source = "registry+https://github.com/rust-lang/crates.io-index"
80checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
82[[package]]
83name = "env_home"
84version = "0.1.0"
85source = "registry+https://github.com/rust-lang/crates.io-index"
86checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
88[[package]]
89name = "erased-serde"
90version = "0.4.10"
91source = "registry+https://github.com/rust-lang/crates.io-index"
92checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
93dependencies = [
94 "serde",
95 "serde_core",
96 "typeid",
97]
99[[package]]
100name = "errno"
101version = "0.3.14"
102source = "registry+https://github.com/rust-lang/crates.io-index"
103checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
104dependencies = [
105 "libc",
106 "windows-sys",
107]
109[[package]]
110name = "find-msvc-tools"
111version = "0.1.9"
112source = "registry+https://github.com/rust-lang/crates.io-index"
113checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
115[[package]]
116name = "half"
117version = "2.7.1"
118source = "registry+https://github.com/rust-lang/crates.io-index"
119checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
120dependencies = [
121 "cfg-if",
122 "crunchy",
123 "zerocopy",
124]
126[[package]]
127name = "libc"
128version = "0.2.186"
129source = "registry+https://github.com/rust-lang/crates.io-index"
130checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
132[[package]]
133name = "linux-raw-sys"
134version = "0.12.1"
135source = "registry+https://github.com/rust-lang/crates.io-index"
136checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
138[[package]]
139name = "lock_api"
140version = "0.4.14"
141source = "registry+https://github.com/rust-lang/crates.io-index"
142checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
143dependencies = [
144 "scopeguard",
145]
147[[package]]
148name = "lua-src"
149version = "547.0.0"
150source = "registry+https://github.com/rust-lang/crates.io-index"
151checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42"
152dependencies = [
153 "cc",
154]
156[[package]]
157name = "luajit-src"
158version = "210.5.12+a4f56a4"
159source = "registry+https://github.com/rust-lang/crates.io-index"
160checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671"
161dependencies = [
162 "cc",
163 "which",
164]
166[[package]]
167name = "memchr"
168version = "2.8.3"
169source = "registry+https://github.com/rust-lang/crates.io-index"
170checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
172[[package]]
173name = "mlua"
174version = "0.10.5"
175source = "registry+https://github.com/rust-lang/crates.io-index"
176checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0"
177dependencies = [
178 "bstr",
179 "either",
180 "erased-serde",
181 "mlua-sys",
182 "num-traits",
183 "parking_lot",
184 "rustc-hash",
185 "rustversion",
186 "serde",
187 "serde-value",
188]
190[[package]]
191name = "mlua-sys"
192version = "0.6.8"
193source = "registry+https://github.com/rust-lang/crates.io-index"
194checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93"
195dependencies = [
196 "cc",
197 "cfg-if",
198 "lua-src",
199 "luajit-src",
200 "pkg-config",
201]
203[[package]]
204name = "num-traits"
205version = "0.2.19"
206source = "registry+https://github.com/rust-lang/crates.io-index"
207checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
208dependencies = [
209 "autocfg",
210]
212[[package]]
213name = "ordered-float"
214version = "2.10.1"
215source = "registry+https://github.com/rust-lang/crates.io-index"
216checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
217dependencies = [
218 "num-traits",
219]
221[[package]]
222name = "p13-secret-proxy-mechanics"
223version = "0.1.0"
224dependencies = [
225 "ciborium",
226 "mlua",
227 "serde",
228]
230[[package]]
231name = "parking_lot"
232version = "0.12.5"
233source = "registry+https://github.com/rust-lang/crates.io-index"
234checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
235dependencies = [
236 "lock_api",
237 "parking_lot_core",
238]
240[[package]]
241name = "parking_lot_core"
242version = "0.9.12"
243source = "registry+https://github.com/rust-lang/crates.io-index"
244checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
245dependencies = [
246 "cfg-if",
247 "libc",
248 "redox_syscall",
249 "smallvec",
250 "windows-link",
251]
253[[package]]
254name = "pkg-config"
255version = "0.3.33"
256source = "registry+https://github.com/rust-lang/crates.io-index"
257checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
259[[package]]
260name = "proc-macro2"
261version = "1.0.106"
262source = "registry+https://github.com/rust-lang/crates.io-index"
263checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
264dependencies = [
265 "unicode-ident",
266]
268[[package]]
269name = "quote"
270version = "1.0.46"
271source = "registry+https://github.com/rust-lang/crates.io-index"
272checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
273dependencies = [
274 "proc-macro2",
275]
277[[package]]
278name = "redox_syscall"
279version = "0.5.18"
280source = "registry+https://github.com/rust-lang/crates.io-index"
281checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
282dependencies = [
283 "bitflags",
284]
286[[package]]
287name = "rustc-hash"
288version = "2.1.3"
289source = "registry+https://github.com/rust-lang/crates.io-index"
290checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
292[[package]]
293name = "rustix"
294version = "1.1.4"
295source = "registry+https://github.com/rust-lang/crates.io-index"
296checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
297dependencies = [
298 "bitflags",
299 "errno",
300 "libc",
301 "linux-raw-sys",
302 "windows-sys",
303]
305[[package]]
306name = "rustversion"
307version = "1.0.23"
308source = "registry+https://github.com/rust-lang/crates.io-index"
309checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
311[[package]]
312name = "scopeguard"
313version = "1.2.0"
314source = "registry+https://github.com/rust-lang/crates.io-index"
315checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
317[[package]]
318name = "serde"
319version = "1.0.228"
320source = "registry+https://github.com/rust-lang/crates.io-index"
321checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
322dependencies = [
323 "serde_core",
324 "serde_derive",
325]
327[[package]]
328name = "serde-value"
329version = "0.7.0"
330source = "registry+https://github.com/rust-lang/crates.io-index"
331checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
332dependencies = [
333 "ordered-float",
334 "serde",
335]
337[[package]]
338name = "serde_core"
339version = "1.0.228"
340source = "registry+https://github.com/rust-lang/crates.io-index"
341checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
342dependencies = [
343 "serde_derive",
344]
346[[package]]
347name = "serde_derive"
348version = "1.0.228"
349source = "registry+https://github.com/rust-lang/crates.io-index"
350checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
351dependencies = [
352 "proc-macro2",
353 "quote",
354 "syn",
355]
357[[package]]
358name = "shlex"
359version = "2.0.1"
360source = "registry+https://github.com/rust-lang/crates.io-index"
361checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
363[[package]]
364name = "smallvec"
365version = "1.15.2"
366source = "registry+https://github.com/rust-lang/crates.io-index"
367checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
369[[package]]
370name = "syn"
371version = "2.0.119"
372source = "registry+https://github.com/rust-lang/crates.io-index"
373checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
374dependencies = [
375 "proc-macro2",
376 "quote",
377 "unicode-ident",
378]
380[[package]]
381name = "typeid"
382version = "1.0.3"
383source = "registry+https://github.com/rust-lang/crates.io-index"
384checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
386[[package]]
387name = "unicode-ident"
388version = "1.0.24"
389source = "registry+https://github.com/rust-lang/crates.io-index"
390checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
392[[package]]
393name = "which"
394version = "7.0.3"
395source = "registry+https://github.com/rust-lang/crates.io-index"
396checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762"
397dependencies = [
398 "either",
399 "env_home",
400 "rustix",
401 "winsafe",
402]
404[[package]]
405name = "windows-link"
406version = "0.2.1"
407source = "registry+https://github.com/rust-lang/crates.io-index"
408checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
410[[package]]
411name = "windows-sys"
412version = "0.61.2"
413source = "registry+https://github.com/rust-lang/crates.io-index"
414checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
415dependencies = [
416 "windows-link",
417]
419[[package]]
420name = "winsafe"
421version = "0.0.19"
422source = "registry+https://github.com/rust-lang/crates.io-index"
423checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"
425[[package]]
426name = "zerocopy"
427version = "0.8.54"
428source = "registry+https://github.com/rust-lang/crates.io-index"
429checksum = "b7cbbc0a705a0fd05cc3676525980d2bf5a9bc4adac6d6475209a7887cf59d19"
430dependencies = [
431 "zerocopy-derive",
432]
434[[package]]
435name = "zerocopy-derive"
436version = "0.8.54"
437source = "registry+https://github.com/rust-lang/crates.io-index"
438checksum = "e2e817b7b52d0c7358d3246da9d69935ebb18116b2b102b4230dac079b4862f5"
439dependencies = [
440 "proc-macro2",
441 "quote",
442 "syn",
443]

prototypes/p13-secret-proxy-mechanics/Cargo.toml

Added
new file mode 100644

+10 / −0 text lines

1[package]
2name = "p13-secret-proxy-mechanics"
3version = "0.1.0"
4edition = "2021"
5publish = false
6
7[dependencies]
8mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }
9serde = { version = "1", features = ["derive"] }
10ciborium = "0.2"

prototypes/p13-secret-proxy-mechanics/plugins/detector.lua

Added
new file mode 100644

+41 / −0 text lines

1-- p13 detector plugin (SPEC §6.7 / §9.8).
2--
3-- Detection MECHANISM belongs to the plugin: this one pattern-matches
4-- `secret%-%w+` tokens in content and registers them through the host
5-- function smith.secret.register(value, label). Masking MECHANICS stay in
6-- Smith: the ingestion scan runs AFTER these hooks, so a value registered
7-- here must land masked in the very content that surfaced it.
8
9local M = {}
11local function detect(s)
12 for tok in s:gmatch("secret%-%w+") do
13 smith.secret.register(tok, "detected:" .. tok:sub(8))
14 end
15end
17-- §9.8 tool_result contract: { content = <replacement> } | { retry } |
18-- { cancel } | nil (keep). This one registers but keeps content untouched.
19function M.tool_result(ev)
20 detect(ev.content)
21 return nil
22end
24-- §9.8 input contract: { action = "handled"|"continue", text = <transformed>? }.
25-- This one registers AND transforms; the registered value survives the
26-- transform verbatim, so the post-hook scan still masks it.
27function M.input(ev)
28 detect(ev.text)
29 return { action = "continue", text = "[seen] " .. ev.text }
30end
32-- EDGE (c): registers from the PRE-transform text, then re-encodes the
33-- content (uppercase) so the registered value appears only in derived form
34-- post-transform. The exact-substring scan runs on post-transform content
35-- only and will miss it.
36function M.input_upper(ev)
37 detect(ev.text)
38 return { action = "continue", text = ev.text:upper() }
39end
41return M

prototypes/p13-secret-proxy-mechanics/src/main.rs

Added
new file mode 100644

+577 / −0 text lines

1//! p13-secret-proxy-mechanics
2//!
3//! Proves or disproves docs/SPEC.md §6.7 (Secret Proxy):
4//! - registry `SecretId → plaintext + label`; plaintext exists only in
5//! secret-registration session entries (§6.6 length-prefixed CBOR),
6//! - ingestion masks by exact substring match, AFTER plugin
7//! `input`/`tool_result` hooks (§9.8 return shapes) — a value registered
8//! DURING a hook is masked in the very content that surfaced it,
9//! - rehydration only immediately before tool execution (Rust and Lua alike);
10//! provider view keeps placeholders; unknown ids pass through untouched,
11//! - resume rebuilds the table by backward scan over session entries,
12//! - edge hunting: overlapping secrets (longest-match-first), a registered
13//! value that IS a placeholder string, hook transforms that hide the secret
14//! from the post-transform scan.
15//!
16//! Verify: `cargo run -- ingest|hook-order|rehydrate|resume|all`
17//! Each exits 0 with PASS lines when the expectations hold.
19use std::cell::RefCell;
20use std::error::Error;
21use std::io::Read as _;
22use std::rc::Rc;
24use mlua::{Function, Lua, Table, Value as LuaValue};
25use serde::{Deserialize, Serialize};
27const DETECTOR: &str = include_str!("../plugins/detector.lua");
29// ---------------------------------------------------------------- registry
31/// One registered secret: SecretId (numeric here; §5.1 SecretId(String) in
32/// the real system) → plaintext + label. Placeholder text is `smith:sec:N`.
33#[derive(Debug, Clone)]
34struct SecretEntry {
35 id: u64,
36 value: String,
37 label: String,
38}
40#[derive(Debug, Default)]
41struct Registry {
42 next_id: u64,
43 entries: Vec<SecretEntry>,
44}
46impl Registry {
47 fn new() -> Self {
48 Registry { next_id: 1, entries: Vec::new() }
49 }
51 /// Register a value; idempotent on identical plaintext (a detector hook
52 /// re-seeing the same token must not mint a new id). §6.7 is silent on
53 /// duplicate registration — this is the behavior we report.
54 fn register(&mut self, value: &str, label: &str) -> u64 {
55 if let Some(e) = self.entries.iter().find(|e| e.value == value) {
56 return e.id;
57 }
58 let id = self.next_id;
59 self.next_id += 1;
60 self.entries.push(SecretEntry { id, value: value.to_string(), label: label.to_string() });
61 id
62 }
64 fn by_id(&self, id: u64) -> Option<&SecretEntry> {
65 self.entries.iter().find(|e| e.id == id)
66 }
68 fn by_value(&self, value: &str) -> Option<&SecretEntry> {
69 self.entries.iter().find(|e| e.value == value)
70 }
71}
73fn placeholder(id: u64) -> String {
74 format!("smith:sec:{id}")
75}
77// ------------------------------------------------------------------ masking
79/// Ingestion scan: exact substring masking of ALL registered values.
80/// Rule under test: LONGEST-MATCH-FIRST at each position, single
81/// left-to-right pass. The pass never rescans emitted placeholder text, so
82/// masking output cannot cascade into further matches.
83fn mask(content: &str, reg: &Registry) -> String {
84 let mut by_len: Vec<&SecretEntry> =
85 reg.entries.iter().filter(|e| !e.value.is_empty()).collect();
86 by_len.sort_by(|a, b| b.value.len().cmp(&a.value.len()));
88 let mut out = String::new();
89 let mut i = 0;
90 while i < content.len() {
91 if let Some(e) = by_len.iter().find(|e| content[i..].starts_with(&e.value)) {
92 out.push_str(&placeholder(e.id));
93 i += e.value.len();
94 } else {
95 let ch = content[i..].chars().next().unwrap();
96 out.push(ch);
97 i += ch.len_utf8();
98 }
99 }
100 out
101}
103/// Deliberately WRONG masking used only to demonstrate the overlap hazard:
104/// sequential whole-string replace, shortest value first.
105fn naive_mask_shortest_first(content: &str, reg: &Registry) -> String {
106 let mut by_len: Vec<&SecretEntry> =
107 reg.entries.iter().filter(|e| !e.value.is_empty()).collect();
108 by_len.sort_by(|a, b| a.value.len().cmp(&b.value.len()));
109 let mut s = content.to_string();
110 for e in by_len {
111 s = s.replace(&e.value, &placeholder(e.id));
112 }
113 s
114}
116/// Rehydration: `smith:sec:` + maximal digit run → plaintext when the id is
117/// registered; an unknown id passes through UNTOUCHED (never an error).
118/// Single pass: rehydrated plaintext is never rescanned.
119fn rehydrate(content: &str, reg: &Registry) -> String {
120 const PREFIX: &str = "smith:sec:";
121 let mut out = String::new();
122 let mut rest = content;
123 while let Some(pos) = rest.find(PREFIX) {
124 out.push_str(&rest[..pos]);
125 let after = &rest[pos + PREFIX.len()..];
126 let digits_len = after.chars().take_while(|c| c.is_ascii_digit()).count();
127 if digits_len == 0 {
128 out.push_str(PREFIX);
129 rest = after;
130 continue;
131 }
132 let digits = &after[..digits_len];
133 match digits.parse::<u64>().ok().and_then(|id| reg.by_id(id)) {
134 Some(e) => out.push_str(&e.value),
135 None => {
136 out.push_str(PREFIX);
137 out.push_str(digits);
138 }
139 }
140 rest = &after[digits_len..];
141 }
142 out.push_str(rest);
143 out
144}
146// ------------------------------------------------------------ session codec
148/// Session entries, §6.6 framing: `u32 BE len | CBOR entry bytes | ...`.
149/// Plaintext is allowed in exactly one kind: `SecretRegistration`.
150#[derive(Debug, Serialize, Deserialize)]
151#[serde(tag = "kind")]
152enum SessionEntry {
153 SecretRegistration { id: u64, value: String, label: String },
154 UserMessage { text: String },
155 ToolCall { name: String, args_json: String },
156 ToolResult { content: String },
157}
159fn entry_text(e: &SessionEntry) -> &str {
160 match e {
161 SessionEntry::SecretRegistration { value, .. } => value,
162 SessionEntry::UserMessage { text } => text,
163 SessionEntry::ToolCall { args_json, .. } => args_json,
164 SessionEntry::ToolResult { content } => content,
165 }
166}
168fn write_session(path: &std::path::Path, entries: &[SessionEntry]) -> Result<(), Box<dyn Error>> {
169 let mut buf = Vec::new();
170 for e in entries {
171 let mut body = Vec::new();
172 ciborium::ser::into_writer(e, &mut body)?;
173 buf.extend_from_slice(&(body.len() as u32).to_be_bytes());
174 buf.extend_from_slice(&body);
175 }
176 std::fs::create_dir_all(path.parent().unwrap())?;
177 std::fs::write(path, buf)?;
178 Ok(())
179}
181fn read_session(path: &std::path::Path) -> Result<Vec<SessionEntry>, Box<dyn Error>> {
182 let bytes = std::fs::read(path)?;
183 let mut cur = &bytes[..];
184 let mut entries = Vec::new();
185 while !cur.is_empty() {
186 let mut len_buf = [0u8; 4];
187 cur.read_exact(&mut len_buf)?;
188 let len = u32::from_be_bytes(len_buf) as usize;
189 let (body, rest) = cur.split_at(len);
190 entries.push(ciborium::de::from_reader(body)?);
191 cur = rest;
192 }
193 Ok(entries)
194}
196/// Resume: rebuild the table by scanning entries BACKWARD for registration
197/// entries (most recent first; first occurrence of an id wins). The id
198/// allocator must resume past the max id seen, or a post-resume registration
199/// would mint a colliding id and silently alias old placeholders.
200fn rebuild_registry(entries: &[SessionEntry]) -> Registry {
201 let mut reg = Registry::new();
202 let mut max_id = 0;
203 for e in entries.iter().rev() {
204 if let SessionEntry::SecretRegistration { id, value, label } = e {
205 if reg.by_id(*id).is_none() {
206 reg.entries.push(SecretEntry { id: *id, value: value.clone(), label: label.clone() });
207 }
208 max_id = max_id.max(*id);
209 }
210 }
211 reg.next_id = max_id + 1;
212 reg
213}
215// --------------------------------------------------------------- lua bridge
217/// Fresh Lua with `smith.secret.register(value, label) -> placeholder`
218/// bridged to the shared registry, plus the detector plugin's hook table.
219fn setup_lua(reg: Rc<RefCell<Registry>>) -> mlua::Result<(Lua, Table)> {
220 let lua = Lua::new();
221 let smith = lua.create_table()?;
222 let secret = lua.create_table()?;
223 secret.set(
224 "register",
225 lua.create_function(move |_, (value, label): (String, String)| {
226 let id = reg.borrow_mut().register(&value, &label);
227 Ok(placeholder(id))
228 })?,
229 )?;
230 smith.set("secret", secret)?;
231 lua.globals().set("smith", smith)?;
232 let hooks: Table = lua.load(DETECTOR).set_name("plugins/detector.lua").eval()?;
233 Ok((lua, hooks))
234}
236#[derive(Clone, Copy)]
237enum Channel {
238 Input,
239 ToolResult,
240}
242/// The §6.7 ingestion pipeline: raw content → plugin hook (§9.8 return
243/// shapes) → ingestion scan over the POST-hook content → entry content.
244fn ingest(
245 lua: &Lua,
246 hook: Option<&Function>,
247 channel: Channel,
248 raw: &str,
249 reg: &Rc<RefCell<Registry>>,
250) -> Result<String, Box<dyn Error>> {
251 let post_hook = match hook {
252 Some(f) => {
253 let ev = lua.create_table()?;
254 match channel {
255 Channel::Input => {
256 ev.set("type", "input")?;
257 ev.set("text", raw)?;
258 }
259 Channel::ToolResult => {
260 ev.set("type", "tool_result")?;
261 ev.set("content", raw)?;
262 }
263 }
264 let ret: LuaValue = f.call(ev)?;
265 match (channel, ret) {
266 // input → { action = "handled"|"continue", text = <transformed>? }
267 (Channel::Input, LuaValue::Table(t)) => {
268 t.get::<Option<String>>("text")?.unwrap_or_else(|| raw.to_string())
269 }
270 // tool_result → { content = <replacement> } or nil (keep)
271 (Channel::ToolResult, LuaValue::Table(t)) => {
272 t.get::<Option<String>>("content")?.unwrap_or_else(|| raw.to_string())
273 }
274 _ => raw.to_string(),
275 }
276 }
277 None => raw.to_string(),
278 };
279 // Scan runs strictly AFTER the hook returned — this is the ordering
280 // §6.7 promises, and why hook-registered values land masked.
281 Ok(mask(&post_hook, &reg.borrow()))
282}
284// ------------------------------------------------------------------ helpers
286struct Check {
287 pass: bool,
288}
290impl Check {
291 fn ok(&mut self, label: &str, ok: bool) {
292 println!("{} {label}", if ok { "PASS" } else { "FAIL" });
293 self.pass &= ok;
294 }
295}
297fn count_occurrences(haystack: &[u8], needle: &[u8]) -> usize {
298 haystack.windows(needle.len()).filter(|w| *w == needle).count()
299}
301fn session_path(name: &str) -> std::path::PathBuf {
302 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("target").join(name)
303}
305// ---------------------------------------------------------------- scenarios
307fn scenario_ingest(c: &mut Check) -> Result<(), Box<dyn Error>> {
308 println!("== ingest: masking at ingestion; plaintext only in registration entries ==");
309 let reg = Rc::new(RefCell::new(Registry::new()));
310 let id1 = reg.borrow_mut().register("hunter2-token", "db-pass");
311 let mut entries = vec![SessionEntry::SecretRegistration {
312 id: id1,
313 value: "hunter2-token".into(),
314 label: "db-pass".into(),
315 }];
317 let masked = mask("connect with hunter2-token now", &reg.borrow());
318 c.ok(
319 &format!("user message masked at ingestion: {masked:?}"),
320 masked == "connect with smith:sec:1 now",
321 );
322 entries.push(SessionEntry::UserMessage { text: masked });
324 let tr = mask("stdout: hunter2-token appears twice hunter2-token", &reg.borrow());
325 c.ok(
326 "tool result masked (every occurrence)",
327 tr == "stdout: smith:sec:1 appears twice smith:sec:1",
328 );
329 entries.push(SessionEntry::ToolResult { content: tr });
331 let path = session_path("p13-ingest.session");
332 write_session(&path, &entries)?;
333 let bytes = std::fs::read(&path)?;
334 let n = count_occurrences(&bytes, b"hunter2-token");
335 c.ok(
336 &format!("session file bytes hold plaintext exactly once (found {n}, in the registration entry)"),
337 n == 1,
338 );
339 let decoded = read_session(&path)?;
340 let leak = decoded.iter().any(|e| {
341 !matches!(e, SessionEntry::SecretRegistration { .. })
342 && entry_text(e).contains("hunter2-token")
343 });
344 c.ok("decoded: no non-registration entry holds plaintext", !leak);
346 // EDGE (a): overlapping secrets — one value is a substring of another.
347 let id_short = reg.borrow_mut().register("abc", "short");
348 let id_long = reg.borrow_mut().register("abc-123", "long");
349 let m = mask("use abc-123 then abc alone", &reg.borrow());
350 let want = format!("use smith:sec:{id_long} then smith:sec:{id_short} alone");
351 c.ok(
352 &format!("overlap: longest-match-first masks correctly: {m:?}"),
353 m == want,
354 );
355 let naive = naive_mask_shortest_first("use abc-123 then abc alone", &reg.borrow());
356 println!(" naive shortest-first output: {naive:?}");
357 c.ok(
358 "overlap: naive shortest-first corrupts — long secret never masked, '-123' residue leaks",
359 naive.contains(&format!("smith:sec:{id_short}-123"))
360 && !naive.contains(&placeholder(id_long)),
361 );
363 // EDGE (b): a registered value that IS a placeholder string.
364 let id_ph = reg.borrow_mut().register("smith:sec:1", "placeholder-shaped");
365 let m2 = mask("value smith:sec:1 here", &reg.borrow());
366 c.ok(
367 &format!("placeholder-shaped secret: legit placeholder text in fresh content is re-masked (aliased): {m2:?}"),
368 m2 == format!("value smith:sec:{id_ph} here"),
369 );
370 let r1 = rehydrate(&m2, &reg.borrow());
371 c.ok(
372 "placeholder-shaped secret: single-pass rehydration yields the literal placeholder string, not secret 1 plaintext",
373 r1 == "value smith:sec:1 here",
374 );
375 let r2 = rehydrate(&r1, &reg.borrow());
376 println!(" a SECOND rehydration pass would yield: {r2:?} (secret 1 plaintext — recursion hazard if rehydration were not single-pass)");
377 c.ok(
378 "placeholder-shaped secret: double rehydration would expose secret 1 — single-pass rule is load-bearing",
379 r2 == "value hunter2-token here",
380 );
381 Ok(())
382}
384fn scenario_hook_order(c: &mut Check) -> Result<(), Box<dyn Error>> {
385 println!("== hook-order: ingestion scan runs AFTER plugin hooks ==");
386 let reg = Rc::new(RefCell::new(Registry::new()));
387 let (lua, hooks) = setup_lua(reg.clone())?;
389 // Value registered DURING the tool_result hook is masked in the very
390 // content that surfaced it.
391 let tr_hook: Function = hooks.get("tool_result")?;
392 let e1 = ingest(&lua, Some(&tr_hook), Channel::ToolResult, "deploy key: secret-A1B2C3 end", &reg)?;
393 c.ok(
394 &format!("tool_result: value registered DURING hook is masked in same content: {e1:?}"),
395 e1 == "deploy key: smith:sec:1 end",
396 );
397 c.ok(
398 "registry holds the hook-registered value with its label",
399 reg.borrow().by_value("secret-A1B2C3").map(|e| e.label.clone())
400 == Some("detected:A1B2C3".into()),
401 );
403 // input hook that registers AND transforms (§9.8 { action, text }):
404 // the scan runs on the post-transform text; the value survives the
405 // transform verbatim, so it is masked.
406 let in_hook: Function = hooks.get("input")?;
407 let e2 = ingest(&lua, Some(&in_hook), Channel::Input, "my token secret-DDDD here", &reg)?;
408 c.ok(
409 &format!("input: transform + register — scan masks post-transform content: {e2:?}"),
410 e2 == "[seen] my token smith:sec:2 here",
411 );
413 // EDGE (c): hook transforms so the secret appears only in PRE-transform
414 // text (uppercase re-encoding). Scan sees post-transform content only —
415 // the derived form lands in the entry unmasked.
416 let up_hook: Function = hooks.get("input_upper")?;
417 let e3 = ingest(&lua, Some(&up_hook), Channel::Input, "escape secret-eee ok", &reg)?;
418 println!(" post-transform entry content: {e3:?}");
419 c.ok(
420 "EDGE: transform re-encodes the secret — exact scan (post-transform only) misses it; derived plaintext lands in the entry",
421 e3 == "ESCAPE SECRET-EEE OK" && reg.borrow().by_value("secret-eee").is_some(),
422 );
423 Ok(())
424}
426fn scenario_rehydrate(c: &mut Check) -> Result<(), Box<dyn Error>> {
427 println!("== rehydrate: plaintext only at tool execution; unknown ids untouched ==");
428 let mut reg = Registry::new();
429 reg.register("hunter2-token", "db-pass"); // id 1
430 // Force a two-digit id to prove maximal-digit-run parsing.
431 reg.entries.push(SecretEntry { id: 12, value: "twelve-plain".into(), label: "twelve".into() });
432 reg.next_id = 13;
434 // The stored session entry (== provider view source): placeholders only,
435 // including one UNKNOWN id.
436 let stored_args =
437 r#"{"cmd":"login --pass smith:sec:1 --extra smith:sec:999 --n smith:sec:12"}"#;
438 let entry = SessionEntry::ToolCall { name: "shell".into(), args_json: stored_args.into() };
440 // Provider view: the entry as stored — placeholders survive, no plaintext.
441 let provider_view = entry_text(&entry).to_string();
442 c.ok(
443 "provider view keeps placeholders (no plaintext)",
444 !provider_view.contains("hunter2-token") && provider_view.contains("smith:sec:1"),
445 );
446 c.ok(
447 "provider view: unknown id smith:sec:999 present verbatim",
448 provider_view.contains("smith:sec:999"),
449 );
451 // Execution view: rehydrated immediately before tool execute.
452 let rehydrated = rehydrate(&provider_view, &reg);
453 println!(" execute view: {rehydrated:?}");
454 c.ok(
455 "execute view: known placeholder rehydrated to plaintext",
456 rehydrated.contains("--pass hunter2-token"),
457 );
458 c.ok(
459 "execute view: unknown id smith:sec:999 passes through untouched (not an error)",
460 rehydrated.contains("--extra smith:sec:999"),
461 );
462 c.ok(
463 "maximal digit run: smith:sec:12 rehydrates as id 12, not id 1 + '2'",
464 rehydrated.contains("--n twelve-plain") && !rehydrated.contains("hunter2-token2"),
465 );
467 // Rust tool execute fn receives the rehydrated args.
468 let rust_execute = |args: &str| args.to_string();
469 let seen = rust_execute(&rehydrated);
470 c.ok("Rust tool execute receives plaintext", seen.contains("hunter2-token"));
472 // Lua tool execute fn receives the same rehydrated args.
473 let lua = Lua::new();
474 let f: Function = lua
475 .load("return function(args) return args.cmd end")
476 .set_name("lua-tool-execute")
477 .eval()?;
478 let args_tbl = lua.create_table()?;
479 let cmd: String = {
480 // parse the JSON-ish cmd out for the Lua call; keep it trivial
481 let start = rehydrated.find(":\"").unwrap() + 2;
482 let end = rehydrated.rfind('"').unwrap();
483 rehydrated[start..end].to_string()
484 };
485 args_tbl.set("cmd", cmd)?;
486 let lua_seen: String = f.call(args_tbl)?;
487 c.ok(
488 "Lua tool execute receives plaintext, unknown id still verbatim",
489 lua_seen.contains("hunter2-token") && lua_seen.contains("smith:sec:999"),
490 );
492 // The stored entry never changed: rehydration is a view at the execution
493 // boundary, not a mutation.
494 c.ok(
495 "stored entry unchanged after rehydration (boundary, not mutation)",
496 entry_text(&entry) == stored_args,
497 );
498 Ok(())
499}
501fn scenario_resume(c: &mut Check) -> Result<(), Box<dyn Error>> {
502 println!("== resume: backward scan rebuilds the table; masking works immediately ==");
503 let path = session_path("p13-resume.session");
504 {
505 let mut reg = Registry::new();
506 let id1 = reg.register("hunter2-token", "db-pass");
507 let id2 = reg.register("aws-KEYXYZ", "aws");
508 let entries = vec![
509 SessionEntry::SecretRegistration { id: id1, value: "hunter2-token".into(), label: "db-pass".into() },
510 SessionEntry::SecretRegistration { id: id2, value: "aws-KEYXYZ".into(), label: "aws".into() },
511 SessionEntry::UserMessage { text: mask("use hunter2-token and aws-KEYXYZ", &reg) },
512 ];
513 write_session(&path, &entries)?;
514 // registry and entries drop here — everything in memory is gone
515 }
517 let entries = read_session(&path)?;
518 c.ok(&format!("reloaded {} entries from session file", entries.len()), entries.len() == 3);
519 let stored = entry_text(&entries[2]);
520 c.ok(
521 &format!("persisted message holds placeholders only: {stored:?}"),
522 stored == "use smith:sec:1 and smith:sec:2",
523 );
525 let mut reg = rebuild_registry(&entries);
526 c.ok(
527 "backward scan rebuilt both registrations (plaintext + label)",
528 reg.by_id(1).map(|e| e.value.as_str()) == Some("hunter2-token")
529 && reg.by_id(2).map(|e| e.label.as_str()) == Some("aws"),
530 );
532 let m = mask("send aws-KEYXYZ please", &reg);
533 c.ok(
534 &format!("new message with a known secret is masked immediately with the ORIGINAL id: {m:?}"),
535 m == "send smith:sec:2 please",
536 );
538 let new_id = reg.register("new-secret-value", "post-resume");
539 c.ok(
540 &format!("id allocator resumed past max seen id (new id {new_id}; a reused id would alias old placeholders)"),
541 new_id == 3,
542 );
543 Ok(())
544}
546// --------------------------------------------------------------------- main
548fn main() -> Result<(), Box<dyn Error>> {
549 let cmd = std::env::args().nth(1).unwrap_or_else(|| "all".into());
550 let mut c = Check { pass: true };
551 match cmd.as_str() {
552 "ingest" => scenario_ingest(&mut c)?,
553 "hook-order" => scenario_hook_order(&mut c)?,
554 "rehydrate" => scenario_rehydrate(&mut c)?,
555 "resume" => scenario_resume(&mut c)?,
556 "all" => {
557 scenario_ingest(&mut c)?;
558 println!();
559 scenario_hook_order(&mut c)?;
560 println!();
561 scenario_rehydrate(&mut c)?;
562 println!();
563 scenario_resume(&mut c)?;
564 }
565 other => {
566 eprintln!("usage: p13 [ingest|hook-order|rehydrate|resume|all] (got {other:?})");
567 std::process::exit(2);
568 }
569 }
570 println!();
571 if c.pass {
572 println!("p13 RESULT ({cmd}): all expectations hold");
573 Ok(())
574 } else {
575 Err(format!("p13 RESULT ({cmd}): expectation failed").into())
576 }
577}

prototypes/p14-steering-queue/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 = "p14-steering-queue"
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.119"
87source = "registry+https://github.com/rust-lang/crates.io-index"
88checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
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/p14-steering-queue/Cargo.toml

Added
new file mode 100644

+8 / −0 text lines

1[package]
2name = "p14-steering-queue"
3version = "0.1.0"
4edition = "2021"
5publish = false
6
7[dependencies]
8serde_json = "1"

prototypes/p14-steering-queue/src/main.rs

Added
new file mode 100644

+779 / −0 text lines

1//! p14-steering-queue
2//!
3//! Proves or disproves docs/SPEC.md §6.1 steering/follow-up claims (with
4//! §5.3 ToolExecutionMode and §12 abort in view):
5//! - steers deliver at the next safe boundary (stream end / current tool
6//! completion),
7//! - pending not-yet-executed tool calls resolve as synthetic error results
8//! (`skipped: user steered`), every call has a result on the wire,
9//! - queued steers drain FIFO as user messages before the next provider call,
10//! - follow-ups dequeue instead of `agent_end` (FIFO, one per run-end),
11//! - session entries are recorded at DELIVERY time only, never when queued,
12//! - a delivered abort ends the run; whatever remains queued stays queued.
13//!
14//! Extends the p07 pattern: scripted StreamFn, deterministic AgentEvent
15//! sequences, expect() comparisons, PASS/FAIL output. Parallel execution is
16//! simulated with a deterministic completion order — concurrency changes
17//! timing, not the boundary semantics under test.
18//!
19//! Decisions this prototype makes where §6.1 is silent or ambiguous (all
20//! reported as spec issues):
21//! - steer-mid-stream: a steer that arrives while the assistant message is
22//! still streaming is delivered after the stream completes; at that point
23//! NO call from that message has started executing, so ALL of its calls
24//! are pending and resolve as synthetic skipped results. The model
25//! re-plans with the steer visible.
26//! - parallel boundary: "after the currently executing tool finishes" is
27//! ambiguous with N tools in flight. Implemented rule:
28//! WAIT-FOR-ALL-IN-FLIGHT — every already-started call runs to completion
29//! (real results, completion order), no new call starts once a steer is
30//! queued, never-started calls resolve skipped. The alternative
31//! (first-completion) would deliver the steer while sibling calls are
32//! still executing — their results would race the steer message or force
33//! mid-execution cancellation, which §6.1 has no vocabulary for.
34//! - synthetic-result ordering: skipped synthetics appear in the transcript
35//! AFTER all real results of the batch, in original call order; the steer
36//! user message follows them; the next provider request sees all of it.
37//! - skipped calls emit ToolExecutionStart/End (is_error=true) mirroring the
38//! §6.4 blocked-call contract, so the UI can render them.
39//! - abort (§12) ends the run with NO synthetic results for unexecuted
40//! calls: there is no next provider request to need them; the queues are
41//! surfaced to the TUI instead (§6.1).
42//!
43//! Verify: `cargo run -- steer-mid-stream|steer-mid-tools|steer-parallel-tools|followup|abort-keeps-queue|all`
44//! (exit 0 each).
46use serde_json::{json, Value};
47use std::collections::VecDeque;
49// ---- smith/ shared types (miniature, mirroring SPEC §5.2–§5.4) ----
51#[derive(Debug, Clone, PartialEq)]
52enum StopReason {
53 EndTurn,
54 ToolUse,
55}
57#[derive(Debug, Clone)]
58enum ProviderEvent {
59 TextDelta(String),
60 ToolCall { id: String, name: String, args: Value },
61 Done { stop: StopReason },
62}
64#[derive(Debug, Clone)]
65struct Message {
66 role: &'static str,
67 content: String,
68}
70#[derive(Debug, Clone)]
71struct ProviderRequest {
72 messages: Vec<Message>,
73}
75/// SPEC §5.4: input ProviderRequest, output stream of ProviderEvent.
76type StreamFn = Box<dyn FnMut(&ProviderRequest) -> Vec<ProviderEvent>>;
78// ---- smith-core/ agent events (miniature, SPEC §6.2 + steering) ----
80#[derive(Debug, Clone, PartialEq)]
81enum AgentEvent {
82 AgentStart,
83 TurnStart(u32),
84 MessageStart,
85 TextDelta(String),
86 MessageEnd,
87 ToolExecutionStart { id: String, name: String },
88 ToolExecutionEnd { id: String, output: String, is_error: bool },
89 /// A queued steer delivered as a user message (safe boundary reached).
90 SteerDelivered(String),
91 /// A queued follow-up delivered instead of `agent_end`.
92 FollowupDelivered(String),
93 /// §12: a delivered abort ends the run.
94 RunAborted,
95 TurnEnd(u32),
96 AgentEnd,
97}
99// ---- input scripting: deterministic arrival points ----
101#[derive(Debug, Clone, Copy, PartialEq)]
102enum InputKind {
103 Steer,
104 Followup,
105}
107/// Deterministic simulation points at which external input can arrive.
108#[derive(Debug, Clone, PartialEq)]
109enum Point {
110 /// Queued before the run starts (already-buffered input).
111 BeforeRun,
112 /// Arrives while the provider stream of `turn` is mid-flight, right
113 /// after the stream event with this index was processed.
114 DuringStream { turn: u32, after_event: usize },
115 /// Arrives while tool `id` is executing — becomes visible at the moment
116 /// that call completes (the earliest boundary at which the loop can
117 /// observe it, in both sequential and parallel mode).
118 WhileToolRuns { id: String },
119}
121struct Arrival {
122 at: Point,
123 kind: InputKind,
124 text: &'static str,
125}
127/// SPEC §5.3 ToolExecutionMode, miniature. Parallel carries the simulated
128/// deterministic completion order of in-flight calls.
129#[derive(Debug, Clone, PartialEq)]
130enum ExecMode {
131 Sequential,
132 Parallel { window: usize, completion_order: Vec<&'static str> },
133}
135/// Session entry recorded at DELIVERY time only (§6.1: "queued messages
136/// become session entries when delivered, never when queued").
137#[derive(Debug, Clone)]
138struct Entry {
139 tick: u64,
140 kind: &'static str, // user | assistant | tool_result | steer | followup
141 text: String,
142}
144struct RunResult {
145 events: Vec<AgentEvent>,
146 messages: Vec<Message>,
147 entries: Vec<Entry>,
148 steer_queue: Vec<String>,
149 followup_queue: Vec<String>,
150 /// (text, tick at which the input ARRIVED — i.e. was queued).
151 arrival_ticks: Vec<(String, u64)>,
152}
154fn fire_arrivals(
155 point: &Point,
156 arrivals: &mut Vec<Arrival>,
157 steer_q: &mut VecDeque<String>,
158 followup_q: &mut VecDeque<String>,
159 arrival_ticks: &mut Vec<(String, u64)>,
160 tick: u64,
161) {
162 let mut i = 0;
163 while i < arrivals.len() {
164 if arrivals[i].at == *point {
165 let a = arrivals.remove(i);
166 arrival_ticks.push((a.text.to_string(), tick));
167 match a.kind {
168 InputKind::Steer => steer_q.push_back(a.text.to_string()),
169 InputKind::Followup => followup_q.push_back(a.text.to_string()),
170 }
171 } else {
172 i += 1;
173 }
174 }
175}
177fn abort_fires(point: &Point, abort_at: &mut Option<Point>) -> bool {
178 if abort_at.as_ref() == Some(point) {
179 *abort_at = None;
180 true
181 } else {
182 false
183 }
184}
186/// Mock tool: every call succeeds deterministically.
187fn execute_tool(_name: &str, id: &str, _args: &Value) -> String {
188 format!("done:{id}")
189}
191/// Pending not-yet-executed calls resolve as synthetic error results, in
192/// ORIGINAL call order, after all real results of the batch (§6.1 rule
193/// under test). Mirrors the §6.4 blocked-call contract: Start/End events
194/// still emitted so the UI can show the skip.
195#[allow(clippy::too_many_arguments)]
196fn skip_pending(
197 pending: &mut VecDeque<(String, String, Value)>,
198 events: &mut Vec<AgentEvent>,
199 messages: &mut Vec<Message>,
200 entries: &mut Vec<Entry>,
201 tick: &mut u64,
202) {
203 while let Some((id, name, _args)) = pending.pop_front() {
204 *tick += 1;
205 events.push(AgentEvent::ToolExecutionStart { id: id.clone(), name });
206 events.push(AgentEvent::ToolExecutionEnd {
207 id: id.clone(),
208 output: "skipped: user steered".into(),
209 is_error: true,
210 });
211 messages.push(Message { role: "tool", content: format!("{id}:skipped: user steered") });
212 entries.push(Entry { tick: *tick, kind: "tool_result", text: format!("{id}:skipped: user steered") });
213 }
214}
216/// Miniature agent loop per SPEC §6.1: outer loop = turns + follow-ups,
217/// inner loop = provider streaming, tool calls, steering.
218fn agent_loop(
219 mut stream: StreamFn,
220 mode: ExecMode,
221 mut arrivals: Vec<Arrival>,
222 mut abort_at: Option<Point>,
223 user_prompt: &str,
224) -> RunResult {
225 let mut events = vec![AgentEvent::AgentStart];
226 let mut messages = vec![Message { role: "user", content: user_prompt.into() }];
227 let mut entries: Vec<Entry> = Vec::new();
228 let mut steer_q: VecDeque<String> = VecDeque::new();
229 let mut followup_q: VecDeque<String> = VecDeque::new();
230 let mut arrival_ticks: Vec<(String, u64)> = Vec::new();
231 let mut tick: u64 = 0;
232 let mut aborted = false;
234 entries.push(Entry { tick, kind: "user", text: user_prompt.into() });
235 fire_arrivals(&Point::BeforeRun, &mut arrivals, &mut steer_q, &mut followup_q, &mut arrival_ticks, tick);
237 let mut turn = 0u32;
238 'outer: loop {
239 turn += 1;
240 if turn > 50 {
241 break; // max_turns_per_user_message guard (§6.1)
242 }
243 events.push(AgentEvent::TurnStart(turn));
244 events.push(AgentEvent::MessageStart);
245 let req = ProviderRequest { messages: messages.clone() };
246 let mut pending: VecDeque<(String, String, Value)> = VecDeque::new();
247 let mut stop = StopReason::EndTurn;
248 let mut text = String::new();
249 // The stream is NOT interrupted by a steer: §6.1 delivers at the
250 // next safe boundary, which is stream end at the earliest.
251 for (i, ev) in stream(&req).into_iter().enumerate() {
252 tick += 1;
253 match ev {
254 ProviderEvent::TextDelta(t) => {
255 text.push_str(&t);
256 events.push(AgentEvent::TextDelta(t));
257 }
258 ProviderEvent::ToolCall { id, name, args } => pending.push_back((id, name, args)),
259 ProviderEvent::Done { stop: s } => stop = s,
260 }
261 let p = Point::DuringStream { turn, after_event: i };
262 fire_arrivals(&p, &mut arrivals, &mut steer_q, &mut followup_q, &mut arrival_ticks, tick);
263 if abort_fires(&p, &mut abort_at) {
264 aborted = true;
265 }
266 }
267 events.push(AgentEvent::MessageEnd);
268 tick += 1;
269 messages.push(Message { role: "assistant", content: text.clone() });
270 entries.push(Entry { tick, kind: "assistant", text });
272 if aborted {
273 events.push(AgentEvent::RunAborted);
274 break 'outer;
275 }
277 // ---- tool phase ----
278 if !pending.is_empty() {
279 if !steer_q.is_empty() {
280 // Steer arrived mid-stream: delivered after stream end. No
281 // call of this assistant message has started; all are
282 // "pending not-yet-executed" and resolve skipped (§6.1).
283 skip_pending(&mut pending, &mut events, &mut messages, &mut entries, &mut tick);
284 } else {
285 let window = match &mode {
286 ExecMode::Sequential => 1,
287 ExecMode::Parallel { window, .. } => *window,
288 };
289 let order: Vec<&'static str> = match &mode {
290 ExecMode::Sequential => Vec::new(),
291 ExecMode::Parallel { completion_order, .. } => completion_order.clone(),
292 };
293 let mut in_flight: Vec<(String, String, Value)> = Vec::new();
294 while in_flight.len() < window && !pending.is_empty() {
295 let c = pending.pop_front().unwrap();
296 tick += 1;
297 events.push(AgentEvent::ToolExecutionStart { id: c.0.clone(), name: c.1.clone() });
298 in_flight.push(c);
299 }
300 while !in_flight.is_empty() {
301 // Deterministic simulated completion: next scripted id
302 // that is in flight, else FIFO.
303 let idx = order
304 .iter()
305 .find_map(|oid| in_flight.iter().position(|c| c.0 == *oid))
306 .unwrap_or(0);
307 let (id, name, args) = in_flight.remove(idx);
308 let output = execute_tool(&name, &id, &args);
309 tick += 1;
310 events.push(AgentEvent::ToolExecutionEnd {
311 id: id.clone(),
312 output: output.clone(),
313 is_error: false,
314 });
315 messages.push(Message { role: "tool", content: format!("{id}:{output}") });
316 entries.push(Entry { tick, kind: "tool_result", text: format!("{id}:{output}") });
318 // A tool completion is a safe boundary (§6.1): input that
319 // arrived while this call ran becomes visible now.
320 let p = Point::WhileToolRuns { id: id.clone() };
321 fire_arrivals(&p, &mut arrivals, &mut steer_q, &mut followup_q, &mut arrival_ticks, tick);
322 if abort_fires(&p, &mut abort_at) {
323 // §12/§6.1: delivered abort ends the run NOW. No
324 // synthetic results — there is no next provider
325 // request. Queues stay intact for the TUI.
326 events.push(AgentEvent::RunAborted);
327 break 'outer;
328 }
329 if steer_q.is_empty() {
330 // No steer visible: keep the window full.
331 while in_flight.len() < window && !pending.is_empty() {
332 let c = pending.pop_front().unwrap();
333 tick += 1;
334 events.push(AgentEvent::ToolExecutionStart { id: c.0.clone(), name: c.1.clone() });
335 in_flight.push(c);
336 }
337 }
338 // Steer visible: WAIT-FOR-ALL-IN-FLIGHT rule — calls that
339 // already started keep draining (loop continues), but no
340 // new call starts.
341 }
342 if !steer_q.is_empty() && !pending.is_empty() {
343 skip_pending(&mut pending, &mut events, &mut messages, &mut entries, &mut tick);
344 }
345 }
346 }
347 events.push(AgentEvent::TurnEnd(turn));
349 // ---- boundary delivery: steers drain FIFO before next provider call ----
350 if !steer_q.is_empty() {
351 while let Some(s) = steer_q.pop_front() {
352 tick += 1;
353 events.push(AgentEvent::SteerDelivered(s.clone()));
354 messages.push(Message { role: "user", content: s.clone() });
355 // Session entry written at DELIVERY time only (§6.1).
356 entries.push(Entry { tick, kind: "steer", text: s });
357 }
358 continue 'outer;
359 }
360 if stop == StopReason::ToolUse {
361 continue 'outer;
362 }
363 // Run would otherwise end: follow-up dequeues instead of agent_end.
364 if let Some(f) = followup_q.pop_front() {
365 tick += 1;
366 events.push(AgentEvent::FollowupDelivered(f.clone()));
367 messages.push(Message { role: "user", content: f.clone() });
368 entries.push(Entry { tick, kind: "followup", text: f });
369 continue 'outer;
370 }
371 break 'outer;
372 }
373 events.push(AgentEvent::AgentEnd);
375 RunResult {
376 events,
377 messages,
378 entries,
379 steer_queue: steer_q.into_iter().collect(),
380 followup_queue: followup_q.into_iter().collect(),
381 arrival_ticks,
382 }
383}
385// ---- scripted mock streams ----
387/// Turn 1: one text delta + `n_calls` tool calls, stop=ToolUse.
388/// Turn 2+: echoes what the request transcript proves — how many tool
389/// results it can see and whether the last message is a user message
390/// (the delivered steer), then stops.
391fn script_batch(first_text: &'static str, n_calls: usize) -> StreamFn {
392 let mut call = 0usize;
393 Box::new(move |req| {
394 call += 1;
395 if call == 1 {
396 let mut evs = vec![ProviderEvent::TextDelta(first_text.into())];
397 for i in 1..=n_calls {
398 evs.push(ProviderEvent::ToolCall {
399 id: format!("t{i}"),
400 name: "work".into(),
401 args: json!({}),
402 });
403 }
404 evs.push(ProviderEvent::Done { stop: StopReason::ToolUse });
405 evs
406 } else {
407 let results = req.messages.iter().filter(|m| m.role == "tool").count();
408 let steer_last = req.messages.last().map(|m| m.role == "user").unwrap_or(false);
409 vec![
410 ProviderEvent::TextDelta(format!("resumed: results={results} steer_last={steer_last}")),
411 ProviderEvent::Done { stop: StopReason::EndTurn },
412 ]
413 }
414 })
415}
417/// Every turn: text answer quoting the last user message, stop=EndTurn.
418/// Proves each follow-up was delivered as a fresh user message.
419fn script_turns() -> StreamFn {
420 let mut call = 0usize;
421 Box::new(move |req| {
422 call += 1;
423 let last_user = req
424 .messages
425 .iter()
426 .rev()
427 .find(|m| m.role == "user")
428 .map(|m| m.content.clone())
429 .unwrap_or_default();
430 vec![
431 ProviderEvent::TextDelta(format!("turn{call} answer to '{last_user}'")),
432 ProviderEvent::Done { stop: StopReason::EndTurn },
433 ]
434 })
435}
437// ---- assertions (p07 style) ----
439fn expect(label: &str, got: &[AgentEvent], want: &[AgentEvent]) -> bool {
440 let ok = got == want;
441 println!("{} {label}", if ok { "PASS" } else { "FAIL" });
442 if !ok {
443 println!(" want: {want:?}");
444 println!(" got: {got:?}");
445 }
446 ok
447}
449fn check(label: &str, ok: bool) -> bool {
450 println!("{} {label}", if ok { "PASS" } else { "FAIL" });
451 ok
452}
454fn dump(events: &[AgentEvent]) {
455 println!(" exact sequence:");
456 for e in events {
457 println!(" {e:?}");
458 }
459}
461fn tool_msgs(msgs: &[Message]) -> Vec<String> {
462 msgs.iter().filter(|m| m.role == "tool").map(|m| m.content.clone()).collect()
463}
465/// §6.1 delivery-time-only recording: the steer's session entry exists
466/// exactly once and was written strictly AFTER the input arrived (queued).
467fn check_delivery_time_entry(r: &RunResult, kind: &str, text: &str) -> bool {
468 let arrival = r.arrival_ticks.iter().find(|(t, _)| t == text).map(|(_, tk)| *tk);
469 let entry_ticks: Vec<u64> =
470 r.entries.iter().filter(|e| e.kind == kind && e.text == text).map(|e| e.tick).collect();
471 let one_entry = entry_ticks.len() == 1;
472 let after_arrival = match (arrival, entry_ticks.first()) {
473 (Some(a), Some(d)) => *d > a,
474 _ => false,
475 };
476 check(
477 &format!("entry for '{text}' recorded once, at delivery tick (> arrival tick)"),
478 one_entry && after_arrival,
479 )
480}
482fn main() -> Result<(), Box<dyn std::error::Error>> {
483 let scenario = std::env::args().nth(1).unwrap_or_else(|| "all".into());
484 let scenarios: Vec<&str> = if scenario == "all" {
485 vec!["steer-mid-stream", "steer-mid-tools", "steer-parallel-tools", "followup", "abort-keeps-queue"]
486 } else {
487 vec![scenario.as_str()]
488 };
490 let mut all_ok = true;
491 for s in &scenarios {
492 println!("== scenario {s} ==");
493 all_ok &= run_scenario(s);
494 println!();
495 }
497 if all_ok {
498 println!("p14 RESULT: scenario '{scenario}' holds");
499 Ok(())
500 } else {
501 Err(format!("p14 RESULT: scenario '{scenario}' failed").into())
502 }
503}
505fn run_scenario(name: &str) -> bool {
506 use AgentEvent::*;
507 let skip = |i: u32| -> [AgentEvent; 2] {
508 [
509 ToolExecutionStart { id: format!("t{i}"), name: "work".into() },
510 ToolExecutionEnd { id: format!("t{i}"), output: "skipped: user steered".into(), is_error: true },
511 ]
512 };
513 let real_end = |i: u32| ToolExecutionEnd {
514 id: format!("t{i}"),
515 output: format!("done:t{i}"),
516 is_error: false,
517 };
518 let start = |i: u32| ToolExecutionStart { id: format!("t{i}"), name: "work".into() };
520 match name {
521 // Steer arrives while the assistant message streams: delivered after
522 // stream end; ALL tool calls of that message are pending → skipped.
523 "steer-mid-stream" => {
524 let arrivals = vec![Arrival {
525 at: Point::DuringStream { turn: 1, after_event: 0 },
526 kind: InputKind::Steer,
527 text: "change of plan",
528 }];
529 let r = agent_loop(script_batch("planning", 2), ExecMode::Sequential, arrivals, None, "go");
530 let mut want = vec![AgentStart, TurnStart(1), MessageStart, TextDelta("planning".into()), MessageEnd];
531 want.extend(skip(1));
532 want.extend(skip(2));
533 want.extend([
534 TurnEnd(1),
535 SteerDelivered("change of plan".into()),
536 TurnStart(2),
537 MessageStart,
538 TextDelta("resumed: results=2 steer_last=true".into()),
539 MessageEnd,
540 TurnEnd(2),
541 AgentEnd,
542 ]);
543 let seq = expect("steer-mid-stream: steer delivered after stream end; both calls skipped", &r.events, &want);
544 dump(&r.events);
545 let order = check(
546 "transcript: skipped synthetics in original call order, steer user message after them",
547 tool_msgs(&r.messages)
548 == vec!["t1:skipped: user steered".to_string(), "t2:skipped: user steered".to_string()]
549 && r.messages.iter().position(|m| m.content == "change of plan")
550 > r.messages.iter().rposition(|m| m.role == "tool"),
551 );
552 let seen = check(
553 "next provider request sees 2 results + steer as latest user message",
554 r.events.iter().any(|e| matches!(e, TextDelta(t) if t == "resumed: results=2 steer_last=true")),
555 );
556 let entry = check_delivery_time_entry(&r, "steer", "change of plan");
557 seq && order && seen && entry
558 }
560 // 6-call sequential batch; steer arrives while call 3 executes:
561 // calls 1–3 real, 4–6 skipped, steer next, before provider call.
562 "steer-mid-tools" => {
563 let arrivals = vec![Arrival {
564 at: Point::WhileToolRuns { id: "t3".into() },
565 kind: InputKind::Steer,
566 text: "stop drilling",
567 }];
568 let r = agent_loop(script_batch("running batch", 6), ExecMode::Sequential, arrivals, None, "go");
569 let mut want = vec![AgentStart, TurnStart(1), MessageStart, TextDelta("running batch".into()), MessageEnd];
570 for i in 1..=3 {
571 want.push(start(i));
572 want.push(real_end(i));
573 }
574 for i in 4..=6 {
575 want.extend(skip(i));
576 }
577 want.extend([
578 TurnEnd(1),
579 SteerDelivered("stop drilling".into()),
580 TurnStart(2),
581 MessageStart,
582 TextDelta("resumed: results=6 steer_last=true".into()),
583 MessageEnd,
584 TurnEnd(2),
585 AgentEnd,
586 ]);
587 let seq = expect(
588 "steer-mid-tools: current tool (t3) completes, t4–t6 skipped, steer precedes next provider request",
589 &r.events,
590 &want,
591 );
592 dump(&r.events);
593 let order = check(
594 "transcript: real results t1–t3 then skipped t4–t6 in original order, steer after",
595 tool_msgs(&r.messages)
596 == vec![
597 "t1:done:t1".to_string(),
598 "t2:done:t2".to_string(),
599 "t3:done:t3".to_string(),
600 "t4:skipped: user steered".to_string(),
601 "t5:skipped: user steered".to_string(),
602 "t6:skipped: user steered".to_string(),
603 ],
604 );
605 let seen = check(
606 "next provider request sees all 6 results + steer last",
607 r.events.iter().any(|e| matches!(e, TextDelta(t) if t == "resumed: results=6 steer_last=true")),
608 );
609 let entry = check_delivery_time_entry(&r, "steer", "stop drilling");
610 seq && order && seen && entry
611 }
613 // 5-call batch, parallel window 3: t1–t3 in flight concurrently
614 // (simulated completion order t2,t1,t3); steer arrives while t2
615 // executes. WAIT-FOR-ALL-IN-FLIGHT: t1,t3 still complete (real);
616 // t4,t5 never start → skipped; steer after.
617 "steer-parallel-tools" => {
618 let arrivals = vec![Arrival {
619 at: Point::WhileToolRuns { id: "t2".into() },
620 kind: InputKind::Steer,
621 text: "new priority",
622 }];
623 let mode = ExecMode::Parallel { window: 3, completion_order: vec!["t2", "t1", "t3"] };
624 let r = agent_loop(script_batch("running parallel batch", 5), mode, arrivals, None, "go");
625 let mut want = vec![
626 AgentStart,
627 TurnStart(1),
628 MessageStart,
629 TextDelta("running parallel batch".into()),
630 MessageEnd,
631 start(1),
632 start(2),
633 start(3),
634 real_end(2),
635 real_end(1),
636 real_end(3),
637 ];
638 want.extend(skip(4));
639 want.extend(skip(5));
640 want.extend([
641 TurnEnd(1),
642 SteerDelivered("new priority".into()),
643 TurnStart(2),
644 MessageStart,
645 TextDelta("resumed: results=5 steer_last=true".into()),
646 MessageEnd,
647 TurnEnd(2),
648 AgentEnd,
649 ]);
650 let seq = expect(
651 "steer-parallel-tools: all in-flight (t1,t2,t3) finish, t4/t5 never start and skip",
652 &r.events,
653 &want,
654 );
655 dump(&r.events);
656 let order = check(
657 "transcript: real results in completion order (t2,t1,t3), skipped t4,t5 in original order, steer after",
658 tool_msgs(&r.messages)
659 == vec![
660 "t2:done:t2".to_string(),
661 "t1:done:t1".to_string(),
662 "t3:done:t3".to_string(),
663 "t4:skipped: user steered".to_string(),
664 "t5:skipped: user steered".to_string(),
665 ],
666 );
667 let seen = check(
668 "next provider request sees all 5 results + steer last",
669 r.events.iter().any(|e| matches!(e, TextDelta(t) if t == "resumed: results=5 steer_last=true")),
670 );
671 let entry = check_delivery_time_entry(&r, "steer", "new priority");
672 println!("REPORT parallel boundary ambiguity (§6.1 x §5.3):");
673 println!(" steer became visible when t2 completed while t1,t3 were still in flight.");
674 println!(" first-completion rule: deliver at t2's completion — t1/t3 are neither");
675 println!(" 'currently executing' (finished) nor 'pending not-yet-executed' (started);");
676 println!(" their results would land AFTER the steer user message or require");
677 println!(" mid-execution cancellation. Ill-defined under §6.1's vocabulary.");
678 println!(" wait-for-all-in-flight rule (implemented): every started call runs to");
679 println!(" completion, no new call starts once a steer is queued, never-started");
680 println!(" calls resolve skipped. This is the rule §6.1 should pin.");
681 seq && order && seen && entry
682 }
684 // Two follow-ups queued before the run: each consumed at run-end
685 // instead of agent_end, FIFO, delivered as fresh user messages.
686 "followup" => {
687 let arrivals = vec![
688 Arrival { at: Point::BeforeRun, kind: InputKind::Followup, text: "first follow-up" },
689 Arrival { at: Point::BeforeRun, kind: InputKind::Followup, text: "second follow-up" },
690 ];
691 let r = agent_loop(script_turns(), ExecMode::Sequential, arrivals, None, "go");
692 let want = vec![
693 AgentStart,
694 TurnStart(1),
695 MessageStart,
696 TextDelta("turn1 answer to 'go'".into()),
697 MessageEnd,
698 TurnEnd(1),
699 FollowupDelivered("first follow-up".into()),
700 TurnStart(2),
701 MessageStart,
702 TextDelta("turn2 answer to 'first follow-up'".into()),
703 MessageEnd,
704 TurnEnd(2),
705 FollowupDelivered("second follow-up".into()),
706 TurnStart(3),
707 MessageStart,
708 TextDelta("turn3 answer to 'second follow-up'".into()),
709 MessageEnd,
710 TurnEnd(3),
711 AgentEnd,
712 ];
713 let seq = expect("followup: dequeued instead of agent_end, one per run-end, FIFO", &r.events, &want);
714 dump(&r.events);
715 let fifo = {
716 let ticks: Vec<u64> =
717 r.entries.iter().filter(|e| e.kind == "followup").map(|e| e.tick).collect();
718 check("followup entries FIFO by delivery tick", ticks.len() == 2 && ticks[0] < ticks[1])
719 };
720 let e1 = check_delivery_time_entry(&r, "followup", "first follow-up");
721 let e2 = check_delivery_time_entry(&r, "followup", "second follow-up");
722 let drained = check("both queues empty at agent_end", r.steer_queue.is_empty() && r.followup_queue.is_empty());
723 seq && fifo && e1 && e2 && drained
724 }
726 // Abort delivered mid-batch (while t2 of 4 runs, with a steer and a
727 // follow-up queued at the same point): run ends immediately after
728 // the current tool; queues stay intact; nothing queued was recorded.
729 "abort-keeps-queue" => {
730 let arrivals = vec![
731 Arrival { at: Point::WhileToolRuns { id: "t2".into() }, kind: InputKind::Steer, text: "queued steer" },
732 Arrival {
733 at: Point::WhileToolRuns { id: "t2".into() },
734 kind: InputKind::Followup,
735 text: "queued follow-up",
736 },
737 ];
738 let abort_at = Some(Point::WhileToolRuns { id: "t2".into() });
739 let r = agent_loop(script_batch("running batch", 4), ExecMode::Sequential, arrivals, abort_at, "go");
740 let want = vec![
741 AgentStart,
742 TurnStart(1),
743 MessageStart,
744 TextDelta("running batch".into()),
745 MessageEnd,
746 start(1),
747 real_end(1),
748 start(2),
749 real_end(2),
750 RunAborted,
751 AgentEnd,
752 ];
753 let seq = expect("abort-keeps-queue: run ends after current tool (t2); t3/t4 never resolve", &r.events, &want);
754 dump(&r.events);
755 let queues = check(
756 "queue snapshot intact after abort",
757 r.steer_queue == vec!["queued steer".to_string()]
758 && r.followup_queue == vec!["queued follow-up".to_string()],
759 );
760 println!("REPORT queue snapshot at abort:");
761 println!(" steer_queue = {:?}", r.steer_queue);
762 println!(" followup_queue = {:?}", r.followup_queue);
763 let no_entries = check(
764 "no session entry for queued-but-undelivered messages (delivery-time-only recording)",
765 !r.entries.iter().any(|e| e.kind == "steer" || e.kind == "followup"),
766 );
767 let no_synth = check(
768 "no synthetic results after abort (no next provider request to feed)",
769 tool_msgs(&r.messages) == vec!["t1:done:t1".to_string(), "t2:done:t2".to_string()],
770 );
771 seq && queues && no_entries && no_synth
772 }
774 other => {
775 println!("unknown scenario {other}");
776 false
777 }
778 }
779}