@descent-vtt/spec-harness 0.11.1 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +159 -0
- package/README.md +68 -10
- package/dist/briefs.d.ts +10 -5
- package/dist/briefs.js +5 -3
- package/dist/briefs.js.map +1 -1
- package/dist/cli.d.ts +7 -6
- package/dist/cli.js +99 -30
- package/dist/cli.js.map +1 -1
- package/dist/commands.d.ts +5 -1
- package/dist/commands.js +32 -11
- package/dist/commands.js.map +1 -1
- package/dist/context.js +4 -1
- package/dist/context.js.map +1 -1
- package/dist/fs.d.ts +2 -0
- package/dist/fs.js +16 -1
- package/dist/fs.js.map +1 -1
- package/dist/premises.js +11 -1
- package/dist/premises.js.map +1 -1
- package/dist/round.js +3 -1
- package/dist/round.js.map +1 -1
- package/dist/rulings.js +3 -1
- package/dist/rulings.js.map +1 -1
- package/dist/sandbox.d.ts +24 -13
- package/dist/sandbox.js +88 -16
- package/dist/sandbox.js.map +1 -1
- package/dist/server.js +85 -24
- package/dist/server.js.map +1 -1
- package/dist/usage.d.ts +224 -0
- package/dist/usage.js +178 -0
- package/dist/usage.js.map +1 -0
- package/dist/workspace.d.ts +9 -2
- package/dist/workspace.js +18 -4
- package/dist/workspace.js.map +1 -1
- package/package.json +3 -3
package/dist/sandbox.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox.js","sourceRoot":"","sources":["../src/sandbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,YAAY,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,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C,EAAE,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,EAAE;YACzB,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,YAAY,CAAC,QAAQ,CAAC,CAAC;YACvB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACtB,wEAAwE;YACxE,MAAM,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;QAC7D,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Temporary worktrees: somewhere to run a command at a commit without\n * touching the person's own checkout.\n *\n * The family's tools read git and never write it (spec-core ADR-0005). The one\n * exception is this: a detached worktree under the system's temporary\n * directory, added for one job and removed after it, whether the job\n * succeeded, threw, or the process was interrupted (ADR-0003). The person's\n * branch, index, stash and working files are never touched; a failed round is\n * discarded by discarding its worktree, never by resetting theirs.\n *\n * Git forgets a worktree whatever becomes of its directory. A directory that\n * cannot be deleted, as on Windows while something a command started still\n * runs in it, costs the job nothing: its answer stands, the directory is\n * tried again as the process exits, and one still there then is named on the\n * standard error.\n */\n\nimport { execFileSync, spawn, type ChildProcess } from 'node:child_process';\nimport { mkdtempSync, rmSync } from 'node:fs';\nimport { constants, tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\nimport { addWorktree, removeWorktree } from './git.js';\nimport { probeEnvironment } from './probe.js';\n\nconst live = new Map<string, string>();\nconst running = new Set<ChildProcess>();\nlet installed = false;\n/** Set once the process is interrupted: from then on a command's end is never answered. */\nlet ending = false;\n\n/**\n * How long the sandbox waits for the commands it stopped to let go of their\n * output and their directory. They were stopped forced, so this is only the\n * time the system takes to end them; whatever still holds either after it has\n * left the tree, and no wait would end it.\n */\nconst SETTLE_MS = 3_000;\n\n/**\n * Whether a process has this id now. Signal 0 asks and sends nothing, and any\n * answer but \"no such process\" says one has it: another user's process\n * answers that it may not be signalled.\n */\nfunction taken(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code !== 'ESRCH';\n }\n}\n\n/**\n * Stops a command with what can be reached of what it started, forced:\n * SIGKILL to its process group on Linux and macOS, taskkill over its tree on\n * Windows. A process that left the group is not in it, and taskkill follows\n * a tree from parent to child while each parent runs: one whose parent has\n * ended is found under no root. Such a process runs on (ADR-0003).\n *\n * Both name the command by its id, and the id is the command's only while\n * something holds it (ADR-0003). Node holds the command's shell until it has\n * seen the shell end, and until then the system gives the id to nothing else.\n * After that the id is free on Windows, where a process started seconds later\n * can be given it: taskkill would stop that process with all it started, and\n * could not have found what the command left anyway, since it finds no tree\n * under a root that has ended. So a command whose shell has ended is not\n * stopped there. On Linux and macOS the id names the command's process group\n * as well, and stays out of use while the group has a member: what the shell\n * left in its group is still stopped, unless a process has the id now, which\n * says the group emptied and the id was given out again.\n *\n * `windowsHide` here and below only keeps a console window from opening on\n * Windows, which nothing reads, so its mutants are equivalent.\n */\nfunction stop(child: ChildProcess): void {\n // No pid means the spawn failed and nothing runs. Past the tick it failed\n // in, the kill below throws on the missing id and the fallback finds no\n // process, so the mutant that lets it through is equivalent; within that\n // tick nothing here stops a command.\n if (child.pid === undefined) return;\n // Node sets one of the two when it sees the shell end, and lets go of the\n // shell then. Windows reports no signal: there the second is set only once\n // the fallback below has stopped the shell, on the path no test takes.\n const held = child.exitCode === null && child.signalCode === null;\n // Windows is not asked whether a process has the id: one could be given it\n // between the answer and taskkill. Elsewhere `win32` is false already, so\n // the mutants that make it false are equivalent there.\n if (!held && (process.platform === 'win32' || taken(child.pid))) return;\n try {\n // False already on Linux and macOS, so the mutants that make it false\n // are equivalent there. On Windows the tests fail without taskkill:\n // stopping the shell alone leaves node holding the output. True already\n // on Windows, so the mutant that makes it true is equivalent there;\n // elsewhere there is no taskkill, and the shell alone is stopped.\n if (process.platform === 'win32') execFileSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });\n else process.kill(-child.pid, 'SIGKILL');\n } catch {\n // Reached when the group is already gone, and the command's shell with\n // it, as when the command left something outside the group holding its\n // output; on Windows when the shell has only just ended, which taskkill\n // sees before Node does; and there when taskkill cannot be run, where\n // stopping the shell is what is left. No test takes that last path.\n // `kill` goes through Node's own hold on the shell, and does nothing\n // once that is gone.\n child.kill('SIGKILL');\n }\n}\n\n/**\n * Deletes a worktree's directory, trying again for up to `SETTLE_MS` while\n * something holds it, and answers `null` once it is gone, or else why it is\n * not. On Windows a command just stopped lets go of its directory a moment\n * after taskkill returns, and an exit handler, which runs synchronously, has\n * no other way to wait; elsewhere a directory in use is deleted all the same.\n */\nfunction discard(directory: string): Error | null {\n const deadline = Date.now() + SETTLE_MS;\n for (;;) {\n try {\n rmSync(directory, { recursive: true, force: true });\n return null;\n } catch (error) {\n // `>=` would differ only in the millisecond the deadline falls on, so\n // that mutant is equivalent.\n if (Date.now() > deadline) return error as Error;\n // The pause only spares the processor between attempts: without it\n // the directory is deleted, or given up on, at the same moment, so\n // that mutant is equivalent.\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);\n }\n }\n}\n\n/**\n * Has git remove the worktree at `directory` with its record of it, as\n * `removeWorktree` does and synchronously, and answers whether git did.\n */\nfunction forget(directory: string, repository: string): boolean {\n try {\n execFileSync('git', ['worktree', 'remove', '--force', directory], { cwd: repository, stdio: 'ignore', windowsHide: true });\n // Asked again about a worktree it has forgotten, git changes nothing, so\n // the mutant that answers false here is equivalent.\n return true;\n } catch {\n // Git refused a worktree its job broke, could not delete all of the\n // directory, holds nothing of it any more, or cannot be run. The answer\n // is read with `!` and nowhere else, so the mutant that answers nothing\n // here is equivalent.\n return false;\n }\n}\n\n/**\n * Stops every command still running, then removes every live worktree:\n * synchronously, the only kind of work an exit handler may do, so at exit\n * nothing waits for the commands to end but `discard`'s retries. A directory\n * that outlasts those is named on the standard error and left: nothing\n * thrown here could be caught, and the next worktree is still to remove.\n */\nfunction sweep(): void {\n for (const child of running) stop(child);\n for (const [directory, repository] of live) {\n // In the order a job's end takes, for the reasons `withWorktree` gives.\n const forgotten = forget(directory, repository);\n const kept = discard(directory);\n if (kept !== null) process.stderr.write(`spec-harness: the temporary worktree at ${directory} could not be deleted and is left there: ${kept.message}\\n`);\n // The mutant that always asks again is equivalent, as in `forget`.\n else if (!forgotten) forget(directory, repository);\n }\n // A signal handler ends in an exit, which sweeps again: over worktrees\n // already gone and forgotten, where keeping them would change nothing, and\n // over one that could not be deleted, which would be named a second time.\n live.clear();\n}\n\n/**\n * Stops every running command with its tree, waits a bounded time for them to\n * let go of their output, removes the worktrees, and exits as a shell reports\n * a process the signal ended: 128 and the signal's number, the same on every\n * platform Node runs on. The commands lead process groups of their own on\n * Linux and macOS, so the terminal's signal never reached them.\n */\nasync function interrupted(signal: NodeJS.Signals): Promise<void> {\n ending = true;\n const stopping = [...running];\n for (const child of stopping) stop(child);\n await Promise.race([\n Promise.all(stopping.map((child) => new Promise((resolve) => child.once('close', resolve)))),\n new Promise((resolve) => setTimeout(resolve, SETTLE_MS)),\n ]);\n sweep();\n process.exit(128 + constants.signals[signal]);\n}\n\nfunction install(): void {\n if (installed) return;\n installed = true;\n process.once('exit', sweep);\n // `on`, not `once`: a second signal while the first waits would otherwise\n // meet Node's default, which ends the process before any 'exit' handler\n // runs, with the worktrees still in place. It runs the same steps again,\n // and the first to finish exits.\n //\n // SIGBREAK is Windows' own: Ctrl+Break, which GitHub's runner sends there,\n // after Ctrl+C, where it sends SIGTERM elsewhere. Unheard, it ends the\n // process before any 'exit' handler runs, and the commands run on.\n // Elsewhere there is no such signal and nothing calls its listener, so\n // its mutants are equivalent there.\n for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGBREAK'] as const) process.on(signal, interrupted);\n}\n\n/**\n * Runs `work` in a detached worktree of `repository` at `revision`, and\n * removes the worktree after.\n *\n * Git removes it first, while it is as the job left it: git then forgets the\n * worktree whether or not all of its directory can be deleted. What git left\n * of the directory is deleted next, which is all of it when the job broke the\n * worktree, since git refuses one whose `.git` file is gone. Only then is\n * git asked again, once the directory is gone, when it forgets what it finds\n * missing (`removeWorktree`).\n *\n * A directory that cannot be deleted stays on the list for the exit to try\n * again, and does not take the job's answer with it.\n */\nexport async function withWorktree<T>(repository: string, revision: string, work: (directory: string) => Promise<T>): Promise<T> {\n install();\n const directory = mkdtempSync(join(tmpdir(), 'spec-harness-'));\n live.set(directory, repository);\n try {\n await addWorktree(directory, revision, repository);\n return await work(directory);\n } finally {\n const forgotten = await removeWorktree(directory, repository);\n if (discard(directory) === null) {\n // Asked again about a worktree it has forgotten, git changes nothing,\n // so the mutant that always asks again is equivalent.\n if (!forgotten) await removeWorktree(directory, repository);\n live.delete(directory);\n }\n }\n}\n\nexport interface CommandRun {\n /** `null` when the command was stopped at its timeout. */\n readonly exitCode: number | null;\n /** What the command had printed by the time it was answered. */\n readonly output: string;\n /**\n * Set on a command that was stopped at its timeout and answered with its\n * output still open: something it started holds the output where the stop\n * did not reach it, and runs on (ADR-0003).\n */\n readonly outputHeld?: true;\n}\n\n/**\n * Runs a command line in a directory, output and errors interleaved, until\n * its output closes. A command that outlives `timeoutSeconds` is stopped\n * with what `stop` reaches of it, as is one still running when the process\n * is interrupted or exits. Once the process is interrupted it never answers:\n * the job waiting on it would otherwise carry on in a worktree being removed.\n *\n * The timeout bounds the wait as well as the command. What the stop reached\n * lets go of the output in the time the system takes to end it, and the\n * command answers then. What still holds the output `SETTLE_MS` later is\n * what `stop` does not reach, and no wait would end it: the sandbox lets go\n * of the output instead, and answers with what was printed and with\n * `outputHeld`. Letting go is what the end of this process would do to\n * whatever holds the output, only sooner, and without it the open output\n * keeps this process from ending once its work is done.\n *\n * Through the shell, on purpose: a probe's command is a line from the\n * repository's own brief - `npm test -- x` - which the person approved with\n * the brief, exactly as CI runs the repository's own scripts. Nothing from\n * outside the repository reaches it.\n *\n * The line is run as it is written. Its environment is the person's own as\n * `probeEnvironment` hands it on: `CI` set, and npm told to fetch nothing for\n * a command where neither that environment nor the line says what it may\n * fetch (ADR-0007).\n */\nexport function runCommand(line: string, cwd: string, timeoutSeconds: number): Promise<CommandRun> {\n install();\n return new Promise((resolve) => {\n // Elsewhere the command leads a process group of its own, so the timeout\n // can stop the group. Windows has none to signal, and taskkill follows\n // the tree instead; a command detached there loses its output, which the\n // tests catch on Windows. Everywhere else `detached` is true already, so\n // the mutants that make it true are equivalent there, as are\n // `windowsHide`'s.\n //\n // It is given no input: nobody is there to type any, and a pipe that is\n // never written to and never closed kept a command that reads its input\n // waiting until the timeout stopped it.\n const child = spawn(line, {\n cwd,\n shell: true,\n windowsHide: true,\n detached: process.platform !== 'win32',\n env: probeEnvironment(process.env),\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n running.add(child);\n let output = '';\n const keep = (chunk: Buffer): void => {\n // Enough to find a signature in; a runaway log is not kept whole.\n if (output.length < 4 * 1024 * 1024) output += chunk.toString('utf8');\n };\n // Both streams are piped, so both exist: `?.` only satisfies the type,\n // and its mutants are equivalent.\n child.stdout?.on('data', keep);\n child.stderr?.on('data', keep);\n const answer = (run: CommandRun): void => {\n if (!ending) resolve(run);\n };\n let stopped = false;\n let settling: NodeJS.Timeout | undefined;\n const timer = setTimeout(() => {\n stopped = true;\n stop(child);\n settling = setTimeout(() => {\n // With both let go, 'close' follows as soon as Node has seen the\n // shell end, and takes the command off the list of those running.\n // The streams exist, as above, so the mutants of `?.` are equivalent.\n child.stdout?.destroy();\n child.stderr?.destroy();\n answer({ exitCode: null, output, outputHeld: true });\n }, SETTLE_MS);\n }, timeoutSeconds * 1000);\n child.on('error', (error) => {\n // 'close' follows the error of a spawn that failed, and clears the\n // timer too, so the mutant that drops this call is equivalent.\n clearTimeout(timer);\n resolve({ exitCode: 127, output: `${output}${error.message}\\n` });\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n clearTimeout(settling);\n running.delete(child);\n // The second answer of a command already answered as held does nothing.\n answer({ exitCode: stopped ? null : (code ?? 1), output });\n });\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sandbox.js","sourceRoot":"","sources":["../src/sandbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,YAAY,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,MAAM,IAAI,GAAG,IAAI,GAAG,EAAkB,CAAC;AACvC,MAAM,OAAO,GAAG,IAAI,GAAG,EAAgB,CAAC;AACxC;;;;;;;GAOG;AACH,MAAM,IAAI,GAAG,IAAI,GAAG,EAAwB,CAAC;AAC7C,IAAI,SAAS,GAAG,KAAK,CAAC;AACtB,2FAA2F;AAC3F,IAAI,MAAM,GAAG,KAAK,CAAC;AAEnB;;;;;;;;;GASG;AACH,MAAM,SAAS,GAAG,KAAK,CAAC;AAExB;;;;GAIG;AACH,SAAS,KAAK,CAAC,GAAW;IACxB,IAAI,CAAC;QACH,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAQ,KAA+B,CAAC,IAAI,KAAK,OAAO,CAAC;IAC3D,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,SAAS,IAAI,CAAC,KAAmB;IAC/B,0EAA0E;IAC1E,wEAAwE;IACxE,yEAAyE;IACzE,qCAAqC;IACrC,IAAI,KAAK,CAAC,GAA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AC;gBAAE,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;YACxD,qEAAqE;YACrE,MAAM,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC;QACpB,CAAC,CAAC,CAAC;QACH,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,EAAE;YACzB,qEAAqE;YACrE,6DAA6D;YAC7D,YAAY,CAAC,QAAQ,CAAC,CAAC;YACvB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACtB,wEAAwE;YACxE,MAAM,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;QAC7D,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * Temporary worktrees: somewhere to run a command at a commit without\n * touching the person's own checkout.\n *\n * The family's tools read git and never write it (spec-core ADR-0005). The one\n * exception is this: a detached worktree under the system's temporary\n * directory, added for one job and removed after it, whether the job\n * succeeded, threw, or the process was interrupted (ADR-0003). The person's\n * branch, index, stash and working files are never touched; a failed round is\n * discarded by discarding its worktree, never by resetting theirs.\n *\n * Git forgets a worktree whatever becomes of its directory. A directory that\n * cannot be deleted, as on Windows while something a command started still\n * runs in it, costs the job nothing: its answer stands, the directory is\n * tried again as the process exits, and one still there then is named on the\n * standard error.\n */\n\nimport { execFileSync, spawn, type ChildProcess } from 'node:child_process';\nimport { mkdtempSync, rmSync } from 'node:fs';\nimport { constants, tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\nimport { addWorktree, removeWorktree } from './git.js';\nimport { probeEnvironment } from './probe.js';\n\nconst live = new Map<string, string>();\nconst running = new Set<ChildProcess>();\n/**\n * The commands whose shell has ended and left a process in its process\n * group, each with the directory it ran in: what `withWorktree` stops when\n * the job in that directory ends, and an interrupt or the exit of the process\n * whenever it comes. Linux and macOS alone have such a group; on Windows\n * nothing is kept, since nothing a command left can be reached once its\n * shell has ended (ADR-0003).\n */\nconst left = new Map<ChildProcess, string>();\nlet installed = false;\n/** Set once the process is interrupted: from then on a command's end is never answered. */\nlet ending = false;\n\n/**\n * How long the sandbox waits for the commands it stopped to let go of their\n * output and their directory. They were stopped forced, so this is only the\n * time the system takes to end them; whatever still holds either after it has\n * left the tree, and no wait would end it.\n *\n * It is also how long the output of a command whose shell ended by itself is\n * waited for: what still holds it then is something the command started and\n * did not wait for, which is no part of the command.\n */\nconst SETTLE_MS = 3_000;\n\n/**\n * Whether a process has this id now. Signal 0 asks and sends nothing, and any\n * answer but \"no such process\" says one has it: another user's process\n * answers that it may not be signalled.\n */\nfunction taken(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code !== 'ESRCH';\n }\n}\n\n/**\n * Stops a command with what can be reached of what it started, forced:\n * SIGKILL to its process group on Linux and macOS, taskkill over its tree on\n * Windows. A process that left the group is not in it, and taskkill follows\n * a tree from parent to child while each parent runs: one whose parent has\n * ended is found under no root. Such a process runs on (ADR-0003).\n *\n * A command is stopped so at its timeout while its shell still runs, and at\n * an interrupt and at the exit of the process. One whose shell has ended is\n * answered and not stopped: what it left in its group runs on until the job\n * in its worktree ends, as what a step leaves runs on until its job ends in\n * CI, and is stopped then, by this.\n *\n * Both name the command by its id, and the id is the command's only while\n * something holds it (ADR-0003). Node holds the command's shell until it has\n * seen the shell end, and until then the system gives the id to nothing else.\n * After that the id is free on Windows, where a process started seconds later\n * can be given it: taskkill would stop that process with all it started, and\n * could not have found what the command left anyway, since it finds no tree\n * under a root that has ended. So a command whose shell has ended is not\n * stopped there. On Linux and macOS the id names the command's process group\n * as well, and stays out of use while the group has a member: what the shell\n * left in its group is still stopped, unless a process has the id now, which\n * says the group emptied and the id was given out again.\n *\n * `windowsHide` here and below only keeps a console window from opening on\n * Windows, which nothing reads, so its mutants are equivalent.\n */\nfunction stop(child: ChildProcess): void {\n // No pid means the spawn failed and nothing runs. Past the tick it failed\n // in, the kill below throws on the missing id and the fallback finds no\n // process, so the mutant that lets it through is equivalent; within that\n // tick nothing here stops a command.\n if (child.pid === undefined) return;\n // Node sets one of the two when it sees the shell end, and lets go of the\n // shell then. Windows reports no signal: there the second is set only once\n // the fallback below has stopped the shell, on the path no test takes.\n const held = child.exitCode === null && child.signalCode === null;\n // Windows is not asked whether a process has the id: one could be given it\n // between the answer and taskkill. Elsewhere `win32` is false already, so\n // the mutants that make it false are equivalent there.\n if (!held && (process.platform === 'win32' || taken(child.pid))) return;\n try {\n // False already on Linux and macOS, so the mutants that make it false\n // are equivalent there. On Windows the tests fail without taskkill:\n // stopping the shell alone leaves node holding the output. True already\n // on Windows, so the mutant that makes it true is equivalent there;\n // elsewhere there is no taskkill, and the shell alone is stopped.\n if (process.platform === 'win32') execFileSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });\n else process.kill(-child.pid, 'SIGKILL');\n } catch {\n // Reached when the group is already gone, and the command's shell with\n // it, as when the command left something outside the group holding its\n // output; on Windows when the shell has only just ended, which taskkill\n // sees before Node does; and there when taskkill cannot be run, where\n // stopping the shell is what is left. No test takes that last path.\n // `kill` goes through Node's own hold on the shell, and does nothing\n // once that is gone.\n child.kill('SIGKILL');\n }\n}\n\n/**\n * Deletes a worktree's directory, trying again for up to `SETTLE_MS` while\n * something holds it, and answers `null` once it is gone, or else why it is\n * not. On Windows a command just stopped lets go of its directory a moment\n * after taskkill returns, and an exit handler, which runs synchronously, has\n * no other way to wait; elsewhere a directory in use is deleted all the same.\n */\nfunction discard(directory: string): Error | null {\n const deadline = Date.now() + SETTLE_MS;\n for (;;) {\n try {\n rmSync(directory, { recursive: true, force: true });\n return null;\n } catch (error) {\n // `>=` would differ only in the millisecond the deadline falls on, so\n // that mutant is equivalent.\n if (Date.now() > deadline) return error as Error;\n // The pause only spares the processor between attempts: without it\n // the directory is deleted, or given up on, at the same moment, so\n // that mutant is equivalent.\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);\n }\n }\n}\n\n/**\n * Has git remove the worktree at `directory` with its record of it, as\n * `removeWorktree` does and synchronously, and answers whether git did.\n */\nfunction forget(directory: string, repository: string): boolean {\n try {\n execFileSync('git', ['worktree', 'remove', '--force', directory], { cwd: repository, stdio: 'ignore', windowsHide: true });\n // Asked again about a worktree it has forgotten, git changes nothing, so\n // the mutant that answers false here is equivalent.\n return true;\n } catch {\n // Git refused a worktree its job broke, could not delete all of the\n // directory, holds nothing of it any more, or cannot be run. The answer\n // is read with `!` and nowhere else, so the mutant that answers nothing\n // here is equivalent.\n return false;\n }\n}\n\n/**\n * Stops what the commands that ran in `directory` left in their process\n * groups, and forgets those commands: the end of a job, before its worktree\n * is removed. With no directory, what every command left: an interrupt, or\n * the exit of the process. One job's end leaves what another job's commands\n * left, which that job may still be using.\n */\nfunction clear(directory?: string): void {\n for (const [child, where] of left) {\n if (directory !== undefined && where !== directory) continue;\n stop(child);\n left.delete(child);\n }\n}\n\n/**\n * Stops every command still running, then removes every live worktree:\n * synchronously, the only kind of work an exit handler may do, so at exit\n * nothing waits for the commands to end but `discard`'s retries. A directory\n * that outlasts those is named on the standard error and left: nothing\n * thrown here could be caught, and the next worktree is still to remove.\n */\nfunction sweep(): void {\n for (const child of running) stop(child);\n clear();\n for (const [directory, repository] of live) {\n // In the order a job's end takes, for the reasons `withWorktree` gives.\n const forgotten = forget(directory, repository);\n const kept = discard(directory);\n if (kept !== null) process.stderr.write(`spec-harness: the temporary worktree at ${directory} could not be deleted and is left there: ${kept.message}\\n`);\n // The mutant that always asks again is equivalent, as in `forget`.\n else if (!forgotten) forget(directory, repository);\n }\n // A signal handler ends in an exit, which sweeps again: over worktrees\n // already gone and forgotten, where keeping them would change nothing, and\n // over one that could not be deleted, which would be named a second time.\n live.clear();\n}\n\n/**\n * Stops every running command with its tree, waits a bounded time for them to\n * let go of their output, removes the worktrees, and exits as a shell reports\n * a process the signal ended: 128 and the signal's number, the same on every\n * platform Node runs on. The commands lead process groups of their own on\n * Linux and macOS, so the terminal's signal never reached them.\n */\nasync function interrupted(signal: NodeJS.Signals): Promise<void> {\n ending = true;\n const stopping = [...running];\n for (const child of stopping) stop(child);\n // A command the stop ended is answered `SETTLE_MS` after its shell ended,\n // its output let go, so every one of them closes by then and the first of\n // the two below is over as soon as the second. The second is for a shell\n // the stop did not end, which no test can make: its mutant survives.\n await Promise.race([\n Promise.all(stopping.map((child) => new Promise((resolve) => child.once('close', resolve)))),\n new Promise((resolve) => setTimeout(resolve, SETTLE_MS)),\n ]);\n sweep();\n process.exit(128 + constants.signals[signal]);\n}\n\nfunction install(): void {\n if (installed) return;\n installed = true;\n process.once('exit', sweep);\n // `on`, not `once`: a second signal while the first waits would otherwise\n // meet Node's default, which ends the process before any 'exit' handler\n // runs, with the worktrees still in place. It runs the same steps again,\n // and the first to finish exits.\n //\n // SIGBREAK is Windows' own: Ctrl+Break, which GitHub's runner sends there,\n // after Ctrl+C, where it sends SIGTERM elsewhere. Unheard, it ends the\n // process before any 'exit' handler runs, and the commands run on.\n // Elsewhere there is no such signal and nothing calls its listener, so\n // its mutants are equivalent there.\n for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGBREAK'] as const) process.on(signal, interrupted);\n}\n\n/**\n * Runs `work` in a detached worktree of `repository` at `revision`, and\n * removes the worktree after.\n *\n * Git removes it first, while it is as the job left it: git then forgets the\n * worktree whether or not all of its directory can be deleted. What git left\n * of the directory is deleted next, which is all of it when the job broke the\n * worktree, since git refuses one whose `.git` file is gone. Only then is\n * git asked again, once the directory is gone, when it forgets what it finds\n * missing (`removeWorktree`).\n *\n * A directory that cannot be deleted stays on the list for the exit to try\n * again, and does not take the job's answer with it.\n *\n * What the job's commands left running in their process groups is stopped\n * first, so that the worktree is removed with as little running in it as the\n * sandbox can reach.\n */\nexport async function withWorktree<T>(repository: string, revision: string, work: (directory: string) => Promise<T>): Promise<T> {\n install();\n const directory = mkdtempSync(join(tmpdir(), 'spec-harness-'));\n live.set(directory, repository);\n try {\n await addWorktree(directory, revision, repository);\n return await work(directory);\n } finally {\n clear(directory);\n const forgotten = await removeWorktree(directory, repository);\n if (discard(directory) === null) {\n // Asked again about a worktree it has forgotten, git changes nothing,\n // so the mutant that always asks again is equivalent.\n if (!forgotten) await removeWorktree(directory, repository);\n live.delete(directory);\n }\n }\n}\n\nexport interface CommandRun {\n /** How the command's shell ended; `null` when the command was stopped at its timeout. */\n readonly exitCode: number | null;\n /** What the command had printed by the time it was answered. */\n readonly output: string;\n /**\n * Set on a command answered with its output still open: something it\n * started holds the output, `SETTLE_MS` after its shell ended or after its\n * timeout stopped what it could reach, and runs on (ADR-0003).\n */\n readonly outputHeld?: true;\n}\n\n/**\n * Runs a command line in a directory, output and errors interleaved, until\n * its shell ends. A command is its shell: it is answered with the shell's\n * exit code and what was printed, once the shell has ended and its output\n * has closed. A command whose shell outlives `timeoutSeconds` is stopped\n * with what `stop` reaches of it, as is one still running when the process\n * is interrupted or exits. Once the process is interrupted it never answers:\n * the job waiting on it would otherwise carry on in a worktree being removed.\n *\n * The wait for the output is bounded, after the shell's own end as after the\n * timeout. A shell that ends leaves its output open only where something it\n * started still holds it, and that is no part of the command: the answer is\n * the shell's, as a step's is in CI, where GitHub's runner waits five seconds\n * for such an output and goes on. Here the bound is `SETTLE_MS`, at the\n * shell's end and at the timeout alike. Then the sandbox lets go of the\n * output and answers with what was printed and with `outputHeld`. Letting go\n * is what the end of this process would do to whatever holds the output,\n * only sooner, and without it the open output keeps this process from ending\n * once its work is done.\n *\n * The timeout is the shell's: once the shell has ended it stops nothing, and\n * a command already judged by its exit code is not made a stopped one by it.\n *\n * Through the shell, on purpose: a probe's command is a line from the\n * repository's own brief - `npm test -- x` - which the person approved with\n * the brief, exactly as CI runs the repository's own scripts. Nothing from\n * outside the repository reaches it.\n *\n * The line is run as it is written. Its environment is the person's own as\n * `probeEnvironment` hands it on: `CI` set, and npm told to fetch nothing for\n * a command where neither that environment nor the line says what it may\n * fetch (ADR-0007).\n */\nexport function runCommand(line: string, cwd: string, timeoutSeconds: number): Promise<CommandRun> {\n install();\n return new Promise((resolve) => {\n // Elsewhere the command leads a process group of its own, so the timeout\n // can stop the group. Windows has none to signal, and taskkill follows\n // the tree instead; a command detached there loses its output, which the\n // tests catch on Windows. Everywhere else `detached` is true already, so\n // the mutants that make it true are equivalent there, as are\n // `windowsHide`'s.\n //\n // It is given no input: nobody is there to type any, and a pipe that is\n // never written to and never closed kept a command that reads its input\n // waiting until the timeout stopped it.\n const child = spawn(line, {\n cwd,\n shell: true,\n windowsHide: true,\n detached: process.platform !== 'win32',\n env: probeEnvironment(process.env),\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n running.add(child);\n let output = '';\n const keep = (chunk: Buffer): void => {\n // Enough to find a signature in; a runaway log is not kept whole.\n if (output.length < 4 * 1024 * 1024) output += chunk.toString('utf8');\n };\n // Both streams are piped, so both exist: `?.` only satisfies the type,\n // and its mutants are equivalent.\n child.stdout?.on('data', keep);\n child.stderr?.on('data', keep);\n const answer = (run: CommandRun): void => {\n if (!ending) resolve(run);\n };\n let stopped = false;\n let settling: NodeJS.Timeout | undefined;\n // Answers a command whose output is still open once the bound on the\n // wait for it has passed: `exitCode` is how its shell ended, or `null`\n // for one stopped at its timeout.\n const settle = (exitCode: number | null): void => {\n settling = setTimeout(() => {\n // With both let go, 'close' follows as soon as Node has seen the\n // shell end, and takes the command off the list of those running.\n // The streams exist, as above, so the mutants of `?.` are equivalent.\n child.stdout?.destroy();\n child.stderr?.destroy();\n answer({ exitCode, output, outputHeld: true });\n }, SETTLE_MS);\n };\n const timer = setTimeout(() => {\n stopped = true;\n stop(child);\n settle(null);\n }, timeoutSeconds * 1000);\n child.on('error', (error) => {\n // A spawn that failed starts no shell, whose end would clear the timer.\n clearTimeout(timer);\n resolve({ exitCode: 127, output: `${output}${error.message}\\n` });\n });\n child.on('exit', (code) => {\n // The shell its timeout stopped: the timeout has the answer already.\n if (stopped) return;\n // The shell ended by itself, so the timeout has nothing left to stop.\n clearTimeout(timer);\n // A group of the shell's id that still has a member is what the shell\n // left running in it, to be stopped when its job ends. The id is set:\n // a shell that was never started does not end. Windows has no group,\n // and answers that there is none.\n if (taken(-(child.pid as number))) left.set(child, cwd);\n // A shell that a signal ended has no code: a failure, as in 'close'.\n settle(code ?? 1);\n });\n child.on('close', (code) => {\n // The command's own timer is over by now: cleared as its shell ended\n // or as its spawn failed, or run. What is left is the bound.\n clearTimeout(settling);\n running.delete(child);\n // The second answer of a command already answered as held does nothing.\n answer({ exitCode: stopped ? null : (code ?? 1), output });\n });\n });\n}\n"]}
|
package/dist/server.js
CHANGED
|
@@ -14,6 +14,7 @@ import { briefIdFromBranch } from './branch.js';
|
|
|
14
14
|
import { titleOf } from './context.js';
|
|
15
15
|
import { createReader } from './reader.js';
|
|
16
16
|
import { buildContext, checkPaths, raiseEscalation, runAudit } from './round.js';
|
|
17
|
+
import { emptyValue, isBlank } from './usage.js';
|
|
17
18
|
import { createMcpServer, serveLines, toolError, unknownArguments, } from './vendor/spec-core/jsonrpc/index.js';
|
|
18
19
|
import { describeActive, openWorkspace, version } from './workspace.js';
|
|
19
20
|
const reader = createReader();
|
|
@@ -22,25 +23,78 @@ export const INSTRUCTIONS = 'spec-harness keeps a round of work inside the brief
|
|
|
22
23
|
'Call check_path before writing a file you are unsure of. A protected file needs a ruling: call request_escalation and stop until a person rules. ' +
|
|
23
24
|
'Call audit_round when the work is done, and fix what it reports; archiving is a person\'s decision. ' +
|
|
24
25
|
'For the architecture rules themselves, spec-guard\'s own server answers get_architectural_rules.';
|
|
25
|
-
const briefProperty = { type: 'string', description: 'The brief id. Omit to use the brief the branch or SPEC_BRIEF names.' };
|
|
26
|
+
const briefProperty = { type: 'string', description: 'The brief id. Omit to use the brief the branch or SPEC_BRIEF names; an empty id is refused.' };
|
|
26
27
|
const baseProperty = {
|
|
27
28
|
type: 'string',
|
|
28
|
-
description: 'The branch the round is measured from, whose allowed signers a ruling is verified against. Omit to use the configured base.',
|
|
29
|
+
description: 'The branch the round is measured from, whose allowed signers a ruling is verified against. Omit to use the configured base; an empty one is refused.',
|
|
29
30
|
};
|
|
30
|
-
/**
|
|
31
|
+
/**
|
|
32
|
+
* The tool error for an argument that is given and names nothing, in the
|
|
33
|
+
* words the command line has for its option. Read as left out, an empty
|
|
34
|
+
* `brief` was answered for the branch's brief and an empty `base` with no
|
|
35
|
+
* ruling verified, and nothing told the agent that neither was the answer to
|
|
36
|
+
* what it had asked.
|
|
37
|
+
*/
|
|
38
|
+
function namesNothing(argument, option, value) {
|
|
39
|
+
return toolError(`${emptyValue(`"${argument}"`, option, value)}.`);
|
|
40
|
+
}
|
|
41
|
+
/** The `base` argument, or the tool error for one that is not a string, or names no commit. */
|
|
31
42
|
function baseOf(args) {
|
|
32
43
|
const base = args['base'];
|
|
33
44
|
if (base !== undefined && typeof base !== 'string')
|
|
34
45
|
return toolError('"base" must be a string.');
|
|
46
|
+
if (base !== undefined && isBlank(base))
|
|
47
|
+
return namesNothing('base', 'base', base);
|
|
35
48
|
return { base };
|
|
36
49
|
}
|
|
50
|
+
/** The `paths` argument, or the tool error for one that is no list of files, or has a place that names none. */
|
|
51
|
+
function pathsOf(args) {
|
|
52
|
+
const paths = args['paths'];
|
|
53
|
+
if (!Array.isArray(paths) || !paths.every((p) => typeof p === 'string') || paths.length === 0) {
|
|
54
|
+
return toolError('"paths" must be a non-empty array of strings.');
|
|
55
|
+
}
|
|
56
|
+
const empty = paths.findIndex(isBlank);
|
|
57
|
+
if (empty !== -1)
|
|
58
|
+
return namesNothing(`paths[${empty}]`, 'path', paths[empty]);
|
|
59
|
+
return { paths };
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The `options` argument as the memo's choices, or the tool error for one
|
|
63
|
+
* the memo cannot be written with: a choice is its label, and one without
|
|
64
|
+
* was written as a number and two empty stars. What a choice costs may be
|
|
65
|
+
* left out, and the memo then gives the choice alone.
|
|
66
|
+
*/
|
|
67
|
+
function optionsOf(args) {
|
|
68
|
+
const raw = args['options'] ?? [];
|
|
69
|
+
if (!Array.isArray(raw))
|
|
70
|
+
return toolError('"options" must be an array.');
|
|
71
|
+
const options = [];
|
|
72
|
+
for (const [index, item] of raw.entries()) {
|
|
73
|
+
// An item that is no object has no label, and is refused for that.
|
|
74
|
+
const entry = (item ?? {});
|
|
75
|
+
const label = entry['label'];
|
|
76
|
+
const consequence = entry['consequence'] ?? '';
|
|
77
|
+
if (typeof label !== 'string')
|
|
78
|
+
return toolError(`"options[${index}].label" must be a string.`);
|
|
79
|
+
if (isBlank(label))
|
|
80
|
+
return toolError(`"options[${index}].label" is ${JSON.stringify(label)}, which names no choice; give the option a label, or leave the option out.`);
|
|
81
|
+
if (typeof consequence !== 'string')
|
|
82
|
+
return toolError(`"options[${index}].consequence" must be a string.`);
|
|
83
|
+
options.push({ label: label.trim(), consequence: consequence.trim() });
|
|
84
|
+
}
|
|
85
|
+
return { options };
|
|
86
|
+
}
|
|
37
87
|
async function round(workspace, env, id) {
|
|
38
88
|
if (id !== undefined && typeof id !== 'string')
|
|
39
89
|
return toolError('"brief" must be a string.');
|
|
90
|
+
if (id !== undefined && isBlank(id))
|
|
91
|
+
return namesNothing('brief', 'brief', id);
|
|
40
92
|
const briefs = await workspace.siblings.briefs();
|
|
41
93
|
const fromBranch = briefIdFromBranch(workspace.config.branches, workspace.branch);
|
|
42
|
-
const active = findActive(briefs, {
|
|
43
|
-
|
|
94
|
+
const active = findActive(briefs, { argument: id, environment: env['SPEC_BRIEF'], branch: fromBranch });
|
|
95
|
+
// Named as every argument of a tool is, where it was called the flag, and
|
|
96
|
+
// a tool call has none.
|
|
97
|
+
const { brief, note, problem } = describeActive(active, '"brief"');
|
|
44
98
|
if (problem !== null)
|
|
45
99
|
return toolError(problem);
|
|
46
100
|
if (brief === null)
|
|
@@ -93,7 +147,7 @@ export function tools(workspace, env) {
|
|
|
93
147
|
inputSchema: {
|
|
94
148
|
type: 'object',
|
|
95
149
|
properties: {
|
|
96
|
-
paths: { type: 'array', items: { type: 'string' }, description: 'Paths relative to the project root, or absolute inside it.' },
|
|
150
|
+
paths: { type: 'array', items: { type: 'string' }, description: 'Paths relative to the project root, or absolute inside it. An empty one is refused.' },
|
|
97
151
|
brief: briefProperty,
|
|
98
152
|
base: baseProperty,
|
|
99
153
|
},
|
|
@@ -106,17 +160,16 @@ export function tools(workspace, env) {
|
|
|
106
160
|
const unknown = unknownArguments(args, ['paths', 'brief', 'base']);
|
|
107
161
|
if (unknown)
|
|
108
162
|
return unknown;
|
|
109
|
-
const
|
|
110
|
-
if (
|
|
111
|
-
return
|
|
112
|
-
}
|
|
163
|
+
const given = pathsOf(args);
|
|
164
|
+
if ('text' in given)
|
|
165
|
+
return given;
|
|
113
166
|
const base = baseOf(args);
|
|
114
167
|
if ('text' in base)
|
|
115
168
|
return base;
|
|
116
169
|
const found = await round(workspace, env, args['brief']);
|
|
117
170
|
if ('text' in found)
|
|
118
171
|
return found;
|
|
119
|
-
const decisions = await checkPaths(workspace, found.brief, undefined, paths, workspace.root, reader, base.base);
|
|
172
|
+
const decisions = await checkPaths(workspace, found.brief, undefined, given.paths, workspace.root, reader, base.base);
|
|
120
173
|
const text = decisions.map((d) => `${d.verdict}: ${d.message}${d.verdict === 'allow' ? '' : `. Next: ${d.hint}`}`).join('\n');
|
|
121
174
|
return { text, structured: { decisions: decisions.map((d) => ({ ...d })) } };
|
|
122
175
|
},
|
|
@@ -129,14 +182,14 @@ export function tools(workspace, env) {
|
|
|
129
182
|
inputSchema: {
|
|
130
183
|
type: 'object',
|
|
131
184
|
properties: {
|
|
132
|
-
paths: { type: 'array', items: { type: 'string' }, description: 'The protected files the round needs to change.' },
|
|
133
|
-
reason: { type: 'string', description: 'Why the round cannot be done without them.' },
|
|
185
|
+
paths: { type: 'array', items: { type: 'string' }, description: 'The protected files the round needs to change. An empty one is refused.' },
|
|
186
|
+
reason: { type: 'string', description: 'Why the round cannot be done without them. It is required, and may not be empty.' },
|
|
134
187
|
options: {
|
|
135
188
|
type: 'array',
|
|
136
189
|
items: { type: 'object', properties: { label: { type: 'string' }, consequence: { type: 'string' } }, required: ['label', 'consequence'] },
|
|
137
|
-
description: 'The choices the person has, each with what it costs.',
|
|
190
|
+
description: 'The choices the person has, each with what it costs. A choice whose label is empty is refused.',
|
|
138
191
|
},
|
|
139
|
-
recommendation: { type: 'string', description: 'Which option you recommend, and why.' },
|
|
192
|
+
recommendation: { type: 'string', description: 'Which option you recommend, and why. Omit it when there is none: an empty one is refused.' },
|
|
140
193
|
brief: briefProperty,
|
|
141
194
|
},
|
|
142
195
|
required: ['paths', 'reason'],
|
|
@@ -148,23 +201,31 @@ export function tools(workspace, env) {
|
|
|
148
201
|
const unknown = unknownArguments(args, ['paths', 'reason', 'options', 'recommendation', 'brief']);
|
|
149
202
|
if (unknown)
|
|
150
203
|
return unknown;
|
|
151
|
-
|
|
204
|
+
// Every part of the memo before anything is written: a person rules
|
|
205
|
+
// on what it says, and cannot rule on a part that says nothing.
|
|
206
|
+
const given = pathsOf(args);
|
|
207
|
+
if ('text' in given)
|
|
208
|
+
return given;
|
|
152
209
|
const reason = args['reason'];
|
|
153
|
-
if (
|
|
154
|
-
return toolError('"paths" must be a non-empty array of strings.');
|
|
155
|
-
if (typeof reason !== 'string' || reason.trim() === '')
|
|
210
|
+
if (typeof reason !== 'string' || isBlank(reason))
|
|
156
211
|
return toolError('"reason" is required.');
|
|
157
|
-
const
|
|
158
|
-
if (
|
|
159
|
-
return
|
|
160
|
-
const options = rawOptions.map((o) => ({ label: String(o['label'] ?? ''), consequence: String(o['consequence'] ?? '') }));
|
|
212
|
+
const choices = optionsOf(args);
|
|
213
|
+
if ('text' in choices)
|
|
214
|
+
return choices;
|
|
161
215
|
const recommendation = args['recommendation'];
|
|
162
216
|
if (recommendation !== undefined && typeof recommendation !== 'string')
|
|
163
217
|
return toolError('"recommendation" must be a string.');
|
|
218
|
+
if (recommendation !== undefined && isBlank(recommendation))
|
|
219
|
+
return namesNothing('recommendation', 'recommend', recommendation);
|
|
164
220
|
const found = await round(workspace, env, args['brief']);
|
|
165
221
|
if ('text' in found)
|
|
166
222
|
return found;
|
|
167
|
-
const { request, memo } = await raiseEscalation(workspace, found.brief, {
|
|
223
|
+
const { request, memo } = await raiseEscalation(workspace, found.brief, {
|
|
224
|
+
paths: given.paths,
|
|
225
|
+
reason,
|
|
226
|
+
options: choices.options,
|
|
227
|
+
recommendation: recommendation ?? null,
|
|
228
|
+
});
|
|
168
229
|
return { text: `${memo}\nStop here until a person rules on ${request.id}.`, structured: { id: request.id } };
|
|
169
230
|
},
|
|
170
231
|
},
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEjF,OAAO,EACL,eAAe,EACf,UAAU,EACV,SAAS,EACT,gBAAgB,GAKjB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,OAAO,EAA4C,MAAM,gBAAgB,CAAC;AAElH,MAAM,MAAM,GAAG,YAAY,EAA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MAAM,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC;QACrG,CAAC;KACF,CAAC,CAAC,CAAC;AACN,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,OAAgB,EAAE,EAAS;IAC1D,4EAA4E;IAC5E,yEAAyE;IACzE,MAAM,SAAS,GAAG,MAAM,aAAa,CAAC,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,oBAAoB,CAAC,IAAI,SAAS,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7H,MAAM,MAAM,GAAG,eAAe,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,YAAY,EAAE,YAAY,EAAE,KAAK,EAAE,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC;IAC9J,yEAAyE;IACzE,+DAA+D;IAC/D,uEAAuE;IACvE,yEAAyE;IACzE,MAAM,KAAK,GAAG,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;IACtG,MAAM,UAAU,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC;IACxE,OAAO,CAAC,CAAC;AACX,CAAC","sourcesContent":["/**\n * `spec-harness mcp`: the round's questions, served over the Model Context\n * Protocol on stdio (ADR-0008). The protocol is spec-core's `jsonrpc` module;\n * this file is the five tools, the four prompts, and nothing else. Every\n * request reads the repository afresh: a brief edited a minute ago is the\n * brief the next answer uses.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { Readable } from 'node:stream';\nimport { fileURLToPath } from 'node:url';\n\nimport { describeMeasured } from './audit.js';\nimport { findActive } from './briefs.js';\nimport { briefIdFromBranch } from './branch.js';\nimport { titleOf } from './context.js';\nimport { createReader } from './reader.js';\nimport { buildContext, checkPaths, raiseEscalation, runAudit } from './round.js';\nimport type { BriefRow } from './types.js';\nimport {\n createMcpServer,\n serveLines,\n toolError,\n unknownArguments,\n type JsonObject,\n type PromptDefinition,\n type ToolDefinition,\n type ToolOutcome,\n} from './vendor/spec-core/jsonrpc/index.js';\nimport { describeActive, openWorkspace, version, type CliIO, type Options, type Workspace } from './workspace.js';\n\nconst reader = createReader();\n\nexport const INSTRUCTIONS =\n 'spec-harness keeps a round of work inside the brief a person approved. ' +\n 'Call start_round before working: it returns the brief, the scope you may write, what you must not touch, the rules in force and the documents the brief cites. ' +\n 'Call check_path before writing a file you are unsure of. A protected file needs a ruling: call request_escalation and stop until a person rules. ' +\n 'Call audit_round when the work is done, and fix what it reports; archiving is a person\\'s decision. ' +\n 'For the architecture rules themselves, spec-guard\\'s own server answers get_architectural_rules.';\n\nconst briefProperty = { type: 'string', description: 'The brief id. Omit to use the brief the branch or SPEC_BRIEF names.' };\nconst baseProperty = {\n type: 'string',\n description: 'The branch the round is measured from, whose allowed signers a ruling is verified against. Omit to use the configured base.',\n};\n\n/** The `base` argument, or the tool error for one that is not a string. */\nfunction baseOf(args: JsonObject): { base: string | undefined } | ToolOutcome {\n const base = args['base'];\n if (base !== undefined && typeof base !== 'string') return toolError('\"base\" must be a string.');\n return { base };\n}\n\nasync function round(workspace: Workspace, env: CliIO['env'], id: unknown): Promise<{ brief: BriefRow; briefs: BriefRow[] } | ToolOutcome> {\n if (id !== undefined && typeof id !== 'string') return toolError('\"brief\" must be a string.');\n const briefs = await workspace.siblings.briefs();\n const fromBranch = briefIdFromBranch(workspace.config.branches, workspace.branch);\n const active = findActive(briefs, { flag: id, environment: env['SPEC_BRIEF'], branch: fromBranch });\n const { brief, note, problem } = describeActive(active);\n if (problem !== null) return toolError(problem);\n if (brief === null) return toolError(note);\n return { brief, briefs };\n}\n\nexport function tools(workspace: Workspace, env: CliIO['env']): ToolDefinition[] {\n const readOnly = { readOnlyHint: true, idempotentHint: true, openWorldHint: false };\n return [\n {\n descriptor: {\n name: 'start_round',\n title: 'Start a round',\n description:\n 'Everything needed to start the round: the brief in full, the files it may write and must not change, signed rulings, the briefs it depends on, the architecture rules in force for its scope, and the documents it cites.',\n inputSchema: { type: 'object', properties: { brief: briefProperty, base: baseProperty }, additionalProperties: false },\n annotations: readOnly,\n },\n async call(args: JsonObject): Promise<ToolOutcome> {\n const unknown = unknownArguments(args, ['brief', 'base']);\n if (unknown) return unknown;\n const base = baseOf(args);\n if ('text' in base) return base;\n const found = await round(workspace, env, args['brief']);\n if ('text' in found) return found;\n const packet = await buildContext(workspace, found.brief, found.briefs, reader, base.base);\n return {\n text: packet.markdown,\n structured: {\n brief: found.brief.id,\n included: [...packet.included],\n omitted: [...packet.omitted],\n unresolved: [...packet.unresolved],\n unclosedFrontMatter: [...packet.unclosedFrontMatter],\n unreadableFrontMatter: [...packet.unreadableFrontMatter],\n unreadableScope: [...packet.unreadableScope],\n unreadableProtections: [...packet.unreadableProtections],\n unreadableRulingPaths: [...packet.unreadableRulingPaths],\n },\n };\n },\n },\n {\n descriptor: {\n name: 'check_path',\n title: 'May the round write these files',\n description:\n 'For each path: allowed (in scope, or covered by a signed ruling), outside the scope, or refused (protected by the brief). Works for files that do not exist yet.',\n inputSchema: {\n type: 'object',\n properties: {\n paths: { type: 'array', items: { type: 'string' }, description: 'Paths relative to the project root, or absolute inside it.' },\n brief: briefProperty,\n base: baseProperty,\n },\n required: ['paths'],\n additionalProperties: false,\n },\n annotations: readOnly,\n },\n async call(args: JsonObject): Promise<ToolOutcome> {\n const unknown = unknownArguments(args, ['paths', 'brief', 'base']);\n if (unknown) return unknown;\n const paths = args['paths'];\n if (!Array.isArray(paths) || !paths.every((p) => typeof p === 'string') || paths.length === 0) {\n return toolError('\"paths\" must be a non-empty array of strings.');\n }\n const base = baseOf(args);\n if ('text' in base) return base;\n const found = await round(workspace, env, args['brief']);\n if ('text' in found) return found;\n const decisions = await checkPaths(workspace, found.brief, undefined, paths as string[], workspace.root, reader, base.base);\n const text = decisions.map((d) => `${d.verdict}: ${d.message}${d.verdict === 'allow' ? '' : `. Next: ${d.hint}`}`).join('\\n');\n return { text, structured: { decisions: decisions.map((d) => ({ ...d })) } };\n },\n },\n {\n descriptor: {\n name: 'request_escalation',\n title: 'Ask a person to rule',\n description:\n 'When the round cannot be finished without changing something the brief protects, record the request and stop. A person reads the memo and rules; only a ruling they sign lets the change through.',\n inputSchema: {\n type: 'object',\n properties: {\n paths: { type: 'array', items: { type: 'string' }, description: 'The protected files the round needs to change.' },\n reason: { type: 'string', description: 'Why the round cannot be done without them.' },\n options: {\n type: 'array',\n items: { type: 'object', properties: { label: { type: 'string' }, consequence: { type: 'string' } }, required: ['label', 'consequence'] },\n description: 'The choices the person has, each with what it costs.',\n },\n recommendation: { type: 'string', description: 'Which option you recommend, and why.' },\n brief: briefProperty,\n },\n required: ['paths', 'reason'],\n additionalProperties: false,\n },\n annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: false },\n },\n async call(args: JsonObject): Promise<ToolOutcome> {\n const unknown = unknownArguments(args, ['paths', 'reason', 'options', 'recommendation', 'brief']);\n if (unknown) return unknown;\n const paths = args['paths'];\n const reason = args['reason'];\n if (!Array.isArray(paths) || !paths.every((p) => typeof p === 'string') || paths.length === 0) return toolError('\"paths\" must be a non-empty array of strings.');\n if (typeof reason !== 'string' || reason.trim() === '') return toolError('\"reason\" is required.');\n const rawOptions = args['options'] ?? [];\n if (!Array.isArray(rawOptions)) return toolError('\"options\" must be an array.');\n const options = rawOptions.map((o) => ({ label: String((o as JsonObject)['label'] ?? ''), consequence: String((o as JsonObject)['consequence'] ?? '') }));\n const recommendation = args['recommendation'];\n if (recommendation !== undefined && typeof recommendation !== 'string') return toolError('\"recommendation\" must be a string.');\n const found = await round(workspace, env, args['brief']);\n if ('text' in found) return found;\n const { request, memo } = await raiseEscalation(workspace, found.brief, { paths: paths as string[], reason, options, recommendation: recommendation ?? null });\n return { text: `${memo}\\nStop here until a person rules on ${request.id}.`, structured: { id: request.id } };\n },\n },\n {\n descriptor: {\n name: 'audit_round',\n title: 'Audit the round',\n description:\n 'Did the round stay inside the lines: what the archive would refuse (open boxes, protected files, files outside the scope), the brief\\'s own assertions, unverified rulings, every dependency added and every package allowed to run install scripts.',\n inputSchema: { type: 'object', properties: { brief: briefProperty, base: baseProperty }, additionalProperties: false },\n annotations: readOnly,\n },\n async call(args: JsonObject): Promise<ToolOutcome> {\n const unknown = unknownArguments(args, ['brief', 'base']);\n if (unknown) return unknown;\n const base = baseOf(args);\n if ('text' in base) return base;\n const found = await round(workspace, env, args['brief']);\n if ('text' in found) return found;\n const result = await runAudit(workspace, found.brief, reader, base.base);\n const { counts, findings, measured } = result.report;\n // What was measured beside what was found: \"nothing found\" from an\n // audit that ran no goal is not a round that is done.\n const text =\n findings.length === 0\n ? 'The audit found nothing in what it measured.'\n : findings.map((f) => `${f.severity} ${f.rule}: ${f.message}. Next: ${f.hint}`).join('\\n');\n return {\n text: `${text}\\n\\n${describeMeasured(measured)}\\n\\n${counts.error} error(s), ${counts.warning} warning(s), ${counts.note} note(s)`,\n structured: { counts, measured: { ...measured }, findings: findings.map((f) => ({ ...f })) },\n };\n },\n },\n {\n descriptor: {\n name: 'list_rounds',\n title: 'List the rounds',\n description: 'The live briefs: status, wave, what each waits on, and which are ready to start.',\n inputSchema: { type: 'object', properties: {}, additionalProperties: false },\n annotations: readOnly,\n },\n async call(args: JsonObject): Promise<ToolOutcome> {\n const unknown = unknownArguments(args, []);\n if (unknown) return unknown;\n const live = (await workspace.siblings.briefs()).filter((brief) => brief.phase === 'live');\n const text = live\n .map((b) => `${[b.id, titleOf(b)].filter((part) => part !== null).join(' ')} - ${b.status ?? 'unknown'}, wave ${b.wave ?? '-'}, ${b.ready ? 'ready' : `waits on ${b.waitingOn.join(', ')}`}`)\n .join('\\n');\n return { text: text === '' ? 'No live brief.' : text, structured: { briefs: live.map((b) => ({ ...b, title: titleOf(b) })) } };\n },\n },\n ];\n}\n\nconst SKILLS: readonly { name: string; title: string; argument: string; description: string }[] = [\n { name: 'draft-brief', title: 'Draft a brief', argument: 'request', description: 'What the round should achieve, in the person\\'s words.' },\n { name: 'split-goal', title: 'Split a goal into rounds', argument: 'goal', description: 'The goal to split.' },\n { name: 'run-round', title: 'Run a round', argument: 'brief', description: 'The brief id.' },\n { name: 'close-round', title: 'Close a round', argument: 'brief', description: 'The brief id.' },\n];\n\nfunction skillText(name: string): string {\n // The package ships the skills beside dist/ (package.json's files), so one\n // that cannot be read is a broken install, and the request fails saying so\n // rather than serving an empty prompt.\n const text = readFileSync(fileURLToPath(new URL(`../skills/${name}/SKILL.md`, import.meta.url)), 'utf8');\n // Every skill opens with its front matter (tests/source.test.ts), so the\n // anchor is equivalent to its mutant here.\n return text.replace(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n/, '').trim();\n}\n\nexport function prompts(): PromptDefinition[] {\n return SKILLS.map((skill) => ({\n descriptor: {\n name: skill.name,\n title: skill.title,\n arguments: [{ name: skill.argument, description: skill.description, required: false }],\n },\n async get(args: Readonly<Record<string, string>>): Promise<JsonObject> {\n const given = args[skill.argument];\n const text = `${skillText(skill.name)}${given === undefined || given === '' ? '' : `\\n\\n${skill.argument}: ${given}`}`;\n return { description: skill.title, messages: [{ role: 'user', content: { type: 'text', text } }] };\n },\n }));\n}\n\nexport async function mcpCommand(options: Options, io: CliIO): Promise<number> {\n // Claude Code starts a plugin's server in the plugin's directory, and names\n // the project in CLAUDE_PROJECT_DIR; the server answers for the project.\n const workspace = await openWorkspace({ ...options, root: options.root ?? (io.env['CLAUDE_PROJECT_DIR'] || undefined) }, io);\n const handle = createMcpServer({ name: 'spec-harness', version: version(), instructions: INSTRUCTIONS, tools: tools(workspace, io.env), prompts: prompts() });\n // A session handed over whole, as a test hands it, is served as a client\n // would stream it on stdin. Only the built command line serves\n // process.stdin, and the suite spawns it from dist/, outside the sweep\n // (tests/integration/mcp.test.ts), so a mutant that ignores it survives.\n const input = io.stdin === undefined ? process.stdin : Readable.from([Buffer.from(await io.stdin())]);\n await serveLines(input, (line) => io.stdout.write(`${line}\\n`), handle);\n return 0;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAGjF,OAAO,EAAE,UAAU,EAAE,OAAO,EAAqB,MAAM,YAAY,CAAC;AACpE,OAAO,EACL,eAAe,EACf,UAAU,EACV,SAAS,EACT,gBAAgB,GAKjB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,OAAO,EAA4C,MAAM,gBAAgB,CAAC;AAElH,MAAM,MAAM,GAAG,YAAY,EAAE,CAAC;AAE9B,MAAM,CAAC,MAAM,YAAY,GACvB,yEAAyE;IACzE,iKAAiK;IACjK,mJA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,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;IACtG,MAAM,UAAU,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC;IACxE,OAAO,CAAC,CAAC;AACX,CAAC","sourcesContent":["/**\n * `spec-harness mcp`: the round's questions, served over the Model Context\n * Protocol on stdio (ADR-0008). The protocol is spec-core's `jsonrpc` module;\n * this file is the five tools, the four prompts, and nothing else. Every\n * request reads the repository afresh: a brief edited a minute ago is the\n * brief the next answer uses.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { Readable } from 'node:stream';\nimport { fileURLToPath } from 'node:url';\n\nimport { describeMeasured } from './audit.js';\nimport { findActive } from './briefs.js';\nimport { briefIdFromBranch } from './branch.js';\nimport { titleOf } from './context.js';\nimport { createReader } from './reader.js';\nimport { buildContext, checkPaths, raiseEscalation, runAudit } from './round.js';\nimport type { EscalationOption } from './rulings.js';\nimport type { BriefRow } from './types.js';\nimport { emptyValue, isBlank, type ValuedOption } from './usage.js';\nimport {\n createMcpServer,\n serveLines,\n toolError,\n unknownArguments,\n type JsonObject,\n type PromptDefinition,\n type ToolDefinition,\n type ToolOutcome,\n} from './vendor/spec-core/jsonrpc/index.js';\nimport { describeActive, openWorkspace, version, type CliIO, type Options, type Workspace } from './workspace.js';\n\nconst reader = createReader();\n\nexport const INSTRUCTIONS =\n 'spec-harness keeps a round of work inside the brief a person approved. ' +\n 'Call start_round before working: it returns the brief, the scope you may write, what you must not touch, the rules in force and the documents the brief cites. ' +\n 'Call check_path before writing a file you are unsure of. A protected file needs a ruling: call request_escalation and stop until a person rules. ' +\n 'Call audit_round when the work is done, and fix what it reports; archiving is a person\\'s decision. ' +\n 'For the architecture rules themselves, spec-guard\\'s own server answers get_architectural_rules.';\n\nconst briefProperty = { type: 'string', description: 'The brief id. Omit to use the brief the branch or SPEC_BRIEF names; an empty id is refused.' };\nconst baseProperty = {\n type: 'string',\n description:\n 'The branch the round is measured from, whose allowed signers a ruling is verified against. Omit to use the configured base; an empty one is refused.',\n};\n\n/**\n * The tool error for an argument that is given and names nothing, in the\n * words the command line has for its option. Read as left out, an empty\n * `brief` was answered for the branch's brief and an empty `base` with no\n * ruling verified, and nothing told the agent that neither was the answer to\n * what it had asked.\n */\nfunction namesNothing(argument: string, option: ValuedOption, value: string): ToolOutcome {\n return toolError(`${emptyValue(`\"${argument}\"`, option, value)}.`);\n}\n\n/** The `base` argument, or the tool error for one that is not a string, or names no commit. */\nfunction baseOf(args: JsonObject): { base: string | undefined } | ToolOutcome {\n const base = args['base'];\n if (base !== undefined && typeof base !== 'string') return toolError('\"base\" must be a string.');\n if (base !== undefined && isBlank(base)) return namesNothing('base', 'base', base);\n return { base };\n}\n\n/** The `paths` argument, or the tool error for one that is no list of files, or has a place that names none. */\nfunction pathsOf(args: JsonObject): { paths: string[] } | ToolOutcome {\n const paths = args['paths'];\n if (!Array.isArray(paths) || !paths.every((p) => typeof p === 'string') || paths.length === 0) {\n return toolError('\"paths\" must be a non-empty array of strings.');\n }\n const empty = paths.findIndex(isBlank);\n if (empty !== -1) return namesNothing(`paths[${empty}]`, 'path', paths[empty] as string);\n return { paths };\n}\n\n/**\n * The `options` argument as the memo's choices, or the tool error for one\n * the memo cannot be written with: a choice is its label, and one without\n * was written as a number and two empty stars. What a choice costs may be\n * left out, and the memo then gives the choice alone.\n */\nfunction optionsOf(args: JsonObject): { options: EscalationOption[] } | ToolOutcome {\n const raw = args['options'] ?? [];\n if (!Array.isArray(raw)) return toolError('\"options\" must be an array.');\n const options: EscalationOption[] = [];\n for (const [index, item] of raw.entries()) {\n // An item that is no object has no label, and is refused for that.\n const entry = (item ?? {}) as JsonObject;\n const label = entry['label'];\n const consequence = entry['consequence'] ?? '';\n if (typeof label !== 'string') return toolError(`\"options[${index}].label\" must be a string.`);\n if (isBlank(label)) return toolError(`\"options[${index}].label\" is ${JSON.stringify(label)}, which names no choice; give the option a label, or leave the option out.`);\n if (typeof consequence !== 'string') return toolError(`\"options[${index}].consequence\" must be a string.`);\n options.push({ label: label.trim(), consequence: consequence.trim() });\n }\n return { options };\n}\n\nasync function round(workspace: Workspace, env: CliIO['env'], id: unknown): Promise<{ brief: BriefRow; briefs: BriefRow[] } | ToolOutcome> {\n if (id !== undefined && typeof id !== 'string') return toolError('\"brief\" must be a string.');\n if (id !== undefined && isBlank(id)) return namesNothing('brief', 'brief', id);\n const briefs = await workspace.siblings.briefs();\n const fromBranch = briefIdFromBranch(workspace.config.branches, workspace.branch);\n const active = findActive(briefs, { argument: id, environment: env['SPEC_BRIEF'], branch: fromBranch });\n // Named as every argument of a tool is, where it was called the flag, and\n // a tool call has none.\n const { brief, note, problem } = describeActive(active, '\"brief\"');\n if (problem !== null) return toolError(problem);\n if (brief === null) return toolError(note);\n return { brief, briefs };\n}\n\nexport function tools(workspace: Workspace, env: CliIO['env']): ToolDefinition[] {\n const readOnly = { readOnlyHint: true, idempotentHint: true, openWorldHint: false };\n return [\n {\n descriptor: {\n name: 'start_round',\n title: 'Start a round',\n description:\n 'Everything needed to start the round: the brief in full, the files it may write and must not change, signed rulings, the briefs it depends on, the architecture rules in force for its scope, and the documents it cites.',\n inputSchema: { type: 'object', properties: { brief: briefProperty, base: baseProperty }, additionalProperties: false },\n annotations: readOnly,\n },\n async call(args: JsonObject): Promise<ToolOutcome> {\n const unknown = unknownArguments(args, ['brief', 'base']);\n if (unknown) return unknown;\n const base = baseOf(args);\n if ('text' in base) return base;\n const found = await round(workspace, env, args['brief']);\n if ('text' in found) return found;\n const packet = await buildContext(workspace, found.brief, found.briefs, reader, base.base);\n return {\n text: packet.markdown,\n structured: {\n brief: found.brief.id,\n included: [...packet.included],\n omitted: [...packet.omitted],\n unresolved: [...packet.unresolved],\n unclosedFrontMatter: [...packet.unclosedFrontMatter],\n unreadableFrontMatter: [...packet.unreadableFrontMatter],\n unreadableScope: [...packet.unreadableScope],\n unreadableProtections: [...packet.unreadableProtections],\n unreadableRulingPaths: [...packet.unreadableRulingPaths],\n },\n };\n },\n },\n {\n descriptor: {\n name: 'check_path',\n title: 'May the round write these files',\n description:\n 'For each path: allowed (in scope, or covered by a signed ruling), outside the scope, or refused (protected by the brief). Works for files that do not exist yet.',\n inputSchema: {\n type: 'object',\n properties: {\n paths: { type: 'array', items: { type: 'string' }, description: 'Paths relative to the project root, or absolute inside it. An empty one is refused.' },\n brief: briefProperty,\n base: baseProperty,\n },\n required: ['paths'],\n additionalProperties: false,\n },\n annotations: readOnly,\n },\n async call(args: JsonObject): Promise<ToolOutcome> {\n const unknown = unknownArguments(args, ['paths', 'brief', 'base']);\n if (unknown) return unknown;\n const given = pathsOf(args);\n if ('text' in given) return given;\n const base = baseOf(args);\n if ('text' in base) return base;\n const found = await round(workspace, env, args['brief']);\n if ('text' in found) return found;\n const decisions = await checkPaths(workspace, found.brief, undefined, given.paths, workspace.root, reader, base.base);\n const text = decisions.map((d) => `${d.verdict}: ${d.message}${d.verdict === 'allow' ? '' : `. Next: ${d.hint}`}`).join('\\n');\n return { text, structured: { decisions: decisions.map((d) => ({ ...d })) } };\n },\n },\n {\n descriptor: {\n name: 'request_escalation',\n title: 'Ask a person to rule',\n description:\n 'When the round cannot be finished without changing something the brief protects, record the request and stop. A person reads the memo and rules; only a ruling they sign lets the change through.',\n inputSchema: {\n type: 'object',\n properties: {\n paths: { type: 'array', items: { type: 'string' }, description: 'The protected files the round needs to change. An empty one is refused.' },\n reason: { type: 'string', description: 'Why the round cannot be done without them. It is required, and may not be empty.' },\n options: {\n type: 'array',\n items: { type: 'object', properties: { label: { type: 'string' }, consequence: { type: 'string' } }, required: ['label', 'consequence'] },\n description: 'The choices the person has, each with what it costs. A choice whose label is empty is refused.',\n },\n recommendation: { type: 'string', description: 'Which option you recommend, and why. Omit it when there is none: an empty one is refused.' },\n brief: briefProperty,\n },\n required: ['paths', 'reason'],\n additionalProperties: false,\n },\n annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: false },\n },\n async call(args: JsonObject): Promise<ToolOutcome> {\n const unknown = unknownArguments(args, ['paths', 'reason', 'options', 'recommendation', 'brief']);\n if (unknown) return unknown;\n // Every part of the memo before anything is written: a person rules\n // on what it says, and cannot rule on a part that says nothing.\n const given = pathsOf(args);\n if ('text' in given) return given;\n const reason = args['reason'];\n if (typeof reason !== 'string' || isBlank(reason)) return toolError('\"reason\" is required.');\n const choices = optionsOf(args);\n if ('text' in choices) return choices;\n const recommendation = args['recommendation'];\n if (recommendation !== undefined && typeof recommendation !== 'string') return toolError('\"recommendation\" must be a string.');\n if (recommendation !== undefined && isBlank(recommendation)) return namesNothing('recommendation', 'recommend', recommendation);\n const found = await round(workspace, env, args['brief']);\n if ('text' in found) return found;\n const { request, memo } = await raiseEscalation(workspace, found.brief, {\n paths: given.paths,\n reason,\n options: choices.options,\n recommendation: recommendation ?? null,\n });\n return { text: `${memo}\\nStop here until a person rules on ${request.id}.`, structured: { id: request.id } };\n },\n },\n {\n descriptor: {\n name: 'audit_round',\n title: 'Audit the round',\n description:\n 'Did the round stay inside the lines: what the archive would refuse (open boxes, protected files, files outside the scope), the brief\\'s own assertions, unverified rulings, every dependency added and every package allowed to run install scripts.',\n inputSchema: { type: 'object', properties: { brief: briefProperty, base: baseProperty }, additionalProperties: false },\n annotations: readOnly,\n },\n async call(args: JsonObject): Promise<ToolOutcome> {\n const unknown = unknownArguments(args, ['brief', 'base']);\n if (unknown) return unknown;\n const base = baseOf(args);\n if ('text' in base) return base;\n const found = await round(workspace, env, args['brief']);\n if ('text' in found) return found;\n const result = await runAudit(workspace, found.brief, reader, base.base);\n const { counts, findings, measured } = result.report;\n // What was measured beside what was found: \"nothing found\" from an\n // audit that ran no goal is not a round that is done.\n const text =\n findings.length === 0\n ? 'The audit found nothing in what it measured.'\n : findings.map((f) => `${f.severity} ${f.rule}: ${f.message}. Next: ${f.hint}`).join('\\n');\n return {\n text: `${text}\\n\\n${describeMeasured(measured)}\\n\\n${counts.error} error(s), ${counts.warning} warning(s), ${counts.note} note(s)`,\n structured: { counts, measured: { ...measured }, findings: findings.map((f) => ({ ...f })) },\n };\n },\n },\n {\n descriptor: {\n name: 'list_rounds',\n title: 'List the rounds',\n description: 'The live briefs: status, wave, what each waits on, and which are ready to start.',\n inputSchema: { type: 'object', properties: {}, additionalProperties: false },\n annotations: readOnly,\n },\n async call(args: JsonObject): Promise<ToolOutcome> {\n const unknown = unknownArguments(args, []);\n if (unknown) return unknown;\n const live = (await workspace.siblings.briefs()).filter((brief) => brief.phase === 'live');\n const text = live\n .map((b) => `${[b.id, titleOf(b)].filter((part) => part !== null).join(' ')} - ${b.status ?? 'unknown'}, wave ${b.wave ?? '-'}, ${b.ready ? 'ready' : `waits on ${b.waitingOn.join(', ')}`}`)\n .join('\\n');\n return { text: text === '' ? 'No live brief.' : text, structured: { briefs: live.map((b) => ({ ...b, title: titleOf(b) })) } };\n },\n },\n ];\n}\n\nconst SKILLS: readonly { name: string; title: string; argument: string; description: string }[] = [\n { name: 'draft-brief', title: 'Draft a brief', argument: 'request', description: 'What the round should achieve, in the person\\'s words.' },\n { name: 'split-goal', title: 'Split a goal into rounds', argument: 'goal', description: 'The goal to split.' },\n { name: 'run-round', title: 'Run a round', argument: 'brief', description: 'The brief id.' },\n { name: 'close-round', title: 'Close a round', argument: 'brief', description: 'The brief id.' },\n];\n\nfunction skillText(name: string): string {\n // The package ships the skills beside dist/ (package.json's files), so one\n // that cannot be read is a broken install, and the request fails saying so\n // rather than serving an empty prompt.\n const text = readFileSync(fileURLToPath(new URL(`../skills/${name}/SKILL.md`, import.meta.url)), 'utf8');\n // Every skill opens with its front matter (tests/source.test.ts), so the\n // anchor is equivalent to its mutant here.\n return text.replace(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n/, '').trim();\n}\n\nexport function prompts(): PromptDefinition[] {\n return SKILLS.map((skill) => ({\n descriptor: {\n name: skill.name,\n title: skill.title,\n arguments: [{ name: skill.argument, description: skill.description, required: false }],\n },\n async get(args: Readonly<Record<string, string>>): Promise<JsonObject> {\n const given = args[skill.argument];\n const text = `${skillText(skill.name)}${given === undefined || given === '' ? '' : `\\n\\n${skill.argument}: ${given}`}`;\n return { description: skill.title, messages: [{ role: 'user', content: { type: 'text', text } }] };\n },\n }));\n}\n\nexport async function mcpCommand(options: Options, io: CliIO): Promise<number> {\n // Claude Code starts a plugin's server in the plugin's directory, and names\n // the project in CLAUDE_PROJECT_DIR; the server answers for the project.\n const workspace = await openWorkspace({ ...options, root: options.root ?? (io.env['CLAUDE_PROJECT_DIR'] || undefined) }, io);\n const handle = createMcpServer({ name: 'spec-harness', version: version(), instructions: INSTRUCTIONS, tools: tools(workspace, io.env), prompts: prompts() });\n // A session handed over whole, as a test hands it, is served as a client\n // would stream it on stdin. Only the built command line serves\n // process.stdin, and the suite spawns it from dist/, outside the sweep\n // (tests/integration/mcp.test.ts), so a mutant that ignores it survives.\n const input = io.stdin === undefined ? process.stdin : Readable.from([Buffer.from(await io.stdin())]);\n await serveLines(input, (line) => io.stdout.write(`${line}\\n`), handle);\n return 0;\n}\n"]}
|