Claude Code platform guards, the adversarial code-review standard, and a docs-as-code scaffold — portable across repos and stacks

Portable Claude Code platform guards plus the adversarial code-review standard. Everything here is coupled to Claude Code's own hook payloads and runtime behavior — not to any repo's tech stack, directory layout, or conventions. That is why it ships as a plugin: the knowledge is identical in every repo, so it should be maintained in one place and consumed, not re-derived.
Defects in anything here are fixed in this repo, never patched in a consuming repo — see docs/adr/0010-harness-defects-fixed-in-canon.md. Managed settings keep the plugin on, so a member cannot disable it (ADR 0143). The escape hatch for urgency is the owner's managed false: report the problem with /ywr-harness:report-issue. A local fork is never the remedy.
Managed settings register the ywrlabs marketplace and enable this plugin on every org machine (ADR 0143). It installs in the background of your next session, with no command, and loads from the session after that. That was measured in an interactive terminal session. The docs do not state the install for Desktop or VS Code, and the Desktop docs say a WSL session loads no plugins. If the prerequisite band names a missing tool, type /ywr-harness:setup and restart Claude Code.
Plugin components resolve as ywr-harness:<name>. A bare name does not resolve:
/ywr-harness:verify /ywr-harness:slice-close /ywr-harness:harness-init /ywr-harness:report-issue /ywr-harness:artifact-publish /ywr-harness:setup
Workflow({name: 'ywr-harness:adversarial-review', args: {...}})
This is enforced — manifest-gate.mjs fails on a shipped instruction that names a component bare, in either the Workflow({name: ...}) or the backticked-slash form. The gate exists because a live session found exactly that defect in shipped text while every selftest passed: the suite calls the scripts directly and never goes through the host's component registry.
| Hook | Event | Contract | ||
|---|---|---|---|---|
agent-model-warn.mjs | PreToolUse (matcher Agent) | Warn-only (ADR 0086). Speaks exactly when an Agent-tool spawn passes an explicit model naming the opus or fable family (opus, fable, or a full id such as claude-opus-5-5): the member sees a Korean banner, the model gets the harness rule (ADR 0109; the org guide carried it until v1.19, ADR 0144) — implementation and research workers run sonnet in every session, so the Agent-tool route is ywr-harness:worker with no per-call model; mechanical work runs haiku; opus · low is for review fan-out on an Opus session; any other opus/fable worker needs a demonstrable reason in the spawn's description; a per-call model overrides a pinned agent's frontmatter; ultracode does not lift the pins (ADR 0108). Never returns a permission decision, never blocks, and is silent on an omitted model — it names per-call overrides only; an unpinned type such as general-purpose spawned without a model inherits the session model, which the org guide's explicit-model rule governs, not this hook. No subagent_type is exempt: no plugin agent pins opus. The hook cannot see the session model. | ||
config-change-audit.mjs | ConfigChange | Visibility only. Surfaces mid-session permission/hook self-modification. Never blocks. | ||
directory-added-guard.mjs | DirectoryAdded | Visibility only by construction — the event carries no decision control and fires after the permission refresh. Its banner never reaches you: an /add-dir message is next-turn context for CLAUDE, an SDK register_repo_root one goes to the debug log. So it is English and tells the model that the added tree is editable and not to be assumed covered by this project's gates, which surfaces it contributes (.claude/skills, .claude/commands, .claude/agents, the two settings keys), and whether its instruction files (CLAUDE.md, .claude/CLAUDE.md, .claude/rules, CLAUDE.local.md) are in context — and asks it to tell you in one sentence (ADR 0097). It speaks on every mid-session add whose payload parses; an unusable directory gets a SCHEMA DRIFT banner instead. | ||
session-start-githooks-nudge.mjs | SessionStart | Suggest-only (ADR 0029). Speaks exactly when the work tree carries .githooks/ and this clone's core.hooksPath is unset — the state where no git hook runs and nothing else says so until slice close or CI. Names the one-line fix; never sets it. A wired clone, a repo without .githooks/, and a deliberate foreign hooksPath are all silent. | ||
session-start-model-route-guard.mjs | SessionStart (matcher `startup\ | resume\ | fork`) | Warn-only (ADR 0107, ADR 0130, ADR 0132). Speaks exactly when a setting can move a model alias to an older model, or a CLAUDE_CODE_EFFORT_LEVEL overrides every worker effort pin: an ANTHROPIC_DEFAULT_*_MODEL, a CLAUDE_CODE_SUBAGENT_MODEL or CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL (any value; the second moves every workflow agent, the model of each agent() call included), a full id in ANTHROPIC_MODEL / ANTHROPIC_DEFAULT_MODEL / a settings model, a non-empty modelOverrides, or a CLAUDE_CODE_USE_* cloud provider; or a non-empty CLAUDE_CODE_EFFORT_LEVEL, which beats an agent's frontmatter effort, a per-call Agent effort (both per the docs) and a Workflow agent() effort (measured on 2.1.295) — read from the environment and the user, project and local settings files. One Korean line naming each setting and where it is set; never model context, never a change. Silent otherwise. node session-start-model-route-guard.mjs --preflight is the environment-only half the eval runner uses to refuse a paid run (one line per finding, exit 1; preflight: clear, exit 0); it never reads the effort variable, which the runner's wrapper sets itself. |
session-start-scaffold-refresh-nudge.mjs | SessionStart | Suggest-only (ADR 0033). Speaks exactly when the work tree carries a ywr-harness scaffold whose TOOLCHAIN placements differ from the installed plugin's templates — the stale-vendor state ADR 0014 recorded as undetected. Byte comparison, EOL-insensitive (the seed .gitattributes makes CRLF/LF checkout variance legitimate); the placement map is read from init.ps1's own literals by a small lexer (anything it cannot read as a bare string constant or a literal table is EXTRACTION DRIFT), so no second copy exists to drift. Comparison is exact apart from line endings — letter case, a BOM, U+00AD and NUL all count. Names the count, the files (capped list, cap stated), and the remedy; writes nothing. Seeds are never compared; a marker-less post-commit is skipped exactly as the scaffold refuses it. The advice is DIRECTION-AWARE (ADR 0042) via the repo's .harness-version stamp (written by harness-init on every successful run): repo ahead of this install → update the plugin, harness-init forbidden; repo behind → refresh, direction stated as measured; same version → hand-edit named; no readable stamp → the direction-blind caveat on the human banner AND the model context (a canon working tree mid-slice, or a multi-writer repo refreshed by a newer plugin, is newer than the installed copy and a re-run would revert it). When the running copy is itself a superseded cache install (a session that outlived a plugin update — ADR 0039), the advice flips: same file list, but the basis is named STALE, /reload-plugins (or a restart) is instructed, and harness-init is forbidden from that session — the loaded skill would place the old templates. The registry probe is best-effort; any failure returns the normal nudge. | ||
session-start-version-announce.mjs | SessionStart | Announce-once-per-version (ADR 0030). At the first session that loads a new plugin version it says so once — old → new, up to three bullets from CHANGELOG.md (the member release-notes canon, Korean), and the onboarding artifact's release-notes tab — then records the version in ~/.claude/ywr-harness/announced-version, the plugin's only user-scope write. A machine's very first run gets a one-time link-only welcome instead (ADR 0031) — "업데이트됨" is claimed only when a previous version was recorded. Steady state and downgrades are silent; manifest-gate.mjs refuses a release whose top CHANGELOG entry does not match plugin.json. | ||
subagent-telemetry.mjs | SubagentStop | Appends a per-agent JSONL ledger to <project>/.claude/telemetry/ — documented SubagentStop fields only (no model: the event carries none). Fail-open. |
hooks.json names one entry under modules, hooks/mods.mjs, which registers two module files: the delegation ledger and the prerequisite check.
hooks/delegation-ledger.mjs is a function-hooks module (ADR 0117, ADR 0118). The host runs it in its own environment — not on node — from Claude Code 2.1.287. It hooks agent.spawn, turn.step and turn.complete and is observe-only: it passes every event on unchanged, never rewrites a model or effort, never denies and never draws. Each finished model loop (a main-loop turn, an Agent-tool subagent, a Workflow agent() worker) becomes one row in its session's file, one of a ring of twenty under <project>/.claude/telemetry/delegations/ (slot-00.json..slot-19.json): the model, effort and usage of every request, the spawn's type and per-call model when the Agent tool started it, and the loop's duration. A new session takes a free slot or the oldest one; each file keeps its session's last 500 loops within 360 KiB, so the slot files never pass ~7 MiB per repo. A workflow worker shows as loop: "unspawned"; its steps show the model it inherited. No prompt, task description or answer is written. It writes only in a repo whose root holds .harness.json. Hosts below 2.1.287, disableAllHooks, --safe-mode and --bare drop it, and the eight hooks above keep running.
hooks/prerequisites.mjs checks the three tools the plugin needs (ADR 0142): node for the eight hooks above, pwsh 7+ for the skills' scripts and the selftests, python 3.9+ for the gate scripts. A mod needs neither node nor pwsh, so it can report any of them missing. At session start it runs each tool's --version in the background, so the start never waits for it. On a missing or too-old tool it shows one Korean band above the prompt naming the tools and /ywr-harness:setup, and adds one note for Claude to the conversation (hidden from you) naming the same. It installs nothing on its own. /ywr-harness:setup is the install, and typing it is your consent: on Windows it runs winget install for each missing tool (a UAC prompt can appear), shows the progress in the status line with a warning not to press Esc (an interrupt may cut the install off part-way; unmeasured — the next session's band shows what is left), reports each result and asks you to restart Claude Code — a running session keeps its old PATH. It never claims a tool is on PATH: the next session's check is the proof, and a band that comes back means installed-but-not-found (for python, possibly the Windows Store app execution alias; unmeasured). Off Windows, or without winget, it prints the commands and runs nothing. Where a host drops the module, /ywr-harness:setup runs as an ordinary skill and Claude does the same steps.
hooks/slice-status.mjs held the slice status line of 0.67.0 (ADR 0138). Since 0.67.1 the entry does not register it, so no line shows (ADR 0140): its "run again" after every test or script run confused more than it helped. The file stays for a redesign.
workflows/adversarial-review.js — lens finders → semantic dedupe → severity-gated skeptic verification. Invoke it as a workflow, or by name from the skill listing (a workflow's meta.whenToUse is what surfaces there; there is no separate skill file).
Workflow({ name: 'ywr-harness:adversarial-review', args: { scope: {
files: [<the emitter's file list>], context: '<what the slice does>',
invariants: [<from REVIEW.md>], gates_passed: '<the gate commands and results, verbatim>' } } })
scope is an object. A string scope still runs, but it loses sharding, the out-of-scope bucket, and skeptic #2's check against gates_passed, without saying so.
Lens defaults are deliberately repo-agnostic. Two knobs keep them that way:
| arg | Effect |
|---|---|
lensExtra | A house-specific angle appended to every lens prompt. Use this for repo vocabulary — how tenancy isolation is implemented, naming rules, a particular determinism boundary. |
lenses | Full override, [{key, prompt}]. An array with no valid entry throws: zero lenses is not a review. |
Prefer lensExtra. Redefining the lens set to add one angle means later improvements to the canonical defaults never reach that repo — the same outcome as a local fork.
root is optional. When omitted the "repo root" line is dropped from the prompts entirely and agents use the session's working directory; baking one repo's absolute path in as a default would be knowledge that is false everywhere else.
The scope block cites the consuming repo's own root REVIEW.md, seeded by /ywr-harness:harness-init (ADR 0054). The plugin's REVIEW.md is the canon repo's own review invariants, not a shared canon.
/ywr-harness:harness-init places two hooks into a consuming repo and wires core.hooksPath conditionally — set when unset, left alone (byte-identical) when it already names .githooks in any spelling — the literal, ./, an absolute path, the MSYS /c/… form, a ~/ value, or a link's real target — refused when it points anywhere else, and a worktree-scoped value that outranks the local one is reported as such (ADR 0015).
| Hook | Scope | Contract |
|---|---|---|
.githooks/pre-commit | staged files | Runs the emitter's file-scoped gates. Whole-program gates (tests, typecheck) are deferred to CI and the deferral is reported. A failing gate blocks the commit. |
.githooks/pre-push | added lines of the pushed range | Regex secret scan. Pre-existing secrets outside the range are not re-flagged; a false positive is exempted per line with harness:allow-secret. |
.githooks/post-commit | the commit just made | Slice retro gate (ADR 0017) — seven deterministic docs-drift checks, zero tokens, silent when clean. Advisory: it never blocks. |
post-commit is placed under a third mode, GUARDED: written when absent, refreshed when the existing file carries the ywr-harness:post-commit marker, refused otherwise. It is the one hook filename repos commonly already use — this repo's own post-commit republishes the docs artifact — so TOOLCHAIN would destroy working automation while SEED would silently deny the retro to every repo that has one.
The retro's checks (DEP · MIGRATION · SPEC · BUILD · FEAT · UNMAPPED · DEADMAP) read their scope from the retro block in .harness.json. An empty list disables the checks it drives, and --coverage says so — silence must mean clean, never "not configured".
python scripts/harness/harness_retro.py main~3..HEAD # whole slice — absorbs mid-slice splits
python scripts/harness/harness_retro.py --coverage # unowned files + dead implements_in
SLICE_RETRO=0 git commit ... # skip once
core.hooksPath lives in .git/config, which is per-clone and never committed — so the scaffold wires exactly the machine it ran on. That gap is closed by reporting, not by wiring harder: harness_gates.py prints a hooks: line on every /ywr-harness:slice-close and CI run, so an unwired clone can never look identical to a wired one.
The emitter also checks any declared claude.ai Artifact (ADR 0032): the artifacts section of .harness.json names each url and title, and the emitter verifies the README carries the link and the title starts with the repo name (convention <repo> · <purpose>). The emitter only reports (artifact: ok | VIOLATION | none declared); the vendored CI is the enforcement point — it fails on artifact: VIOLATION. The gate cannot see claude.ai, so an undeclared Artifact is unchecked, and that state is reported rather than silent.
Both hooks degrade the way everything else here does. A missing python, awk, or emitter is a reported skip, never a silent pass — an unparsed emitter would otherwise read as "no gates matched", which is the hardest kind of gate failure to notice.
pwsh -NoProfile -File "${CLAUDE_PLUGIN_ROOT}/statusline/install.ps1" # add -DryRun to preview
Renders location · model · effort · ctx N%/SIZE · 5h N% · 7d N% · ywr-harness vX.Y.Z, dropping the model's (1M context) suffix — a session constant costing width on every render — in favour of how much of that window is actually gone.
The trailing segment is the plugin version installed on this machine, read from Claude Code's install registry (~/.claude/plugins/installed_plugins.json). It is deliberately the on-disk value, never the repo's or the marketplace's: with marketplace auto-update on (ADR 0026), disk moves ahead of a live session, and that visible mismatch is the "restart to apply" signal. A machine without the plugin installed renders no segment. The org-guide version segment this replaces is retired (ADR 0027) — guide drift detection is spec 0003 §7's job, where it always really lived.
A plugin cannot contribute the main status line: a plugin's settings.json supports only agent and subagentStatusLine. So this ships as canon plus an installer that writes the user's own ~/.claude/ (ADR 0016). Run it once per machine; it is not applied automatically, and nothing detects a machine that never ran it.
The installer separates its two effects because they carry different risk. The script is TOOLCHAIN, overwritten on every run. The statusLine setting follows ADR 0015's rule — written when absent, left alone when already ours, refused when it points anywhere else. settings.json is parsed and re-emitted so unrelated keys survive; a file that does not parse is a hard refusal that prints the snippet to add by hand.
A key the payload does not carry removes its segment — never 0%. Unmeasured and zero are different states, and rate-limit keys are legitimately absent on a session's first render, before the first API response. Context and quota use different threshold curves: 50% context is ordinary working state, 50% of a rate limit is already worth watching.
report-issue skill)/ywr-harness:report-issue <description> — send a defect or request to the canon (ADR 0064). The canon repo is private, so the report is filed as an issue on the PUBLIC dist repo orcait-co/ywr-harness, and the canon's session-start inbox lists every open dist issue (ADR 0085 — no label is set, because GitHub drops one set by a filer without push access). The skill drafts the body (running + registered plugin versions, claude --version, OS, owner/repo + .harness-version, the refresh nudge's verdict and init.ps1 -DryRun output quoted verbatim, git log --oneline -3 of every file a re-run would change, a dedupe fingerprint), shows it, and files it only after ONE confirmation — the reviewed file is what gets filed. It never includes file contents or diffs (the tracker is public; the canon asks in-thread), never runs harness-init, and without gh keeps the body and prints the by-hand URL (NOT FILED, exit 2).
/ywr-harness:artifact-publish — republish a declared claude.ai Artifact safely (ADR 0068). A repo that commits a GENERATED Artifact source declares source + check on its artifacts.items[] entry; the emitter enforces that the source exists and rides the drift check through CI, and this skill closes the loop: list the declared items, run each check, ONE confirmation, then the Artifact-tool publish with the enforced read-before-republish sequence and a byte-level lockstep proof against the committed file. Never headless (headless sessions have no Artifact tool — measured), never from a hook, never past a VIOLATION or a failed check; an ownership refusal is reported, not worked around.
/ywr-harness:update — for the member who does not want to wait for the background auto-update (ADR 0026 converges every machine by its next session start). It reads the plugin's marketplace version and scope from claude plugin list --json, runs the two CLI commands with --json (claude plugin marketplace update, then claude plugin update -s <scope>), reports the on-disk old → new from the result line, falls back to the text forms on a host without --json, never accepts a marketplace-declared command (-y, --accept-command), and hands off the two steps no skill can perform: /reload-plugins (a REPL built-in — the remedy for the update CLI's own "restart required to apply"), and /ywr-harness:harness-init only when the ADR 0033 nudge reports drifted toolchain files. It never runs the scaffold refresh itself — the byte comparison alone cannot prove direction (the .harness-version stamp orients the nudge's advice since ADR 0042, but a stampless repo stays ambiguous), and an automatic re-run could revert a working tree deliberately newer than the installed plugin (ADR 0034).
scripts/workflow-gates.mjs (parse + behavioral gate over a workflow corpus; --dir selects the corpus, default .claude/workflows) and scripts/resolve-base.sh (CI diff-range base resolution — since ADR 0043 vendored by the scaffold as scripts/harness/resolve-base.sh and invoked by the vendored workflow to resolve the PR base once, MODE=blocking). lib/selftest-lib.ps1 is the shared assertion core the selftests dot-source — dot-source it, do not run it.
node — runs all eight hooks (hooks/*.mjs, with the shared hooks/hook-lib.mjs; Node costs ~70 ms per hook call against ~780 ms for pwsh, ADR 0116) and the gates scripts/workflow-gates.mjs and the workflow corpus gate. Absent node: those hooks cannot start on a member machine — the host reports a hook error and never a blocked call, since no hook can block; the suites report a skip locally and a hard failure on CI, where they must actually run.pwsh (PowerShell 7+) on PATH — the skills' scripts (harness-init, report-issue) and every selftest. No hook runs on it.python 3.9+ (stdlib only) — every gate script under scripts/ requires it: harness_gates.py (invoked by the pre-commit hook), harness_retro.py (by the post-commit hook), verify_map.py (by ywr-harness:verify), and fix_proof.py (by /ywr-harness:slice-close, plugin-only — the scaffold does not vendor it, ADR 0169).The prerequisite check (hooks/prerequisites.mjs, above) names any of the three that is missing or too old at each session start, and /ywr-harness:setup installs them on your command.
Hooks run wherever the session runs; the gates and selftests are also exercised on Linux pwsh, so nothing here may assume Windows.
selftest.ps1 is the single entry point — the manifest/wiring gate, the workflow corpus gate, then every shipped PowerShell selftest:
pwsh -NoProfile -File ./selftest.ps1
The two gates run first; the suites then run side by side (-Jobs N, default the CPU count capped at 8; -Jobs 1 runs them one at a time). Each finished suite prints one done line, then the results come back in discovery order: a failed suite in full, a passing suite as one line plus any SKIP lines. -Full prints every suite's whole output. To iterate on one component, run its own *.selftest.ps1 directly.
manifest-gate.mjs is deterministic and CLI-free; it is Node with built-ins only (ADR 0141), and the runner fails it when node is not on PATH. It fails on the defects with d
hooks/mods.mjs 17 lines1// The plugin's hooks-module ENTRY (Claude Mods; ADR 0117, ADR 0138): `hooks.json` names this file under
2// `modules`, which takes exactly one path. It registers each module file's hooks and holds no logic of its
3// own, so each file keeps its own contract and its own selftest:
4//
5// - `delegation-ledger.mjs`: the observe-only delegation ledger (ADR 0117, ADR 0118). Never draws.
6// - `prerequisites.mjs`: the pwsh / node / python check, its band and `/ywr-harness:setup` (ADR 0142).
7//
8// `slice-status.mjs` (ADR 0138, ADR 0139) stays in the tree but is NOT registered (ADR 0140): its status
9// line is off until a new ADR redesigns it.
10import { register as registerLedger } from './delegation-ledger.mjs'
11import { register as registerPrerequisites } from './prerequisites.mjs'
12
13export function register(on, options) {
14 registerLedger(on, options)
15 registerPrerequisites(on, options)
16}
17hooks/delegation-ledger.mjs 361 lines1// Hooks module (Claude Mods, Claude Code 2.1.287+; ADR 0117, ADR 0118) — the OBSERVE-ONLY per-request
2// delegation ledger. `mods.mjs`, the entry `hooks.json` names under `modules`, registers it (alone
3// since ADR 0140); the settings hooks beside it are unaffected.
4//
5// What it records, per finished model loop (the main loop's turn, or one run of a subagent's loop):
6// every request the loop made (`turn.step`: the model the engine resolved, the effort it sends, the
7// usage the API reported), the loop's end (`turn.complete`: reason, duration, summed usage) and, for
8// a spawned agent, the spawn itself (`agent.spawn`: type, the per-call model as given, the parent
9// model, the resolved model). An agent-team teammate raises `agent.spawn` too from Claude Code 2.1.289
10// (`e.isTeammate`); its loop keeps the `agent-tool` kind and its spawn row says `teammate: true`, which
11// is what the reader splits on (schema 2 unchanged — the field is additive). A Workflow `agent()` worker
12// raises `agent.spawn` from Claude Code 2.1.292 with `e.workflow` ({runId, agentIndex}); its spawn row
13// carries `workflow: {run_id, agent_index}` and its loop is kind `workflow` (ADR 0126), and a row with
14// no `model_param` proves the call gave no model, so the worker inherited the session's. On 2.1.287 to
15// 2.1.291 such a worker raises no `agent.spawn` (fact 89): its loop is written with `spawn: null` and
16// `loop: 'unspawned'`, whose steps still name the model and effort it ran on. On 2.1.292+ `unspawned`
17// means an evicted spawn row. From Claude Code 2.1.299 a resumed agent raises `agent.spawn` again with
18// `e.resume` ({agentId}; fact 141): its first spawn row is KEPT and counts the resume in `resumes`, so
19// the per-call model and the first `tool_use_id`/`background` survive (ADR 0147). A resume with no row
20// in memory starts one from the resume event, flagged `from_resume`.
21//
22// Observe-only, by contract: every hook passes the event on unchanged (`next(e)`, `yield* next(e)`),
23// never rewrites `model`/`effort`, never denies, never draws, and swallows its own failures — the
24// recording code runs after `next` resolved and inside try/catch, because a hook that fails
25// mid-stream is "left where it stood". It never carries a gate: hosts < 2.1.287, `disableAllHooks`,
26// `--safe-mode` and a managed `allowManagedModsOnly` all drop it (ADR 0117).
27//
28// What it never writes: a prompt, a task description, an answer or any other message text (the
29// secret-adjacent rule `subagent-telemetry` keeps). Where it writes (ADR 0118): a RING of twenty
30// session files, `<project root>/.claude/telemetry/delegations/slot-00.json`..`slot-19.json` —
31// gitignored by the scaffold and the canon — and only where the root holds `.harness.json` (a repo
32// that adopted the harness), so a session in a home directory or a stranger's checkout leaves nothing
33// behind. `$.fs` has no delete, so the bound is by construction: a session claims a missing slot or
34// the oldest by `mtimeMs`, and its file keeps its last 500 loops within 360 KiB. `$.fs.write` is not
35// atomic and replaces the whole file, so a session's writes are serialized, and a slot another
36// session took (its `mtimeMs`/`size` moved since this session's last write) is given up for a new one.
37//
38// The pure half (`createLedger`, `createSessionLog`, `pickSlot`, `stepRow`, `spawnRow`, `fingerprint`)
39// is exported so `delegation-ledger.selftest.ps1` drives it under plain node with a fake engine; the
40// engine imports only `register`.
41
42export const SCHEMA = 2
43export const LEDGER_DIR = '.claude/telemetry/delegations'
44export const RING = 20
45// One session file: its last MAX_LOOPS loops within MAX_FILE_BYTES (UTF-8, counted as an upper
46// bound). The ring's worst case is RING x MAX_FILE_BYTES, ~7 MiB per adopted repo.
47export const MAX_LOOPS = 500
48export const MAX_FILE_BYTES = 360 * 1024
49// Room left in MAX_FILE_BYTES for the file's own fields around `loops` (a session id is ~40 B).
50const HEADER_RESERVE = 1024
51// A loop keeps its first MAX_STEPS step rows; the rest are counted. Bounds one row (~67 B a step)
52// and the memory of an open loop.
53export const MAX_STEPS = 200
54// Open loops are held in module memory until their loop ends. A loop that never ends (killed agent,
55// crash) would otherwise leak; past this many, the oldest is dropped unwritten.
56export const MAX_OPEN = 256
57// Spawn rows outlive their loop (a resumed agent runs again under the same id), so they are capped
58// separately and higher (a row is ~330 B); a resume moves its row to the newest end. An evicted row would make that agent's later run read as
59// `unspawned` — the workflow signal ADR 0117 Decision 6 counts on hosts before 2.1.292, and a plain
60// eviction after — so each record carries `spawn_rows_evicted`, the session's running count, and a
61// reader discounts `unspawned` when it is > 0.
62export const MAX_SPAWNS = 4096
63// Session loop lists held at once (a `/clear` starts a new session in the same module).
64export const MAX_SESSIONS = 4
65
66const MAIN = 'main'
67
68export function slotName(i) {
69 return `slot-${String(i).padStart(2, '0')}.json`
70}
71
72// The slot a new session claims from a `$.fs.list` of the ledger directory: the lowest-numbered slot
73// with no entry, else the regular slot file with the oldest `mtimeMs` (ties: the lowest number), else
74// null. A slot name that is a directory, a link or anything but a file is never claimed.
75export function pickSlot(entries, ring = RING) {
76 const byName = new Map()
77 for (const en of Array.isArray(entries) ? entries : []) if (en && typeof en.name === 'string') byName.set(en.name, en)
78 let oldest = null
79 for (let i = 0; i < ring; i++) {
80 const en = byName.get(slotName(i))
81 if (!en) return i
82 if (en.kind !== 'file' || en.isLink || typeof en.mtimeMs !== 'number') continue
83 if (oldest === null || en.mtimeMs < oldest.mtimeMs) oldest = { i, mtimeMs: en.mtimeMs }
84 }
85 return oldest ? oldest.i : null
86}
87
88// An upper bound on the UTF-8 length of a string: a code unit above U+007F counts 3 bytes (a
89// surrogate pair counts 6 for its 4).
90export function utf8Bound(s) {
91 let n = s.length
92 for (let i = 0; i < s.length; i++) if (s.charCodeAt(i) > 0x7f) n += 2
93 return n
94}
95
96function usageRow(u) {
97 if (!u || typeof u !== 'object') return null
98 return {
99 model: u.model ?? null,
100 input_tokens: u.input_tokens ?? 0,
101 output_tokens: u.output_tokens ?? 0,
102 cache_read_input_tokens: u.cache_read_input_tokens ?? 0,
103 cache_creation_input_tokens: u.cache_creation_input_tokens ?? 0,
104 }
105}
106
107export function spawnRow(e, r) {
108 const wf = e.workflow && typeof e.workflow === 'object' ? e.workflow : null
109 return {
110 tool_use_id: e.tool_use_id ?? null,
111 subagent_type: e.subagentType ?? null,
112 provider: e.provider ? `${e.provider.plugin}/${e.provider.tier}` : null,
113 model_param: e.model ?? null,
114 parent_model: e.parentModel ?? null,
115 model: r && typeof r === 'object' && !('deny' in r && r.deny) ? (r.model ?? null) : null,
116 denied: !!(r && typeof r === 'object' && r.deny),
117 fork: !!e.fork,
118 background: !!e.background,
119 teammate: !!e.isTeammate,
120 workflow: wf ? { run_id: wf.runId ?? null, agent_index: wf.agentIndex ?? null } : null,
121 parent_agent_id: e.parentAgentId ?? null,
122 resumes: e.resume ? 1 : 0,
123 from_resume: !!e.resume,
124 }
125}
126
127// A step row is a TUPLE in STEP_FIELDS order (~67 B, against ~236 B as an object): the ledger is
128// read by analysis code, never by eye, and the file names the fields once, as `step_fields`. The
129// token counts are null when the request reported no usage; `usage_model` (the model the API
130// reported) is null when it equals `model` or no usage came back.
131export const STEP_FIELDS = ['index', 'model', 'effort', 'message_count', 'stop_reason', 'input_tokens',
132 'output_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens', 'usage_model']
133
134export function stepRow(e, r) {
135 const res = r && typeof r === 'object' ? r : null
136 const u = usageRow(res ? res.usage : null)
137 const model = e.model ?? null
138 return [
139 e.index ?? null,
140 model,
141 e.effort ?? null,
142 e.messageCount ?? null,
143 res ? (res.stopReason ?? null) : null,
144 u ? u.input_tokens : null,
145 u ? u.output_tokens : null,
146 u ? u.cache_read_input_tokens : null,
147 u ? u.cache_creation_input_tokens : null,
148 u && u.model !== model ? u.model : null,
149 ]
150}
151
152const present = x => x !== null && x !== undefined
153
154// The ledger's bookkeeping, engine-free. `spawn` / `step` / `complete` take the event and the result
155// `next` resolved to; `complete` answers the loop's row (empty steps when nothing was open).
156export function createLedger({ maxOpen = MAX_OPEN, maxSpawns = MAX_SPAWNS, maxSteps = MAX_STEPS } = {}) {
157 const spawns = new Map() // agentId -> spawn row (kept across that agent's runs)
158 const open = new Map() // `${agentId|main}\u0000${turnId}` -> { steps, dropped, models, efforts }
159 let evicted = 0
160 const cap = (map, max, onDrop) => { while (map.size > max) { map.delete(map.keys().next().value); onDrop?.() } }
161 const key = (agentId, turnId) => `${agentId ?? MAIN}\u0000${turnId}`
162 return {
163 spawn(e, r) {
164 const agentId = r && typeof r === 'object' ? r.agentId : undefined
165 if (!agentId) return
166 const first = spawns.get(agentId)
167 if (e.resume && first) {
168 // ADR 0147: a loop row already written holds its own copy, so the count is the resumes so far.
169 // A denied resume runs nothing, so it changes nothing.
170 if ('deny' in r && r.deny) return
171 first.resumes++
172 spawns.delete(agentId)
173 spawns.set(agentId, first)
174 return
175 }
176 spawns.set(agentId, spawnRow(e, r))
177 cap(spawns, maxSpawns, () => { evicted++ })
178 },
179 step(e, r) {
180 const k = key(e.agentId, e.turnId)
181 if (!open.has(k)) { open.set(k, { steps: [], dropped: 0, models: new Set(), efforts: new Set() }); cap(open, maxOpen) }
182 const loop = open.get(k)
183 if (!loop) return
184 const row = stepRow(e, r)
185 if (present(row[1])) loop.models.add(row[1])
186 if (present(row[2])) loop.efforts.add(row[2])
187 if (loop.steps.length < maxSteps) loop.steps.push(row)
188 else loop.dropped++
189 },
190 complete(e, { iso }) {
191 const k = key(e.agentId, e.turnId)
192 const loop = open.get(k) ?? { steps: [], dropped: 0, models: new Set(), efforts: new Set() }
193 open.delete(k)
194 const spawn = e.agentId ? (spawns.get(e.agentId) ?? null) : null
195 return {
196 ts: iso,
197 loop: !e.agentId ? MAIN : !spawn ? 'unspawned' : spawn.workflow ? 'workflow' : 'agent-tool',
198 agent_id: e.agentId ?? null,
199 turn_id: e.turnId ?? null,
200 spawn,
201 spawn_rows_evicted: evicted,
202 steps: loop.steps,
203 steps_dropped: loop.dropped,
204 models: [...loop.models],
205 efforts: [...loop.efforts],
206 complete: {
207 reason: e.reason ?? null,
208 aborted: !!e.isAborted,
209 duration_ms: e.durationMs ?? null,
210 usage: usageRow(e.usage),
211 },
212 }
213 },
214 sizes: () => ({ spawns: spawns.size, open: open.size, evicted }),
215 }
216}
217
218// One session's loop rows, kept serialized and capped; `render` is the whole file's text.
219export function createSessionLog({ maxLoops = MAX_LOOPS, maxBytes = MAX_FILE_BYTES } = {}) {
220 const loops = [] // { text, bytes }
221 let bytes = 0
222 let dropped = 0
223 return {
224 add(row) {
225 const text = JSON.stringify(row)
226 const b = utf8Bound(text) + 1 // + its comma
227 loops.push({ text, bytes: b })
228 bytes += b
229 while (loops.length > maxLoops || (loops.length > 0 && bytes + HEADER_RESERVE > maxBytes)) {
230 bytes -= loops.shift().bytes
231 dropped++
232 }
233 },
234 // `header` is the file's own fields; `loops` goes last, spliced in as the rows' kept text.
235 render(header) {
236 const h = JSON.stringify({ ...header, loops_dropped: dropped, loops: [] })
237 return `${h.slice(0, -3)}[${loops.map(l => l.text).join(',')}]}\n`
238 },
239 sizes: () => ({ loops: loops.length, bytes, dropped }),
240 }
241}
242
243// --- the engine half ---------------------------------------------------------------------------
244// Declared at the top of the file: the engine follows `$` only into such functions.
245
246// The project root to write under, or null where the root holds no `.harness.json`. `adopted`
247// caches the answer per root (a `/cd` or worktree move changes the root mid-session).
248async function target($, adopted) {
249 const root = await $.session.root()
250 if (!adopted.has(root)) adopted.set(root, await $.fs.exists(`${root}/.harness.json`))
251 return adopted.get(root) ? root : null
252}
253
254async function statOf($, path) {
255 try {
256 const st = await $.fs.stat(path)
257 return { mtimeMs: st.mtimeMs, size: st.size }
258 } catch { return null }
259}
260
261// The start every file this session renders begins with (`render` puts the header keys first).
262const headerOf = id => `{"schema":${SCHEMA},"session_id":${JSON.stringify(id)},`
263
264// A 32-bit FNV-1a over the UTF-16 code units: the mark of the text this session last wrote whole.
265export function fingerprint(text) {
266 let h = 0x811c9dc5
267 for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193)
268 return h >>> 0
269}
270
271// One rewrite of a session's file. Runs on the session's chain, never two at once for one session.
272async function flush($, s, root, iso) {
273 const dir = `${root}/${LEDGER_DIR}`
274 if (s.root !== root) { s.root = root; s.slot = null; s.seen = null; s.mark = null }
275 if (s.slot !== null && s.seen) {
276 const now = await statOf($, `${dir}/${slotName(s.slot)}`)
277 // moved since this session's last write: another session claimed it. A stat that fails (a missing
278 // slot among the causes) proves nothing either way, so the read-back below decides.
279 if (!now) s.seen = null
280 else if (now.mtimeMs !== s.seen.mtimeMs || now.size !== s.seen.size) s.slot = null
281 }
282 if (s.slot !== null && !s.seen) {
283 // the last write or a stat failed, so there is no stat to compare: the file itself says whose
284 // it is. A missing or empty file stays ours; so does the very text this session last wrote whole
285 // (its fingerprint, which covers a stat that keeps failing), and a file starting with our own
286 // header (a partial write of ours keeps it). A file that exists but cannot be read proves
287 // nothing, and neither does a null session id's header (every id-less session writes the same
288 // one), so both are given up.
289 const path = `${dir}/${slotName(s.slot)}`
290 let text = ''
291 try { text = await $.fs.read(path) } catch {
292 let there = true
293 try { there = await $.fs.exists(path) } catch { /* unknown: not provably ours */ }
294 if (there) text = null
295 }
296 const ours = text === '' || (text !== null && ((s.mark !== null && fingerprint(text) === s.mark) ||
297 (s.id !== null && text.startsWith(headerOf(s.id)))))
298 if (!ours) s.slot = null
299 }
300 if (s.slot === null) {
301 let entries = []
302 try { entries = await $.fs.list(dir) } catch { /* no directory yet: every slot is missing */ }
303 s.slot = pickSlot(entries)
304 if (s.slot === null) return
305 }
306 const path = `${dir}/${slotName(s.slot)}`
307 const text = s.log.render({ schema: SCHEMA, session_id: s.id, slot: s.slot, updated: iso, step_fields: STEP_FIELDS })
308 s.seen = null
309 s.mark = null
310 await $.fs.write(path, text)
311 s.mark = fingerprint(text)
312 s.seen = await statOf($, path)
313}
314
315export function register(on) {
316 const ledger = createLedger()
317 const adopted = new Map() // project root -> whether it holds .harness.json
318 const sessions = new Map() // session id -> { id, log, root, slot, seen, mark, chain }
319 const sessionOf = id => {
320 let s = sessions.get(id)
321 if (s) { sessions.delete(id); sessions.set(id, s) } // most recently used last: eviction takes the idlest
322 else {
323 s = { id, log: createSessionLog(), root: null, slot: null, seen: null, mark: null, chain: Promise.resolve() }
324 sessions.set(id, s)
325 while (sessions.size > MAX_SESSIONS) sessions.delete(sessions.keys().next().value)
326 }
327 return s
328 }
329
330 on('agent.spawn', async ($, e, next) => {
331 const r = await next(e)
332 try { ledger.spawn(e, r) } catch { /* observe-only: never fail the spawn */ }
333 return r
334 })
335
336 on('turn.step', async function* ($, e, next) {
337 const r = yield* next(e)
338 try { ledger.step(e, r) } catch { /* observe-only */ }
339 return r
340 })
341
342 on('turn.complete', async ($, e, next) => {
343 const r = await next(e)
344 try {
345 // The loop leaves memory first: a failing engine call below costs this one record, never a leak.
346 const row = ledger.complete(e, { iso: null })
347 const id = (await $.session.id()) ?? null
348 row.ts = new Date(await $.clock.now()).toISOString()
349 const root = await target($, adopted)
350 if (root) {
351 const s = sessionOf(id)
352 s.log.add(row)
353 const run = s.chain.then(() => flush($, s, root, row.ts))
354 s.chain = run.catch(() => {})
355 await run
356 }
357 } catch { /* observe-only: a ledger write never reaches the turn */ }
358 return r
359 })
360}
361hooks/prerequisites.mjs 335 lines1// Hooks module (Claude Mods; ADR 0142) — the PREREQUISITE check and its install command. `mods.mjs`, the
2// entry `hooks.json` names under `modules`, registers it beside the delegation ledger.
3//
4// The plugin needs three tools on PATH: `node` runs the eight settings hooks (ADR 0116), `pwsh` 7+ runs
5// the skills' scripts and every selftest, `python` 3.9+ runs the gate scripts. A settings hook cannot
6// report its own runtime's absence, so this check is a mod: the host runs a mod in an engine
7// environment of its own, with no Node (fact 135), and `$.process.run` reaches the host's commands.
8//
9// What it does:
10// - `session.start`: after `next(e)` resolves it starts the three `--version` probes on a
11// `$.clock.after(0, …)` timer and does not wait for them, so the probes never delay the session start
12// (ADR 0164; a host without the call runs them directly). A probe that rejects with ENOENT / "not
13// found", or a command that exits non-zero (the Windows Store `python` alias does), is MISSING; a
14// `pwsh` below 7 or a `python` below 3.9 is OLD; anything else (a timeout, a surface without
15// `$.process`) is UNKNOWN and never speaks. On Windows a not-found refusal is tried once more by the
16// app execution alias path (`aliasPath`, ADR 0150): the runner refuses a bare alias name when the cwd
17// is an ancestor of the alias folder, as the home folder is (fact 147).
18// - `ui.render` on `AbovePrompt`: while a tool is missing or old, one Korean band (ADR 0045) names the
19// tools and `/ywr-harness:setup`. The engine's own `[-]` collapses it. Nothing missing: `next(e)`.
20// - The model note: when the probes find a missing or old tool, `$.session.append` adds ONE English
21// meta user row, which the person does not see. It tells Claude the cause of the hook errors and
22// failing scripts it will see, the command, and to install nothing unasked. The module adds no
23// `prompt.compose` section: on 2.1.296 the engine skips that hook for a user-tier plugin (fact 136).
24// The row belongs to the conversation, so a `/clear` drops it, and a resume or a fork adds it again.
25// - `command.run` on `ywr-harness:setup` (the command `skills/setup/SKILL.md` declares; a
26// `$.command.register` name carries no plugin prefix — fact 136): the member typed it, which is the
27// consent. On Windows with `winget` it probes again and runs `winget install` for each missing or old
28// tool, one at a time, each output piece's last line in the plugin status line, then reports each
29// result and asks for a restart (a running session keeps its PATH). Off Windows, or without `winget`,
30// it prints the commands and runs nothing. The hook answers the command itself, so no model turn
31// runs; on a host that drops mods the skill body runs instead.
32//
33// It never installs unasked, never denies, and passes every other event on unchanged. Text from a
34// child's output reaches the status line only through `flatten()` (the `hook-lib.mjs` `inline()`
35// class; the module cannot import hook-lib, which needs Node).
36//
37// The pure half (`TOOLS`, `parseVersion`, `verdictOf`, `needsOf`, `bandText`, `noteText`, `manualText`,
38// `lastLine`, `flatten`, `aliasPath`, `wingetArgv`, `resultLine`, `resultNote`, `unknownText`) is exported so `prerequisites.selftest.ps1` drives it
39// under plain node with a fake engine; the engine imports only `register`.
40
41export const COMMAND = 'ywr-harness:setup'
42// An interrupt aborts the command's dispatch, and an aborted dispatch kills the spawned winget (the
43// `$.process.spawn` contract). Whether Esc aborts it, and what a killed winget leaves of an installer
44// it started, is unmeasured (ADR 0142), so the status line says so while an install runs. The next
45// session's probe shows the band again for anything left half-installed.
46export const ESC_WARN = 'Esc 를 누르면 설치가 끊길 수 있습니다'
47export const PROBE_TIMEOUT_MS = 15000
48// winget's "no applicable upgrade" (APPINSTALLER_CLI_ERROR_UPDATE_NOT_APPLICABLE): the package is
49// installed, so a probe that missed it reads a PATH older than the install.
50export const WINGET_UP_TO_DATE = 0x8A15002B
51
52export const TOOLS = [
53 {
54 name: 'node', argv: ['node', '--version'], min: null, winget: 'OpenJS.NodeJS.LTS',
55 other: 'macOS: `brew install node` · Linux: the distribution package or nodejs.org',
56 uses: 'the eight ywr-harness settings hooks (session start, config change, added directory, every Agent call, every subagent stop) report a hook error',
57 },
58 {
59 name: 'pwsh', argv: ['pwsh', '--version'], min: [7, 0], winget: 'Microsoft.PowerShell',
60 other: 'macOS: `brew install --cask powershell` · Linux: learn.microsoft.com/powershell',
61 uses: 'the harness-init and report-issue skill scripts and every plugin selftest fail',
62 },
63 {
64 name: 'python', argv: ['python', '--version'], min: [3, 9], winget: 'Python.Python.3.13',
65 other: 'macOS: `brew install python` · Linux: the distribution package (the command must be `python`)',
66 uses: 'the gate scripts fail (harness_gates.py in pre-commit, harness_retro.py in post-commit, verify_map.py in /ywr-harness:verify)',
67 },
68]
69
70const minText = t => (t.min ? `${t.min[0]}.${t.min[1]}` : '')
71
72// The first `major.minor` in a `--version` line: `PowerShell 7.6.6`, `v24.14.0`, `Python 3.13.13`.
73export function parseVersion(text) {
74 const m = /(\d+)\.(\d+)/.exec(String(text ?? ''))
75 return m ? [Number(m[1]), Number(m[2])] : null
76}
77
78const isNotFound = err => /ENOENT|not found/i.test(String((err && err.message) ?? err ?? ''))
79
80// One probe's verdict from its outcome: `{ result }` (what `$.process.run` resolved) or `{ error }`.
81export function verdictOf(tool, outcome) {
82 if (!outcome || typeof outcome !== 'object') return { state: 'unknown' }
83 if ('error' in outcome) return { state: isNotFound(outcome.error) ? 'missing' : 'unknown' }
84 const r = outcome.result
85 if (!r || typeof r.exitCode !== 'number') return { state: 'unknown' }
86 if (r.exitCode !== 0) return { state: 'missing' }
87 const v = parseVersion(`${r.stdout ?? ''} ${r.stderr ?? ''}`)
88 const version = v ? `${v[0]}.${v[1]}` : null
89 if (tool.min && v && (v[0] < tool.min[0] || (v[0] === tool.min[0] && v[1] < tool.min[1]))) return { state: 'old', version }
90 return { state: 'ok', version }
91}
92
93// The tools that need an install, in TOOLS order: `[{ tool, state, version }]`.
94export function needsOf(verdicts) {
95 const out = []
96 TOOLS.forEach((tool, i) => {
97 const v = verdicts && verdicts[i]
98 if (v && (v.state === 'missing' || v.state === 'old')) out.push({ tool, state: v.state, version: v.version ?? null })
99 })
100 return out
101}
102
103// The per-user folder of Windows app execution aliases. The Store `pwsh` and `winget` are aliases there
104// (0-byte reparse points). `$.process.run` refuses a bare alias name with the not-found error when the
105// session's cwd is an ancestor of that folder, the home folder included, and runs the same alias by its
106// absolute path (fact 147, ADR 0150). The Desktop session that showed it ran in the home folder.
107const BS = '\\'
108export function aliasPath(localAppData, name) {
109 const base = String(localAppData ?? '')
110 if (!/^[A-Za-z]:\\/.test(base)) return null
111 return base.replace(/\\+$/, '') + BS + 'Microsoft' + BS + 'WindowsApps' + BS + name + '.exe'
112}
113
114async function runVerdict($, tool, argv) {
115 try { return { verdict: verdictOf(tool, { result: await $.process.run(argv, { timeoutMs: PROBE_TIMEOUT_MS }) }), refused: false } }
116 catch (error) { return { verdict: verdictOf(tool, { error }), refused: true } }
117}
118
119// One probe. On Windows a not-found refusal of the bare name tries the alias path once. Only an answer
120// ("ok" or "old") replaces the first "missing": an "unknown" retry (a timeout, another rejection) is no
121// evidence that the alias exists, and an "unknown" never speaks, so it would hide a missing tool. The
122// verdict carries `exe`, the command that answered, so the install runs `winget` the way the probe reached it.
123async function probeOne($, tool, win) {
124 const first = await runVerdict($, tool, tool.argv)
125 if (win && first.refused && first.verdict.state === 'missing') {
126 let path = null
127 try { path = aliasPath(await $.env.get('LOCALAPPDATA'), tool.argv[0]) } catch { /* no alias path */ }
128 if (path) {
129 const second = (await runVerdict($, tool, [path, ...tool.argv.slice(1)])).verdict
130 if (second.state === 'ok' || second.state === 'old') return { ...second, exe: path }
131 }
132 }
133 return { ...first.verdict, exe: tool.argv[0] }
134}
135
136async function probeAll($, win) {
137 return Promise.all(TOOLS.map(tool => probeOne($, tool, win)))
138}
139
140const needText = n => (n.state === 'old' ? `${n.tool.name} ${n.version} (${minText(n.tool)} 이상 필요)` : n.tool.name)
141
142export function bandText(needs) {
143 return `[ywr-harness] ${needs.map(needText).join(' · ')} 이(가) 없어 일부 기능이 동작하지 않습니다. ` +
144 `/ywr-harness:setup 을 입력하면 설치합니다.`
145}
146
147export function noteText(needs) {
148 const lines = needs.map(n => n.state === 'old'
149 ? `- \`${n.tool.name}\` ${n.version} is older than the ${minText(n.tool)} the harness needs: ${n.tool.uses}.`
150 : `- \`${n.tool.name}\` is not on PATH: ${n.tool.uses}.`)
151 return [
152 'ywr-harness prerequisite check (from the plugin, at session start):',
153 ...lines,
154 'Those failures come from the missing tools, not from a defect in the repository. The user sees a band that names ' +
155 'the command `/ywr-harness:setup`. That command runs winget on Windows, and the plugin installs nothing until the ' +
156 'user types it. A new tool is visible only after Claude Code restarts.',
157 ].join('\n')
158}
159
160// The install commands for a manual install: winget lines on Windows, the other line elsewhere.
161export function manualText(needs, isWindows) {
162 return needs.map(n => (isWindows ? `- ${n.tool.name}: \`${wingetArgv(n.tool).join(' ')}\`` : `- ${n.tool.name}: ${n.tool.other}`)).join('\n')
163}
164
165// `exe` is the `winget` the probe reached: the bare name, or the alias path (fact 147). A line shown to the
166// member keeps the bare name, which a terminal resolves.
167export function wingetArgv(tool, exe = 'winget') {
168 return [exe, 'install', '--id', tool.winget, '--exact', '--source', 'winget',
169 '--accept-package-agreements', '--accept-source-agreements', '--disable-interactivity', '--silent']
170}
171
172// A winget exit 0 does not prove the command resolves on PATH: whether the python installer puts
173// `python` on PATH, and whether the Windows Store alias of `python` shadows it, is unmeasured (ADR 0142).
174// The next session's probe is the check, so the report says what a returning band means.
175const PATH_HINT = '재시작한 뒤에도 안내 줄에 다시 나오면, 설치는 됐지만 PATH 에서 찾지 못하는 것입니다.'
176const ALIAS_HINT = ' python 이면 Windows 설정 > 앱 > 고급 앱 설정 > 앱 실행 별칭에서 python.exe 별칭을 끄고, PATH 에 Python 폴더가 있는지 확인하세요.'
177// For a tool the probe found OLD, a band after the restart means the old binary still comes first on
178// PATH (winget installs the new one beside it), not that the new one is missing from PATH.
179const OLD_HINT = old => `재시작한 뒤에도 안내 줄에 다시 나오면, 이전 버전(${old})이 PATH 에서 먼저 잡히는 것입니다. 이전 버전을 지우거나 PATH 순서를 바꾸세요.`
180const hintFor = (tool, old) => (old ? OLD_HINT(old) : PATH_HINT + (tool.name === 'python' ? ALIAS_HINT : ''))
181const isUpToDate = code => typeof code === 'number' && (code >>> 0) === WINGET_UP_TO_DATE
182
183// One install's report line (Korean, for the member) from the exit code `$.process.spawn` returned
184// (null: a signal, or no start). `old` is the version the probe found when the tool was OLD, else null.
185export function resultLine(tool, code, old = null) {
186 if (code === 0) return `- ${tool.name}: 설치 명령이 끝났습니다. ${hintFor(tool, old)}`
187 if (isUpToDate(code)) return `- ${tool.name}: winget 은 이미 설치돼 있다고 합니다. ${hintFor(tool, old)}`
188 return `- ${tool.name}: 설치하지 못했습니다 (winget exit ${code === null ? '없음' : code}). 직접 실행: \`${wingetArgv(tool).join(' ')}\``
189}
190
191// The same result for the model (English).
192export function resultNote(tool, code, old = null) {
193 if (code === 0) return `${tool.name}: winget exited 0; whether the new \`${tool.name}\` resolves first on PATH is known only after a restart.`
194 if (isUpToDate(code)) return old
195 ? `${tool.name}: winget reports a current version installed, but this session found ${old} first on PATH.`
196 : `${tool.name}: winget reports it already installed, but this session did not find it on PATH.`
197 return `${tool.name}: winget failed (exit ${code === null ? 'none' : code}).`
198}
199
200// The tools whose probe was neither found nor missing (a timeout, an unexpected rejection): never
201// reported as present (ADR 0142 Decision 10), never installed blind.
202export function unknownText(verdicts) {
203 const names = TOOLS.filter((t, i) => verdicts[i] && verdicts[i].state === 'unknown').map(t => t.name)
204 return names.length ? `\n${names.join(' · ')} 은(는) 확인하지 못했습니다 (시간 초과 등). 직접 확인: ${names.map(n => `\`${n} --version\``).join(', ')}` : ''
205}
206
207// The flattened class of hook-lib.mjs's inline(): C0, DEL, NEL, LS, PS and the backtick become a space.
208function isFlattened(c) {
209 return c <= 0x1f || c === 0x7f || c === 0x85 || c === 0x2028 || c === 0x2029 || c === 0x60
210}
211
212export function flatten(text, max = 160) {
213 const s = String(text ?? '')
214 let out = ''
215 for (let i = 0; i < s.length; i++) out += isFlattened(s.charCodeAt(i)) ? ' ' : s[i]
216 out = out.replace(/ {2,}/g, ' ').trim()
217 return out.length > max ? out.slice(0, max - 1) + '…' : out
218}
219
220// The last line of a child's output piece with two or more visible characters (a progress spinner's
221// single glyph is skipped), flattened; '' when there is none.
222export function lastLine(text) {
223 const parts = String(text ?? '').split(/[\r\n]+/)
224 for (let i = parts.length - 1; i >= 0; i--) {
225 const t = flatten(parts[i])
226 if (t.replace(/\s/g, '').length >= 2) return t
227 }
228 return ''
229}
230
231async function isWindows($) {
232 try { return (await $.env.get('OS')) === 'Windows_NT' } catch { return false }
233}
234
235async function runSetup($) {
236 const win = await isWindows($)
237 const verdicts = await probeAll($, win)
238 if (verdicts.every(v => v.state === 'unknown')) {
239 return {
240 text: '이 환경에서는 도구를 확인할 수 없습니다. 아래 명령으로 직접 설치하세요.\n' + manualText(needsOf(TOOLS.map(() => ({ state: 'missing' }))), win),
241 context: ['ywr-harness setup could not run host commands on this surface; it printed the manual install commands and installed nothing.'],
242 }
243 }
244 const needs = needsOf(verdicts)
245 const unknown = unknownText(verdicts)
246 const unknownNames = TOOLS.filter((t, i) => verdicts[i].state === 'unknown').map(t => t.name)
247 const unknownNote = unknownNames.length ? ` Not verified (probe timed out or failed): ${unknownNames.join(', ')}.` : ''
248 if (needs.length === 0) {
249 const found = TOOLS.filter((t, i) => verdicts[i].state === 'ok').map(t => t.name)
250 return {
251 text: `${found.join(' · ')} 이(가) 설치돼 있습니다.` + unknown,
252 context: [`ywr-harness setup found ${found.join(', ')} on PATH; it installed nothing.` + unknownNote],
253 }
254 }
255 if (!win) {
256 return {
257 text: 'Windows 가 아니라 자동 설치는 하지 않습니다. 아래 명령으로 설치한 뒤 Claude Code 를 다시 시작하세요.\n' + manualText(needs, false) + unknown,
258 context: [`ywr-harness setup is not on Windows; it printed the install commands for ${needs.map(n => n.tool.name).join(', ')} and installed nothing.` + unknownNote],
259 }
260 }
261 const winget = await probeOne($, { name: 'winget', argv: ['winget', '--version'], min: null }, win)
262 if (winget.state !== 'ok') {
263 return {
264 text: '`winget` 을 찾지 못했습니다. Microsoft Store 에서 "앱 설치 관리자"(App Installer)를 설치하거나, 아래 도구를 직접 설치하세요.\n' +
265 needs.map(n => `- ${n.tool.name}: ${n.tool.winget}`).join('\n') + unknown,
266 context: ['ywr-harness setup found no winget; it installed nothing.' + unknownNote],
267 }
268 }
269 const lines = []
270 const notes = []
271 try {
272 for (let i = 0; i < needs.length; i++) {
273 const tool = needs[i].tool
274 const old = needs[i].state === 'old' ? needs[i].version : null
275 const head = `${tool.name} 설치 중 (${i + 1}/${needs.length}) · ${ESC_WARN}`
276 $.ui.status(head)
277 let code = null
278 let shown = ''
279 try {
280 const child = $.process.spawn({ argv: wingetArgv(tool, winget.exe) })
281 for await (const piece of child) {
282 const line = lastLine(piece && piece.text)
283 if (line && line !== shown) { shown = line; $.ui.status(`${head} — ${line}`) }
284 }
285 const end = await child.result
286 code = end && typeof end.code === 'number' ? end.code : null
287 } catch { code = null }
288 lines.push(resultLine(tool, code, old))
289 notes.push(resultNote(tool, code, old))
290 }
291 } finally {
292 $.ui.status(undefined)
293 }
294 return {
295 text: 'setup 결과:\n' + lines.join('\n') + unknown + '\nClaude Code 를 완전히 종료한 뒤 다시 시작해야 새로 설치한 도구가 보입니다.',
296 context: ['ywr-harness setup ran winget for ' + needs.map(n => n.tool.name).join(', ') + '. Results: ' +
297 notes.join(' ') + ' The running session keeps its old PATH until Claude Code restarts.' + unknownNote],
298 }
299}
300
301export function register(on) {
302 let needs = null // null: not probed yet, or nothing to say; else the tools to install
303 let running = false // one setup at a time: a second run would race winget on the same packages
304
305 on('session.start', async ($, e, next) => {
306 const r = await next(e)
307 let started = false // one run: a clock call that scheduled the timer and then threw must not start a second
308 const probe = async () => {
309 if (started) return
310 started = true
311 try {
312 const found = needsOf(await probeAll($, await isWindows($)))
313 needs = found.length ? found : null
314 if (!needs) return
315 try { $.ui.invalidate('ui.render') } catch { /* the band draws at the next render instead */ }
316 await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: noteText(needs) }] } })
317 } catch { /* a failed probe or append says nothing */ }
318 }
319 try { $.clock.after(0, probe) } catch { void probe() }
320 return r
321 })
322
323 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
324 if (!needs || e.props.hasSurvey) return next(e)
325 const { Box, Text } = $.ui.resolve(e)
326 return h(Box, null, h(Text, { color: 'yellow', wrap: 'wrap' }, bandText(needs)))
327 })
328
329 on('command.run', { command: COMMAND }, async $ => {
330 if (running) return { text: '설치가 이미 진행 중입니다. 끝날 때까지 기다리세요.', context: ['ywr-harness setup is already running; this second run did nothing.'] }
331 running = true
332 try { return await runSetup($) } finally { running = false }
333 })
334}
335