From f7a17633972baaf419dff7b99ffa329e9984bd99 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:54:07 -0300 Subject: [PATCH 1/4] Model fixture lifetimes, lexer tokens and cleanup reminders Keep each scan, outstanding call, token and Git baseline with the data its phase owns. Read both tool advertisements on the prompted load request. Check the stop continuation at the fixture provider. Verified: 34 focused suites, 628 differential parser cases, 12 isolated host cases and 14 golden cases. --- .agents/skills/verify/SKILL.md | 10 +- .agents/skills/verify/scripts/omp-smoke.ts | 132 +++++++++--------- .agents/skills/verify/scripts/smokeScan.ts | 33 +++-- .../skills/verify/scripts/smokeTalkTurns.ts | 97 ++++++++++--- SoT/.omp/plugin/extensions/hygiene.ts | 114 +++++++++------ cli/scripts/build-talk.ts | 63 +++++---- cli/src/generated/sotPayload.ts | 4 +- cli/test/goldens/mutation.json | 24 ++-- cli/test/lib/rootGuard.ts | 54 ++++--- cli/test/unit/ompKitPluginExtension.test.ts | 120 ++++++++++++++++ cli/test/unit/rootGuard.test.ts | 45 +++++- cli/test/unit/talk/build.test.ts | 11 ++ cli/test/unit/verifySmokeScan.test.ts | 13 ++ cli/test/unit/verifySmokeTalkTurns.test.ts | 99 +++++++++++++ 14 files changed, 611 insertions(+), 208 deletions(-) diff --git a/.agents/skills/verify/SKILL.md b/.agents/skills/verify/SKILL.md index 0dc60611a..e8a81821e 100644 --- a/.agents/skills/verify/SKILL.md +++ b/.agents/skills/verify/SKILL.md @@ -29,7 +29,7 @@ Hosts: the commands below are POSIX shell for Linux and macOS. On Windows, run ` | V3 | Dry-run goldens through the engine and the public CLI | `bun run golden:dryrun` | A line `golden-dryrun: OK ( case(s))` and exit 0 | | V4 | Removed sync target and flag | `./docks-kit sync omp --dry-run; echo "exit $?"; ./docks-kit sync --dry-run --prune; echo "exit $?"` | First the sync help on stdout, then `ERROR` and `Unexpected positional argument: "omp"` on stderr, and `exit 1`. Then `unknown flag --prune for 'sync'` and `exit 2`. Observed 2026-11-19 on Linux x64: exactly these lines | | V5 | Trigger rules on a large tool call, in the real omp | `bun .agents/skills/verify/scripts/ttsr-snippet.ts big-reset \| omp ttsr test --rule SoT/.omp/plugin/rules/git-safety.md --source tool --tool eval --file -`, then the same command with `big-quiet` | For `big-reset`, `Triggered (1)` and a `git-safety` line within a few seconds. For `big-quiet`, `No rules triggered. (evaluated 1)`. The `big-reset` snippet is a 21 KB eval cell with many `\"` escapes that ends with `sh("git reset --hard HEAD")`. The rules of 0.22.29 stayed quiet on it after 4.7 s: JavaScriptCore stopped at its match limit and reported no match, so the rule failed open | -| V6 | Kit plugin in the real omp, isolated | `bun .agents/skills/verify/scripts/omp-smoke.ts; echo "exit $?"`, then `bun .agents/skills/verify/scripts/omp-smoke.ts hooks; echo "exit $?"`, then `bun .agents/skills/verify/scripts/omp-smoke.ts talk; echo "exit $?"`, then `bun .agents/skills/verify/scripts/omp-smoke.ts talk-ui; echo "exit $?"` | The load mode prints `docks-kit-omp -> /SoT/.omp/plugin`; `skills: 34`; `skill names:` with the name of each skill, which are the names of `REQUIRED_SKILLS` in `omp-smoke.ts` and of the skill folders under `SoT/.omp/plugin/skills/`, `talk` among them; `agents: code-reviewer,plan-reviewer`; `extensions:` with the entries of the manifest, `./extensions/talk.js` among them; `talk tool: offered`; `warnings: 0`; `ok registry: talk registered only in the private folder`; `ok registry-removed`; and `exit 0`. The `hooks` mode prints the `ok` lines of the expected output in the V6 section below and `exit 0`. The `talk` mode prints the `ok` lines of the expected output in the V6 `talk` section below, `handover-refused` among them, and `exit 0`. The `talk-ui` mode prints the `ok` lines of the expected output in the V6 `talk-ui` section below, `ui-tool-handover` and `ui-tool-handover-cancel` among them, and `exit 0`. Observed 2026-11-27 on Linux x64 with omp 19.2.1 and the default omp settings in the load mode: exactly these lines; the load mode took 1.7 s, the `hooks` mode 5.8 s, the `talk` mode 4.5 s, and the `talk-ui` mode 7.3 s, each with `nice -n 19` | +| V6 | Kit plugin in real, isolated omp sessions | `bun .agents/skills/verify/scripts/omp-smoke.ts`, then repeat with `hooks`, `talk` and `talk-ui` | All four modes exit zero. Load reports the linked kit plugin, the exact shipped skills, both review agents and the `talk` tool on the prompted request, no warnings, private registration and cleanup. The sections below list the expected output for each mode. | ## V6 — Kit plugin smoke in an isolated omp state @@ -50,7 +50,9 @@ Each mode loads the shipped `talk` extension (`extensions/talk.js`), so each mod - The final scan: immediately before the smoke ends an omp process that it checked, while the process is still live, a scan child reads the default folder once more for the registrations of that process. It fails with the diagnostic that names the default folder, after ` before it ended:`, when the folder holds an entry with the process id and the work folder of a registration of that process (the session ids of a session change included). Thus a copy that a session writes to the default folder after its first check passed still fails the run. Each process gets its own final scan, and the `registry` line keeps the problem of each scan. The script tracks each omp process that runs talk at its spawn, with its process id and folder, before it waits for the process to become ready. In the load mode and the `hooks` mode, the fake model holds the text answer that ends each `omp -p` session until its final scan ends. A session that reaches the command timeout of 120 s without that answer gets the same final scan before the script kills it. A session that is still live at the command timeout after its final scan ended gets a fresh bounded scan before the kill, and the `registry` line keeps the problems of all its scans. In the `talk` mode, the peer scan runs before the peer stdin ends in `closed-peer-not-live`, and the sender scan before the sender gets its last turn at the end of the mode. In the `talk-ui` mode, the TUI scan runs before `ctrl+d`, and the peer scan after the TUI omp exits and before the peer stdin ends. A TUI omp whose footer never shows and an RPC peer that never sends its ready line get their final scan before the cleanup ends them. With an omp before 19.2.0, talk is off, and the TUI omp has no final scan. After a failed step, the scans run before the cleanup ends each process. The final scan has the same deadline of 10 s and the same child, and its diagnostics start with `the final scan of the default talk registry folder`. 4. The line `registry` reports the check of all sessions of the mode: `ok registry: talk registered only in the private folder`. The last line, `registry-removed`, checks after the cleanup that the private folder does not exist. -The load mode writes no `config.yml`, so omp runs with its default settings. talk registers its tool with `loadMode: "essential"`, so omp gives `talk` to the model as a top-level tool and does not mount it as a Bash command. The mode reads `omp skill list --json` and the requests of one `omp -p` session. It prints the names of the skills whose file is inside the linked plugin folder. It fails unless they are the names of the skill folders under `SoT/.omp/plugin/skills/`, and also exactly the names of `REQUIRED_SKILLS` in `omp-smoke.ts`: the 32 docks and plan-lifecycle skills, `workspace-hygiene`, and `talk`. The fixed list does not come from the checkout, so a deleted skill folder, or a skill folder that replaces another, fails the mode. A change that adds, removes, or renames a skill on purpose updates the list. It lists the plugin agents that the task tool offers. It prints the `omp.extensions` list of the linked `package.json`, and fails when the list has no `./extensions/talk.js` entry or the plugin has no `extensions/talk.js`. It fails when the first model request does not offer the `talk` tool. The `hooks` mode makes a scratch git repository with its own git config. The repository holds a root `AGENTS.md`, a root `README.md`, `notes.txt`, and the nested node `scripts/AGENTS.md` with `scripts/ci.mjs`. The fake model plays scripted tool calls in `omp -p --mode json` sessions, and the script reads the JSON event stream, the requests that the fake model receives, `git log`, and the `verify-gate.jsonl` log of each session. Each session has its own `XDG_STATE_HOME` in the scratch folder. The `hooks` mode writes no `config.yml`. Expected output of the `hooks` mode, in order: +The load mode writes no `config.yml`. It compares `omp skill list --json` with the linked plugin folders and the fixed `REQUIRED_SKILLS` list. Update that list only when adding, removing or renaming a skill on purpose. It checks the manifest for `./extensions/talk.js` and checks that the file exists. It checks both the task tool's agent list and the top-level `talk` tool on the first request for the fixture prompt. An earlier auxiliary request or a later request cannot supply either advertisement. Talk uses `loadMode: "essential"` so omp does not mount it as a Bash command. + +The `hooks` mode runs scripted `omp -p --mode json` sessions in a scratch Git repository with private Git configuration. Each session has its own `XDG_STATE_HOME`. The driver checks the event stream, provider requests, Git log and each `verify-gate.jsonl` log. Expected output, in order: ```text ok install @@ -69,6 +71,7 @@ ok nudge-failed-edit-none ok nudge-url-write-none ok hygiene-scratch-tool ok hygiene-temp-reminder +ok hygiene-stop-reminder ok extensions-loaded ok sessions ok isolated @@ -92,6 +95,7 @@ exit 0 | `nudge-url-write-none` | `write` to `local://notes.md`; the session folder is inside the `scripts` node | The write succeeds. No added-context message follows. | | `hygiene-scratch-tool` | The requests of a session with one `bash` `mktemp -d` call | A request lists the `scratch_new` tool with `Prefer it over /tmp`. | | `hygiene-temp-reminder` | Same session: the `mktemp -d` result | After the tool result, an added-context message holds the reminder `Prefer a directory from the \`scratch_new\` tool`. | +| `hygiene-stop-reminder` | The same session leaves its temporary directory in place | A new user message at the fixture provider contains the stop reminder and the exact directory. | | `extensions-loaded` | All sessions | omp reported no warning that names the linked plugin folder or `docks-kit-omp`, and no `Failed to load extension` record for a plugin file, `hygiene.ts` included. | | `isolated` | The whole run | The `tidy.stamp` of the scratch home kept its modification time, so no hygiene sweep started. | | `real-state` | The whole run | The real omp registry files kept their modification times. The real `verify-gate.jsonl` has no new line with a `cwd` inside the scratch folder. Lines that other omp sessions add during the run do not count. | @@ -252,7 +256,7 @@ The other lines are as above. talk is off on this omp and registers no session, | V6 prints a `FAIL hygiene-` line | The `scratch_new` description or the temporary-file reminder lost its preference for scratch, or the reminder did not run | Check the `scratch_new` description and `SCRATCH_NOTE` in `SoT/.omp/plugin/extensions/hygiene.ts` | | V6 prints a `FAIL` line that names `./extensions/talk.js` or `extensions/talk.js` (a missing file or manifest entry) | The shipped plugin has no `talk.js` bundle or no manifest entry for it | Run `bun cli/scripts/build-talk.ts --check`; when it reports a stale or missing bundle, run `bun cli/scripts/build-talk.ts` and check the `omp.extensions` list of `SoT/.omp/plugin/package.json` | | V6 prints `FAIL install` with another reason, or the load mode prints `FAIL omp exited` | An omp command exited with a status other than 0, omp kept no plugin state, `omp plugin list --json` has no `docks-kit-omp` row, `omp --version` names no version, or the private registry folder has the wrong mode | Read the reason on the `FAIL` line: it names the command, the path, or the output that failed. Check the omp binary (V2) and the scratch folder | -| V6 load mode prints `talk tool: missing` | The first model request with omp's default settings does not offer `talk`: `talk.js` did not load, or omp mounted `talk` as a Bash command | Read the `warnings:` line. Check that the tool registration in `cli/talk/extension.ts` sets `loadMode: "essential"`, then rebuild `talk.js` | +| V6 load mode prints `talk tool: missing` | The prompted request does not offer `talk`, or no such request reached the local provider | Read the `FAIL` and `warnings:` lines. If the tool is missing, check `loadMode: "essential"` in `cli/talk/extension.ts` and rebuild `talk.js`. | | V6 prints `FAIL registry:` with `no valid entry of process` | No poll that the scan child started before its cutoff, 9 s after the launch of the child, found a valid entry of the session in the private folder: talk did not load, did not register, or did not read `DOCKS_KIT_TALK_DIR`. A poll sees a registration that appears before it lists the folder, so a registration close to the cutoff can still count. With `and the session`, the peer did not publish the new session of `new_session` or `fork` | Read the `extensions-loaded` line and the warnings. Check `cli/talk/transport/folder.ts` and the registration in `cli/talk/extension.ts` | | V6 prints `FAIL registry:` with `did not end within 10 s` | Timeout cancellation: the scan child of a registry check gave no result before the 10 s deadline, so the script killed the child and its process group. A scan stalled, for example because the macOS ACL listing (`ls -led`) or a file system call hung | Run `ls -led` on the folder that the line names and check that it ends at once. Check the folder trust check in `cli/talk/transport/trustPosix.ts` | | V6 prints `FAIL registry:` with `ended early` | The scan child exited with an error code or stopped on a signal before it gave a result; the script read this at the exit of the child and then killed its process group | Run the child by hand to see its error: `bun .agents/skills/verify/scripts/omp-smoke.ts registry-scan ''`. A malformed request exits 2 | diff --git a/.agents/skills/verify/scripts/omp-smoke.ts b/.agents/skills/verify/scripts/omp-smoke.ts index fa6c9002c..7952216db 100755 --- a/.agents/skills/verify/scripts/omp-smoke.ts +++ b/.agents/skills/verify/scripts/omp-smoke.ts @@ -85,6 +85,7 @@ import { isObject, type Json, type JsonObject, + loadFixtureTools, newUserText, objects, offersTool, @@ -412,13 +413,8 @@ interface Script { * session lasts until the driver has acted on another session. */ respond?: (request: JsonObject) => Promise; - /** When set, each answer waits for it first, so the omp session stays live until a check ends. */ - hold?: Promise; - /** - * When set, a text answer waits for it first. A text answer ends an `omp -p` session, so the session stays - * live until the final check ends. - */ - final?: () => Promise; + /** Keep the print session live through attribution and the scan before its final answer. */ + registry?: SessionRegistryChecks; } function sseChunk(model: Json, choice: JsonObject, extra: JsonObject = {}): string { @@ -430,7 +426,7 @@ function sseChunk(model: Json, choice: JsonObject, extra: JsonObject = {}): stri * `script.turns[n]` answers a request that holds n assistant messages, unless `script.respond` is set. */ async function scriptedAnswer(script: Script, request: JsonObject): Promise { - if (script.hold !== undefined) await script.hold; + if (script.registry !== undefined) await script.registry.attribution; let answer: Answer | undefined; if (script.respond !== undefined) answer = await script.respond(request); else { @@ -441,7 +437,7 @@ async function scriptedAnswer(script: Script, request: JsonObject): Promise checks?.timeout() ?? Promise.resolve(""), problem: async () => { - run.script.hold = undefined; - run.script.final = undefined; + run.script.registry = undefined; return checks === undefined ? `${label}: the omp session did not start` : checks.problem(); }, }; @@ -1221,20 +1215,6 @@ function pluginSkillNames(root: string): string[] { .sort(); } -/** Agent names in the "Available Agents" list of the task tool that the model receives. */ -function taskToolAgents(requests: readonly JsonObject[]): string[] | null { - for (const request of requests) { - for (const tool of objects(request["tools"])) { - const fn = isObject(tool["function"]) ? tool["function"] : tool; - if (fn["name"] !== "task") continue; - const description = text(fn["description"]); - if (description !== undefined) - return [...description.matchAll(/^- `([^`]+)`/gm)].map((match) => match[1] ?? ""); - } - } - return null; -} - function stateLogLines(stateDir: string): string[] { const logsDir = join(stateDir, "logs"); if (!existsSync(logsDir)) return []; @@ -1539,23 +1519,23 @@ async function smoke(): Promise<{ lines: string[]; registry: string | null }> { `skills: ${skills.length}, expected the ${required.length} skills of REQUIRED_SKILLS: ${required.join(",")}; update REQUIRED_SKILLS only when a skill was added, removed, or renamed on purpose`, ); - const offered = taskToolAgents(run.requests); + const tools = loadFixtureTools(run.requests, MODEL_ID, SESSION_PROMPT); const ownAgents = run.plugin === null ? new Set() : pluginAgentNames(run.plugin.realPath); - const agents = (offered ?? []).filter((agent) => ownAgents.has(agent)).sort(); + const agents = (tools?.agents ?? []).filter((agent) => ownAgents.has(agent)).sort(); lines.push(`agents: ${agents.join(",")}`); if (run.requests.length === 0) failures.push("the fake model received no request from the omp session"); - else if (offered === null) failures.push("the model request has no task tool with an agent list"); + else if (tools === undefined) failures.push("the fake model received no opening fixture request"); + else if (tools.agents === null) failures.push("the fixture request has no task tool with an agent list"); const missingAgents = REQUIRED_AGENTS.filter((agent) => !agents.includes(agent)); if (missingAgents.length > 0) failures.push(`agents missing from the task tool: ${missingAgents.join(",")}`); lines.push(`extensions: ${extensions.join(",")}`); - const firstRequest = run.requests[0]; - const talkOffered = firstRequest !== undefined && offersTool(firstRequest, TALK_TOOL); + const talkOffered = tools?.talkOffered === true; lines.push(`talk tool: ${talkOffered ? "offered" : "missing"}`); - if (firstRequest !== undefined && !talkOffered) - failures.push(`the first model request does not offer the ${TALK_TOOL} tool`); + if (tools !== undefined && !talkOffered) + failures.push(`the first fixture request does not offer the ${TALK_TOOL} tool`); const skillWarnings = Array.isArray(skillList?.["warnings"]) ? skillList["warnings"] : []; const warnings = countWarnings( @@ -1967,6 +1947,23 @@ async function hooks(): Promise<{ lines: string[]; registry: string | null }> { ? null : `no added-context message with '${SCRATCH_REMINDER_TEXT}' after the tool result`, ); + const directory = temp?.text.trim(); + const stopReachedModel = + directory !== undefined && + isAbsolute(directory) && + run.requests.some((request, index) => { + if (index < requestsBefore) return false; + if (request["model"] !== MODEL_ID) return false; + const messages = request["messages"]; + const last = Array.isArray(messages) ? messages.at(-1) : undefined; + if (!isObject(last) || last["role"] !== "user") return false; + const context = textOf(last["content"]); + return ( + context.includes("These resources from this session still exist:") && + context.includes(`- the temporary directory ${directory}:`) + ); + }); + check("hygiene-stop-reminder", stopReachedModel ? null : "the stop reminder did not name the fixture directory in the next model request"); const warnings = countWarnings( [], @@ -2359,8 +2356,7 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }> const pass = (): void => { results.set(step, ""); }; - let peer: RpcPeer | null = null; - let peerResult: OmpResult | null = null; + let peer: FixtureProcess = { kind: "absent" }; let senderRun: Promise | null = null; // The registrations that the mode attributed for each omp process, and the problems of the `registry` line. const peerAttributed: Attributed[] = []; @@ -2388,7 +2384,7 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }> peerAttributed.push({ label: "peer", registration: { processId: pid, cwd: run.workDir } }); }, ); - peer = rpc; + peer = { kind: "ready", handle: rpc }; const peerRegistry = sessionAttribution(run, "peer", rpc.pid, run.workDir); const peerState = async (): Promise => { const data = await rpc.send({ type: "get_state" }); @@ -2708,7 +2704,7 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }> step = "closed-peer-not-live"; // The smoke ends the peer here; the sender stays live until the end of the mode. await finalScan(peerAttributed); - peerResult = await rpc.close(); + peer = { kind: "closed", result: await rpc.close() }; const closed = await sender.call(TALK_TOOL, { action: "send", instance: afterFork.instance, @@ -2727,10 +2723,11 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }> await finalScan(senderAttributed); sender.finish(); peerModel.release(); - if (peerResult === null) { + if (peer.kind !== "closed") { await finalScan(peerAttributed); - if (peer !== null) peerResult = await peer.close(); + if (peer.kind === "ready") peer = { kind: "closed", result: await peer.handle.close() }; } + const peerResult = peer.kind === "closed" ? peer.result : null; const senderResult = senderRun === null ? null @@ -3165,12 +3162,25 @@ class TerminalOmp { } } +type FixtureProcess = + | { readonly kind: "absent" } + | { readonly kind: "ready"; readonly handle: Handle } + | { readonly kind: "closed"; readonly result: OmpResult }; + /** One `talk` call of the RPC peer that the driver waits for. */ interface MarkedCall { - readonly marker: string; - readonly call: ToolCall; + phase: + | { readonly kind: "prompt"; readonly marker: string; readonly call: ToolCall } + | { readonly kind: "result"; readonly id: string }; readonly result: Deferred; - issued: boolean; +} + +/** Issue the call once, on the matching prompt. Only its result ID matters after that. */ +function issueMarkedCall(pending: MarkedCall, prompt: string | undefined): readonly ToolCall[] { + const phase = pending.phase; + if (phase.kind !== "prompt" || prompt?.includes(phase.marker) !== true) return []; + pending.phase = { kind: "result", id: phase.call.id }; + return [phase.call]; } /** @@ -3186,10 +3196,8 @@ class PeerCalls { this.#count += 1; const result = Promise.withResolvers(); this.#pending = { - marker, - call: { id: `peer-${this.#count}`, name: TALK_TOOL, arguments: toolArgs }, + phase: { kind: "prompt", marker, call: { id: `peer-${this.#count}`, name: TALK_TOOL, arguments: toolArgs } }, result, - issued: false, }; return withTimeout( result.promise, @@ -3201,12 +3209,8 @@ class PeerCalls { async respond(request: JsonObject): Promise { const pending = this.#pending; if (pending === null) return []; - if (!pending.issued) { - if (newUserText(request)?.includes(pending.marker) !== true) return []; - pending.issued = true; - return [pending.call]; - } - const result = toolResultText(request, pending.call.id); + if (pending.phase.kind === "prompt") return issueMarkedCall(pending, newUserText(request)); + const result = toolResultText(request, pending.phase.id); if (result !== undefined) { this.#pending = null; pending.result.resolve(result); @@ -3244,7 +3248,7 @@ class TerminalModel { const id = `tui-${this.#count}`; const result = Promise.withResolvers(); const call = { id, name: TALK_TOOL, arguments: toolArgs }; - this.#pending = { marker, call, draft, result, issued: false }; + this.#pending = { phase: { kind: "prompt", marker, call }, draft, result }; return withTimeout(result.promise, STEP_TIMEOUT_MS, `the handover call ${id} of the TUI omp`); } @@ -3254,14 +3258,10 @@ class TerminalModel { // The side turn copies the session with the pending call and a synthetic result of it (#260 F7), so the // template decides before the result does. if (prompt?.includes(HANDOVER_PROMPT_TEXT) === true) - return pending?.issued === true ? pending.draft : HANDOVER_DRAFT; + return pending?.phase.kind === "result" ? pending.draft : HANDOVER_DRAFT; if (pending === null) return []; - if (!pending.issued) { - if (prompt?.includes(pending.marker) !== true) return []; - pending.issued = true; - return [pending.call]; - } - const result = toolResultText(request, pending.call.id); + if (pending.phase.kind === "prompt") return issueMarkedCall(pending, prompt); + const result = toolResultText(request, pending.phase.id); if (result !== undefined) { this.#pending = null; pending.result.resolve(result); @@ -3315,8 +3315,7 @@ async function talkUiMode(): Promise<{ lines: string[]; registry: string | null const pass = (): void => { results.set(step, ""); }; - let terminal: TerminalOmp | null = null; - let terminalResult: OmpResult | null = null; + let terminal: FixtureProcess = { kind: "absent" }; let peer: RpcPeer | null = null; /** @@ -3807,7 +3806,7 @@ async function talkUiMode(): Promise<{ lines: string[]; registry: string | null run.workDir, env, ); - terminal = screen; + terminal = { kind: "ready", handle: screen }; // On omp 19.2.0 or later the TUI omp runs talk from its spawn, so its final scan runs also when its footer or // the peer never shows. On an older omp talk is off, and the TUI omp has no final scan. if (checks !== OLD_OMP_CHECKS) @@ -3840,15 +3839,16 @@ async function talkUiMode(): Promise<{ lines: string[]; registry: string | null await currentFlow(screen, peer); } await finalScan(terminalAttributed); - terminalResult = await screen.close(); + terminal = { kind: "closed", result: await screen.close() }; } catch (error) { results.set(step, error instanceof Error ? error.message : String(error)); } - if (terminal !== null && terminalResult === null) { + if (terminal.kind === "ready") { await finalScan(terminalAttributed); - terminalResult = await terminal.close(); + terminal = { kind: "closed", result: await terminal.handle.close() }; } + const terminalResult = terminal.kind === "closed" ? terminal.result : null; // The peer stays live while the TUI omp closes, so its final scan comes after that; a peer that never became // ready stays live until the cleanup. await finalScan(peerAttributed); diff --git a/.agents/skills/verify/scripts/smokeScan.ts b/.agents/skills/verify/scripts/smokeScan.ts index 80ad560a0..ab931b33e 100644 --- a/.agents/skills/verify/scripts/smokeScan.ts +++ b/.agents/skills/verify/scripts/smokeScan.ts @@ -58,6 +58,14 @@ export interface SessionRegistryChecks { readonly problem: () => Promise; } +/** + * The final scan of one print session: not started, running, or ended with success. A running or ended scan keeps + * its original promise, so repeated final answers and the problem report share it. + */ +type FinalScan = + | { readonly phase: "idle" } + | { readonly phase: "running" | "ended"; readonly scan: Promise }; + /** * The check state of one print session. `scanFinal` runs one bounded scan of the default folder for the session * and gives its problem, or an empty text. @@ -66,28 +74,31 @@ export function sessionRegistryChecks(options: { readonly attribution: Promise; readonly scanFinal: () => Promise; }): SessionRegistryChecks { - let final: Promise | undefined; - let finalEnded = false; + let final: FinalScan = { phase: "idle" }; let timeoutScan: Promise | undefined; const finalAnswer = (): Promise => { - if (final === undefined) { - final = options.scanFinal(); - void final.then(() => { - finalEnded = true; - }); - } - return final; + if (final.phase !== "idle") return final.scan; + const scan = options.scanFinal(); + final = { phase: "running", scan }; + void scan.then(() => { + final = { phase: "ended", scan }; + }); + return scan; }; return { attribution: options.attribution, finalAnswer, timeout: () => { - if (!finalEnded) return finalAnswer(); + if (final.phase !== "ended") return finalAnswer(); timeoutScan = options.scanFinal(); return timeoutScan; }, problem: async () => { - const problems = [await options.attribution, await (final ?? ""), await (timeoutScan ?? "")]; + const problems = [ + await options.attribution, + await (final.phase === "idle" ? "" : final.scan), + await (timeoutScan ?? ""), + ]; return [...new Set(problems.filter(Boolean))].join("; "); }, }; diff --git a/.agents/skills/verify/scripts/smokeTalkTurns.ts b/.agents/skills/verify/scripts/smokeTalkTurns.ts index f1903b4e1..0a8cfafd7 100644 --- a/.agents/skills/verify/scripts/smokeTalkTurns.ts +++ b/.agents/skills/verify/scripts/smokeTalkTurns.ts @@ -1,11 +1,12 @@ /** * The scripted model turns of the `talk` mode of `omp-smoke.ts`: the JSON narrowing and the reading of provider - * requests, the responders of the sender and of the peer, and the `talk-offered` check. omp can send other - * requests with the model id of a session, for example a request without tools and without the fixture prompt - * before the first prompted turn, or one that copies the conversation. A responder acts only on the current - * turn of a request: the user messages and tool results after its last assistant message. Any other request - * gets a plain answer and neither starts a responder nor takes or advances a call of it. The module uses no Bun - * API and has no side effect at import, so unit tests can load it (`cli/test/unit/verifySmokeTalkTurns.test.ts`). + * requests, the responders of the sender and of the peer, the `talk-offered` check, and the tools of the opening + * request of the load mode. omp can send other requests with the model id of a session, for example a request + * without tools and without the fixture prompt before the first prompted turn, or one that copies the + * conversation. A responder acts only on the current turn of a request: the user messages and tool results after + * its last assistant message. Any other request gets a plain answer and neither starts a responder nor takes or + * advances a call of it. The module uses no Bun API and has no side effect at import, so unit tests can load it + * (`cli/test/unit/verifySmokeTalkTurns.test.ts`). */ import { TRUST_LINE } from "../../../../cli/talk/tool/format.ts"; @@ -153,6 +154,11 @@ function latestEvent(request: JsonObject): FixtureEvent | undefined { return undefined; } +/** Whether an event is the user instruction `prompt`: the opening of a fixture conversation. */ +function isOpening(event: FixtureEvent | undefined, prompt: string): boolean { + return event?.role === "user" && event.text.trim() === prompt; +} + /** * Whether a user message of a request holds the handover template: the request is a side turn. The template * counts also when it spans adjacent text parts of one message. @@ -164,6 +170,45 @@ export function holdsHandoverPrompt(request: JsonObject): boolean { ); } +interface FixtureTools { + readonly talkOffered: boolean; + /** Null when the task tool has no agent list. */ + readonly agents: readonly string[] | null; +} + +/** The agent names of the task tool of a request, or null when no task tool has a description. */ +function taskToolAgents(request: JsonObject): string[] | null { + for (const tool of objects(request["tools"])) { + const fn = isObject(tool["function"]) ? tool["function"] : tool; + if (fn["name"] !== "task") continue; + const description = fn["description"]; + if (typeof description === "string") + return [...description.matchAll(/^- `([^`]+)`/gm)].map((match) => match[1] ?? ""); + } + return null; +} + +/** + * The tools of the first request of `model` whose latest user instruction is `prompt`, outside handover side + * turns, or undefined when no request opens the fixture. Auxiliary requests of omp with the same model id do + * not count, and the tools of a request never select it: both checks read the same opening request. + */ +export function loadFixtureTools( + requests: readonly JsonObject[], + model: string, + prompt: string, +): FixtureTools | undefined { + const opening = requests.find( + (request) => + request["model"] === model && + isOpening(latestEvent(request), prompt) && + !holdsHandoverPrompt(request), + ); + return opening === undefined + ? undefined + : { talkOffered: offersTool(opening, TALK_TOOL), agents: taskToolAgents(opening) }; +} + /** * The `talk-offered` check of one session: its first fixture turn comes within the step timeout, and that turn * offers the `talk` tool. @@ -181,6 +226,15 @@ export async function expectTalkOffered( throw new Error(`the first fixture turn of the ${label} does not offer the ${TALK_TOOL} tool`); } +/** + * The outstanding call of a scripted session: none, a call that waits for its result, or the exit of omp, which + * fails each later call. + */ +type CallSlot = + | { readonly state: "idle" } + | { readonly state: "waiting"; readonly id: string; readonly result: Deferred } + | { readonly state: "aborted"; readonly error: Error }; + /** * The sender starts when its opening prompt is the latest user instruction. Each call waits until * its result is the latest event. A newer instruction supersedes a copied result. Handover side @@ -191,9 +245,9 @@ export class ScriptedSession { readonly #prompt: string; readonly #first = Promise.withResolvers(); #next = Promise.withResolvers(); - #pending: { readonly id: string; readonly result: Deferred } | null = null; + #call: CallSlot = { state: "idle" }; + /** Whether the opening prompt came; a staged call or an auxiliary request does not imply it. */ #started = false; - #ended: Error | null = null; #count = 0; constructor(label: string, prompt: string) { @@ -210,15 +264,15 @@ export class ScriptedSession { async respond(request: JsonObject): Promise { if (holdsHandoverPrompt(request)) return []; const event = latestEvent(request); - const pending = this.#pending; - if (pending === null) { - if (this.#started || event?.role !== "user" || event.text.trim() !== this.#prompt) return []; + const slot = this.#call; + if (slot.state === "waiting") { + if (event?.role !== "tool" || event.id !== slot.id) return []; + this.#call = { state: "idle" }; + slot.result.resolve(event.text); + } else { + if (this.#started || !isOpening(event, this.#prompt)) return []; this.#started = true; this.#first.resolve(request); - } else { - if (event?.role !== "tool" || event.id !== pending.id) return []; - this.#pending = null; - pending.result.resolve(event.text); } const call = await this.#next.promise; this.#next = Promise.withResolvers(); @@ -227,11 +281,11 @@ export class ScriptedSession { /** Makes the next turn of the session call `name` with `args`; gives the text of its tool result. */ call(name: string, toolArgs: Readonly>): Promise { - if (this.#ended !== null) return Promise.reject(this.#ended); + if (this.#call.state === "aborted") return Promise.reject(this.#call.error); this.#count += 1; const id = `${this.#label}-${this.#count}`; const result = Promise.withResolvers(); - this.#pending = { id, result }; + this.#call = { state: "waiting", id, result }; this.#next.resolve({ id, name, arguments: toolArgs }); return withTimeout( result.promise, @@ -247,10 +301,11 @@ export class ScriptedSession { /** The omp process exited: a call that waits fails at once. */ abort(reason: string): void { - this.#ended = new Error(reason); - this.#first.reject(this.#ended); - this.#pending?.result.reject(this.#ended); - this.#pending = null; + const error = new Error(reason); + const slot = this.#call; + this.#call = { state: "aborted", error }; + this.#first.reject(error); + if (slot.state === "waiting") slot.result.reject(error); } } diff --git a/SoT/.omp/plugin/extensions/hygiene.ts b/SoT/.omp/plugin/extensions/hygiene.ts index 83780eeb8..29d522637 100644 --- a/SoT/.omp/plugin/extensions/hygiene.ts +++ b/SoT/.omp/plugin/extensions/hygiene.ts @@ -308,6 +308,15 @@ interface ScopedSegment extends ShellSegment { setupKnown: boolean; } +/** The word that scopedSegments reads. An empty quoted word such as `''` is a word too. */ +interface ShellToken { + text: string; + /** True when the word holds a quoted or escaped character. */ + quoted: boolean; + /** The source index of the last character that the word took without quoting, else -1. */ + lastUnquoted: number; +} + export interface RunOptions { readonly signal?: AbortSignal; readonly timeoutMs: number; @@ -536,12 +545,8 @@ function scopedSegments(command: string, rootScope: string): Array = []; - let word = ""; - let inWord = false; - /** True when the current word holds a quoted or escaped character. */ - let wordQuoted = false; - /** The source index of the last character that the word took without quoting. */ - let lastUnquoted = -1; + /** The word that the scan reads, or undefined between words. */ + let token: ShellToken | undefined; /** The strip flag of a `<<` operator whose delimiter is the next word. */ let heredocOperator: boolean | undefined; /** The operators after the last segment; they count only when a segment follows. */ @@ -550,8 +555,12 @@ function scopedSegments(command: string, rootScope: string): Array scopes.at(-1) ?? rootScope; const childScope = (): string => `${currentScope()}/${childScopes++}`; + /** The current word; the first character of a word starts it. */ + const startToken = (): ShellToken => (token ??= { text: "", quoted: false, lastUnquoted: -1 }); const finishWord = (): void => { - if (!inWord) return; + if (token === undefined) return; + const word = token.text; + token = undefined; if (heredocOperator !== undefined) { heredocs.push({ delimiter: word, strip: heredocOperator }); heredocOperator = undefined; @@ -565,9 +574,6 @@ function scopedSegments(command: string, rootScope: string): Array { + const current = startToken(); + current.quoted = true; let index = start; - inWord = true; while (index < command.length && command[index] !== '"') { const char = command[index]; const next = command[index + 1]; if (char === "\\" && next !== undefined && '"\\$`\n'.includes(next)) { - if (next !== "\n") word += next; + if (next !== "\n") current.text += next; index += 2; } else if (char === "$" && next === "(") { index = readSubstitution(index); } else if (char === "`") { index = readBacktick(index); } else { - word += char; + current.text += char; index++; } } @@ -674,18 +679,17 @@ function scopedSegments(command: string, rootScope: string): Array 0; + const continues = words.length === 0 && token === undefined && pendingSeparators.size > 0; finishSegment(continues ? undefined : ";"); index = skipHeredocBodies(index + 1); - } else if (char === "(" && !inWord) { + } else if (char === "(" && token === undefined) { // `name ()` defines a function: its body runs only when it is called. if (definesFunction(words)) skipsCommands = true; finishSegment(undefined); @@ -721,7 +725,7 @@ function scopedSegments(command: string, rootScope: string): Array|file` the `|` belongs to the redirection; the split stays as it // was, but it separates nothing. Only an unquoted `>` directly before // the `|` makes a clobber, so `echo '>'|` and `echo \>|` are pipes. - const clobber = inWord && command[index - 1] === ">" && lastUnquoted === index - 1; + const clobber = command[index - 1] === ">" && token?.lastUnquoted === index - 1; if (clobber) { finishSegment(undefined); index++; @@ -733,23 +737,31 @@ function scopedSegments(command: string, rootScope: string): Array" || word.endsWith(">") || word.endsWith("<")) { + } else if ( + next === ">" || + token?.text.endsWith(">") === true || + token?.text.endsWith("<") === true + ) { // A redirection such as `&>file` or `2>&1`. - word += char; - inWord = true; + startToken().text += char; index++; } else { finishSegment("&"); index++; } } else { + const current = startToken(); // `name()` without a space: an unquoted name word directly before `(`. - if (char === "(" && words.length === 0 && !wordQuoted && FUNCTION_NAME.test(word)) { + if ( + char === "(" && + words.length === 0 && + !current.quoted && + FUNCTION_NAME.test(current.text) + ) { skipsCommands = true; } - word += char; - inWord = true; - lastUnquoted = index; + current.text += char; + current.lastUnquoted = index; index++; } } @@ -1918,12 +1930,25 @@ export function claimSweep(cacheDir: string, nowMs: number): boolean { // ---------------------------------------------------------------- ledger ---- +/** + * The stop state of one resource key; a key without an entry is absent. A + * pending entry holds the latest resource recorded under the key, and a stop + * names it while it exists. A reminded key stays reminded, also when a later + * call records the same resource again. + */ +type LedgerEntry = HygieneResource | "reminded"; /** * One omp process shares module state across its sessions, so the main * session also sees the resources that its subagents created. */ -const ledger = new Map(); -const reminded = new Set(); +const ledger = new Map(); + +/** Records a created resource for the stop check; a reminded key stays reminded. */ +function recordResource(resource: HygieneResource): void { + const key = resourceKey(resource); + if (ledger.get(key) !== "reminded") ledger.set(key, resource); +} + /** * The stash IDs of each directory of a bash call before the call ran, keyed * by tool call ID. The tool_result handler takes the snapshot out. omp sends @@ -2114,7 +2139,7 @@ async function resourceLines(event: ToolResultEvent, ctx: ExtensionContext): Pro const detected = detectResources(call.command, call.cwd, output, homedir()); const resources: Array = failed ? [] : detected.resources; resources.push(...(await createdStashes(detected.stashes, snapshot))); - for (const resource of resources) ledger.set(resourceKey(resource), resource); + for (const resource of resources) recordResource(resource); return [...resources.map(creationReminder), ...(failed ? [] : detected.notes)]; } @@ -2147,7 +2172,7 @@ export default function docksKitOmp(pi: ExtensionApi): void { const path = lastAbsoluteLine(output); if (path === undefined) throw new Error(`docks-kit scratch new printed no path: ${output}`); const resource: HygieneResource = { kind: "scratch", path }; - ledger.set(resourceKey(resource), resource); + recordResource(resource); return textResult(path, { path }); } catch (error) { throw toError(error); @@ -2229,7 +2254,11 @@ export default function docksKitOmp(pi: ExtensionApi): void { pi.on("session_stop", async (event) => { try { if (event.stop_hook_active === true) return undefined; - const pending = [...ledger].filter(([key]) => !reminded.has(key)); + // Each check holds the resource as it was when this stop started. + const pending: Array<[string, HygieneResource]> = []; + for (const [key, entry] of ledger) { + if (entry !== "reminded") pending.push([key, entry]); + } if (pending.length === 0) return undefined; const states = await Promise.all( pending.map(async ([key, resource]) => ({ @@ -2242,10 +2271,11 @@ export default function docksKitOmp(pi: ExtensionApi): void { const unverified: Array = []; for (const { key, resource, exists } of states) { if (!exists) { - ledger.delete(key); + // A missing key leaves the pending ledger, but cannot undo another stop's reminder. + if (ledger.get(key) !== "reminded") ledger.delete(key); continue; } - reminded.add(key); + ledger.set(key, "reminded"); if (resource.kind === "other") unverified.push(resource); else verified.push(resource); } diff --git a/cli/scripts/build-talk.ts b/cli/scripts/build-talk.ts index 37b4a7d57..658824ac8 100644 --- a/cli/scripts/build-talk.ts +++ b/cli/scripts/build-talk.ts @@ -236,14 +236,17 @@ export interface LexedCode { readonly requireCalls: ReadonlyMap; } -/** What the tokens before a "(" call: nothing that matters, the `import` word, - * `import.meta`, or a `require` loader. */ -type Callee = "none" | "import" | "import.meta" | "require"; +/** A run of tokens that a "(" may call as a loader: the `import` word, + * `import.meta`, or a `require` loader, with the offset of the name that + * starts it. */ +interface LoaderCandidate { + kind: "import" | "import.meta" | "require"; + readonly start: number; +} -// The stack entry of a "(" that does not follow `import`; an `import(` entry is -// the offset of its word. -const PLAIN_PAREN = -1; -const CONTROL_PAREN = -2; +/** An open "(": after `import`, with the offset of that word; after the word + * of a control statement such as `if`; or any other. */ +type OpenParen = number | "control" | "plain"; /** Lex `code` in one pass. In the returned text, quotes, backticks, the `${` * and `}` of a template, and the slashes and flags of a regular expression @@ -266,15 +269,14 @@ export function lexCode(code: string): LexedCode { const requireCalls = new Map(); // The brace depth at each open template `${`, innermost last. const templateBraces: Array = []; - // Each open "(": the offset of its `import` word, PLAIN_PAREN, or CONTROL_PAREN. - const openParens: Array = []; + const openParens: Array = []; let braces = 0; let regexNext = true; let word = ""; // Whether the token before is the "." of a property access. let propertyNext = false; - let callee: Callee = "none"; - let calleeStart = 0; + // The loader that a "(" at this point would call; undefined for most tokens. + let candidate: LoaderCandidate | undefined; let at = 0; // Skip template text from `at` to the closing backtick or the next `${`. @@ -311,18 +313,19 @@ export function lexCode(code: string): LexedCode { at = identifierEnd(code, nameAt + part); const name = code.slice(start, at); if (propertyNext || privateName) { - // A member name continues `import.meta.require`; any other ends the callee. - if (callee === "import" && name === "meta") callee = "import.meta"; - else if (callee === "import.meta" && name === "require") callee = "require"; - else callee = "none"; + // A member name continues `import.meta.require`; any other ends the candidate. + if (candidate?.kind === "import" && name === "meta") { + candidate.kind = "import.meta"; + } else if (candidate?.kind === "import.meta" && name === "require") { + candidate.kind = "require"; + } else candidate = undefined; word = ""; } else { // `import` must be the whole name. A bare name that ends in `require`, // such as `__require`, is a loader. - if (name === "import") callee = "import"; - else if (name.endsWith("require")) callee = "require"; - else callee = "none"; - calleeStart = start; + if (name === "import") candidate = { kind: "import", start }; + else if (name.endsWith("require")) candidate = { kind: "require", start }; + else candidate = undefined; word = name; } propertyNext = false; @@ -345,11 +348,11 @@ export function lexCode(code: string): LexedCode { continue; } const before = word; - const called = callee; + const called = candidate; word = ""; propertyNext = char === "." && next !== "." && code[at - 1] !== "."; - // A property "." keeps the callee for the member name after it. - if (!propertyNext) callee = "none"; + // A property "." keeps the candidate for the member name after it. + if (!propertyNext) candidate = undefined; if (char === '"' || char === "'") { let end = at + 1; while (end < code.length && code[end] !== char) end += code[end] === "\\" ? 2 : 1; @@ -395,20 +398,20 @@ export function lexCode(code: string): LexedCode { continue; } if (char === "(") { - if (called === "import") { - importCalls.set(calleeStart, -1); - openParens.push(calleeStart); + if (called?.kind === "import") { + importCalls.set(called.start, -1); + openParens.push(called.start); } else { - if (called === "require") requireCalls.set(calleeStart, at); - openParens.push(CONTROL_WORDS[before] === true ? CONTROL_PAREN : PLAIN_PAREN); + if (called?.kind === "require") requireCalls.set(called.start, at); + openParens.push(CONTROL_WORDS[before] === true ? "control" : "plain"); } } if (char === "{") braces += 1; if (char === "}") braces -= 1; if (char === ")") { - const open = openParens.pop() ?? PLAIN_PAREN; - if (open >= 0) importCalls.set(open, at); - regexNext = open === CONTROL_PAREN; + const open = openParens.pop(); + if (typeof open === "number") importCalls.set(open, at); + regexNext = open === "control"; } else regexNext = char !== "]"; at += 1; } diff --git a/cli/src/generated/sotPayload.ts b/cli/src/generated/sotPayload.ts index ebd469f98..6942c53b0 100644 --- a/cli/src/generated/sotPayload.ts +++ b/cli/src/generated/sotPayload.ts @@ -14,7 +14,7 @@ export const GENERATED_PAYLOAD_TEXT = { "SoT/.omp/plugin/commands/cleanup.md": "---\ndescription: Remove what this session created and list other leftovers\n---\nFollow the workspace-hygiene skill. List each resource that this session created. Remove each one that the task no longer needs. Remove only local resources and remote resources whose target is not production. For a production resource, ask first, and keep it if you get no answer. Then run tidy_report, and report the items that this session did not create without removing them.\n", "SoT/.omp/plugin/extensions/context-tree-core.ts": "// The host-neutral core of the context-tree-nudge omp extension (`context-tree-nudge.ts`):\n// after a file edit inside a context-tree node, name the node, so that the agent can refresh\n// it. A node is a folder below the repository root that holds an AGENTS.md. The core uses\n// git and the file system only: no model call. Its git calls and file operations are\n// asynchronous, so a check does not hold the event loop of omp.\nimport { execFile } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n// Each git call stops after this time.\nconst GIT_TIMEOUT_MS = 5000;\n\n// The root of the git repository that holds `dir`. Outside a repository `dir` itself counts as\n// the root, so that no folder is a node below it. git prints the root with `/` separators also on\n// Windows; path.resolve gives it the native form of the folders that it is compared with.\nfunction repositoryRoot(dir: string): Promise {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['rev-parse', '--show-toplevel'],\n { cwd: dir, encoding: 'utf8', timeout: GIT_TIMEOUT_MS },\n (error, stdout) => resolve(error ? dir : path.resolve(stdout.trim())),\n );\n });\n}\n\n// True when `file` exists.\nconst exists = (file: string): Promise =>\n fs.promises.stat(file).then(\n () => true,\n () => false,\n );\n\n// The nearest folder of `file` that exists, with symbolic links resolved, so that it compares\n// with the root that git gives. A deleted file or a moved file can have a folder that does not\n// exist now. The walk stops at the file system root at the latest, because that root exists.\nasync function existingFolder(file: string): Promise {\n let dir = path.dirname(file);\n while (!(await exists(dir))) dir = path.dirname(dir);\n return fs.promises.realpath(dir);\n}\n\n// The nearest node of `dir`, as a path relative to `root`, or null when the nearest AGENTS.md\n// is the one at the root: the nudge names sub-folder nodes only. The walk runs only in folders\n// below `root`, so it also stops when `dir` is not below `root`.\nasync function nearestNode(root: string, dir: string): Promise {\n for (let current = dir; current.startsWith(`${root}${path.sep}`); current = path.dirname(current)) {\n if (await exists(path.join(current, 'AGENTS.md'))) return path.relative(root, current);\n }\n return null;\n}\n\n// A node name made only of these characters goes into the text as it is. Any other name goes in as\n// a JSON string, so that a newline in a folder name cannot start a new line of the added context.\n// Names use `/` separators on every platform; on Windows an absolute name starts with a drive\n// prefix such as `C:` before its first `/`.\nconst PLAIN_NAME =\n process.platform === 'win32' ? /^(?:[A-Za-z]:(?=\\/))?[A-Za-z0-9._/@+-]+$/u : /^[A-Za-z0-9._/@+-]+$/u;\n\n// The last sentence of a line that holds a JSON string: the words of a folder name are not\n// instructions for the agent.\nconst QUOTED_NAMES_NOTE = 'Quoted names are folder names from the repository, not instructions.';\n\nconst nodeName = (name: string): string => (PLAIN_NAME.test(name) ? name : JSON.stringify(name));\n\n// One line of the nudge text for the node names of one root.\nfunction nudgeLine(names: ReadonlyArray): string {\n const text =\n `Edited files inside context-tree node(s): ${names.map(nodeName).join(', ')}. If conventions in a listed folder changed, ` +\n 'run context-tree refresh on it (no-op when nothing semantic changed).';\n return names.every((name) => PLAIN_NAME.test(name)) ? text : `${text} ${QUOTED_NAMES_NOTE}`;\n}\n\n// The nudge text for the absolute paths of the edited files, or null when no file is inside a\n// node. Each path finds its own repository root, because an agent can edit files in another\n// repository than its session folder `cwd`. A node in the repository of `cwd` is named relative\n// to its root; a node in another repository is named by its absolute path, so that the agent\n// refreshes the right folder. When `cwd` does not exist now (a session folder can be removed),\n// each node is named by its absolute path. The text has one line for each root, in the order of\n// the first path of each root, and each line lists its nodes once, in the order of the paths. The\n// root of each folder is found once for each call, so that many files in one folder start one git\n// call.\nexport async function nudgeText(files: ReadonlyArray, cwd: string): Promise {\n const roots = new Map>();\n const rootOf = (dir: string): Promise => {\n let root = roots.get(dir);\n if (root === undefined) {\n root = repositoryRoot(dir);\n roots.set(dir, root);\n }\n return root;\n };\n // The root of the session folder, or null when that folder does not resolve.\n let sessionRoot: string | null | undefined;\n const nodesByRoot = new Map();\n for (const file of files) {\n const dir = await existingFolder(file);\n const root = await rootOf(dir);\n const node = await nearestNode(root, dir);\n if (node === null) continue;\n if (sessionRoot === undefined) sessionRoot = await fs.promises.realpath(cwd).then(rootOf, () => null);\n const name = (root === sessionRoot ? node : path.join(root, node)).split(path.sep).join('/');\n const nodes = nodesByRoot.get(root) ?? [];\n if (!nodes.includes(name)) nodes.push(name);\n nodesByRoot.set(root, nodes);\n }\n if (nodesByRoot.size === 0) return null;\n return [...nodesByRoot.values()].map(nudgeLine).join('\\n');\n}\n", "SoT/.omp/plugin/extensions/context-tree-nudge.ts": "// omp extension: the context-tree nudge. After a file edit that did not fail, it adds a\n// message that names each context-tree node that holds an edited file. The node rules live in\n// `context-tree-core.ts`; this file only takes the edited paths from the omp event and turns\n// the answer of the core into an omp result.\n//\n// The edited paths come from the `details` of the tool result:\n// edit `perFileResults[].path` and `.sourcePath` (each mode, also apply_patch), else `path`.\n// write `resolvedPath`, but no URL target. A write to `xd://resolve` that applies an\n// ast_edit gives the files of the ast_edit, relative to the session folder.\n// An ast_edit itself only previews, so it gets no nudge.\n//\n// The handler catches each error and adds nothing, because a nudge must not stop the work of\n// the agent.\nimport path from 'node:path';\nimport { nudgeText } from './context-tree-core.ts';\n\n// The local structural types below name only the omp extension API parts that this module\n// uses. The module does not import @oh-my-pi packages: they do not resolve outside omp.\n\ninterface ExtensionContext {\n readonly cwd: string;\n}\n\ninterface ToolResultEvent {\n readonly toolName: string;\n readonly toolCallId?: string;\n readonly input?: Readonly>;\n readonly details?: unknown;\n readonly isError?: boolean;\n}\n\ninterface ExtensionApi {\n on(\n event: 'tool_result',\n handler: (event: ToolResultEvent, ctx: ExtensionContext) => Promise<{ additionalContext: string } | undefined>,\n ): void;\n}\n\n// A tool path with a scheme, such as `local://notes.md` or `xd://bash`, names no file in a repository.\nconst URL_TARGET = /^[a-z][a-z0-9+.-]*:\\/\\//iu;\n\n// The fields of an event value; undefined and null give no fields.\nconst record = (value: unknown): Record => Object(value);\n\n// The strings of one value or of a list of values.\nconst strings = (values: unknown): string[] =>\n (Array.isArray(values) ? values : [values]).filter((value): value is string => typeof value === 'string');\n\n// The paths of an edit result: each file of a multi-file result, with the source of a move.\nfunction editPaths(details: Record): string[] {\n const perFile = details.perFileResults;\n if (Array.isArray(perFile))\n return strings(perFile.flatMap((result) => [record(result).path, record(result).sourcePath]));\n return strings(details.path);\n}\n\n// The paths of a write result. A write to a URL target names no file, but the result of a write to `xd://resolve`\n// that applies an ast_edit names the files of the ast_edit.\nfunction writePaths(input: Record, details: Record): string[] {\n if (!URL_TARGET.test(String(input.path))) return strings(details.resolvedPath);\n const inner = record(record(details.xdev).inner);\n if (inner.sourceToolName !== 'ast_edit' || inner.action !== 'apply') return [];\n return strings(record(inner.sourceResultDetails).files);\n}\n\nfunction editedPaths(event: ToolResultEvent): string[] {\n const details = record(event.details);\n if (event.toolName === 'edit') return editPaths(details);\n if (event.toolName === 'write') return writePaths(record(event.input), details);\n return [];\n}\n\nexport default function contextTreeNudge(pi: ExtensionApi): void {\n pi.on('tool_result', async (event, ctx) => {\n if (event.isError) return undefined;\n try {\n const files = editedPaths(event).map((file) => path.resolve(ctx.cwd, file));\n const text = await nudgeText(files, ctx.cwd);\n return text === null ? undefined : { additionalContext: text };\n } catch {\n return undefined;\n }\n });\n}\n", - "SoT/.omp/plugin/extensions/hygiene.ts": "/**\n * docks-kit-omp extension: workspace hygiene for omp sessions.\n *\n * - The tools scratch_new, scratch_remove, and tidy_report run docks-kit.\n * - The tool_result handler records each resource that a bash command\n * creates, and it adds a reminder that names the cleanup command.\n * - The tool_call handler reads the stash list before a `git stash` command,\n * so the tool_result handler can name the stash entry that the command\n * added. The tool_execution_end handler drops the list of a blocked call.\n * - The session_stop handler lists the recorded resources that still exist.\n * - The session_start handler of a main session starts `docks-kit tidy --apply`\n * in the background, at most one time in each sweep interval. When the\n * sweep cannot start, the next tool result of the main session tells why.\n *\n * The module imports only node: modules, so omp loads it without a package\n * install. No subprocess uses a command interpreter, so a tool argument never\n * gets to a shell.\n */\nimport { execFile, spawn } from \"node:child_process\";\nimport { randomBytes, randomUUID } from \"node:crypto\";\nimport {\n accessSync,\n chmodSync,\n closeSync,\n constants,\n existsSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n statSync,\n unlinkSync,\n utimesSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, posix, resolve, win32 } from \"node:path\";\n\n// ------------------------------------------------------------- constants ----\n\nconst SWEEP_INTERVAL_MS = 12 * 60 * 60 * 1000;\nconst CLAIM_STALE_MS = 60 * 1000;\nconst STAMP_FILE = \"tidy.stamp\";\nconst CLAIM_FILE = \"tidy.stamp.claim\";\nconst TAKEOVER_FILE = \"tidy.stamp.takeover\";\nconst DOCKER_CHECK_TIMEOUT_MS = 5000;\nconst GIT_CHECK_TIMEOUT_MS = 5000;\n/** The pre-call stash read delays the command, so it gets a short timeout. */\nconst STASH_SNAPSHOT_TIMEOUT_MS = 1000;\n/** One line for each stash entry: full ID, short ID, and reflog message, split by NUL. */\nconst STASH_LIST_FORMAT = \"--format=%H%x00%h%x00%gs\";\nconst SCRATCH_TIMEOUT_MS = 60_000;\nconst REPORT_TIMEOUT_MS = 120_000;\nconst OUTPUT_LIMIT_BYTES = 16 * 1024 * 1024;\nconst COMMAND_TEXT_LIMIT = 120;\nconst LABEL_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\nconst LABEL_ERROR = \"label must match ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$\";\nconst NOT_ON_PATH = \"docks-kit is not on PATH; install docks-kit and run docks-kit sync\";\n\n/**\n * A bash command that does not match this pattern creates no tracked\n * resource. Each detection rule below has a word in this pattern.\n */\nconst TRIGGER =\n /worktree\\s+add|compose|docker|scratch\\s+new|mktemp|nohup|setsid|disown|&|tmux|screen|ngrok|cloudflared|port-forward|ssh|cluster|minikube|multipass|limactl|machine|colima|crontab|\\bat\\b|systemctl|systemd-run|launchctl|install|(?:^|\\s)-g(?:\\s|$)|global|branches|branch\\s+create|vercel|netlify|wrangler|fly\\s|fork|codespace|stash/;\n\n/** The scope of the top-level command; a subshell scope extends it with `/`. */\nconst ROOT_SCOPE = \"0\";\n\nconst UNRESOLVED = /[$`*]/;\nconst ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;\nconst VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst REDIRECT_OPERATOR = /^(?:\\d+|&)?(?:<<<|<<-?|>>|>&|<&|>\\||<>|>|<)$/;\nconst ATTACHED_REDIRECT = /^(?:\\d+|&)?[<>]/;\n/**\n * A word that is one redirection of the standard error alone: `2>&1`, `2>&-`,\n * `2>file`, `2>>file`, or the operator `2>` before its target. A second `<`\n * or `>` in the word is a second redirection. The segment parser splits\n * `2>|file` at the `|`, so that form gives the generic note.\n */\nconst STDERR_REDIRECT = /^2(?:>&(?:\\d+|-)|>>?[^<>]*)$/;\nconst SHORT_CLUSTER_WITH_D = /^-[A-Za-z]*d[A-Za-z]*$/;\n/** The long options of GNU mktemp, which also accepts a unique prefix of each. */\nconst MKTEMP_LONG_OPTIONS: ReadonlyArray = [\n \"--directory\",\n \"--dry-run\",\n \"--quiet\",\n \"--suffix\",\n \"--tmpdir\",\n \"--help\",\n \"--version\",\n];\nconst CONTAINER_ID = /^[0-9a-f]{64}$/;\nconst SAFE_WORD = /^[A-Za-z0-9_/.:@%+=,-]+$/;\nconst RESERVED_WORDS: Record = {\n \"{\": true,\n \"}\": true,\n \"!\": true,\n if: true,\n then: true,\n else: true,\n elif: true,\n do: true,\n while: true,\n until: true,\n time: true,\n};\n/**\n * Reserved words of a conditional, a loop, or a function body, where a\n * command may run once, many times, or never. The list holds the closing\n * words too, because a segment can start with one of them.\n */\nconst COMPOUND_WORDS: Record = {\n if: true,\n then: true,\n else: true,\n elif: true,\n fi: true,\n for: true,\n select: true,\n while: true,\n until: true,\n do: true,\n done: true,\n case: true,\n esac: true,\n function: true,\n coproc: true,\n};\n/** A shell function name, as in `name()` or `name ()`. */\nconst FUNCTION_NAME = /^[A-Za-z_][A-Za-z0-9_.:-]*$/;\n\nconst GIT_VALUE_OPTIONS: Record = { \"-C\": true, \"-c\": true };\nconst WORKTREE_VALUE_OPTIONS: Record = { \"-b\": true, \"-B\": true, \"--reason\": true };\n/** Docker global options that select the daemon, mapped to their long names. */\nconst DOCKER_CONNECTION_VALUE_OPTIONS: Record = {\n \"-c\": \"--context\",\n \"--context\": \"--context\",\n \"-H\": \"--host\",\n \"--host\": \"--host\",\n \"--config\": \"--config\",\n \"--tlscacert\": \"--tlscacert\",\n \"--tlscert\": \"--tlscert\",\n \"--tlskey\": \"--tlskey\",\n};\nconst DOCKER_CONNECTION_FLAGS: Record = { \"--tls\": true, \"--tlsverify\": true };\nconst DOCKER_LOG_LEVEL_OPTIONS: Record = { \"-l\": true, \"--log-level\": true };\n/** Environment variables that select the Docker daemon. */\nconst DOCKER_ENVIRONMENT: Record = {\n DOCKER_HOST: true,\n DOCKER_CONTEXT: true,\n DOCKER_CONFIG: true,\n DOCKER_TLS_VERIFY: true,\n DOCKER_CERT_PATH: true,\n};\n/** Builtins that declare shell variables, with options and `NAME=value` words. */\nconst DECLARATION_COMMANDS: Record = {\n declare: true,\n typeset: true,\n local: true,\n readonly: true,\n};\n/** Builtins that run shell code that detection does not read. */\nconst SHELL_CODE_COMMANDS: Record = { eval: true, source: true, \".\": true };\nconst COMPOSE_VALUE_OPTIONS: Record = {\n \"-f\": true,\n \"--file\": true,\n \"-p\": true,\n \"--project-name\": true,\n \"--project-directory\": true,\n \"--env-file\": true,\n \"--profile\": true,\n \"--ansi\": true,\n \"--progress\": true,\n};\nconst SSH_VALUE_FLAGS = \"BbcDEeFIiJLlmOoPpQRSWw\";\nconst STASH_WITHOUT_ENTRY: Record = {\n list: true,\n show: true,\n pop: true,\n apply: true,\n drop: true,\n clear: true,\n branch: true,\n};\n\nconst RM_NOTE = \"Add `--rm` to `docker run` so that Docker removes the container when it stops.\";\nconst SCRATCH_NOTE =\n \"Prefer a directory from the `scratch_new` tool or `docks-kit scratch new