@alterset/alterspec-client 0.31.0 → 0.32.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/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/config.ts","../../src/schemas/work.ts","../src/role.ts","../src/ssh.ts","../src/auth.ts","../src/bugs.ts","../../src/schemas/delta.ts","../../src/schemas/change.ts","../../src/schemas/common.ts","../../src/schemas/ids.ts","../../src/changes/delta-record.ts","../../src/changes/compatibility.ts","../../src/changes/data-change.ts","../../src/export/paths.ts","../../src/lib/frontmatter-split.ts","../../src/changes/parts.ts","../../src/export/read.ts","../../src/spec/layout.ts","../../src/lib/diff.ts","../../src/lib/comments.ts","../../src/spec/criteria.ts","../../src/lib/sections-split.ts","../../src/export/cut.ts","../src/pin.ts","../src/questions.ts","../src/mcp.ts","../src/context.ts","../src/pinstore.ts","../src/task.ts","../src/git.ts","../src/install.ts","../../src/install/installer.ts","../../src/install/hash.ts","../../src/lib/names.ts","../src/lookup.ts","../src/open.ts","../src/progress.ts","../src/version.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { join } from 'node:path';\nimport { KeyRefused, keyOf, sessionOf } from './auth.js';\nimport { bugContext, bugTaskState, bugsText, listBugs, renderBugContext } from './bugs.js';\nimport { readExport } from '../../src/export/read.js';\nimport { CONFIG_FILE, type LoadedConfig, exportDir, loadConfig, readConfigAt } from './config.js';\nimport {\n type CoveredState,\n contextStats,\n parseChangedSince,\n parseQuestionsFull,\n parseSiblings,\n pinFiles,\n renderChecklist,\n renderContext,\n shownOf,\n startFrom,\n taskContext,\n} from './context.js';\nimport { pinsDir, readShown, writePins, writeShown } from './pinstore.js';\nimport { exportHead, mainBranch, mergedCommit } from './git.js';\nimport {\n CLAUDE_LOCAL_SETTINGS,\n CLAUDE_SETTINGS,\n approveHere,\n type IgnoreOutcome,\n MCP_JSON,\n PROMPTS_DIR,\n initClient,\n} from './install.js';\nimport { lookup, renderLookup, unread } from './lookup.js';\nimport { callTool, runProxy } from './mcp.js';\nimport { OPENABLE, openDispatcher } from './open.js';\nimport {\n coveredItems,\n currentTask,\n hookCwd,\n progressHook,\n progressText,\n reportProgress,\n} from './progress.js';\nimport { changeQuestions, listQuestions, missingCites, parseAnswers, questionsText } from './questions.js';\nimport { roleOf } from './role.js';\nimport { type TaskRef, branchOf, parseTask } from './task.js';\nimport { packageVersion } from './version.js';\n\n/** `whoami` as a person reads it: who, which role, what the dispatcher has of the export. */\nexport function whoamiText(me: Record<string, unknown>): string {\n const role = roleOf(me);\n const latest = me.latest_export as { commit?: string; ordinal?: number } | undefined;\n const lines = [\n `${String(me.email ?? '?')}${me.name ? ` (${String(me.name)})` : ''}: ${role === 'product' ? 'a product person (answers questions, sees no task)' : 'a developer'}`,\n ];\n if (role === 'developer') {\n const tracks = Array.isArray(me.tracks) ? (me.tracks as string[]) : [];\n if (tracks.length) lines.push(`Tracks: ${tracks.join(', ')}`);\n }\n if (latest?.commit)\n lines.push(`Latest ingested export: ${latest.commit}${latest.ordinal ? ` (#${latest.ordinal})` : ''}`);\n const ingested = Array.isArray(me.ingested) ? (me.ingested as { commit?: string; at?: string }[]) : [];\n if (ingested.length)\n lines.push(\n 'Ingested exports, newest first:',\n ...ingested.map((i) => ` ${String(i.commit ?? '?').slice(0, 12)} ${String(i.at ?? '')}`),\n );\n return lines.join('\\n') + '\\n';\n}\n\nconst tryConfig = (): LoadedConfig | undefined => {\n try {\n return loadConfig();\n } catch {\n return undefined;\n }\n};\n\n/**\n * Which of the task's items the dispatcher holds covered and which of its change's answers the track built already,\n * or why it couldn't be asked (the brief goes on).\n */\nasync function coveredState(loaded: LoadedConfig, task: TaskRef): Promise<CoveredState> {\n try {\n const answer = await callTool(sessionOf(loaded), 'task', { id: task.id });\n const items = (answer.items ?? []) as {\n item: string;\n covered_commit: string | null;\n weight?: number | null;\n label?: string | null;\n }[];\n const answers = parseAnswers(answer.answers);\n const from = startFrom(task.track, answer.after);\n const siblings = parseSiblings(answer.siblings);\n const questionsFull = parseQuestionsFull(answer.questions_full);\n const changedSince = parseChangedSince(answer.changed_since);\n return {\n covered: new Map(items.flatMap((i) => (i.covered_commit ? [[i.item, i.covered_commit] as const] : []))),\n // The dispatcher's list is the checklist: its first item list stands (its spec, section 9), so the brief and\n // the `Alterspec-Covers` it accepts name the same items.\n ...(items.length\n ? {\n items: items.map((i) => ({\n item: i.item,\n ...(typeof i.weight === 'number' ? { weight: i.weight } : {}),\n ...(typeof i.label === 'string' && i.label ? { label: i.label } : {}),\n })),\n }\n : {}),\n ...(answers ? { answers } : {}),\n ...(from.length ? { startFrom: from } : {}),\n ...(siblings?.length ? { siblings } : {}),\n ...(questionsFull ? { questionsFull } : {}),\n ...(changedSince ? { changedSince } : {}),\n };\n } catch (e) {\n return { unknown: (e as Error).message.split('\\n')[0]! };\n }\n}\n\n/** Run a command, printing its error as one line and exiting 1. */\nconst run =\n <A extends unknown[]>(fn: (...args: A) => unknown) =>\n async (...args: A) => {\n try {\n await fn(...args);\n } catch (e) {\n process.stderr.write(`${e instanceof KeyRefused ? e.advice : (e as Error).message}\\n`);\n process.exit(1);\n }\n };\n\n/** What `init` says about keeping the approval out of git: Claude Code ignores it in a tracked file. */\nconst ignoreLines = (o: IgnoreOutcome): string[] =>\n o === 'added'\n ? [`Added ${CLAUDE_LOCAL_SETTINGS} to .gitignore; commit that too.`]\n : o === 'tracked'\n ? [\n `${CLAUDE_LOCAL_SETTINGS} is committed, so Claude Code ignores its approval: \\`git rm --cached\\` it and ignore it.`,\n ]\n : o === 'unknown'\n ? [\n `Make sure git ignores ${CLAUDE_LOCAL_SETTINGS} (where .claude is a symlink, in the repository it points to).`,\n ]\n : [];\n\n/**\n * In a checkout other than the configuration's (a task worktree the developer made), approve the dispatcher server\n * there once, and say so: a worktree has what git tracks, not the git-ignored approval.\n */\nfunction approveWorktree(loaded: { root: string }): void {\n const { root, outcome } = approveHere(loaded.root);\n if (outcome === 'unchanged') return;\n process.stderr.write(\n `Approved the \"dispatcher\" server for you in ${join(root, CLAUDE_LOCAL_SETTINGS)} (this checkout had no approval of its own); its tools appear in the next Claude Code session here.\\n`,\n );\n}\n\nconst program = new Command();\n\nprogram\n .name('alterspec-client')\n .description('alterspec client — takes tasks of an alterspec export from the dispatcher.')\n .version(packageVersion());\n\nprogram\n .command('init')\n .description(\n 'set the client up in this repository: configuration, the dispatcher in .mcp.json, the progress hook, the skills; with --product (in a spec project) only the configuration and the dispatcher',\n )\n .option('--dispatcher <url>', 'the dispatcher’s URL')\n .option('--export <path>', 'your clone of the export repository')\n .option('--track <code...>', 'the tracks this repository builds (BE, WEB, …)')\n .option('--key <key>', 'the public key to sign with: a .pub path or the key line')\n .option('--branch <name>', 'the track’s main branch (default the remote’s HEAD)')\n .option(\n '--npx <flags>',\n 'flags this project runs npx with, comma-separated (--npx=--min-release-age=0); --npx= removes them',\n )\n .option(\n '--product',\n 'the product side’s set-up, in the spec project: a dispatcher and a key, no export, no track, no developer skill or hook',\n )\n .option('--force', 'replace skills you modified')\n .action(\n run(\n (opts: {\n npx?: string;\n dispatcher?: string;\n export?: string;\n track?: string[];\n key?: string;\n branch?: string;\n product?: boolean;\n force?: boolean;\n }) => {\n const root = process.cwd();\n const { track, npx, ...rest } = opts;\n const npxArgs = npx\n ?.split(',')\n .map((a) => a.trim())\n .filter(Boolean);\n const tracks = track\n ?.flatMap((t) => t.split(','))\n .map((t) => t.trim().toUpperCase())\n .filter(Boolean);\n const r = initClient(\n root,\n { ...rest, ...(tracks ? { tracks } : {}), ...(npxArgs ? { npx: { args: npxArgs } } : {}) },\n packageVersion(),\n );\n const f = r.files;\n const lines =\n r.role === 'product'\n ? [\n `${CONFIG_FILE} (the product side: dispatcher and key, no export, no tracks): ${r.config}`,\n `${MCP_JSON} (server \"dispatcher\"): ${r.mcp}`,\n `${CLAUDE_LOCAL_SETTINGS} (the \"dispatcher\" server approved for you): ${r.approval}`,\n 'Nothing of the developer’s was installed: no hook, no skill, no prompt.',\n '',\n `Commit ${CONFIG_FILE} and ${MCP_JSON}.`,\n ...ignoreLines(r.ignore),\n 'The dispatcher’s product tools (whoami, questions, answer, reconcile, feedback, bug_reports) appear in the next Claude Code session; /alterspec-answer post and /alterspec-reconcile use them.',\n ]\n : [\n `${CONFIG_FILE}: ${r.config}`,\n `${MCP_JSON} (server \"dispatcher\"): ${r.mcp}`,\n `${CLAUDE_SETTINGS} (progress hook after git commit): ${r.hook}`,\n `${CLAUDE_LOCAL_SETTINGS} (the \"dispatcher\" server approved for you): ${r.approval}`,\n `Skills, the answerer agent and ${PROMPTS_DIR}/: ${f.created.length} created, ${f.updated.length} updated, ${f.unchanged.length} unchanged${f.removed.length ? `, ${f.removed.length} removed` : ''}.`,\n ...f.conflicts.map((p) => `Kept your modified ${p}; --force replaces it.`),\n '',\n 'Commit .mcp.json, .claude/settings.json, .claude/skills/alterspec-*, .claude/agents/alterspec-* and .alterspec-client/, so task worktrees have them too.',\n ...ignoreLines(r.ignore),\n \"The dispatcher's tools appear in the next Claude Code session.\",\n ];\n try {\n const key = keyOf({ root, config: readConfigAt(root)! });\n lines.push(\n '',\n r.role === 'product'\n ? 'Send this public key to the dispatcher’s admin, to register as a product person:'\n : 'Send this public key to the dispatcher’s admin:',\n key.line,\n key.fingerprint,\n );\n } catch (e) {\n lines.push('', (e as Error).message);\n }\n process.stdout.write(lines.join('\\n') + '\\n');\n },\n ),\n );\n\nprogram\n .command('whoami')\n .description('sign in and print who this key is to the dispatcher: email, role, the latest ingested export')\n .option('--json', 'print the dispatcher’s answer as JSON')\n .action(\n run(async (opts: { json?: boolean }) => {\n const me = await callTool(sessionOf(loadConfig()), 'whoami');\n if (opts.json) return void process.stdout.write(JSON.stringify(me, null, 2) + '\\n');\n process.stdout.write(whoamiText(me));\n }),\n );\n\nprogram\n .command('key')\n .description('print the public key and fingerprint the client signs with, to send to the admin')\n .action(\n run(() => {\n const key = keyOf(tryConfig());\n process.stdout.write(`${key.line}\\n${key.fingerprint}\\n`);\n }),\n );\n\nprogram\n .command('open')\n .description('sign in and open the dispatcher’s pages in the browser (a one-time link)')\n .argument('<what>', `what to open: ${OPENABLE.join(', ')}`)\n .action(\n run(async (what: string) => {\n if (!(OPENABLE as readonly string[]).includes(what))\n throw new Error(`Nothing to open called \"${what}\": ${OPENABLE.join(', ')}.`);\n const loaded = loadConfig();\n const url = await openDispatcher(sessionOf(loaded));\n process.stdout.write(\n `Opened ${new URL(url).origin} in the browser (the link works once, for a minute).\\n`,\n );\n }),\n );\n\nprogram\n .command('mcp')\n .description(\n 'the local MCP server Claude Code starts over stdio (from .mcp.json); forwards to the dispatcher',\n )\n .action(\n run(async () => {\n const loaded = loadConfig();\n const session = sessionOf(loaded);\n await runProxy({ session, input: process.stdin, output: process.stdout, version: packageVersion() });\n }),\n );\n\nprogram\n .command('export-head')\n .description('pull the export clone and print its HEAD and the commit to send the dispatcher (JSON)')\n .option('--latest <sha>', 'the dispatcher’s latest_export')\n .action(\n run((opts: { latest?: string }) => {\n const loaded = loadConfig();\n approveWorktree(loaded);\n const head = exportHead(exportDir(loaded), opts.latest);\n process.stdout.write(JSON.stringify(head, null, 2) + '\\n');\n }),\n );\n\nprogram\n .command('context')\n .description('print a task’s brief, assembled from the export')\n .argument('<task>', 'the task, e.g. CHG-012/BE or BUG-3/BE')\n .option('--json', 'print it as JSON')\n .option('--stats', 'print its size by section instead')\n .option(\n '--checklist',\n 'print only the task’s questions and checklist, for re-reading during the work (a bug’s brief whole)',\n )\n .action(\n run(async (id: string, opts: { json?: boolean; stats?: boolean; checklist?: boolean }) => {\n const loaded = loadConfig();\n approveWorktree(loaded);\n const dir = exportDir(loaded);\n const x = readExport(dir);\n const task = parseTask(id);\n if (task.kind === 'bug') {\n // A bug task's brief: the bug from the dispatcher (work.json never names one), the cites as its checklist.\n const session = sessionOf(loaded);\n const ctx = bugContext(\n x,\n task,\n dir,\n await bugTaskState(session, task),\n await changeQuestions(session, [task.id]),\n );\n process.stdout.write(\n opts.stats\n ? contextStats(renderBugContext(ctx))\n : opts.json\n ? JSON.stringify(ctx, null, 2) + '\\n'\n : renderBugContext(ctx),\n );\n return;\n }\n // The change's tasks, this one first: another track's assumptions and answers bear on this one.\n const tasks = [\n task.id,\n ...(x.work.changes.find((c) => c.id === task.change)?.tasks ?? [])\n .map((t) => `${task.change}/${t.track}`)\n .filter((t) => t !== task.id),\n ];\n const pins = pinsDir(loaded.root, task);\n const ctx = taskContext(\n x,\n task,\n dir,\n await coveredState(loaded, task),\n await changeQuestions(sessionOf(loaded), tasks),\n { pins, shown: readShown(process.cwd(), task) },\n );\n // The objects later changes touched, as this task's change saw them, where the brief's paths point.\n // The checklist alone shows no \"Changed since\", so it marks nothing as shown and writes no pin.\n if (!opts.stats && !opts.checklist) {\n writePins(pins, pinFiles(x, ctx));\n writeShown(process.cwd(), task, shownOf(ctx));\n }\n process.stdout.write(\n opts.stats\n ? contextStats(renderContext(ctx))\n : opts.json\n ? JSON.stringify(ctx, null, 2) + '\\n'\n : opts.checklist\n ? renderChecklist(ctx)\n : renderContext(ctx),\n );\n }),\n );\n\nprogram\n .command('progress')\n .description('report the items the task’s commits cover to the dispatcher')\n .argument(\n '[task]',\n 'the task, e.g. CHG-012/BE; default the one of the branch task/<chg>-<track> or of the last commit’s trailer',\n )\n .option('--hook', 'as the Claude Code hook after a commit: silent, throttled, never failing')\n .option('--json', 'print the dispatcher’s answer as JSON')\n .action(async (id: string | undefined, opts: { hook?: boolean; json?: boolean }) => {\n if (opts.hook) {\n // Whatever happens, the hook ends quietly and in time: it must never fail or hold up the agent's turn.\n setTimeout(() => process.exit(0), 30_000).unref();\n const repo = (await hookCwd(process.stdin)) ?? process.cwd();\n await progressHook({\n repo,\n session: () => sessionOf(loadConfig(repo)),\n say: (text) => process.stdout.write(text),\n });\n process.exit(0);\n }\n await run(async () => {\n const repo = process.cwd();\n const task = id ? parseTask(id) : currentTask(repo);\n if (!task)\n throw new Error(\n 'Neither the branch (task/<chg>-<track>) nor the last commit’s Alterspec-Task trailer names a task: name it, e.g. `progress CHG-012/BE`.',\n );\n const report = await reportProgress(sessionOf(loadConfig()), task, coveredItems(repo, task));\n process.stdout.write(opts.json ? JSON.stringify(report, null, 2) + '\\n' : progressText(report));\n })();\n });\n\nprogram\n .command('lookup')\n .description(\n 'where in the export a question is answered: what to read first, and what before calling it silent',\n )\n .argument('[ref...]', 'IDs and terms the question is about')\n .option('--question <text>', 'the question, in full')\n .option('--task <task>', 'the task it came up in, e.g. CHG-012/BE')\n .option('--item <item>', 'the checklist item it concerns')\n .option('--unread <path...>', 'the paths that were opened: print what must still be, and exit 1 when any')\n .option('--json', 'print it as JSON')\n .action(\n run(\n (\n refs: string[],\n opts: { question?: string; task?: string; item?: string; unread?: string[]; json?: boolean },\n ) => {\n const x = readExport(exportDir(loadConfig()));\n const found = lookup(x, {\n refs,\n ...(opts.question ? { question: opts.question } : {}),\n ...(opts.task ? { task: parseTask(opts.task) } : {}),\n ...(opts.item ? { item: opts.item } : {}),\n });\n if (opts.unread) {\n const left = unread(x, found, opts.unread);\n if (left.length)\n throw new Error(\n `Not opened yet:\\n${left.map((c) => `- ${c.path} (${c.why})`).join('\\n')}\\nThe export isn’t silent until these are read.`,\n );\n process.stdout.write('Everything that had to be opened was.\\n');\n } else process.stdout.write(opts.json ? JSON.stringify(found, null, 2) + '\\n' : renderLookup(found));\n },\n ),\n );\n\nprogram\n .command('cites')\n .description('check that every reference is an ID or a path the export holds')\n .argument('<ref...>', 'IDs (RULE-PRC-001, CAP-PRC-001-AC-02) and export paths')\n .action(\n run((refs: string[]) => {\n const missing = missingCites(readExport(exportDir(loadConfig())), refs);\n if (missing.length)\n throw new Error(\n `Not in the export: ${missing.join(', ')}. An answer that cites them is not from the spec.`,\n );\n process.stdout.write(`All ${refs.length} in the export.\\n`);\n }),\n );\n\nprogram\n .command('questions')\n .description(\n 'print the questions the dispatcher keeps: some by number, a task’s, or without either your own',\n )\n .argument('[ref...]', 'a task, e.g. CHG-012/BE, or questions by number, e.g. Q-12 Q-14')\n .option('--open', 'only the ones still open')\n .option('--about <id...>', 'everyone’s questions that name these IDs')\n .option('--json', 'print them as JSON')\n .action(\n run(async (refs: string[], opts: { open?: boolean; about?: string[]; json?: boolean }) => {\n const ids = refs.filter((r) => /^Q-\\d+$/i.test(r)).map((r) => r.toUpperCase());\n const rest = refs.filter((r) => !/^Q-\\d+$/i.test(r));\n if (rest.length > 1 || (rest.length && ids.length))\n throw new Error('Name one task, or questions by number (Q-<n>), not both.');\n const id = rest[0];\n const questions = await listQuestions(sessionOf(loadConfig()), {\n ...(ids.length ? { ids } : {}),\n ...(id ? { task: parseTask(id).id } : {}),\n ...(opts.about ? { about: opts.about } : {}),\n ...(opts.open ? { open: true } : {}),\n });\n process.stdout.write(opts.json ? JSON.stringify(questions, null, 2) + '\\n' : questionsText(questions));\n }),\n );\n\nprogram\n .command('bugs')\n .description('print the bugs the dispatcher keeps: the ones naming some IDs, or without --about your own')\n .option('--about <id...>', 'everyone’s bugs whose cites, title or description name these IDs')\n .option('--status <status>', 'only the open, done or dismissed ones')\n .option('--track <code>', 'only those with a task on this track')\n .option('--json', 'print them as JSON')\n .action(\n run(async (opts: { about?: string[]; status?: string; track?: string; json?: boolean }) => {\n if (opts.status && !['open', 'done', 'dismissed'].includes(opts.status))\n throw new Error(`--status takes open, done or dismissed, not \"${opts.status}\".`);\n const bugs = await listBugs(sessionOf(loadConfig()), {\n ...(opts.about ? { about: opts.about } : {}),\n ...(opts.status ? { status: opts.status as 'open' | 'done' | 'dismissed' } : {}),\n ...(opts.track ? { track: opts.track.toUpperCase() } : {}),\n });\n process.stdout.write(opts.json ? JSON.stringify(bugs, null, 2) + '\\n' : bugsText(bugs));\n }),\n );\n\nprogram\n .command('merged')\n .description(\n 'print the commit and branch to report done with: the pushed task branch’s head, or the commit on origin/<main> that brought the task in',\n )\n .argument('<task>', 'the task, e.g. CHG-012/BE')\n .option('--json', 'print { commit, branch } as JSON')\n .action(\n run((id: string, opts: { json?: boolean }) => {\n const loaded = loadConfig();\n const main = mainBranch(process.cwd(), loaded.config.branch);\n const task = parseTask(id);\n const found = mergedCommit(process.cwd(), task, main);\n if (!found)\n throw new Error(\n `${task.id} is not pushed yet: push its branch ${branchOf(task)} (or merge it into ${main} with the trailer \"Alterspec-Task: ${task.id}\" on a commit), then run this again.`,\n );\n process.stdout.write(\n opts.json\n ? JSON.stringify(found) + '\\n'\n : found.branch\n ? `${found.commit} on ${found.branch} (pushed, not in ${main} yet)\\n`\n : `${found.commit} on ${main} (merged)\\n`,\n );\n }),\n );\n\nawait program.parseAsync();\n","import { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { basename, dirname, isAbsolute, join, resolve } from 'node:path';\nimport { z } from 'zod';\nimport { TrackCode } from '../../src/schemas/work.js';\n\n/** The client's configuration in an implementation repository (spec 12.1), written by `init`. */\nexport const CONFIG_FILE = '.alterspec-client.json';\n\n/**\n * A flag for npx itself (`--min-release-age=0`). The configuration is committed and these end up in a shell command\n * Claude Code runs after every commit, so nothing but a flag and its value passes: no space, quote or `;`.\n */\nexport const NpxArg = z\n .string()\n .regex(/^--?[A-Za-z0-9][A-Za-z0-9=._:/-]*$/, 'must be one npx flag, like --min-release-age=0');\n\nexport const ClientConfigSchema = z\n .object({\n /** The dispatcher's URL. */\n dispatcher: z.url(),\n /**\n * The developer's clone of the export repository, relative to this file's folder or absolute. Absent in the\n * product side's configuration (`init --product`, spec 8.6): the spec project reads its own spec, never an export.\n */\n export: z.string().min(1).optional(),\n /** The tracks this repository builds: the default of `next_task`. A product configuration has none. */\n tracks: z.array(TrackCode).default([]),\n /** Unused since 0.14.0 (the client makes no worktree); accepted so a configuration written before stays valid. */\n worktrees: z.string().min(1).optional(),\n /** The public key to sign with: a `.pub` path or the key line; default ssh-agent, then `~/.ssh/id_ed25519.pub`. */\n key: z.string().min(1).optional(),\n /** The track's main branch; default the remote's `HEAD`, else `main`. */\n branch: z.string().min(1).optional(),\n /**\n * How this project runs the client: flags put before the package name wherever `init` writes the invocation\n * (`.mcp.json`, the progress hook, the skills and the prompts). The registry is the project's `.npmrc`'s.\n */\n npx: z\n .object({ args: z.array(NpxArg).default([]) })\n .strict()\n .optional(),\n })\n .strict();\nexport type ClientConfig = z.infer<typeof ClientConfigSchema>;\n\n/** The product side's configuration (spec 8.6, 12.4): a dispatcher and a key, no export and no tracks. */\nexport const isProduct = (config: ClientConfig): boolean => config.export === undefined;\n\nexport class ConfigError extends Error {}\n\nexport interface LoadedConfig {\n /** The folder holding the configuration: relative paths in it are relative to this folder. */\n root: string;\n config: ClientConfig;\n}\n\nconst git = (cwd: string, ...args: string[]) => {\n try {\n return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();\n } catch {\n return undefined;\n }\n};\n\n/**\n * The folders a configuration is looked for in: the checkout's top level, then the main checkout's when this is a\n * task worktree (where an uncommitted configuration isn't), then the folder itself.\n */\nfunction candidates(cwd: string): string[] {\n const top = git(cwd, 'rev-parse', '--show-toplevel');\n const common = git(cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir');\n const main = common && basename(common) === '.git' ? dirname(common) : undefined;\n return [...new Set([top, main, resolve(cwd)].filter((d): d is string => !!d))];\n}\n\nexport function readConfigAt(root: string): ClientConfig | undefined {\n const path = join(root, CONFIG_FILE);\n if (!existsSync(path)) return undefined;\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(path, 'utf8'));\n } catch {\n throw new ConfigError(`${path} is not valid JSON.`);\n }\n const parsed = ClientConfigSchema.safeParse(raw);\n if (!parsed.success)\n throw new ConfigError(\n `${path} is not valid: ${parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'} ${i.message}`).join('; ')}.`,\n );\n return parsed.data;\n}\n\nexport function loadConfig(cwd = process.cwd()): LoadedConfig {\n for (const root of candidates(cwd)) {\n const config = readConfigAt(root);\n if (config) return { root, config };\n }\n throw new ConfigError(\n `No ${CONFIG_FILE} here: run \\`npx @alterset/alterspec-client init --dispatcher <url> --export <path>\\` first (in a spec project, \\`init --product --dispatcher <url>\\`).`,\n );\n}\n\n/** A path of the configuration as an absolute path: `~` is the home folder, relative is to the config's folder. */\nexport function configPath(root: string, path: string): string {\n if (path === '~' || path.startsWith('~/')) return join(homedir(), path.slice(1));\n return isAbsolute(path) ? path : resolve(root, path);\n}\n\n/** The export clone's folder; a product configuration has none, and the developer commands stop here. */\nexport function exportDir({ root, config }: LoadedConfig): string {\n if (config.export === undefined)\n throw new ConfigError(\n `${join(root, CONFIG_FILE)} is a product configuration (no export): it answers the build's questions and takes no task. The developer commands need a repository set up with \\`init --dispatcher <url> --export <path>\\`.`,\n );\n return configPath(root, config.export);\n}\n\nexport function writeConfig(root: string, config: ClientConfig): void {\n writeFileSync(join(root, CONFIG_FILE), JSON.stringify(config, null, 2) + '\\n');\n}\n","import { z } from 'zod';\n\n/**\n * `work.json` in an export: the work every signed-off change implies, for an application that hands it to developers\n * (the alterspec dispatcher). The one definition of the format. It imports nothing but zod, so the alterspec client\n * can carry it as it is. Format 8 (alterspec 0.43.0) names each change's optional `initiative` and carries the\n * `initiatives` they name (the envelope around a group of changes: why they exist; no status). Format 7 (alterspec 0.42.0) gives each task its own optional `weight` and drops the\n * change's. Format 6 (alterspec 0.41.0) weighs each item per track and allows 0 (nothing to build\n * on that track). Format 5 (alterspec 0.38.0) adds the words a person reads: each task's optional `title`,\n * `summary` and `labels`, and the objects' `names`. Format 4 (alterspec 0.34.0) adds each change's optional `weight`; format 3 (0.33.0) adds each task's optional `weights`; format 2 (0.24.0) added\n * each task's `items`; format 1 is the same without them. A reader of every format takes `AnyWorkSchema`.\n */\n\n/** `BE` (the backend, API channels included) or the code of a channel with an experience of its own. */\nexport const TrackCode = z.string().regex(/^[A-Z]{2,5}$/, { message: 'must be BE or a channel code' });\nexport type TrackCode = z.infer<typeof TrackCode>;\n\n/**\n * A weight from 1 to 100: the size of a task (format 7; of a whole change in formats 4 to 6), and (to format 5) of a\n * task item, reasoned at sign-off\n * against alterspec's rubric (a typical acceptance criterion is about 10), never an estimate of anyone's code.\n */\nexport const WorkWeight = z.number().int().min(1).max(100);\nexport type WorkWeight = z.infer<typeof WorkWeight>;\n\n/**\n * The weight of a task item on one track, 0–100 (format 6): how much of the behaviour the item specifies that\n * track builds. 0: the track has nothing to build for it (a behaviour only another channel shows, a mockup file);\n * the item stays on the checklist to be read.\n */\nexport const ItemWeight = z.number().int().min(0).max(100);\nexport type ItemWeight = z.infer<typeof ItemWeight>;\n\n/** The longest title, summary and label (characters). */\nexport const WORD_CAPS = { title: 100, summary: 400, label: 100, name: 100 } as const;\n\n/** A word a person reads: plain text of one line, trimmed, never empty, at most `max` characters. */\nconst words = (max: number) =>\n z\n .string()\n .max(max, { message: `at most ${max} characters` })\n .regex(/^\\S(?:[^\\n\\r]*\\S)?$/, { message: 'one line of text, without spaces around it' });\n\n/** What a track builds in a change, for a list (format 5). */\nexport const WorkTitle = words(WORD_CAPS.title);\n/** The same in two or three plain sentences. */\nexport const WorkSummary = words(WORD_CAPS.summary);\n/** What one checklist item is, apart from its siblings. */\nexport const WorkLabel = words(WORD_CAPS.label);\n/** An object's own title in the spec. */\nexport const WorkName = words(WORD_CAPS.name);\n\nconst ChangeRef = z.string().regex(/^CHG-\\d{3,}$/);\n/** An initiative's ID (alterspec's `INITIATIVE_ID`, written here again: this file imports nothing but zod). */\nconst InitiativeRef = z.string().regex(/^INI-[A-Z0-9]+(?:-[A-Z0-9]+)*$/);\nconst Day = z.iso.date();\n\nexport const WorkTrackSchema = z\n .object({\n code: TrackCode,\n kind: z.enum(['backend', 'ui']),\n /** The channel codes the track builds: the API channels for `BE`, the channels sharing the experience for a UI track. */\n channels: z.array(z.string()),\n })\n .strict();\nexport type WorkTrack = z.infer<typeof WorkTrackSchema>;\n\nexport const WorkTaskSchema = z\n .object({\n track: TrackCode,\n /** The keys of the objects in the change's delta that put it on the track. */\n objects: z.array(z.string()),\n /**\n * The task's checklist, derived from the delta: the acceptance criteria (`<CAP>-AC-NN`), screen actions\n * (`<SCR>.Ann`) and contract states (`<UX-SCR>#<state>`) the change adds or changes, and every other object as\n * its key; on `BE`, `<CHG>#data-change` when the proposal declares a one-time data change (alterspec 0.27.0).\n * Sorted, never empty.\n */\n items: z.array(z.string().min(1)).min(1),\n /**\n * The tasks this one waits for, resolved and reduced: the same change's `BE` task, and the track's tasks of the\n * changes it builds on that did the same work (an item of both, a line of a whole object this task edits again,\n * or an object this task names that entered the export with the earlier change).\n */\n after: z.array(z.object({ change: ChangeRef, track: TrackCode }).strict()),\n /**\n * The weight of each item on this track (format 3; per track and 0–100 from format 6): how much of the\n * behaviour the item specifies this track builds, reasoned at the change's sign-off against alterspec's rubric\n * (a typical acceptance criterion about 10), never anyone's code. 0: nothing to build on this track; the item\n * is read, not built, and counts in no progress. A task whose weights are all 0 has no work and is not handed\n * out. An item the sign-off didn't weigh takes the median of the task's weighed items above 0; a task of a\n * change signed off without weights has no `weights`, and a reader counts each of its items as 10.\n */\n weights: z.record(z.string().min(1), ItemWeight).optional(),\n /**\n * The size of what this track builds in this change, 1–100 (format 7): reasoned at sign-off against alterspec's\n * task rubric (a wording fix about 1–5, one capability's criteria 10–20, a new capability or flow 30–50, a new\n * module or the application's foundation 80–100), never a sum of the item weights and never anyone's code.\n * Absent: the change was signed off without one. For the lists; progress and ETA keep the item weights.\n */\n weight: WorkWeight.optional(),\n /**\n * What this track builds in this change, for a person reading a list (format 5): reasoned at the change's\n * sign-off, in the product's words, naming no ID. Absent: the change was signed off without one.\n */\n title: WorkTitle.optional(),\n /** The same in two or three plain sentences (format 5). */\n summary: WorkSummary.optional(),\n /**\n * What each item is (format 5), by item, naming only the task's own items and not necessarily all: reasoned at\n * sign-off where the spec has no word for the item (an acceptance criterion), composed at export from the spec\n * where it has (a screen's action, a contract's state, a part of an object, a whole object). For reading only.\n */\n labels: z.record(z.string().min(1), WorkLabel).optional(),\n })\n .strict();\nexport type WorkTask = z.infer<typeof WorkTaskSchema>;\n\nexport const WorkChangeSchema = z\n .object({\n id: ChangeRef,\n title: z.string(),\n signed_off: Day,\n /** The hash of the change's `delta.json`; a signed-off change never changes. */\n delta: z.string().regex(/^[0-9a-f]{16}$/),\n depends_on: z.array(ChangeRef),\n /** The change map's level. */\n level: z.number().int().min(1),\n /** One per track the change is on; empty = no work. */\n tasks: z.array(WorkTaskSchema),\n /** The initiative the change belongs to (format 8): its entry in `initiatives`. Absent: none. */\n initiative: InitiativeRef.optional(),\n })\n .strict();\nexport type WorkChange = z.infer<typeof WorkChangeSchema>;\n\n/** An initiative a change names (format 8): its prose is `initiatives/<id>.md` in the export. */\nexport const WorkInitiativeSchema = z.object({ id: InitiativeRef, title: z.string().min(1) }).strict();\nexport type WorkInitiative = z.infer<typeof WorkInitiativeSchema>;\n\nexport const WORK_FORMAT = 8;\n\nexport const WorkSchema = z\n .object({\n format: z.literal(WORK_FORMAT),\n /** The alterspec version that wrote the export. */\n alterspec: z.string(),\n exported: Day,\n /** Everything signed off before the changes began; `built`: the product as it runs (a reverse-spec), no work. */\n baseline: z.object({ date: Day, built: z.boolean() }).strict().nullable(),\n tracks: z.array(WorkTrackSchema),\n /** Every change signed off after the baseline, in the change map's order. */\n changes: z.array(WorkChangeSchema),\n /**\n * The title of every object a task's `objects` names, by key, as the spec holds it now (format 5); an object\n * the spec no longer holds, and a file, has no entry. Absent when no object has one.\n */\n names: z.record(z.string().min(1), WorkName).optional(),\n /** The initiatives the changes name, by ID (format 8). Absent when no change names one. */\n initiatives: z.array(WorkInitiativeSchema).optional(),\n })\n .strict();\nexport type Work = z.infer<typeof WorkSchema>;\n\n/** The first 12 hex of the SHA-256 of a text normalised for work (format 9). */\nconst Version = z.string().regex(/^[0-9a-f]{12}$/);\nconst TaskRef = z.object({ change: ChangeRef, track: TrackCode }).strict();\n\n/** One part of the brief alterspec writes for a task (format 9): sizes and paths, never text. */\nexport const WorkBriefPartSchema = z\n .object({\n kind: z.enum(['capability', 'used_by', 'decision', 'object']),\n key: z.string().min(1),\n /** A file path inside the export, never an anchor; `paragraphs` names a decision's paragraphs. */\n path: z.string().min(1),\n bytes: z.number().int().min(0),\n touched: z.boolean().optional(),\n paragraphs: z.array(z.string().min(1)).optional(),\n })\n .strict();\nexport type WorkBriefPart = z.infer<typeof WorkBriefPartSchema>;\n\n/** Format 9: a task may carry `versions`, `alters`, `brief` and `amends`; every one optional. */\nexport const WorkTaskV9Schema = WorkTaskSchema.extend({\n /** The version of every object, item and cited decision paragraph (`DEC-573#p3`) of the task, as of this export. */\n versions: z.record(z.string().min(1), Version).optional(),\n /** The tracks whose existing behaviour this task changes; sorted, never its own track. */\n alters: z.array(TrackCode).optional(),\n brief: z\n .object({ bytes: z.number().int().min(0), parts: z.array(WorkBriefPartSchema) })\n .strict()\n .optional(),\n /** The signed-off tasks whose cited objects a later edit changed, which this task exists for. A label only. */\n amends: z.array(TaskRef).optional(),\n})\n .strict()\n .refine((t) => !t.alters?.includes(t.track), {\n message: \"alters never names the task's own track\",\n path: ['alters'],\n });\nexport type WorkTaskV9 = z.infer<typeof WorkTaskV9Schema>;\n\n/**\n * Format 9: a change may be held (`released: false`, then no `tasks` field at all; `tasks: []` still means no work)\n * or `coupled` (the server task reaches the main branch only after the change's client tasks are done).\n */\nexport const WorkChangeV9Schema = WorkChangeSchema.extend({\n tasks: z.array(WorkTaskV9Schema).optional(),\n released: z.literal(false).optional(),\n coupled: z.literal(true).optional(),\n})\n .strict()\n .refine((c) => (c.released === false ? c.tasks === undefined : c.tasks !== undefined), {\n message: 'a held change (released: false) has no tasks; a released one has tasks',\n path: ['tasks'],\n });\nexport type WorkChangeV9 = z.infer<typeof WorkChangeV9Schema>;\n\n/** The release an export makes (format 9). Absent: every change in the file is released. */\nexport const WorkReleaseSchema = z\n .object({\n id: z.string().regex(/^R-\\d{4}-\\d{2}-\\d{2}-\\d+$/),\n date: Day,\n note: z\n .string()\n .max(400)\n .refine((t) => !/[\\r\\n]/.test(t), { message: 'one line' }),\n changes: z.array(ChangeRef),\n held: z.array(ChangeRef),\n touches: z.record(ChangeRef, z.array(z.string().min(1))),\n })\n .strict();\nexport type WorkRelease = z.infer<typeof WorkReleaseSchema>;\n\n/** Format 9 (read by client 0.31.0, written from alterspec 0.54.0): format 8 plus `paths`, `release` and the above. */\nexport const WorkV9Schema = WorkSchema.extend({\n format: z.literal(9),\n changes: z.array(WorkChangeV9Schema),\n /** The path of every object any task names, every decision any task cites, and every initiative. */\n paths: z.record(z.string().min(1), z.string().min(1)).optional(),\n release: WorkReleaseSchema.optional(),\n}).strict();\nexport type WorkV9 = z.infer<typeof WorkV9Schema>;\n\n/** Format 7 (alterspec 0.42): the same without the change's `initiative` and without `initiatives`. */\nexport const WorkChangeV7Schema = WorkChangeSchema.omit({ initiative: true }).strict();\nexport type WorkChangeV7 = z.infer<typeof WorkChangeV7Schema>;\n\nexport const WorkV7Schema = WorkSchema.omit({ initiatives: true })\n .extend({ format: z.literal(7), changes: z.array(WorkChangeV7Schema) })\n .strict();\nexport type WorkV7 = z.infer<typeof WorkV7Schema>;\n\n/**\n * Format 6 (alterspec 0.41): the same without the task's `weight`, with the size of the whole change, 1–100, as\n * the change's optional `weight`.\n */\nexport const WorkTaskV6Schema = WorkTaskSchema.omit({ weight: true }).strict();\nexport type WorkTaskV6 = z.infer<typeof WorkTaskV6Schema>;\n\nexport const WorkChangeV6Schema = WorkChangeV7Schema.extend({\n tasks: z.array(WorkTaskV6Schema),\n weight: WorkWeight.optional(),\n}).strict();\nexport type WorkChangeV6 = z.infer<typeof WorkChangeV6Schema>;\n\nexport const WorkV6Schema = WorkV7Schema.extend({\n format: z.literal(6),\n changes: z.array(WorkChangeV6Schema),\n}).strict();\nexport type WorkV6 = z.infer<typeof WorkV6Schema>;\n\n/** Format 5 (alterspec 0.38 to 0.40): the same with one weight per item for every track, 1–100. */\nexport const WorkTaskV5Schema = WorkTaskV6Schema.extend({\n weights: z.record(z.string().min(1), WorkWeight).optional(),\n}).strict();\nexport type WorkTaskV5 = z.infer<typeof WorkTaskV5Schema>;\n\nexport const WorkChangeV5Schema = WorkChangeV6Schema.extend({ tasks: z.array(WorkTaskV5Schema) }).strict();\nexport type WorkChangeV5 = z.infer<typeof WorkChangeV5Schema>;\n\nexport const WorkV5Schema = WorkV7Schema.extend({\n format: z.literal(5),\n changes: z.array(WorkChangeV5Schema),\n}).strict();\nexport type WorkV5 = z.infer<typeof WorkV5Schema>;\n\n/** Format 4 (alterspec 0.34 to 0.37): the same without the tasks' `title`, `summary` and `labels` and without `names`. */\nexport const WorkTaskV4Schema = WorkTaskV5Schema.omit({ title: true, summary: true, labels: true }).strict();\nexport type WorkTaskV4 = z.infer<typeof WorkTaskV4Schema>;\n\nexport const WorkChangeV4Schema = WorkChangeV5Schema.extend({ tasks: z.array(WorkTaskV4Schema) }).strict();\nexport type WorkChangeV4 = z.infer<typeof WorkChangeV4Schema>;\n\nexport const WorkV4Schema = WorkV5Schema.omit({ names: true })\n .extend({ format: z.literal(4), changes: z.array(WorkChangeV4Schema) })\n .strict();\nexport type WorkV4 = z.infer<typeof WorkV4Schema>;\n\n/** Format 3 (alterspec 0.33): the same without the change's `weight`. */\nexport const WorkChangeV3Schema = WorkChangeV4Schema.omit({ weight: true }).strict();\nexport type WorkChangeV3 = z.infer<typeof WorkChangeV3Schema>;\n\nexport const WorkV3Schema = WorkV4Schema.extend({\n format: z.literal(3),\n changes: z.array(WorkChangeV3Schema),\n}).strict();\nexport type WorkV3 = z.infer<typeof WorkV3Schema>;\n\n/** Format 2 (alterspec 0.24 to 0.32): the same without `weights`. */\nexport const WorkTaskV2Schema = WorkTaskV4Schema.omit({ weights: true });\nexport type WorkTaskV2 = z.infer<typeof WorkTaskV2Schema>;\n\nexport const WorkV2Schema = WorkV4Schema.extend({\n format: z.literal(2),\n changes: z.array(WorkChangeV3Schema.extend({ tasks: z.array(WorkTaskV2Schema) }).strict()),\n}).strict();\nexport type WorkV2 = z.infer<typeof WorkV2Schema>;\n\n/** Format 1 (alterspec 0.23): the same without `items`, `weights` and the change's `weight`. */\nexport const WorkTaskV1Schema = WorkTaskV2Schema.omit({ items: true });\nexport type WorkTaskV1 = z.infer<typeof WorkTaskV1Schema>;\n\nexport const WorkV1Schema = WorkV4Schema.extend({\n format: z.literal(1),\n changes: z.array(WorkChangeV3Schema.extend({ tasks: z.array(WorkTaskV1Schema) }).strict()),\n}).strict();\nexport type WorkV1 = z.infer<typeof WorkV1Schema>;\n\n/** Any format, told apart by `format`: what a reader of exports from several alterspec versions takes. */\nexport const AnyWorkSchema = z.discriminatedUnion('format', [\n WorkV1Schema,\n WorkV2Schema,\n WorkV3Schema,\n WorkV4Schema,\n WorkV5Schema,\n WorkV6Schema,\n WorkV7Schema,\n WorkSchema,\n WorkV9Schema,\n]);\nexport type AnyWork = z.infer<typeof AnyWorkSchema>;\n","import { type ClientConfig, isProduct } from './config.js';\n\n/**\n * The two roles a key has with the dispatcher (spec decisions 32 and 33, sections 8.6 and 12.4): a developer takes\n * tasks, a product person answers the build's questions and sees no build state. A person may be both; a session is\n * one, the role its configuration means, asked for on every request (`X-Alterspec-Role`). The proxy cuts\n * `tools/list` to the role's tools and refuses a call outside them itself, so a product session never reaches a\n * task, whatever the dispatcher lists.\n */\n\nexport type Role = 'developer' | 'product';\n\n/** The request header the session's role is asked with (dispatcher spec 10.5, decision 33). */\nexport const ROLE_HEADER = 'x-alterspec-role';\n\n/** The role a configuration means: `product` without an export (`init --product`), `developer` with one. */\nexport const roleOfConfig = (config: ClientConfig): Role => (isProduct(config) ? 'product' : 'developer');\n\n/** The product role's tools, and no other (spec 10.3, \"Tools by role\"). */\nexport const PRODUCT_TOOLS = [\n 'whoami',\n 'questions',\n 'answer',\n 'reconcile',\n 'feedback',\n 'bug_reports',\n] as const;\n\n/** The tools only the product role has; every other tool the dispatcher lists is the developers'. */\nexport const PRODUCT_ONLY = new Set<string>(['answer', 'reconcile', 'bug_reports']);\n\n/** The role `whoami` returns; `product: true` stands for `role: product` while the dispatcher is older. */\nexport function roleOf(whoami: Record<string, unknown>): Role {\n if (whoami.role === 'product' || whoami.role === 'developer') return whoami.role;\n return whoami.product === true ? 'product' : 'developer';\n}\n\n/**\n * Whether the role may call the tool: a product key only its six (an allow-list, so a product session never sees a\n * developer tool the dispatcher adds later), a developer key everything but the product's own (a deny-list, so a\n * developer tool added later is never hidden by an older client).\n */\nexport function allows(role: Role, tool: string): boolean {\n return role === 'product' ? (PRODUCT_TOOLS as readonly string[]).includes(tool) : !PRODUCT_ONLY.has(tool);\n}\n\n/** The refusal the proxy answers a call outside the role with: the dispatcher's codes, one sentence. */\nexport function refusal(role: Role, tool: string): { code: string; message: string } {\n return role === 'product'\n ? {\n code: 'NOT_DEVELOPER',\n message: `Your key is registered as a product person; \\`${tool}\\` is the developers'. A product session sees the build's questions, feedback and bugs, never its tasks.`,\n }\n : {\n code: 'NOT_PRODUCT',\n message: `Your key is registered as a developer; \\`${tool}\\` is the product side's. Answers and reconciling are the spec project's, through a key registered as a product person.`,\n };\n}\n","import { execFileSync } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir, tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * The developer's SSH key (spec 10.5): which public key the client signs with, its fingerprint as `ssh-keygen -l`\n * prints it, and the signature of a challenge by `ssh-keygen -Y sign`, through ssh-agent when it holds the key. The\n * private key never leaves ssh-agent or ssh-keygen.\n */\n\nexport const NAMESPACE = 'alterspec-dispatcher';\nconst KEY_TYPES = ['ssh-ed25519', 'sk-ssh-ed25519@openssh.com'];\n\nexport class KeyError extends Error {}\n\nexport interface PublicKey {\n type: string;\n /** The key line as `authorized_keys` holds it: type, base64 blob, comment. */\n line: string;\n /** `SHA256:` and the unpadded base64 SHA-256 of the key blob, as `ssh-keygen -l` prints it. */\n fingerprint: string;\n /** Where it came from, for messages: a path or `ssh-agent`. */\n source: string;\n /** The `.pub` file, when the key came from one. */\n file?: string;\n}\n\nexport function parseKeyLine(line: string, source: string, file?: string): PublicKey {\n const [type, blob] = line.trim().split(/\\s+/);\n if (!type || !blob || !KEY_TYPES.includes(type))\n throw new KeyError(\n `${source} is not an ssh-ed25519 public key: the dispatcher accepts ${KEY_TYPES.join(' and ')}.`,\n );\n const bytes = Buffer.from(blob, 'base64');\n const fingerprint = `SHA256:${createHash('sha256').update(bytes).digest('base64').replace(/=+$/, '')}`;\n return { type, line: line.trim(), fingerprint, source, ...(file ? { file } : {}) };\n}\n\n/** The key lines ssh-agent holds, or none when there is no agent. */\nexport function agentKeys(): string[] {\n try {\n return execFileSync('ssh-add', ['-L'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })\n .split('\\n')\n .filter((l) => l.trim());\n } catch {\n return [];\n }\n}\n\nexport interface KeyOptions {\n /** The configuration's `key`: a key line, or a `.pub` path already made absolute. */\n configured?: string;\n agent?: () => string[];\n home?: string;\n}\n\nconst isKeyLine = (s: string) => KEY_TYPES.some((t) => s.trim().startsWith(`${t} `));\n\n/** The key the client signs with: the configured one, else the first ssh-ed25519 key in ssh-agent, else `~/.ssh/id_ed25519.pub`. */\nexport function resolveKey(opts: KeyOptions = {}): PublicKey {\n const { configured, agent = agentKeys, home = homedir() } = opts;\n if (configured) {\n if (isKeyLine(configured)) return parseKeyLine(configured, 'the configuration');\n if (!existsSync(configured)) throw new KeyError(`The configured key ${configured} doesn't exist.`);\n return parseKeyLine(readFileSync(configured, 'utf8'), configured, configured);\n }\n const fromAgent = agent().find((l) => l.startsWith('ssh-ed25519 '));\n if (fromAgent) return parseKeyLine(fromAgent, 'ssh-agent');\n const file = join(home, '.ssh', 'id_ed25519.pub');\n if (existsSync(file)) return parseKeyLine(readFileSync(file, 'utf8'), file, file);\n throw new KeyError(\n 'No SSH key to sign with: add an ssh-ed25519 key to ssh-agent, create ~/.ssh/id_ed25519, or name one as `key` in .alterspec-client.json.',\n );\n}\n\nconst blobOf = (line: string) => line.trim().split(/\\s+/)[1];\n\n/**\n * The armored SSH signature of `data` (its UTF-8 bytes, nothing added) in the dispatcher's namespace. Through\n * ssh-agent when it holds the key (passphrase-protected keys included), else with the private key beside the `.pub`.\n */\nexport function sign(key: PublicKey, data: string, agent: () => string[] = agentKeys): string {\n const inAgent = agent().some((l) => blobOf(l) === blobOf(key.line));\n const temp = !key.file || inAgent ? mkdtempSync(join(tmpdir(), 'alterspec-client-')) : undefined;\n try {\n let keyFile: string;\n if (inAgent || !key.file) {\n if (!inAgent)\n throw new KeyError(`ssh-agent doesn't hold the key ${key.fingerprint}: add it with ssh-add.`);\n // A public key file makes ssh-keygen sign through the agent.\n keyFile = join(temp!, 'key.pub');\n writeFileSync(keyFile, key.line + '\\n');\n } else {\n keyFile = key.file.replace(/\\.pub$/, '');\n if (keyFile === key.file || !existsSync(keyFile))\n throw new KeyError(\n `No private key beside ${key.file} and ssh-agent doesn't hold it: add it with ssh-add.`,\n );\n }\n return execFileSync('ssh-keygen', ['-q', '-Y', 'sign', '-n', NAMESPACE, '-f', keyFile], {\n input: data,\n encoding: 'utf8',\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n } catch (e) {\n if (e instanceof KeyError) throw e;\n const stderr = String((e as { stderr?: unknown }).stderr ?? '').trim();\n throw new KeyError(\n `ssh-keygen could not sign with ${key.fingerprint}${stderr ? `: ${stderr}` : ''}. A key with a passphrase must be in ssh-agent (ssh-add).`,\n );\n } finally {\n if (temp) rmSync(temp, { recursive: true, force: true });\n }\n}\n","import { type LoadedConfig, configPath } from './config.js';\nimport { ROLE_HEADER, type Role, roleOfConfig } from './role.js';\nimport { type PublicKey, resolveKey, sign } from './ssh.js';\n\n/**\n * Signing in to the dispatcher with the developer's SSH key (spec 10.5): a challenge, its nonce signed, a token valid\n * for hours, kept in memory only and renewed when it runs out or the dispatcher says to sign in again.\n */\n\n/** An answer of the dispatcher that is no success, with its stable code and its sentence. */\nexport class DispatcherError extends Error {\n constructor(\n readonly code: string,\n message: string,\n readonly status?: number,\n ) {\n super(message);\n }\n}\n\n/** The dispatcher does not let this key in: unknown, removed, or its developer disabled. */\nexport class KeyRefused extends DispatcherError {\n constructor(\n code: string,\n message: string,\n readonly key: PublicKey,\n ) {\n super(code, message);\n }\n /** One sentence, and the key to send to the admin. */\n get advice(): string {\n return `The dispatcher refused your SSH key (${this.code}): send this public key to an admin, then reconnect the dispatcher server in Claude Code (/mcp).\\n${this.key.line}\\n${this.key.fingerprint}`;\n }\n}\n\nconst REFUSED = new Set(['KEY_UNKNOWN', 'DEVELOPER_UNKNOWN', 'DEVELOPER_INACTIVE']);\n/** Renew this long before the token runs out. */\nconst MARGIN_MS = 60_000;\n\nexport interface SessionOptions {\n fetch?: typeof fetch;\n now?: () => number;\n signer?: (key: PublicKey, data: string) => string;\n /**\n * The role this configuration means (spec 10.5, decision 33), sent on every request as `X-Alterspec-Role`: a\n * product configuration asks `product`, a track repository's `developer`; none, and the dispatcher takes the\n * person's own. A role the key's row lacks is refused by the dispatcher (`ROLE_NOT_ALLOWED`).\n */\n role?: Role;\n}\n\nasync function errorOf(res: Response, key: PublicKey): Promise<DispatcherError> {\n let code = 'HTTP_' + res.status;\n let message = `The dispatcher answered ${res.status} ${res.statusText}.`;\n try {\n const body = (await res.json()) as { error?: { code?: string; message?: string } };\n if (body.error?.code) code = body.error.code;\n if (body.error?.message) message = body.error.message;\n } catch {\n // Not JSON: keep the status.\n }\n return REFUSED.has(code)\n ? new KeyRefused(code, message, key)\n : new DispatcherError(code, message, res.status);\n}\n\nexport class Session {\n private token?: { value: string; expires: number };\n private readonly fetchFn: typeof fetch;\n private readonly now: () => number;\n private readonly signer: (key: PublicKey, data: string) => string;\n /** The role asked for on every request, when the configuration means one (decision 33). */\n readonly role?: Role;\n /** How many times this session signed in, for tests and logs. */\n signIns = 0;\n\n constructor(\n readonly base: string,\n readonly key: PublicKey,\n opts: SessionOptions = {},\n ) {\n this.base = base.replace(/\\/+$/, '');\n this.fetchFn = opts.fetch ?? fetch;\n this.now = opts.now ?? Date.now;\n this.signer = opts.signer ?? sign;\n this.role = opts.role;\n }\n\n private async call(path: string, init: RequestInit): Promise<Response> {\n try {\n return await this.fetchFn(this.base + path, init);\n } catch (e) {\n throw new DispatcherError(\n 'UNREACHABLE',\n `The dispatcher at ${this.base} can't be reached (${(e as Error).message}).`,\n );\n }\n }\n\n private async post(path: string, body: unknown): Promise<unknown> {\n const res = await this.call(path, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw await errorOf(res, this.key);\n return res.json();\n }\n\n private async signIn(): Promise<void> {\n const { fingerprint } = this.key;\n const { nonce } = (await this.post('/auth/challenge', { fingerprint })) as { nonce: string };\n const signature = this.signer(this.key, nonce);\n const t = (await this.post('/auth/token', { fingerprint, nonce, signature })) as {\n token: string;\n expires_at: string;\n };\n this.token = { value: t.token, expires: Date.parse(t.expires_at) };\n this.signIns++;\n }\n\n /** A valid token, signing in when there is none or it is about to run out. */\n async bearer(): Promise<string> {\n if (!this.token || this.token.expires - MARGIN_MS <= this.now()) await this.signIn();\n return this.token!.value;\n }\n\n /**\n * A request with the token. A 401 `UNAUTHENTICATED` (token expired or revoked) signs in again once and repeats\n * the request; a refused key surfaces then as `KeyRefused`.\n */\n async fetch(path: string, init: RequestInit = {}): Promise<Response> {\n for (let attempt = 0; ; attempt++) {\n const headers = new Headers(init.headers);\n headers.set('authorization', `Bearer ${await this.bearer()}`);\n if (this.role) headers.set(ROLE_HEADER, this.role);\n const res = await this.call(path, { ...init, headers });\n if (res.status !== 401 || attempt > 0) {\n if (res.status === 401 || res.status === 403) throw await errorOf(res, this.key);\n return res;\n }\n const err = await errorOf(res, this.key);\n if (err.code !== 'UNAUTHENTICATED') throw err;\n this.token = undefined;\n }\n }\n}\n\n/** The key of this repository's configuration, else the default one. */\nexport function keyOf(loaded: LoadedConfig | undefined): PublicKey {\n const key = loaded?.config.key;\n const configured =\n key && !/^(ssh-ed25519|sk-ssh-ed25519@openssh\\.com) /.test(key) ? configPath(loaded.root, key) : key;\n return resolveKey({ configured });\n}\n\n/** A session with the dispatcher of this repository's configuration. */\n/** The session of a configuration: its dispatcher, its key, and the role it means (decision 33). */\nexport const sessionOf = (loaded: LoadedConfig) =>\n new Session(loaded.config.dispatcher, keyOf(loaded), { role: roleOfConfig(loaded.config) });\n","import { z } from 'zod';\nimport type { ExportReader } from '../../src/export/read.js';\nimport type { Session } from './auth.js';\nimport { type CoveredState, type StartFrom, itemWhat, startFrom } from './context.js';\nimport { callTool } from './mcp.js';\nimport { type Question, questionsSection } from './questions.js';\nimport type { TaskRef } from './task.js';\n\n/**\n * Bugs (spec 8.5, decision 17): a deviation of the product from the spec, raised from the client after grooming the\n * report against the export, kept by the dispatcher and never by the spec. Raising and dismissing are the\n * dispatcher's tools, called by the agent; the CLI reads the bugs back and assembles a bug task's brief.\n */\n\nconst BugTaskSchema = z.object({\n id: z.string(),\n track: z.string(),\n status: z.string(),\n developer: z.string().nullish(),\n items: z.array(z.string()).default([]),\n /** The built tasks it waits for. */\n after: z.array(z.string()).default([]),\n branch: z.string().nullish(),\n in_main: z.boolean().nullish(),\n});\n\nexport type BugTask = z.infer<typeof BugTaskSchema>;\n\nconst BugSchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string(),\n /** The reporter. */\n developer: z.string(),\n at: z.string(),\n export: z.string().nullish(),\n cites: z.array(z.string()).default([]),\n /** The changes of the tasks it waits for. */\n origin: z.array(z.string()).default([]),\n status: z.enum(['open', 'done', 'dismissed']).default('open'),\n dismissed: z\n .object({ by: z.string(), at: z.string(), reason: z.string(), duplicate_of: z.string().nullish() })\n .nullish(),\n tasks: z.array(BugTaskSchema).default([]),\n});\n\nexport type Bug = z.infer<typeof BugSchema>;\n\nexport class BugsError extends Error {}\n\nexport interface BugsFilter {\n /** Everyone's bugs naming these IDs, to find one raised before. */\n about?: string[];\n status?: 'open' | 'done' | 'dismissed';\n track?: string;\n}\n\n/** The bugs naming some IDs, or without `about` the developer's own (which marks them as listed). */\nexport async function listBugs(session: Session, filter: BugsFilter = {}): Promise<Bug[]> {\n const answer = await callTool(session, 'bugs', {\n ...(filter.about ? { about: filter.about } : { mine: true }),\n ...(filter.status ? { status: filter.status } : {}),\n ...(filter.track ? { track: filter.track } : {}),\n });\n const parsed = z.array(BugSchema).safeParse(answer.bugs ?? []);\n if (!parsed.success) throw new BugsError('The dispatcher’s bugs are not in a form this client reads.');\n return parsed.data;\n}\n\nconst one = (text: string) => text.replace(/\\s+/g, ' ').trim();\n\n/** One task of a bug in a few words: its status, who has it, what it waits for or where it is. */\nfunction bugTaskWords(t: BugTask): string {\n const who = t.developer ? ` (${t.developer})` : '';\n const where =\n t.status === 'blocked' && t.after.length\n ? `, after ${t.after.join(', ')}`\n : t.status === 'done'\n ? t.in_main\n ? ', in main'\n : t.branch\n ? `, on \\`${t.branch}\\``\n : ''\n : '';\n return `${t.id} ${t.status}${who}${where}`;\n}\n\n/** One bug as the lines the agent reads: what is wrong, whose word, where its tasks stand. */\nexport function bugLines(b: Bug): string[] {\n const state =\n b.status === 'dismissed'\n ? `dismissed by ${b.dismissed?.by ?? 'an admin'}${b.dismissed?.duplicate_of ? `, duplicate of ${b.dismissed.duplicate_of}` : ''}`\n : b.status;\n const lines = [`- ${b.id} (${state}; ${b.developer}, ${b.at.slice(0, 10)}): ${one(b.title)}`];\n if (b.cites.length) lines.push(` - Cites: ${b.cites.join(', ')}`);\n if (b.dismissed) lines.push(` - Reason: ${one(b.dismissed.reason)}`);\n else if (b.tasks.length) lines.push(` - Tasks: ${b.tasks.map(bugTaskWords).join('; ')}`);\n return lines;\n}\n\nexport function bugsText(bugs: Bug[]): string {\n if (!bugs.length) return 'No bugs.\\n';\n return bugs.flatMap(bugLines).join('\\n') + '\\n';\n}\n\n/** The `bug` of the dispatcher's `task` for a bug task; undefined when it sends none or something this client doesn't read. */\nexport function parseBug(raw: unknown): Bug | undefined {\n const parsed = BugSchema.safeParse(raw);\n return parsed.success ? parsed.data : undefined;\n}\n\n/** What the dispatcher says of a bug task: its bug, its objects, what it waits for and where it starts from. */\nexport interface BugTaskState extends CoveredState {\n bug: Bug;\n objects: string[];\n after: string[];\n}\n\n/** The dispatcher's `task` of a bug task; a bug task has no brief without it (work.json never names a bug). */\nexport async function bugTaskState(session: Session, task: TaskRef): Promise<BugTaskState> {\n let answer: Record<string, unknown>;\n try {\n answer = await callTool(session, 'task', { id: task.id });\n } catch (e) {\n throw new BugsError(\n `${task.id} is a bug's task, and only the dispatcher holds a bug: ${(e as Error).message.split('\\n')[0]}`,\n );\n }\n const bug = parseBug(answer.bug);\n if (!bug) throw new BugsError(`The dispatcher sent no bug for ${task.id} this client reads.`);\n const items = (answer.items ?? []) as { item: string; covered_commit: string | null }[];\n const from = startFrom(task.track, answer.after);\n return {\n bug,\n objects: z.array(z.string()).catch([]).parse(answer.objects),\n after: ((answer.after ?? []) as { id?: string }[]).flatMap((a) => (a.id ? [a.id] : [])),\n // The task's items are the bug's cites on this track, not every track's.\n ...(items.length ? { items: items.map((i) => ({ item: i.item })) } : {}),\n covered: new Map(items.flatMap((i) => (i.covered_commit ? [[i.item, i.covered_commit] as const] : []))),\n ...(from.length ? { startFrom: from } : {}),\n };\n}\n\nexport interface BugObject {\n key: string;\n file?: string;\n shards?: string;\n /** The changes of the export that touched it, latest last (`changed_by`). */\n changed_by?: string[];\n}\n\nexport interface BugContext {\n task: string;\n bug: Bug;\n track: { code: string; kind: string; channels: string[] };\n export: string;\n questions?: Question[];\n after: string[];\n startFrom?: StartFrom[];\n checklist: { items: { item: string; what: string; covered?: string }[] };\n /** The objects the cites belong to, where each is in the export now. */\n objects: BugObject[];\n /** The changes the bug originates in, each with its title and proposal. */\n origin: { id: string; title?: string; proposal?: string }[];\n}\n\n/** The object key an item's ID starts with, among the task's objects; the item itself when none does. */\nexport const objectOfItem = (item: string, objects: readonly string[]): string =>\n [...objects]\n .filter(\n (o) => item === o || item.startsWith(`${o}-`) || item.startsWith(`${o}.`) || item.startsWith(`${o}#`),\n )\n .sort((a, b) => b.length - a.length)[0] ?? item.replace(/(-AC-\\d+|\\.A\\d+|#.+)$/, '');\n\n/**\n * A bug task's brief: the bug's words and cites, the cites as the checklist, the objects they belong to as they are\n * in the export now (a bug is fixed against the current text, not a delta), and the changes it originates in.\n */\nexport function bugContext(\n x: ExportReader,\n task: TaskRef,\n exportDir: string,\n state: BugTaskState,\n questions?: Question[],\n): BugContext {\n const track = x.work.tracks.find((t) => t.code === task.track) ?? {\n code: task.track,\n kind: 'ui',\n channels: [],\n };\n // The checklist is this track's cites, as the dispatcher's task holds them; a bug cited on two tracks has two tasks.\n const cites = state.items?.length ? state.items.map((i) => i.item) : state.bug.cites;\n const keys = [...new Set(state.objects.length ? state.objects : cites.map((c) => objectOfItem(c, [])))];\n const objects: BugObject[] = keys.map((key) => {\n const file = x.fileOf(key);\n const held = file !== undefined && x.has(file);\n const o: BugObject = { key, ...(held ? { file } : {}) };\n if (held && x.shards(file).length) o.shards = x.shards(file)[0]!.replace(/\\/[^/]+$/, '');\n const by = x.sources.get(key)?.changed_by;\n if (by?.length) o.changed_by = by;\n return o;\n });\n return {\n task: task.id,\n bug: state.bug,\n track: { code: track.code, kind: track.kind, channels: track.channels },\n export: exportDir,\n ...(questions?.length ? { questions } : {}),\n after: state.after,\n ...(state.startFrom?.length ? { startFrom: state.startFrom } : {}),\n checklist: {\n items: cites.map((item) => {\n const covered = state.covered?.get(item);\n return { item, what: itemWhat(x, item, undefined, task.track), ...(covered ? { covered } : {}) };\n }),\n },\n objects,\n origin: state.bug.origin.map((id) => {\n const change = x.work.changes.find((c) => c.id === id);\n const proposal = x.proposalPath(id);\n return { id, ...(change ? { title: change.title } : {}), ...(proposal ? { proposal } : {}) };\n }),\n };\n}\n\n/** The brief of a bug task as Markdown, for the agent. */\nexport function renderBugContext(c: BugContext): string {\n const b = c.bug;\n const out: string[] = [\n `# ${c.task}: ${b.title}`,\n '',\n `Track ${c.track.code} (${c.track.kind}${c.track.channels.length ? `: ${c.track.channels.join(', ')}` : ''}). ` +\n `Bug ${b.id}, raised by ${b.developer} on ${b.at.slice(0, 10)}${b.export ? `, groomed against export ${b.export.slice(0, 12)}` : ''}` +\n `${b.origin.length ? `, in what ${b.origin.join(', ')} built` : ''}. ` +\n `Paths are relative to the export, ${c.export}.`,\n ];\n if (c.after.length) out.push('', `Waits for: ${c.after.join(', ')}.`);\n if (c.startFrom?.length)\n out.push(\n '',\n `Start from ${c.startFrom.map((s) => `\\`${s.branch}\\` (${s.id}${s.commit ? ` done at ${s.commit.slice(0, 12)}` : ''})`).join(', then ')}, not from the main branch: ` +\n `the work the bug is in is pushed there and not merged yet (fetch it and base your branch on \\`origin/${c.startFrom[c.startFrom.length - 1]!.branch}\\`).`,\n );\n out.push('');\n if (c.questions?.length) out.push(...questionsSection(c.questions));\n out.push(\n '## The bug',\n '',\n 'The reporter’s words, naming IDs; what the spec says is in the export, under the objects below. The product deviates from the cited items: make it do what they say, and nothing else. The tasks that built them stay as they are; this task is the fix.',\n '',\n b.description.trim(),\n '',\n `Cites: ${b.cites.join(', ')}.`,\n );\n const done = c.checklist.items.filter((i) => i.covered).length;\n out.push(\n '',\n `## Checklist (${done} of ${c.checklist.items.length} covered)`,\n '',\n 'The cited items on this track. Name an item in `Alterspec-Covers` on the commit with which its tests pass again.',\n '',\n ...c.checklist.items.map(\n (i) =>\n `- [${i.covered ? 'x' : ' '}] \\`${i.item}\\`: ${i.what}${i.covered ? ` (covered by ${i.covered.slice(0, 12)})` : ''}`,\n ),\n );\n out.push('', '## The objects', '', 'What the spec says now; a bug is fixed against the current text.', '');\n for (const o of c.objects) {\n const where = o.file\n ? `\\`${o.file}\\`${o.shards ? `, shards in \\`${o.shards}/\\`` : ''}`\n : 'not in the export now';\n out.push(\n `- ${o.key}: ${where}${o.changed_by?.length ? `; last changed by ${o.changed_by.join(', ')}` : ''}.`,\n );\n }\n if (c.origin.length) {\n out.push(\n '',\n '## The changes it originates in',\n '',\n 'What was built and found wanting; their proposals say why.',\n '',\n );\n for (const ch of c.origin)\n out.push(`- ${ch.id}${ch.title ? ` ${ch.title}` : ''}${ch.proposal ? `: ${ch.proposal}` : ''}`);\n }\n out.push('');\n return out.join('\\n');\n}\n","import { z } from 'zod';\nimport { ObjectKey } from './change.js';\nimport { ChangeId } from './ids.js';\n\n/**\n * The record of what a signed-off change changed in the spec, written once at sign-off next to its archived proposal\n * (`delta.json`, rendered as `delta.md`). One entry per object whose content or place the sign-off changed, with its\n * text before and after; generated blocks are left out of both, so a regenerated view is never work.\n */\n\nconst Fingerprint = z.string().regex(/^[0-9a-f]{16}$/);\nconst Side = <T extends z.ZodType>(t: T) => z.object({ before: t.optional(), after: t.optional() }).strict();\nconst Binary = z.object({ sha256: z.string().regex(/^[0-9a-f]{64}$/), size: z.number().int() }).strict();\n\nexport const DeltaChange = z.enum(['added', 'modified', 'removed', 'moved']);\nexport type DeltaChange = z.infer<typeof DeltaChange>;\n\nexport const DeltaEntrySchema = z\n .object({\n key: ObjectKey,\n kind: z.enum(['doc', 'item', 'prose']),\n change: DeltaChange,\n file: Side(z.string()),\n /** The object's status before and after, when it has one. */\n status: Side(z.string()).optional(),\n /** Whether the export held the object before and after the sign-off (`buildBundle`). */\n exported: z.object({ before: z.boolean(), after: z.boolean() }).strict(),\n fingerprint: Side(Fingerprint),\n /** The text without generated blocks; absent for a binary file and for a side the object has no content on. */\n before: z.string().optional(),\n after: z.string().optional(),\n /** A binary file (an image): its hash and size instead of its text. */\n binary: Side(Binary).optional(),\n })\n .strict();\nexport type DeltaEntry = z.infer<typeof DeltaEntrySchema>;\n\nexport const DeltaSchema = z\n .object({\n change: ChangeId,\n title: z.string(),\n signed_off: z.iso.date().optional(),\n /** `git`: rebuilt afterwards from the repository's history by `alterspec migrate changes`. */\n recovered: z.literal('git').optional(),\n /** In the export: which objects it shows in export terms only (see the export README). */\n view: z.literal('export').optional(),\n objects: z.array(DeltaEntrySchema),\n /** Objects a rebuilt delta could not recover, with why. */\n unrecoverable: z.array(z.object({ key: z.string(), why: z.string() }).strict()).optional(),\n })\n .strict();\nexport type Delta = z.infer<typeof DeltaSchema>;\n","import { z } from 'zod';\nimport { AcceptSchema, Title, list } from './common.js';\nimport { ChangeId, ID_REGEX, InitiativeId, type IdKind } from './ids.js';\nimport { ItemWeight, TrackCode, WorkLabel, WorkSummary, WorkTitle, WorkWeight } from './work.js';\n\n/** `signed_off` is the end: a change is merged into the spec the moment the person signs it off. */\nexport const ChangeStatus = z.enum(['draft', 'in_review', 'signed_off', 'rejected'], {\n error: (iss) =>\n iss.input === 'applied' || iss.input === 'approved'\n ? `${iss.input} is no longer a status: a change is merged into the spec when it is signed off; \\`alterspec status migrate\\` moves a spec to the current statuses`\n : undefined,\n});\nexport type ChangeStatus = z.infer<typeof ChangeStatus>;\n\n/**\n * Key of an object a change touches: a spec ID, `term:<Term>` for a glossary term,\n * or `file:<path>` for a prose file such as application/nfr.md.\n */\nexport const ObjectKey = z\n .string()\n .refine(\n (v) =>\n /^term:\\S.*$/.test(v) ||\n /^file:[\\w./-]+\\.md$/.test(v) ||\n /^file:experience\\/(?:[a-z]{2,5}\\/)?mockups\\/[\\w./-]+$/.test(v) ||\n v === 'file:experience/data.js' ||\n (Object.keys(ID_REGEX) as IdKind[]).some(\n (k) => k !== 'screenAction' && k !== 'acceptance' && ID_REGEX[k].test(v),\n ),\n { message: 'must be a spec ID, term:<Term> or file:<path>' },\n );\n\nexport const ChangeSchema = z\n .object({\n id: ChangeId,\n title: Title,\n status: ChangeStatus,\n created: z.iso.date(),\n /** The day the change was signed off and merged. Written by the CLI. */\n signed_off: z.iso.date().optional(),\n /** Objects this change removes. */\n removes: list(ObjectKey),\n /**\n * Fingerprint of each touched object when the change started touching it (null = new object).\n * Written by the CLI; used to detect conflicts.\n */\n base: z.record(z.string(), z.string().nullable()).default({}),\n /**\n * The earlier signed-off changes this one builds on: developers take it after them. Written by the CLI at sign-off\n * once a baseline exists, never rewritten; `[]` builds on the baseline alone. Absent: signed off before the\n * baseline, part of it.\n */\n depends_on: z.array(ChangeId).optional(),\n /**\n * The tracks the change puts work on (`BE`, or the code of a channel with an experience of its own), each with the\n * keys of its delta that put it there; `{}` = no work. Written by the CLI at sign-off next to `depends_on`, never\n * rewritten, so a channel added later gives an old change no task.\n */\n tracks: z.record(TrackCode, z.array(z.string())).optional(),\n /**\n * The weight of each task item (`work.json`), 0–100, on every track that has no weight of its own for it\n * (`track_weights`): how much specified behaviour the item adds or changes, reasoned by the sign-off skill\n * against the rubric (`_weights.md`), never anyone's code. Written by `change weigh`, frozen at sign-off next\n * to `tracks` (`{}` = signed off without weighing); absent = signed off before weights existed. The dispatcher\n * weighs progress and ETA by it.\n */\n weights: z.record(z.string(), ItemWeight).optional(),\n /**\n * The weight of an item on one track where it differs from `weights`, by track then item, 0–100: the part of\n * the behaviour that track builds; 0 when it builds nothing of it (a criterion only another channel shows).\n * Written by `change weigh` (an entry with `track`), frozen at sign-off as it is.\n */\n track_weights: z.record(TrackCode, z.record(z.string(), ItemWeight)).optional(),\n /**\n * Superseded by `task_weights` (0.42.0): the size of the whole change, 1–100, as `change weigh` wrote it from\n * 0.34 to 0.41. Still read so an archived proposal stays valid; nothing uses it, and the next `change weigh`\n * with a task weight removes it.\n */\n change_weight: WorkWeight.optional(),\n /** Superseded with `change_weight`. */\n change_weight_why: z.string().optional(),\n /**\n * The size of each task's work, by track, 1–100 (`work.json` format 7, `tasks[].weight`): how much that track\n * builds in this change, reasoned by the sign-off skill against the rubric (`_weights.md` \"The task's weight\"),\n * never a sum of the item weights and never anyone's code. Written by `change weigh` (an entry `{ task }`),\n * archived as it is; absent = not weighed. The dispatcher shows it on each task's row.\n */\n task_weights: z\n .record(TrackCode, z.object({ weight: WorkWeight, why: z.string().optional() }).strict())\n .optional(),\n /**\n * What each track builds in this change, for a person reading a list (`work.json` format 5, `tasks[].title` and\n * `summary`): reasoned by the sign-off skill against the rubric (`_labels.md`), in the product's words, naming\n * no ID. Written by `change label`, archived as it is; absent = not titled.\n */\n task_words: z\n .record(TrackCode, z.object({ title: WorkTitle.optional(), summary: WorkSummary.optional() }).strict())\n .optional(),\n /**\n * What a task item is (`tasks[].labels`), by item: reasoned by the sign-off skill where the spec has no word\n * for the item (an acceptance criterion); the export composes the others from the spec. Written by\n * `change label`.\n */\n labels: z.record(z.string(), WorkLabel).optional(),\n /**\n * In a team project: the draft IDs the change and what it creates carried until the sign-off numbered them\n * (draft → final). Written by the CLI at sign-off.\n */\n drafted_as: z.record(z.string(), z.string()).optional(),\n /**\n * The initiative the change belongs to, if any: the envelope (`spec/initiatives/<INI>.md`) that says why it\n * exists. Grouping only: no status, no gate, outside the delta and every fingerprint. Written by\n * `change new --initiative` and `change initiative`, on an archived proposal too.\n */\n initiative: InitiativeId.optional(),\n /** The first 16 hex of the sha256 of the change's `delta.json`, written with it at sign-off, never rewritten. */\n delta: z\n .string()\n .regex(/^[0-9a-f]{16}$/)\n .optional(),\n /**\n * Accepted findings on the archived change itself (`delta-chain`: a merge of parallel sign-offs no delta\n * recorded), each on a decided decision naming the change; history can't be fixed, only accepted.\n */\n accepts: list(AcceptSchema),\n })\n .strict()\n .superRefine((c, ctx) => {\n for (const key of Object.keys(c.base)) {\n if (!ObjectKey.safeParse(key).success) {\n ctx.addIssue({ code: 'custom', path: ['base', key], message: `${key} is not a valid object key` });\n }\n }\n });\n\nexport type Change = z.infer<typeof ChangeSchema>;\n","import { z } from 'zod';\nimport { DecisionId } from './ids.js';\n\n/**\n * How far a spec object has matured: `draft` while it is worked on, `ready` once it is complete and every check\n * passes, `signed_off` on the person's word, which is what lets it be handed off. Implementation is the development\n * teams' business, not the spec's: several teams may build the same spec, so `signed_off` is the last status.\n */\nexport const Status = z.enum(['draft', 'ready', 'signed_off'], {\n error: (iss) => {\n const was: Record<string, string> = {\n refined: 'refined is no longer a status; a complete object is ready',\n approved: 'approved is no longer a status; use signed_off',\n implemented:\n 'implemented is no longer a status (implementation is tracked by the teams, not in the spec)',\n };\n const said = typeof iss.input === 'string' ? was[iss.input] : undefined;\n return said ? `${said}; \\`alterspec status migrate\\` moves a spec to the current statuses` : undefined;\n },\n});\nexport type Status = z.infer<typeof Status>;\n\n/** Permission scope: which data a role may act on. */\nexport const Scope = z.enum(['own', 'team', 'org', 'all']);\nexport type Scope = z.infer<typeof Scope>;\n\n/** Entity operations: Create, Read, Update, Delete, Archive. */\nexport const Op = z.enum(['C', 'R', 'U', 'D', 'A']);\n\nexport const Title = z.string().trim().min(1, { message: 'must not be empty' });\nexport const Version = z.number().int().min(1);\n\n/** Lifecycle state name, e.g. `draft`, `active`, `on_leave`. */\nexport const StateName = z.string().regex(/^[a-z][a-z0-9_]*$/, {\n message: 'must be a lowercase state name (letters, digits, underscore)',\n});\n\n/** A state transition written as `from->to`. */\nexport const TransitionRef = z.string().regex(/^[a-z][a-z0-9_]*->[a-z][a-z0-9_]*$/, {\n message: 'must be written as from->to, e.g. draft->active',\n});\n\nexport const list = <T extends z.ZodType>(item: T) => z.array(item).default([]);\n\n/**\n * A finding of one lint rule on this object that is true of the product and accepted, on a decision that says why\n * (2026-10-27). An accepted finding is reported, not counted: it doesn't stop a status, a change or a handoff.\n */\nexport const AcceptSchema = z\n .object({\n /** The lint rule's name. */\n rule: z.string().trim().min(1),\n /** Part of the finding's message; absent, every finding of the rule on this object is accepted. */\n match: z.string().trim().min(1).optional(),\n /** The decided `DEC-NNN` (kind decision) that records why, naming this object in `affects`. */\n decision: DecisionId,\n reason: z.string().trim().min(1),\n })\n .strict();\n\nexport type Accept = z.infer<typeof AcceptSchema>;\n","import { z } from 'zod';\n\n/**\n * Single source of truth for alterspec ID formats.\n * Module codes are 2–6 uppercase letters (e.g. HR, INV). `GLB` is reserved for the global module.\n */\nconst CODE = '[A-Z]{2,6}';\nconst NAME = '[A-Z0-9]+(?:-[A-Z0-9]+)*';\n/** Channel codes (application.md `channels[].code`): 2–5 uppercase letters, e.g. WEB, MOB. */\nexport const CHANNEL_CODE = '[A-Z]{2,5}';\n/**\n * A draft number: what a numbered ID carries while its change is open in a team project (`team` in the config).\n * `T`, a digit, three more characters (`CHG-T4K9Q`); the digit tells it from a module code. The sign-off replaces\n * it with the next sequential number, so it never reaches the spec itself, the archive or the export.\n */\nexport const DRAFT_NUMBER = 'T\\\\d[A-Z0-9]{3}';\nconst N2 = `(?:\\\\d{2}|${DRAFT_NUMBER})`;\nconst N3 = `(?:\\\\d{3}|${DRAFT_NUMBER})`;\n/** Unanchored sources, for the patterns other files build from an ID. */\nexport const CAPABILITY_ID = `CAP-${CODE}-${N3}`;\nexport const SCREEN_ID = `SCR-${CODE}-${N2}`;\nexport const APP_RULE_ID = `RULE-${N3}`;\nexport const DECISION_ID = `DEC-${N3}`;\n\nexport const ID_PATTERNS = {\n app: '^APP$',\n module: `^MOD-${CODE}$`,\n capability: `^${CAPABILITY_ID}$`,\n screen: `^${SCREEN_ID}$`,\n role: `^ROLE-${NAME}$`,\n persona: `^PER-${NAME}$`,\n entity: `^ENT-${NAME}$`,\n rule: `^RULE-(?:${CODE}-)?${N3}$`,\n flow: `^FLOW-${N3}$`,\n event: `^EVT-${NAME}$`,\n decision: `^${DECISION_ID}$`,\n change: `^CHG-${N3}$`,\n integration: `^INT-${NAME}$`,\n nfr: `^NFR-${N3}$`,\n acceptance: `^${CAPABILITY_ID}-AC-\\\\d{2}$`,\n screenAction: '^A\\\\d{2}$',\n experience: `^UX-${SCREEN_ID}-${CHANNEL_CODE}$`,\n} as const;\n\nexport type IdKind = keyof typeof ID_PATTERNS;\n\nexport const ID_REGEX: Record<IdKind, RegExp> = Object.fromEntries(\n Object.entries(ID_PATTERNS).map(([k, p]) => [k, new RegExp(p)]),\n) as Record<IdKind, RegExp>;\n\nconst idOf = (kind: IdKind, label: string) =>\n z.string().regex(ID_REGEX[kind], { message: `must be a ${label} ID matching ${ID_PATTERNS[kind]}` });\n\nexport const AppId = idOf('app', 'application');\nexport const ModuleId = idOf('module', 'module');\nexport const CapabilityId = idOf('capability', 'capability');\nexport const ScreenId = idOf('screen', 'screen');\nexport const ExperienceId = idOf('experience', 'experience screen');\nexport const RoleId = idOf('role', 'role');\nexport const IntegrationId = idOf('integration', 'integration');\nexport const NfrId = idOf('nfr', 'non-functional requirement');\nexport const PersonaId = idOf('persona', 'persona');\nexport const EntityId = idOf('entity', 'entity');\nexport const RuleId = idOf('rule', 'rule');\nexport const FlowId = idOf('flow', 'flow');\nexport const EventId = idOf('event', 'event');\nexport const DecisionId = idOf('decision', 'decision');\nexport const ChangeId = idOf('change', 'change');\nexport const AcceptanceId = idOf('acceptance', 'acceptance criterion');\nexport const ScreenActionId = idOf('screenAction', 'screen action');\n/**\n * An initiative: the envelope around a group of changes, named by the person (`INI-SUPPLIER-ONBOARDING`), never\n * numbered. It is not a spec object, so its pattern stays out of `ID_PATTERNS`: never an `AnyId`, an object key of\n * a change or an ID a lint rule looks for in prose.\n */\nexport const INITIATIVE_ID = `INI-${NAME}`;\nconst INITIATIVE_REGEX = new RegExp(`^${INITIATIVE_ID}$`);\nexport const InitiativeId = z.string().regex(INITIATIVE_REGEX, {\n message: `must be an initiative ID matching ^${INITIATIVE_ID}$, e.g. INI-ONBOARDING`,\n});\nexport const isInitiativeId = (id: string): boolean => INITIATIVE_REGEX.test(id);\nexport const ChannelCode = z\n .string()\n .regex(new RegExp(`^${CHANNEL_CODE}$`), { message: 'must be 2–5 uppercase letters, e.g. WEB or MOB' });\n\n/** Any spec object ID (used where several kinds are allowed, e.g. change deltas). */\nexport const AnyId = z\n .string()\n .refine(\n (v) => (Object.keys(ID_REGEX) as IdKind[]).some((k) => k !== 'screenAction' && ID_REGEX[k].test(v)),\n { message: 'must be a valid alterspec ID' },\n );\n\n/** Module code from a module ID: MOD-HR → HR. */\nexport const moduleCode = (moduleId: string): string => moduleId.replace(/^MOD-/, '');\n\n/** Module code embedded in a CAP/SCR/module-RULE ID: CAP-HR-004 → HR. */\nexport const codeInId = (id: string): string | undefined => /^(?:CAP|SCR|RULE)-([A-Z]{2,6})-/.exec(id)?.[1];\n\n/** Detect the kind of an ID, or undefined. */\nexport function idKind(id: string): IdKind | undefined {\n return (Object.keys(ID_REGEX) as IdKind[]).find((k) => ID_REGEX[k].test(id));\n}\n\nconst DRAFT = new RegExp(\n `^(?:CHG|FLOW|DEC|NFR|RULE|(?:CAP|SCR|RULE)-${CODE}|UX-SCR-${CODE})-${DRAFT_NUMBER}(?:-|$)`,\n);\n/** Whether an ID (or an ID derived from one: a criterion, an experience screen) carries a draft number. */\nexport const isDraftId = (id: string): boolean => DRAFT.test(id) && idKind(id) !== undefined;\n\nconst NUMBERED = new Set<IdKind>(['capability', 'screen', 'rule', 'flow', 'decision', 'change', 'nfr']);\n/** Whether the CLI numbers this ID (the others are named by the person). */\nexport const isNumberedId = (id: string): boolean => NUMBERED.has(idKind(id) as IdKind);\n","import { DeltaSchema, type Delta, type DeltaEntry } from '../schemas/delta.js';\n\n/**\n * Reading a change's delta, apart from computing it (`delta.ts`): imports only the schema, so the client bundles it\n * to read the deltas of an export.\n */\n\n/** The record's files, next to the archived proposal. */\nexport const DELTA_JSON = 'delta.json';\nexport const DELTA_MD = 'delta.md';\n/** `changes/archive/CHG-NNN/delta.json`, at the root or in a module. */\nexport const ARCHIVED_DELTA = /^(?:modules\\/[^/]+\\/)?changes\\/archive\\/(?<change>[^/]+)\\/delta\\.json$/;\n\nexport function parseDelta(json: string): Delta | undefined {\n try {\n const parsed = DeltaSchema.safeParse(JSON.parse(json));\n return parsed.success ? parsed.data : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** What an entry means for developers, in export terms. */\nexport function exportChange(e: DeltaEntry): string {\n const { before, after } = e.exported;\n if (before && after) return e.change;\n if (after) return 'enters the export';\n if (before) return 'leaves the export';\n return 'not in the export';\n}\n","/**\n * A change's compatibility: what the server keeps accepting from the apps as they are today while the change's other\n * tracks build it, declared in the proposal's \"## Compatibility\" section as the criteria that say so, by ID. Ending\n * it is a change of its own, whose backend task the export puts after every task of the change that kept it.\n * Imports nothing, so the client (which carries no YAML parser) shares the names with the export.\n */\n\n/** The proposal section. */\nexport const COMPATIBILITY_SECTION = 'Compatibility';\n\n/** The section's text when it declares a compatibility: not empty and not \"None.\" (comments already removed). */\nexport function compatibilityText(sectionText: string | undefined): string | undefined {\n const text = sectionText?.trim();\n return text && !/^none\\b/i.test(text) ? text : undefined;\n}\n","/**\n * A change's one-time data change: what the release does once to the records the product already holds, declared in\n * the proposal's \"## One-time data change\" section and carried to the backend as the item `CHG-NNN#data-change`.\n * Imports nothing, so the client (which carries no YAML parser) shares the names with the export that writes them.\n */\n\n/** The proposal section. */\nexport const DATA_CHANGE_SECTION = 'One-time data change';\n\n/** The suffix of the backend item: `CHG-NNN#data-change`. */\nexport const DATA_CHANGE_ITEM = 'data-change';\n\n/** The item regex: the change it belongs to is group 1. */\nexport const DATA_CHANGE_RE = new RegExp(`^(CHG-\\\\d{3,})#${DATA_CHANGE_ITEM}$`);\n\n/** The section's text when it declares a change: not empty and not \"None.\" (comments already removed). */\nexport function dataChangeText(sectionText: string | undefined): string | undefined {\n const text = sectionText?.trim();\n return text && !/^none\\b/i.test(text) ? text : undefined;\n}\n","/**\n * The names an export's files are written under. Imports nothing: alterspec writes the export with them and the\n * client (`client/`) reads it with the same ones, so a change of the layout and the reader land in one commit.\n */\n\n/** The file every export opens with: how to read it, run its mockups and build from it. */\nexport const README = 'README.md';\n/** The export's own record: the alterspec version, the date and every source with its fingerprint. */\nexport const EXPORT_JSON = 'export.json';\n/** The work every signed-off change implies, for the dispatcher. */\nexport const WORK_JSON = 'work.json';\n\n/** Where the shards of an export live: one folder per file, at the file's path without `.md`. */\nexport const SHARDS_DIR = '_shards';\n\n/** A heading or a term as a file name: lower case, ASCII letters and digits, words joined by `-`. */\nexport const slug = (text: string) =>\n text\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n // Letters that don't decompose into a base letter and a mark.\n .replace(/[đłøæœßþ]/g, (c) => ({ đ: 'd', ł: 'l', ø: 'o', æ: 'ae', œ: 'oe', ß: 'ss', þ: 'th' })[c] ?? c)\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 60)\n .replace(/-+$/, '') || 'section';\n\n/** The shard folder of an export file. */\nexport const shardDir = (path: string) => `${SHARDS_DIR}/${path.replace(/\\.md$/, '')}`;\n\n/** The shard of a collection item, named by its key (the ID, or the term's slug in the glossary). */\nexport const itemShardName = (key: string) => `${key.startsWith('term:') ? slug(key.slice(5)) : key}.md`;\nexport const itemShardPath = (path: string, key: string) => `${shardDir(path)}/${itemShardName(key)}`;\n\n/** A document's shards: its front-matter, its introduction, then one per `## ` section, numbered from 02. */\nexport const FRONT_MATTER_SHARD = '00-front-matter.yaml';\nexport const INTRO_SHARD = '01-introduction.md';\nexport const sectionShardName = (index: number, heading: string) =>\n `${String(index + 2).padStart(2, '0')}-${slug(heading)}.md`;\n/** Whether a shard file name is the section with this heading (whatever its number). */\nexport const isSectionShard = (name: string, heading: string) =>\n new RegExp(`^\\\\d{2}-${slug(heading)}\\\\.md$`).test(name);\n","const FRONT_MATTER = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---[ \\t]*(?:\\r?\\n|$)/;\n\nexport interface FrontMatterSplit {\n /** Raw YAML between the `---` lines, or undefined when there is no front-matter. */\n raw: string | undefined;\n body: string;\n /** 1-based line where the body starts. */\n bodyLine: number;\n}\n\n/**\n * Split a markdown file into raw front-matter and body without parsing the YAML. Imports nothing, so the client can\n * bundle it without a YAML parser.\n */\nexport function splitFrontMatter(source: string): FrontMatterSplit {\n const m = FRONT_MATTER.exec(source);\n if (!m) return { raw: undefined, body: source, bodyLine: 1 };\n return {\n raw: m[1] ?? '',\n body: source.slice(m[0].length),\n bodyLine: m[0].split('\\n').length - (m[0].endsWith('\\n') ? 0 : 1),\n };\n}\n","import { slug } from '../export/paths.js';\nimport { splitFrontMatter } from '../lib/frontmatter-split.js';\n\n/**\n * The finer parts of an object a task changes as a whole, for the checklist (`taskItems`) and the brief: an object\n * whose kind has no part of its own on the track (a criterion, a screen action, a contract state) is cut into the\n * parts its own text has, so that one open question about one record kind of a quality requirement doesn't hold the\n * whole requirement out of the task's progress. Imports no YAML parser: the client bundles it.\n */\n\nexport type PartLabel = 'front-matter' | 'section' | 'line';\n\nexport interface ObjectPart {\n label: PartLabel;\n /** The section's heading, the bullet's lead, or `front-matter`. */\n heading: string;\n /** The part's text as the work compares it. */\n text: string;\n}\n\nexport const FRONT_MATTER_PART = 'front-matter';\n\n/**\n * The object an item belongs to: `CAP-X-AC-03` → `CAP-X`, `SCR-X.A01` → `SCR-X`, `UX-SCR-X-BO#state` → `UX-SCR-X-BO`,\n * `NFR-019#sign-in` → `NFR-019`; a file is its own.\n */\nexport const itemObject = (item: string): string =>\n item.startsWith('file:') ? item : item.replace(/-AC-\\d{2}$/, '').replace(/[.#][^.#]*$/, '');\n\n/**\n * An object's text as the work compares it: without the template's comments, the `version:` line the sign-off\n * raises and the fingerprints a contract keeps, which tell a builder nothing.\n */\nexport const forWork = (text: string) =>\n text\n .replace(/^[^\\S\\n]*<!--[\\s\\S]*?-->[^\\S\\n]*\\n/gm, '')\n .replace(/<!--[\\s\\S]*?-->/g, '')\n .replace(/^version:[^\\S\\n]*\\d+[^\\S\\n]*\\n/m, '')\n .replace(/^(?:reviewed|dry|page):[^\\n]*\\n/gm, '');\n\n/**\n * The parts of an object's text, each under the slug the checklist names it by (`<KEY>#<slug>`): a document's\n * front-matter (`front-matter`) and its `## ` sections; a collection item's yaml block (`front-matter`) and its `### `\n * sections, else the top-level bullets of its body, each by its lead (the text before its first colon, dash or full\n * stop, at most eight words). Two parts with one slug are told apart by a number. What is in no part (a title, an\n * introduction) is the object's own.\n */\nexport function objectParts(text: string, kind: 'doc' | 'item'): Map<string, ObjectPart> {\n const out = new Map<string, ObjectPart>();\n const put = (label: PartLabel, heading: string, body: string) => {\n const base = label === 'front-matter' ? FRONT_MATTER_PART : slug(heading);\n let key = base;\n for (let n = 2; out.has(key); n++) key = `${base}-${n}`;\n out.set(key, { label, heading, text: body });\n };\n const t = forWork(text);\n if (kind === 'doc') {\n const { raw, body } = splitFrontMatter(t);\n if (raw) put('front-matter', FRONT_MATTER_PART, raw);\n for (const s of headed(body, '## ').sections) put('section', s.heading, s.text);\n return out;\n }\n const yaml = /^```ya?ml\\n([\\s\\S]*?)\\n```[^\\S\\n]*$/m.exec(t);\n if (yaml) put('front-matter', FRONT_MATTER_PART, yaml[1]!);\n const body = yaml ? t.slice(yaml.index + yaml[0].length) : t.replace(/^## [^\\n]*\\n?/, '');\n const { sections } = headed(body, '### ');\n if (sections.length) for (const s of sections) put('section', s.heading, s.text);\n else for (const b of bullets(body)) put('line', b.heading, b.text);\n return out;\n}\n\n/** The text of an object outside its parts: the title and introduction of a document, an item's heading and prose. */\nexport function restOf(text: string, kind: 'doc' | 'item'): string {\n const t = forWork(text);\n if (kind === 'doc') return headed(splitFrontMatter(t).body, '## ').intro;\n const yaml = /^```ya?ml\\n[\\s\\S]*?\\n```[^\\S\\n]*$/m.exec(t);\n const body = yaml ? t.slice(yaml.index + yaml[0].length) : t;\n const { intro, sections } = headed(body, '### ');\n if (sections.length) return (yaml ? t.slice(0, yaml.index) : '') + intro;\n return (yaml ? t.slice(0, yaml.index) : '') + withoutBullets(body);\n}\n\n/** A text cut at its headings of one level (fenced blocks respected), with what comes before the first. */\nfunction headed(\n text: string,\n marker: string,\n): { intro: string; sections: { heading: string; text: string }[] } {\n const sections: { heading: string; text: string }[] = [];\n let intro = '';\n let fence = false;\n for (const l of text.split('\\n')) {\n if (/^(?:```|~~~)/.test(l)) fence = !fence;\n if (!fence && l.startsWith(marker) && /\\S/.test(l.slice(marker.length))) {\n sections.push({ heading: l.slice(marker.length).trim(), text: '' });\n continue;\n }\n if (sections.length) sections[sections.length - 1]!.text += `${l}\\n`;\n else intro += `${l}\\n`;\n }\n return { intro, sections };\n}\n\nconst BULLET = /^(?:[-*+]|\\d+[.)])\\s+(.*)$/;\n\n/** The top-level bullets of a body (fenced blocks left out), each with its indented continuation lines. */\nfunction bullets(text: string): { heading: string; text: string }[] {\n const out: { heading: string; text: string }[] = [];\n let current: { heading: string; text: string } | undefined;\n let fence = false;\n for (const l of text.split('\\n')) {\n if (/^(?:```|~~~)/.test(l)) {\n fence = !fence;\n current = undefined;\n continue;\n }\n if (fence) continue;\n const m = BULLET.exec(l);\n if (m) {\n current = { heading: lead(m[1]!), text: `${l}\\n` };\n out.push(current);\n } else if (current && /^\\s+\\S/.test(l)) current.text += `${l}\\n`;\n else current = undefined;\n }\n return out;\n}\n\n/** A body without its top-level bullets and their continuation lines. */\nfunction withoutBullets(text: string): string {\n const kept: string[] = [];\n let inBullet = false;\n let fence = false;\n for (const l of text.split('\\n')) {\n if (/^(?:```|~~~)/.test(l)) {\n fence = !fence;\n inBullet = false;\n kept.push(l);\n continue;\n }\n if (fence) {\n kept.push(l);\n continue;\n }\n if (BULLET.test(l)) inBullet = true;\n else if (!(inBullet && /^\\s+\\S/.test(l))) {\n inBullet = false;\n kept.push(l);\n }\n }\n return kept.join('\\n');\n}\n\n/** A bullet's lead: its text before the first colon, dash or full stop, at most eight words, without emphasis. */\nconst lead = (s: string) =>\n s\n .replace(/\\*\\*|__|`/g, '')\n .split(/:\\s|:$|\\s[—–-]\\s|\\.\\s|\\.$/)[0]!\n .trim()\n .split(/\\s+/)\n .slice(0, 8)\n .join(' ');\n","import { existsSync, readFileSync, readdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { DELTA_JSON, parseDelta } from '../changes/delta-record.js';\nimport { splitFrontMatter } from '../lib/frontmatter-split.js';\nimport type { Delta } from '../schemas/delta.js';\nimport { ID_PATTERNS, type IdKind } from '../schemas/ids.js';\nimport { AnyWorkSchema, type AnyWork } from '../schemas/work.js';\nimport { INDEX_FILE, ROOT_DOCS, archiveDir, initiativePath, moduleDir } from '../spec/layout.js';\nimport { EXPORT_JSON, WORK_JSON, isSectionShard, itemShardPath, shardDir } from './paths.js';\n\n/**\n * Reading a finished export, for the client (`client/`), which bundles this module: what the export holds is found\n * through `export.json` and the paths alterspec writes it under, never by searching. Imports no YAML parser and\n * nothing of the spec model.\n */\n\nexport class ExportReadError extends Error {}\n\nexport interface ExportSource {\n id: string;\n status?: string;\n file: string;\n /** The signed-off changes that touched it, oldest first (alterspec 0.20). */\n changed_by?: string[];\n}\n\n/**\n * What the client reads of `_generated/index.json`: the structured facts the Markdown keeps in YAML (a screen's\n * fields, a capability's data in and out, a rule's guards, an entity's attributes), typed only as far as it reads them.\n */\nexport interface ExportIndex {\n screens: {\n id: string;\n title: string;\n roles?: { role: string }[];\n fields: { entity: string; attributes: string[]; mode: string }[];\n }[];\n capabilities: {\n id: string;\n title: string;\n roles?: { role: string; scope?: string }[];\n screens?: string[];\n entities: { entity: string }[];\n rules?: string[];\n inputs?: ({ entity: string; attributes: string[] } | { transient: string })[];\n outputs?: ({ entity: string; attributes: string[] } | { transient: string })[];\n }[];\n rules: { id: string; title: string; entities: string[]; guards?: { entity: string }[] }[];\n entities: {\n id: string;\n title: string;\n attributes: { name: string; kind: string; references?: string }[];\n states?: string[];\n initial_state?: string;\n transitions?: { from: string; to: string; by?: string; at?: string }[];\n }[];\n}\n\nexport interface ExportReader {\n dir: string;\n /** `work.json`, any format (1 to 9). */\n work: AnyWork;\n /** The export's sources by ID. */\n sources: Map<string, ExportSource>;\n /** The file holding an object key: a spec ID, `file:<path>` or `term:<Term>`. */\n fileOf(key: string): string | undefined;\n /** An export file's text, or undefined when the export doesn't hold it. */\n read(path: string): string | undefined;\n has(path: string): boolean;\n /** `changes/archive/<CHG>/proposal.md`, at the root or in a module. */\n proposalPath(change: string): string | undefined;\n /** The change's delta as the export shows it. */\n delta(change: string): Delta | undefined;\n /** The shards of an export file, sorted. */\n shards(file: string): string[];\n /** The shard of a document's `## ` section, found by its heading. */\n sectionShard(file: string, heading: string): string | undefined;\n /** The shard of a collection item. */\n itemShard(file: string, key: string): string | undefined;\n /** `_generated/index.json`, when the export has it. */\n index(): ExportIndex | undefined;\n /** An initiative the export carries (format 8): its title from `work.json`, its prose from its file. */\n initiative(id: string): { id: string; title: string; body: string } | undefined;\n}\n\nfunction readJson(dir: string, name: string): unknown {\n const path = join(dir, name);\n if (!existsSync(path)) throw new ExportReadError(`${dir} is not an alterspec export: it has no ${name}.`);\n try {\n return JSON.parse(readFileSync(path, 'utf8'));\n } catch {\n throw new ExportReadError(`${join(dir, name)} is not valid JSON.`);\n }\n}\n\nexport function readExport(dir: string): ExportReader {\n const exp = readJson(dir, EXPORT_JSON) as { sources?: ExportSource[] };\n const parsed = AnyWorkSchema.safeParse(readJson(dir, WORK_JSON));\n if (!parsed.success)\n throw new ExportReadError(`${join(dir, WORK_JSON)} is not a work.json this client reads.`);\n const sources = new Map((exp.sources ?? []).map((s) => [s.id, s]));\n const has = (path: string) => existsSync(join(dir, path));\n const read = (path: string) => (has(path) ? readFileSync(join(dir, path), 'utf8') : undefined);\n const modules = () =>\n existsSync(join(dir, 'modules')) ? readdirSync(join(dir, 'modules')).map((m) => moduleDir(m)) : [];\n\n const shards = (file: string) => {\n const folder = shardDir(file);\n return has(folder)\n ? readdirSync(join(dir, folder))\n .sort()\n .map((n) => `${folder}/${n}`)\n : [];\n };\n\n let indexCache: ExportIndex | undefined | null = null;\n const index = () => {\n if (indexCache === null) {\n const text = read(INDEX_FILE);\n indexCache = text ? (JSON.parse(text) as ExportIndex) : undefined;\n }\n return indexCache;\n };\n\n const proposalPath = (change: string) =>\n [archiveDir(), ...modules().map((m) => `${m}/changes/archive`)]\n .map((a) => `${a}/${change}/proposal.md`)\n .find(has);\n\n return {\n dir,\n work: parsed.data,\n sources,\n has,\n read,\n fileOf(key) {\n if (key.startsWith('file:')) return key.slice(5);\n if (key.startsWith('term:')) return ROOT_DOCS.glossary;\n return sources.get(key)?.file;\n },\n proposalPath,\n delta(change) {\n const proposal = proposalPath(change);\n const json = proposal && read(proposal.replace(/proposal\\.md$/, DELTA_JSON));\n return json ? parseDelta(json) : undefined;\n },\n shards,\n sectionShard(file, heading) {\n const prefix = `${shardDir(file)}/`;\n return shards(file).find((p) => isSectionShard(p.slice(prefix.length), heading));\n },\n itemShard(file, key) {\n const path = itemShardPath(file, key);\n return has(path) ? path : undefined;\n },\n index,\n initiative(id) {\n const work = parsed.data;\n const title = 'initiatives' in work ? work.initiatives?.find((i) => i.id === id)?.title : undefined;\n const text = read(initiativePath(id));\n if (!title || text === undefined) return undefined;\n return { id, title, body: splitFrontMatter(text).body };\n },\n };\n}\n\n/** The IDs of the given kinds a text names, in order of first appearance. */\nexport function idsIn(text: string, kinds: IdKind[]): string[] {\n const pattern = new RegExp(\n kinds.map((k) => `(?:${ID_PATTERNS[k].replace(/^\\^|\\$$/g, '')})`).join('|'),\n 'g',\n );\n const out: string[] = [];\n for (const m of text.matchAll(new RegExp(`(?<![A-Z0-9-])(?:${pattern.source})(?![A-Z0-9-])`, 'g')))\n if (!out.includes(m[0])) out.push(m[0]);\n return out;\n}\n\n/** The raw front-matter of an export document, unparsed. */\nexport const frontMatterOf = (text: string) => splitFrontMatter(text).raw ?? '';\n","import { codeInId, SCREEN_ID } from '../schemas/ids.js';\nimport type { SpecFile } from './files.js';\n\n/**\n * Where everything lives under spec/. The spec folder is the application: its documents sit at the root, shared\n * entities in `entities/`, flows in `flows/`, changes that touch several modules in `changes/`. A module folder\n * holds its own entities, rules, changes, capabilities and screens; each screen is a folder with the business\n * document and one experience contract per channel. IDs are identity, folders are placement: nothing is renamed\n * when it moves, and placement is the CLI's, never the person's (`alterspec place`).\n */\n\n/** The application's documents at the spec root, by file type. */\nexport const ROOT_DOCS = {\n application: 'application.md',\n 'personas-roles': 'personas-roles.md',\n glossary: 'glossary.md',\n rules: 'rules.md',\n events: 'events.md',\n decisions: 'decisions.md',\n integrations: 'integrations.md',\n nfr: 'nfr.md',\n} as const;\nexport type RootDoc = keyof typeof ROOT_DOCS;\n\nexport const APPLICATION = ROOT_DOCS.application;\nexport const MODULES_DIR = 'modules';\nexport const CHANGES_DIR = 'changes';\nexport const ENTITIES_DIR = 'entities';\nexport const FLOWS_DIR = 'flows';\n/** Initiatives: prose envelopes around groups of changes, outside the spec model (the loader ignores them). */\nexport const INITIATIVES_DIR = 'initiatives';\n\n/** `HR` or `MOD-HR` → `modules/hr`. */\nexport const moduleDir = (code: string) => `${MODULES_DIR}/${code.replace(/^MOD-/, '').toLowerCase()}`;\nexport const moduleDoc = (code: string) => `${moduleDir(code)}/module.md`;\nexport const moduleRulesPath = (code: string) => `${moduleDir(code)}/rules.md`;\n\n/** The module folder an ID with a module code belongs to (CAP, SCR, RULE-<MOD>), or undefined. */\nexport const moduleDirOf = (id: string): string | undefined => {\n const code = codeInId(id);\n return code ? moduleDir(code) : undefined;\n};\n\n/** The module (lower-case folder name) a path sits in, or undefined at the root. */\nexport const moduleOfPath = (path: string): string | undefined =>\n new RegExp(`^${MODULES_DIR}/([^/]+)/`).exec(path)?.[1];\n\nexport const capabilityPath = (id: string) => `${moduleDirOf(id)}/capabilities/${id}.md`;\n/** An entity at the root, or inside the module (lower-case folder name or code) that alone uses it. */\nexport const entityPath = (id: string, mod?: string) =>\n mod ? `${moduleDir(mod)}/${ENTITIES_DIR}/${id}.md` : `${ENTITIES_DIR}/${id}.md`;\nexport const flowPath = (id: string) => `${FLOWS_DIR}/${id}.md`;\nexport const initiativePath = (id: string) => `${INITIATIVES_DIR}/${id}.md`;\n\n/** A screen is a folder: its document, its experience contracts (one per channel) and its reverse-spec screenshots. */\nexport const screenDir = (screenId: string) => `${moduleDirOf(screenId)}/screens/${screenId}`;\nexport const screenDoc = (screenId: string) => `${screenDir(screenId)}/screen.md`;\nexport const contractPath = (screenId: string, code: string) =>\n `${screenDir(screenId)}/experience/${code.toLowerCase()}.md`;\nexport const screenshotsDir = (screenId: string) => `${screenDir(screenId)}/mockups`;\n\n/** A channel's experience layer: design system, patterns and its mockup app, one page per screen. */\nexport const EXPERIENCE_DIR = 'experience';\nexport const surfaceDir = (code: string) => `${EXPERIENCE_DIR}/${code.toLowerCase()}`;\nexport const mockupPath = (code: string, screenId: string) => `${surfaceDir(code)}/mockups/${screenId}.html`;\nexport const patternsPath = (code: string) => `${surfaceDir(code)}/patterns.md`;\nexport const designSystemPath = (code: string) => `${surfaceDir(code)}/design-system.md`;\n\n/** The operations catalogue, generated while a capability is exposed on an API channel. */\nexport const OPERATIONS_FILE = '_generated/operations.md';\n/** The spec's objects as JSON (`index(model)` in src/views/render.ts); the export carries it, the client reads it. */\nexport const INDEX_FILE = '_generated/index.json';\n/** Where the rule matrix is written, relative to spec/; an export carries it too. */\nexport const RULE_MATRIX_FILE = '_generated/rule-matrix.md';\n\nconst CONTRACT = new RegExp(\n `^modules/[^/]+/screens/(?<screen>${SCREEN_ID})/experience/(?<code>[a-z]{2,5})\\\\.md$`,\n);\n/** `modules/prc/screens/SCR-PRC-01/experience/bo.md` → { screen: SCR-PRC-01, channel: BO }. */\nexport function parseContractPath(path: string): { screen: string; channel: string } | undefined {\n const m = CONTRACT.exec(path);\n return m ? { screen: m.groups!.screen!, channel: m.groups!.code!.toUpperCase() } : undefined;\n}\n\n/** `changes` at the root, or a module's. */\nexport const changesDir = (mod?: string) => (mod ? `${moduleDir(mod)}/${CHANGES_DIR}` : CHANGES_DIR);\nexport const changeDirOf = (id: string, mod?: string) => `${changesDir(mod)}/${id}`;\nexport const archiveDir = (mod?: string) => `${changesDir(mod)}/archive`;\n\nconst CHANGE_PREFIX = String.raw`^(?:${MODULES_DIR}\\/[^/]+\\/)?${CHANGES_DIR}\\/`;\nconst CHANGE_FILE = new RegExp(CHANGE_PREFIX);\nconst ARCHIVED_FILE = new RegExp(`${CHANGE_PREFIX}archive\\\\/`);\nconst OVERLAY_FILE = new RegExp(`${CHANGE_PREFIX}[^/]+\\\\/spec\\\\/`);\nconst WORK_FILE = new RegExp(`${CHANGE_PREFIX}[^/]+\\\\/(?:impact|groom(?:-[^/]+)?)\\\\.md$`);\nexport const PROPOSAL_FILE = new RegExp(\n String.raw`^(?:${MODULES_DIR}\\/(?<mod>[^/]+)\\/)?${CHANGES_DIR}\\/(?<change>[^/]+)\\/proposal\\.md$`,\n);\n/** The proposal of an archived change, at the root or in a module. */\nexport const ARCHIVED_PROPOSAL = new RegExp(\n String.raw`^(?:${MODULES_DIR}\\/(?<mod>[^/]+)\\/)?${CHANGES_DIR}\\/archive\\/(?<change>[^/]+)\\/proposal\\.md$`,\n);\n\n/** Anything under a changes folder, at the root or in a module. */\nexport const isChangeFile = (path: string) => CHANGE_FILE.test(path);\nexport const isArchivedFile = (path: string) => ARCHIVED_FILE.test(path);\n/** A file of a change's overlay spec (`changes/CHG-NNN/spec/…`). */\nexport const isOverlayFile = (path: string) => OVERLAY_FILE.test(path);\n/** A change's working documents next to its proposal: impact and grooming. */\nexport const isChangeWorkFile = (path: string) => WORK_FILE.test(path);\n/** The overlay spec root of an overlay file (`changes/CHG-NNN/spec/`), with the trailing slash. */\nexport const overlayRootOf = (path: string): string | undefined =>\n new RegExp(`(${CHANGE_PREFIX}[^/]+\\\\/spec\\\\/)`).exec(path)?.[1];\n\n/**\n * The layout before 0.12 (`application/`, flat screen files, contracts under `experience/<ch>/screens/`).\n * Archived changes keep whatever layout they were written in and never count.\n */\nexport const LEGACY_APPLICATION = 'application/application.md';\nconst LEGACY: RegExp[] = [\n /^application\\//,\n /^modules\\/[^/]+\\/screens\\/SCR-[^/]+\\.md$/,\n /^experience\\/[a-z]{2,5}\\/screens\\/UX-[^/]+\\.md$/,\n];\nexport const isLegacyPath = (path: string) => !isChangeFile(path) && LEGACY.some((re) => re.test(path));\nexport const legacyPaths = (files: readonly SpecFile[]) => files.map((f) => f.path).filter(isLegacyPath);\n/** Which layout a set of spec files is in: 1 before 0.12, 2 now. */\nexport const layoutOf = (files: readonly SpecFile[]): 1 | 2 => (legacyPaths(files).length ? 1 : 2);\n\nexport class LayoutError extends Error {}\n\nexport const LAYOUT_HINT =\n 'run `alterspec migrate layout` to move it to the current layout (a spec started before 0.10 needs `alterspec experience migrate` and `alterspec status migrate` first)';\n\n/** Refuse to work on a spec in the layout before 0.12. */\nexport function assertLayout(files: readonly SpecFile[], specDir = 'spec'): void {\n const legacy = legacyPaths(files);\n if (!legacy.length) return;\n throw new LayoutError(\n `${specDir}/ is in the layout of alterspec 0.11 or earlier (${specDir}/${legacy[0]} and ${legacy.length - 1} more); ${LAYOUT_HINT}`,\n );\n}\n","/** One line of a line diff: kept, removed or added. */\nexport interface DiffLine {\n op: ' ' | '-' | '+';\n text: string;\n}\n\nconst linesOf = (text: string) => (text === '' ? [] : text.replace(/\\n$/, '').split('\\n'));\n\n/** The shortest line diff from `a` to `b` (Myers). */\nexport function diffLines(a: string, b: string): DiffLine[] {\n const x = linesOf(a);\n const y = linesOf(b);\n const n = x.length;\n const m = y.length;\n const max = n + m;\n const v = new Map<number, number>([[1, 0]]);\n const trace: Map<number, number>[] = [];\n outer: for (let d = 0; d <= max; d++) {\n trace.push(new Map(v));\n for (let k = -d; k <= d; k += 2) {\n let i =\n k === -d || (k !== d && (v.get(k - 1) ?? -1) < (v.get(k + 1) ?? -1))\n ? (v.get(k + 1) ?? 0)\n : (v.get(k - 1) ?? 0) + 1;\n let j = i - k;\n while (i < n && j < m && x[i] === y[j]) {\n i++;\n j++;\n }\n v.set(k, i);\n if (i >= n && j >= m) break outer;\n }\n }\n const out: DiffLine[] = [];\n let i = n;\n let j = m;\n for (let d = trace.length - 1; d >= 0; d--) {\n const vd = trace[d]!;\n const k = i - j;\n const down = k === -d || (k !== d && (vd.get(k - 1) ?? -1) < (vd.get(k + 1) ?? -1));\n const pk = down ? k + 1 : k - 1;\n const pi = vd.get(pk) ?? 0;\n const pj = pi - pk;\n while (i > pi && j > pj) {\n out.push({ op: ' ', text: x[--i]! });\n j--;\n }\n if (d > 0) {\n if (down) out.push({ op: '+', text: y[--j]! });\n else out.push({ op: '-', text: x[--i]! });\n }\n }\n return out.reverse();\n}\n\n/** The diff as unified hunks with `context` lines around each change; empty when nothing changed. */\nexport function unifiedDiff(a: string, b: string, context = 3): string {\n const lines = diffLines(a, b);\n const changed = lines.map((l, i) => (l.op === ' ' ? -1 : i)).filter((i) => i >= 0);\n if (!changed.length) return '';\n const hunks: [number, number][] = [];\n for (const i of changed) {\n const from = Math.max(0, i - context);\n const to = Math.min(lines.length, i + context + 1);\n const last = hunks[hunks.length - 1];\n if (last && from <= last[1]) last[1] = to;\n else hunks.push([from, to]);\n }\n const out: string[] = [];\n for (const [from, to] of hunks) {\n let ai = 1;\n let bi = 1;\n for (const l of lines.slice(0, from)) {\n if (l.op !== '+') ai++;\n if (l.op !== '-') bi++;\n }\n const body = lines.slice(from, to);\n const aLen = body.filter((l) => l.op !== '+').length;\n const bLen = body.filter((l) => l.op !== '-').length;\n out.push(`@@ -${aLen ? ai : ai - 1},${aLen} +${bLen ? bi : bi - 1},${bLen} @@`);\n for (const l of body) out.push(`${l.op}${l.text}`);\n }\n return out.join('\\n');\n}\n","/** Replace HTML comments with blanks, keeping line breaks so line numbers stay valid. */\nexport const blankComments = (text: string) =>\n text.replace(/<!--[\\s\\S]*?-->/g, (c) => c.replace(/[^\\n]/g, ' '));\n","import { blankComments } from '../lib/comments.js';\n\n/*\n * Acceptance criteria as plain text: no YAML parser and nothing of the spec model, so the client (which bundles\n * this module) reads criteria exactly as alterspec does.\n */\n\n/** The two outcomes of one criterion, for telling which track builds what. */\nexport interface CriterionParts {\n /**\n * The criterion as the backend reads it: every line but `Shown` and the `And` lines that continue it; empty for a\n * criterion that says only what is shown (no `Then`), which is no backend's work.\n */\n system: string;\n /** The criterion as a screen reads it: its `Given` and `When` (and their `And`s), and its `Shown` lines. */\n shown: string;\n hasThen: boolean;\n hasShown: boolean;\n}\n\nconst PART = /^\\s*[-*]?\\s*\\*\\*(Given|When|Then|Shown|And|Covers):?\\*\\*/i;\n\n/**\n * One criterion's text (its `### ` chunk, heading included or not) split into what the system guarantees and what\n * the screen shows. A criterion without `Shown` is wholly the system's. String work only: the client uses it too.\n */\nexport function criterionParts(chunk: string): CriterionParts {\n const system: string[] = [];\n const shown: string[] = [];\n let label: string | undefined;\n let inShown = false;\n let hasThen = false;\n for (const raw of blankComments(chunk).split('\\n')) {\n const line = raw.trimEnd();\n if (!line.trim() || /^### /.test(line)) continue;\n const m = PART.exec(line);\n // A label with nothing after it (a template's empty line) says nothing.\n if (m && !line.slice(m[0].length).replace(/^:/, '').trim()) continue;\n if (m) {\n label = m[1]!.toLowerCase();\n if (label === 'shown') inShown = true;\n else if (label !== 'and') inShown = false;\n if (label === 'then') hasThen = true;\n }\n const text = line.trim();\n if (inShown) shown.push(text);\n else {\n system.push(text);\n if (label === 'given' || label === 'when' || (label === 'and' && !hasThen)) shown.push(text);\n }\n }\n const hasShown = shown.some((l) => PART.exec(l)?.[1]?.toLowerCase() === 'shown');\n return {\n system: hasShown && !hasThen ? '' : system.join('\\n'),\n shown: hasShown ? shown.join('\\n') : '',\n hasThen,\n hasShown,\n };\n}\n\n/**\n * A capability body cut at its criteria: each `### ` chunk of `## Acceptance criteria` by its ID, and the body\n * without them. String work only, like `criterionParts`.\n */\nexport function splitCriteria(body: string): { criteria: Map<string, string>; rest: string } {\n const chunks: string[][] = [];\n const rest: string[] = [];\n let inSection = false;\n let current: string[] | undefined;\n for (const line of blankComments(body).split('\\n')) {\n if (/^## /.test(line)) {\n inSection = /^## acceptance criteria\\s*$/i.test(line.trim());\n current = undefined;\n } else if (inSection && /^### \\S/.test(line)) chunks.push((current = []));\n (current ?? rest).push(line);\n }\n const criteria = new Map<string, string>();\n for (const chunk of chunks) {\n const id = chunk[0]!.slice(4).trim().split(/\\s+/)[0]!;\n // The first of two criteria with one ID counts, as everywhere else.\n if (!criteria.has(id)) criteria.set(id, chunk.join('\\n').trim());\n }\n return { criteria, rest: rest.join('\\n') };\n}\n","/**\n * The `## ` sections of a markdown body. Imports nothing, so the client can bundle it (`src/spec/sections.ts`, which\n * reads templates and YAML, re-exports it).\n */\nexport interface Section {\n heading: string;\n /** 1-based line of the heading, relative to the text parsed. */\n line: number;\n text: string;\n}\n\n/** `## ` sections of a markdown body (fenced blocks respected). */\nexport function sections(body: string): Section[] {\n const lines = body.split('\\n');\n const out: Section[] = [];\n let inFence = false;\n lines.forEach((l, i) => {\n if (l.startsWith('```')) inFence = !inFence;\n if (!inFence && /^## \\S/.test(l)) out.push({ heading: l.slice(3).trim(), line: i + 1, text: '' });\n else if (out.length) out[out.length - 1]!.text += l + '\\n';\n });\n return out;\n}\n","import { splitFrontMatter } from '../lib/frontmatter-split.js';\nimport { sections } from '../lib/sections-split.js';\nimport { FRONT_MATTER_SHARD, INTRO_SHARD, sectionShardName } from './paths.js';\n\n/**\n * A document cut into the parts its shards hold: the front-matter, the introduction (the text before the first\n * `## `, the title included), then each `## ` section, in the file's order. Imports no YAML parser: alterspec\n * writes an export's shards from it (`shards.ts` adds the source comments) and the client (`client/`) cuts the text\n * a change saw with it, so both name and cut a document the same way.\n */\nexport interface DocumentPart {\n /** The shard's file name: `00-front-matter.yaml`, `01-introduction.md`, `NN-<heading>.md` from 02. */\n name: string;\n kind: 'front-matter' | 'introduction' | 'section';\n /** A section's `## ` heading. */\n heading?: string;\n /** The part's text as its shard holds it under the source comment. */\n text: string;\n}\n\n/** A part with no text is left out; the numbers of the others don't move. */\nexport function cutDocument(content: string): DocumentPart[] {\n const out: DocumentPart[] = [];\n const { raw, body } = splitFrontMatter(content);\n if (raw !== undefined && raw.trim())\n out.push({ name: FRONT_MATTER_SHARD, kind: 'front-matter', text: `${raw.trimEnd()}\\n` });\n const parts = sections(body);\n const lines = body.split('\\n');\n const intro = lines\n .slice(0, parts.length ? parts[0]!.line - 1 : lines.length)\n .join('\\n')\n .trim();\n if (intro) out.push({ name: INTRO_SHARD, kind: 'introduction', text: `${intro}\\n` });\n parts.forEach((s, i) => {\n const text = s.text.trim();\n out.push({\n name: sectionShardName(i, s.heading),\n kind: 'section',\n heading: s.heading,\n text: `## ${s.heading}\\n${text ? `\\n${text}\\n` : ''}`,\n });\n });\n return out;\n}\n","import { cutDocument } from '../../src/export/cut.js';\nimport { SHARDS_DIR, isSectionShard, itemShardPath, shardDir } from '../../src/export/paths.js';\nimport type { ExportReader } from '../../src/export/read.js';\nimport type { DeltaEntry } from '../../src/schemas/delta.js';\n\n/**\n * The spec as a change saw it at its sign-off, from the export as it is now (client 0.19.0). An export holds the\n * current text of every object, and each signed-off change's delta holds the full text of what it touched before\n * and after; so the text an earlier change stood on is in the deltas: the `after` of the last change that touched\n * the object by then. A task's brief is read through `pinnedReader`, and what later changes did to the objects it\n * names is listed apart, as their tasks' work. No git and no copy of the export: only the deltas are read.\n */\n\n/** A change that touched an object after the one a brief is of, with its entry in that change's delta. */\nexport interface Later {\n change: string;\n entry: DeltaEntry;\n}\n\nexport interface Seen {\n /**\n * The object's text as the change saw it. Undefined when nothing touched it since (the export's text is what the\n * change saw), when the export did not hold it then (`absent`), or for a binary file.\n */\n text?: string;\n /** The later changes that touched it, in the order they did; empty when nothing moved. */\n later: Later[];\n /**\n * The export did not hold the object when the change was signed off: a later change brought it in (it was\n * signed off later). The export never held its earlier text, so a brief shows it as the export holds it now.\n */\n absent?: boolean;\n}\n\ninterface Memo {\n ancestors: Map<string, Set<string>>;\n entries: Map<string, Map<string, DeltaEntry>>;\n history: Map<string, Later[]>;\n}\n\nconst memos = new WeakMap<ExportReader, Memo>();\nconst memoOf = (x: ExportReader): Memo => {\n let m = memos.get(x);\n if (!m) memos.set(x, (m = { ancestors: new Map(), entries: new Map(), history: new Map() }));\n return m;\n};\n\n/** Every change a change builds on, through `depends_on` (the lineage the sign-offs froze). */\nexport function ancestors(x: ExportReader, change: string): Set<string> {\n const memo = memoOf(x).ancestors;\n const known = memo.get(change);\n if (known) return known;\n const out = new Set<string>();\n memo.set(change, out);\n for (const d of x.work.changes.find((c) => c.id === change)?.depends_on ?? []) {\n out.add(d);\n for (const a of ancestors(x, d)) out.add(a);\n }\n return out;\n}\n\nfunction entriesOf(x: ExportReader, change: string): Map<string, DeltaEntry> {\n const memo = memoOf(x).entries;\n let entries = memo.get(change);\n if (!entries) memo.set(change, (entries = new Map(x.delta(change)?.objects.map((e) => [e.key, e]))));\n return entries;\n}\n\n/**\n * The changes that touched an object, each with its entry, in the order they did: an entry follows the one whose\n * fingerprint after is its fingerprint before (sign-offs of one day are not in ID order, and the change map sorts\n * a day by ID), and where no link says, the change map's order.\n */\nexport function history(x: ExportReader, key: string): Later[] {\n const memo = memoOf(x).history;\n const known = memo.get(key);\n if (known) return known;\n const order = x.work.changes.map((c) => c.id);\n // An object the export no longer holds has no source to name its changes: every delta is asked.\n const touched = x.sources.get(key)?.changed_by ?? order;\n const rest = order\n .filter((c) => touched.includes(c))\n .flatMap((change): Later[] => {\n const entry = entriesOf(x, change).get(key);\n return entry ? [{ change, entry }] : [];\n });\n const out: Later[] = [];\n while (rest.length) {\n const last = out[out.length - 1]?.entry.fingerprint.after;\n const follows = last === undefined ? -1 : rest.findIndex((e) => e.entry.fingerprint.before === last);\n // Nothing follows: the earliest entry no other waiting entry leads to (the head of what is left).\n const head = rest.findIndex(\n (e) =>\n e.entry.fingerprint.before === undefined ||\n !rest.some((o) => o !== e && o.entry.fingerprint.after === e.entry.fingerprint.before),\n );\n out.push(...rest.splice(follows >= 0 ? follows : Math.max(head, 0), 1));\n }\n memo.set(key, out);\n return out;\n}\n\nconst after = (e: DeltaEntry) => (e.exported.after ? e.after : undefined);\nconst before = (e: DeltaEntry) => (e.exported.before ? e.before : undefined);\n\n/**\n * What a change saw of an object, and what later changes did to it. The change's own entry when it touched the\n * object; else the last entry whose change it builds on (`depends_on`, transitively) or that was signed off on an\n * earlier day and doesn't build on it. A change of the same day outside the lineage counts as later: the brief\n * then shows less, never a sentence that wasn't there.\n */\nexport function seen(x: ExportReader, change: string, key: string): Seen {\n // Every change that touched it is this one or one it builds on: nothing is later, and no delta need be read.\n const touched = x.sources.get(key)?.changed_by;\n if (touched) {\n const built = ancestors(x, change);\n if (touched.every((c) => c === change || built.has(c))) return { later: [] };\n }\n const h = history(x, key);\n if (!h.length) return { later: [] };\n let at = h.findIndex((e) => e.change === change);\n if (at < 0) {\n const built = ancestors(x, change);\n const day = (id: string) => x.work.changes.find((c) => c.id === id)?.signed_off;\n const mine = day(change);\n h.forEach((e, i) => {\n const theirs = day(e.change);\n if (built.has(e.change)) at = i;\n else if (mine && theirs && theirs < mine && !ancestors(x, e.change).has(change)) at = i;\n });\n }\n const later = h.slice(at + 1);\n if (!later.length) return { later };\n const text = at >= 0 ? after(h[at]!.entry) : before(h[0]!.entry);\n if (text !== undefined) return { text, later };\n // No text on that side: a binary file, or an object the export did not hold then.\n const held = at >= 0 ? h[at]!.entry.exported.after : h[0]!.entry.exported.before;\n if (held) return { later };\n // What touched it before it was signed off never reached the export: the change that brought it in comes first.\n const entered = later.findIndex((l) => l.entry.exported.after);\n return { later: later.slice(Math.max(entered, 0)), absent: true };\n}\n\nexport interface PinnedReader extends ExportReader {\n /** The reader of the export as it is now. */\n current: ExportReader;\n /** What the change saw of an object and what later changes did to it. */\n seen(key: string): Seen;\n /** The object an export path belongs to: its file, a shard of it, or its shard folder. */\n keyOf(path: string): string | undefined;\n /** Whether the path (a file, a shard, a shard folder) reads differently for this change than in the export now. */\n isPinned(path: string): boolean;\n /** The files that hold an object as the change saw it, by export path; empty when nothing moved since. */\n pinnedFiles(key: string): Map<string, string>;\n}\n\n/**\n * The export read as `change` saw it: an object a later change touched reads as it was at the change's sign-off\n * (its file, and its shards cut the way the export cuts them); everything else, an object a later change brought\n * into the export included, is the export's own file. Facts the export derives (`index()`, the generated views)\n * stay current.\n */\nexport function pinnedReader(x: ExportReader, change: string): PinnedReader {\n const byFile = new Map<string, string[]>();\n for (const s of x.sources.values()) byFile.set(s.file, [...(byFile.get(s.file) ?? []), s.id]);\n const isItem = (file: string, id: string) => x.has(itemShardPath(file, id));\n\n const keys = new Map<string, string | undefined>();\n const keyOf = (path: string): string | undefined => {\n if (keys.has(path)) return keys.get(path);\n let key: string | undefined;\n if (path.startsWith(`${SHARDS_DIR}/`)) {\n const inner = path.slice(SHARDS_DIR.length + 1);\n // A shard folder, an item's shard in its collection's folder, or a section shard in its document's.\n const folder = `${inner}.md`;\n const parent = `${inner.replace(/\\/[^/]+$/, '')}.md`;\n key =\n byFile.get(folder)?.find((id) => !isItem(folder, id)) ??\n byFile.get(parent)?.find((id) => itemShardPath(parent, id) === path) ??\n byFile.get(parent)?.find((id) => !isItem(parent, id));\n } else {\n key = byFile.get(path)?.find((id) => !isItem(path, id));\n }\n keys.set(path, key);\n return key;\n };\n\n const seenOf = new Map<string, Seen>();\n const see = (key: string) => {\n let s = seenOf.get(key);\n if (!s) seenOf.set(key, (s = seen(x, change, key)));\n return s;\n };\n\n const files = new Map<string, Map<string, string>>();\n const none = new Map<string, string>();\n const pinnedFiles = (key: string): Map<string, string> => {\n const known = files.get(key);\n if (known) return known;\n const s = see(key);\n const file = x.fileOf(key);\n let out = none;\n if (s.text !== undefined && file) {\n out = new Map();\n if (isItem(file, key)) out.set(itemShardPath(file, key), `${s.text.trim()}\\n`);\n else {\n out.set(file, s.text);\n if (file.endsWith('.md'))\n for (const part of cutDocument(s.text)) out.set(`${shardDir(file)}/${part.name}`, part.text);\n }\n }\n files.set(key, out);\n return out;\n };\n\n /** How a path reads for the change: its pinned text, `null` when the change saw nothing there, undefined when the export's own file is what it saw. */\n const view = (path: string): string | null | undefined => {\n const key = keyOf(path);\n if (!key) return undefined;\n const pinned = pinnedFiles(key);\n if (!pinned.size) return undefined;\n return pinned.get(path) ?? null;\n };\n\n const shards = (file: string): string[] => {\n const key = keyOf(file);\n const pinned = key ? pinnedFiles(key) : none;\n return pinned.size\n ? [...pinned.keys()].filter((p) => p.startsWith(`${shardDir(file)}/`)).sort()\n : x.shards(file);\n };\n\n return {\n ...x,\n current: x,\n seen: see,\n keyOf,\n pinnedFiles,\n isPinned(path) {\n const key = keyOf(path);\n return !!key && pinnedFiles(key).size > 0;\n },\n read(path) {\n const v = view(path);\n return v === undefined ? x.read(path) : (v ?? undefined);\n },\n has(path) {\n const v = view(path);\n return v === undefined ? x.has(path) : v !== null;\n },\n shards,\n sectionShard(file, heading) {\n const prefix = `${shardDir(file)}/`;\n return shards(file).find((p) => isSectionShard(p.slice(prefix.length), heading));\n },\n itemShard(file, key) {\n const path = itemShardPath(file, key);\n const v = view(path);\n return (v === undefined ? x.has(path) : v !== null) ? path : undefined;\n },\n };\n}\n","import { z } from 'zod';\nimport type { ExportReader } from '../../src/export/read.js';\nimport type { Session } from './auth.js';\nimport { callTool } from './mcp.js';\n\n/**\n * Questions from the build (spec 8.3): what an answer may cite, and the questions the dispatcher keeps. Asking and\n * answering are the dispatcher's tools, called by the agent; the CLI checks cites and reads the answers back.\n */\n\nconst AnswerSchema = z.object({\n developer: z.string(),\n at: z.string(),\n text: z.string(),\n verdict: z.enum(['confirmed', 'corrected']).nullish(),\n change: z.string().nullish(),\n});\n\nconst QuestionSchema = z.object({\n id: z.string(),\n task: z.string().nullish(),\n item: z.string().nullish(),\n developer: z.string(),\n at: z.string(),\n question: z.string(),\n outcome: z.enum(['spec', 'assumed', 'open', 'proposal']),\n status: z.enum(['open', 'answered']),\n cites: z.array(z.string()).default([]),\n answer: z.string().nullish(),\n assumption: z.string().nullish(),\n corrected: z.boolean().optional(),\n /** The product side's mark: the spec now says what the answer says. */\n reconciled: z.boolean().optional(),\n answers: z.array(AnswerSchema).default([]),\n /** What an open question waits for (wave contract 2.4). */\n waits_for: z.enum(['contradiction', 'business']).nullish(),\n /** Why an open question carries no reading of the spec. */\n no_reading: z.string().nullish(),\n /** The question this one was joined into. */\n merged_into: z.string().nullish(),\n /** The `REWORK-<n>` item a corrected assumption opened on the asking task. */\n rework: z.string().nullish(),\n});\n\nexport type Question = z.infer<typeof QuestionSchema>;\n\n/** One question a task carries into the spec, built on the task's track already or not (spec 8.4). */\nconst TaskAnswerSchema = z.object({\n question: z.string(),\n built: z.boolean(),\n /** The asking change's task on this track, when it has one. */\n task: z.string().nullish(),\n done_at: z.string().nullish(),\n answer_at: z.string().nullish(),\n /** Why not built: no_task | not_done | answered_after_done | no_task_asked. */\n why: z.string().nullish(),\n});\n\nexport type TaskAnswer = z.infer<typeof TaskAnswerSchema>;\n\n/** The `answers` of the dispatcher's `task`; undefined when it sends none or something this client doesn't read. */\nexport function parseAnswers(raw: unknown): TaskAnswer[] | undefined {\n const parsed = z.array(TaskAnswerSchema).safeParse(raw);\n return parsed.success && parsed.data.length ? parsed.data : undefined;\n}\n\nexport class QuestionsError extends Error {}\n\n/** A criterion, a screen action or a contract state: cited by the ID of the object that holds it. */\nconst PART = /^(.+?)(?:-AC-\\d+|\\.A\\d+|#[\\w-]+)$/;\n\n/**\n * The references the export doesn't hold. A reference is an ID of the export's sources (or a criterion, action or\n * state of one, when its file names it) or a path in the export, shards included.\n */\nexport function missingCites(x: ExportReader, refs: string[]): string[] {\n const held = (ref: string) => {\n if (x.sources.has(ref)) return true;\n const owner = PART.exec(ref)?.[1];\n if (owner && x.sources.has(owner)) {\n if (ref.includes('#')) return true;\n const text = x.read(x.fileOf(owner) ?? '') ?? '';\n const action = /\\.(A\\d+)$/.exec(ref)?.[1];\n return action ? new RegExp(`\\\\bid: ${action}\\\\b`).test(text) : text.includes(ref);\n }\n return /[/.]/.test(ref) && !ref.includes('..') && !ref.startsWith('/') && x.has(ref);\n };\n return refs.filter((r) => !held(r));\n}\n\nexport interface QuestionsFilter {\n /** Questions by number (`Q-<n>`), whole, wherever they were asked. */\n ids?: string[];\n task?: string;\n /** Everyone's questions naming these IDs, to find one asked before. */\n about?: string[];\n open?: boolean;\n}\n\n/** The task's questions, the ones naming some IDs, or without either the developer's own (which marks them as listed). */\nexport async function listQuestions(session: Session, filter: QuestionsFilter = {}): Promise<Question[]> {\n const answer = await callTool(session, 'questions', {\n ...(filter.ids?.length\n ? { ids: filter.ids }\n : filter.task\n ? { task: filter.task }\n : filter.about\n ? { about: filter.about }\n : { mine: true }),\n ...(filter.open ? { status: 'open' } : {}),\n });\n const parsed = z.array(QuestionSchema).safeParse(answer.questions ?? []);\n if (!parsed.success)\n throw new QuestionsError('The dispatcher’s questions are not in a form this client reads.');\n return parsed.data;\n}\n\n/** The task's questions for the brief; undefined when the dispatcher can't be asked or keeps none yet. */\nexport async function taskQuestions(session: Session, task: string): Promise<Question[] | undefined> {\n try {\n return await listQuestions(session, { task });\n } catch {\n return undefined;\n }\n}\n\n/**\n * The questions of every task of the change, the given one first, each once: what another track assumed or was\n * told bears on this one. Undefined when the dispatcher can't be asked.\n */\nexport async function changeQuestions(session: Session, tasks: string[]): Promise<Question[] | undefined> {\n const lists = await Promise.all(tasks.map((t) => taskQuestions(session, t)));\n if (lists.some((l) => l === undefined)) return undefined;\n const seen = new Set<string>();\n return lists.flat().filter((q) => q && !seen.has(q.id) && seen.add(q.id)) as Question[];\n}\n\nconst holding = (q: Question) => q.answers.at(-1);\nconst isCorrected = (q: Question) => q.corrected ?? holding(q)?.verdict === 'corrected';\n\n/** A corrected assumption first (rework), then the open ones, then the answered. */\nexport function sortQuestions(questions: Question[]): Question[] {\n const rank = (q: Question) => (isCorrected(q) ? 0 : q.status === 'open' ? 1 : 2);\n return [...questions].sort((a, b) => rank(a) - rank(b));\n}\n\nconst one = (text: string) => text.replace(/\\s+/g, ' ').trim();\n\n/** What holds for a question now, and whose word that is. */\nfunction stateOf(q: Question): string {\n const last = holding(q);\n return isCorrected(q)\n ? 'ASSUMPTION CORRECTED'\n : last\n ? q.outcome === 'assumed'\n ? 'assumption confirmed'\n : 'answered by the product side'\n : q.outcome === 'spec'\n ? 'answered from the spec'\n : q.outcome === 'assumed'\n ? 'open, working on an assumption'\n : q.outcome === 'proposal'\n ? 'a proposal for the product side'\n : q.merged_into\n ? `joined into ${q.merged_into}`\n : q.waits_for === 'contradiction'\n ? 'open, waiting for the product side on a contradiction'\n : 'open, waiting for the product side';\n}\n\n/** One question as the lines the agent reads: what was asked, what holds now, and whose word that is. */\nexport function questionLines(q: Question): string[] {\n const about = [q.task, q.item].filter(Boolean).join(' ');\n const last = holding(q);\n const lines = [`- ${q.id} (${stateOf(q)}${about ? `; ${about}` : ''}): ${one(q.question)}`];\n if (q.outcome === 'assumed' && q.assumption) lines.push(` - Assumed: ${one(q.assumption)}`);\n if (q.outcome === 'open' && q.assumption) lines.push(` - Reading: ${one(q.assumption)}`);\n if (isCorrected(q) && q.rework)\n lines.push(` - Rework: ${q.rework}, covered with \\`Alterspec-Covers: ${q.rework}\\`.`);\n if (q.outcome === 'spec' && q.answer)\n lines.push(` - From the spec: ${one(q.answer)}${q.cites.length ? ` (${q.cites.join(', ')})` : ''}`);\n if (last)\n lines.push(\n ` - Product side (${last.developer}, ${last.at.slice(0, 10)}): ${one(last.text)}${q.reconciled ? ' The spec says so now.' : last.change ? ` It comes into the spec with ${last.change}.` : ''}`,\n );\n return lines;\n}\n\nexport function questionsText(questions: Question[]): string {\n if (!questions.length) return 'No questions.\\n';\n return sortQuestions(questions).flatMap(questionLines).join('\\n') + '\\n';\n}\n\n/** A question the brief names only: its number, task, object and state, and where its full text is read. */\nexport function questionLine(q: Question): string {\n const about = [q.task, q.item].filter(Boolean).join(' ');\n return `- ${q.id} (${about ? `${about}; ` : ''}${stateOf(q)}): \\`alterspec-client questions ${q.id}\\``;\n}\n\n/**\n * The brief's section: what the task must read before it goes on. With `full` (the dispatcher's `questions_full`:\n * asked on this track, or answered with a change to an item of this task), only those are whole and every other is\n * one line naming where it is read; without it, every question is whole, as before the dispatcher sent the list.\n */\nexport function questionsSection(questions: Question[], full?: ReadonlySet<string>): string[] {\n if (!questions.length) return [];\n const sorted = sortQuestions(questions);\n const whole = (q: Question) => !full || full.has(q.id);\n const lined = sorted.filter((q) => !whole(q)).length;\n const corrected = sorted.filter(isCorrected).length;\n const open = sorted.filter((q) => q.status === 'open').length;\n return [\n `## Questions (${open} open${corrected ? `, ${corrected} corrected` : ''})`,\n '',\n corrected\n ? 'A corrected assumption is rework: what was built on it follows the product side’s answer before the task is done.'\n : 'What was asked about this change, on any of its tracks (each names the task it was asked on). An open one on an assumption may still be corrected; an item waiting for an answer stays uncovered.',\n ...(lined\n ? [\n '',\n `Whole: the questions asked on this track or answered with a change to an item of this task. The other ${lined} are one line each; read one with \\`alterspec-client questions <id>\\` when its object is in front of you.`,\n ]\n : []),\n '',\n ...sorted.flatMap((q) => (whole(q) ? questionLines(q) : [questionLine(q)])),\n '',\n ];\n}\n\nconst day = (at?: string | null) => (at ? at.slice(0, 10) : undefined);\n\n/** Why a question isn't built on this track, in words. */\nfunction notBuilt(a: TaskAnswer): string {\n const t = a.task ? `${a.task}` : 'the asking task';\n switch (a.why) {\n case 'no_task':\n return 'the change it was asked on had no task on this track';\n case 'not_done':\n return `${t} isn’t done`;\n case 'answered_after_done':\n return `the product side’s answer (${day(a.answer_at) ?? 'later'}) came after ${t} was done${a.done_at ? ` (${day(a.done_at)})` : ''}`;\n case 'no_task_asked':\n return 'it was asked outside a task';\n default:\n return a.why ?? 'not built on this track';\n }\n}\n\n/** One answer the task carries into the spec, as the agent reads it. */\nexport function answerLine(a: TaskAnswer): string {\n return a.built\n ? `- ${a.question}: built in ${a.task ?? 'the asking task'}, done ${day(a.done_at) ?? 'earlier'}, after the product side’s answer of ${day(a.answer_at) ?? 'before it'}.`\n : `- ${a.question}: not built here: ${notBuilt(a)}.`;\n}\n\n/**\n * The brief's section after the questions: what the dispatcher says this task's change carries into the spec and\n * which of it the track built already (spec 8.4), and how to work such a task.\n */\nexport function answersSection(answers: TaskAnswer[]): string[] {\n if (!answers.length) return [];\n const built = answers.filter((a) => a.built).length;\n const how =\n built === answers.length\n ? 'This change carries answers this track built already: the task checks that the code says what the spec now says. Read each checklist item against the code, add the tests that are missing, cover each item as its tests pass, and rebuild nothing.'\n : built\n ? 'This change carries answers this track built in part: build what stands on a question not built here; for the rest, read each checklist item against the code, add the tests that are missing and cover each item as its tests pass.'\n : 'This change carries answers to questions another track or task asked; none was built on this track, so build it as any task.';\n return [`## Built already (${built} of ${answers.length})`, '', how, '', ...answers.map(answerLine), ''];\n}\n","import { createInterface } from 'node:readline';\nimport type { Readable, Writable } from 'node:stream';\nimport { DispatcherError, KeyRefused, type Session } from './auth.js';\nimport { type Role, allows, refusal, roleOf } from './role.js';\n\n/**\n * The local MCP server Claude Code starts over stdio (spec 10.5): every JSON-RPC message from Claude Code is posted\n * to the dispatcher's `/mcp` with the key's token, and every answer (JSON or a server-sent event stream) goes\n * back on stdout. It forwards rather than reimplements, so the dispatcher's tools, schemas and errors reach Claude\n * Code unchanged. stdout carries protocol messages only; the log goes to stderr.\n *\n * One cut (spec 12.4): the role the key has, asked of `whoami` once per run, decides which tools are listed and may be\n * called. A product session (the spec project) sees its six tools and nothing of the build's tasks; a developer's\n * never sees the product's own. A call outside the role is answered here and never forwarded.\n *\n * When the dispatcher refuses the key, Claude Code still gets a server: `initialize` is answered here and the one\n * tool listed, `whoami`, returns the sentence and the key to send to the admin, so every skill can say it.\n */\n\ntype Id = string | number | null;\ninterface Message {\n jsonrpc?: string;\n id?: Id;\n method?: string;\n params?: Record<string, unknown>;\n}\n\nexport interface ProxyOptions {\n session: Session;\n input: Readable;\n output: Writable;\n version: string;\n log?: (line: string) => void;\n}\n\nconst isRequest = (m: Message) => m.method !== undefined && m.id !== undefined;\n\n/**\n * One call of a dispatcher tool, for the CLI's own commands (`progress`, `context`): a single `tools/call`, which the\n * stateless `/mcp` answers without an `initialize`. The tool's structured result, or its error as `DispatcherError`.\n */\nexport async function callTool(\n session: Session,\n name: string,\n args: Record<string, unknown> = {},\n): Promise<Record<string, unknown>> {\n const res = await session.fetch('/mcp', {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },\n body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),\n });\n const text = await res.text();\n if (!res.ok)\n throw new DispatcherError(`HTTP_${res.status}`, `The dispatcher answered ${res.status}.`, res.status);\n const answer = messagesOf(res.headers.get('content-type') ?? '', text)[0] as\n { result?: ToolResult; error?: { message?: string } } | undefined;\n if (!answer?.result)\n throw new DispatcherError(\n 'MCP_ERROR',\n answer?.error?.message ?? `The dispatcher gave no answer to ${name}.`,\n );\n const out = answer.result.structuredContent ?? {};\n if (answer.result.isError) {\n const err = (out as { error?: { code?: string; message?: string } }).error;\n throw new DispatcherError(\n err?.code ?? 'TOOL_ERROR',\n err?.message ?? answer.result.content?.map((c) => c.text ?? '').join('\\n') ?? `${name} failed.`,\n );\n }\n return out;\n}\n\ninterface ToolResult {\n structuredContent?: Record<string, unknown>;\n content?: { type: string; text?: string }[];\n isError?: boolean;\n}\n\n/** The JSON-RPC messages of an answer: a JSON body, or the `data:` of each server-sent event. */\nexport function messagesOf(contentType: string, text: string): unknown[] {\n if (!text.trim()) return [];\n if (!contentType.includes('text/event-stream')) return [JSON.parse(text)];\n const out: unknown[] = [];\n for (const event of text.split(/\\r?\\n\\r?\\n/)) {\n const data = event\n .split(/\\r?\\n/)\n .filter((l) => l.startsWith('data:'))\n .map((l) => l.slice(5).replace(/^ /, ''))\n .join('\\n');\n if (data.trim()) out.push(JSON.parse(data));\n }\n return out;\n}\n\nexport function runProxy(opts: ProxyOptions): Promise<void> {\n const { session, input, output, version } = opts;\n const log = opts.log ?? ((line: string) => process.stderr.write(`alterspec-client: ${line}\\n`));\n let protocolVersion: string | undefined;\n const pending = new Set<Promise<void>>();\n\n const send = (message: unknown): void => void output.write(JSON.stringify(message) + '\\n');\n const result = (id: Id, value: unknown) => send({ jsonrpc: '2.0', id, result: value });\n const error = (id: Id, message: string, code = -32000) =>\n send({ jsonrpc: '2.0', id, error: { code, message } });\n\n /** The key's role, asked once per run; a failed ask is not kept, so the next request asks again. */\n let role: Promise<Role> | undefined;\n const roleOnce = (): Promise<Role> =>\n (role ??= callTool(session, 'whoami')\n .then(roleOf)\n .catch((e: unknown) => {\n role = undefined;\n throw e;\n }));\n\n /** A `tools/list` answer cut to the role's tools. */\n const cut = (answer: unknown, r: Role): unknown => {\n const tools = (answer as { result?: { tools?: { name?: string }[] } }).result?.tools;\n if (!Array.isArray(tools)) return answer;\n const a = answer as { result: { tools: { name?: string }[] } };\n return { ...a, result: { ...a.result, tools: tools.filter((t) => allows(r, t.name ?? '')) } };\n };\n\n /** The answer of a refused key, from here, without the dispatcher. */\n function refused(m: Message, e: KeyRefused): void {\n if (!isRequest(m)) return;\n const id = m.id as Id;\n switch (m.method) {\n case 'initialize':\n return result(id, {\n protocolVersion: m.params?.protocolVersion ?? '2025-06-18',\n capabilities: { tools: {} },\n serverInfo: { name: 'alterspec-client', version },\n instructions: e.advice,\n });\n case 'ping':\n return result(id, {});\n case 'tools/list':\n return result(id, {\n tools: [\n {\n name: 'whoami',\n description: 'Who you are to the dispatcher. Your SSH key is refused: this says what to do.',\n inputSchema: { type: 'object', properties: {} },\n },\n ],\n });\n case 'tools/call':\n return result(id, {\n content: [{ type: 'text', text: e.advice }],\n structuredContent: {\n error: { code: e.code, message: e.advice },\n key: { line: e.key.line, fingerprint: e.key.fingerprint },\n },\n isError: true,\n });\n default:\n return error(id, e.advice);\n }\n }\n\n async function forward(m: Message): Promise<void> {\n try {\n const gated = m.method === 'tools/list' || m.method === 'tools/call';\n const r = gated ? await roleOnce() : undefined;\n if (r && m.method === 'tools/call') {\n const tool = String(m.params?.name ?? '');\n if (!allows(r, tool)) {\n const why = refusal(r, tool);\n log(`${tool} refused: ${why.code}`);\n if (!isRequest(m)) return;\n return result(m.id as Id, {\n content: [{ type: 'text', text: why.message }],\n structuredContent: { error: why },\n isError: true,\n });\n }\n }\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n accept: 'application/json, text/event-stream',\n };\n if (protocolVersion) headers['mcp-protocol-version'] = protocolVersion;\n const res = await session.fetch('/mcp', { method: 'POST', headers, body: JSON.stringify(m) });\n const text = await res.text();\n if (!res.ok && res.status !== 202) {\n let message = `The dispatcher answered ${res.status}.`;\n try {\n message = (JSON.parse(text) as { error?: { message?: string } }).error?.message ?? message;\n } catch {\n // Not JSON: keep the status.\n }\n if (isRequest(m)) error(m.id as Id, message);\n return;\n }\n for (const answer of messagesOf(res.headers.get('content-type') ?? '', text)) {\n const pv = (answer as { result?: { protocolVersion?: unknown } }).result?.protocolVersion;\n if (m.method === 'initialize' && typeof pv === 'string') protocolVersion = pv;\n send(r && m.method === 'tools/list' ? cut(answer, r) : answer);\n }\n } catch (e) {\n if (e instanceof KeyRefused) {\n log(e.advice.split('\\n')[0]!);\n return refused(m, e);\n }\n const message = e instanceof DispatcherError ? e.message : `The client failed: ${(e as Error).message}`;\n log(message);\n if (!isRequest(m)) return;\n if (m.method === 'tools/call')\n return result(m.id as Id, { content: [{ type: 'text', text: message }], isError: true });\n error(m.id as Id, message);\n }\n }\n\n return new Promise((resolve) => {\n const lines = createInterface({ input, crlfDelay: Infinity });\n lines.on('line', (line) => {\n if (!line.trim()) return;\n let m: Message;\n try {\n m = JSON.parse(line) as Message;\n } catch {\n return error(null, 'Parse error: not a JSON-RPC message.', -32700);\n }\n // Several messages at once (a batch) go as they came; the dispatcher answers them together.\n const p = forward(m).finally(() => pending.delete(p));\n pending.add(p);\n });\n lines.on('close', () => void Promise.allSettled([...pending]).then(() => resolve()));\n });\n}\n","import { exportChange } from '../../src/changes/delta-record.js';\nimport { COMPATIBILITY_SECTION, compatibilityText } from '../../src/changes/compatibility.js';\nimport { DATA_CHANGE_RE, DATA_CHANGE_SECTION, dataChangeText } from '../../src/changes/data-change.js';\nimport { itemObject, objectParts } from '../../src/changes/parts.js';\nimport { type ExportReader, frontMatterOf, idsIn } from '../../src/export/read.js';\nimport { slug } from '../../src/export/paths.js';\nimport { diffLines, unifiedDiff } from '../../src/lib/diff.js';\nimport { splitFrontMatter } from '../../src/lib/frontmatter-split.js';\nimport { criterionParts } from '../../src/spec/criteria.js';\nimport type { DeltaEntry } from '../../src/schemas/delta.js';\nimport { type IdKind, idKind } from '../../src/schemas/ids.js';\nimport type { WorkChange, WorkTask, WorkTrack } from '../../src/schemas/work.js';\nimport {\n OPERATIONS_FILE,\n contractPath,\n designSystemPath,\n initiativePath,\n mockupPath,\n patternsPath,\n RULE_MATRIX_FILE,\n} from '../../src/spec/layout.js';\nimport { history, type PinnedReader, pinnedReader } from './pin.js';\nimport { type Question, type TaskAnswer, answersSection, questionsSection } from './questions.js';\nimport type { TaskRef } from './task.js';\n\n/**\n * A task's brief, assembled from the export (spec 12.2 `context`): what the change is for, what it changed in the\n * task's objects, where each object is now, and for the backend the criteria on the checklist and the operations of\n * its capabilities, for a UI track the screens, their contracts, pages and the channel's design. Texts only for what\n * the task changes; the rules, events and other criteria its capabilities name are an index of paths, so the agent\n * never reads more of the export than it needs. Every text is the one the task's change saw at its sign-off\n * (`pin.ts`, client 0.19.0): what later changes did to the objects the brief names is listed apart, as their tasks'\n * work, so a task's brief doesn't change when a rule it names does.\n */\n\nexport class ContextError extends Error {}\n\nexport interface Piece {\n /** The ID or key it is about. */\n id: string;\n /** The export path, relative to the export folder. */\n path: string;\n /** Its title, for a piece the brief only points to. */\n title?: string;\n /** Its text, for a piece the brief carries; without one the brief names its path. */\n text?: string;\n /** Whether the task changes it, so its delta is among the task's objects. */\n changed?: boolean;\n /** A line after the text, saying where the rest is. */\n rest?: string;\n /** A fact about it in one line (an entity's lifecycle), after the path. */\n note?: string;\n /** The later changes that touched it: the brief shows it as the task's change saw it. */\n since?: string[];\n /** A later change brought it into the export: the brief shows it as the export holds it now. */\n entered?: boolean;\n}\n\nexport interface ObjectBrief {\n key: string;\n /** Its file in the export now, or undefined when the export doesn't hold it. */\n file?: string;\n /** Its shards' folder, when it has one. */\n shards?: string;\n /** What the change did to it, in export terms; undefined when the delta has no entry for it. */\n change?: string;\n status?: { before?: string; after?: string };\n /** A line diff of its text before and after the change (the export's side of it), or one line saying why none. */\n diff?: string;\n /** Why the delta could not say, for an object the backfill could not recover. */\n unrecoverable?: string;\n /**\n * What moved since this change: the later signed-off changes that touched the object, in the order they did, and\n * whether the export's current text differs from this delta's after.\n */\n since?: { changes: string[]; differs: boolean };\n /** The file holding it as this change left it, when a later change touched it. */\n pinned?: string;\n}\n\n/** A later change that touched something the brief names. */\nexport interface LaterChange {\n id: string;\n title?: string;\n /** That change's task on this track, when it has one. */\n task?: string;\n /** Its delta, in the export. */\n delta?: string;\n}\n\n/** An object the brief names that later changes touched: their tasks' work, never this task's. */\nexport interface ChangedSince {\n key: string;\n title?: string;\n /** Whether the task changes the object, or only names it. */\n own?: boolean;\n /** The later changes, in the order they touched it; `fresh` on those the last read of the brief didn't show. */\n changes: { id: string; fresh?: boolean }[];\n /** The file holding the object as the task's change saw it. */\n pinned?: string;\n /** What the changes new since the last read did to it: from the text before the first of them to the export's now. */\n diff?: string;\n /** The export no longer holds it. */\n gone?: boolean;\n /** The export did not hold it when the task's change was signed off: the first of the changes brought it in. */\n entered?: boolean;\n /**\n * For an object this task changes: the check was made here, from the deltas, whether a later change removed or\n * reworded a line of this change's hunks. Absent for a binary file or an object the export did not hold then.\n */\n checked?: boolean;\n /** The later changes that removed or reworded lines this change wrote, with those lines. */\n lost?: { change: string; lines: string[] }[];\n}\n\nexport interface ChecklistItem {\n /** The item as `work.json` and the `Alterspec-Covers` trailer write it. */\n item: string;\n /** What it is, in one line. */\n what: string;\n /** The commit that covered it, as the dispatcher recorded it. */\n covered?: string;\n /**\n * Its weight on this track (work.json format 3 on): how much specified behaviour it is, reasoned at sign-off;\n * 0 (format 6 on): this track builds nothing of it, so it is read, never covered.\n */\n weight?: number;\n /** What a person calls it (work.json format 5): the words the dispatcher's lists show beside the ID. */\n label?: string;\n /** For an item of weight 0 whose object the export no longer holds: the later change that took it out. */\n removedBy?: string;\n}\n\nexport interface Checklist {\n items: ChecklistItem[];\n /** Whether the covered marks are the dispatcher's; false when it couldn't be asked. */\n known: boolean;\n /** Why the covered items are unknown. */\n note?: string;\n}\n\nexport interface CoveredState {\n /** Item → the commit that covered it, from the dispatcher's `task`. */\n covered?: Map<string, string>;\n /** The questions the task carries into the spec, built on its track or not (spec 8.4), from the same `task`. */\n answers?: TaskAnswer[];\n /** The done predecessors whose branch the work starts from (not in the main branch yet), from the same `task`. */\n startFrom?: StartFrom[];\n /** The task's items as the dispatcher holds them (its first list stands; the weights are the latest export's). */\n items?: DispatcherItem[];\n /** The change's tasks on the other tracks and their statuses (dispatcher decision 36); absent from an older one. */\n siblings?: Sibling[];\n /**\n * The questions the brief shows whole (`questions_full`: asked on this track, or answered with a change to an item\n * of this task); the others are one line. Absent from an older dispatcher: every question whole, as before.\n */\n questionsFull?: Set<string>;\n /**\n * The objects of this task a later change touched (`changed_since`: added, changed, removed, keys only). Absent from\n * an older dispatcher: the brief works it out from the deltas; empty: no part of this task changed.\n */\n changedSince?: Set<string>;\n /** Why the dispatcher couldn't be asked. */\n unknown?: string;\n}\n\n/** An item of a task as the dispatcher's `task` returns it. */\nexport interface DispatcherItem {\n item: string;\n weight?: number;\n label?: string;\n}\n\n/** A task of the same change on another track, as the dispatcher's `task` returns it (decision 36). */\nexport interface Sibling {\n id: string;\n track: string;\n status: string;\n commit?: string;\n branch?: string;\n in_main_at?: string;\n}\n\n/** The dispatcher's `questions_full`: question IDs, as strings or objects with `id`; undefined when it sent none. */\nexport function parseQuestionsFull(value: unknown): Set<string> | undefined {\n if (!Array.isArray(value)) return undefined;\n return new Set(\n value.flatMap((v: unknown) => {\n const id = typeof v === 'string' ? v : (v as { id?: unknown } | null)?.id;\n return typeof id === 'string' && id ? [id] : [];\n }),\n );\n}\n\n/** The dispatcher's `changed_since { added, changed, removed }` as one set of keys; undefined when it sent none. */\nexport function parseChangedSince(value: unknown): Set<string> | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n const lists = ['added', 'changed', 'removed'].map((k) => (value as Record<string, unknown>)[k]);\n if (!lists.some(Array.isArray)) return undefined;\n return new Set(\n lists.flatMap((l) =>\n Array.isArray(l)\n ? l.flatMap((v: unknown) => {\n const key =\n typeof v === 'string'\n ? v\n : ((v as { key?: unknown; id?: unknown } | null)?.key ?? (v as { id?: unknown } | null)?.id);\n return typeof key === 'string' && key ? [key] : [];\n })\n : [],\n ),\n );\n}\n\n/** The dispatcher's `siblings`, the well-formed entries only; undefined when it sent none. */\nexport function parseSiblings(value: unknown): Sibling[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const str = (v: unknown) => (typeof v === 'string' && v ? v : undefined);\n return value.flatMap((v: Record<string, unknown>) => {\n const id = str(v?.id);\n const track = str(v?.track) ?? id?.split('/')[1];\n const status = str(v?.status);\n if (!id || !track || !status) return [];\n const commit = str(v.commit);\n const branch = str(v.branch);\n const inMain = str(v.in_main_at);\n return [\n {\n id,\n track,\n status,\n ...(commit ? { commit } : {}),\n ...(branch ? { branch } : {}),\n ...(inMain ? { in_main_at: inMain } : {}),\n },\n ];\n });\n}\n\n/** What the brief says about a compatibility (the proposal's \"## Compatibility\" section). */\nexport interface Compatibility {\n /** This change keeps the old behaviour while its other tracks build it: the section, its UI tracks, who ends it. */\n kept?: { text: string; tracks: string[]; endedBy: string[] };\n /** The compatibilities this task ends: another change's tasks on other tracks it waits for, by change. */\n ends?: { change: string; tracks: string[] }[];\n}\n\n/** A done predecessor on a pushed branch: the task's branch is based on it, not on the main branch. */\nexport interface StartFrom {\n /** The predecessor, e.g. `CHG-012/BE`. */\n id: string;\n /** The branch it was done on, e.g. `task/chg-012-be`. */\n branch: string;\n /** The commit it was done at. */\n commit?: string;\n}\n\n/**\n * The branches to start a task from, out of the dispatcher's `after` entries (of `next_task` or `task`): the done\n * predecessors of the same track whose branch isn't the main one (`branch` null), the predecessor's own track first.\n */\nexport function startFrom(track: string, after: unknown): StartFrom[] {\n if (!Array.isArray(after)) return [];\n const out: StartFrom[] = [];\n for (const a of after as { id?: unknown; commit?: unknown; branch?: unknown }[]) {\n if (typeof a?.id !== 'string' || typeof a.branch !== 'string' || !a.branch) continue;\n if (a.id.split('/')[1] !== track) continue;\n out.push({ id: a.id, branch: a.branch, ...(typeof a.commit === 'string' ? { commit: a.commit } : {}) });\n }\n return out;\n}\n\n/** Where the export uses an entity, or one attribute of it, that the task changes. */\nexport interface WhereUsed {\n entity: string;\n /** One attribute the task's diff names; absent for the entity as a whole. */\n attribute?: string;\n /** Screens whose fields show it. */\n screens: Piece[];\n /** Capabilities that take or return it (an attribute), or work with it (the entity). */\n capabilities: Piece[];\n /** Rules about the entity (rules name no attributes); only for the entity as a whole. */\n rules: Piece[];\n}\n\n/** The reach of a rule or role the task touches or names: where the export enforces, holds or shows it. */\nexport interface Reach {\n id: string;\n kind: 'rule' | 'role';\n title?: string;\n /** A rule: the capabilities that list it; a role: the capabilities it may perform, each with its scope. */\n capabilities: (Piece & { scope?: string })[];\n /** A rule: the criteria whose Covers name it, by capability; absent for a role. */\n criteria?: string[];\n /** A rule: the screens of those capabilities; a role: the screens it is on. */\n screens: Piece[];\n /** A rule: its row of the export's rule matrix (triggered by, reads, listed by, covered by, message shown on). */\n matrix?: string[];\n}\n\nexport interface TaskContext {\n task: string;\n /** The change's questions on every track, as the dispatcher keeps them; absent when it couldn't be asked. */\n questions?: Question[];\n /** The questions shown whole (the dispatcher's `questions_full`); absent: every question whole. */\n questionsFull?: string[];\n /** What this task carries into the spec and which of it the track built already; absent when none or unknown. */\n answers?: TaskAnswer[];\n /** What this track builds in this change, in a line and in two or three sentences (work.json format 5). */\n title?: string;\n summary?: string;\n /** The size of what this track builds in this change, 1–100 (work.json format 7), reasoned at sign-off. */\n weight?: number;\n /**\n * The initiative the change belongs to (work.json format 8): the whole it is part of, the idea and the problem it\n * solves, as the export holds it now. Why the work exists; never work of its own.\n */\n initiative?: { id: string; title: string; path: string; body: string };\n /** The task's items (work.json format 2 on, with weights from 3 and labels from 5); undefined for a format 1 export, which has none. */\n checklist?: Checklist;\n export: string;\n change: Pick<WorkChange, 'id' | 'title' | 'signed_off' | 'level' | 'depends_on'>;\n track: WorkTrack;\n after: WorkTask['after'];\n /** The done predecessors' branches the task's branch starts from; absent when none or the dispatcher wasn't asked. */\n startFrom?: StartFrom[];\n /** The change's tasks on other tracks, from the dispatcher; absent when it sent none. */\n siblings?: Sibling[];\n /** The compatibility this change keeps or this task ends; absent when neither. */\n compatibility?: Compatibility;\n proposal: {\n path: string;\n why?: string;\n what?: string;\n /** The one-time data change the proposal declares; absent for \"None.\" (the backend's `CHG#data-change` item). */\n dataChange?: string;\n };\n delta?: string;\n objects: ObjectBrief[];\n /** Where the export uses the entities and attributes the task changes. */\n whereUsed?: WhereUsed[];\n /** Where the export enforces, holds or shows the rules and roles the task touches or its text names. */\n reach?: Reach[];\n /** The rule matrix's \"How to read\" lines for the rows shown under Reach. */\n matrixLegend?: string[];\n /** The backend track. */\n acceptance?: Piece[];\n rules?: Piece[];\n events?: Piece[];\n operations?: Piece[];\n /** The decisions the task's text names. */\n decisions?: Piece[];\n /** The glossary terms the change's text uses. */\n terms?: Piece[];\n /** The backend track: the entities its capabilities work with, by path, each with its lifecycle in one line. */\n entities?: Piece[];\n /** The backend track: the quality requirements and integrations the task touches or its text names. */\n nfr?: Piece[];\n integrations?: Piece[];\n /** A UI track. */\n screens?: { id: string; file?: string; contract?: string; page?: string }[];\n design?: { designSystem?: string; patterns?: string };\n /** The folder the pinned files are written to: an absolute path in the brief is under it. */\n pins?: string;\n /** The objects the brief names that later changes touched; absent when nothing moved since the change. */\n changedSince?: ChangedSince[];\n /** Those later changes, in the change map's order. */\n later?: LaterChange[];\n /**\n * With the dispatcher's `changed_since`: how many objects the brief names were changed by later changes that the\n * task doesn't cite (left out of \"Changed since\"), and whether none it cites was.\n */\n sinceElsewhere?: number;\n changedSinceNone?: boolean;\n}\n\n/** A shard's text without the comment naming its source. */\nconst shardText = (x: ExportReader, path: string | undefined) =>\n path\n ? x\n .read(path)\n ?.replace(/^<!-- source: [^\\n]*-->\\n\\n/, '')\n .trim()\n : undefined;\n/** A section shard's text without its `## ` heading, which the brief gives itself. */\nconst sectionText = (x: ExportReader, path: string | undefined) =>\n shardText(x, path)?.replace(/^## [^\\n]*\\n*/, '');\n\nconst screenOf = (key: string): string | undefined =>\n /^UX-(SCR-[A-Z]{2,6}-\\d{2})-[A-Z]{2,5}$/.exec(key)?.[1] ??\n /^file:experience\\/[a-z]{2,5}\\/mockups\\/(SCR-[A-Z]{2,6}-\\d{2})\\.html$/.exec(key)?.[1] ??\n (/^SCR-[A-Z]{2,6}-\\d{2}$/.test(key) ? key : undefined);\n\n/**\n * An object's text as the brief compares it: without the `version:` line the sign-off raises, the fingerprints a\n * contract keeps (`reviewed:`, `dry:`, `page:`) and the template's HTML comments, which tell an author what to write\n * and a builder nothing. Files (pages, design) stay whole.\n */\nexport const forDiff = (key: string, text: string | undefined) =>\n key.startsWith('file:')\n ? (text ?? '')\n : (text ?? '')\n .replace(/^[^\\S\\n]*<!--[\\s\\S]*?-->[^\\S\\n]*\\n/gm, '')\n .replace(/<!--[\\s\\S]*?-->/g, '')\n .replace(/^version:[^\\S\\n]*\\d+[^\\S\\n]*\\n/m, '')\n .replace(/^(?:reviewed|dry|page):[^\\n]*\\n/gm, '');\n\n/**\n * Each hunk header of a document's diff with the section it falls in, as git names the function: `@@ … @@ ## Main\n * flow`, `@@ … @@ ## Acceptance criteria › CAP-X-001-AC-02`, or `front-matter`, so the agent needn't open the file\n * to know where a change sits.\n */\nexport function withSections(diff: string, before: string, after: string): string {\n const where = (text: string, line: number) => {\n const lines = text.split('\\n');\n if (lines[0] === '---') {\n const end = lines.indexOf('---', 1);\n if (end > 0 && line - 1 <= end) return 'front-matter';\n }\n let sub: string | undefined;\n for (let i = Math.min(line, lines.length) - 1; i >= 0; i--) {\n const l = lines[i]!;\n if (sub === undefined && /^### /.test(l)) sub = l.slice(4).split(/\\s/)[0];\n if (/^## /.test(l)) return sub ? `${l} › ${sub}` : l;\n }\n return undefined;\n };\n const lines = diff.split('\\n');\n return lines\n .map((header, i) => {\n const m = /^@@ -(\\d+),\\d+ \\+(\\d+),\\d+ @@$/.exec(header);\n if (!m) return header;\n // The hunk's first changed line, not its first context line, names the section.\n let k = i + 1;\n while (lines[k]?.startsWith(' ')) k++;\n const skipped = k - i - 1;\n const name = lines[k]?.startsWith('+')\n ? where(after, Number(m[2]) + skipped)\n : where(before, Number(m[1]) + skipped);\n return name ? `${header} ${name}` : header;\n })\n .join('\\n');\n}\n\n/** Front-matter the tooling keeps (review and page fingerprints, status), which says nothing about the work. */\nconst BOOKKEEPING = /^(reviewed|page|dry|status|version|signed_off|base):/;\n\n/** The first line a text adds to another, as a sentence: no list marker, heading mark or emphasis. */\nconst firstAddedLine = (a: string, b: string) =>\n diffLines(a, b)\n .filter((l) => l.op === '+')\n .map((l) =>\n l.text\n .replace(/^\\s*(?:[-*]|#+|\\d+\\.)\\s+/, '')\n .replace(/\\*\\*/g, '')\n .trim(),\n )\n .find((t) => t && !/^(---|```)/.test(t) && !BOOKKEEPING.test(t));\n\nconst clipped = (line: string | undefined) => (line && line.length > 200 ? `${line.slice(0, 199)}…` : line);\n\n/** The first sentence the change added to an object's body, else to its front-matter; for a whole-object item. */\nfunction firstAdded(key: string, entry: DeltaEntry): string | undefined {\n const before = forDiff(key, entry.before);\n const after = forDiff(key, entry.after);\n return clipped(\n firstAddedLine(splitFrontMatter(before).body, splitFrontMatter(after).body) ??\n firstAddedLine(splitFrontMatter(before).raw ?? '', splitFrontMatter(after).raw ?? ''),\n );\n}\n\n/** An object's text in the export: an item's shard (without the comment naming its source), else its file. */\nfunction currentText(x: ExportReader, key: string): string | undefined {\n const file = x.fileOf(key);\n if (!file || !x.has(file)) return undefined;\n const shard = x.itemShard(file, key);\n return shard ? shardText(x, shard) : x.read(file);\n}\n\n/** The first file holding an object as the change saw it: an item's shard, a document's file. */\nconst pinnedPath = (x: PinnedReader, key: string): string | undefined =>\n x.pinnedFiles(key).keys().next().value;\n\nfunction objectBrief(\n x: PinnedReader,\n key: string,\n entry: DeltaEntry | undefined,\n why: string | undefined,\n at: (path: string) => string,\n): ObjectBrief {\n const now = x.current;\n const file = now.fileOf(key);\n const held = file !== undefined && now.has(file);\n const brief: ObjectBrief = { key, ...(held ? { file } : {}) };\n if (held && now.shards(file).length) brief.shards = now.shards(file)[0]!.replace(/\\/[^/]+$/, '');\n if (why) brief.unrecoverable = why;\n if (!entry) return brief;\n // What moved since the sign-off: a later change that touched it, or a current text that isn't this delta's after.\n const later = x.seen(key).later.map((l) => l.change);\n const text = currentText(now, key);\n const differs =\n held &&\n entry.exported.after &&\n entry.after !== undefined &&\n !entry.binary &&\n text !== undefined &&\n forDiff(key, entry.after).trim() !== forDiff(key, text).trim();\n if (later.length || differs) brief.since = { changes: later, differs: !!differs };\n const own = later.length ? pinnedPath(x, key) : undefined;\n if (own) brief.pinned = at(own);\n brief.change = exportChange(entry);\n if (entry.status) brief.status = entry.status;\n if (entry.before !== undefined || entry.after !== undefined) {\n const d = unifiedDiff(forDiff(key, entry.before), forDiff(key, entry.after));\n if (d)\n brief.diff = key.startsWith('file:')\n ? d\n : withSections(d, forDiff(key, entry.before), forDiff(key, entry.after));\n else if (unifiedDiff(entry.before ?? '', entry.after ?? ''))\n brief.diff = 'Only its version, its fingerprints or the template’s comments changed: nothing to build.';\n } else if (entry.binary) {\n brief.diff = `binary: ${[entry.binary.before, entry.binary.after].map((b) => (b ? `${b.size} bytes` : '—')).join(' → ')}`;\n }\n return brief;\n}\n\nconst KIND_WORDS: Partial<Record<IdKind, string>> = {\n app: 'the application',\n module: 'module',\n capability: 'capability',\n screen: 'screen',\n experience: 'experience screen',\n role: 'role',\n integration: 'integration',\n nfr: 'non-functional requirement',\n persona: 'persona',\n entity: 'entity',\n rule: 'rule',\n flow: 'flow',\n event: 'event',\n decision: 'decision',\n};\n\n/** The title of an object: its item shard's `## <ID> <title>`, else its file's first `# ` heading. */\nexport function titleOf(x: ExportReader, id: string): string | undefined {\n const file = x.fileOf(id);\n if (!file || !x.has(file)) return undefined;\n const shard = x.itemShard(file, id);\n if (shard) return /^## \\S+ (.+)$/m.exec(shardText(x, shard) ?? '')?.[1]?.trim();\n return /^# (.+)$/m.exec(splitFrontMatter(x.read(file)!).body)?.[1]?.trim();\n}\n\nconst named = (x: ExportReader, id: string) => {\n const title = titleOf(x, id);\n return title ? `${id} ${title}` : `${id} (not in the export now)`;\n};\n\n/**\n * What a criterion asks of a track, from the capability's Acceptance criteria shard: on `BE` its `Then` (and what\n * follows it but `Covers` and `Shown`), on a UI track its `Shown`; with a note when the other part is another task's.\n */\nfunction criterionOf(x: ExportReader, cap: string, id: string, track?: string): string | undefined {\n const file = x.fileOf(cap);\n const text = file && x.has(file) ? sectionText(x, x.sectionShard(file, 'Acceptance criteria')) : undefined;\n const chunk = text?.split(/^### /m).find((c) => c.split(/\\s/)[0] === id);\n if (!chunk) return undefined;\n const parts = criterionParts(chunk.split('\\n').slice(1).join('\\n'));\n const ui = track !== undefined && track !== BACKEND;\n const lines = (ui ? parts.shown : parts.system)\n .split('\\n')\n .map((l) =>\n l\n .replace(/^\\s*[-*]\\s*/, '')\n .replace(/\\*\\*/g, '')\n .trim(),\n )\n .filter(Boolean);\n const from = lines.findIndex((l) => (ui ? /^Shown\\b/ : /^Then\\b/).test(l));\n const kept = (from >= 0 ? lines.slice(from) : lines).filter((l) => !/^Covers:/.test(l));\n const note = ui\n ? parts.hasThen\n ? ' (what the system guarantees is the BE task’s)'\n : ''\n : parts.hasShown\n ? ' (what the screen shows is the UI task’s)'\n : '';\n return kept.length ? `${kept.join(' ')}${note}` : undefined;\n}\n\nconst BACKEND = 'BE';\n\n/**\n * One line saying what an item is, from the export (no YAML parsed: the client carries no YAML parser). An object\n * that is an item whole says what the change did to it, with the first sentence it added, so the line names the work\n * rather than the object.\n */\nexport function itemWhat(x: ExportReader, item: string, entry?: DeltaEntry, track?: string): string {\n const ac = /^((CAP-[A-Z]{2,6}-\\d{3})-AC-\\d{2})$/.exec(item);\n if (ac) {\n const then = criterionOf(x, ac[2]!, ac[1]!, track);\n return `acceptance criterion of ${named(x, ac[2]!)}${then ? `: ${then}` : ''}`;\n }\n const action = /^(SCR-[A-Z]{2,6}-\\d{2})\\.(A\\d{2})$/.exec(item);\n if (action) {\n const [, scr, a] = action;\n const file = x.fileOf(scr!);\n const actions = file && x.has(file) ? sectionText(x, x.sectionShard(file, 'Actions')) : undefined;\n const line = actions\n ?.split('\\n')\n .map((l) => l.replace(/^\\s*[-*]\\s*/, '').trim())\n .find((l) => l.startsWith(`${a} `));\n const label = line?.slice(a!.length).trim();\n return `action ${a}${label ? ` \"${label.replace(/\\s*→\\s*/, '\" → ')}` : ''}${label && !label.includes('→') ? '\"' : ''} on ${named(x, scr!)}`;\n }\n const state = /^(UX-(SCR-[A-Z]{2,6}-\\d{2})-([A-Z]{2,5}))#(.+)$/.exec(item);\n if (state) {\n const [, ux, scr, code, id] = state;\n const rule = /^rule-(.+)$/.exec(id!)?.[1];\n // The mockup shows a state by its URL, so the agent opens exactly what it builds.\n const page = mockupPath(code!, scr!);\n const open = x.has(page) ? `; open \\`${page}?state=${encodeURIComponent(id!)}\\`` : '';\n return `state \"${id}\" of ${ux} (${named(x, scr!)})${rule ? `: the message of RULE-${rule.toUpperCase()}` : ''}${open}`;\n }\n if (item.startsWith('file:')) {\n const path = item.slice(5);\n const page = /\\/mockups\\/(SCR-[A-Z]{2,6}-\\d{2})\\.html$/.exec(path)?.[1];\n const what = page\n ? `the mockup page of ${page}`\n : /\\/design-system\\.md$/.test(path)\n ? 'the channel’s design system'\n : /\\/patterns\\.md$/.test(path)\n ? 'the channel’s patterns'\n : 'a file of the channel’s experience';\n return `${what}: \\`${path}\\`${x.has(path) ? '' : ' (not in the export now)'}`;\n }\n if (item.startsWith('term:')) return `glossary term \"${item.slice(5)}\"`;\n if (DATA_CHANGE_RE.test(item))\n return `the one-time change to the records the product already holds (the proposal's \"${DATA_CHANGE_SECTION}\", below)`;\n // A part of an object with no part of its own kind: its front-matter, a section, a line (alterspec 0.30).\n const part = /^([^#]+)#([^#]+)$/.exec(item);\n if (part && !/^UX-/.test(item)) {\n const [, key, slug] = part as unknown as [string, string, string];\n const k = idKind(key);\n const owner = `${k && KIND_WORDS[k] ? `${KIND_WORDS[k]} ` : ''}${named(x, key)}`;\n const kind = entry?.kind === 'item' ? 'item' : 'doc';\n const after = entry?.after !== undefined ? objectParts(entry.after, kind).get(slug) : undefined;\n const before = entry?.before !== undefined ? objectParts(entry.before, kind).get(slug) : undefined;\n const label = !after\n ? `the part \"${slug}\"`\n : after.label === 'front-matter'\n ? 'the front-matter'\n : after.label === 'section'\n ? `the section \"${after.heading}\"`\n : `the line \"${after.heading}\"`;\n const line = after ? clipped(firstAddedLine(before?.text ?? '', after.text)) : undefined;\n return `${label} of ${owner}${line ? `: \"${line}\"` : ''}`;\n }\n const kind = idKind(item);\n const what = `${kind && KIND_WORDS[kind] ? `${KIND_WORDS[kind]} ` : ''}${named(x, item)}`;\n if (!entry) return what;\n const change = exportChange(entry);\n if (change !== 'modified') return `${what}, ${change}`;\n const line = firstAdded(item, entry);\n return line ? `${what}, modified: \"${line}\"` : `${what}, modified (see its delta)`;\n}\n\n/** The proposal's one-time data change, unless it says \"None.\" or nothing. */\nfunction dataChangeOf(text: string | undefined): { dataChange?: string } {\n const t = dataChangeText(text);\n return t ? { dataChange: t } : {};\n}\n\n/**\n * The attributes an entity's diff adds, removes or changes (`- name: X` and the lines under it); undefined when the\n * entity enters or leaves the export, when the whole of it is new or gone to the team.\n */\nfunction changedAttributes(entry: DeltaEntry | undefined): string[] | undefined {\n if (!entry || !entry.exported.before || !entry.exported.after) return undefined;\n if (entry.before === undefined || entry.after === undefined) return undefined;\n const names = (raw: string) =>\n new Map([...raw.matchAll(/^ {2}- name: (.+?)\\s*$/gm)].map((m) => [m[1]!, m.index!]));\n const before = splitFrontMatter(entry.before).raw ?? '';\n const after = splitFrontMatter(entry.after).raw ?? '';\n const attr = (raw: string, from: number) => {\n const chunk = raw.slice(from).split(/\\n(?! {4})/)[0] ?? '';\n return chunk.replace(/^\\s*- name: .*\\n?/, '');\n };\n const b = names(before);\n const a = names(after);\n const out = new Set<string>();\n for (const [n, i] of a) if (!b.has(n) || attr(before, b.get(n)!) !== attr(after, i)) out.add(n);\n for (const n of b.keys()) if (!a.has(n)) out.add(n);\n return [...out];\n}\n\n/**\n * Where the export uses what the task changes: for every entity among the task's objects, the screens, capabilities\n * and rules of the export (its `_generated/index.json`) that show, take, return or guard it, per changed attribute\n * and for the entity as a whole. Only what the export holds is listed: a screen not signed off isn't the team's yet.\n */\nfunction whereUsed(\n x: ExportReader,\n objects: readonly string[],\n entries: Map<string, DeltaEntry>,\n changed: Set<string>,\n): WhereUsed[] {\n const index = x.index();\n if (!index) return [];\n const piece = (id: string, title: string, file: string | undefined): Piece => ({\n id,\n path: file ?? '',\n title,\n ...(changed.has(id) ? { changed: true } : {}),\n });\n const out: WhereUsed[] = [];\n for (const entity of objects.filter((k) => idKind(k) === 'entity')) {\n const attributes = changedAttributes(entries.get(entity)) ?? [];\n for (const attribute of attributes)\n out.push({\n entity,\n attribute,\n screens: index.screens\n .filter((s) => s.fields.some((f) => f.entity === entity && f.attributes.includes(attribute)))\n .map((s) => piece(s.id, s.title, x.fileOf(s.id))),\n capabilities: index.capabilities\n .filter((c) =>\n [...(c.inputs ?? []), ...(c.outputs ?? [])].some(\n (d) => 'entity' in d && d.entity === entity && d.attributes.includes(attribute),\n ),\n )\n .map((c) => piece(c.id, c.title, x.fileOf(c.id))),\n rules: [],\n });\n out.push({\n entity,\n screens: index.screens\n .filter((s) => s.fields.some((f) => f.entity === entity))\n .map((s) => piece(s.id, s.title, x.fileOf(s.id))),\n capabilities: index.capabilities\n .filter((c) => c.entities.some((e) => e.entity === entity))\n .map((c) => piece(c.id, c.title, x.fileOf(c.id))),\n rules: index.rules\n .filter((r) => r.entities.includes(entity) || (r.guards ?? []).some((g) => g.entity === entity))\n .map((r) => piece(r.id, r.title, x.fileOf(r.id))),\n });\n }\n return out;\n}\n\n/** An entity's lifecycle in one line, from the index: its states, the initial one, its transitions and by what. */\nfunction lifecycleOf(x: ExportReader, id: string): string | undefined {\n const e = x.index()?.entities.find((e) => e.id === id);\n if (!e?.states?.length) return undefined;\n const states = e.states.map((s) => (s === e.initial_state ? `${s} (initial)` : s)).join(', ');\n const transitions = (e.transitions ?? [])\n .map((t) => `${t.from}->${t.to}${t.by === 'time' ? ` by time${t.at ? ` at ${t.at}` : ''}` : ''}`)\n .join(', ');\n return `states ${states}${transitions ? `; transitions ${transitions}` : '; no transitions'}`;\n}\n\n/** The lines of an object's text that count when two deltas are compared: trimmed, non-blank, no front-matter fence. */\nconst linesOf = (key: string, text: string | undefined): Set<string> =>\n new Set(\n forDiff(key, text)\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l && l !== '---'),\n );\n\n/** The lines of a rule's matrix row that say where it reaches; the rule's own text says the rest. */\nconst MATRIX_ROW =\n /^- \\*\\*(Triggered by|Reads the guarded entity|Listed by, without triggering a guard|Covered by|Message shown on)/;\n\ninterface Matrix {\n /** The \"How to read\" bullets of the rows' lines, each with its continuation lines. */\n legend: string[];\n /** Rule ID → its row's lines, links reduced to their text. */\n rows: Map<string, string[]>;\n}\n\nconst matrices = new WeakMap<ExportReader, Matrix>();\n\n/** The export's rule matrix, read once: the view the agents opened for every rule's reach. */\nfunction matrixOf(x: ExportReader): Matrix {\n const known = matrices.get(x);\n if (known) return known;\n const m: Matrix = { legend: [], rows: new Map() };\n const text = x.read(RULE_MATRIX_FILE);\n if (text) {\n const [head, ...blocks] = text.split(/^(?=## )/m);\n const legend = head!.split('How to read a rule:')[1] ?? '';\n const bullets = legend.split(/^(?=- )/m).map((b) => b.trimEnd());\n for (const b of bullets) if (MATRIX_ROW.test(b)) m.legend.push(...b.split('\\n'));\n for (const block of blocks) {\n const id = block.slice(3).split(/\\s/)[0];\n if (!id) continue;\n const rows = block\n .split('\\n')\n .filter((l) => MATRIX_ROW.test(l))\n .map((l) => l.replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1'));\n if (rows.length) m.rows.set(id, rows);\n }\n }\n matrices.set(x, m);\n return m;\n}\n\n/** Where the export enforces, holds or shows a rule or a role, from the index and the capabilities' criteria. */\nfunction reachOf(\n x: ExportReader,\n id: string,\n kind: 'rule' | 'role',\n changed: Set<string>,\n): Reach | undefined {\n const index = x.index();\n if (!index) return undefined;\n const piece = (pid: string, title: string | undefined, scope?: string): Piece & { scope?: string } => ({\n id: pid,\n path: x.fileOf(pid) ?? '',\n ...(title ? { title } : {}),\n ...(changed.has(pid) ? { changed: true } : {}),\n ...(scope ? { scope } : {}),\n });\n const screenPiece = (sid: string) =>\n piece(sid, index.screens.find((s) => s.id === sid)?.title ?? titleOf(x, sid));\n const title = titleOf(x, id);\n if (kind === 'rule') {\n const caps = index.capabilities.filter((c) => (c.rules ?? []).includes(id));\n const criteria = caps.flatMap((c) => {\n const file = x.fileOf(c.id);\n const text =\n file && x.has(file) ? sectionText(x, x.sectionShard(file, 'Acceptance criteria')) : undefined;\n return (text ?? '')\n .split(/^(?=### )/m)\n .filter(\n (chunk) =>\n chunk.startsWith('### ') &&\n new RegExp(`^\\\\s*[-*]?\\\\s*\\\\**Covers:?\\\\**[^\\\\n]*\\\\b${id}\\\\b`, 'm').test(chunk),\n )\n .map((chunk) => chunk.slice(4).split(/\\s/)[0]!);\n });\n const screens = [...new Set(caps.flatMap((c) => c.screens ?? []))].filter((sid) => x.sources.has(sid));\n const matrix = matrixOf(x).rows.get(id) ?? [];\n return {\n id,\n kind,\n ...(title ? { title } : {}),\n capabilities: caps.map((c) => piece(c.id, c.title)),\n criteria,\n screens: screens.map(screenPiece),\n ...(matrix.length ? { matrix } : {}),\n };\n }\n const caps = index.capabilities.filter((c) => (c.roles ?? []).some((r) => r.role === id));\n const screens = index.screens.filter((s) => (s.roles ?? []).some((r) => r.role === id));\n return {\n id,\n kind,\n ...(title ? { title } : {}),\n capabilities: caps.map((c) => piece(c.id, c.title, c.roles?.find((r) => r.role === id)?.scope)),\n screens: screens.map((s) => piece(s.id, s.title)),\n };\n}\n\ntype Edges = Pick<WorkTask, 'track' | 'after'>;\n\n/** The compatibility the task's change keeps (its proposal's section) and the ones this task ends (its `after`). */\nfunction compatibilityOf(\n x: ExportReader,\n change: { id: string; tasks?: Edges[] },\n work: Edges,\n proposal: string,\n): { compatibility?: Compatibility } {\n const text = compatibilityText(sectionText(x, x.sectionShard(proposal, COMPATIBILITY_SECTION)));\n // An edge that crosses both change and track is one only the end of a compatibility makes.\n const crosses = (owner: Edges, ownerChange: string, a: { change: string; track: string }) =>\n a.change !== ownerChange && a.track !== owner.track;\n const endedBy = x.work.changes.flatMap((other) =>\n (other.tasks ?? [])\n .filter((t) => t.after.some((a) => a.change === change.id && crosses(t, other.id, a)))\n .map((t) => `${other.id}/${t.track}`),\n );\n const kept = text\n ? { text, tracks: (change.tasks ?? []).filter((t) => t.track !== 'BE').map((t) => t.track), endedBy }\n : undefined;\n const byChange = new Map<string, string[]>();\n for (const a of work.after)\n if (crosses(work, change.id, a)) byChange.set(a.change, [...(byChange.get(a.change) ?? []), a.track]);\n const ends = [...byChange].map(([c, tracks]) => ({ change: c, tracks }));\n return kept || ends.length\n ? { compatibility: { ...(kept ? { kept } : {}), ...(ends.length ? { ends } : {}) } }\n : {};\n}\n\n/**\n * The later change that took an object out of the export, when the export no longer holds it: the last change of\n * its history whose entry leaves it out, signed off after the task's change.\n */\nfunction removedByOf(x: ExportReader, change: string, key: string): { removedBy?: string } {\n if (x.sources.has(key)) return {};\n const h = history(x, key);\n const at = h.findIndex((e) => e.change === change);\n const gone = h\n .slice(at + 1)\n .reverse()\n .find((e) => e.entry.exported.before && !e.entry.exported.after);\n return gone && gone.change !== change ? { removedBy: gone.change } : {};\n}\n\nexport function taskContext(\n current: ExportReader,\n task: TaskRef,\n exportDir: string,\n state: CoveredState = {},\n questions?: Question[],\n opts: {\n /** The folder the pinned files are written to: a pinned path is printed under it. */\n pins?: string;\n /** `<key><<change>` of what the last read of this brief showed as changed since. */\n shown?: ReadonlySet<string>;\n } = {},\n): TaskContext {\n // Texts are read as the task's change saw them; facts the export derives (the index, the operations) as they are.\n const x = pinnedReader(current, task.change);\n const at = (path: string) => (opts.pins && x.isPinned(path) ? `${opts.pins}/${path}` : path);\n /** The objects the brief names, to say which of them later changes touched. */\n const names = new Set<string>();\n const since = (key: string): { since?: string[]; entered?: boolean } => {\n names.add(key);\n const s = x.seen(key);\n return s.later.length\n ? { since: s.later.map((l) => l.change), ...(s.absent ? { entered: true } : {}) }\n : {};\n };\n const change = x.work.changes.find((c) => c.id === task.change);\n if (!change) throw new ContextError(`${task.change} is not in this export's work.json: pull the export.`);\n const work = (change.tasks ?? []).find((t) => t.track === task.track);\n if (!work)\n throw new ContextError(\n `${task.change} has no task on ${task.track}: its tracks are ${(change.tasks ?? []).map((t) => t.track).join(', ') || 'none'}.`,\n );\n const track = x.work.tracks.find((t) => t.code === task.track)!;\n const proposal = x.proposalPath(task.change);\n if (!proposal) throw new ContextError(`The export holds no archived proposal of ${task.change}.`);\n const delta = x.delta(task.change);\n const entries = new Map(delta?.objects.map((e) => [e.key, e]));\n const lost = new Map(delta?.unrecoverable?.map((u) => [u.key, u.why]));\n\n // The checklist is the dispatcher's list of the task's items when it answered (its first list stands, whatever a\n // newer alterspec derives; its weights follow the latest export), the export's own only when it couldn't be asked.\n const exported = work as { items?: string[]; weights?: Record<string, number> };\n const items = state.items?.length ? state.items.map((i) => i.item) : exported.items;\n const weights: Record<string, number> | undefined = state.items?.length\n ? Object.fromEntries(\n state.items.flatMap((i) => {\n const w = i.weight ?? exported.weights?.[i.item];\n return w === undefined ? [] : [[i.item, w] as const];\n }),\n )\n : exported.weights;\n const words = work as {\n title?: string;\n summary?: string;\n labels?: Record<string, string>;\n weight?: number;\n };\n /** An item's label: the dispatcher's, else the export's. */\n const labelOf = (item: string) => state.items?.find((i) => i.item === item)?.label ?? words.labels?.[item];\n const initiativeId = (change as { initiative?: string }).initiative;\n const initiative = initiativeId ? x.initiative(initiativeId) : undefined;\n const ctx: TaskContext = {\n task: task.id,\n ...(initiative ? { initiative: { ...initiative, path: initiativePath(initiative.id) } } : {}),\n ...(words.title ? { title: words.title } : {}),\n ...(words.summary ? { summary: words.summary } : {}),\n ...(words.weight === undefined ? {} : { weight: words.weight }),\n ...(questions ? { questions } : {}),\n ...(questions && state.questionsFull ? { questionsFull: [...state.questionsFull].sort() } : {}),\n ...(state.answers?.length ? { answers: state.answers } : {}),\n ...(items\n ? {\n checklist: {\n items: items.map((item) => {\n const covered = state.covered?.get(item);\n const weight = weights?.[item];\n return {\n item,\n what: itemWhat(x, item, entries.get(itemObject(item)), task.track),\n ...(covered ? { covered } : {}),\n ...(weight === undefined ? {} : { weight }),\n ...(labelOf(item) ? { label: labelOf(item) } : {}),\n ...(weight === 0 ? removedByOf(current, task.change, itemObject(item)) : {}),\n };\n }),\n known: state.covered !== undefined,\n ...(state.unknown ? { note: state.unknown } : {}),\n },\n }\n : {}),\n export: exportDir,\n change: {\n id: change.id,\n title: change.title,\n signed_off: change.signed_off,\n level: change.level,\n depends_on: change.depends_on,\n },\n track,\n after: work.after,\n ...(state.startFrom?.length ? { startFrom: state.startFrom } : {}),\n ...(state.siblings?.length ? { siblings: state.siblings } : {}),\n ...compatibilityOf(x, change, work, proposal),\n proposal: {\n path: proposal,\n why: sectionText(x, x.sectionShard(proposal, 'Why')),\n what: sectionText(x, x.sectionShard(proposal, 'What changes')),\n ...dataChangeOf(sectionText(x, x.sectionShard(proposal, DATA_CHANGE_SECTION))),\n },\n ...(delta ? { delta: proposal.replace(/proposal\\.md$/, 'delta.md') } : {}),\n objects: work.objects.map((key) => objectBrief(x, key, entries.get(key), lost.get(key), at)),\n ...(opts.pins ? { pins: opts.pins } : {}),\n };\n for (const key of work.objects) names.add(key);\n\n // What bears on the work: the IDs the change wrote (its why and what, the lines it added to the task's objects) and,\n // for the backend, the criteria on the checklist. Those are carried whole; the rest the task names, by path.\n const added = work.objects\n .flatMap((key) => {\n const e = entries.get(key);\n return e ? diffLines(forDiff(key, e.before), forDiff(key, e.after)).filter((l) => l.op === '+') : [];\n })\n .map((l) => l.text);\n const written = [ctx.proposal.why ?? '', ctx.proposal.what ?? '', ...added];\n const changed = new Set(work.objects);\n /** Whether the task adds it, so its delta holds it whole. */\n const isNew = (id: string) => changed.has(id) && !entries.get(id)?.exported.before;\n /** An item of a collection, whole when it bears on the work (and isn't whole in the delta already), else by path. */\n const piece = (id: string, bears: boolean): Piece[] => {\n const file = x.fileOf(id);\n const path = file && x.itemShard(file, id);\n if (!path) return [];\n const title = titleOf(x, id);\n const text = bears && !isNew(id) ? sectionText(x, path) : undefined;\n return [\n {\n id,\n path: at(path),\n ...(title ? { title } : {}),\n ...(text ? { text } : {}),\n ...(changed.has(id) ? { changed: true } : {}),\n ...since(id),\n },\n ];\n };\n\n ctx.whereUsed = whereUsed(current, work.objects, entries, changed);\n\n const capabilities = work.objects.filter((k) => /^CAP-/.test(k) && x.fileOf(k) && x.has(x.fileOf(k)!));\n // On either track: the changed criteria on the checklist whole, since their diff shows only the lines that moved; a new one is\n // whole in its delta already. A format 1 export has no checklist, so it gets them all.\n const onList = items && new Set(items);\n ctx.acceptance = capabilities.flatMap((id): Piece[] => {\n const path = x.sectionShard(x.fileOf(id)!, 'Acceptance criteria');\n if (!path) return [];\n const chunks = (sectionText(x, path) ?? '').split(/^(?=### )/m).filter((c) => c.startsWith('### '));\n const existed = new Set([...(entries.get(id)?.before ?? '').matchAll(/^### (\\S+)/gm)].map((m) => m[1]));\n const idOf = (c: string) => c.slice(4).split(/\\s/)[0]!;\n const listed = onList ? chunks.filter((c) => onList.has(idOf(c))) : chunks;\n written.push(...listed);\n const kept = onList ? listed.filter((c) => existed.has(idOf(c))) : chunks;\n const added = listed.length - kept.length;\n const title = titleOf(x, id);\n const rest = [\n added\n ? `${added === 1 ? 'One new criterion is' : `${added} new criteria are`} whole in its delta above.`\n : '',\n chunks.length > listed.length ? `Its other criteria: \\`${at(path)}\\`.` : '',\n ]\n .filter(Boolean)\n .join(' ');\n return [\n {\n id,\n path: at(path),\n ...(title ? { title } : {}),\n ...(kept.length ? { text: kept.join('').trim() } : {}),\n ...(kept.length && rest ? { rest } : {}),\n },\n ];\n });\n if (!ctx.acceptance.length) delete ctx.acceptance;\n\n if (track.kind === 'backend') {\n const named = (kind: 'rule' | 'event') => [\n ...new Set([\n ...work.objects.filter((k) => idsIn(k, [kind]).length === 1 && idsIn(k, [kind])[0] === k),\n ...capabilities.flatMap((c) => idsIn(frontMatterOf(x.read(x.fileOf(c)!)!), [kind])),\n ]),\n ];\n const carried = (kind: 'rule' | 'event') => {\n const bearing = idsIn(written.join('\\n'), [kind]);\n return [...new Set([...named(kind), ...bearing])].flatMap((id) => piece(id, bearing.includes(id)));\n };\n ctx.rules = carried('rule');\n ctx.events = carried('event');\n const whole = (kind: 'nfr' | 'integration') => {\n const bearing = idsIn(written.join('\\n'), [kind]);\n const own = work.objects.filter((k) => idKind(k) === kind);\n return [...new Set([...own, ...bearing])].flatMap((id) => piece(id, true));\n };\n ctx.nfr = whole('nfr');\n ctx.integrations = whole('integration');\n ctx.entities = [\n ...new Set([\n ...work.objects.filter((k) => idKind(k) === 'entity'),\n ...capabilities.flatMap((c) => idsIn(frontMatterOf(x.read(x.fileOf(c)!)!), ['entity'])),\n ]),\n ].flatMap((id): Piece[] => {\n const file = x.fileOf(id);\n if (!file || !x.has(file)) return [];\n const title = titleOf(x, id);\n const note = lifecycleOf(current, id);\n return [\n {\n id,\n path: at(file),\n ...(title ? { title } : {}),\n ...(changed.has(id) ? { changed: true } : {}),\n ...(note ? { note } : {}),\n ...since(id),\n },\n ];\n });\n ctx.operations = current.has(OPERATIONS_FILE)\n ? capabilities.flatMap((id): Piece[] => {\n const path = current\n .shards(OPERATIONS_FILE)\n .find((p) => new RegExp(`/\\\\d{2}-${slug(id)}(-|\\\\.md$)`).test(p));\n return path ? [{ id, path, text: shardText(current, path) }] : [];\n })\n : [];\n } else {\n const existing = (p: string) => (x.has(p) ? at(p) : undefined);\n // The task's screens, and the screens of this channel that perform a capability the task changes (its criteria's\n // Shown is theirs to show).\n const performing = [...x.sources.keys()].filter(\n (id) =>\n /^SCR-/.test(id) &&\n x.has(contractPath(id, track.code)) &&\n idsIn(frontMatterOf(x.read(x.fileOf(id)!) ?? ''), ['capability']).some((c) =>\n capabilities.includes(c),\n ),\n );\n const screens = [\n ...new Set([...work.objects.map(screenOf).filter((s): s is string => !!s), ...performing]),\n ];\n ctx.screens = screens.map((id) => {\n for (const key of [id, `UX-${id}-${track.code}`, `file:${mockupPath(track.code, id)}`]) names.add(key);\n const file = x.fileOf(id);\n return {\n id,\n file: file && at(file),\n contract: existing(contractPath(id, track.code)),\n page: existing(mockupPath(track.code, id)),\n };\n });\n for (const path of [designSystemPath(track.code), patternsPath(track.code)]) names.add(`file:${path}`);\n ctx.design = {\n designSystem: existing(designSystemPath(track.code)),\n patterns: existing(patternsPath(track.code)),\n };\n }\n const bearing = idsIn(written.join('\\n'), ['decision']);\n const named = idsIn(work.objects.map((k) => entries.get(k)?.after ?? '').join('\\n'), ['decision']);\n ctx.decisions = [...new Set([...bearing, ...named])].flatMap((id) => piece(id, bearing.includes(id)));\n // The reach of the rules the task touches or carries whole, and of the roles it touches.\n const rules = [\n ...new Set([\n ...work.objects.filter((k) => idKind(k) === 'rule'),\n ...(ctx.rules ?? []).filter((r) => r.text).map((r) => r.id),\n ]),\n ];\n const roles = work.objects.filter((k) => idKind(k) === 'role');\n ctx.reach = [\n ...rules.map((id) => reachOf(current, id, 'rule', changed)),\n ...roles.map((id) => reachOf(current, id, 'role', changed)),\n ].filter((r): r is Reach => !!r);\n if (!ctx.reach.length) delete ctx.reach;\n if (ctx.reach?.some((r) => r.matrix?.length)) {\n const legend = matrixOf(current).legend;\n if (legend.length) ctx.matrixLegend = legend;\n }\n // The glossary terms the change's text uses, by their exact name (or its plural); a term the task changes is\n // among its objects.\n const glossary = x.fileOf('term:');\n const writtenText = written.join('\\n');\n ctx.terms = (glossary && x.has(glossary) ? x.shards(glossary) : [])\n .filter((path) => !/\\/\\d{2}-[^/]*$/.test(path))\n .flatMap((path): Piece[] => {\n const name = /^## (.+)$/m.exec(shardText(x, path) ?? '')?.[1]?.trim();\n if (!name || changed.has(`term:${name}`)) return [];\n const term = name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n if (!new RegExp(`(?<![\\\\w-])${term}(?:s|es)?(?![\\\\w-])`, 'i').test(writtenText)) return [];\n const text = sectionText(x, path);\n return [{ id: name, path: at(path), ...(text ? { text } : {}), ...since(`term:${name}`) }];\n });\n\n // What later changes did to the objects the brief names: their tasks' work, listed apart.\n const moved = [...names].flatMap((key): ChangedSince[] => {\n const s = x.seen(key);\n if (!s.later.length) return [];\n const now = currentText(current, key);\n const changes = s.later.map((l) => ({\n id: l.change,\n ...(opts.shown && !opts.shown.has(shownKey(key, l.change)) ? { fresh: true } : {}),\n }));\n // What is new since the last read: from the text before the first new change to the export's text now.\n const first = changes.findIndex((ch) => ch.fresh);\n const from =\n first < 0 || s.absent ? undefined : first === 0 ? s.text : textAfter(s.later[first - 1]!.entry);\n let diff: string | undefined;\n if (from !== undefined && now !== undefined) {\n const [a, b] = [forDiff(key, from), forDiff(key, now)];\n const d = unifiedDiff(a, b);\n if (d) diff = clippedDiff(key.startsWith('file:') ? d : withSections(d, a, b));\n }\n const title = key.includes(':') ? undefined : titleOf(current, key);\n const pinned = pinnedPath(x, key);\n // This task's own object: whether a later change removed or reworded a line this change wrote is settled here,\n // from the deltas, so the agent compares nothing.\n const mine = entries.get(key);\n let checked = false;\n let lost: ChangedSince['lost'];\n if (changed.has(key) && mine && !mine.binary && !s.absent) {\n checked = true;\n const wroteBefore = linesOf(key, mine.exported.before ? mine.before : undefined);\n const wrote = [...linesOf(key, mine.exported.after ? mine.after : undefined)].filter(\n (l) => !wroteBefore.has(l),\n );\n lost = s.later.flatMap((l) => {\n if (l.entry.binary) return [];\n const kept = linesOf(key, l.entry.exported.after ? l.entry.after : undefined);\n const gone = [...linesOf(key, l.entry.exported.before ? l.entry.before : undefined)].filter(\n (line) => wrote.includes(line) && !kept.has(line),\n );\n return gone.length ? [{ change: l.change, lines: gone }] : [];\n });\n }\n return [\n {\n key,\n ...(title ? { title } : {}),\n ...(changed.has(key) ? { own: true } : {}),\n changes,\n ...(pinned ? { pinned: at(pinned) } : {}),\n ...(diff ? { diff } : {}),\n ...(now === undefined ? { gone: true } : {}),\n ...(s.absent ? { entered: true } : {}),\n ...(checked ? { checked: true } : {}),\n ...(lost?.length ? { lost } : {}),\n },\n ];\n });\n // With the dispatcher's list (the keys the task cites that changed since), only those; objects that entered the\n // export after the change stay, since the brief shows them as they are now.\n const cited = state.changedSince;\n const kept = cited ? moved.filter((e) => e.entered || cited.has(e.key)) : moved;\n if (cited) {\n const elsewhere = moved.length - kept.length;\n if (elsewhere) ctx.sinceElsewhere = elsewhere;\n if (!kept.some((e) => !e.entered)) ctx.changedSinceNone = true;\n }\n if (kept.length) {\n ctx.changedSince = kept.sort(\n (a, b) => Number(!!b.own) - Number(!!a.own) || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0),\n );\n const touched = new Set(kept.flatMap((e) => e.changes.map((ch) => ch.id)));\n ctx.later = x.work.changes\n .filter((c) => touched.has(c.id))\n .map((c) => {\n const delta = x.proposalPath(c.id)?.replace(/proposal\\.md$/, 'delta.md');\n return {\n id: c.id,\n title: c.title,\n ...((c.tasks ?? []).some((t) => t.track === task.track) ? { task: `${c.id}/${task.track}` } : {}),\n ...(delta ? { delta } : {}),\n };\n });\n }\n return ctx;\n}\n\n/** How the client remembers that a brief showed a later change of an object. */\nexport const shownKey = (key: string, change: string) => `${key}<${change}`;\n\n/** What a brief showed as changed since, to mark what is new at its next read. */\nexport const shownOf = (c: TaskContext): string[] =>\n (c.changedSince ?? []).flatMap((e) => e.changes.map((ch) => shownKey(e.key, ch.id)));\n\n/**\n * The files holding the objects of a brief's \"Changed since\" as the task's change saw them, by export path: what\n * `context` writes to the pin folder so the paths the brief prints can be opened.\n */\nexport function pinFiles(current: ExportReader, c: TaskContext): Map<string, string> {\n const x = pinnedReader(current, c.change.id);\n const out = new Map<string, string>();\n for (const e of c.changedSince ?? []) for (const [path, text] of x.pinnedFiles(e.key)) out.set(path, text);\n return out;\n}\n\nconst textAfter = (e: DeltaEntry) => (e.exported.after ? e.after : undefined);\n\n/** A diff of at most this many lines in the brief; the rest is in the later changes' deltas. */\nconst DIFF_LINES = 40;\n/** The brief shows this many diffs of what is new; the other objects are named. */\nconst NEW_DIFFS = 12;\n/** How many lines of this task's hunks a later change removed are listed per change under \"Checked\". */\nconst LOST_LINES = 8;\nfunction clippedDiff(diff: string): string {\n const lines = diff.split('\\n');\n return lines.length <= DIFF_LINES\n ? diff\n : `${lines.slice(0, DIFF_LINES).join('\\n')}\\n… ${lines.length - DIFF_LINES} more lines: see the changes’ deltas.`;\n}\n\nconst fence = (text: string, lang = '') => {\n const ticks = '`'.repeat(Math.max(3, ...[...text.matchAll(/`+/g)].map((m) => m[0].length + 1)));\n return `${ticks}${lang}\\n${text}\\n${ticks}`;\n};\n\n/**\n * The initiative as the brief opens with it: its prose under one heading (its own title line dropped, its sections a\n * level down), and what it is for.\n */\nfunction initiativeSection(i: NonNullable<TaskContext['initiative']>): string[] {\n const prose = i.body\n .replace(/<!--[^]*?-->/g, '')\n .replace(/^\\s*# .*\\n/, '')\n .replace(/^(#{2,5}) /gm, '#$1 ')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n return [\n `## Initiative: ${i.title}`,\n '',\n `The whole this change is part of (\\`${i.path}\\`): why the work exists. It adds nothing to build beyond the checklist.`,\n '',\n ...(prose ? [prose, ''] : []),\n ];\n}\n\n/** The checklist as the brief shows it: the items, what each is, its weight and whether it is covered. */\nfunction checklistSection(c: TaskContext): string[] {\n const out: string[] = [];\n if (!c.checklist)\n out.push('This export has no checklist (work.json format 1): the task’s progress is its status only.');\n else {\n const list = c.checklist;\n // An item of weight 0 is nothing this track builds: it is read, and counts in neither total.\n const toBuild = list.items.filter((i) => i.weight !== 0);\n const readOnly = list.items.length - toBuild.length;\n const done = toBuild.filter((i) => i.covered).length;\n const weighed = list.items.some((i) => i.weight !== undefined);\n const sum = (items: ChecklistItem[]) => items.reduce((a, i) => a + (i.weight ?? 0), 0);\n const weight = weighed\n ? list.known\n ? `, ${sum(list.items.filter((i) => i.covered))} of ${sum(list.items)} weight`\n : `, ${sum(list.items)} weight`\n : '';\n out.push(\n `## Checklist (${list.known ? `${done} of ${toBuild.length} covered` : `${toBuild.length} item${toBuild.length === 1 ? '' : 's'}`}${weight}${readOnly ? `; ${readOnly} to read only` : ''})`,\n '',\n 'Name an item in `Alterspec-Covers` on the commit with which its tests pass.',\n ...(weighed\n ? [\n 'The weight (w) is how much specified behaviour an item is on this track, reasoned at the sign-off from the spec alone;',\n 'progress and the ETA count weight, not items. Start with the heavy ones.',\n ]\n : []),\n ...(readOnly\n ? [\n 'An item of weight 0 is nothing this track builds (another channel shows it, or it is a mockup file): read it,',\n 'build nothing for it and never name it in `Alterspec-Covers`. If your track does have work for it, say so with `/alterspec-spec-ask`.',\n ]\n : []),\n ...(list.note ? ['', `Covered items unknown: ${list.note}`] : []),\n '',\n ...list.items.map(\n (i) =>\n `- [${i.weight === 0 ? '-' : i.covered ? 'x' : ' '}] \\`${i.item}\\`${i.weight === undefined ? '' : i.weight === 0 ? (i.removedBy ? ` (w 0, removed by ${i.removedBy})` : ' (w 0, nothing to build on this track)') : ` (w ${i.weight})`}: ${i.label ? `**${i.label}** — ` : ''}${i.what}${i.covered ? ` (covered by ${i.covered.slice(0, 12)})` : ''}`,\n ),\n );\n }\n return out;\n}\n\n/**\n * The brief's head and checklist alone, for re-reading during the work: the task's questions and answers and its\n * items; no objects, no \"Changed since\" (so nothing is marked as shown), no paths to open.\n */\nexport function renderChecklist(c: TaskContext): string {\n const out: string[] = [\n `# ${c.task}: ${c.title ?? c.change.title}`,\n '',\n ...(c.summary ? [c.summary, ''] : []),\n ...(c.weight === undefined ? [] : [`Task weight ${c.weight} of 100.`, '']),\n ...shippedLines(c),\n ...(c.questions?.length\n ? questionsSection(c.questions, c.questionsFull ? new Set(c.questionsFull) : undefined)\n : []),\n ...(c.answers?.length ? answersSection(c.answers) : []),\n ...checklistSection(c),\n '',\n `This task’s questions and checklist only; the full brief is \\`alterspec-client context ${c.task}\\`.`,\n ];\n return (\n out\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trimEnd() + '\\n'\n );\n}\n\n/**\n * What the brief says about the change's other tracks (decision 36) and a compatibility: a track that has shipped the\n * change (its tests of the old behaviour fail until this task is done, unless the server keeps it), one building it\n * now, what this change keeps and who ends it, what this task ends. Empty when none applies.\n */\nexport function shippedLines(c: TaskContext): string[] {\n const out: string[] = [];\n const kept = c.compatibility?.kept;\n for (const s of c.siblings ?? []) {\n if (s.status === 'done') {\n const where = [s.commit?.slice(0, 12), s.in_main_at ? 'in main' : (s.branch ?? 'main')]\n .filter(Boolean)\n .join(', ');\n out.push(\n `**${s.track} has shipped this change** (${where})` +\n (kept\n ? ': the server keeps the old behaviour this change’s Compatibility names until the other tracks’ tasks are done (below).'\n : ': tests that check the behaviour it removes or changes are expected to fail until this task is done; updating them is part of this task.'),\n '',\n );\n } else if (s.status === 'in_progress') out.push(`${s.track} is building this change now.`, '');\n }\n if (kept) {\n const ended = kept.endedBy.length\n ? `${kept.endedBy.join(', ')} ends it.`\n : 'The change that ends it is not signed off yet.';\n out.push(\n c.track.kind === 'backend'\n ? `**Compatibility**: ${kept.tracks.join(', ')} build this change too; the server keeps what the proposal’s Compatibility says until their tasks are done. ${ended}`\n : `**Compatibility**: the server keeps the old behaviour (${c.change.id}’s Compatibility) until this task is done. ${ended}`,\n '',\n kept.text,\n '',\n );\n }\n for (const e of c.compatibility?.ends ?? [])\n out.push(\n `**Ends a compatibility**: this task ends the compatibility ${e.change} kept for ${e.tracks.join(', ')}; it is available once their tasks are done. When to deploy it is the team’s call: old app versions stay in use after a task is done.`,\n '',\n );\n return out;\n}\n\n/** The brief as Markdown, for the agent. */\nexport function renderContext(c: TaskContext): string {\n const out: string[] = [\n `# ${c.task}: ${c.title ?? c.change.title}`,\n '',\n // The words the lists show for the task: what a person calls it, never what to build from.\n ...(c.summary ? [c.summary, ''] : []),\n ...(c.title ? [`Change: ${c.change.title}.`, ''] : []),\n ...(c.initiative ? initiativeSection(c.initiative) : []),\n `Track ${c.track.code} (${c.track.kind}${c.track.channels.length ? `: ${c.track.channels.join(', ')}` : ''}). ` +\n `Change ${c.change.id}, signed off ${c.change.signed_off}, level ${c.change.level}. ` +\n (c.weight === undefined ? '' : `Task weight ${c.weight} of 100. `) +\n `Paths are relative to the export, ${c.export}.`,\n ];\n const movedSince = (c.changedSince ?? []).filter((e) => !e.entered);\n if (movedSince.length) {\n const n = movedSince.length;\n const fresh = movedSince.filter((e) => e.changes.some((ch) => ch.fresh)).length;\n out.push(\n '',\n `This brief is the spec as ${c.change.id} saw it at its sign-off. ${n === 1 ? 'One object it names was' : `${n} objects it names were`} changed since by later changes` +\n `${fresh ? ` (${fresh} new since you last read this brief)` : ''}: those are the later changes’ tasks, listed under \"Changed since\" at the end, never this task’s work.` +\n (c.pins ? ` An absolute path under ${c.pins} is such an object as ${c.change.id} saw it.` : ''),\n );\n }\n if (c.after.length) out.push('', `Waits for: ${c.after.map((a) => `${a.change}/${a.track}`).join(', ')}.`);\n if (c.startFrom?.length)\n out.push(\n '',\n `Start from ${c.startFrom.map((s) => `\\`${s.branch}\\` (${s.id}${s.commit ? ` done at ${s.commit.slice(0, 12)}` : ''})`).join(', then ')}, not from the main branch: ` +\n `the predecessor's work is pushed there and not merged yet (fetch it and base your branch on \\`origin/${c.startFrom[c.startFrom.length - 1]!.branch}\\`).`,\n );\n out.push('', ...shippedLines(c));\n if (c.questions?.length)\n out.push(...questionsSection(c.questions, c.questionsFull ? new Set(c.questionsFull) : undefined));\n if (c.answers?.length) out.push(...answersSection(c.answers));\n out.push(...checklistSection(c));\n out.push('', `## Why (${c.proposal.path})`, '', c.proposal.why || '(none written)');\n out.push('', '## What changes', '', c.proposal.what || '(none written)');\n if (c.proposal.dataChange)\n out.push(\n '',\n `## ${DATA_CHANGE_SECTION}`,\n '',\n c.track.kind === 'backend'\n ? 'What the release does once to the records the product already holds; the backend’s `#data-change` item on the checklist.'\n : 'What the release does once to the records the product already holds; the backend’s work, here so the screens read it.',\n '',\n c.proposal.dataChange,\n );\n\n out.push('', '## The task’s objects', '');\n if (c.delta) out.push(`The whole record of the change: ${c.delta}.`, '');\n for (const o of c.objects) {\n const where = o.file\n ? `\\`${o.file}\\`${o.shards ? `, shards in \\`${o.shards}/\\`` : ''}`\n : 'not in the export now';\n const status =\n o.status && o.status.before !== o.status.after\n ? `, ${o.status.before ?? '—'} → ${o.status.after ?? '—'}`\n : '';\n out.push(`### ${o.key}`, '', `${o.change ?? 'no delta entry'}${status}; ${where}.`);\n if (o.unrecoverable) out.push('', `The delta could not recover it: ${o.unrecoverable}.`);\n if (o.since?.changes.length)\n out.push(\n '',\n `Changed since by ${o.since.changes.join(', ')}: their tasks’ work (see \"Changed since\"). Build it as ${c.change.id} left it` +\n `${o.pinned ? `: \\`${o.pinned}\\`` : ''}${o.since.differs ? '' : '; the export’s text equals that again'}.`,\n );\n else if (o.since)\n out.push(\n '',\n 'The export’s text differs from this delta’s after though no later change touched it: build to the export’s file.',\n );\n if (o.diff) out.push('', o.diff.startsWith('@@') ? fence(o.diff, 'diff') : o.diff);\n out.push('');\n }\n\n if (c.whereUsed?.length) {\n out.push(\n '## Where used',\n '',\n 'What the export shows, takes, returns or guards of the entities this task changes, per changed attribute and for the entity as a whole; a screen or capability not in the export isn’t listed.',\n '',\n );\n const list = (ps: Piece[]) =>\n ps.map((p) => `${p.id}${p.changed ? ' (this task changes it)' : ''}`).join(', ');\n for (const w of c.whereUsed) {\n if (w.attribute) {\n const parts = [\n w.screens.length ? `shown on ${list(w.screens)}` : 'no screen shows it',\n w.capabilities.length\n ? `taken or returned by ${list(w.capabilities)}`\n : 'no capability takes or returns it',\n ];\n out.push(`- ${w.entity}.${w.attribute}: ${parts.join('; ')}.`);\n } else {\n const parts = [\n w.screens.length ? `shown on ${list(w.screens)}` : 'no screen shows it',\n w.capabilities.length ? `worked with by ${list(w.capabilities)}` : 'no capability works with it',\n w.rules.length ? `rules about it: ${list(w.rules)}` : 'no rule about it',\n ];\n out.push(`- ${w.entity}: ${parts.join('; ')}.`);\n }\n }\n out.push('');\n }\n\n if (c.reach?.length) {\n out.push(\n '## Reach',\n '',\n 'Where the export enforces, holds or shows the rules and roles this task touches or names; a capability or screen not in the export isn’t listed.',\n '',\n );\n if (c.matrixLegend?.length)\n out.push(\n `Under a rule, its row of the rule matrix (\\`${RULE_MATRIX_FILE}\\`), so the matrix need not be opened. How to read it:`,\n '',\n ...c.matrixLegend,\n '',\n );\n const list = (ps: (Piece & { scope?: string })[]) =>\n ps\n .map((p) => `${p.id}${p.scope ? ` (${p.scope})` : ''}${p.changed ? ' (this task changes it)' : ''}`)\n .join(', ');\n for (const r of c.reach) {\n const name = `${r.id}${r.title ? ` ${r.title}` : ''}`;\n if (r.kind === 'rule') {\n const parts = [\n r.capabilities.length ? `enforced by ${list(r.capabilities)}` : 'no capability lists it',\n r.criteria?.length ? `covered by ${r.criteria.join(', ')}` : 'no criterion covers it',\n r.screens.length ? `on ${list(r.screens)}` : 'on no screen',\n ];\n out.push(`- ${name}: ${parts.join('; ')}.`);\n for (const line of r.matrix ?? []) out.push(` ${line}`);\n } else {\n const parts = [\n r.capabilities.length ? `may perform ${list(r.capabilities)}` : 'may perform no capability',\n r.screens.length ? `on ${list(r.screens)}` : 'on no screen',\n ];\n out.push(`- ${name}: ${parts.join('; ')}.`);\n }\n }\n out.push('');\n }\n\n const pieces = (title: string, list: Piece[] | undefined, intro?: string) => {\n if (!list?.length) return;\n out.push(`## ${title}`, '');\n if (intro) out.push(intro, '');\n const moved = (p: Piece) =>\n !p.since?.length\n ? ''\n : p.entered\n ? `signed off since, by ${p.since.join(', ')}; here as the export holds it now`\n : `changed since by ${p.since.join(', ')}; here as ${c.change.id} saw it`;\n for (const p of list.filter((p) => p.text))\n out.push(\n `### ${p.id}${p.title ? ` ${p.title}` : ''} (\\`${p.path}\\`)`,\n '',\n ...(moved(p) ? [`(${moved(p)})`, ''] : []),\n p.text!,\n ...(p.rest ? ['', p.rest] : []),\n '',\n );\n for (const p of list.filter((p) => !p.text))\n out.push(\n `- ${p.id}${p.title ? ` ${p.title}` : ''}: \\`${p.path}\\`${p.changed ? ' (this task changes it: its delta is above)' : ''}${p.note ? `; ${p.note}` : ''}${moved(p) ? ` (${moved(p)})` : ''}`,\n );\n out.push('');\n };\n pieces(\n 'Acceptance criteria',\n c.acceptance,\n c.checklist\n ? 'The changed criteria on the checklist, whole (new ones are whole in the delta above); the rest by shard.'\n : undefined,\n );\n pieces(\n 'Rules',\n c.rules,\n 'The rules the checklist’s criteria or the change’s text name, whole; the others the capabilities name, by path.',\n );\n pieces(\n 'Events',\n c.events,\n 'The events the checklist’s criteria or the change’s text name, whole; the others the capabilities name, by path.',\n );\n pieces(\n 'Entities',\n c.entities,\n 'The entities the task’s capabilities work with, each with its lifecycle; open one for its attributes.',\n );\n pieces(\n 'Quality requirements',\n c.nfr,\n 'The quality requirements the task touches or the change’s text names, whole (one the task adds is whole in its delta above).',\n );\n pieces(\n 'Integrations',\n c.integrations,\n 'The integrations the task touches or the change’s text names, whole (one the task adds is whole in its delta above).',\n );\n pieces('Operations for other systems', c.operations);\n pieces(\n 'Decisions',\n c.decisions,\n 'The decisions the change’s text names, whole; the others its objects name, by path.',\n );\n pieces('Terms', c.terms, 'The glossary terms the change’s text uses.');\n\n if (c.screens?.length) {\n out.push('## Screens', '');\n for (const s of c.screens) {\n out.push(`- **${s.id}**: \\`${s.file ?? 'not in the export'}\\``);\n if (s.contract) out.push(` - experience contract: \\`${s.contract}\\``);\n if (s.page) out.push(` - mockup page: \\`${s.page}\\``);\n }\n out.push('');\n if (c.design?.designSystem || c.design?.patterns)\n out.push(\n '## The channel’s design',\n '',\n ...[c.design.designSystem, c.design.patterns].filter(Boolean).map((p) => `- \\`${p}\\``),\n '',\n );\n }\n if (c.changedSinceNone && !movedSince.length)\n out.push(\n '## Changed since (other tasks’ work)',\n '',\n `No part of this task changed (the dispatcher’s list).${c.sinceElsewhere ? ` ${c.sinceElsewhere === 1 ? 'One other object' : `${c.sinceElsewhere} other objects`} the brief names ${c.sinceElsewhere === 1 ? 'was' : 'were'}, in other tasks’ work.` : ''}`,\n '',\n );\n if (c.changedSince?.length) {\n if (!(c.changedSinceNone && !movedSince.length)) out.push('## Changed since (other tasks’ work)', '');\n if (c.sinceElsewhere && movedSince.length)\n out.push(\n `Only the objects this task cites (the dispatcher’s list); ${c.sinceElsewhere === 1 ? 'one other object' : `${c.sinceElsewhere} other objects`} the brief names ${c.sinceElsewhere === 1 ? 'was' : 'were'} changed in other tasks’ work.`,\n '',\n );\n const names = (e: ChangedSince) =>\n `${e.key}${e.title ? ` ${e.title}` : ''}${e.own ? ' (this task changes it)' : ''}`;\n if (movedSince.length) {\n out.push(\n `Later changes touched what this brief names. Build this task to the text above: what a later change added is built in its own task.` +\n (movedSince.some((e) => e.own)\n ? ' For the objects this task changes, whether a later change removed or reworded a line of this task’s hunks is checked here, under \"Checked\": compare nothing yourself.'\n : ''),\n '',\n ...(c.later ?? []).map(\n (l) =>\n `- ${l.id}${l.title ? ` \"${l.title}\"` : ''}: ${l.task ? `its task ${l.task}` : 'no task on this track'}${l.delta ? `; \\`${l.delta}\\`` : ''}`,\n ),\n '',\n 'What each touched, in the order it did:',\n '',\n ...movedSince.map(\n (e) =>\n `- ${names(e)}: ${e.changes.map((ch) => `${ch.fresh ? '**new** ' : ''}${ch.id}`).join(', ')}${e.gone ? '; the export no longer holds it' : ''}`,\n ),\n '',\n );\n const own = movedSince.filter((e) => e.own);\n if (own.length)\n out.push(\n 'Checked: this task’s own lines against the later changes’ deltas.',\n '',\n ...own.map((e) => {\n if (!e.checked)\n return `- ${names(e)}: not checked (a binary file, or the export did not hold it then): compare the pinned file with the export’s.`;\n if (!e.lost?.length)\n return `- ${names(e)}: no line of this task’s hunks was removed or reworded by ${e.changes.map((ch) => ch.id).join(', ')}. Build it as the brief says.`;\n return [\n `- ${names(e)}: build these lines as the later change says, not as the brief has them, and say so in the commit’s body:`,\n ...e.lost.flatMap((l) => [\n ` - ${l.change} removed or reworded ${l.lines.length === 1 ? 'one line' : `${l.lines.length} lines`}:`,\n ...l.lines.slice(0, LOST_LINES).map((line) => ` - \\`${line.replace(/`/g, \"'\")}\\``),\n ...(l.lines.length > LOST_LINES\n ? [` - and ${l.lines.length - LOST_LINES} more (see its delta)`]\n : []),\n ]),\n ].join('\\n');\n }),\n '',\n );\n const fresh = movedSince.filter((e) => e.diff);\n if (fresh.length) {\n out.push(\n 'New since you last read this brief, from what it showed then to the export’s text now:',\n '',\n );\n for (const e of fresh.slice(0, NEW_DIFFS))\n out.push(`### ${names(e)}`, '', fence(e.diff!, 'diff'), '');\n if (fresh.length > NEW_DIFFS)\n out.push(\n `And ${fresh.length - NEW_DIFFS} more: ${fresh\n .slice(NEW_DIFFS)\n .map((e) => e.key)\n .join(', ')} (see the changes’ deltas).`,\n '',\n );\n }\n }\n const entered = c.changedSince.filter((e) => e.entered);\n if (entered.length)\n out.push(\n `Signed off after ${c.change.id}, so the export never held them as it saw them; the brief shows them as the export holds them now:`,\n '',\n ...entered.map((e) => {\n const [first, ...rest] = e.changes;\n const task = c.later?.find((l) => l.id === first!.id)?.task;\n return `- ${names(e)}: in the export since ${first!.id}${task ? ` (its task ${task})` : ''}${rest.length ? `, changed after by ${rest.map((ch) => ch.id).join(', ')}` : ''}`;\n }),\n '',\n );\n }\n return (\n out\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trimEnd() + '\\n'\n );\n}\n\n/**\n * The brief's size by section, for measuring it: characters and an estimate of tokens (a quarter of the characters,\n * the usual rule of thumb for English; a tokenizer counts a little differently).\n */\nexport function contextStats(markdown: string): string {\n const sections = markdown.split(/^(?=## )/m).map((part, i) => ({\n name: i === 0 ? '(heading)' : part.split('\\n')[0]!.slice(3),\n chars: part.length,\n }));\n const width = Math.max(...sections.map((x) => x.name.length), 'Total'.length);\n const row = (name: string, chars: number) =>\n `${name.padEnd(width)} ${String(Math.ceil(chars / 4)).padStart(7)} ${String(chars).padStart(8)}`;\n return (\n [\n `${'Section'.padEnd(width)} ${'~tokens'.padStart(7)} ${'chars'.padStart(8)}`,\n ...sections.map((x) => row(x.name, x.chars)),\n row('Total', markdown.length),\n ].join('\\n') + '\\n'\n );\n}\n","import { execFileSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { type TaskRef, folderOf } from './task.js';\n\n/**\n * What `context` keeps on disk for a brief (client 0.19.0): the files of the objects later changes touched, as the\n * task's change saw them, under `.alterspec-client/pins/<chg>-<track>/` in the folder that holds the configuration\n * (a few small files at their export paths, rewritten on every run, never to be committed), and, in the\n * repository's git folder next to the progress state, which later changes the brief already showed.\n */\n\nexport const PINS_DIR = '.alterspec-client/pins';\n\nexport const pinsDir = (root: string, task: TaskRef) => join(root, PINS_DIR, folderOf(task));\n\n/** Replace a task's pinned files; an empty set removes its folder. */\nexport function writePins(dir: string, files: ReadonlyMap<string, string>): void {\n rmSync(dir, { recursive: true, force: true });\n if (!files.size) return;\n const root = dirname(dir);\n mkdirSync(root, { recursive: true });\n // The folder ignores itself, so nothing in it is committed whatever the repository's own rules are.\n if (!existsSync(join(root, '.gitignore'))) writeFileSync(join(root, '.gitignore'), '*\\n');\n for (const [path, text] of files) {\n const to = join(dir, path);\n mkdirSync(dirname(to), { recursive: true });\n writeFileSync(to, text);\n }\n}\n\nfunction shownPath(repo: string, task: TaskRef): string | undefined {\n try {\n const common = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], {\n cwd: repo,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim();\n return common ? join(common, 'alterspec-client', `seen-${folderOf(task)}.json`) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** What the brief's earlier reads showed as changed since; undefined before its first read, or outside a repository. */\nexport function readShown(repo: string, task: TaskRef): Set<string> | undefined {\n const path = shownPath(repo, task);\n if (!path || !existsSync(path)) return undefined;\n try {\n const data = JSON.parse(readFileSync(path, 'utf8')) as { shown?: unknown };\n return new Set(\n Array.isArray(data.shown) ? data.shown.filter((s): s is string => typeof s === 'string') : [],\n );\n } catch {\n return undefined;\n }\n}\n\n/** Remember what this read showed, with what earlier reads did; never fails the command. */\nexport function writeShown(repo: string, task: TaskRef, shown: readonly string[], now = new Date()): void {\n const path = shownPath(repo, task);\n if (!path) return;\n try {\n const all = [...new Set([...(readShown(repo, task) ?? []), ...shown])].sort();\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify({ shown: all, at: now.toISOString() }) + '\\n');\n } catch {\n // a read-only repository: the next read marks the same changes as new again\n }\n}\n","/**\n * A task is one change on one track, written `CHG-012/BE` (spec 2), or one bug on one track, `BUG-3/BE` (spec 8.5).\n * Its branch is `task/chg-012-be` and its commits carry the trailer `Alterspec-Task: CHG-012/BE` (spec 12.2); only\n * the client spells either.\n */\n\nexport interface TaskRef {\n id: string;\n /** The change (`CHG-012`) or the bug (`BUG-3`) the task is of. */\n change: string;\n track: string;\n kind: 'change' | 'bug';\n}\n\nexport const TRAILER = 'Alterspec-Task';\n\nexport class TaskError extends Error {}\n\nexport function parseTask(text: string): TaskRef {\n const m = /^(CHG-\\d{3}|BUG-[1-9]\\d*)\\/([A-Z]{2,5})$/.exec(text.trim().toUpperCase());\n if (!m)\n throw new TaskError(\n `\"${text}\" is not a task: write it as CHG-012/BE (the change, a slash, the track), or BUG-3/BE for a bug's.`,\n );\n return {\n id: `${m[1]}/${m[2]}`,\n change: m[1]!,\n track: m[2]!,\n kind: m[1]!.startsWith('BUG-') ? 'bug' : 'change',\n };\n}\n\nexport const branchOf = (t: TaskRef) => `task/${t.change.toLowerCase()}-${t.track.toLowerCase()}`;\nexport const folderOf = (t: TaskRef) => `${t.change.toLowerCase()}-${t.track.toLowerCase()}`;\nexport const trailerOf = (t: TaskRef) => `${TRAILER}: ${t.id}`;\n\n/** The trailer naming the items a commit covers once their tests pass (spec 8.1): `Alterspec-Covers: A, B`. */\nexport const COVERS = 'Alterspec-Covers';\n\n/** The task whose branch this is (`task/chg-012-be` → `CHG-012/BE`), or undefined for any other branch. */\nexport function taskOfBranch(branch: string | undefined): TaskRef | undefined {\n const m = /^task\\/(chg-\\d{3}|bug-[1-9]\\d*)-([a-z]{2,5})$/.exec(branch?.trim() ?? '');\n return m ? parseTask(`${m[1]}/${m[2]}`) : undefined;\n}\n","import { execFileSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { type TaskRef, TRAILER, branchOf } from './task.js';\n\n/**\n * The git reading of the client (spec 12.2), with git only, whatever hosts the repositories: the export clone's head\n * and the commit to send the dispatcher, and the commit that brought a task into the track's main branch. The client\n * makes no branch, worktree or commit in the developer's repository (0.14.0): where and how they work is theirs.\n */\n\nexport class GitError extends Error {}\n\nfunction git(cwd: string, args: string[]): string {\n try {\n return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();\n } catch (e) {\n const stderr = String((e as { stderr?: unknown }).stderr ?? '').trim();\n throw new GitError(`git ${args.join(' ')} failed in ${cwd}${stderr ? `: ${stderr}` : ''}`);\n }\n}\n\nconst tryGit = (cwd: string, args: string[]): string | undefined => {\n try {\n return git(cwd, args);\n } catch {\n return undefined;\n }\n};\n\nconst isAncestor = (cwd: string, a: string, b: string) =>\n tryGit(cwd, ['merge-base', '--is-ancestor', a, b]) !== undefined;\n\nexport interface ExportHead {\n /** The clone's `HEAD` after the pull. */\n head: string;\n /** Whether `git pull --ff-only` succeeded. */\n pulled: boolean;\n /** The dispatcher's `latest_export`, when given. */\n latest?: string;\n /** The commit to send as `next_task`'s `export`. */\n send: string;\n /** Commits `HEAD` is behind `latest_export` (the pull failed); null when the clone doesn't have it to count. */\n behind: number | null;\n}\n\n/**\n * Pull the export clone and say which commit to send: `HEAD` when the dispatcher knows it or knows more,\n * `latest_export` when `HEAD` is ahead of it (pulled before the ingest finished). Refuses when neither is an\n * ancestor of the other: the export's history was rewritten.\n */\nexport function exportHead(dir: string, latest?: string): ExportHead {\n if (!existsSync(join(dir, '.git')) && tryGit(dir, ['rev-parse', '--git-dir']) === undefined)\n throw new GitError(`${dir} is not a clone of the export repository.`);\n const pulled = tryGit(dir, ['pull', '--ff-only', '--quiet']) !== undefined;\n const head = git(dir, ['rev-parse', 'HEAD']);\n if (!latest) return { head, pulled, send: head, behind: 0 };\n const known = tryGit(dir, ['rev-parse', '--verify', '--quiet', `${latest}^{commit}`]);\n if (!known) {\n if (!pulled) return { head, pulled, latest, send: head, behind: null };\n throw rewritten(latest);\n }\n if (known === head) return { head, pulled, latest, send: head, behind: 0 };\n if (isAncestor(dir, known, head)) return { head, pulled, latest, send: known, behind: 0 };\n if (isAncestor(dir, head, known))\n return {\n head,\n pulled,\n latest,\n send: head,\n behind: Number(git(dir, ['rev-list', '--count', `${head}..${known}`])),\n };\n throw rewritten(latest);\n}\n\nconst rewritten = (latest: string) =>\n new GitError(\n `The export's history was rewritten: the dispatcher's latest export ${latest.slice(0, 12)} and your clone don't follow each other. Stop and tell an admin.`,\n );\n\n/** The track's main branch: the configured one, else the remote's `HEAD`, else `main`. */\nexport function mainBranch(repo: string, configured?: string): string {\n if (configured) return configured;\n const head = tryGit(repo, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD']);\n return head?.replace(/^origin\\//, '') || 'main';\n}\n\nconst escape = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\/]/g, '\\\\$&');\n\nexport interface Merged {\n /** The commit to report `done` with. */\n commit: string;\n /** The pushed task branch the commit is the head of; absent when the commit is on the track's main branch. */\n branch?: string;\n}\n\n/**\n * What to report `done` with: the head of the pushed task branch `origin/task/<chg>-<track>` while it isn't in the\n * main branch yet (with the branch), else the commit on `origin/<main>` that brought the task in (no branch), else\n * the pushed head again (merged some other way). Undefined while the branch isn't pushed and nothing is merged.\n */\nexport function mergedCommit(repo: string, task: TaskRef, main: string): Merged | undefined {\n const branch = branchOf(task);\n tryGit(repo, ['fetch', '--quiet', 'origin', main]);\n // Fetched apart: one fetch of both would bring neither while the branch isn't pushed.\n tryGit(repo, ['fetch', '--quiet', 'origin', branch]);\n const target = `origin/${main}`;\n if (!tryGit(repo, ['rev-parse', '--verify', '--quiet', target]))\n throw new GitError(`There is no ${target} here: is \"${main}\" the track's main branch?`);\n const pushed = tryGit(repo, ['rev-parse', '--verify', '--quiet', `origin/${branch}^{commit}`]);\n if (pushed && !isAncestor(repo, pushed, target)) return { commit: pushed, branch };\n const merged = mergedInto(repo, task, target);\n if (merged) return { commit: merged };\n return pushed ? { commit: pushed, branch } : undefined;\n}\n\n/**\n * The commit on `origin/<main>` that brought the task in: on the branch's first-parent history, the newest commit\n * carrying the trailer `Alterspec-Task: <task>` (a squash, rebase or direct commit) or the merge of the branch\n * `task/<chg>-<track>` (GitHub's \"Merge pull request #1 from owner/task/…\", Bitbucket's \"Merged in task/…\", git's\n * \"Merge branch 'task/…'\"); else the first-parent commit that brought in a commit carrying the trailer. Undefined\n * while the work isn't on the main branch.\n */\nfunction mergedInto(repo: string, task: TaskRef, target: string): string | undefined {\n const trailer = new RegExp(`^${TRAILER}:\\\\s*${escape(task.id)}\\\\s*$`, 'mi');\n const branch = new RegExp(`(^|[\\\\s'\"/:])${escape(branchOf(task))}($|[\\\\s'\".,)])`, 'm');\n const log = git(repo, ['log', '--first-parent', '--format=%H%x1f%P%x1f%B%x1e', target]);\n for (const record of log.split('\\x1e')) {\n const [sha, parents, body] = record.trim().split('\\x1f');\n if (!sha || body === undefined) continue;\n if (trailer.test(body)) return sha;\n if (parents!.trim().includes(' ') && branch.test(body)) return sha;\n }\n const carrying = git(repo, ['log', '--format=%H', '-F', `--grep=${TRAILER}: ${task.id}`, target])\n .split('\\n')\n .filter(Boolean)\n .find((sha) => trailer.test(git(repo, ['show', '-s', '--format=%B', sha])));\n if (!carrying) return undefined;\n return git(repo, [\n 'rev-list',\n '--first-parent',\n '--ancestry-path',\n '--reverse',\n `${carrying}..${target}`,\n ]).split('\\n')[0];\n}\n","import { spawnSync } from 'node:child_process';\nimport {\n existsSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n realpathSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { type InstallResult, install } from '../../src/install/installer.js';\nimport type { PlannedFile } from '../../src/install/manifest.js';\nimport {\n CONFIG_FILE,\n type ClientConfig,\n ClientConfigSchema,\n ConfigError,\n isProduct,\n readConfigAt,\n writeConfig,\n} from './config.js';\nimport type { Role } from './role.js';\n\n/**\n * `init` (spec 12.1): the configuration, the `dispatcher` server in `.mcp.json` and its approval in the git-ignored\n * `.claude/settings.local.json`, the progress hook in `.claude/settings.json` and the skills and the answerer agent\n * with their prompts,\n * installed through alterspec's own installer (manifest, wrapper policy, removal of what an older version installed).\n *\n * `init --product` (spec 8.6, 12.4), in the spec project: the configuration with `dispatcher` and `key` only, the\n * server in `.mcp.json` and its approval, and nothing of the developer's: no hook, no skill, no prompt, no manifest.\n */\n\n/** The shipped skills and prompts, one level above both src/ (tests) and dist/ (built CLI). */\nexport const ASSETS_DIR = fileURLToPath(new URL('../assets', import.meta.url));\nexport const CLIENT_DIR = '.alterspec-client';\nexport const PROMPTS_DIR = `${CLIENT_DIR}/prompts`;\nexport const MANIFEST_PATH = `${CLIENT_DIR}/manifest.json`;\nexport const MCP_JSON = '.mcp.json';\n/** The server Claude Code starts: tools appear as `mcp__dispatcher__<tool>`. */\nexport const MCP_SERVER = 'dispatcher';\nexport const PACKAGE = '@alterset/alterspec-client';\n/** The invocation as the shipped skills and prompts spell it; `init` puts the project's npx flags into it. */\nexport const INVOCATION = `npx ${PACKAGE}`;\nexport const invocation = (npxArgs: string[] = []) => ['npx', ...npxArgs, PACKAGE].join(' ');\nexport const mcpEntry = (npxArgs: string[] = []) => ({ command: 'npx', args: [...npxArgs, PACKAGE, 'mcp'] });\nexport const MCP_ENTRY = mcpEntry();\n\nfunction walk(dir: string): string[] {\n return readdirSync(dir)\n .sort()\n .flatMap((n) => (statSync(join(dir, n)).isDirectory() ? walk(join(dir, n)) : [join(dir, n)]));\n}\n\nconst assetFiles = (sub: string) =>\n walk(join(ASSETS_DIR, sub)).map((f) => ({\n rel: relative(join(ASSETS_DIR, sub), f).split('\\\\').join('/'),\n content: readFileSync(f, 'utf8'),\n }));\n\n/**\n * What `init` installs. With npx flags of the project's (`npx.args` in its configuration) every invocation in the\n * skills and prompts carries them: a skill's `allowed-tools` pattern is matched as written, so the plain one would\n * not allow the command the project has to run. The manifest hashes this content, so it needs nothing more.\n */\nexport function buildClientPlan(version: string, npxArgs: string[] = []): PlannedFile[] {\n const plan = clientPlan(version);\n if (!npxArgs.length) return plan;\n return plan.map((f) => ({ ...f, content: f.content.split(INVOCATION).join(invocation(npxArgs)) }));\n}\n\nfunction clientPlan(version: string): PlannedFile[] {\n return [\n ...assetFiles('skills').map((f) => ({\n path: `.claude/skills/${f.rel}`,\n content: f.content,\n policy: 'wrapper' as const,\n })),\n ...assetFiles('agents').map((f) => ({\n path: `.claude/agents/${f.rel}`,\n content: f.content,\n policy: 'wrapper' as const,\n })),\n ...assetFiles('prompts').map((f) => ({\n path: `${PROMPTS_DIR}/${f.rel}`,\n content: f.content,\n policy: 'framework' as const,\n })),\n { path: `${CLIENT_DIR}/version`, content: `${version}\\n`, policy: 'framework' },\n ];\n}\n\nexport type Outcome = 'created' | 'updated' | 'unchanged';\n\n/** The `dispatcher` entry in `.mcp.json`, every other server kept. */\nexport function writeMcpJson(root: string, npxArgs: string[] = []): Outcome {\n const path = join(root, MCP_JSON);\n let data: { mcpServers?: Record<string, unknown> } & Record<string, unknown> = {};\n const before = existsSync(path) ? readFileSync(path, 'utf8') : undefined;\n if (before !== undefined)\n try {\n data = JSON.parse(before) as typeof data;\n } catch {\n throw new ConfigError(`${path} is not valid JSON: fix it, then run init again.`);\n }\n data.mcpServers = { ...(data.mcpServers ?? {}), [MCP_SERVER]: mcpEntry(npxArgs) };\n const after = JSON.stringify(data, null, 2) + '\\n';\n if (after === before) return 'unchanged';\n writeFileSync(path, after);\n return before === undefined ? 'created' : 'updated';\n}\n\nexport const CLAUDE_SETTINGS = '.claude/settings.json';\n/** The hook that reports progress after a commit (spec 12.1); found again by its command. */\nexport const hookEntry = (npxArgs: string[] = []) => ({\n type: 'command',\n if: 'Bash(git commit *)',\n command: `${invocation(npxArgs)} progress --hook`,\n timeout: 60,\n async: true,\n});\nexport const HOOK_ENTRY = hookEntry();\nexport const HOOK_COMMAND = HOOK_ENTRY.command;\n\ntype HookGroup = { matcher?: string; hooks?: Record<string, unknown>[] } & Record<string, unknown>;\nconst isOurs = (h: Record<string, unknown>) =>\n typeof h.command === 'string' && h.command.includes(`${PACKAGE} progress`);\n\n/**\n * The client's hook in `.claude/settings.json`: after Claude Code runs `git commit`, `progress --hook` in the\n * background. Merged: its own entry is replaced where it is, else added as a group of its own; nothing else changes.\n */\nexport function writeClaudeSettings(root: string, npxArgs: string[] = []): Outcome {\n const entry = hookEntry(npxArgs);\n const path = join(root, CLAUDE_SETTINGS);\n const before = existsSync(path) ? readFileSync(path, 'utf8') : undefined;\n let data: { hooks?: Record<string, unknown> } & Record<string, unknown> = {};\n if (before !== undefined)\n try {\n data = JSON.parse(before) as typeof data;\n } catch {\n throw new ConfigError(`${path} is not valid JSON: fix it, then run init again.`);\n }\n const hooks = (data.hooks ??= {});\n const groups = (hooks.PostToolUse ??= []) as HookGroup[];\n let found = false;\n for (const group of groups)\n group.hooks = group.hooks?.flatMap((h) => {\n if (!isOurs(h)) return [h];\n if (found) return [];\n found = true;\n return [entry];\n });\n if (!found) groups.push({ matcher: 'Bash', hooks: [entry] });\n const after = JSON.stringify(data, null, 2) + '\\n';\n if (before !== undefined && JSON.stringify(JSON.parse(before)) === JSON.stringify(data)) return 'unchanged';\n mkdirSync(join(root, '.claude'), { recursive: true });\n writeFileSync(path, after);\n return before === undefined ? 'created' : 'updated';\n}\n\nexport const CLAUDE_LOCAL_SETTINGS = '.claude/settings.local.json';\n\n/**\n * The approval of the `dispatcher` server in `.claude/settings.local.json`: Claude Code loads a server of a project's\n * `.mcp.json` only once approved, and honours an approval there only while git doesn't track the file. Merged: the\n * name is added to `enabledMcpjsonServers`, nothing else changes.\n */\nexport function writeLocalSettings(root: string): Outcome {\n const path = join(root, CLAUDE_LOCAL_SETTINGS);\n const before = existsSync(path) ? readFileSync(path, 'utf8') : undefined;\n let data: { enabledMcpjsonServers?: unknown } & Record<string, unknown> = {};\n if (before !== undefined)\n try {\n data = JSON.parse(before) as typeof data;\n } catch {\n throw new ConfigError(`${path} is not valid JSON: fix it, then run init again.`);\n }\n const enabled = Array.isArray(data.enabledMcpjsonServers) ? (data.enabledMcpjsonServers as unknown[]) : [];\n if (before !== undefined && enabled.includes(MCP_SERVER)) return 'unchanged';\n data.enabledMcpjsonServers = [...enabled, MCP_SERVER];\n mkdirSync(join(root, '.claude'), { recursive: true });\n writeFileSync(path, JSON.stringify(data, null, 2) + '\\n');\n return before === undefined ? 'created' : 'updated';\n}\n\n/**\n * The approval in the checkout a command runs in, when that is not the one holding the configuration: a task\n * worktree the developer made has what git tracks (`.mcp.json` declares the server) but not the git-ignored\n * approval, so Claude Code there would not load the dispatcher. Written only where `.mcp.json` exists, and never\n * through a `.claude` link that points nowhere; `unchanged` everywhere else, so the main checkout is never touched\n * here (0.14.0: the client makes no worktree, it only makes the ones the developer makes work).\n */\nexport function approveHere(configRoot: string, cwd = process.cwd()): { root: string; outcome: Outcome } {\n const top = spawnSync('git', ['rev-parse', '--show-toplevel'], {\n cwd,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).stdout?.trim();\n const same = (a: string, b: string) => {\n try {\n return realpathSync(a) === realpathSync(b);\n } catch {\n return a === b;\n }\n };\n if (!top || same(top, configRoot)) return { root: configRoot, outcome: 'unchanged' };\n if (!existsSync(join(top, MCP_JSON))) return { root: top, outcome: 'unchanged' };\n const claude = join(top, '.claude');\n try {\n if (lstatSync(claude).isSymbolicLink() && !existsSync(claude)) return { root: top, outcome: 'unchanged' };\n } catch {\n // no .claude yet: writeLocalSettings makes it\n }\n return { root: top, outcome: writeLocalSettings(top) };\n}\n\n/**\n * Whether git keeps `.claude/settings.local.json` out: `ignored` already, `added` to `.gitignore` now, `tracked`\n * (committed, so Claude Code ignores its approval), or `unknown` (no git repository, or `.claude` is a symlink git\n * can't look through).\n */\nexport type IgnoreOutcome = 'ignored' | 'added' | 'tracked' | 'unknown';\n\nexport function ignoreLocalSettings(root: string): IgnoreOutcome {\n const git = (...args: string[]) =>\n spawnSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).status;\n if (git('ls-files', '--error-unmatch', CLAUDE_LOCAL_SETTINGS) === 0) return 'tracked';\n const status = git('check-ignore', '-q', CLAUDE_LOCAL_SETTINGS);\n if (status === 0) return 'ignored';\n if (status !== 1) return 'unknown';\n const path = join(root, '.gitignore');\n const before = existsSync(path) ? readFileSync(path, 'utf8') : '';\n writeFileSync(path, `${before}${before && !before.endsWith('\\n') ? '\\n' : ''}${CLAUDE_LOCAL_SETTINGS}\\n`);\n return 'added';\n}\n\nexport interface InitOptions extends Partial<ClientConfig> {\n force?: boolean;\n /** The product side's set-up (spec 8.6): a dispatcher and a key, nothing of the developer's. */\n product?: boolean;\n}\n\nexport interface InitResult {\n /** What the repository is set up as; a product configuration is one without `export`. */\n role: Role;\n config: Outcome;\n mcp: Outcome;\n /** `none` for the product side, which gets no hook. */\n hook: Outcome | 'none';\n approval: Outcome;\n ignore: IgnoreOutcome;\n files: InstallResult;\n}\n\nconst NO_FILES: InstallResult = {\n created: [],\n updated: [],\n unchanged: [],\n kept: [],\n outdated: [],\n conflicts: [],\n removed: [],\n};\n\n/** The configuration as the file holds it: no empty `tracks` on the product side, no `npx` without flags. */\nfunction written(config: ClientConfig): ClientConfig {\n const out: ClientConfig = { ...config };\n if (!out.npx?.args.length) delete out.npx;\n if (isProduct(out) && !out.tracks.length) delete (out as Partial<ClientConfig>).tracks;\n return out;\n}\n\n/** Write what `init` writes; running it again with the same options changes nothing. */\nexport function initClient(root: string, opts: InitOptions, version: string): InitResult {\n const { force, product: asked, ...given } = opts;\n const existing = readConfigAt(root);\n const defined = Object.fromEntries(Object.entries(given).filter(([, v]) => v !== undefined));\n const developerFlags = given.export !== undefined || (given.tracks?.length ?? 0) > 0;\n // One key, one role (spec decision 29): a repository is set up for a developer or for the product side, and\n // `init` never turns one into the other in passing.\n if (asked && developerFlags)\n throw new ConfigError(\n 'init --product takes no --export and no --track: the product side has no export and builds no track.',\n );\n if (asked && existing && !isProduct(existing))\n throw new ConfigError(\n `This repository is set up for a developer (${CONFIG_FILE} has an export): remove that configuration first if it is to be the product side's.`,\n );\n if (!asked && existing && isProduct(existing) && developerFlags)\n throw new ConfigError(\n `This repository is set up for the product side (${CONFIG_FILE} has no export): remove that configuration first if a developer is to use it.`,\n );\n const product = asked || (existing !== undefined && isProduct(existing));\n const parsed = ClientConfigSchema.safeParse({ ...existing, ...defined });\n if (!parsed.success) {\n const missing = parsed.error.issues.map((i) => i.path.join('.')).filter(Boolean);\n throw new ConfigError(\n existing\n ? `The configuration would not be valid: ${parsed.error.issues.map((i) => `${i.path.join('.')} ${i.message}`).join('; ')}.`\n : product\n ? `init --product needs --dispatcher <url>${missing.length ? ` (missing or wrong: ${missing.join(', ')})` : ''}.`\n : `init needs --dispatcher <url> and --export <path to your clone of the export>${missing.length ? ` (missing or wrong: ${missing.join(', ')})` : ''}.`,\n );\n }\n if (!product && parsed.data.export === undefined)\n throw new ConfigError(\n 'init needs --export <path to your clone of the export> for a developer’s repository; the product side runs `init --product` instead.',\n );\n const next = written(parsed.data);\n const npxArgs = next.npx?.args ?? [];\n const before = existing && JSON.stringify(written(existing));\n const config: Outcome = !existing ? 'created' : before === JSON.stringify(next) ? 'unchanged' : 'updated';\n if (config !== 'unchanged') writeConfig(root, next);\n const mcp = writeMcpJson(root, npxArgs);\n const ignore = ignoreLocalSettings(root);\n const approval = writeLocalSettings(root);\n if (product) return { role: 'product', config, mcp, hook: 'none', approval, ignore, files: NO_FILES };\n const hook = writeClaudeSettings(root, npxArgs);\n const files = install(root, buildClientPlan(version, npxArgs), {\n mode: 'update',\n force,\n version,\n manifestPath: MANIFEST_PATH,\n emptiedFolder: /\\.claude\\/skills\\/alterspec-[^/]+$/,\n });\n return { role: 'developer', config, mcp, hook, approval, ignore, files };\n}\n","import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { sha256 } from './hash.js';\nimport type { PlannedFile } from './manifest.js';\n\nexport const MANIFEST_PATH = '.alterspec/manifest.json';\n\nexport interface Manifest {\n version: string;\n /** Hash of the content alterspec last wrote, per framework/wrapper file. */\n files: Record<string, string>;\n}\n\nexport interface InstallOptions {\n mode: 'init' | 'update';\n /** Overwrite wrappers the user modified. */\n force?: boolean;\n version: string;\n /** Where the manifest lives; alterspec's by default, the client keeps its own. */\n manifestPath?: string;\n /** A folder emptied by a removal that is removed too (a skill folder of a wrapper no longer shipped). */\n emptiedFolder?: RegExp;\n}\n\nexport interface InstallResult {\n created: string[];\n updated: string[];\n unchanged: string[];\n /** User-owned files that already existed. */\n kept: string[];\n /** Framework files that differ from this version (init only fills gaps; `update` refreshes them). */\n outdated: string[];\n /** Wrappers the user modified; skipped unless --force. */\n conflicts: string[];\n /** Framework files from an older version that are no longer shipped. */\n removed: string[];\n}\n\nexport function readManifest(root: string, path = MANIFEST_PATH): Manifest | undefined {\n const p = join(root, path);\n if (!existsSync(p)) return undefined;\n try {\n return JSON.parse(readFileSync(p, 'utf8')) as Manifest;\n } catch {\n return undefined;\n }\n}\n\nfunction write(root: string, path: string, content: string) {\n const full = join(root, path);\n mkdirSync(dirname(full), { recursive: true });\n writeFileSync(full, content);\n}\n\n/** Apply an install plan to a project. Never touches user-owned files that exist. */\nexport function install(root: string, plan: PlannedFile[], opts: InstallOptions): InstallResult {\n const result: InstallResult = {\n created: [],\n updated: [],\n unchanged: [],\n kept: [],\n outdated: [],\n conflicts: [],\n removed: [],\n };\n const manifestPath = opts.manifestPath ?? MANIFEST_PATH;\n const emptiedFolder = opts.emptiedFolder ?? /\\.claude\\/skills\\/[^/]+$/;\n const previous = readManifest(root, manifestPath);\n const next: Manifest = { version: opts.version, files: {} };\n\n for (const file of plan) {\n const full = join(root, file.path);\n const newHash = sha256(file.content);\n\n if (!existsSync(full)) {\n write(root, file.path, file.content);\n result.created.push(file.path);\n if (file.policy !== 'user') next.files[file.path] = newHash;\n continue;\n }\n\n if (file.policy === 'user') {\n result.kept.push(file.path);\n continue;\n }\n\n const diskHash = sha256(readFileSync(full, 'utf8'));\n if (diskHash === newHash) {\n result.unchanged.push(file.path);\n next.files[file.path] = newHash;\n continue;\n }\n\n if (opts.mode === 'init') {\n result.outdated.push(file.path);\n next.files[file.path] = previous?.files[file.path] ?? diskHash;\n continue;\n }\n\n // update\n const userModified = file.policy === 'wrapper' && previous?.files[file.path] !== diskHash;\n if (userModified && !opts.force) {\n result.conflicts.push(file.path);\n next.files[file.path] = previous?.files[file.path] ?? diskHash;\n continue;\n }\n write(root, file.path, file.content);\n result.updated.push(file.path);\n next.files[file.path] = newHash;\n }\n\n // Remove framework files and unmodified wrappers that this version no longer ships.\n if (opts.mode === 'update' && previous) {\n const planned = new Set(plan.map((f) => f.path));\n for (const [path, hash] of Object.entries(previous.files)) {\n if (planned.has(path)) continue;\n const full = join(root, path);\n if (!existsSync(full)) continue;\n if (sha256(readFileSync(full, 'utf8')) === hash) {\n rmSync(full);\n result.removed.push(path);\n // A skill folder of a wrapper this version no longer ships: drop it once it is empty.\n const folder = dirname(full);\n if (emptiedFolder.test(folder) && readdirSync(folder).length === 0)\n rmSync(folder, { recursive: true });\n } else {\n result.conflicts.push(path);\n }\n }\n }\n\n write(root, manifestPath, JSON.stringify(next, null, 2) + '\\n');\n return result;\n}\n","import { createHash } from 'node:crypto';\n\nexport const sha256 = (content: string): string => createHash('sha256').update(content).digest('hex');\n","/**\n * Names as people say them, matched against names as the spec writes them. Imports nothing: the reverse-spec\n * coverage and the client's `lookup` share it, and the client bundles no part of the spec model.\n */\n\n/** Case, spacing and punctuation don't matter; `full_name`, `Full-name` and `Full name` are the same name. */\nexport const normalizeName = (s: string) =>\n s\n .toLowerCase()\n .replace(/[_\\-./]+/g, ' ')\n .replace(/[^\\p{L}\\p{N} ]+/gu, '')\n .replace(/\\s+/g, ' ')\n .trim();\n\n/**\n * The names a thing may go by: its own, plus the glossary's view of it (a forbidden synonym matches the canonical\n * term and the other way round), so \"worker\" matches the spec's \"Employee\".\n */\nexport function aliasGroups(\n glossary: { term: string; forbidden?: string[] }[],\n): (name: string) => Set<string> {\n const groups: Set<string>[] = glossary.map(\n (g) => new Set([g.term, ...(g.forbidden ?? [])].map(normalizeName)),\n );\n return (name) => {\n const n = normalizeName(name);\n const out = new Set([n]);\n for (const g of groups) if (g.has(n)) for (const x of g) out.add(x);\n return out;\n };\n}\n","import { FRONT_MATTER_SHARD, shardDir } from '../../src/export/paths.js';\nimport { type ExportReader, frontMatterOf, idsIn } from '../../src/export/read.js';\nimport { aliasGroups, normalizeName } from '../../src/lib/names.js';\nimport { type IdKind, idKind } from '../../src/schemas/ids.js';\nimport { titleOf } from './context.js';\nimport type { TaskRef } from './task.js';\n\n/**\n * `lookup`: where in the export a question is answered. It resolves what the question names (IDs, glossary terms and\n * the synonyms people say, titles), follows the export's own links one hop, and prints the shards to read first, the\n * ones that must be opened before the export may be called silent, and the neighbours. Paths and titles only, never\n * spec text: the answerer reads, the CLI finds.\n */\n\n/** `_generated/index.json` as far as lookup follows it; every list may be absent in an older export. */\ninterface Index {\n capabilities?: {\n id: string;\n title: string;\n roles?: { role: string; scope?: string }[];\n screens?: string[];\n entities?: { entity: string; ops?: string[] }[];\n rules?: string[];\n events?: { emits?: string[]; consumes?: string[] };\n depends_on?: string[];\n flows?: string[];\n }[];\n screens?: {\n id: string;\n title: string;\n roles?: { role: string }[];\n fields?: { entity: string }[];\n actions?: { id: string; label?: string; capability?: string }[];\n }[];\n entities?: { id: string; title: string; attributes?: { name: string; references?: string }[] }[];\n rules?: { id: string; title: string; entities?: string[]; guards?: { entity: string; on?: string[] }[] }[];\n events?: { id: string; title: string; entities?: string[] }[];\n roles?: { id: string; title: string }[];\n personas?: { id: string; title: string; roles?: string[] }[];\n decisions?: { id: string; title: string; affects?: string[] }[];\n flows?: { id: string; title: string; steps?: { capability?: string }[] }[];\n glossary?: { term: string; forbidden?: string[] }[];\n}\n\nconst ID_KINDS: IdKind[] = [\n 'acceptance',\n 'screenAction',\n 'experience',\n 'capability',\n 'screen',\n 'entity',\n 'rule',\n 'event',\n 'decision',\n 'role',\n 'persona',\n 'flow',\n 'integration',\n 'nfr',\n 'module',\n];\n\n/** The sections that usually hold the answer, by the kind of object; the rest of its shards are in the same folder. */\nconst READ: Partial<Record<IdKind, string[]>> = {\n capability: [\n 'Acceptance criteria',\n 'Alternative and exception flows',\n 'Permissions and data visibility',\n 'Main flow',\n ],\n entity: ['Attributes', 'Lifecycle'],\n screen: ['Displayed data', 'Actions', 'Business states', 'Per-role differences'],\n experience: ['Interactions', 'Validation messages', 'Loading and errors'],\n flow: ['Steps'],\n};\n/** Where an object says what it deliberately leaves out, and what is still undecided about it. */\nconst SILENCE = ['Out of scope', 'Open questions'];\n\nconst VIEWS: [string, string][] = [\n ['_generated/role-matrix.md', 'who may perform a capability, and with which scope'],\n ['_generated/visibility.md', 'which states of a record a role sees'],\n ['_generated/rule-matrix.md', 'where a rule is enforced, what triggers it, which criteria cover it'],\n ['_generated/channel-matrix.md', 'on which channel and screen a capability is performed'],\n ['_generated/navigation.md', 'how a screen is reached and where its actions lead'],\n ['_generated/traceability.md', 'the order of a flow’s steps and what joins them'],\n ['_generated/operations.md', 'what other systems may do'],\n];\n\nexport interface About {\n id: string;\n title?: string;\n /** How the question named it, when not by its ID. */\n said?: string;\n /** The criterion, action or state the question is about. */\n focus?: string[];\n}\n\nexport interface Reading {\n id: string;\n title?: string;\n /** The shard folder (documents) or the item's shard (collections). */\n at: string;\n /** The shards of the folder to open first. */\n shards: string[];\n}\n\nexport interface Check {\n path: string;\n why: string;\n}\n\nexport interface Lookup {\n about: About[];\n /** IDs and references the question names that the export doesn't hold. */\n missing: string[];\n read: Reading[];\n check: Check[];\n neighbours: (Check & { id: string })[];\n views: Check[];\n}\n\nexport interface LookupOptions {\n refs?: string[];\n question?: string;\n task?: TaskRef;\n item?: string;\n}\n\nconst NEIGHBOURS = 15;\nconst ORDER: IdKind[] = ['rule', 'decision', 'capability', 'entity', 'screen', 'experience', 'event', 'role'];\n\nconst ownerOf = (id: string) =>\n /^(.+)-AC-\\d+$/.exec(id)?.[1] ?? /^(.+)\\.A\\d+$/.exec(id)?.[1] ?? id.replace(/#.*$/, '');\nconst screenOfUx = (id: string) => /^UX-(SCR-.+)-[A-Z]{2,5}$/.exec(id)?.[1];\n\nexport function lookup(x: ExportReader, opts: LookupOptions): Lookup {\n const index = (x.index() ?? {}) as unknown as Index;\n const caps = index.capabilities ?? [];\n const screens = index.screens ?? [];\n const entities = index.entities ?? [];\n const rules = index.rules ?? [];\n const events = index.events ?? [];\n const decisions = index.decisions ?? [];\n const text = [...(opts.refs ?? []), opts.question ?? ''].join(' ');\n\n // 1. What the question names.\n const about = new Map<string, About>();\n const missing: string[] = [];\n const add = (id: string, more: Partial<About> = {}) => {\n const owner = ownerOf(id);\n if (!x.sources.has(owner)) {\n if (!missing.includes(id)) missing.push(id);\n return;\n }\n const a = about.get(owner) ?? { id: owner, ...(titleOf(x, owner) ? { title: titleOf(x, owner)! } : {}) };\n if (owner !== id) a.focus = [...new Set([...(a.focus ?? []), id])];\n about.set(owner, { ...a, ...more });\n };\n for (const id of idsIn(text, ID_KINDS)) add(id);\n for (const m of text.matchAll(/(?<![\\w-])(UX-SCR-[A-Z0-9-]+#[\\w-]+|SCR-[A-Z0-9-]+\\.A\\d+)/g)) add(m[1]!);\n\n // Names: titles and glossary terms, and the synonyms the glossary knows people say.\n const aliases = aliasGroups(index.glossary ?? []);\n const names = new Map<string, { id: string; said?: string }>();\n const name = (said: string, id: string) => {\n for (const n of aliases(said))\n if (n.length > 2 && !names.has(n))\n names.set(n, { id, ...(n === normalizeName(said) ? {} : { said: n }) });\n };\n for (const list of [entities, screens, caps, rules, events, index.roles ?? [], index.personas ?? []])\n for (const o of list) name(o.title, o.id);\n for (const g of index.glossary ?? []) name(g.term, `term:${g.term}`);\n const spoken = ` ${normalizeName(text.replace(/\\b[A-Z]+(?:-[A-Z0-9]+)+\\b/g, ' '))} `;\n for (const [n, hit] of [...names].sort((a, b) => b[0].length - a[0].length))\n if (new RegExp(` ${n}(?:s|es)? `).test(spoken) && !about.has(hit.id))\n add(hit.id, hit.said ? { said: hit.said } : {});\n for (const ref of opts.refs ?? [])\n if (!idsIn(ref, ID_KINDS).length && !/#/.test(ref) && !names.has(normalizeName(ref))) {\n const plural = normalizeName(ref).replace(/e?s$/, '');\n if (!names.has(plural) && !missing.includes(ref)) missing.push(ref);\n }\n\n // A capability by what it does: its title's verb (\"Approve sales price\"), or the label of an action that performs\n // it, said about something the question already named (its role, its entity) or with another word of its title.\n const said = (word: string) => {\n const w = normalizeName(word);\n return w.length > 3 && new RegExp(` ${w.replace(/e$/, '')}(?:e|es|ed|d|s|ing)? `).test(spoken);\n };\n for (const c of caps) {\n if (about.has(c.id)) continue;\n const [verb, ...rest] = normalizeName(c.title).split(' ');\n const labels = screens.flatMap((sc) =>\n (sc.actions ?? []).filter((act) => act.capability === c.id).map((act) => act.label ?? ''),\n );\n const word = [verb!, ...labels].find(said);\n if (!word) continue;\n const near =\n c.roles?.some((r) => about.has(r.role)) ||\n c.entities?.some((e) => about.has(e.entity)) ||\n rest.some(said);\n if (near) add(c.id, { said: normalizeName(word) });\n }\n\n // The task's own objects, when the question named nothing; the item it is about, always.\n if (opts.item) add(opts.item);\n if (!about.size && opts.task) {\n const task = x.work.changes\n .find((c) => c.id === opts.task!.change)\n ?.tasks?.find((t) => t.track === opts.task!.track);\n for (const key of task?.objects ?? []) if (x.sources.has(key) && !key.startsWith('file:')) add(key);\n }\n\n // 2. One hop through the export's links, both ways.\n const links = (id: string): { id: string; why: string }[] => {\n const out: { id: string; why: string }[] = [];\n const cap = caps.find((c) => c.id === id);\n if (cap) {\n for (const r of cap.rules ?? []) out.push({ id: r, why: `a rule of ${id}` });\n for (const e of cap.entities ?? [])\n out.push({ id: e.entity, why: `${id} works with it${e.ops?.length ? ` (${e.ops.join('')})` : ''}` });\n for (const e of cap.events?.emits ?? []) out.push({ id: e, why: `emitted by ${id}` });\n for (const e of cap.events?.consumes ?? []) out.push({ id: e, why: `starts or informs ${id}` });\n for (const r of cap.roles ?? [])\n out.push({ id: r.role, why: `performs ${id}${r.scope ? `, scope ${r.scope}` : ''}` });\n for (const d of cap.depends_on ?? []) out.push({ id: d, why: `${id} depends on it` });\n }\n for (const s of screens) {\n const acts = (s.actions ?? []).filter((a) => a.capability === id);\n if (acts.length)\n out.push({\n id: s.id,\n why: `performs ${id} (${acts.map((a) => `${a.id}${a.label ? ` ${a.label}` : ''}`).join(', ')})`,\n });\n if (s.id === id) {\n for (const a of s.actions ?? [])\n if (a.capability) out.push({ id: a.capability, why: `${id}.${a.id} performs it` });\n for (const f of s.fields ?? []) out.push({ id: f.entity, why: `shown on ${id}` });\n } else if ((s.fields ?? []).some((f) => f.entity === id)) out.push({ id: s.id, why: `shows ${id}` });\n }\n for (const r of rules) {\n const guards = (r.guards ?? []).filter((g) => g.entity === id);\n if (r.id === id) {\n for (const c of caps) if (c.rules?.includes(id)) out.push({ id: c.id, why: `applies ${id}` });\n for (const e of new Set([...(r.entities ?? []), ...(r.guards ?? []).map((g) => g.entity)]))\n out.push({ id: e, why: `${id} is about it` });\n } else if (guards.length)\n out.push({\n id: r.id,\n why: `guards ${id} on ${guards.flatMap((g) => g.on ?? []).join(', ') || 'it'}`,\n });\n else if (r.entities?.includes(id)) out.push({ id: r.id, why: `is about ${id}` });\n }\n const ent = entities.find((e) => e.id === id);\n for (const a of ent?.attributes ?? [])\n if (a.references) out.push({ id: a.references, why: `${id}.${a.name} refers to it` });\n for (const e of entities)\n if (e.id !== id && e.attributes?.some((a) => a.references === id))\n out.push({ id: e.id, why: `refers to ${id}` });\n for (const c of caps) {\n if (c.id === id) continue;\n if (c.entities?.some((e) => e.entity === id)) out.push({ id: c.id, why: `works with ${id}` });\n if (c.events?.emits?.includes(id)) out.push({ id: c.id, why: `emits ${id}` });\n if (c.events?.consumes?.includes(id)) out.push({ id: c.id, why: `consumes ${id}` });\n if (c.roles?.some((r) => r.role === id)) out.push({ id: c.id, why: `${id} performs it` });\n if (c.depends_on?.includes(id)) out.push({ id: c.id, why: `depends on ${id}` });\n }\n for (const e of events.find((v) => v.id === id)?.entities ?? [])\n out.push({ id: e, why: `${id} is about it` });\n for (const d of decisions) {\n if (d.id === id) for (const a of d.affects ?? []) out.push({ id: a, why: `${id} affects it` });\n else if (d.affects?.includes(id)) out.push({ id: d.id, why: `decides about ${id}` });\n }\n const scr = screenOfUx(id);\n if (scr) out.push({ id: scr, why: `${id} is its design` });\n for (const s of x.sources.keys())\n if (screenOfUx(s) === id) out.push({ id: s, why: `the design of ${id}` });\n // An export without the index: what the object's own front-matter names.\n if (!x.index()) {\n const file = x.fileOf(id);\n for (const n of idsIn(frontMatterOf((file && x.read(file)) || ''), ID_KINDS))\n if (n !== id) out.push({ id: n, why: `named by ${id}` });\n }\n return out.filter((l) => x.sources.has(l.id));\n };\n\n // 3. The lists.\n const isDoc = (id: string) => {\n const file = x.fileOf(id);\n return !!file && x.has(`${shardDir(file)}/${FRONT_MATTER_SHARD}`);\n };\n const pathOf = (id: string): string | undefined => {\n const file = x.fileOf(id);\n if (!file) return undefined;\n return isDoc(id) ? `${shardDir(file)}/${FRONT_MATTER_SHARD}` : (x.itemShard(file, id) ?? file);\n };\n const resolved = [...about.keys()];\n const read: Reading[] = resolved.flatMap((id) => {\n const file = x.fileOf(id);\n const a = about.get(id)!;\n if (!file) return [];\n if (!isDoc(id)) return [{ id, ...(a.title ? { title: a.title } : {}), at: pathOf(id)!, shards: [] }];\n const folder = `${shardDir(file)}/`;\n const kind = idKind(id);\n const sections = (kind && READ[kind]) ?? [];\n return [\n {\n id,\n ...(a.title ? { title: a.title } : {}),\n at: folder,\n shards: [\n FRONT_MATTER_SHARD,\n ...sections.flatMap((h) => x.sectionShard(file, h)?.slice(folder.length) ?? []),\n ],\n },\n ];\n });\n\n const check = new Map<string, string>();\n const must = (path: string | undefined, why: string) => {\n if (path && x.has(path) && !check.has(path)) check.set(path, why);\n };\n const hop = new Map(resolved.map((id) => [id, links(id)]));\n for (const id of resolved) {\n const file = x.fileOf(id)!;\n if (isDoc(id)) {\n must(pathOf(id), `the facts of ${id}`);\n for (const h of SILENCE) must(x.sectionShard(file, h), `${id}: ${h.toLowerCase()}`);\n } else must(pathOf(id), id.startsWith('term:') ? `what \"${id.slice(5)}\" means` : `${id} itself`);\n }\n for (const id of resolved)\n for (const l of hop.get(id)!) if (idKind(l.id) === 'rule') must(pathOf(l.id), `${l.id}: ${l.why}`);\n // Decisions about what the question names, and about the entities and rules behind it.\n const behind = new Set(\n resolved\n .filter((id) => ['capability', 'screen'].includes(idKind(id) ?? ''))\n .flatMap((id) => hop.get(id)!.map((l) => l.id)),\n );\n for (const d of decisions)\n if (d.affects?.some((a) => resolved.includes(a))) must(pathOf(d.id), `${d.id} decides about it`);\n for (const d of decisions)\n if (d.affects?.some((a) => behind.has(a) && ['entity', 'rule'].includes(idKind(a) ?? '')))\n must(pathOf(d.id), `${d.id} decides about ${d.affects.find((a) => behind.has(a))}`);\n for (const id of resolved) {\n const last = (x.sources.get(id) as { changed_by?: string[] } | undefined)?.changed_by?.at(-1);\n must(last && x.proposalPath(last), `why ${id} is as it is (${last}, the last change of it)`);\n }\n must('_generated/open-items.md', 'what the spec itself holds open');\n\n const seen = new Set(resolved);\n const neighbours = resolved\n .flatMap((id) => hop.get(id)!)\n .filter((l) => !seen.has(l.id) && seen.add(l.id))\n .map((l) => ({ id: l.id, path: pathOf(l.id) ?? '', why: l.why }))\n .filter((l) => l.path && !check.has(l.path))\n .sort((a, b) => {\n const rank = (id: string) => (ORDER.indexOf(idKind(id)!) + 1 || ORDER.length + 1) - 1;\n return rank(a.id) - rank(b.id);\n })\n .slice(0, NEIGHBOURS);\n\n return {\n about: [...about.values()],\n missing,\n read,\n check: [...check].map(([path, why]) => ({ path, why })),\n neighbours,\n views: VIEWS.filter(([p]) => x.has(p)).map(([path, why]) => ({ path, why })),\n };\n}\n\n/**\n * The paths of `check` nobody opened. A path counts as opened when it was read itself, when the file it is a shard\n * of was read whole, or when the object was named by its ID.\n */\nexport function unread(x: ExportReader, found: Lookup, opened: string[]): Check[] {\n const dir = x.dir.replace(/\\/+$/, '');\n const given = opened.map((o) =>\n (o.startsWith(`${dir}/`) ? o.slice(dir.length + 1) : o).replace(/^\\.\\//, ''),\n );\n const covers = (path: string) =>\n given.some((g) => {\n if (g === path || path.endsWith(`/${g}`)) return true;\n if (g.endsWith('.md') && path.startsWith(`${shardDir(g)}/`)) return true;\n const file = x.sources.has(g) ? x.fileOf(g) : undefined;\n return !!file && (path.startsWith(`${shardDir(file)}/`) || path === file);\n });\n return found.check.filter((c) => !covers(c.path));\n}\n\nexport function renderLookup(l: Lookup): string {\n const out: string[] = [];\n if (!l.about.length)\n out.push(\n 'The question names nothing the export holds: no ID, glossary term or title of it. Rephrase it in the',\n 'export’s terms (glossary.md), or it is about something the product doesn’t have.',\n );\n else\n out.push(\n `About: ${l.about\n .map(\n (a) =>\n `${a.id}${a.title && !a.id.startsWith('term:') ? ` ${a.title}` : ''}${a.said ? ` (said as \"${a.said}\")` : ''}${a.focus ? ` [${a.focus.join(', ')}]` : ''}`,\n )\n .join('; ')}`,\n );\n if (l.missing.length) out.push(`Not in the export: ${l.missing.join(', ')}`);\n if (l.read.length)\n out.push(\n '',\n 'Read first:',\n ...l.read.map((r) => `- ${r.id}: ${r.at}${r.shards.length ? ` ${r.shards.join(', ')}` : ''}`),\n );\n if (l.check.length)\n out.push('', 'Open before calling the export silent:', ...l.check.map((c) => `- ${c.path} (${c.why})`));\n if (l.neighbours.length)\n out.push('', 'Neighbours, when one bears on it:', ...l.neighbours.map((n) => `- ${n.path} (${n.why})`));\n if (l.views.length)\n out.push('', 'Views, by the kind of question:', ...l.views.map((v) => `- ${v.path}: ${v.why}`));\n return out.join('\\n') + '\\n';\n}\n","import { spawn } from 'node:child_process';\nimport { DispatcherError, type Session } from './auth.js';\n\n/** What `open` opens: only the dispatcher's pages for now. */\nexport const OPENABLE = ['dispatcher'] as const;\n\nexport function openInBrowser(url: string): void {\n const [cmd, args] =\n process.platform === 'darwin'\n ? ['open', [url]]\n : process.platform === 'win32'\n ? ['cmd', ['/c', 'start', '', url]]\n : ['xdg-open', [url]];\n spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();\n}\n\n/** Sign in, ask for a one-time link to the dispatcher's pages (valid for a minute, used once) and open it. */\nexport async function openDispatcher(\n session: Session,\n open: (url: string) => void = openInBrowser,\n): Promise<string> {\n const res = await session.fetch('/auth/link', { method: 'POST' });\n if (!res.ok) throw new DispatcherError('HTTP_' + res.status, `The dispatcher answered ${res.status}.`);\n const { url } = (await res.json()) as { url: string };\n open(url);\n return url;\n}\n","import { execFileSync } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { DispatcherError, type Session } from './auth.js';\nimport { callTool } from './mcp.js';\nimport { COVERS, TRAILER, type TaskRef, folderOf, parseTask, taskOfBranch } from './task.js';\n\n/**\n * A task's progress, from the developer's commits (spec 8.1 and 12.2 `progress`): the commits reachable from `HEAD`\n * carrying the task's trailer name the items they cover in `Alterspec-Covers`, each with the first commit naming it,\n * and the dispatcher gets them with `report_progress`. The agent only names items; counting is the dispatcher's.\n */\n\nexport interface Covered {\n item: string;\n commit: string;\n}\n\nconst git = (cwd: string, args: string[]) =>\n execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();\n\n/**\n * The task being worked on in `repo`: the one of the task branch checked out, else the one the `Alterspec-Task`\n * trailer of the last commit names, since the client makes no branch and the developer may work on any.\n */\nexport function currentTask(repo: string): TaskRef | undefined {\n try {\n const task = taskOfBranch(git(repo, ['symbolic-ref', '--short', 'HEAD']));\n if (task) return task;\n } catch {\n // A detached HEAD: the trailer may still say.\n }\n try {\n const named = git(repo, [\n 'log',\n '-1',\n `--format=%(trailers:key=${TRAILER},valueonly,separator=%x1d)`,\n 'HEAD',\n ]);\n for (const id of named.split('\\x1d'))\n try {\n return parseTask(id.trim());\n } catch {\n // Not a task as the dispatcher writes it.\n }\n } catch {\n // No commit yet.\n }\n return undefined;\n}\n\n/**\n * The items the task's commits reachable from `HEAD` cover, sorted, each with the first (oldest) commit that named\n * it. Trailers are read by git itself, so only the message's trailer block counts.\n */\nexport function coveredItems(repo: string, task: TaskRef): Covered[] {\n const trailer = (key: string) => `%(trailers:key=${key},valueonly,separator=%x1d)`;\n const log = git(repo, [\n 'log',\n '--reverse',\n '--topo-order',\n `--format=%H%x1f${trailer(TRAILER)}%x1f${trailer(COVERS)}%x1e`,\n 'HEAD',\n ]);\n const first = new Map<string, string>();\n for (const record of log.split('\\x1e')) {\n const [sha, tasks = '', covers = ''] = record.trim().split('\\x1f');\n if (!sha) continue;\n if (!tasks.split('\\x1d').some((t) => t.trim().toUpperCase() === task.id)) continue;\n for (const item of covers\n .replaceAll('\\x1d', ',')\n .split(/[,\\s]+/)\n .filter(Boolean))\n if (!first.has(item)) first.set(item, sha);\n }\n return [...first]\n .map(([item, commit]) => ({ item, commit }))\n .sort((a, b) => (a.item < b.item ? -1 : a.item > b.item ? 1 : 0));\n}\n\n/** An item named without its section (`RULE-WH-018`) where the checklist holds parts of it (`RULE-WH-018#front-matter`). */\nexport interface Misnamed {\n item: string;\n /** The checklist's items of that object, as the trailer should name them. */\n forms: string[];\n}\n\nexport interface ProgressReport {\n task: string;\n covered: Covered[];\n /** Items the commits name that the task lacks: left out, said in one line. */\n unknown: string[];\n /** Items named without their section while the checklist holds parts of the object none of which is covered yet. */\n misnamed: Misnamed[];\n /**\n * Items named without their section whose parts some commit or earlier report covers in the checklist's form: an\n * old trailer can't be corrected, so these are left out without a word.\n */\n superseded: string[];\n /** The dispatcher's answer: the task with its progress and ETA. */\n answer: Record<string, unknown>;\n}\n\n/** The items `UNKNOWN_ITEM` names: the indented lines after its sentence. */\nconst unknownOf = (e: DispatcherError) =>\n e.message\n .split('\\n')\n .slice(1)\n .map((l) => l.trim())\n .filter(Boolean);\n\n/** The task's checklist from the dispatcher's `task`, with what it holds covered; empty when it can't be asked. */\nasync function checklistOf(session: Session, task: TaskRef) {\n try {\n const answer = await callTool(session, 'task', { id: task.id });\n return ((answer.items ?? []) as { item: string; covered_commit?: string | null }[]).map((i) => ({\n item: i.item,\n covered: !!i.covered_commit,\n }));\n } catch {\n return [];\n }\n}\n\n/**\n * Sort the refused items: a bare object ID whose parts are on the checklist is a name without its section, settled\n * when one of those parts is covered (by this report or an earlier one), else a hint with the form to use; the rest\n * are unknown.\n */\nexport function sortRefused(\n refused: string[],\n sent: string[],\n checklist: { item: string; covered: boolean }[],\n): Pick<ProgressReport, 'unknown' | 'misnamed' | 'superseded'> {\n const sentSet = new Set(sent);\n const out: Pick<ProgressReport, 'unknown' | 'misnamed' | 'superseded'> = {\n unknown: [],\n misnamed: [],\n superseded: [],\n };\n for (const item of refused) {\n const parts = item.includes('#') ? [] : checklist.filter((c) => c.item.startsWith(`${item}#`));\n if (!parts.length) out.unknown.push(item);\n else if (parts.some((p) => p.covered || sentSet.has(p.item))) out.superseded.push(item);\n else out.misnamed.push({ item, forms: parts.map((p) => p.item).sort() });\n }\n return out;\n}\n\n/**\n * Send the covered items. An item the task lacks is left out and the rest sent again: a pushed commit's trailer can't\n * be corrected, so one wrong name must not keep every later report out. The dispatcher stays strict (spec 8: exact\n * items); a name without its section is only worded here.\n */\nexport async function reportProgress(\n session: Session,\n task: TaskRef,\n covered: Covered[],\n): Promise<ProgressReport> {\n try {\n const answer = await callTool(session, 'report_progress', { id: task.id, covered });\n return { task: task.id, covered, unknown: [], misnamed: [], superseded: [], answer };\n } catch (e) {\n if (!(e instanceof DispatcherError) || e.code !== 'UNKNOWN_ITEM') throw e;\n const refused = unknownOf(e);\n const known = covered.filter((c) => !refused.includes(c.item));\n if (!refused.length || known.length === covered.length) throw e;\n const answer = await callTool(session, 'report_progress', { id: task.id, covered: known });\n const sorted = sortRefused(\n refused,\n known.map((c) => c.item),\n await checklistOf(session, task),\n );\n return { task: task.id, covered: known, ...sorted, answer };\n }\n}\n\ninterface Progress {\n covered: number;\n of: number;\n percent: number;\n}\n/** The dispatcher's weighed progress (its step 8): covered and total weight of the task's items. */\ninterface Weight {\n covered: number;\n total: number;\n}\ninterface Eta {\n date: string | null;\n at_least?: boolean;\n by?: string;\n computed?: { date: string | null };\n}\n\n/** The report in one or two lines: what the dispatcher counts, and what it refused. */\nexport function progressText(r: ProgressReport): string {\n const progress = r.answer.progress as Progress | null | undefined;\n const weight = r.answer.weight as Weight | null | undefined;\n const eta = r.answer.eta as Eta | undefined;\n const count = progress\n ? `${progress.covered} of ${progress.of} items covered (${progress.percent} %${weight ? `, ${weight.covered} of ${weight.total} weight` : ''})`\n : 'no checklist (its export predates task items)';\n const when = !eta\n ? ''\n : eta.by === 'done'\n ? '; done'\n : eta.date\n ? `; ETA ${eta.at_least ? 'at least ' : ''}${eta.date}${eta.by === 'developer' ? ` (yours; computed ${eta.computed?.date ?? 'unknown'})` : ''}`\n : '; ETA unknown';\n return [...refusedLines(r), `${r.task}: ${count}${when}.`].join('\\n') + '\\n';\n}\n\n/** What the dispatcher refused, in the words the developer acts on; nothing for names already settled. */\nexport const refusedLines = (r: Pick<ProgressReport, 'task' | 'unknown' | 'misnamed'>): string[] => [\n ...(r.unknown.length ? [unknownLine(r)] : []),\n ...r.misnamed.map(misnamedLine),\n];\n\nexport const unknownLine = (r: Pick<ProgressReport, 'task' | 'unknown'>) =>\n `${r.task} has no item ${r.unknown.join(', ')}; left out of the report: name only the task's items (context lists them).`;\n\nexport const misnamedLine = (m: Misnamed) =>\n `${m.item} is named without its section; the checklist writes it as ${m.forms.join(m.forms.length > 2 ? ', ' : ' or ')}: name ${m.forms.length === 1 ? 'that' : 'the part you covered'} in Alterspec-Covers (left out of the report).`;\n\n/** Report no more often than this from the hook. */\nexport const THROTTLE_MS = 15 * 60_000;\n\ninterface HookState {\n /** The hash of the covered items last reported. */\n reported: string;\n at: string;\n}\n\nconst statePath = (repo: string, task: TaskRef) =>\n join(\n git(repo, ['rev-parse', '--path-format=absolute', '--git-common-dir']),\n 'alterspec-client',\n `progress-${folderOf(task)}.json`,\n );\n\nconst hashOf = (covered: Covered[]) =>\n createHash('sha256').update(JSON.stringify(covered)).digest('hex').slice(0, 16);\n\nfunction readState(path: string): HookState | undefined {\n try {\n return existsSync(path) ? (JSON.parse(readFileSync(path, 'utf8')) as HookState) : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport type HookOutcome = 'off-task' | 'unchanged' | 'throttled' | 'reported' | 'failed';\n\n/**\n * `progress --hook`, after a commit in Claude Code: reports when it knows the task, when the covered items changed and\n * the last report is 15 minutes old; never fails, so it never fails the agent's turn.\n */\nexport async function progressHook(opts: {\n repo: string;\n session: () => Session;\n now?: () => number;\n /** Where to say what the last commit named wrongly (the hook's stdout). */\n say?: (text: string) => void;\n}): Promise<HookOutcome> {\n const now = opts.now ?? Date.now;\n try {\n const task = currentTask(opts.repo);\n if (!task) return 'off-task';\n const covered = coveredItems(opts.repo, task);\n const path = statePath(opts.repo, task);\n const state = readState(path);\n const hash = hashOf(covered);\n if (state?.reported === hash) return 'unchanged';\n if (state && now() - Date.parse(state.at) < THROTTLE_MS) return 'throttled';\n const report = await reportProgress(opts.session(), task, covered);\n const named = new Set(headCovers(opts.repo, task));\n const wrong = refusedLines({\n task: report.task,\n unknown: report.unknown.filter((i) => named.has(i)),\n misnamed: report.misnamed.filter((m) => named.has(m.item)),\n });\n if (wrong.length && opts.say) opts.say(hookContext(wrong.join('\\n')));\n mkdirSync(join(path, '..'), { recursive: true });\n writeFileSync(path, JSON.stringify({ reported: hash, at: new Date(now()).toISOString() }) + '\\n');\n return 'reported';\n } catch {\n return 'failed';\n }\n}\n\n/** The items the last commit's `Alterspec-Covers` names, when its `Alterspec-Task` is the task. */\nexport function headCovers(repo: string, task: TaskRef): string[] {\n const trailer = (key: string) => `%(trailers:key=${key},valueonly,separator=%x1d)`;\n const [tasks = '', covers = ''] = git(repo, [\n 'log',\n '-1',\n `--format=${trailer(TRAILER)}%x1f${trailer(COVERS)}`,\n 'HEAD',\n ]).split('\\x1f');\n if (!tasks.split('\\x1d').some((t) => t.trim().toUpperCase() === task.id)) return [];\n return covers\n .replaceAll('\\x1d', ',')\n .split(/[,\\s]+/)\n .filter(Boolean);\n}\n\n/**\n * The hook's answer to Claude: one line of JSON whose `additionalContext` an async hook's output delivers on the next\n * turn (code.claude.com/docs/en/hooks, \"Run hooks in the background\", checked 2026-11-21).\n */\nexport const hookContext = (text: string) =>\n JSON.stringify({\n hookSpecificOutput: {\n hookEventName: 'PostToolUse',\n additionalContext: `alterspec-client progress: ${text}`,\n },\n }) + '\\n';\n\n/** The folder the hook works in: the `cwd` of the hook's input on stdin, when Claude Code gives one. */\nexport async function hookCwd(input: NodeJS.ReadableStream & { isTTY?: boolean }, waitMs = 1000) {\n if (input.isTTY) return undefined;\n const text = await new Promise<string>((resolve) => {\n let data = '';\n const done = () => resolve(data);\n const timer = setTimeout(done, waitMs);\n input.on('data', (c: Buffer | string) => (data += c.toString()));\n input.on('end', () => {\n clearTimeout(timer);\n done();\n });\n input.on('error', done);\n });\n try {\n const cwd = (JSON.parse(text) as { cwd?: unknown }).cwd;\n return typeof cwd === 'string' && cwd ? cwd : undefined;\n } catch {\n return undefined;\n }\n}\n","import { readFileSync } from 'node:fs';\n\n/** The client's version, from its package.json, one level above both src/ (tests) and dist/ (built CLI). */\nexport function packageVersion(): string {\n const pkg = JSON.parse(readFileSync(new URL('../package.json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FileSync","writeFileSync","homedir","join","z","z","z","z","z","z","z","Version","z","z","before","after","sectionText","sectionText","body","sections","sections","fence","existsSync","readFileSync","join","join","existsSync","readFileSync","i","j","day","keyOf","z","resolve","z","PART","seen","after","before","lines","line","what","slug","kind","e","linesOf","bullets","title","caps","screens","exportDir","words","written","idOf","kept","added","named","bearing","lost","delta","list","p","sections","z","one","exportDir","execFileSync","existsSync","readFileSync","rmSync","writeFileSync","dirname","join","join","rmSync","dirname","existsSync","writeFileSync","execFileSync","readFileSync","execFileSync","existsSync","join","git","execFileSync","existsSync","join","existsSync","mkdirSync","readFileSync","readdirSync","writeFileSync","join","existsSync","mkdirSync","readFileSync","readdirSync","rmSync","writeFileSync","dirname","join","createHash","join","existsSync","readFileSync","mkdirSync","dirname","writeFileSync","rmSync","readdirSync","MANIFEST_PATH","readdirSync","join","readFileSync","before","existsSync","after","writeFileSync","mkdirSync","git","said","list","sections","seen","execFileSync","createHash","existsSync","mkdirSync","readFileSync","writeFileSync","join","git","execFileSync","named","join","createHash","existsSync","readFileSync","mkdirSync","writeFileSync","resolve","readFileSync","join","ctx"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/config.ts","../../src/schemas/work.ts","../src/role.ts","../src/ssh.ts","../src/auth.ts","../src/bugs.ts","../../src/schemas/delta.ts","../../src/schemas/change.ts","../../src/schemas/common.ts","../../src/schemas/ids.ts","../../src/changes/delta-record.ts","../../src/changes/compatibility.ts","../../src/changes/data-change.ts","../../src/export/paths.ts","../../src/lib/frontmatter-split.ts","../../src/changes/parts.ts","../../src/export/read.ts","../../src/spec/layout.ts","../../src/lib/diff.ts","../../src/lib/comments.ts","../../src/spec/criteria.ts","../../src/lib/sections-split.ts","../../src/export/cut.ts","../src/pin.ts","../src/questions.ts","../src/mcp.ts","../src/related.ts","../src/ruled.ts","../src/context.ts","../src/pinstore.ts","../src/task.ts","../src/git.ts","../src/install.ts","../../src/install/installer.ts","../../src/install/hash.ts","../../src/lib/names.ts","../src/lookup.ts","../src/open.ts","../src/progress.ts","../src/version.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { join } from 'node:path';\nimport { KeyRefused, keyOf, sessionOf } from './auth.js';\nimport { bugContext, bugTaskState, bugsText, listBugs, renderBugContext } from './bugs.js';\nimport { readExport } from '../../src/export/read.js';\nimport { CONFIG_FILE, type LoadedConfig, exportDir, loadConfig, readConfigAt } from './config.js';\nimport {\n type CoveredState,\n contextStats,\n parseChangedSince,\n parseQuestionsFull,\n parseSiblings,\n pinFiles,\n renderChecklist,\n renderContext,\n shownOf,\n startFrom,\n taskContext,\n} from './context.js';\nimport { pinsDir, readShown, writePins, writeShown } from './pinstore.js';\nimport { exportHead, mainBranch, mergedCommit } from './git.js';\nimport {\n CLAUDE_LOCAL_SETTINGS,\n CLAUDE_SETTINGS,\n approveHere,\n type IgnoreOutcome,\n MCP_JSON,\n PROMPTS_DIR,\n initClient,\n} from './install.js';\nimport { lookup, renderLookup, unread } from './lookup.js';\nimport { callTool, runProxy } from './mcp.js';\nimport { OPENABLE, openDispatcher } from './open.js';\nimport {\n coveredItems,\n currentTask,\n hookCwd,\n progressHook,\n progressText,\n reportProgress,\n} from './progress.js';\nimport { changeQuestions, listQuestions, missingCites, parseAnswers, questionsText } from './questions.js';\nimport { roleOf } from './role.js';\nimport { parseRuled } from './ruled.js';\nimport { type TaskRef, branchOf, parseTask } from './task.js';\nimport { packageVersion } from './version.js';\n\n/** `whoami` as a person reads it: who, which role, what the dispatcher has of the export. */\nexport function whoamiText(me: Record<string, unknown>): string {\n const role = roleOf(me);\n const latest = me.latest_export as { commit?: string; ordinal?: number } | undefined;\n const lines = [\n `${String(me.email ?? '?')}${me.name ? ` (${String(me.name)})` : ''}: ${role === 'product' ? 'a product person (answers questions, sees no task)' : 'a developer'}`,\n ];\n if (role === 'developer') {\n const tracks = Array.isArray(me.tracks) ? (me.tracks as string[]) : [];\n if (tracks.length) lines.push(`Tracks: ${tracks.join(', ')}`);\n // Wave contract points 3 and 5: counts, as a number or a list; absent from an older dispatcher.\n const count = (v: unknown) => (typeof v === 'number' ? v : Array.isArray(v) ? v.length : 0);\n const changed = count(me.ruled_changed);\n const shipped = count(me.shipped_for_you);\n if (changed)\n lines.push(\n `Rulings changed on your tasks: ${changed} (\\`alterspec-client context <task>\\` says which and what follows).`,\n );\n if (shipped)\n lines.push(\n `Changes another track has shipped, with a task of yours still open: ${shipped} (the brief says what that means for your tests).`,\n );\n }\n if (latest?.commit)\n lines.push(`Latest ingested export: ${latest.commit}${latest.ordinal ? ` (#${latest.ordinal})` : ''}`);\n const ingested = Array.isArray(me.ingested) ? (me.ingested as { commit?: string; at?: string }[]) : [];\n if (ingested.length)\n lines.push(\n 'Ingested exports, newest first:',\n ...ingested.map((i) => ` ${String(i.commit ?? '?').slice(0, 12)} ${String(i.at ?? '')}`),\n );\n return lines.join('\\n') + '\\n';\n}\n\nconst tryConfig = (): LoadedConfig | undefined => {\n try {\n return loadConfig();\n } catch {\n return undefined;\n }\n};\n\n/**\n * Which of the task's items the dispatcher holds covered and which of its change's answers the track built already,\n * or why it couldn't be asked (the brief goes on).\n */\nasync function coveredState(loaded: LoadedConfig, task: TaskRef): Promise<CoveredState> {\n try {\n const answer = await callTool(sessionOf(loaded), 'task', { id: task.id });\n const items = (answer.items ?? []) as {\n item: string;\n covered_commit: string | null;\n weight?: number | null;\n label?: string | null;\n }[];\n const answers = parseAnswers(answer.answers);\n const from = startFrom(task.track, answer.after);\n const siblings = parseSiblings(answer.siblings);\n const questionsFull = parseQuestionsFull(answer.questions_full);\n const changedSince = parseChangedSince(answer.changed_since);\n const ruled = parseRuled(answer.ruled);\n const ruledChanged = parseRuled(answer.ruled_changed);\n return {\n covered: new Map(items.flatMap((i) => (i.covered_commit ? [[i.item, i.covered_commit] as const] : []))),\n // The dispatcher's list is the checklist: its first item list stands (its spec, section 9), so the brief and\n // the `Alterspec-Covers` it accepts name the same items.\n ...(items.length\n ? {\n items: items.map((i) => ({\n item: i.item,\n ...(typeof i.weight === 'number' ? { weight: i.weight } : {}),\n ...(typeof i.label === 'string' && i.label ? { label: i.label } : {}),\n })),\n }\n : {}),\n ...(answers ? { answers } : {}),\n ...(from.length ? { startFrom: from } : {}),\n ...(siblings?.length ? { siblings } : {}),\n ...(questionsFull ? { questionsFull } : {}),\n ...(changedSince ? { changedSince } : {}),\n ...(ruled?.length ? { ruled } : {}),\n ...(ruledChanged?.length ? { ruledChanged } : {}),\n };\n } catch (e) {\n return { unknown: (e as Error).message.split('\\n')[0]! };\n }\n}\n\n/** Run a command, printing its error as one line and exiting 1. */\nconst run =\n <A extends unknown[]>(fn: (...args: A) => unknown) =>\n async (...args: A) => {\n try {\n await fn(...args);\n } catch (e) {\n process.stderr.write(`${e instanceof KeyRefused ? e.advice : (e as Error).message}\\n`);\n process.exit(1);\n }\n };\n\n/** What `init` says about keeping the approval out of git: Claude Code ignores it in a tracked file. */\nconst ignoreLines = (o: IgnoreOutcome): string[] =>\n o === 'added'\n ? [`Added ${CLAUDE_LOCAL_SETTINGS} to .gitignore; commit that too.`]\n : o === 'tracked'\n ? [\n `${CLAUDE_LOCAL_SETTINGS} is committed, so Claude Code ignores its approval: \\`git rm --cached\\` it and ignore it.`,\n ]\n : o === 'unknown'\n ? [\n `Make sure git ignores ${CLAUDE_LOCAL_SETTINGS} (where .claude is a symlink, in the repository it points to).`,\n ]\n : [];\n\n/**\n * In a checkout other than the configuration's (a task worktree the developer made), approve the dispatcher server\n * there once, and say so: a worktree has what git tracks, not the git-ignored approval.\n */\nfunction approveWorktree(loaded: { root: string }): void {\n const { root, outcome } = approveHere(loaded.root);\n if (outcome === 'unchanged') return;\n process.stderr.write(\n `Approved the \"dispatcher\" server for you in ${join(root, CLAUDE_LOCAL_SETTINGS)} (this checkout had no approval of its own); its tools appear in the next Claude Code session here.\\n`,\n );\n}\n\nconst program = new Command();\n\nprogram\n .name('alterspec-client')\n .description('alterspec client — takes tasks of an alterspec export from the dispatcher.')\n .version(packageVersion());\n\nprogram\n .command('init')\n .description(\n 'set the client up in this repository: configuration, the dispatcher in .mcp.json, the progress hook, the skills; with --product (in a spec project) only the configuration and the dispatcher',\n )\n .option('--dispatcher <url>', 'the dispatcher’s URL')\n .option('--export <path>', 'your clone of the export repository')\n .option('--track <code...>', 'the tracks this repository builds (BE, WEB, …)')\n .option('--key <key>', 'the public key to sign with: a .pub path or the key line')\n .option('--branch <name>', 'the track’s main branch (default the remote’s HEAD)')\n .option(\n '--npx <flags>',\n 'flags this project runs npx with, comma-separated (--npx=--min-release-age=0); --npx= removes them',\n )\n .option(\n '--product',\n 'the product side’s set-up, in the spec project: a dispatcher and a key, no export, no track, no developer skill or hook',\n )\n .option('--force', 'replace skills you modified')\n .action(\n run(\n (opts: {\n npx?: string;\n dispatcher?: string;\n export?: string;\n track?: string[];\n key?: string;\n branch?: string;\n product?: boolean;\n force?: boolean;\n }) => {\n const root = process.cwd();\n const { track, npx, ...rest } = opts;\n const npxArgs = npx\n ?.split(',')\n .map((a) => a.trim())\n .filter(Boolean);\n const tracks = track\n ?.flatMap((t) => t.split(','))\n .map((t) => t.trim().toUpperCase())\n .filter(Boolean);\n const r = initClient(\n root,\n { ...rest, ...(tracks ? { tracks } : {}), ...(npxArgs ? { npx: { args: npxArgs } } : {}) },\n packageVersion(),\n );\n const f = r.files;\n const lines =\n r.role === 'product'\n ? [\n `${CONFIG_FILE} (the product side: dispatcher and key, no export, no tracks): ${r.config}`,\n `${MCP_JSON} (server \"dispatcher\"): ${r.mcp}`,\n `${CLAUDE_LOCAL_SETTINGS} (the \"dispatcher\" server approved for you): ${r.approval}`,\n 'Nothing of the developer’s was installed: no hook, no skill, no prompt.',\n '',\n `Commit ${CONFIG_FILE} and ${MCP_JSON}.`,\n ...ignoreLines(r.ignore),\n 'The dispatcher’s product tools (whoami, questions, answer, reconcile, feedback, bug_reports) appear in the next Claude Code session; /alterspec-answer post and /alterspec-reconcile use them.',\n ]\n : [\n `${CONFIG_FILE}: ${r.config}`,\n `${MCP_JSON} (server \"dispatcher\"): ${r.mcp}`,\n `${CLAUDE_SETTINGS} (progress hook after git commit): ${r.hook}`,\n `${CLAUDE_LOCAL_SETTINGS} (the \"dispatcher\" server approved for you): ${r.approval}`,\n `Skills, the answerer agent and ${PROMPTS_DIR}/: ${f.created.length} created, ${f.updated.length} updated, ${f.unchanged.length} unchanged${f.removed.length ? `, ${f.removed.length} removed` : ''}.`,\n ...f.conflicts.map((p) => `Kept your modified ${p}; --force replaces it.`),\n '',\n 'Commit .mcp.json, .claude/settings.json, .claude/skills/alterspec-*, .claude/agents/alterspec-* and .alterspec-client/, so task worktrees have them too.',\n ...ignoreLines(r.ignore),\n \"The dispatcher's tools appear in the next Claude Code session.\",\n ];\n try {\n const key = keyOf({ root, config: readConfigAt(root)! });\n lines.push(\n '',\n r.role === 'product'\n ? 'Send this public key to the dispatcher’s admin, to register as a product person:'\n : 'Send this public key to the dispatcher’s admin:',\n key.line,\n key.fingerprint,\n );\n } catch (e) {\n lines.push('', (e as Error).message);\n }\n process.stdout.write(lines.join('\\n') + '\\n');\n },\n ),\n );\n\nprogram\n .command('whoami')\n .description('sign in and print who this key is to the dispatcher: email, role, the latest ingested export')\n .option('--json', 'print the dispatcher’s answer as JSON')\n .action(\n run(async (opts: { json?: boolean }) => {\n const me = await callTool(sessionOf(loadConfig()), 'whoami');\n if (opts.json) return void process.stdout.write(JSON.stringify(me, null, 2) + '\\n');\n process.stdout.write(whoamiText(me));\n }),\n );\n\nprogram\n .command('key')\n .description('print the public key and fingerprint the client signs with, to send to the admin')\n .action(\n run(() => {\n const key = keyOf(tryConfig());\n process.stdout.write(`${key.line}\\n${key.fingerprint}\\n`);\n }),\n );\n\nprogram\n .command('open')\n .description('sign in and open the dispatcher’s pages in the browser (a one-time link)')\n .argument('<what>', `what to open: ${OPENABLE.join(', ')}`)\n .action(\n run(async (what: string) => {\n if (!(OPENABLE as readonly string[]).includes(what))\n throw new Error(`Nothing to open called \"${what}\": ${OPENABLE.join(', ')}.`);\n const loaded = loadConfig();\n const url = await openDispatcher(sessionOf(loaded));\n process.stdout.write(\n `Opened ${new URL(url).origin} in the browser (the link works once, for a minute).\\n`,\n );\n }),\n );\n\nprogram\n .command('mcp')\n .description(\n 'the local MCP server Claude Code starts over stdio (from .mcp.json); forwards to the dispatcher',\n )\n .action(\n run(async () => {\n const loaded = loadConfig();\n const session = sessionOf(loaded);\n await runProxy({ session, input: process.stdin, output: process.stdout, version: packageVersion() });\n }),\n );\n\nprogram\n .command('export-head')\n .description('pull the export clone and print its HEAD and the commit to send the dispatcher (JSON)')\n .option('--latest <sha>', 'the dispatcher’s latest_export')\n .action(\n run((opts: { latest?: string }) => {\n const loaded = loadConfig();\n approveWorktree(loaded);\n const head = exportHead(exportDir(loaded), opts.latest);\n process.stdout.write(JSON.stringify(head, null, 2) + '\\n');\n }),\n );\n\nprogram\n .command('context')\n .description('print a task’s brief, assembled from the export')\n .argument('<task>', 'the task, e.g. CHG-012/BE or BUG-3/BE')\n .option('--json', 'print it as JSON')\n .option('--stats', 'print its size by section instead')\n .option(\n '--checklist',\n 'print only the task’s questions and checklist, for re-reading during the work (a bug’s brief whole)',\n )\n .action(\n run(async (id: string, opts: { json?: boolean; stats?: boolean; checklist?: boolean }) => {\n const loaded = loadConfig();\n approveWorktree(loaded);\n const dir = exportDir(loaded);\n const x = readExport(dir);\n const task = parseTask(id);\n if (task.kind === 'bug') {\n // A bug task's brief: the bug from the dispatcher (work.json never names one), the cites as its checklist.\n const session = sessionOf(loaded);\n const ctx = bugContext(\n x,\n task,\n dir,\n await bugTaskState(session, task),\n await changeQuestions(session, [task.id]),\n );\n process.stdout.write(\n opts.stats\n ? contextStats(renderBugContext(ctx))\n : opts.json\n ? JSON.stringify(ctx, null, 2) + '\\n'\n : renderBugContext(ctx),\n );\n return;\n }\n // The change's tasks, this one first: another track's assumptions and answers bear on this one.\n const tasks = [\n task.id,\n ...(x.work.changes.find((c) => c.id === task.change)?.tasks ?? [])\n .map((t) => `${task.change}/${t.track}`)\n .filter((t) => t !== task.id),\n ];\n const pins = pinsDir(loaded.root, task);\n const ctx = taskContext(\n x,\n task,\n dir,\n await coveredState(loaded, task),\n await changeQuestions(sessionOf(loaded), tasks),\n { pins, shown: readShown(process.cwd(), task) },\n );\n // The objects later changes touched, as this task's change saw them, where the brief's paths point.\n // The checklist alone shows no \"Changed since\", so it marks nothing as shown and writes no pin.\n if (!opts.stats && !opts.checklist) {\n writePins(pins, pinFiles(x, ctx));\n writeShown(process.cwd(), task, shownOf(ctx));\n }\n process.stdout.write(\n opts.stats\n ? contextStats(renderContext(ctx))\n : opts.json\n ? JSON.stringify(ctx, null, 2) + '\\n'\n : opts.checklist\n ? renderChecklist(ctx)\n : renderContext(ctx),\n );\n }),\n );\n\nprogram\n .command('progress')\n .description('report the items the task’s commits cover to the dispatcher')\n .argument(\n '[task]',\n 'the task, e.g. CHG-012/BE; default the one of the branch task/<chg>-<track> or of the last commit’s trailer',\n )\n .option('--hook', 'as the Claude Code hook after a commit: silent, throttled, never failing')\n .option('--json', 'print the dispatcher’s answer as JSON')\n .action(async (id: string | undefined, opts: { hook?: boolean; json?: boolean }) => {\n if (opts.hook) {\n // Whatever happens, the hook ends quietly and in time: it must never fail or hold up the agent's turn.\n setTimeout(() => process.exit(0), 30_000).unref();\n const repo = (await hookCwd(process.stdin)) ?? process.cwd();\n await progressHook({\n repo,\n session: () => sessionOf(loadConfig(repo)),\n say: (text) => process.stdout.write(text),\n });\n process.exit(0);\n }\n await run(async () => {\n const repo = process.cwd();\n const task = id ? parseTask(id) : currentTask(repo);\n if (!task)\n throw new Error(\n 'Neither the branch (task/<chg>-<track>) nor the last commit’s Alterspec-Task trailer names a task: name it, e.g. `progress CHG-012/BE`.',\n );\n const report = await reportProgress(sessionOf(loadConfig()), task, coveredItems(repo, task));\n process.stdout.write(opts.json ? JSON.stringify(report, null, 2) + '\\n' : progressText(report));\n })();\n });\n\nprogram\n .command('lookup')\n .description(\n 'where in the export a question is answered: what to read first, and what before calling it silent',\n )\n .argument('[ref...]', 'IDs and terms the question is about')\n .option('--question <text>', 'the question, in full')\n .option('--task <task>', 'the task it came up in, e.g. CHG-012/BE')\n .option('--item <item>', 'the checklist item it concerns')\n .option('--unread <path...>', 'the paths that were opened: print what must still be, and exit 1 when any')\n .option('--json', 'print it as JSON')\n .action(\n run(\n (\n refs: string[],\n opts: { question?: string; task?: string; item?: string; unread?: string[]; json?: boolean },\n ) => {\n const x = readExport(exportDir(loadConfig()));\n const found = lookup(x, {\n refs,\n ...(opts.question ? { question: opts.question } : {}),\n ...(opts.task ? { task: parseTask(opts.task) } : {}),\n ...(opts.item ? { item: opts.item } : {}),\n });\n if (opts.unread) {\n const left = unread(x, found, opts.unread);\n if (left.length)\n throw new Error(\n `Not opened yet:\\n${left.map((c) => `- ${c.path} (${c.why})`).join('\\n')}\\nThe export isn’t silent until these are read.`,\n );\n process.stdout.write('Everything that had to be opened was.\\n');\n } else process.stdout.write(opts.json ? JSON.stringify(found, null, 2) + '\\n' : renderLookup(found));\n },\n ),\n );\n\nprogram\n .command('cites')\n .description('check that every reference is an ID or a path the export holds')\n .argument('<ref...>', 'IDs (RULE-PRC-001, CAP-PRC-001-AC-02) and export paths')\n .action(\n run((refs: string[]) => {\n const missing = missingCites(readExport(exportDir(loadConfig())), refs);\n if (missing.length)\n throw new Error(\n `Not in the export: ${missing.join(', ')}. An answer that cites them is not from the spec.`,\n );\n process.stdout.write(`All ${refs.length} in the export.\\n`);\n }),\n );\n\nprogram\n .command('questions')\n .description(\n 'print the questions the dispatcher keeps: some by number, a task’s, or without either your own',\n )\n .argument('[ref...]', 'a task, e.g. CHG-012/BE, or questions by number, e.g. Q-12 Q-14')\n .option('--open', 'only the ones still open')\n .option('--about <id...>', 'everyone’s questions that name these IDs')\n .option('--json', 'print them as JSON')\n .action(\n run(async (refs: string[], opts: { open?: boolean; about?: string[]; json?: boolean }) => {\n const ids = refs.filter((r) => /^Q-\\d+$/i.test(r)).map((r) => r.toUpperCase());\n const rest = refs.filter((r) => !/^Q-\\d+$/i.test(r));\n if (rest.length > 1 || (rest.length && ids.length))\n throw new Error('Name one task, or questions by number (Q-<n>), not both.');\n const id = rest[0];\n const questions = await listQuestions(sessionOf(loadConfig()), {\n ...(ids.length ? { ids } : {}),\n ...(id ? { task: parseTask(id).id } : {}),\n ...(opts.about ? { about: opts.about } : {}),\n ...(opts.open ? { open: true } : {}),\n });\n process.stdout.write(opts.json ? JSON.stringify(questions, null, 2) + '\\n' : questionsText(questions));\n }),\n );\n\nprogram\n .command('bugs')\n .description('print the bugs the dispatcher keeps: the ones naming some IDs, or without --about your own')\n .option('--about <id...>', 'everyone’s bugs whose cites, title or description name these IDs')\n .option('--status <status>', 'only the open, done or dismissed ones')\n .option('--track <code>', 'only those with a task on this track')\n .option('--json', 'print them as JSON')\n .action(\n run(async (opts: { about?: string[]; status?: string; track?: string; json?: boolean }) => {\n if (opts.status && !['open', 'done', 'dismissed'].includes(opts.status))\n throw new Error(`--status takes open, done or dismissed, not \"${opts.status}\".`);\n const bugs = await listBugs(sessionOf(loadConfig()), {\n ...(opts.about ? { about: opts.about } : {}),\n ...(opts.status ? { status: opts.status as 'open' | 'done' | 'dismissed' } : {}),\n ...(opts.track ? { track: opts.track.toUpperCase() } : {}),\n });\n process.stdout.write(opts.json ? JSON.stringify(bugs, null, 2) + '\\n' : bugsText(bugs));\n }),\n );\n\nprogram\n .command('merged')\n .description(\n 'print the commit and branch to report done with: the pushed task branch’s head, or the commit on origin/<main> that brought the task in',\n )\n .argument('<task>', 'the task, e.g. CHG-012/BE')\n .option('--json', 'print { commit, branch } as JSON')\n .action(\n run((id: string, opts: { json?: boolean }) => {\n const loaded = loadConfig();\n const main = mainBranch(process.cwd(), loaded.config.branch);\n const task = parseTask(id);\n const found = mergedCommit(process.cwd(), task, main);\n if (!found)\n throw new Error(\n `${task.id} is not pushed yet: push its branch ${branchOf(task)} (or merge it into ${main} with the trailer \"Alterspec-Task: ${task.id}\" on a commit), then run this again.`,\n );\n process.stdout.write(\n opts.json\n ? JSON.stringify(found) + '\\n'\n : found.branch\n ? `${found.commit} on ${found.branch} (pushed, not in ${main} yet)\\n`\n : `${found.commit} on ${main} (merged)\\n`,\n );\n }),\n );\n\nawait program.parseAsync();\n","import { execFileSync } from 'node:child_process';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { basename, dirname, isAbsolute, join, resolve } from 'node:path';\nimport { z } from 'zod';\nimport { TrackCode } from '../../src/schemas/work.js';\n\n/** The client's configuration in an implementation repository (spec 12.1), written by `init`. */\nexport const CONFIG_FILE = '.alterspec-client.json';\n\n/**\n * A flag for npx itself (`--min-release-age=0`). The configuration is committed and these end up in a shell command\n * Claude Code runs after every commit, so nothing but a flag and its value passes: no space, quote or `;`.\n */\nexport const NpxArg = z\n .string()\n .regex(/^--?[A-Za-z0-9][A-Za-z0-9=._:/-]*$/, 'must be one npx flag, like --min-release-age=0');\n\nexport const ClientConfigSchema = z\n .object({\n /** The dispatcher's URL. */\n dispatcher: z.url(),\n /**\n * The developer's clone of the export repository, relative to this file's folder or absolute. Absent in the\n * product side's configuration (`init --product`, spec 8.6): the spec project reads its own spec, never an export.\n */\n export: z.string().min(1).optional(),\n /** The tracks this repository builds: the default of `next_task`. A product configuration has none. */\n tracks: z.array(TrackCode).default([]),\n /** Unused since 0.14.0 (the client makes no worktree); accepted so a configuration written before stays valid. */\n worktrees: z.string().min(1).optional(),\n /** The public key to sign with: a `.pub` path or the key line; default ssh-agent, then `~/.ssh/id_ed25519.pub`. */\n key: z.string().min(1).optional(),\n /** The track's main branch; default the remote's `HEAD`, else `main`. */\n branch: z.string().min(1).optional(),\n /**\n * How this project runs the client: flags put before the package name wherever `init` writes the invocation\n * (`.mcp.json`, the progress hook, the skills and the prompts). The registry is the project's `.npmrc`'s.\n */\n npx: z\n .object({ args: z.array(NpxArg).default([]) })\n .strict()\n .optional(),\n })\n .strict();\nexport type ClientConfig = z.infer<typeof ClientConfigSchema>;\n\n/** The product side's configuration (spec 8.6, 12.4): a dispatcher and a key, no export and no tracks. */\nexport const isProduct = (config: ClientConfig): boolean => config.export === undefined;\n\nexport class ConfigError extends Error {}\n\nexport interface LoadedConfig {\n /** The folder holding the configuration: relative paths in it are relative to this folder. */\n root: string;\n config: ClientConfig;\n}\n\nconst git = (cwd: string, ...args: string[]) => {\n try {\n return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();\n } catch {\n return undefined;\n }\n};\n\n/**\n * The folders a configuration is looked for in: the checkout's top level, then the main checkout's when this is a\n * task worktree (where an uncommitted configuration isn't), then the folder itself.\n */\nfunction candidates(cwd: string): string[] {\n const top = git(cwd, 'rev-parse', '--show-toplevel');\n const common = git(cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir');\n const main = common && basename(common) === '.git' ? dirname(common) : undefined;\n return [...new Set([top, main, resolve(cwd)].filter((d): d is string => !!d))];\n}\n\nexport function readConfigAt(root: string): ClientConfig | undefined {\n const path = join(root, CONFIG_FILE);\n if (!existsSync(path)) return undefined;\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(path, 'utf8'));\n } catch {\n throw new ConfigError(`${path} is not valid JSON.`);\n }\n const parsed = ClientConfigSchema.safeParse(raw);\n if (!parsed.success)\n throw new ConfigError(\n `${path} is not valid: ${parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'} ${i.message}`).join('; ')}.`,\n );\n return parsed.data;\n}\n\nexport function loadConfig(cwd = process.cwd()): LoadedConfig {\n for (const root of candidates(cwd)) {\n const config = readConfigAt(root);\n if (config) return { root, config };\n }\n throw new ConfigError(\n `No ${CONFIG_FILE} here: run \\`npx @alterset/alterspec-client init --dispatcher <url> --export <path>\\` first (in a spec project, \\`init --product --dispatcher <url>\\`).`,\n );\n}\n\n/** A path of the configuration as an absolute path: `~` is the home folder, relative is to the config's folder. */\nexport function configPath(root: string, path: string): string {\n if (path === '~' || path.startsWith('~/')) return join(homedir(), path.slice(1));\n return isAbsolute(path) ? path : resolve(root, path);\n}\n\n/** The export clone's folder; a product configuration has none, and the developer commands stop here. */\nexport function exportDir({ root, config }: LoadedConfig): string {\n if (config.export === undefined)\n throw new ConfigError(\n `${join(root, CONFIG_FILE)} is a product configuration (no export): it answers the build's questions and takes no task. The developer commands need a repository set up with \\`init --dispatcher <url> --export <path>\\`.`,\n );\n return configPath(root, config.export);\n}\n\nexport function writeConfig(root: string, config: ClientConfig): void {\n writeFileSync(join(root, CONFIG_FILE), JSON.stringify(config, null, 2) + '\\n');\n}\n","import { z } from 'zod';\n\n/**\n * `work.json` in an export: the work every signed-off change implies, for an application that hands it to developers\n * (the alterspec dispatcher). The one definition of the format. It imports nothing but zod, so the alterspec client\n * can carry it as it is. Format 9 (alterspec 0.54.0) adds `paths`, the `release` the export makes, a held change\n * (`released: false`, no `tasks`), `coupled`, and each task's optional `versions`, `alters`, `brief` and `amends`.\n * Format 8 (alterspec 0.43.0) names each change's optional `initiative` and carries the\n * `initiatives` they name (the envelope around a group of changes: why they exist; no status). Format 7 (alterspec 0.42.0) gives each task its own optional `weight` and drops the\n * change's. Format 6 (alterspec 0.41.0) weighs each item per track and allows 0 (nothing to build\n * on that track). Format 5 (alterspec 0.38.0) adds the words a person reads: each task's optional `title`,\n * `summary` and `labels`, and the objects' `names`. Format 4 (alterspec 0.34.0) adds each change's optional `weight`; format 3 (0.33.0) adds each task's optional `weights`; format 2 (0.24.0) added\n * each task's `items`; format 1 is the same without them. A reader of every format takes `AnyWorkSchema`.\n */\n\n/** `BE` (the backend, API channels included) or the code of a channel with an experience of its own. */\nexport const TrackCode = z.string().regex(/^[A-Z]{2,5}$/, { message: 'must be BE or a channel code' });\nexport type TrackCode = z.infer<typeof TrackCode>;\n\n/**\n * A weight from 1 to 100: the size of a task (format 7; of a whole change in formats 4 to 6), and (to format 5) of a\n * task item, reasoned at sign-off\n * against alterspec's rubric (a typical acceptance criterion is about 10), never an estimate of anyone's code.\n */\nexport const WorkWeight = z.number().int().min(1).max(100);\nexport type WorkWeight = z.infer<typeof WorkWeight>;\n\n/**\n * The weight of a task item on one track, 0–100 (format 6): how much of the behaviour the item specifies that\n * track builds. 0: the track has nothing to build for it (a behaviour only another channel shows, a mockup file);\n * the item stays on the checklist to be read.\n */\nexport const ItemWeight = z.number().int().min(0).max(100);\nexport type ItemWeight = z.infer<typeof ItemWeight>;\n\n/** The longest title, summary and label (characters). */\nexport const WORD_CAPS = { title: 100, summary: 400, label: 100, name: 100 } as const;\n\n/** A word a person reads: plain text of one line, trimmed, never empty, at most `max` characters. */\nconst words = (max: number) =>\n z\n .string()\n .max(max, { message: `at most ${max} characters` })\n .regex(/^\\S(?:[^\\n\\r]*\\S)?$/, { message: 'one line of text, without spaces around it' });\n\n/** What a track builds in a change, for a list (format 5). */\nexport const WorkTitle = words(WORD_CAPS.title);\n/** The same in two or three plain sentences. */\nexport const WorkSummary = words(WORD_CAPS.summary);\n/** What one checklist item is, apart from its siblings. */\nexport const WorkLabel = words(WORD_CAPS.label);\n/** An object's own title in the spec. */\nexport const WorkName = words(WORD_CAPS.name);\n\nconst ChangeRef = z.string().regex(/^CHG-\\d{3,}$/);\n/** An initiative's ID (alterspec's `INITIATIVE_ID`, written here again: this file imports nothing but zod). */\nconst InitiativeRef = z.string().regex(/^INI-[A-Z0-9]+(?:-[A-Z0-9]+)*$/);\nconst Day = z.iso.date();\n\nexport const WorkTrackSchema = z\n .object({\n code: TrackCode,\n kind: z.enum(['backend', 'ui']),\n /** The channel codes the track builds: the API channels for `BE`, the channels sharing the experience for a UI track. */\n channels: z.array(z.string()),\n })\n .strict();\nexport type WorkTrack = z.infer<typeof WorkTrackSchema>;\n\nexport const WorkTaskSchema = z\n .object({\n track: TrackCode,\n /** The keys of the objects in the change's delta that put it on the track. */\n objects: z.array(z.string()),\n /**\n * The task's checklist, derived from the delta: the acceptance criteria (`<CAP>-AC-NN`), screen actions\n * (`<SCR>.Ann`) and contract states (`<UX-SCR>#<state>`) the change adds or changes, and every other object as\n * its key; on `BE`, `<CHG>#data-change` when the proposal declares a one-time data change (alterspec 0.27.0).\n * Sorted, never empty.\n */\n items: z.array(z.string().min(1)).min(1),\n /**\n * The tasks this one waits for, resolved and reduced: the same change's `BE` task, and the track's tasks of the\n * changes it builds on that did the same work (an item of both, a line of a whole object this task edits again,\n * or an object this task names that entered the export with the earlier change).\n */\n after: z.array(z.object({ change: ChangeRef, track: TrackCode }).strict()),\n /**\n * The weight of each item on this track (format 3; per track and 0–100 from format 6): how much of the\n * behaviour the item specifies this track builds, reasoned at the change's sign-off against alterspec's rubric\n * (a typical acceptance criterion about 10), never anyone's code. 0: nothing to build on this track; the item\n * is read, not built, and counts in no progress. A task whose weights are all 0 has no work and is not handed\n * out. An item the sign-off didn't weigh takes the median of the task's weighed items above 0; a task of a\n * change signed off without weights has no `weights`, and a reader counts each of its items as 10.\n */\n weights: z.record(z.string().min(1), ItemWeight).optional(),\n /**\n * The size of what this track builds in this change, 1–100 (format 7): reasoned at sign-off against alterspec's\n * task rubric (a wording fix about 1–5, one capability's criteria 10–20, a new capability or flow 30–50, a new\n * module or the application's foundation 80–100), never a sum of the item weights and never anyone's code.\n * Absent: the change was signed off without one. For the lists; progress and ETA keep the item weights.\n */\n weight: WorkWeight.optional(),\n /**\n * What this track builds in this change, for a person reading a list (format 5): reasoned at the change's\n * sign-off, in the product's words, naming no ID. Absent: the change was signed off without one.\n */\n title: WorkTitle.optional(),\n /** The same in two or three plain sentences (format 5). */\n summary: WorkSummary.optional(),\n /**\n * What each item is (format 5), by item, naming only the task's own items and not necessarily all: reasoned at\n * sign-off where the spec has no word for the item (an acceptance criterion), composed at export from the spec\n * where it has (a screen's action, a contract's state, a part of an object, a whole object). For reading only.\n */\n labels: z.record(z.string().min(1), WorkLabel).optional(),\n })\n .strict();\nexport type WorkTask = z.infer<typeof WorkTaskSchema>;\n\nexport const WorkChangeSchema = z\n .object({\n id: ChangeRef,\n title: z.string(),\n signed_off: Day,\n /** The hash of the change's `delta.json`; a signed-off change never changes. */\n delta: z.string().regex(/^[0-9a-f]{16}$/),\n depends_on: z.array(ChangeRef),\n /** The change map's level. */\n level: z.number().int().min(1),\n /** One per track the change is on; empty = no work. */\n tasks: z.array(WorkTaskSchema),\n /** The initiative the change belongs to (format 8): its entry in `initiatives`. Absent: none. */\n initiative: InitiativeRef.optional(),\n })\n .strict();\nexport type WorkChange = z.infer<typeof WorkChangeSchema>;\n\n/** An initiative a change names (format 8): its prose is `initiatives/<id>.md` in the export. */\nexport const WorkInitiativeSchema = z.object({ id: InitiativeRef, title: z.string().min(1) }).strict();\nexport type WorkInitiative = z.infer<typeof WorkInitiativeSchema>;\n\n/** Format 8 (alterspec 0.43 to 0.53). */\nexport const WorkV8Schema = z\n .object({\n format: z.literal(8),\n /** The alterspec version that wrote the export. */\n alterspec: z.string(),\n exported: Day,\n /** Everything signed off before the changes began; `built`: the product as it runs (a reverse-spec), no work. */\n baseline: z.object({ date: Day, built: z.boolean() }).strict().nullable(),\n tracks: z.array(WorkTrackSchema),\n /** Every change signed off after the baseline, in the change map's order. */\n changes: z.array(WorkChangeSchema),\n /**\n * The title of every object a task's `objects` names, by key, as the spec holds it now (format 5); an object\n * the spec no longer holds, and a file, has no entry. Absent when no object has one.\n */\n names: z.record(z.string().min(1), WorkName).optional(),\n /** The initiatives the changes name, by ID (format 8). Absent when no change names one. */\n initiatives: z.array(WorkInitiativeSchema).optional(),\n })\n .strict();\nexport type WorkV8 = z.infer<typeof WorkV8Schema>;\n\n/** The first 12 hex of the SHA-256 of a text normalised for work (format 9). */\nconst Version = z.string().regex(/^[0-9a-f]{12}$/);\nconst TaskRef = z.object({ change: ChangeRef, track: TrackCode }).strict();\n\n/** One part of the brief alterspec writes for a task (format 9): sizes and paths, never text. */\nexport const WorkBriefPartSchema = z\n .object({\n kind: z.enum(['capability', 'used_by', 'decision', 'object']),\n key: z.string().min(1),\n /** A file path inside the export, never an anchor; `paragraphs` names a decision's paragraphs. */\n path: z.string().min(1),\n bytes: z.number().int().min(0),\n touched: z.boolean().optional(),\n paragraphs: z.array(z.string().min(1)).optional(),\n })\n .strict();\nexport type WorkBriefPart = z.infer<typeof WorkBriefPartSchema>;\n\n/** Format 9: a task may carry `versions`, `alters`, `brief` and `amends`; every one optional. */\nexport const WorkTaskV9Schema = WorkTaskSchema.extend({\n /** The version of every object, item and cited decision paragraph (`DEC-573#p3`) of the task, as of this export. */\n versions: z.record(z.string().min(1), Version).optional(),\n /** The tracks whose existing behaviour this task changes; sorted, never its own track. */\n alters: z.array(TrackCode).optional(),\n brief: z\n .object({ bytes: z.number().int().min(0), parts: z.array(WorkBriefPartSchema) })\n .strict()\n .optional(),\n /** The signed-off tasks whose cited objects a later edit changed, which this task exists for. A label only. */\n amends: z.array(TaskRef).optional(),\n})\n .strict()\n .refine((t) => !t.alters?.includes(t.track), {\n message: \"alters never names the task's own track\",\n path: ['alters'],\n });\nexport type WorkTaskV9 = z.infer<typeof WorkTaskV9Schema>;\n\n/**\n * Format 9: a change may be held (`released: false`, then no `tasks` field at all; `tasks: []` still means no work)\n * or `coupled` (the server task reaches the main branch only after the change's client tasks are done).\n */\nexport const WorkChangeV9Schema = WorkChangeSchema.extend({\n tasks: z.array(WorkTaskV9Schema).optional(),\n released: z.literal(false).optional(),\n coupled: z.literal(true).optional(),\n})\n .strict()\n .refine((c) => (c.released === false ? c.tasks === undefined : c.tasks !== undefined), {\n message: 'a held change (released: false) has no tasks; a released one has tasks',\n path: ['tasks'],\n });\nexport type WorkChangeV9 = z.infer<typeof WorkChangeV9Schema>;\n\n/** The release an export makes (format 9). Absent: every change in the file is released. */\nexport const WorkReleaseSchema = z\n .object({\n id: z.string().regex(/^R-\\d{4}-\\d{2}-\\d{2}-\\d+$/),\n date: Day,\n note: z\n .string()\n .max(400)\n .refine((t) => !/[\\r\\n]/.test(t), { message: 'one line' }),\n changes: z.array(ChangeRef),\n held: z.array(ChangeRef),\n touches: z.record(ChangeRef, z.array(z.string().min(1))),\n })\n .strict();\nexport type WorkRelease = z.infer<typeof WorkReleaseSchema>;\n\n/** Format 9 (read by client 0.31.0, written from alterspec 0.54.0): format 8 plus `paths`, `release` and the above. */\nexport const WorkV9Schema = WorkV8Schema.extend({\n format: z.literal(9),\n changes: z.array(WorkChangeV9Schema),\n /** The path of every object any task names, every decision any task cites, and every initiative. */\n paths: z.record(z.string().min(1), z.string().min(1)).optional(),\n release: WorkReleaseSchema.optional(),\n}).strict();\nexport type WorkV9 = z.infer<typeof WorkV9Schema>;\n\n/** The format alterspec writes. */\nexport const WORK_FORMAT = 9;\nexport const WorkSchema = WorkV9Schema;\nexport type Work = WorkV9;\n\n/** Format 7 (alterspec 0.42): the same without the change's `initiative` and without `initiatives`. */\nexport const WorkChangeV7Schema = WorkChangeSchema.omit({ initiative: true }).strict();\nexport type WorkChangeV7 = z.infer<typeof WorkChangeV7Schema>;\n\nexport const WorkV7Schema = WorkV8Schema.omit({ initiatives: true })\n .extend({ format: z.literal(7), changes: z.array(WorkChangeV7Schema) })\n .strict();\nexport type WorkV7 = z.infer<typeof WorkV7Schema>;\n\n/**\n * Format 6 (alterspec 0.41): the same without the task's `weight`, with the size of the whole change, 1–100, as\n * the change's optional `weight`.\n */\nexport const WorkTaskV6Schema = WorkTaskSchema.omit({ weight: true }).strict();\nexport type WorkTaskV6 = z.infer<typeof WorkTaskV6Schema>;\n\nexport const WorkChangeV6Schema = WorkChangeV7Schema.extend({\n tasks: z.array(WorkTaskV6Schema),\n weight: WorkWeight.optional(),\n}).strict();\nexport type WorkChangeV6 = z.infer<typeof WorkChangeV6Schema>;\n\nexport const WorkV6Schema = WorkV7Schema.extend({\n format: z.literal(6),\n changes: z.array(WorkChangeV6Schema),\n}).strict();\nexport type WorkV6 = z.infer<typeof WorkV6Schema>;\n\n/** Format 5 (alterspec 0.38 to 0.40): the same with one weight per item for every track, 1–100. */\nexport const WorkTaskV5Schema = WorkTaskV6Schema.extend({\n weights: z.record(z.string().min(1), WorkWeight).optional(),\n}).strict();\nexport type WorkTaskV5 = z.infer<typeof WorkTaskV5Schema>;\n\nexport const WorkChangeV5Schema = WorkChangeV6Schema.extend({ tasks: z.array(WorkTaskV5Schema) }).strict();\nexport type WorkChangeV5 = z.infer<typeof WorkChangeV5Schema>;\n\nexport const WorkV5Schema = WorkV7Schema.extend({\n format: z.literal(5),\n changes: z.array(WorkChangeV5Schema),\n}).strict();\nexport type WorkV5 = z.infer<typeof WorkV5Schema>;\n\n/** Format 4 (alterspec 0.34 to 0.37): the same without the tasks' `title`, `summary` and `labels` and without `names`. */\nexport const WorkTaskV4Schema = WorkTaskV5Schema.omit({ title: true, summary: true, labels: true }).strict();\nexport type WorkTaskV4 = z.infer<typeof WorkTaskV4Schema>;\n\nexport const WorkChangeV4Schema = WorkChangeV5Schema.extend({ tasks: z.array(WorkTaskV4Schema) }).strict();\nexport type WorkChangeV4 = z.infer<typeof WorkChangeV4Schema>;\n\nexport const WorkV4Schema = WorkV5Schema.omit({ names: true })\n .extend({ format: z.literal(4), changes: z.array(WorkChangeV4Schema) })\n .strict();\nexport type WorkV4 = z.infer<typeof WorkV4Schema>;\n\n/** Format 3 (alterspec 0.33): the same without the change's `weight`. */\nexport const WorkChangeV3Schema = WorkChangeV4Schema.omit({ weight: true }).strict();\nexport type WorkChangeV3 = z.infer<typeof WorkChangeV3Schema>;\n\nexport const WorkV3Schema = WorkV4Schema.extend({\n format: z.literal(3),\n changes: z.array(WorkChangeV3Schema),\n}).strict();\nexport type WorkV3 = z.infer<typeof WorkV3Schema>;\n\n/** Format 2 (alterspec 0.24 to 0.32): the same without `weights`. */\nexport const WorkTaskV2Schema = WorkTaskV4Schema.omit({ weights: true });\nexport type WorkTaskV2 = z.infer<typeof WorkTaskV2Schema>;\n\nexport const WorkV2Schema = WorkV4Schema.extend({\n format: z.literal(2),\n changes: z.array(WorkChangeV3Schema.extend({ tasks: z.array(WorkTaskV2Schema) }).strict()),\n}).strict();\nexport type WorkV2 = z.infer<typeof WorkV2Schema>;\n\n/** Format 1 (alterspec 0.23): the same without `items`, `weights` and the change's `weight`. */\nexport const WorkTaskV1Schema = WorkTaskV2Schema.omit({ items: true });\nexport type WorkTaskV1 = z.infer<typeof WorkTaskV1Schema>;\n\nexport const WorkV1Schema = WorkV4Schema.extend({\n format: z.literal(1),\n changes: z.array(WorkChangeV3Schema.extend({ tasks: z.array(WorkTaskV1Schema) }).strict()),\n}).strict();\nexport type WorkV1 = z.infer<typeof WorkV1Schema>;\n\n/** Any format, told apart by `format`: what a reader of exports from several alterspec versions takes. */\nexport const AnyWorkSchema = z.discriminatedUnion('format', [\n WorkV1Schema,\n WorkV2Schema,\n WorkV3Schema,\n WorkV4Schema,\n WorkV5Schema,\n WorkV6Schema,\n WorkV7Schema,\n WorkV8Schema,\n WorkV9Schema,\n]);\nexport type AnyWork = z.infer<typeof AnyWorkSchema>;\n","import { type ClientConfig, isProduct } from './config.js';\n\n/**\n * The two roles a key has with the dispatcher (spec decisions 32 and 33, sections 8.6 and 12.4): a developer takes\n * tasks, a product person answers the build's questions and sees no build state. A person may be both; a session is\n * one, the role its configuration means, asked for on every request (`X-Alterspec-Role`). The proxy cuts\n * `tools/list` to the role's tools and refuses a call outside them itself, so a product session never reaches a\n * task, whatever the dispatcher lists.\n */\n\nexport type Role = 'developer' | 'product';\n\n/** The request header the session's role is asked with (dispatcher spec 10.5, decision 33). */\nexport const ROLE_HEADER = 'x-alterspec-role';\n\n/** The role a configuration means: `product` without an export (`init --product`), `developer` with one. */\nexport const roleOfConfig = (config: ClientConfig): Role => (isProduct(config) ? 'product' : 'developer');\n\n/** The product role's tools, and no other (spec 10.3, \"Tools by role\"). */\nexport const PRODUCT_TOOLS = [\n 'whoami',\n 'questions',\n 'answer',\n 'reconcile',\n 'feedback',\n 'bug_reports',\n] as const;\n\n/** The tools only the product role has; every other tool the dispatcher lists is the developers'. */\nexport const PRODUCT_ONLY = new Set<string>(['answer', 'reconcile', 'bug_reports']);\n\n/** The role `whoami` returns; `product: true` stands for `role: product` while the dispatcher is older. */\nexport function roleOf(whoami: Record<string, unknown>): Role {\n if (whoami.role === 'product' || whoami.role === 'developer') return whoami.role;\n return whoami.product === true ? 'product' : 'developer';\n}\n\n/**\n * Whether the role may call the tool: a product key only its six (an allow-list, so a product session never sees a\n * developer tool the dispatcher adds later), a developer key everything but the product's own (a deny-list, so a\n * developer tool added later is never hidden by an older client).\n */\nexport function allows(role: Role, tool: string): boolean {\n return role === 'product' ? (PRODUCT_TOOLS as readonly string[]).includes(tool) : !PRODUCT_ONLY.has(tool);\n}\n\n/** The refusal the proxy answers a call outside the role with: the dispatcher's codes, one sentence. */\nexport function refusal(role: Role, tool: string): { code: string; message: string } {\n return role === 'product'\n ? {\n code: 'NOT_DEVELOPER',\n message: `Your key is registered as a product person; \\`${tool}\\` is the developers'. A product session sees the build's questions, feedback and bugs, never its tasks.`,\n }\n : {\n code: 'NOT_PRODUCT',\n message: `Your key is registered as a developer; \\`${tool}\\` is the product side's. Answers and reconciling are the spec project's, through a key registered as a product person.`,\n };\n}\n","import { execFileSync } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir, tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * The developer's SSH key (spec 10.5): which public key the client signs with, its fingerprint as `ssh-keygen -l`\n * prints it, and the signature of a challenge by `ssh-keygen -Y sign`, through ssh-agent when it holds the key. The\n * private key never leaves ssh-agent or ssh-keygen.\n */\n\nexport const NAMESPACE = 'alterspec-dispatcher';\nconst KEY_TYPES = ['ssh-ed25519', 'sk-ssh-ed25519@openssh.com'];\n\nexport class KeyError extends Error {}\n\nexport interface PublicKey {\n type: string;\n /** The key line as `authorized_keys` holds it: type, base64 blob, comment. */\n line: string;\n /** `SHA256:` and the unpadded base64 SHA-256 of the key blob, as `ssh-keygen -l` prints it. */\n fingerprint: string;\n /** Where it came from, for messages: a path or `ssh-agent`. */\n source: string;\n /** The `.pub` file, when the key came from one. */\n file?: string;\n}\n\nexport function parseKeyLine(line: string, source: string, file?: string): PublicKey {\n const [type, blob] = line.trim().split(/\\s+/);\n if (!type || !blob || !KEY_TYPES.includes(type))\n throw new KeyError(\n `${source} is not an ssh-ed25519 public key: the dispatcher accepts ${KEY_TYPES.join(' and ')}.`,\n );\n const bytes = Buffer.from(blob, 'base64');\n const fingerprint = `SHA256:${createHash('sha256').update(bytes).digest('base64').replace(/=+$/, '')}`;\n return { type, line: line.trim(), fingerprint, source, ...(file ? { file } : {}) };\n}\n\n/** The key lines ssh-agent holds, or none when there is no agent. */\nexport function agentKeys(): string[] {\n try {\n return execFileSync('ssh-add', ['-L'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })\n .split('\\n')\n .filter((l) => l.trim());\n } catch {\n return [];\n }\n}\n\nexport interface KeyOptions {\n /** The configuration's `key`: a key line, or a `.pub` path already made absolute. */\n configured?: string;\n agent?: () => string[];\n home?: string;\n}\n\nconst isKeyLine = (s: string) => KEY_TYPES.some((t) => s.trim().startsWith(`${t} `));\n\n/** The key the client signs with: the configured one, else the first ssh-ed25519 key in ssh-agent, else `~/.ssh/id_ed25519.pub`. */\nexport function resolveKey(opts: KeyOptions = {}): PublicKey {\n const { configured, agent = agentKeys, home = homedir() } = opts;\n if (configured) {\n if (isKeyLine(configured)) return parseKeyLine(configured, 'the configuration');\n if (!existsSync(configured)) throw new KeyError(`The configured key ${configured} doesn't exist.`);\n return parseKeyLine(readFileSync(configured, 'utf8'), configured, configured);\n }\n const fromAgent = agent().find((l) => l.startsWith('ssh-ed25519 '));\n if (fromAgent) return parseKeyLine(fromAgent, 'ssh-agent');\n const file = join(home, '.ssh', 'id_ed25519.pub');\n if (existsSync(file)) return parseKeyLine(readFileSync(file, 'utf8'), file, file);\n throw new KeyError(\n 'No SSH key to sign with: add an ssh-ed25519 key to ssh-agent, create ~/.ssh/id_ed25519, or name one as `key` in .alterspec-client.json.',\n );\n}\n\nconst blobOf = (line: string) => line.trim().split(/\\s+/)[1];\n\n/**\n * The armored SSH signature of `data` (its UTF-8 bytes, nothing added) in the dispatcher's namespace. Through\n * ssh-agent when it holds the key (passphrase-protected keys included), else with the private key beside the `.pub`.\n */\nexport function sign(key: PublicKey, data: string, agent: () => string[] = agentKeys): string {\n const inAgent = agent().some((l) => blobOf(l) === blobOf(key.line));\n const temp = !key.file || inAgent ? mkdtempSync(join(tmpdir(), 'alterspec-client-')) : undefined;\n try {\n let keyFile: string;\n if (inAgent || !key.file) {\n if (!inAgent)\n throw new KeyError(`ssh-agent doesn't hold the key ${key.fingerprint}: add it with ssh-add.`);\n // A public key file makes ssh-keygen sign through the agent.\n keyFile = join(temp!, 'key.pub');\n writeFileSync(keyFile, key.line + '\\n');\n } else {\n keyFile = key.file.replace(/\\.pub$/, '');\n if (keyFile === key.file || !existsSync(keyFile))\n throw new KeyError(\n `No private key beside ${key.file} and ssh-agent doesn't hold it: add it with ssh-add.`,\n );\n }\n return execFileSync('ssh-keygen', ['-q', '-Y', 'sign', '-n', NAMESPACE, '-f', keyFile], {\n input: data,\n encoding: 'utf8',\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n } catch (e) {\n if (e instanceof KeyError) throw e;\n const stderr = String((e as { stderr?: unknown }).stderr ?? '').trim();\n throw new KeyError(\n `ssh-keygen could not sign with ${key.fingerprint}${stderr ? `: ${stderr}` : ''}. A key with a passphrase must be in ssh-agent (ssh-add).`,\n );\n } finally {\n if (temp) rmSync(temp, { recursive: true, force: true });\n }\n}\n","import { type LoadedConfig, configPath } from './config.js';\nimport { ROLE_HEADER, type Role, roleOfConfig } from './role.js';\nimport { type PublicKey, resolveKey, sign } from './ssh.js';\n\n/**\n * Signing in to the dispatcher with the developer's SSH key (spec 10.5): a challenge, its nonce signed, a token valid\n * for hours, kept in memory only and renewed when it runs out or the dispatcher says to sign in again.\n */\n\n/** An answer of the dispatcher that is no success, with its stable code and its sentence. */\nexport class DispatcherError extends Error {\n constructor(\n readonly code: string,\n message: string,\n readonly status?: number,\n ) {\n super(message);\n }\n}\n\n/** The dispatcher does not let this key in: unknown, removed, or its developer disabled. */\nexport class KeyRefused extends DispatcherError {\n constructor(\n code: string,\n message: string,\n readonly key: PublicKey,\n ) {\n super(code, message);\n }\n /** One sentence, and the key to send to the admin. */\n get advice(): string {\n return `The dispatcher refused your SSH key (${this.code}): send this public key to an admin, then reconnect the dispatcher server in Claude Code (/mcp).\\n${this.key.line}\\n${this.key.fingerprint}`;\n }\n}\n\nconst REFUSED = new Set(['KEY_UNKNOWN', 'DEVELOPER_UNKNOWN', 'DEVELOPER_INACTIVE']);\n/** Renew this long before the token runs out. */\nconst MARGIN_MS = 60_000;\n\nexport interface SessionOptions {\n fetch?: typeof fetch;\n now?: () => number;\n signer?: (key: PublicKey, data: string) => string;\n /**\n * The role this configuration means (spec 10.5, decision 33), sent on every request as `X-Alterspec-Role`: a\n * product configuration asks `product`, a track repository's `developer`; none, and the dispatcher takes the\n * person's own. A role the key's row lacks is refused by the dispatcher (`ROLE_NOT_ALLOWED`).\n */\n role?: Role;\n}\n\nasync function errorOf(res: Response, key: PublicKey): Promise<DispatcherError> {\n let code = 'HTTP_' + res.status;\n let message = `The dispatcher answered ${res.status} ${res.statusText}.`;\n try {\n const body = (await res.json()) as { error?: { code?: string; message?: string } };\n if (body.error?.code) code = body.error.code;\n if (body.error?.message) message = body.error.message;\n } catch {\n // Not JSON: keep the status.\n }\n return REFUSED.has(code)\n ? new KeyRefused(code, message, key)\n : new DispatcherError(code, message, res.status);\n}\n\nexport class Session {\n private token?: { value: string; expires: number };\n private readonly fetchFn: typeof fetch;\n private readonly now: () => number;\n private readonly signer: (key: PublicKey, data: string) => string;\n /** The role asked for on every request, when the configuration means one (decision 33). */\n readonly role?: Role;\n /** How many times this session signed in, for tests and logs. */\n signIns = 0;\n\n constructor(\n readonly base: string,\n readonly key: PublicKey,\n opts: SessionOptions = {},\n ) {\n this.base = base.replace(/\\/+$/, '');\n this.fetchFn = opts.fetch ?? fetch;\n this.now = opts.now ?? Date.now;\n this.signer = opts.signer ?? sign;\n this.role = opts.role;\n }\n\n private async call(path: string, init: RequestInit): Promise<Response> {\n try {\n return await this.fetchFn(this.base + path, init);\n } catch (e) {\n throw new DispatcherError(\n 'UNREACHABLE',\n `The dispatcher at ${this.base} can't be reached (${(e as Error).message}).`,\n );\n }\n }\n\n private async post(path: string, body: unknown): Promise<unknown> {\n const res = await this.call(path, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw await errorOf(res, this.key);\n return res.json();\n }\n\n private async signIn(): Promise<void> {\n const { fingerprint } = this.key;\n const { nonce } = (await this.post('/auth/challenge', { fingerprint })) as { nonce: string };\n const signature = this.signer(this.key, nonce);\n const t = (await this.post('/auth/token', { fingerprint, nonce, signature })) as {\n token: string;\n expires_at: string;\n };\n this.token = { value: t.token, expires: Date.parse(t.expires_at) };\n this.signIns++;\n }\n\n /** A valid token, signing in when there is none or it is about to run out. */\n async bearer(): Promise<string> {\n if (!this.token || this.token.expires - MARGIN_MS <= this.now()) await this.signIn();\n return this.token!.value;\n }\n\n /**\n * A request with the token. A 401 `UNAUTHENTICATED` (token expired or revoked) signs in again once and repeats\n * the request; a refused key surfaces then as `KeyRefused`.\n */\n async fetch(path: string, init: RequestInit = {}): Promise<Response> {\n for (let attempt = 0; ; attempt++) {\n const headers = new Headers(init.headers);\n headers.set('authorization', `Bearer ${await this.bearer()}`);\n if (this.role) headers.set(ROLE_HEADER, this.role);\n const res = await this.call(path, { ...init, headers });\n if (res.status !== 401 || attempt > 0) {\n if (res.status === 401 || res.status === 403) throw await errorOf(res, this.key);\n return res;\n }\n const err = await errorOf(res, this.key);\n if (err.code !== 'UNAUTHENTICATED') throw err;\n this.token = undefined;\n }\n }\n}\n\n/** The key of this repository's configuration, else the default one. */\nexport function keyOf(loaded: LoadedConfig | undefined): PublicKey {\n const key = loaded?.config.key;\n const configured =\n key && !/^(ssh-ed25519|sk-ssh-ed25519@openssh\\.com) /.test(key) ? configPath(loaded.root, key) : key;\n return resolveKey({ configured });\n}\n\n/** A session with the dispatcher of this repository's configuration. */\n/** The session of a configuration: its dispatcher, its key, and the role it means (decision 33). */\nexport const sessionOf = (loaded: LoadedConfig) =>\n new Session(loaded.config.dispatcher, keyOf(loaded), { role: roleOfConfig(loaded.config) });\n","import { z } from 'zod';\nimport type { ExportReader } from '../../src/export/read.js';\nimport type { Session } from './auth.js';\nimport { type CoveredState, type StartFrom, itemWhat, startFrom } from './context.js';\nimport { callTool } from './mcp.js';\nimport { type Question, questionsSection } from './questions.js';\nimport type { TaskRef } from './task.js';\n\n/**\n * Bugs (spec 8.5, decision 17): a deviation of the product from the spec, raised from the client after grooming the\n * report against the export, kept by the dispatcher and never by the spec. Raising and dismissing are the\n * dispatcher's tools, called by the agent; the CLI reads the bugs back and assembles a bug task's brief.\n */\n\nconst BugTaskSchema = z.object({\n id: z.string(),\n track: z.string(),\n status: z.string(),\n developer: z.string().nullish(),\n items: z.array(z.string()).default([]),\n /** The built tasks it waits for. */\n after: z.array(z.string()).default([]),\n branch: z.string().nullish(),\n in_main: z.boolean().nullish(),\n});\n\nexport type BugTask = z.infer<typeof BugTaskSchema>;\n\nconst BugSchema = z.object({\n id: z.string(),\n title: z.string(),\n description: z.string(),\n /** The reporter. */\n developer: z.string(),\n at: z.string(),\n export: z.string().nullish(),\n cites: z.array(z.string()).default([]),\n /** The changes of the tasks it waits for. */\n origin: z.array(z.string()).default([]),\n status: z.enum(['open', 'done', 'dismissed']).default('open'),\n dismissed: z\n .object({ by: z.string(), at: z.string(), reason: z.string(), duplicate_of: z.string().nullish() })\n .nullish(),\n tasks: z.array(BugTaskSchema).default([]),\n});\n\nexport type Bug = z.infer<typeof BugSchema>;\n\nexport class BugsError extends Error {}\n\nexport interface BugsFilter {\n /** Everyone's bugs naming these IDs, to find one raised before. */\n about?: string[];\n status?: 'open' | 'done' | 'dismissed';\n track?: string;\n}\n\n/** The bugs naming some IDs, or without `about` the developer's own (which marks them as listed). */\nexport async function listBugs(session: Session, filter: BugsFilter = {}): Promise<Bug[]> {\n const answer = await callTool(session, 'bugs', {\n ...(filter.about ? { about: filter.about } : { mine: true }),\n ...(filter.status ? { status: filter.status } : {}),\n ...(filter.track ? { track: filter.track } : {}),\n });\n const parsed = z.array(BugSchema).safeParse(answer.bugs ?? []);\n if (!parsed.success) throw new BugsError('The dispatcher’s bugs are not in a form this client reads.');\n return parsed.data;\n}\n\nconst one = (text: string) => text.replace(/\\s+/g, ' ').trim();\n\n/** One task of a bug in a few words: its status, who has it, what it waits for or where it is. */\nfunction bugTaskWords(t: BugTask): string {\n const who = t.developer ? ` (${t.developer})` : '';\n const where =\n t.status === 'blocked' && t.after.length\n ? `, after ${t.after.join(', ')}`\n : t.status === 'done'\n ? t.in_main\n ? ', in main'\n : t.branch\n ? `, on \\`${t.branch}\\``\n : ''\n : '';\n return `${t.id} ${t.status}${who}${where}`;\n}\n\n/** One bug as the lines the agent reads: what is wrong, whose word, where its tasks stand. */\nexport function bugLines(b: Bug): string[] {\n const state =\n b.status === 'dismissed'\n ? `dismissed by ${b.dismissed?.by ?? 'an admin'}${b.dismissed?.duplicate_of ? `, duplicate of ${b.dismissed.duplicate_of}` : ''}`\n : b.status;\n const lines = [`- ${b.id} (${state}; ${b.developer}, ${b.at.slice(0, 10)}): ${one(b.title)}`];\n if (b.cites.length) lines.push(` - Cites: ${b.cites.join(', ')}`);\n if (b.dismissed) lines.push(` - Reason: ${one(b.dismissed.reason)}`);\n else if (b.tasks.length) lines.push(` - Tasks: ${b.tasks.map(bugTaskWords).join('; ')}`);\n return lines;\n}\n\nexport function bugsText(bugs: Bug[]): string {\n if (!bugs.length) return 'No bugs.\\n';\n return bugs.flatMap(bugLines).join('\\n') + '\\n';\n}\n\n/** The `bug` of the dispatcher's `task` for a bug task; undefined when it sends none or something this client doesn't read. */\nexport function parseBug(raw: unknown): Bug | undefined {\n const parsed = BugSchema.safeParse(raw);\n return parsed.success ? parsed.data : undefined;\n}\n\n/** What the dispatcher says of a bug task: its bug, its objects, what it waits for and where it starts from. */\nexport interface BugTaskState extends CoveredState {\n bug: Bug;\n objects: string[];\n after: string[];\n}\n\n/** The dispatcher's `task` of a bug task; a bug task has no brief without it (work.json never names a bug). */\nexport async function bugTaskState(session: Session, task: TaskRef): Promise<BugTaskState> {\n let answer: Record<string, unknown>;\n try {\n answer = await callTool(session, 'task', { id: task.id });\n } catch (e) {\n throw new BugsError(\n `${task.id} is a bug's task, and only the dispatcher holds a bug: ${(e as Error).message.split('\\n')[0]}`,\n );\n }\n const bug = parseBug(answer.bug);\n if (!bug) throw new BugsError(`The dispatcher sent no bug for ${task.id} this client reads.`);\n const items = (answer.items ?? []) as { item: string; covered_commit: string | null }[];\n const from = startFrom(task.track, answer.after);\n return {\n bug,\n objects: z.array(z.string()).catch([]).parse(answer.objects),\n after: ((answer.after ?? []) as { id?: string }[]).flatMap((a) => (a.id ? [a.id] : [])),\n // The task's items are the bug's cites on this track, not every track's.\n ...(items.length ? { items: items.map((i) => ({ item: i.item })) } : {}),\n covered: new Map(items.flatMap((i) => (i.covered_commit ? [[i.item, i.covered_commit] as const] : []))),\n ...(from.length ? { startFrom: from } : {}),\n };\n}\n\nexport interface BugObject {\n key: string;\n file?: string;\n shards?: string;\n /** The changes of the export that touched it, latest last (`changed_by`). */\n changed_by?: string[];\n}\n\nexport interface BugContext {\n task: string;\n bug: Bug;\n track: { code: string; kind: string; channels: string[] };\n export: string;\n questions?: Question[];\n after: string[];\n startFrom?: StartFrom[];\n checklist: { items: { item: string; what: string; covered?: string }[] };\n /** The objects the cites belong to, where each is in the export now. */\n objects: BugObject[];\n /** The changes the bug originates in, each with its title and proposal. */\n origin: { id: string; title?: string; proposal?: string }[];\n}\n\n/** The object key an item's ID starts with, among the task's objects; the item itself when none does. */\nexport const objectOfItem = (item: string, objects: readonly string[]): string =>\n [...objects]\n .filter(\n (o) => item === o || item.startsWith(`${o}-`) || item.startsWith(`${o}.`) || item.startsWith(`${o}#`),\n )\n .sort((a, b) => b.length - a.length)[0] ?? item.replace(/(-AC-\\d+|\\.A\\d+|#.+)$/, '');\n\n/**\n * A bug task's brief: the bug's words and cites, the cites as the checklist, the objects they belong to as they are\n * in the export now (a bug is fixed against the current text, not a delta), and the changes it originates in.\n */\nexport function bugContext(\n x: ExportReader,\n task: TaskRef,\n exportDir: string,\n state: BugTaskState,\n questions?: Question[],\n): BugContext {\n const track = x.work.tracks.find((t) => t.code === task.track) ?? {\n code: task.track,\n kind: 'ui',\n channels: [],\n };\n // The checklist is this track's cites, as the dispatcher's task holds them; a bug cited on two tracks has two tasks.\n const cites = state.items?.length ? state.items.map((i) => i.item) : state.bug.cites;\n const keys = [...new Set(state.objects.length ? state.objects : cites.map((c) => objectOfItem(c, [])))];\n const objects: BugObject[] = keys.map((key) => {\n const file = x.fileOf(key);\n const held = file !== undefined && x.has(file);\n const o: BugObject = { key, ...(held ? { file } : {}) };\n if (held && x.shards(file).length) o.shards = x.shards(file)[0]!.replace(/\\/[^/]+$/, '');\n const by = x.sources.get(key)?.changed_by;\n if (by?.length) o.changed_by = by;\n return o;\n });\n return {\n task: task.id,\n bug: state.bug,\n track: { code: track.code, kind: track.kind, channels: track.channels },\n export: exportDir,\n ...(questions?.length ? { questions } : {}),\n after: state.after,\n ...(state.startFrom?.length ? { startFrom: state.startFrom } : {}),\n checklist: {\n items: cites.map((item) => {\n const covered = state.covered?.get(item);\n return { item, what: itemWhat(x, item, undefined, task.track), ...(covered ? { covered } : {}) };\n }),\n },\n objects,\n origin: state.bug.origin.map((id) => {\n const change = x.work.changes.find((c) => c.id === id);\n const proposal = x.proposalPath(id);\n return { id, ...(change ? { title: change.title } : {}), ...(proposal ? { proposal } : {}) };\n }),\n };\n}\n\n/** The brief of a bug task as Markdown, for the agent. */\nexport function renderBugContext(c: BugContext): string {\n const b = c.bug;\n const out: string[] = [\n `# ${c.task}: ${b.title}`,\n '',\n `Track ${c.track.code} (${c.track.kind}${c.track.channels.length ? `: ${c.track.channels.join(', ')}` : ''}). ` +\n `Bug ${b.id}, raised by ${b.developer} on ${b.at.slice(0, 10)}${b.export ? `, groomed against export ${b.export.slice(0, 12)}` : ''}` +\n `${b.origin.length ? `, in what ${b.origin.join(', ')} built` : ''}. ` +\n `Paths are relative to the export, ${c.export}.`,\n ];\n if (c.after.length) out.push('', `Waits for: ${c.after.join(', ')}.`);\n if (c.startFrom?.length)\n out.push(\n '',\n `Start from ${c.startFrom.map((s) => `\\`${s.branch}\\` (${s.id}${s.commit ? ` done at ${s.commit.slice(0, 12)}` : ''})`).join(', then ')}, not from the main branch: ` +\n `the work the bug is in is pushed there and not merged yet (fetch it and base your branch on \\`origin/${c.startFrom[c.startFrom.length - 1]!.branch}\\`).`,\n );\n out.push('');\n if (c.questions?.length) out.push(...questionsSection(c.questions));\n out.push(\n '## The bug',\n '',\n 'The reporter’s words, naming IDs; what the spec says is in the export, under the objects below. The product deviates from the cited items: make it do what they say, and nothing else. The tasks that built them stay as they are; this task is the fix.',\n '',\n b.description.trim(),\n '',\n `Cites: ${b.cites.join(', ')}.`,\n );\n const done = c.checklist.items.filter((i) => i.covered).length;\n out.push(\n '',\n `## Checklist (${done} of ${c.checklist.items.length} covered)`,\n '',\n 'The cited items on this track. Name an item in `Alterspec-Covers` on the commit with which its tests pass again.',\n '',\n ...c.checklist.items.map(\n (i) =>\n `- [${i.covered ? 'x' : ' '}] \\`${i.item}\\`: ${i.what}${i.covered ? ` (covered by ${i.covered.slice(0, 12)})` : ''}`,\n ),\n );\n out.push('', '## The objects', '', 'What the spec says now; a bug is fixed against the current text.', '');\n for (const o of c.objects) {\n const where = o.file\n ? `\\`${o.file}\\`${o.shards ? `, shards in \\`${o.shards}/\\`` : ''}`\n : 'not in the export now';\n out.push(\n `- ${o.key}: ${where}${o.changed_by?.length ? `; last changed by ${o.changed_by.join(', ')}` : ''}.`,\n );\n }\n if (c.origin.length) {\n out.push(\n '',\n '## The changes it originates in',\n '',\n 'What was built and found wanting; their proposals say why.',\n '',\n );\n for (const ch of c.origin)\n out.push(`- ${ch.id}${ch.title ? ` ${ch.title}` : ''}${ch.proposal ? `: ${ch.proposal}` : ''}`);\n }\n out.push('');\n return out.join('\\n');\n}\n","import { z } from 'zod';\nimport { ObjectKey } from './change.js';\nimport { ChangeId } from './ids.js';\n\n/**\n * The record of what a signed-off change changed in the spec, written once at sign-off next to its archived proposal\n * (`delta.json`, rendered as `delta.md`). One entry per object whose content or place the sign-off changed, with its\n * text before and after; generated blocks are left out of both, so a regenerated view is never work.\n */\n\nconst Fingerprint = z.string().regex(/^[0-9a-f]{16}$/);\nconst Side = <T extends z.ZodType>(t: T) => z.object({ before: t.optional(), after: t.optional() }).strict();\nconst Binary = z.object({ sha256: z.string().regex(/^[0-9a-f]{64}$/), size: z.number().int() }).strict();\n\nexport const DeltaChange = z.enum(['added', 'modified', 'removed', 'moved']);\nexport type DeltaChange = z.infer<typeof DeltaChange>;\n\nexport const DeltaEntrySchema = z\n .object({\n key: ObjectKey,\n kind: z.enum(['doc', 'item', 'prose']),\n change: DeltaChange,\n file: Side(z.string()),\n /** The object's status before and after, when it has one. */\n status: Side(z.string()).optional(),\n /** Whether the export held the object before and after the sign-off (`buildBundle`). */\n exported: z.object({ before: z.boolean(), after: z.boolean() }).strict(),\n fingerprint: Side(Fingerprint),\n /** The text without generated blocks; absent for a binary file and for a side the object has no content on. */\n before: z.string().optional(),\n after: z.string().optional(),\n /** A binary file (an image): its hash and size instead of its text. */\n binary: Side(Binary).optional(),\n })\n .strict();\nexport type DeltaEntry = z.infer<typeof DeltaEntrySchema>;\n\nexport const DeltaSchema = z\n .object({\n change: ChangeId,\n title: z.string(),\n signed_off: z.iso.date().optional(),\n /** `git`: rebuilt afterwards from the repository's history by `alterspec migrate changes`. */\n recovered: z.literal('git').optional(),\n /** In the export: which objects it shows in export terms only (see the export README). */\n view: z.literal('export').optional(),\n objects: z.array(DeltaEntrySchema),\n /** Objects a rebuilt delta could not recover, with why. */\n unrecoverable: z.array(z.object({ key: z.string(), why: z.string() }).strict()).optional(),\n })\n .strict();\nexport type Delta = z.infer<typeof DeltaSchema>;\n","import { z } from 'zod';\nimport { AcceptSchema, Title, list } from './common.js';\nimport { ChangeId, ID_REGEX, InitiativeId, type IdKind } from './ids.js';\nimport { ItemWeight, TrackCode, WorkLabel, WorkSummary, WorkTitle, WorkWeight } from './work.js';\n\n/** `signed_off` is the end: a change is merged into the spec the moment the person signs it off. */\nexport const ChangeStatus = z.enum(['draft', 'in_review', 'signed_off', 'rejected'], {\n error: (iss) =>\n iss.input === 'applied' || iss.input === 'approved'\n ? `${iss.input} is no longer a status: a change is merged into the spec when it is signed off; \\`alterspec status migrate\\` moves a spec to the current statuses`\n : undefined,\n});\nexport type ChangeStatus = z.infer<typeof ChangeStatus>;\n\n/**\n * Key of an object a change touches: a spec ID, `term:<Term>` for a glossary term,\n * or `file:<path>` for a prose file such as application/nfr.md.\n */\nexport const ObjectKey = z\n .string()\n .refine(\n (v) =>\n /^term:\\S.*$/.test(v) ||\n /^file:[\\w./-]+\\.md$/.test(v) ||\n /^file:experience\\/(?:[a-z]{2,5}\\/)?mockups\\/[\\w./-]+$/.test(v) ||\n v === 'file:experience/data.js' ||\n (Object.keys(ID_REGEX) as IdKind[]).some(\n (k) => k !== 'screenAction' && k !== 'acceptance' && ID_REGEX[k].test(v),\n ),\n { message: 'must be a spec ID, term:<Term> or file:<path>' },\n );\n\nexport const ChangeSchema = z\n .object({\n id: ChangeId,\n title: Title,\n status: ChangeStatus,\n created: z.iso.date(),\n /** The day the change was signed off and merged. Written by the CLI. */\n signed_off: z.iso.date().optional(),\n /** Objects this change removes. */\n removes: list(ObjectKey),\n /**\n * Fingerprint of each touched object when the change started touching it (null = new object).\n * Written by the CLI; used to detect conflicts.\n */\n base: z.record(z.string(), z.string().nullable()).default({}),\n /**\n * The earlier signed-off changes this one builds on: developers take it after them. Written by the CLI at sign-off\n * once a baseline exists, never rewritten; `[]` builds on the baseline alone. Absent: signed off before the\n * baseline, part of it.\n */\n depends_on: z.array(ChangeId).optional(),\n /**\n * The tracks the change puts work on (`BE`, or the code of a channel with an experience of its own), each with the\n * keys of its delta that put it there; `{}` = no work. Written by the CLI at sign-off next to `depends_on`, never\n * rewritten, so a channel added later gives an old change no task.\n */\n tracks: z.record(TrackCode, z.array(z.string())).optional(),\n /**\n * The weight of each task item (`work.json`), 0–100, on every track that has no weight of its own for it\n * (`track_weights`): how much specified behaviour the item adds or changes, reasoned by the sign-off skill\n * against the rubric (`_weights.md`), never anyone's code. Written by `change weigh`, frozen at sign-off next\n * to `tracks` (`{}` = signed off without weighing); absent = signed off before weights existed. The dispatcher\n * weighs progress and ETA by it.\n */\n weights: z.record(z.string(), ItemWeight).optional(),\n /**\n * The weight of an item on one track where it differs from `weights`, by track then item, 0–100: the part of\n * the behaviour that track builds; 0 when it builds nothing of it (a criterion only another channel shows).\n * Written by `change weigh` (an entry with `track`), frozen at sign-off as it is.\n */\n track_weights: z.record(TrackCode, z.record(z.string(), ItemWeight)).optional(),\n /**\n * Superseded by `task_weights` (0.42.0): the size of the whole change, 1–100, as `change weigh` wrote it from\n * 0.34 to 0.41. Still read so an archived proposal stays valid; nothing uses it, and the next `change weigh`\n * with a task weight removes it.\n */\n change_weight: WorkWeight.optional(),\n /** Superseded with `change_weight`. */\n change_weight_why: z.string().optional(),\n /**\n * The size of each task's work, by track, 1–100 (`work.json` format 7, `tasks[].weight`): how much that track\n * builds in this change, reasoned by the sign-off skill against the rubric (`_weights.md` \"The task's weight\"),\n * never a sum of the item weights and never anyone's code. Written by `change weigh` (an entry `{ task }`),\n * archived as it is; absent = not weighed. The dispatcher shows it on each task's row.\n */\n task_weights: z\n .record(TrackCode, z.object({ weight: WorkWeight, why: z.string().optional() }).strict())\n .optional(),\n /**\n * What each track builds in this change, for a person reading a list (`work.json` format 5, `tasks[].title` and\n * `summary`): reasoned by the sign-off skill against the rubric (`_labels.md`), in the product's words, naming\n * no ID. Written by `change label`, archived as it is; absent = not titled.\n */\n task_words: z\n .record(TrackCode, z.object({ title: WorkTitle.optional(), summary: WorkSummary.optional() }).strict())\n .optional(),\n /**\n * What a task item is (`tasks[].labels`), by item: reasoned by the sign-off skill where the spec has no word\n * for the item (an acceptance criterion); the export composes the others from the spec. Written by\n * `change label`.\n */\n labels: z.record(z.string(), WorkLabel).optional(),\n /**\n * In a team project: the draft IDs the change and what it creates carried until the sign-off numbered them\n * (draft → final). Written by the CLI at sign-off.\n */\n drafted_as: z.record(z.string(), z.string()).optional(),\n /**\n * The initiative the change belongs to, if any: the envelope (`spec/initiatives/<INI>.md`) that says why it\n * exists. Grouping only: no status, no gate, outside the delta and every fingerprint. Written by\n * `change new --initiative` and `change initiative`, on an archived proposal too.\n */\n initiative: InitiativeId.optional(),\n /**\n * Set when the change alters behaviour another track already built (`alters` in `work.json`): its server task\n * reaches the main branch only after the change's client tasks are done. A hold, never a cycle in `after`.\n */\n coupled: z.literal(true).optional(),\n /** The first 16 hex of the sha256 of the change's `delta.json`, written with it at sign-off, never rewritten. */\n delta: z\n .string()\n .regex(/^[0-9a-f]{16}$/)\n .optional(),\n /**\n * Accepted findings on the archived change itself (`delta-chain`: a merge of parallel sign-offs no delta\n * recorded), each on a decided decision naming the change; history can't be fixed, only accepted.\n */\n accepts: list(AcceptSchema),\n })\n .strict()\n .superRefine((c, ctx) => {\n for (const key of Object.keys(c.base)) {\n if (!ObjectKey.safeParse(key).success) {\n ctx.addIssue({ code: 'custom', path: ['base', key], message: `${key} is not a valid object key` });\n }\n }\n });\n\nexport type Change = z.infer<typeof ChangeSchema>;\n","import { z } from 'zod';\nimport { DecisionId } from './ids.js';\n\n/**\n * How far a spec object has matured: `draft` while it is worked on, `ready` once it is complete and every check\n * passes, `signed_off` on the person's word, which is what lets it be handed off. Implementation is the development\n * teams' business, not the spec's: several teams may build the same spec, so `signed_off` is the last status.\n */\nexport const Status = z.enum(['draft', 'ready', 'signed_off'], {\n error: (iss) => {\n const was: Record<string, string> = {\n refined: 'refined is no longer a status; a complete object is ready',\n approved: 'approved is no longer a status; use signed_off',\n implemented:\n 'implemented is no longer a status (implementation is tracked by the teams, not in the spec)',\n };\n const said = typeof iss.input === 'string' ? was[iss.input] : undefined;\n return said ? `${said}; \\`alterspec status migrate\\` moves a spec to the current statuses` : undefined;\n },\n});\nexport type Status = z.infer<typeof Status>;\n\n/** Permission scope: which data a role may act on. */\nexport const Scope = z.enum(['own', 'team', 'org', 'all']);\nexport type Scope = z.infer<typeof Scope>;\n\n/** Entity operations: Create, Read, Update, Delete, Archive. */\nexport const Op = z.enum(['C', 'R', 'U', 'D', 'A']);\n\nexport const Title = z.string().trim().min(1, { message: 'must not be empty' });\nexport const Version = z.number().int().min(1);\n\n/** Lifecycle state name, e.g. `draft`, `active`, `on_leave`. */\nexport const StateName = z.string().regex(/^[a-z][a-z0-9_]*$/, {\n message: 'must be a lowercase state name (letters, digits, underscore)',\n});\n\n/** A state transition written as `from->to`. */\nexport const TransitionRef = z.string().regex(/^[a-z][a-z0-9_]*->[a-z][a-z0-9_]*$/, {\n message: 'must be written as from->to, e.g. draft->active',\n});\n\nexport const list = <T extends z.ZodType>(item: T) => z.array(item).default([]);\n\n/**\n * A finding of one lint rule on this object that is true of the product and accepted, on a decision that says why\n * (2026-10-27). An accepted finding is reported, not counted: it doesn't stop a status, a change or a handoff.\n */\nexport const AcceptSchema = z\n .object({\n /** The lint rule's name. */\n rule: z.string().trim().min(1),\n /** Part of the finding's message; absent, every finding of the rule on this object is accepted. */\n match: z.string().trim().min(1).optional(),\n /** The decided `DEC-NNN` (kind decision) that records why, naming this object in `affects`. */\n decision: DecisionId,\n reason: z.string().trim().min(1),\n })\n .strict();\n\nexport type Accept = z.infer<typeof AcceptSchema>;\n","import { z } from 'zod';\n\n/**\n * Single source of truth for alterspec ID formats.\n * Module codes are 2–6 uppercase letters (e.g. HR, INV). `GLB` is reserved for the global module.\n */\nconst CODE = '[A-Z]{2,6}';\nconst NAME = '[A-Z0-9]+(?:-[A-Z0-9]+)*';\n/** Channel codes (application.md `channels[].code`): 2–5 uppercase letters, e.g. WEB, MOB. */\nexport const CHANNEL_CODE = '[A-Z]{2,5}';\n/**\n * A draft number: what a numbered ID carries while its change is open in a team project (`team` in the config).\n * `T`, a digit, three more characters (`CHG-T4K9Q`); the digit tells it from a module code. The sign-off replaces\n * it with the next sequential number, so it never reaches the spec itself, the archive or the export.\n */\nexport const DRAFT_NUMBER = 'T\\\\d[A-Z0-9]{3}';\nconst N2 = `(?:\\\\d{2}|${DRAFT_NUMBER})`;\nconst N3 = `(?:\\\\d{3}|${DRAFT_NUMBER})`;\n/** Unanchored sources, for the patterns other files build from an ID. */\nexport const CAPABILITY_ID = `CAP-${CODE}-${N3}`;\nexport const SCREEN_ID = `SCR-${CODE}-${N2}`;\nexport const APP_RULE_ID = `RULE-${N3}`;\nexport const DECISION_ID = `DEC-${N3}`;\n\nexport const ID_PATTERNS = {\n app: '^APP$',\n module: `^MOD-${CODE}$`,\n capability: `^${CAPABILITY_ID}$`,\n screen: `^${SCREEN_ID}$`,\n role: `^ROLE-${NAME}$`,\n persona: `^PER-${NAME}$`,\n entity: `^ENT-${NAME}$`,\n rule: `^RULE-(?:${CODE}-)?${N3}$`,\n flow: `^FLOW-${N3}$`,\n event: `^EVT-${NAME}$`,\n decision: `^${DECISION_ID}$`,\n change: `^CHG-${N3}$`,\n integration: `^INT-${NAME}$`,\n nfr: `^NFR-${N3}$`,\n acceptance: `^${CAPABILITY_ID}-AC-\\\\d{2}$`,\n screenAction: '^A\\\\d{2}$',\n experience: `^UX-${SCREEN_ID}-${CHANNEL_CODE}$`,\n} as const;\n\nexport type IdKind = keyof typeof ID_PATTERNS;\n\nexport const ID_REGEX: Record<IdKind, RegExp> = Object.fromEntries(\n Object.entries(ID_PATTERNS).map(([k, p]) => [k, new RegExp(p)]),\n) as Record<IdKind, RegExp>;\n\nconst idOf = (kind: IdKind, label: string) =>\n z.string().regex(ID_REGEX[kind], { message: `must be a ${label} ID matching ${ID_PATTERNS[kind]}` });\n\nexport const AppId = idOf('app', 'application');\nexport const ModuleId = idOf('module', 'module');\nexport const CapabilityId = idOf('capability', 'capability');\nexport const ScreenId = idOf('screen', 'screen');\nexport const ExperienceId = idOf('experience', 'experience screen');\nexport const RoleId = idOf('role', 'role');\nexport const IntegrationId = idOf('integration', 'integration');\nexport const NfrId = idOf('nfr', 'non-functional requirement');\nexport const PersonaId = idOf('persona', 'persona');\nexport const EntityId = idOf('entity', 'entity');\nexport const RuleId = idOf('rule', 'rule');\nexport const FlowId = idOf('flow', 'flow');\nexport const EventId = idOf('event', 'event');\nexport const DecisionId = idOf('decision', 'decision');\nexport const ChangeId = idOf('change', 'change');\nexport const AcceptanceId = idOf('acceptance', 'acceptance criterion');\nexport const ScreenActionId = idOf('screenAction', 'screen action');\n/**\n * An initiative: the envelope around a group of changes, named by the person (`INI-SUPPLIER-ONBOARDING`), never\n * numbered. It is not a spec object, so its pattern stays out of `ID_PATTERNS`: never an `AnyId`, an object key of\n * a change or an ID a lint rule looks for in prose.\n */\nexport const INITIATIVE_ID = `INI-${NAME}`;\nconst INITIATIVE_REGEX = new RegExp(`^${INITIATIVE_ID}$`);\nexport const InitiativeId = z.string().regex(INITIATIVE_REGEX, {\n message: `must be an initiative ID matching ^${INITIATIVE_ID}$, e.g. INI-ONBOARDING`,\n});\nexport const isInitiativeId = (id: string): boolean => INITIATIVE_REGEX.test(id);\nexport const ChannelCode = z\n .string()\n .regex(new RegExp(`^${CHANNEL_CODE}$`), { message: 'must be 2–5 uppercase letters, e.g. WEB or MOB' });\n\n/** Any spec object ID (used where several kinds are allowed, e.g. change deltas). */\nexport const AnyId = z\n .string()\n .refine(\n (v) => (Object.keys(ID_REGEX) as IdKind[]).some((k) => k !== 'screenAction' && ID_REGEX[k].test(v)),\n { message: 'must be a valid alterspec ID' },\n );\n\n/** Module code from a module ID: MOD-HR → HR. */\nexport const moduleCode = (moduleId: string): string => moduleId.replace(/^MOD-/, '');\n\n/** Module code embedded in a CAP/SCR/module-RULE ID: CAP-HR-004 → HR. */\nexport const codeInId = (id: string): string | undefined => /^(?:CAP|SCR|RULE)-([A-Z]{2,6})-/.exec(id)?.[1];\n\n/** Detect the kind of an ID, or undefined. */\nexport function idKind(id: string): IdKind | undefined {\n return (Object.keys(ID_REGEX) as IdKind[]).find((k) => ID_REGEX[k].test(id));\n}\n\nconst DRAFT = new RegExp(\n `^(?:CHG|FLOW|DEC|NFR|RULE|(?:CAP|SCR|RULE)-${CODE}|UX-SCR-${CODE})-${DRAFT_NUMBER}(?:-|$)`,\n);\n/** Whether an ID (or an ID derived from one: a criterion, an experience screen) carries a draft number. */\nexport const isDraftId = (id: string): boolean => DRAFT.test(id) && idKind(id) !== undefined;\n\nconst NUMBERED = new Set<IdKind>(['capability', 'screen', 'rule', 'flow', 'decision', 'change', 'nfr']);\n/** Whether the CLI numbers this ID (the others are named by the person). */\nexport const isNumberedId = (id: string): boolean => NUMBERED.has(idKind(id) as IdKind);\n","import { DeltaSchema, type Delta, type DeltaEntry } from '../schemas/delta.js';\n\n/**\n * Reading a change's delta, apart from computing it (`delta.ts`): imports only the schema, so the client bundles it\n * to read the deltas of an export.\n */\n\n/** The record's files, next to the archived proposal. */\nexport const DELTA_JSON = 'delta.json';\nexport const DELTA_MD = 'delta.md';\n/** `changes/archive/CHG-NNN/delta.json`, at the root or in a module. */\nexport const ARCHIVED_DELTA = /^(?:modules\\/[^/]+\\/)?changes\\/archive\\/(?<change>[^/]+)\\/delta\\.json$/;\n\nexport function parseDelta(json: string): Delta | undefined {\n try {\n const parsed = DeltaSchema.safeParse(JSON.parse(json));\n return parsed.success ? parsed.data : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** What an entry means for developers, in export terms. */\nexport function exportChange(e: DeltaEntry): string {\n const { before, after } = e.exported;\n if (before && after) return e.change;\n if (after) return 'enters the export';\n if (before) return 'leaves the export';\n return 'not in the export';\n}\n","/**\n * A change's compatibility: what the server keeps accepting from the apps as they are today while the change's other\n * tracks build it, declared in the proposal's \"## Compatibility\" section as the criteria that say so, by ID. Ending\n * it is a change of its own, whose backend task the export puts after every task of the change that kept it.\n * Imports nothing, so the client (which carries no YAML parser) shares the names with the export.\n */\n\n/** The proposal section. */\nexport const COMPATIBILITY_SECTION = 'Compatibility';\n\n/** The section's text when it declares a compatibility: not empty and not \"None.\" (comments already removed). */\nexport function compatibilityText(sectionText: string | undefined): string | undefined {\n const text = sectionText?.trim();\n return text && !/^none\\b/i.test(text) ? text : undefined;\n}\n","/**\n * A change's one-time data change: what the release does once to the records the product already holds, declared in\n * the proposal's \"## One-time data change\" section and carried to the backend as the item `CHG-NNN#data-change`.\n * Imports nothing, so the client (which carries no YAML parser) shares the names with the export that writes them.\n */\n\n/** The proposal section. */\nexport const DATA_CHANGE_SECTION = 'One-time data change';\n\n/** The suffix of the backend item: `CHG-NNN#data-change`. */\nexport const DATA_CHANGE_ITEM = 'data-change';\n\n/** The item regex: the change it belongs to is group 1. */\nexport const DATA_CHANGE_RE = new RegExp(`^(CHG-\\\\d{3,})#${DATA_CHANGE_ITEM}$`);\n\n/** The section's text when it declares a change: not empty and not \"None.\" (comments already removed). */\nexport function dataChangeText(sectionText: string | undefined): string | undefined {\n const text = sectionText?.trim();\n return text && !/^none\\b/i.test(text) ? text : undefined;\n}\n","/**\n * The names an export's files are written under. Imports nothing: alterspec writes the export with them and the\n * client (`client/`) reads it with the same ones, so a change of the layout and the reader land in one commit.\n */\n\n/** The file every export opens with: how to read it, run its mockups and build from it. */\nexport const README = 'README.md';\n/** The export's own record: the alterspec version, the date and every source with its fingerprint. */\nexport const EXPORT_JSON = 'export.json';\n/** The work every signed-off change implies, for the dispatcher. */\nexport const WORK_JSON = 'work.json';\n\n/** Where the shards of an export live: one folder per file, at the file's path without `.md`. */\nexport const SHARDS_DIR = '_shards';\n\n/** A heading or a term as a file name: lower case, ASCII letters and digits, words joined by `-`. */\nexport const slug = (text: string) =>\n text\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n // Letters that don't decompose into a base letter and a mark.\n .replace(/[đłøæœßþ]/g, (c) => ({ đ: 'd', ł: 'l', ø: 'o', æ: 'ae', œ: 'oe', ß: 'ss', þ: 'th' })[c] ?? c)\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 60)\n .replace(/-+$/, '') || 'section';\n\n/** The shard folder of an export file. */\nexport const shardDir = (path: string) => `${SHARDS_DIR}/${path.replace(/\\.md$/, '')}`;\n\n/** The shard of a collection item, named by its key (the ID, or the term's slug in the glossary). */\nexport const itemShardName = (key: string) => `${key.startsWith('term:') ? slug(key.slice(5)) : key}.md`;\nexport const itemShardPath = (path: string, key: string) => `${shardDir(path)}/${itemShardName(key)}`;\n\n/** A document's shards: its front-matter, its introduction, then one per `## ` section, numbered from 02. */\nexport const FRONT_MATTER_SHARD = '00-front-matter.yaml';\nexport const INTRO_SHARD = '01-introduction.md';\nexport const sectionShardName = (index: number, heading: string) =>\n `${String(index + 2).padStart(2, '0')}-${slug(heading)}.md`;\n/** Whether a shard file name is the section with this heading (whatever its number). */\nexport const isSectionShard = (name: string, heading: string) =>\n new RegExp(`^\\\\d{2}-${slug(heading)}\\\\.md$`).test(name);\n","const FRONT_MATTER = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---[ \\t]*(?:\\r?\\n|$)/;\n\nexport interface FrontMatterSplit {\n /** Raw YAML between the `---` lines, or undefined when there is no front-matter. */\n raw: string | undefined;\n body: string;\n /** 1-based line where the body starts. */\n bodyLine: number;\n}\n\n/**\n * Split a markdown file into raw front-matter and body without parsing the YAML. Imports nothing, so the client can\n * bundle it without a YAML parser.\n */\nexport function splitFrontMatter(source: string): FrontMatterSplit {\n const m = FRONT_MATTER.exec(source);\n if (!m) return { raw: undefined, body: source, bodyLine: 1 };\n return {\n raw: m[1] ?? '',\n body: source.slice(m[0].length),\n bodyLine: m[0].split('\\n').length - (m[0].endsWith('\\n') ? 0 : 1),\n };\n}\n","import { slug } from '../export/paths.js';\nimport { splitFrontMatter } from '../lib/frontmatter-split.js';\n\n/**\n * The finer parts of an object a task changes as a whole, for the checklist (`taskItems`) and the brief: an object\n * whose kind has no part of its own on the track (a criterion, a screen action, a contract state) is cut into the\n * parts its own text has, so that one open question about one record kind of a quality requirement doesn't hold the\n * whole requirement out of the task's progress. Imports no YAML parser: the client bundles it.\n */\n\nexport type PartLabel = 'front-matter' | 'section' | 'line';\n\nexport interface ObjectPart {\n label: PartLabel;\n /** The section's heading, the bullet's lead, or `front-matter`. */\n heading: string;\n /** The part's text as the work compares it. */\n text: string;\n}\n\nexport const FRONT_MATTER_PART = 'front-matter';\n\n/**\n * The object an item belongs to: `CAP-X-AC-03` → `CAP-X`, `SCR-X.A01` → `SCR-X`, `UX-SCR-X-BO#state` → `UX-SCR-X-BO`,\n * `NFR-019#sign-in` → `NFR-019`; a file is its own.\n */\nexport const itemObject = (item: string): string =>\n item.startsWith('file:') ? item : item.replace(/-AC-\\d{2}$/, '').replace(/[.#][^.#]*$/, '');\n\n/**\n * An object's text as the work compares it: without the template's comments, the `version:` line the sign-off\n * raises and the fingerprints a contract keeps, which tell a builder nothing.\n */\nexport const forWork = (text: string) =>\n text\n .replace(/^[^\\S\\n]*<!--[\\s\\S]*?-->[^\\S\\n]*\\n/gm, '')\n .replace(/<!--[\\s\\S]*?-->/g, '')\n .replace(/^version:[^\\S\\n]*\\d+[^\\S\\n]*\\n/m, '')\n .replace(/^(?:reviewed|dry|page):[^\\n]*\\n/gm, '');\n\n/**\n * The parts of an object's text, each under the slug the checklist names it by (`<KEY>#<slug>`): a document's\n * front-matter (`front-matter`) and its `## ` sections; a collection item's yaml block (`front-matter`) and its `### `\n * sections, else the top-level bullets of its body, each by its lead (the text before its first colon, dash or full\n * stop, at most eight words). Two parts with one slug are told apart by a number. What is in no part (a title, an\n * introduction) is the object's own.\n */\nexport function objectParts(text: string, kind: 'doc' | 'item'): Map<string, ObjectPart> {\n const out = new Map<string, ObjectPart>();\n const put = (label: PartLabel, heading: string, body: string) => {\n const base = label === 'front-matter' ? FRONT_MATTER_PART : slug(heading);\n let key = base;\n for (let n = 2; out.has(key); n++) key = `${base}-${n}`;\n out.set(key, { label, heading, text: body });\n };\n const t = forWork(text);\n if (kind === 'doc') {\n const { raw, body } = splitFrontMatter(t);\n if (raw) put('front-matter', FRONT_MATTER_PART, raw);\n for (const s of headed(body, '## ').sections) put('section', s.heading, s.text);\n return out;\n }\n const yaml = /^```ya?ml\\n([\\s\\S]*?)\\n```[^\\S\\n]*$/m.exec(t);\n if (yaml) put('front-matter', FRONT_MATTER_PART, yaml[1]!);\n const body = yaml ? t.slice(yaml.index + yaml[0].length) : t.replace(/^## [^\\n]*\\n?/, '');\n const { sections } = headed(body, '### ');\n if (sections.length) for (const s of sections) put('section', s.heading, s.text);\n else for (const b of bullets(body)) put('line', b.heading, b.text);\n return out;\n}\n\n/** The text of an object outside its parts: the title and introduction of a document, an item's heading and prose. */\nexport function restOf(text: string, kind: 'doc' | 'item'): string {\n const t = forWork(text);\n if (kind === 'doc') return headed(splitFrontMatter(t).body, '## ').intro;\n const yaml = /^```ya?ml\\n[\\s\\S]*?\\n```[^\\S\\n]*$/m.exec(t);\n const body = yaml ? t.slice(yaml.index + yaml[0].length) : t;\n const { intro, sections } = headed(body, '### ');\n if (sections.length) return (yaml ? t.slice(0, yaml.index) : '') + intro;\n return (yaml ? t.slice(0, yaml.index) : '') + withoutBullets(body);\n}\n\n/** A text cut at its headings of one level (fenced blocks respected), with what comes before the first. */\nfunction headed(\n text: string,\n marker: string,\n): { intro: string; sections: { heading: string; text: string }[] } {\n const sections: { heading: string; text: string }[] = [];\n let intro = '';\n let fence = false;\n for (const l of text.split('\\n')) {\n if (/^(?:```|~~~)/.test(l)) fence = !fence;\n if (!fence && l.startsWith(marker) && /\\S/.test(l.slice(marker.length))) {\n sections.push({ heading: l.slice(marker.length).trim(), text: '' });\n continue;\n }\n if (sections.length) sections[sections.length - 1]!.text += `${l}\\n`;\n else intro += `${l}\\n`;\n }\n return { intro, sections };\n}\n\nconst BULLET = /^(?:[-*+]|\\d+[.)])\\s+(.*)$/;\n\n/** The top-level bullets of a body (fenced blocks left out), each with its indented continuation lines. */\nfunction bullets(text: string): { heading: string; text: string }[] {\n const out: { heading: string; text: string }[] = [];\n let current: { heading: string; text: string } | undefined;\n let fence = false;\n for (const l of text.split('\\n')) {\n if (/^(?:```|~~~)/.test(l)) {\n fence = !fence;\n current = undefined;\n continue;\n }\n if (fence) continue;\n const m = BULLET.exec(l);\n if (m) {\n current = { heading: lead(m[1]!), text: `${l}\\n` };\n out.push(current);\n } else if (current && /^\\s+\\S/.test(l)) current.text += `${l}\\n`;\n else current = undefined;\n }\n return out;\n}\n\n/** A body without its top-level bullets and their continuation lines. */\nfunction withoutBullets(text: string): string {\n const kept: string[] = [];\n let inBullet = false;\n let fence = false;\n for (const l of text.split('\\n')) {\n if (/^(?:```|~~~)/.test(l)) {\n fence = !fence;\n inBullet = false;\n kept.push(l);\n continue;\n }\n if (fence) {\n kept.push(l);\n continue;\n }\n if (BULLET.test(l)) inBullet = true;\n else if (!(inBullet && /^\\s+\\S/.test(l))) {\n inBullet = false;\n kept.push(l);\n }\n }\n return kept.join('\\n');\n}\n\n/** A bullet's lead: its text before the first colon, dash or full stop, at most eight words, without emphasis. */\nconst lead = (s: string) =>\n s\n .replace(/\\*\\*|__|`/g, '')\n .split(/:\\s|:$|\\s[—–-]\\s|\\.\\s|\\.$/)[0]!\n .trim()\n .split(/\\s+/)\n .slice(0, 8)\n .join(' ');\n","import { existsSync, readFileSync, readdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { DELTA_JSON, parseDelta } from '../changes/delta-record.js';\nimport { splitFrontMatter } from '../lib/frontmatter-split.js';\nimport type { Delta } from '../schemas/delta.js';\nimport { ID_PATTERNS, type IdKind } from '../schemas/ids.js';\nimport { AnyWorkSchema, type AnyWork } from '../schemas/work.js';\nimport { INDEX_FILE, ROOT_DOCS, archiveDir, initiativePath, moduleDir } from '../spec/layout.js';\nimport { EXPORT_JSON, WORK_JSON, isSectionShard, itemShardPath, shardDir } from './paths.js';\n\n/**\n * Reading a finished export, for the client (`client/`), which bundles this module: what the export holds is found\n * through `export.json` and the paths alterspec writes it under, never by searching. Imports no YAML parser and\n * nothing of the spec model.\n */\n\nexport class ExportReadError extends Error {}\n\nexport interface ExportSource {\n id: string;\n status?: string;\n file: string;\n /** The signed-off changes that touched it, oldest first (alterspec 0.20). */\n changed_by?: string[];\n}\n\n/**\n * What the client reads of `_generated/index.json`: the structured facts the Markdown keeps in YAML (a screen's\n * fields, a capability's data in and out, a rule's guards, an entity's attributes), typed only as far as it reads them.\n */\nexport interface ExportIndex {\n screens: {\n id: string;\n title: string;\n roles?: { role: string }[];\n fields: { entity: string; attributes: string[]; mode: string }[];\n }[];\n capabilities: {\n id: string;\n title: string;\n roles?: { role: string; scope?: string }[];\n screens?: string[];\n entities: { entity: string }[];\n rules?: string[];\n inputs?: ({ entity: string; attributes: string[] } | { transient: string })[];\n outputs?: ({ entity: string; attributes: string[] } | { transient: string })[];\n }[];\n rules: { id: string; title: string; entities: string[]; guards?: { entity: string }[] }[];\n entities: {\n id: string;\n title: string;\n attributes: { name: string; kind: string; references?: string }[];\n states?: string[];\n initial_state?: string;\n transitions?: { from: string; to: string; by?: string; at?: string }[];\n }[];\n}\n\nexport interface ExportReader {\n dir: string;\n /** `work.json`, any format (1 to 9). */\n work: AnyWork;\n /** The export's sources by ID. */\n sources: Map<string, ExportSource>;\n /** The file holding an object key: a spec ID, `file:<path>` or `term:<Term>`. */\n fileOf(key: string): string | undefined;\n /** An export file's text, or undefined when the export doesn't hold it. */\n read(path: string): string | undefined;\n has(path: string): boolean;\n /** `changes/archive/<CHG>/proposal.md`, at the root or in a module. */\n proposalPath(change: string): string | undefined;\n /** The change's delta as the export shows it. */\n delta(change: string): Delta | undefined;\n /** The shards of an export file, sorted. */\n shards(file: string): string[];\n /** The shard of a document's `## ` section, found by its heading. */\n sectionShard(file: string, heading: string): string | undefined;\n /** The shard of a collection item. */\n itemShard(file: string, key: string): string | undefined;\n /** `_generated/index.json`, when the export has it. */\n index(): ExportIndex | undefined;\n /** An initiative the export carries (format 8): its title from `work.json`, its prose from its file. */\n initiative(id: string): { id: string; title: string; body: string } | undefined;\n}\n\nfunction readJson(dir: string, name: string): unknown {\n const path = join(dir, name);\n if (!existsSync(path)) throw new ExportReadError(`${dir} is not an alterspec export: it has no ${name}.`);\n try {\n return JSON.parse(readFileSync(path, 'utf8'));\n } catch {\n throw new ExportReadError(`${join(dir, name)} is not valid JSON.`);\n }\n}\n\nexport function readExport(dir: string): ExportReader {\n const exp = readJson(dir, EXPORT_JSON) as { sources?: ExportSource[] };\n const parsed = AnyWorkSchema.safeParse(readJson(dir, WORK_JSON));\n if (!parsed.success)\n throw new ExportReadError(`${join(dir, WORK_JSON)} is not a work.json this client reads.`);\n const sources = new Map((exp.sources ?? []).map((s) => [s.id, s]));\n const has = (path: string) => existsSync(join(dir, path));\n const read = (path: string) => (has(path) ? readFileSync(join(dir, path), 'utf8') : undefined);\n const modules = () =>\n existsSync(join(dir, 'modules')) ? readdirSync(join(dir, 'modules')).map((m) => moduleDir(m)) : [];\n\n const shards = (file: string) => {\n const folder = shardDir(file);\n return has(folder)\n ? readdirSync(join(dir, folder))\n .sort()\n .map((n) => `${folder}/${n}`)\n : [];\n };\n\n let indexCache: ExportIndex | undefined | null = null;\n const index = () => {\n if (indexCache === null) {\n const text = read(INDEX_FILE);\n indexCache = text ? (JSON.parse(text) as ExportIndex) : undefined;\n }\n return indexCache;\n };\n\n const proposalPath = (change: string) =>\n [archiveDir(), ...modules().map((m) => `${m}/changes/archive`)]\n .map((a) => `${a}/${change}/proposal.md`)\n .find(has);\n\n return {\n dir,\n work: parsed.data,\n sources,\n has,\n read,\n fileOf(key) {\n if (key.startsWith('file:')) return key.slice(5);\n if (key.startsWith('term:')) return ROOT_DOCS.glossary;\n return sources.get(key)?.file;\n },\n proposalPath,\n delta(change) {\n const proposal = proposalPath(change);\n const json = proposal && read(proposal.replace(/proposal\\.md$/, DELTA_JSON));\n return json ? parseDelta(json) : undefined;\n },\n shards,\n sectionShard(file, heading) {\n const prefix = `${shardDir(file)}/`;\n return shards(file).find((p) => isSectionShard(p.slice(prefix.length), heading));\n },\n itemShard(file, key) {\n const path = itemShardPath(file, key);\n return has(path) ? path : undefined;\n },\n index,\n initiative(id) {\n const work = parsed.data;\n const title = 'initiatives' in work ? work.initiatives?.find((i) => i.id === id)?.title : undefined;\n const text = read(initiativePath(id));\n if (!title || text === undefined) return undefined;\n return { id, title, body: splitFrontMatter(text).body };\n },\n };\n}\n\n/** The IDs of the given kinds a text names, in order of first appearance. */\nexport function idsIn(text: string, kinds: IdKind[]): string[] {\n const pattern = new RegExp(\n kinds.map((k) => `(?:${ID_PATTERNS[k].replace(/^\\^|\\$$/g, '')})`).join('|'),\n 'g',\n );\n const out: string[] = [];\n for (const m of text.matchAll(new RegExp(`(?<![A-Z0-9-])(?:${pattern.source})(?![A-Z0-9-])`, 'g')))\n if (!out.includes(m[0])) out.push(m[0]);\n return out;\n}\n\n/** The raw front-matter of an export document, unparsed. */\nexport const frontMatterOf = (text: string) => splitFrontMatter(text).raw ?? '';\n","import { codeInId, SCREEN_ID } from '../schemas/ids.js';\nimport type { SpecFile } from './files.js';\n\n/**\n * Where everything lives under spec/. The spec folder is the application: its documents sit at the root, shared\n * entities in `entities/`, flows in `flows/`, changes that touch several modules in `changes/`. A module folder\n * holds its own entities, rules, changes, capabilities and screens; each screen is a folder with the business\n * document and one experience contract per channel. IDs are identity, folders are placement: nothing is renamed\n * when it moves, and placement is the CLI's, never the person's (`alterspec place`).\n */\n\n/** The application's documents at the spec root, by file type. */\nexport const ROOT_DOCS = {\n application: 'application.md',\n 'personas-roles': 'personas-roles.md',\n glossary: 'glossary.md',\n rules: 'rules.md',\n events: 'events.md',\n decisions: 'decisions.md',\n integrations: 'integrations.md',\n nfr: 'nfr.md',\n} as const;\nexport type RootDoc = keyof typeof ROOT_DOCS;\n\nexport const APPLICATION = ROOT_DOCS.application;\nexport const MODULES_DIR = 'modules';\nexport const CHANGES_DIR = 'changes';\nexport const ENTITIES_DIR = 'entities';\nexport const FLOWS_DIR = 'flows';\n/** Initiatives: prose envelopes around groups of changes, outside the spec model (the loader ignores them). */\nexport const INITIATIVES_DIR = 'initiatives';\n\n/** The record of the exports' releases (`export --only`), at the spec root: JSON, outside the spec model. */\nexport const RELEASES_FILE = 'releases.json';\n\n/** `HR` or `MOD-HR` → `modules/hr`. */\nexport const moduleDir = (code: string) => `${MODULES_DIR}/${code.replace(/^MOD-/, '').toLowerCase()}`;\nexport const moduleDoc = (code: string) => `${moduleDir(code)}/module.md`;\nexport const moduleRulesPath = (code: string) => `${moduleDir(code)}/rules.md`;\n\n/** The module folder an ID with a module code belongs to (CAP, SCR, RULE-<MOD>), or undefined. */\nexport const moduleDirOf = (id: string): string | undefined => {\n const code = codeInId(id);\n return code ? moduleDir(code) : undefined;\n};\n\n/** The module (lower-case folder name) a path sits in, or undefined at the root. */\nexport const moduleOfPath = (path: string): string | undefined =>\n new RegExp(`^${MODULES_DIR}/([^/]+)/`).exec(path)?.[1];\n\nexport const capabilityPath = (id: string) => `${moduleDirOf(id)}/capabilities/${id}.md`;\n/** An entity at the root, or inside the module (lower-case folder name or code) that alone uses it. */\nexport const entityPath = (id: string, mod?: string) =>\n mod ? `${moduleDir(mod)}/${ENTITIES_DIR}/${id}.md` : `${ENTITIES_DIR}/${id}.md`;\nexport const flowPath = (id: string) => `${FLOWS_DIR}/${id}.md`;\nexport const initiativePath = (id: string) => `${INITIATIVES_DIR}/${id}.md`;\n\n/** A screen is a folder: its document, its experience contracts (one per channel) and its reverse-spec screenshots. */\nexport const screenDir = (screenId: string) => `${moduleDirOf(screenId)}/screens/${screenId}`;\nexport const screenDoc = (screenId: string) => `${screenDir(screenId)}/screen.md`;\nexport const contractPath = (screenId: string, code: string) =>\n `${screenDir(screenId)}/experience/${code.toLowerCase()}.md`;\nexport const screenshotsDir = (screenId: string) => `${screenDir(screenId)}/mockups`;\n\n/** A channel's experience layer: design system, patterns and its mockup app, one page per screen. */\nexport const EXPERIENCE_DIR = 'experience';\nexport const surfaceDir = (code: string) => `${EXPERIENCE_DIR}/${code.toLowerCase()}`;\nexport const mockupPath = (code: string, screenId: string) => `${surfaceDir(code)}/mockups/${screenId}.html`;\nexport const patternsPath = (code: string) => `${surfaceDir(code)}/patterns.md`;\nexport const designSystemPath = (code: string) => `${surfaceDir(code)}/design-system.md`;\n\n/** The operations catalogue, generated while a capability is exposed on an API channel. */\nexport const OPERATIONS_FILE = '_generated/operations.md';\n/** The spec's objects as JSON (`index(model)` in src/views/render.ts); the export carries it, the client reads it. */\nexport const INDEX_FILE = '_generated/index.json';\n/** Where the rule matrix is written, relative to spec/; an export carries it too. */\nexport const RULE_MATRIX_FILE = '_generated/rule-matrix.md';\n\nconst CONTRACT = new RegExp(\n `^modules/[^/]+/screens/(?<screen>${SCREEN_ID})/experience/(?<code>[a-z]{2,5})\\\\.md$`,\n);\n/** `modules/prc/screens/SCR-PRC-01/experience/bo.md` → { screen: SCR-PRC-01, channel: BO }. */\nexport function parseContractPath(path: string): { screen: string; channel: string } | undefined {\n const m = CONTRACT.exec(path);\n return m ? { screen: m.groups!.screen!, channel: m.groups!.code!.toUpperCase() } : undefined;\n}\n\n/** `changes` at the root, or a module's. */\nexport const changesDir = (mod?: string) => (mod ? `${moduleDir(mod)}/${CHANGES_DIR}` : CHANGES_DIR);\nexport const changeDirOf = (id: string, mod?: string) => `${changesDir(mod)}/${id}`;\nexport const archiveDir = (mod?: string) => `${changesDir(mod)}/archive`;\n\nconst CHANGE_PREFIX = String.raw`^(?:${MODULES_DIR}\\/[^/]+\\/)?${CHANGES_DIR}\\/`;\nconst CHANGE_FILE = new RegExp(CHANGE_PREFIX);\nconst ARCHIVED_FILE = new RegExp(`${CHANGE_PREFIX}archive\\\\/`);\nconst OVERLAY_FILE = new RegExp(`${CHANGE_PREFIX}[^/]+\\\\/spec\\\\/`);\nconst WORK_FILE = new RegExp(`${CHANGE_PREFIX}[^/]+\\\\/(?:impact|groom(?:-[^/]+)?)\\\\.md$`);\nexport const PROPOSAL_FILE = new RegExp(\n String.raw`^(?:${MODULES_DIR}\\/(?<mod>[^/]+)\\/)?${CHANGES_DIR}\\/(?<change>[^/]+)\\/proposal\\.md$`,\n);\n/** The proposal of an archived change, at the root or in a module. */\nexport const ARCHIVED_PROPOSAL = new RegExp(\n String.raw`^(?:${MODULES_DIR}\\/(?<mod>[^/]+)\\/)?${CHANGES_DIR}\\/archive\\/(?<change>[^/]+)\\/proposal\\.md$`,\n);\n\n/** Anything under a changes folder, at the root or in a module. */\nexport const isChangeFile = (path: string) => CHANGE_FILE.test(path);\nexport const isArchivedFile = (path: string) => ARCHIVED_FILE.test(path);\n/** A file of a change's overlay spec (`changes/CHG-NNN/spec/…`). */\nexport const isOverlayFile = (path: string) => OVERLAY_FILE.test(path);\n/** A change's working documents next to its proposal: impact and grooming. */\nexport const isChangeWorkFile = (path: string) => WORK_FILE.test(path);\n/** The overlay spec root of an overlay file (`changes/CHG-NNN/spec/`), with the trailing slash. */\nexport const overlayRootOf = (path: string): string | undefined =>\n new RegExp(`(${CHANGE_PREFIX}[^/]+\\\\/spec\\\\/)`).exec(path)?.[1];\n\n/**\n * The layout before 0.12 (`application/`, flat screen files, contracts under `experience/<ch>/screens/`).\n * Archived changes keep whatever layout they were written in and never count.\n */\nexport const LEGACY_APPLICATION = 'application/application.md';\nconst LEGACY: RegExp[] = [\n /^application\\//,\n /^modules\\/[^/]+\\/screens\\/SCR-[^/]+\\.md$/,\n /^experience\\/[a-z]{2,5}\\/screens\\/UX-[^/]+\\.md$/,\n];\nexport const isLegacyPath = (path: string) => !isChangeFile(path) && LEGACY.some((re) => re.test(path));\nexport const legacyPaths = (files: readonly SpecFile[]) => files.map((f) => f.path).filter(isLegacyPath);\n/** Which layout a set of spec files is in: 1 before 0.12, 2 now. */\nexport const layoutOf = (files: readonly SpecFile[]): 1 | 2 => (legacyPaths(files).length ? 1 : 2);\n\nexport class LayoutError extends Error {}\n\nexport const LAYOUT_HINT =\n 'run `alterspec migrate layout` to move it to the current layout (a spec started before 0.10 needs `alterspec experience migrate` and `alterspec status migrate` first)';\n\n/** Refuse to work on a spec in the layout before 0.12. */\nexport function assertLayout(files: readonly SpecFile[], specDir = 'spec'): void {\n const legacy = legacyPaths(files);\n if (!legacy.length) return;\n throw new LayoutError(\n `${specDir}/ is in the layout of alterspec 0.11 or earlier (${specDir}/${legacy[0]} and ${legacy.length - 1} more); ${LAYOUT_HINT}`,\n );\n}\n","/** One line of a line diff: kept, removed or added. */\nexport interface DiffLine {\n op: ' ' | '-' | '+';\n text: string;\n}\n\nconst linesOf = (text: string) => (text === '' ? [] : text.replace(/\\n$/, '').split('\\n'));\n\n/** The shortest line diff from `a` to `b` (Myers). */\nexport function diffLines(a: string, b: string): DiffLine[] {\n const x = linesOf(a);\n const y = linesOf(b);\n const n = x.length;\n const m = y.length;\n const max = n + m;\n const v = new Map<number, number>([[1, 0]]);\n const trace: Map<number, number>[] = [];\n outer: for (let d = 0; d <= max; d++) {\n trace.push(new Map(v));\n for (let k = -d; k <= d; k += 2) {\n let i =\n k === -d || (k !== d && (v.get(k - 1) ?? -1) < (v.get(k + 1) ?? -1))\n ? (v.get(k + 1) ?? 0)\n : (v.get(k - 1) ?? 0) + 1;\n let j = i - k;\n while (i < n && j < m && x[i] === y[j]) {\n i++;\n j++;\n }\n v.set(k, i);\n if (i >= n && j >= m) break outer;\n }\n }\n const out: DiffLine[] = [];\n let i = n;\n let j = m;\n for (let d = trace.length - 1; d >= 0; d--) {\n const vd = trace[d]!;\n const k = i - j;\n const down = k === -d || (k !== d && (vd.get(k - 1) ?? -1) < (vd.get(k + 1) ?? -1));\n const pk = down ? k + 1 : k - 1;\n const pi = vd.get(pk) ?? 0;\n const pj = pi - pk;\n while (i > pi && j > pj) {\n out.push({ op: ' ', text: x[--i]! });\n j--;\n }\n if (d > 0) {\n if (down) out.push({ op: '+', text: y[--j]! });\n else out.push({ op: '-', text: x[--i]! });\n }\n }\n return out.reverse();\n}\n\n/** The diff as unified hunks with `context` lines around each change; empty when nothing changed. */\nexport function unifiedDiff(a: string, b: string, context = 3): string {\n const lines = diffLines(a, b);\n const changed = lines.map((l, i) => (l.op === ' ' ? -1 : i)).filter((i) => i >= 0);\n if (!changed.length) return '';\n const hunks: [number, number][] = [];\n for (const i of changed) {\n const from = Math.max(0, i - context);\n const to = Math.min(lines.length, i + context + 1);\n const last = hunks[hunks.length - 1];\n if (last && from <= last[1]) last[1] = to;\n else hunks.push([from, to]);\n }\n const out: string[] = [];\n for (const [from, to] of hunks) {\n let ai = 1;\n let bi = 1;\n for (const l of lines.slice(0, from)) {\n if (l.op !== '+') ai++;\n if (l.op !== '-') bi++;\n }\n const body = lines.slice(from, to);\n const aLen = body.filter((l) => l.op !== '+').length;\n const bLen = body.filter((l) => l.op !== '-').length;\n out.push(`@@ -${aLen ? ai : ai - 1},${aLen} +${bLen ? bi : bi - 1},${bLen} @@`);\n for (const l of body) out.push(`${l.op}${l.text}`);\n }\n return out.join('\\n');\n}\n","/** Replace HTML comments with blanks, keeping line breaks so line numbers stay valid. */\nexport const blankComments = (text: string) =>\n text.replace(/<!--[\\s\\S]*?-->/g, (c) => c.replace(/[^\\n]/g, ' '));\n","import { blankComments } from '../lib/comments.js';\n\n/*\n * Acceptance criteria as plain text: no YAML parser and nothing of the spec model, so the client (which bundles\n * this module) reads criteria exactly as alterspec does.\n */\n\n/** The two outcomes of one criterion, for telling which track builds what. */\nexport interface CriterionParts {\n /**\n * The criterion as the backend reads it: every line but `Shown` and the `And` lines that continue it; empty for a\n * criterion that says only what is shown (no `Then`), which is no backend's work.\n */\n system: string;\n /** The criterion as a screen reads it: its `Given` and `When` (and their `And`s), and its `Shown` lines. */\n shown: string;\n hasThen: boolean;\n hasShown: boolean;\n}\n\nconst PART = /^\\s*[-*]?\\s*\\*\\*(Given|When|Then|Shown|And|Covers):?\\*\\*/i;\n\n/**\n * One criterion's text (its `### ` chunk, heading included or not) split into what the system guarantees and what\n * the screen shows. A criterion without `Shown` is wholly the system's. String work only: the client uses it too.\n */\nexport function criterionParts(chunk: string): CriterionParts {\n const system: string[] = [];\n const shown: string[] = [];\n let label: string | undefined;\n let inShown = false;\n let hasThen = false;\n for (const raw of blankComments(chunk).split('\\n')) {\n const line = raw.trimEnd();\n if (!line.trim() || /^### /.test(line)) continue;\n const m = PART.exec(line);\n // A label with nothing after it (a template's empty line) says nothing.\n if (m && !line.slice(m[0].length).replace(/^:/, '').trim()) continue;\n if (m) {\n label = m[1]!.toLowerCase();\n if (label === 'shown') inShown = true;\n else if (label !== 'and') inShown = false;\n if (label === 'then') hasThen = true;\n }\n const text = line.trim();\n if (inShown) shown.push(text);\n else {\n system.push(text);\n if (label === 'given' || label === 'when' || (label === 'and' && !hasThen)) shown.push(text);\n }\n }\n const hasShown = shown.some((l) => PART.exec(l)?.[1]?.toLowerCase() === 'shown');\n return {\n system: hasShown && !hasThen ? '' : system.join('\\n'),\n shown: hasShown ? shown.join('\\n') : '',\n hasThen,\n hasShown,\n };\n}\n\n/**\n * A capability body cut at its criteria: each `### ` chunk of `## Acceptance criteria` by its ID, and the body\n * without them. String work only, like `criterionParts`.\n */\nexport function splitCriteria(body: string): { criteria: Map<string, string>; rest: string } {\n const chunks: string[][] = [];\n const rest: string[] = [];\n let inSection = false;\n let current: string[] | undefined;\n for (const line of blankComments(body).split('\\n')) {\n if (/^## /.test(line)) {\n inSection = /^## acceptance criteria\\s*$/i.test(line.trim());\n current = undefined;\n } else if (inSection && /^### \\S/.test(line)) chunks.push((current = []));\n (current ?? rest).push(line);\n }\n const criteria = new Map<string, string>();\n for (const chunk of chunks) {\n const id = chunk[0]!.slice(4).trim().split(/\\s+/)[0]!;\n // The first of two criteria with one ID counts, as everywhere else.\n if (!criteria.has(id)) criteria.set(id, chunk.join('\\n').trim());\n }\n return { criteria, rest: rest.join('\\n') };\n}\n","/**\n * The `## ` sections of a markdown body. Imports nothing, so the client can bundle it (`src/spec/sections.ts`, which\n * reads templates and YAML, re-exports it).\n */\nexport interface Section {\n heading: string;\n /** 1-based line of the heading, relative to the text parsed. */\n line: number;\n text: string;\n}\n\n/** `## ` sections of a markdown body (fenced blocks respected). */\nexport function sections(body: string): Section[] {\n const lines = body.split('\\n');\n const out: Section[] = [];\n let inFence = false;\n lines.forEach((l, i) => {\n if (l.startsWith('```')) inFence = !inFence;\n if (!inFence && /^## \\S/.test(l)) out.push({ heading: l.slice(3).trim(), line: i + 1, text: '' });\n else if (out.length) out[out.length - 1]!.text += l + '\\n';\n });\n return out;\n}\n","import { splitFrontMatter } from '../lib/frontmatter-split.js';\nimport { sections } from '../lib/sections-split.js';\nimport { FRONT_MATTER_SHARD, INTRO_SHARD, sectionShardName } from './paths.js';\n\n/**\n * A document cut into the parts its shards hold: the front-matter, the introduction (the text before the first\n * `## `, the title included), then each `## ` section, in the file's order. Imports no YAML parser: alterspec\n * writes an export's shards from it (`shards.ts` adds the source comments) and the client (`client/`) cuts the text\n * a change saw with it, so both name and cut a document the same way.\n */\nexport interface DocumentPart {\n /** The shard's file name: `00-front-matter.yaml`, `01-introduction.md`, `NN-<heading>.md` from 02. */\n name: string;\n kind: 'front-matter' | 'introduction' | 'section';\n /** A section's `## ` heading. */\n heading?: string;\n /** The part's text as its shard holds it under the source comment. */\n text: string;\n}\n\n/** A part with no text is left out; the numbers of the others don't move. */\nexport function cutDocument(content: string): DocumentPart[] {\n const out: DocumentPart[] = [];\n const { raw, body } = splitFrontMatter(content);\n if (raw !== undefined && raw.trim())\n out.push({ name: FRONT_MATTER_SHARD, kind: 'front-matter', text: `${raw.trimEnd()}\\n` });\n const parts = sections(body);\n const lines = body.split('\\n');\n const intro = lines\n .slice(0, parts.length ? parts[0]!.line - 1 : lines.length)\n .join('\\n')\n .trim();\n if (intro) out.push({ name: INTRO_SHARD, kind: 'introduction', text: `${intro}\\n` });\n parts.forEach((s, i) => {\n const text = s.text.trim();\n out.push({\n name: sectionShardName(i, s.heading),\n kind: 'section',\n heading: s.heading,\n text: `## ${s.heading}\\n${text ? `\\n${text}\\n` : ''}`,\n });\n });\n return out;\n}\n","import { cutDocument } from '../../src/export/cut.js';\nimport { SHARDS_DIR, isSectionShard, itemShardPath, shardDir } from '../../src/export/paths.js';\nimport type { ExportReader } from '../../src/export/read.js';\nimport type { DeltaEntry } from '../../src/schemas/delta.js';\n\n/**\n * The spec as a change saw it at its sign-off, from the export as it is now (client 0.19.0). An export holds the\n * current text of every object, and each signed-off change's delta holds the full text of what it touched before\n * and after; so the text an earlier change stood on is in the deltas: the `after` of the last change that touched\n * the object by then. A task's brief is read through `pinnedReader`, and what later changes did to the objects it\n * names is listed apart, as their tasks' work. No git and no copy of the export: only the deltas are read.\n */\n\n/** A change that touched an object after the one a brief is of, with its entry in that change's delta. */\nexport interface Later {\n change: string;\n entry: DeltaEntry;\n}\n\nexport interface Seen {\n /**\n * The object's text as the change saw it. Undefined when nothing touched it since (the export's text is what the\n * change saw), when the export did not hold it then (`absent`), or for a binary file.\n */\n text?: string;\n /** The later changes that touched it, in the order they did; empty when nothing moved. */\n later: Later[];\n /**\n * The export did not hold the object when the change was signed off: a later change brought it in (it was\n * signed off later). The export never held its earlier text, so a brief shows it as the export holds it now.\n */\n absent?: boolean;\n}\n\ninterface Memo {\n ancestors: Map<string, Set<string>>;\n entries: Map<string, Map<string, DeltaEntry>>;\n history: Map<string, Later[]>;\n}\n\nconst memos = new WeakMap<ExportReader, Memo>();\nconst memoOf = (x: ExportReader): Memo => {\n let m = memos.get(x);\n if (!m) memos.set(x, (m = { ancestors: new Map(), entries: new Map(), history: new Map() }));\n return m;\n};\n\n/** Every change a change builds on, through `depends_on` (the lineage the sign-offs froze). */\nexport function ancestors(x: ExportReader, change: string): Set<string> {\n const memo = memoOf(x).ancestors;\n const known = memo.get(change);\n if (known) return known;\n const out = new Set<string>();\n memo.set(change, out);\n for (const d of x.work.changes.find((c) => c.id === change)?.depends_on ?? []) {\n out.add(d);\n for (const a of ancestors(x, d)) out.add(a);\n }\n return out;\n}\n\nfunction entriesOf(x: ExportReader, change: string): Map<string, DeltaEntry> {\n const memo = memoOf(x).entries;\n let entries = memo.get(change);\n if (!entries) memo.set(change, (entries = new Map(x.delta(change)?.objects.map((e) => [e.key, e]))));\n return entries;\n}\n\n/**\n * The changes that touched an object, each with its entry, in the order they did: an entry follows the one whose\n * fingerprint after is its fingerprint before (sign-offs of one day are not in ID order, and the change map sorts\n * a day by ID), and where no link says, the change map's order.\n */\nexport function history(x: ExportReader, key: string): Later[] {\n const memo = memoOf(x).history;\n const known = memo.get(key);\n if (known) return known;\n const order = x.work.changes.map((c) => c.id);\n // An object the export no longer holds has no source to name its changes: every delta is asked.\n const touched = x.sources.get(key)?.changed_by ?? order;\n const rest = order\n .filter((c) => touched.includes(c))\n .flatMap((change): Later[] => {\n const entry = entriesOf(x, change).get(key);\n return entry ? [{ change, entry }] : [];\n });\n const out: Later[] = [];\n while (rest.length) {\n const last = out[out.length - 1]?.entry.fingerprint.after;\n const follows = last === undefined ? -1 : rest.findIndex((e) => e.entry.fingerprint.before === last);\n // Nothing follows: the earliest entry no other waiting entry leads to (the head of what is left).\n const head = rest.findIndex(\n (e) =>\n e.entry.fingerprint.before === undefined ||\n !rest.some((o) => o !== e && o.entry.fingerprint.after === e.entry.fingerprint.before),\n );\n out.push(...rest.splice(follows >= 0 ? follows : Math.max(head, 0), 1));\n }\n memo.set(key, out);\n return out;\n}\n\nconst after = (e: DeltaEntry) => (e.exported.after ? e.after : undefined);\nconst before = (e: DeltaEntry) => (e.exported.before ? e.before : undefined);\n\n/**\n * What a change saw of an object, and what later changes did to it. The change's own entry when it touched the\n * object; else the last entry whose change it builds on (`depends_on`, transitively) or that was signed off on an\n * earlier day and doesn't build on it. A change of the same day outside the lineage counts as later: the brief\n * then shows less, never a sentence that wasn't there.\n */\nexport function seen(x: ExportReader, change: string, key: string): Seen {\n // Every change that touched it is this one or one it builds on: nothing is later, and no delta need be read.\n const touched = x.sources.get(key)?.changed_by;\n if (touched) {\n const built = ancestors(x, change);\n if (touched.every((c) => c === change || built.has(c))) return { later: [] };\n }\n const h = history(x, key);\n if (!h.length) return { later: [] };\n let at = h.findIndex((e) => e.change === change);\n if (at < 0) {\n const built = ancestors(x, change);\n const day = (id: string) => x.work.changes.find((c) => c.id === id)?.signed_off;\n const mine = day(change);\n h.forEach((e, i) => {\n const theirs = day(e.change);\n if (built.has(e.change)) at = i;\n else if (mine && theirs && theirs < mine && !ancestors(x, e.change).has(change)) at = i;\n });\n }\n const later = h.slice(at + 1);\n if (!later.length) return { later };\n const text = at >= 0 ? after(h[at]!.entry) : before(h[0]!.entry);\n if (text !== undefined) return { text, later };\n // No text on that side: a binary file, or an object the export did not hold then.\n const held = at >= 0 ? h[at]!.entry.exported.after : h[0]!.entry.exported.before;\n if (held) return { later };\n // What touched it before it was signed off never reached the export: the change that brought it in comes first.\n const entered = later.findIndex((l) => l.entry.exported.after);\n return { later: later.slice(Math.max(entered, 0)), absent: true };\n}\n\nexport interface PinnedReader extends ExportReader {\n /** The reader of the export as it is now. */\n current: ExportReader;\n /** What the change saw of an object and what later changes did to it. */\n seen(key: string): Seen;\n /** The object an export path belongs to: its file, a shard of it, or its shard folder. */\n keyOf(path: string): string | undefined;\n /** Whether the path (a file, a shard, a shard folder) reads differently for this change than in the export now. */\n isPinned(path: string): boolean;\n /** The files that hold an object as the change saw it, by export path; empty when nothing moved since. */\n pinnedFiles(key: string): Map<string, string>;\n}\n\n/**\n * The export read as `change` saw it: an object a later change touched reads as it was at the change's sign-off\n * (its file, and its shards cut the way the export cuts them); everything else, an object a later change brought\n * into the export included, is the export's own file. Facts the export derives (`index()`, the generated views)\n * stay current.\n */\nexport function pinnedReader(x: ExportReader, change: string): PinnedReader {\n const byFile = new Map<string, string[]>();\n for (const s of x.sources.values()) byFile.set(s.file, [...(byFile.get(s.file) ?? []), s.id]);\n const isItem = (file: string, id: string) => x.has(itemShardPath(file, id));\n\n const keys = new Map<string, string | undefined>();\n const keyOf = (path: string): string | undefined => {\n if (keys.has(path)) return keys.get(path);\n let key: string | undefined;\n if (path.startsWith(`${SHARDS_DIR}/`)) {\n const inner = path.slice(SHARDS_DIR.length + 1);\n // A shard folder, an item's shard in its collection's folder, or a section shard in its document's.\n const folder = `${inner}.md`;\n const parent = `${inner.replace(/\\/[^/]+$/, '')}.md`;\n key =\n byFile.get(folder)?.find((id) => !isItem(folder, id)) ??\n byFile.get(parent)?.find((id) => itemShardPath(parent, id) === path) ??\n byFile.get(parent)?.find((id) => !isItem(parent, id));\n } else {\n key = byFile.get(path)?.find((id) => !isItem(path, id));\n }\n keys.set(path, key);\n return key;\n };\n\n const seenOf = new Map<string, Seen>();\n const see = (key: string) => {\n let s = seenOf.get(key);\n if (!s) seenOf.set(key, (s = seen(x, change, key)));\n return s;\n };\n\n const files = new Map<string, Map<string, string>>();\n const none = new Map<string, string>();\n const pinnedFiles = (key: string): Map<string, string> => {\n const known = files.get(key);\n if (known) return known;\n const s = see(key);\n const file = x.fileOf(key);\n let out = none;\n if (s.text !== undefined && file) {\n out = new Map();\n if (isItem(file, key)) out.set(itemShardPath(file, key), `${s.text.trim()}\\n`);\n else {\n out.set(file, s.text);\n if (file.endsWith('.md'))\n for (const part of cutDocument(s.text)) out.set(`${shardDir(file)}/${part.name}`, part.text);\n }\n }\n files.set(key, out);\n return out;\n };\n\n /** How a path reads for the change: its pinned text, `null` when the change saw nothing there, undefined when the export's own file is what it saw. */\n const view = (path: string): string | null | undefined => {\n const key = keyOf(path);\n if (!key) return undefined;\n const pinned = pinnedFiles(key);\n if (!pinned.size) return undefined;\n return pinned.get(path) ?? null;\n };\n\n const shards = (file: string): string[] => {\n const key = keyOf(file);\n const pinned = key ? pinnedFiles(key) : none;\n return pinned.size\n ? [...pinned.keys()].filter((p) => p.startsWith(`${shardDir(file)}/`)).sort()\n : x.shards(file);\n };\n\n return {\n ...x,\n current: x,\n seen: see,\n keyOf,\n pinnedFiles,\n isPinned(path) {\n const key = keyOf(path);\n return !!key && pinnedFiles(key).size > 0;\n },\n read(path) {\n const v = view(path);\n return v === undefined ? x.read(path) : (v ?? undefined);\n },\n has(path) {\n const v = view(path);\n return v === undefined ? x.has(path) : v !== null;\n },\n shards,\n sectionShard(file, heading) {\n const prefix = `${shardDir(file)}/`;\n return shards(file).find((p) => isSectionShard(p.slice(prefix.length), heading));\n },\n itemShard(file, key) {\n const path = itemShardPath(file, key);\n const v = view(path);\n return (v === undefined ? x.has(path) : v !== null) ? path : undefined;\n },\n };\n}\n","import { z } from 'zod';\nimport type { ExportReader } from '../../src/export/read.js';\nimport type { Session } from './auth.js';\nimport { callTool } from './mcp.js';\n\n/**\n * Questions from the build (spec 8.3): what an answer may cite, and the questions the dispatcher keeps. Asking and\n * answering are the dispatcher's tools, called by the agent; the CLI checks cites and reads the answers back.\n */\n\nconst AnswerSchema = z.object({\n developer: z.string(),\n at: z.string(),\n text: z.string(),\n verdict: z.enum(['confirmed', 'corrected']).nullish(),\n change: z.string().nullish(),\n});\n\nconst QuestionSchema = z.object({\n id: z.string(),\n task: z.string().nullish(),\n item: z.string().nullish(),\n developer: z.string(),\n at: z.string(),\n question: z.string(),\n outcome: z.enum(['spec', 'assumed', 'open', 'proposal']),\n status: z.enum(['open', 'answered']),\n cites: z.array(z.string()).default([]),\n answer: z.string().nullish(),\n assumption: z.string().nullish(),\n corrected: z.boolean().optional(),\n /** The product side's mark: the spec now says what the answer says. */\n reconciled: z.boolean().optional(),\n answers: z.array(AnswerSchema).default([]),\n /** What an open question waits for (wave contract 2.4). */\n waits_for: z.enum(['contradiction', 'business']).nullish(),\n /** Why an open question carries no reading of the spec. */\n no_reading: z.string().nullish(),\n /** The question this one was joined into. */\n merged_into: z.string().nullish(),\n /** The `REWORK-<n>` item a corrected assumption opened on the asking task. */\n rework: z.string().nullish(),\n});\n\nexport type Question = z.infer<typeof QuestionSchema>;\n\n/** One question a task carries into the spec, built on the task's track already or not (spec 8.4). */\nconst TaskAnswerSchema = z.object({\n question: z.string(),\n built: z.boolean(),\n /** The asking change's task on this track, when it has one. */\n task: z.string().nullish(),\n done_at: z.string().nullish(),\n answer_at: z.string().nullish(),\n /** Why not built: no_task | not_done | answered_after_done | no_task_asked. */\n why: z.string().nullish(),\n});\n\nexport type TaskAnswer = z.infer<typeof TaskAnswerSchema>;\n\n/** The `answers` of the dispatcher's `task`; undefined when it sends none or something this client doesn't read. */\nexport function parseAnswers(raw: unknown): TaskAnswer[] | undefined {\n const parsed = z.array(TaskAnswerSchema).safeParse(raw);\n return parsed.success && parsed.data.length ? parsed.data : undefined;\n}\n\nexport class QuestionsError extends Error {}\n\n/** A criterion, a screen action or a contract state: cited by the ID of the object that holds it. */\nconst PART = /^(.+?)(?:-AC-\\d+|\\.A\\d+|#[\\w-]+)$/;\n\n/**\n * The references the export doesn't hold. A reference is an ID of the export's sources (or a criterion, action or\n * state of one, when its file names it) or a path in the export, shards included.\n */\nexport function missingCites(x: ExportReader, refs: string[]): string[] {\n const held = (ref: string) => {\n if (x.sources.has(ref)) return true;\n const owner = PART.exec(ref)?.[1];\n if (owner && x.sources.has(owner)) {\n if (ref.includes('#')) return true;\n const text = x.read(x.fileOf(owner) ?? '') ?? '';\n const action = /\\.(A\\d+)$/.exec(ref)?.[1];\n return action ? new RegExp(`\\\\bid: ${action}\\\\b`).test(text) : text.includes(ref);\n }\n return /[/.]/.test(ref) && !ref.includes('..') && !ref.startsWith('/') && x.has(ref);\n };\n return refs.filter((r) => !held(r));\n}\n\nexport interface QuestionsFilter {\n /** Questions by number (`Q-<n>`), whole, wherever they were asked. */\n ids?: string[];\n task?: string;\n /** Everyone's questions naming these IDs, to find one asked before. */\n about?: string[];\n open?: boolean;\n}\n\n/** The task's questions, the ones naming some IDs, or without either the developer's own (which marks them as listed). */\nexport async function listQuestions(session: Session, filter: QuestionsFilter = {}): Promise<Question[]> {\n const answer = await callTool(session, 'questions', {\n ...(filter.ids?.length\n ? { ids: filter.ids }\n : filter.task\n ? { task: filter.task }\n : filter.about\n ? { about: filter.about }\n : { mine: true }),\n ...(filter.open ? { status: 'open' } : {}),\n });\n const parsed = z.array(QuestionSchema).safeParse(answer.questions ?? []);\n if (!parsed.success)\n throw new QuestionsError('The dispatcher’s questions are not in a form this client reads.');\n return parsed.data;\n}\n\n/** The task's questions for the brief; undefined when the dispatcher can't be asked or keeps none yet. */\nexport async function taskQuestions(session: Session, task: string): Promise<Question[] | undefined> {\n try {\n return await listQuestions(session, { task });\n } catch {\n return undefined;\n }\n}\n\n/**\n * The questions of every task of the change, the given one first, each once: what another track assumed or was\n * told bears on this one. Undefined when the dispatcher can't be asked.\n */\nexport async function changeQuestions(session: Session, tasks: string[]): Promise<Question[] | undefined> {\n const lists = await Promise.all(tasks.map((t) => taskQuestions(session, t)));\n if (lists.some((l) => l === undefined)) return undefined;\n const seen = new Set<string>();\n return lists.flat().filter((q) => q && !seen.has(q.id) && seen.add(q.id)) as Question[];\n}\n\nconst holding = (q: Question) => q.answers.at(-1);\nconst isCorrected = (q: Question) => q.corrected ?? holding(q)?.verdict === 'corrected';\n\n/** A corrected assumption first (rework), then the open ones, then the answered. */\nexport function sortQuestions(questions: Question[]): Question[] {\n const rank = (q: Question) => (isCorrected(q) ? 0 : q.status === 'open' ? 1 : 2);\n return [...questions].sort((a, b) => rank(a) - rank(b));\n}\n\nconst one = (text: string) => text.replace(/\\s+/g, ' ').trim();\n\n/** What holds for a question now, and whose word that is. */\nfunction stateOf(q: Question): string {\n const last = holding(q);\n return isCorrected(q)\n ? 'ASSUMPTION CORRECTED'\n : last\n ? q.outcome === 'assumed'\n ? 'assumption confirmed'\n : q.reconciled\n ? 'answered by the product side'\n : 'answered by the product side, not in the export yet'\n : q.outcome === 'spec'\n ? 'answered from the spec'\n : q.outcome === 'assumed'\n ? 'open, working on an assumption'\n : q.outcome === 'proposal'\n ? 'a proposal for the product side'\n : q.merged_into\n ? `joined into ${q.merged_into}`\n : q.waits_for === 'contradiction'\n ? 'open, waiting for the product side on a contradiction'\n : 'open, waiting for the product side';\n}\n\n/** One question as the lines the agent reads: what was asked, what holds now, and whose word that is. */\nexport function questionLines(q: Question): string[] {\n const about = [q.task, q.item].filter(Boolean).join(' ');\n const last = holding(q);\n const lines = [`- ${q.id} (${stateOf(q)}${about ? `; ${about}` : ''}): ${one(q.question)}`];\n if (q.outcome === 'assumed' && q.assumption) lines.push(` - Assumed: ${one(q.assumption)}`);\n if (q.outcome === 'open' && q.assumption) lines.push(` - Reading: ${one(q.assumption)}`);\n if (isCorrected(q) && q.rework)\n lines.push(` - Rework: ${q.rework}, covered with \\`Alterspec-Covers: ${q.rework}\\`.`);\n if (q.outcome === 'spec' && q.answer)\n lines.push(` - From the spec: ${one(q.answer)}${q.cites.length ? ` (${q.cites.join(', ')})` : ''}`);\n if (last)\n lines.push(\n ` - Product side (${last.developer}, ${last.at.slice(0, 10)}): ${one(last.text)}${q.reconciled ? ' The spec says so now.' : `${last.change ? ` It comes into the spec with ${last.change}.` : ''} Not in the export yet: this answer stands over the export’s silence.`}`,\n );\n return lines;\n}\n\nexport function questionsText(questions: Question[]): string {\n if (!questions.length) return 'No questions.\\n';\n return sortQuestions(questions).flatMap(questionLines).join('\\n') + '\\n';\n}\n\n/** A question the brief names only: its number, task, object and state, and where its full text is read. */\nexport function questionLine(q: Question): string {\n const about = [q.task, q.item].filter(Boolean).join(' ');\n return `- ${q.id} (${about ? `${about}; ` : ''}${stateOf(q)}): \\`alterspec-client questions ${q.id}\\``;\n}\n\n/**\n * The brief's section: what the task must read before it goes on. With `full` (the dispatcher's `questions_full`:\n * asked on this track, or answered with a change to an item of this task), only those are whole and every other is\n * one line naming where it is read; without it, every question is whole, as before the dispatcher sent the list.\n */\nexport function questionsSection(questions: Question[], full?: ReadonlySet<string>): string[] {\n if (!questions.length) return [];\n const sorted = sortQuestions(questions);\n const whole = (q: Question) => !full || full.has(q.id);\n const lined = sorted.filter((q) => !whole(q)).length;\n const corrected = sorted.filter(isCorrected).length;\n const open = sorted.filter((q) => q.status === 'open').length;\n return [\n `## Questions (${open} open${corrected ? `, ${corrected} corrected` : ''})`,\n '',\n corrected\n ? 'A corrected assumption is rework: what was built on it follows the product side’s answer before the task is done.'\n : 'What was asked about this change, on any of its tracks (each names the task it was asked on). An open one on an assumption may still be corrected; an item waiting for an answer stays uncovered.',\n ...(lined\n ? [\n '',\n `Whole: the questions asked on this track or answered with a change to an item of this task. The other ${lined} are one line each; read one with \\`alterspec-client questions <id>\\` when its object is in front of you.`,\n ]\n : []),\n '',\n ...sorted.flatMap((q) => (whole(q) ? questionLines(q) : [questionLine(q)])),\n '',\n ];\n}\n\nconst day = (at?: string | null) => (at ? at.slice(0, 10) : undefined);\n\n/** Why a question isn't built on this track, in words. */\nfunction notBuilt(a: TaskAnswer): string {\n const t = a.task ? `${a.task}` : 'the asking task';\n switch (a.why) {\n case 'no_task':\n return 'the change it was asked on had no task on this track';\n case 'not_done':\n return `${t} isn’t done`;\n case 'answered_after_done':\n return `the product side’s answer (${day(a.answer_at) ?? 'later'}) came after ${t} was done${a.done_at ? ` (${day(a.done_at)})` : ''}`;\n case 'no_task_asked':\n return 'it was asked outside a task';\n default:\n return a.why ?? 'not built on this track';\n }\n}\n\n/** One answer the task carries into the spec, as the agent reads it. */\nexport function answerLine(a: TaskAnswer): string {\n return a.built\n ? `- ${a.question}: built in ${a.task ?? 'the asking task'}, done ${day(a.done_at) ?? 'earlier'}, after the product side’s answer of ${day(a.answer_at) ?? 'before it'}.`\n : `- ${a.question}: not built here: ${notBuilt(a)}.`;\n}\n\n/**\n * The brief's section after the questions: what the dispatcher says this task's change carries into the spec and\n * which of it the track built already (spec 8.4), and how to work such a task.\n */\nexport function answersSection(answers: TaskAnswer[]): string[] {\n if (!answers.length) return [];\n const built = answers.filter((a) => a.built).length;\n const how =\n built === answers.length\n ? 'This change carries answers this track built already: the task checks that the code says what the spec now says. Read each checklist item against the code, add the tests that are missing, cover each item as its tests pass, and rebuild nothing.'\n : built\n ? 'This change carries answers this track built in part: build what stands on a question not built here; for the rest, read each checklist item against the code, add the tests that are missing and cover each item as its tests pass.'\n : 'This change carries answers to questions another track or task asked; none was built on this track, so build it as any task.';\n return [`## Built already (${built} of ${answers.length})`, '', how, '', ...answers.map(answerLine), ''];\n}\n","import { createInterface } from 'node:readline';\nimport type { Readable, Writable } from 'node:stream';\nimport { DispatcherError, KeyRefused, type Session } from './auth.js';\nimport { RELATED_FIRST, aboutOf, forwardedArgs, relatedRefusal, settled } from './related.js';\nimport { type Role, allows, refusal, roleOf } from './role.js';\n\n/**\n * The local MCP server Claude Code starts over stdio (spec 10.5): every JSON-RPC message from Claude Code is posted\n * to the dispatcher's `/mcp` with the key's token, and every answer (JSON or a server-sent event stream) goes\n * back on stdout. It forwards rather than reimplements, so the dispatcher's tools, schemas and errors reach Claude\n * Code unchanged. stdout carries protocol messages only; the log goes to stderr.\n *\n * One cut (spec 12.4): the role the key has, asked of `whoami` once per run, decides which tools are listed and may be\n * called. A product session (the spec project) sees its six tools and nothing of the build's tasks; a developer's\n * never sees the product's own. A call outside the role is answered here and never forwarded.\n *\n * One look before a developer's `ask` (client 0.32.0, `related.ts`): the questions already held on its objects are\n * listed back as `RELATED_FIRST` until the call joins one, extends one or says `new: true`.\n *\n * When the dispatcher refuses the key, Claude Code still gets a server: `initialize` is answered here and the one\n * tool listed, `whoami`, returns the sentence and the key to send to the admin, so every skill can say it.\n */\n\ntype Id = string | number | null;\ninterface Message {\n jsonrpc?: string;\n id?: Id;\n method?: string;\n params?: Record<string, unknown>;\n}\n\nexport interface ProxyOptions {\n session: Session;\n input: Readable;\n output: Writable;\n version: string;\n log?: (line: string) => void;\n}\n\nconst isRequest = (m: Message) => m.method !== undefined && m.id !== undefined;\n\n/**\n * One call of a dispatcher tool, for the CLI's own commands (`progress`, `context`): a single `tools/call`, which the\n * stateless `/mcp` answers without an `initialize`. The tool's structured result, or its error as `DispatcherError`.\n */\nexport async function callTool(\n session: Session,\n name: string,\n args: Record<string, unknown> = {},\n): Promise<Record<string, unknown>> {\n const res = await session.fetch('/mcp', {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },\n body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),\n });\n const text = await res.text();\n if (!res.ok)\n throw new DispatcherError(`HTTP_${res.status}`, `The dispatcher answered ${res.status}.`, res.status);\n const answer = messagesOf(res.headers.get('content-type') ?? '', text)[0] as\n { result?: ToolResult; error?: { message?: string } } | undefined;\n if (!answer?.result)\n throw new DispatcherError(\n 'MCP_ERROR',\n answer?.error?.message ?? `The dispatcher gave no answer to ${name}.`,\n );\n const out = answer.result.structuredContent ?? {};\n if (answer.result.isError) {\n const err = (out as { error?: { code?: string; message?: string } }).error;\n throw new DispatcherError(\n err?.code ?? 'TOOL_ERROR',\n err?.message ?? answer.result.content?.map((c) => c.text ?? '').join('\\n') ?? `${name} failed.`,\n );\n }\n return out;\n}\n\ninterface ToolResult {\n structuredContent?: Record<string, unknown>;\n content?: { type: string; text?: string }[];\n isError?: boolean;\n}\n\n/** The JSON-RPC messages of an answer: a JSON body, or the `data:` of each server-sent event. */\nexport function messagesOf(contentType: string, text: string): unknown[] {\n if (!text.trim()) return [];\n if (!contentType.includes('text/event-stream')) return [JSON.parse(text)];\n const out: unknown[] = [];\n for (const event of text.split(/\\r?\\n\\r?\\n/)) {\n const data = event\n .split(/\\r?\\n/)\n .filter((l) => l.startsWith('data:'))\n .map((l) => l.slice(5).replace(/^ /, ''))\n .join('\\n');\n if (data.trim()) out.push(JSON.parse(data));\n }\n return out;\n}\n\nexport function runProxy(opts: ProxyOptions): Promise<void> {\n const { session, input, output, version } = opts;\n const log = opts.log ?? ((line: string) => process.stderr.write(`alterspec-client: ${line}\\n`));\n let protocolVersion: string | undefined;\n const pending = new Set<Promise<void>>();\n\n const send = (message: unknown): void => void output.write(JSON.stringify(message) + '\\n');\n const result = (id: Id, value: unknown) => send({ jsonrpc: '2.0', id, result: value });\n const error = (id: Id, message: string, code = -32000) =>\n send({ jsonrpc: '2.0', id, error: { code, message } });\n\n /** The key's role, asked once per run; a failed ask is not kept, so the next request asks again. */\n let role: Promise<Role> | undefined;\n const roleOnce = (): Promise<Role> =>\n (role ??= callTool(session, 'whoami')\n .then(roleOf)\n .catch((e: unknown) => {\n role = undefined;\n throw e;\n }));\n\n /** A `tools/list` answer cut to the role's tools. */\n const cut = (answer: unknown, r: Role): unknown => {\n const tools = (answer as { result?: { tools?: { name?: string }[] } }).result?.tools;\n if (!Array.isArray(tools)) return answer;\n const a = answer as { result: { tools: { name?: string }[] } };\n return { ...a, result: { ...a.result, tools: tools.filter((t) => allows(r, t.name ?? '')) } };\n };\n\n /** The answer of a refused key, from here, without the dispatcher. */\n function refused(m: Message, e: KeyRefused): void {\n if (!isRequest(m)) return;\n const id = m.id as Id;\n switch (m.method) {\n case 'initialize':\n return result(id, {\n protocolVersion: m.params?.protocolVersion ?? '2025-06-18',\n capabilities: { tools: {} },\n serverInfo: { name: 'alterspec-client', version },\n instructions: e.advice,\n });\n case 'ping':\n return result(id, {});\n case 'tools/list':\n return result(id, {\n tools: [\n {\n name: 'whoami',\n description: 'Who you are to the dispatcher. Your SSH key is refused: this says what to do.',\n inputSchema: { type: 'object', properties: {} },\n },\n ],\n });\n case 'tools/call':\n return result(id, {\n content: [{ type: 'text', text: e.advice }],\n structuredContent: {\n error: { code: e.code, message: e.advice },\n key: { line: e.key.line, fingerprint: e.key.fingerprint },\n },\n isError: true,\n });\n default:\n return error(id, e.advice);\n }\n }\n\n /**\n * The questions already held on the objects an `ask` is about, as the refusal's text; undefined when there are none\n * or they can't be asked (a failed look never holds a question back).\n */\n async function earlier(args: Record<string, unknown>): Promise<string | undefined> {\n const about = aboutOf(args);\n if (!about.length) return undefined;\n try {\n const answer = await callTool(session, 'questions', { about });\n return relatedRefusal(answer.questions, about);\n } catch {\n return undefined;\n }\n }\n\n async function forward(m: Message): Promise<void> {\n try {\n const gated = m.method === 'tools/list' || m.method === 'tools/call';\n const r = gated ? await roleOnce() : undefined;\n if (r && m.method === 'tools/call') {\n const tool = String(m.params?.name ?? '');\n if (!allows(r, tool)) {\n const why = refusal(r, tool);\n log(`${tool} refused: ${why.code}`);\n if (!isRequest(m)) return;\n return result(m.id as Id, {\n content: [{ type: 'text', text: why.message }],\n structuredContent: { error: why },\n isError: true,\n });\n }\n if (r === 'developer' && tool === 'ask') {\n const args = (m.params?.arguments ?? {}) as Record<string, unknown>;\n const held = settled(args) ? undefined : await earlier(args);\n if (held) {\n log(`ask held: ${RELATED_FIRST}`);\n if (!isRequest(m)) return;\n return result(m.id as Id, {\n content: [{ type: 'text', text: held }],\n structuredContent: { error: { code: RELATED_FIRST, message: held } },\n isError: true,\n });\n }\n if ('new' in args) m = { ...m, params: { ...m.params, arguments: forwardedArgs(args) } };\n }\n }\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n accept: 'application/json, text/event-stream',\n };\n if (protocolVersion) headers['mcp-protocol-version'] = protocolVersion;\n const res = await session.fetch('/mcp', { method: 'POST', headers, body: JSON.stringify(m) });\n const text = await res.text();\n if (!res.ok && res.status !== 202) {\n let message = `The dispatcher answered ${res.status}.`;\n try {\n message = (JSON.parse(text) as { error?: { message?: string } }).error?.message ?? message;\n } catch {\n // Not JSON: keep the status.\n }\n if (isRequest(m)) error(m.id as Id, message);\n return;\n }\n for (const answer of messagesOf(res.headers.get('content-type') ?? '', text)) {\n const pv = (answer as { result?: { protocolVersion?: unknown } }).result?.protocolVersion;\n if (m.method === 'initialize' && typeof pv === 'string') protocolVersion = pv;\n send(r && m.method === 'tools/list' ? cut(answer, r) : answer);\n }\n } catch (e) {\n if (e instanceof KeyRefused) {\n log(e.advice.split('\\n')[0]!);\n return refused(m, e);\n }\n const message = e instanceof DispatcherError ? e.message : `The client failed: ${(e as Error).message}`;\n log(message);\n if (!isRequest(m)) return;\n if (m.method === 'tools/call')\n return result(m.id as Id, { content: [{ type: 'text', text: message }], isError: true });\n error(m.id as Id, message);\n }\n }\n\n return new Promise((resolve) => {\n const lines = createInterface({ input, crlfDelay: Infinity });\n lines.on('line', (line) => {\n if (!line.trim()) return;\n let m: Message;\n try {\n m = JSON.parse(line) as Message;\n } catch {\n return error(null, 'Parse error: not a JSON-RPC message.', -32700);\n }\n // Several messages at once (a batch) go as they came; the dispatcher answers them together.\n const p = forward(m).finally(() => pending.delete(p));\n pending.add(p);\n });\n lines.on('close', () => void Promise.allSettled([...pending]).then(() => resolve()));\n });\n}\n","/**\n * Before a question is posted (wave contract point 4, client point C2): the questions the dispatcher already holds on\n * the same objects, answered or open, including answers the export doesn't hold yet. The proxy asks the deployed\n * `questions { about }` first and posts only once the agent has settled it: `joins` another asker's question,\n * `extends` its own, or `new: true` (a local flag, never forwarded). The dispatcher never judges sameness; the agent\n * does, from this list. A leaf: no imports, so the proxy and the tests share it without a cycle.\n */\n\n/** The code of the local refusal that lists the earlier questions. */\nexport const RELATED_FIRST = 'RELATED_FIRST';\n\n/** At most this many earlier questions are listed; the rest are counted. */\nconst SHOWN = 10;\n\nconst str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined);\n\n/** Whether an `ask` call's arguments have settled what came before: a join, an extension or a question sent as new. */\nexport function settled(args: Record<string, unknown>): boolean {\n return Boolean(str(args.joins) || str(args.extends) || args.new === true);\n}\n\n/** The IDs an `ask` is about, for `questions { about }`: its cites and item, paths left out; empty when none. */\nexport function aboutOf(args: Record<string, unknown>): string[] {\n const cites = Array.isArray(args.cites) ? args.cites : [];\n const refs = [...cites, args.item].flatMap((r) => {\n const s = str(r);\n return s && !s.includes('/') ? [s.trim()] : [];\n });\n return [...new Set(refs)];\n}\n\n/** The arguments forwarded to the dispatcher: the local `new` flag is not its field. */\nexport function forwardedArgs(args: Record<string, unknown>): Record<string, unknown> {\n if (!('new' in args)) return args;\n const rest = { ...args };\n delete rest.new;\n return rest;\n}\n\n/** What holds for an earlier question, in a few words. */\nfunction stateOf(q: Record<string, unknown>): string {\n const answers = Array.isArray(q.answers) ? (q.answers as Record<string, unknown>[]) : [];\n const answered = q.status === 'answered' || answers.length > 0;\n if (str(q.merged_into)) return `joined into ${String(q.merged_into)}`;\n if (answered)\n return q.reconciled === true ? 'answered, the spec says so now' : 'answered, not in the export yet';\n if (q.outcome === 'assumed') return 'open, working on an assumption';\n return 'open';\n}\n\nconst one = (text: string, max = 160) => {\n const t = text.replace(/\\s+/g, ' ').trim();\n return t.length > max ? `${t.slice(0, max - 1)}…` : t;\n};\n\n/** One line per earlier question: its number, task, state and first words. Malformed entries are skipped. */\nexport function relatedLines(questions: unknown): string[] {\n if (!Array.isArray(questions)) return [];\n return questions.flatMap((v: unknown) => {\n const q = v as Record<string, unknown> | null;\n const id = str(q?.id);\n if (!q || !id) return [];\n const task = str(q.task);\n const text = str(q.question) ?? '';\n return [`- ${id} (${task ? `${task}; ` : ''}${stateOf(q)}): ${one(text)}`];\n });\n}\n\n/**\n * The refusal's text: the earlier questions on the same objects and how to settle them; undefined when there are\n * none, so the question is posted as it came.\n */\nexport function relatedRefusal(questions: unknown, about: string[] = []): string | undefined {\n const lines = relatedLines(questions);\n if (!lines.length) return undefined;\n const more = lines.length - SHOWN;\n return [\n `Not posted: the dispatcher holds ${lines.length === 1 ? 'a question' : `${lines.length} questions`} on the same objects. Read ${lines.length === 1 ? 'it' : 'them'} first (\\`alterspec-client questions <id>\\` prints one whole); an answer not in the export yet stands over the export's silence.`,\n ...lines.slice(0, SHOWN),\n ...(more > 0\n ? [`- and ${more} more: \\`alterspec-client questions --about ${about.join(' ') || '<ID...>'}\\``]\n : []),\n 'If one of them answers your question, use that answer and post nothing. Otherwise call `ask` again with `joins: \"Q-<n>\"` (another asker’s question on the same matter: your task waits on its answer), `extends: \"Q-<n>\"` (your own earlier question: this is its next part), or `new: true` (none of them is this matter).',\n ].join('\\n');\n}\n","/**\n * Rulings not in the export yet (wave contract point 3, client point C4): the dispatcher's `task` returns `ruled`,\n * the answered questions not yet reconciled whose `touches` (or cites) share an ID with the task's objects or items,\n * the answer whole where it names an item of the task and one line elsewhere, and `ruled_changed` once after the\n * product side reversed a ruling this task's brief showed. The contract names no fields inside an entry, so each is\n * read leniently: a question's number, its text, the holding answer, the object, the state. A leaf: no imports.\n */\n\nexport interface Ruling {\n /** `Q-<n>`. */\n id: string;\n /** The question, as asked; may be absent. */\n question?: string;\n /** The holding answer's text, when the dispatcher sent it (the ruling changes an item of this task). */\n text?: string;\n /** The task or object it was asked about. */\n about?: string;\n state?: string;\n /** Where the whole question is read. */\n path: string;\n}\n\nconst str = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v.trim() : undefined);\n\n/** One entry of `ruled` / `ruled_changed`, or undefined when it names no question. */\nfunction rulingOf(v: unknown): Ruling | undefined {\n if (typeof v === 'string')\n return /^Q-\\d+$/.test(v) ? { id: v, path: `alterspec-client questions ${v}` } : undefined;\n const r = v as Record<string, unknown> | null;\n if (!r || typeof r !== 'object') return undefined;\n const id =\n str(r.id) ?? str(r.question_id) ?? (/^Q-\\d+$/.test(String(r.question)) ? str(r.question) : undefined);\n if (!id) return undefined;\n const answers = Array.isArray(r.answers) ? (r.answers as Record<string, unknown>[]) : [];\n const answer = r.answer as unknown;\n const text =\n r.full === false\n ? undefined\n : (str(answer) ??\n str((answer as Record<string, unknown> | null)?.text) ??\n str(r.text) ??\n str(answers.at(-1)?.text));\n const question = str(r.title) ?? (str(r.question) === id ? undefined : str(r.question));\n const about = [str(r.task), str(r.item) ?? str(r.object)].filter(Boolean).join(' ') || undefined;\n const state = str(r.state);\n return {\n id,\n ...(question ? { question } : {}),\n ...(text ? { text } : {}),\n ...(about ? { about } : {}),\n ...(state ? { state } : {}),\n path: str(r.path) ?? `alterspec-client questions ${id}`,\n };\n}\n\n/** The dispatcher's `ruled` or `ruled_changed`, each question once; undefined when it sent no list. */\nexport function parseRuled(value: unknown): Ruling[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const seen = new Set<string>();\n return value.flatMap((v) => {\n const r = rulingOf(v);\n if (!r || seen.has(r.id)) return [];\n seen.add(r.id);\n return [r];\n });\n}\n\nconst one = (text: string) => text.replace(/\\s+/g, ' ').trim();\n\n/** One ruling as the brief's lines: whole with its answer, else one line naming where it is read. */\nfunction rulingLines(r: Ruling): string[] {\n const head = `- ${r.id}${r.about || r.state ? ` (${[r.about, r.state].filter(Boolean).join('; ')})` : ''}`;\n if (!r.text) return [`${head}: ${r.question ? `${one(r.question)} ` : ''}\\`${r.path}\\``];\n return [`${head}${r.question ? `: ${one(r.question)}` : ''}`, ` - Ruled: ${one(r.text)}`];\n}\n\n/**\n * The notice that opens the brief after a reversal: the product side replaced a ruling this task saw, and what was\n * built on the earlier answer follows the new one. Empty when nothing changed.\n */\nexport function ruledChangedLines(changed: Ruling[] | undefined): string[] {\n if (!changed?.length) return [];\n return [\n `**A ruling changed since you last read this brief** (${changed.map((r) => r.id).join(', ')}): the product side replaced an answer this task saw. What you built on the earlier answer follows this one; the tests that checked the earlier answer change with it.`,\n '',\n ...changed.flatMap(rulingLines),\n '',\n ];\n}\n\n/**\n * The brief's section \"Ruled, not in the export yet\": the rulings the product side gave on this task's objects that\n * the export doesn't hold yet, without the questions the brief already shows whole. Empty when none.\n */\nexport function ruledSection(\n ruled: Ruling[] | undefined,\n shownWhole: ReadonlySet<string> = new Set(),\n): string[] {\n const list = (ruled ?? []).filter((r) => !shownWhole.has(r.id));\n if (!list.length) return [];\n const whole = list.filter((r) => r.text).length;\n return [\n '## Ruled, not in the export yet',\n '',\n [\n 'The product side has answered these about this task’s objects; the export will say so once the ruling is groomed and signed off. Build on them as you would on the spec, over the export’s silence or older wording. Name no question number in code or tests: write the behaviour, as the spec will.',\n whole === list.length\n ? ''\n : whole\n ? `Whole: the ${whole === 1 ? 'ruling' : `${whole} rulings`} that change an item of this task; the others are one line each, read with the command they name when their object is in front of you.`\n : 'None changes an item of this task: each is one line, read with the command it names when its object is in front of you.',\n ]\n .filter(Boolean)\n .join(' '),\n '',\n ...list.flatMap(rulingLines),\n '',\n ];\n}\n","import { exportChange } from '../../src/changes/delta-record.js';\nimport { COMPATIBILITY_SECTION, compatibilityText } from '../../src/changes/compatibility.js';\nimport { DATA_CHANGE_RE, DATA_CHANGE_SECTION, dataChangeText } from '../../src/changes/data-change.js';\nimport { itemObject, objectParts } from '../../src/changes/parts.js';\nimport { type ExportReader, frontMatterOf, idsIn } from '../../src/export/read.js';\nimport { slug } from '../../src/export/paths.js';\nimport { diffLines, unifiedDiff } from '../../src/lib/diff.js';\nimport { splitFrontMatter } from '../../src/lib/frontmatter-split.js';\nimport { criterionParts } from '../../src/spec/criteria.js';\nimport type { DeltaEntry } from '../../src/schemas/delta.js';\nimport { type IdKind, idKind } from '../../src/schemas/ids.js';\nimport type { WorkChange, WorkTask, WorkTrack } from '../../src/schemas/work.js';\nimport {\n OPERATIONS_FILE,\n contractPath,\n designSystemPath,\n initiativePath,\n mockupPath,\n patternsPath,\n RULE_MATRIX_FILE,\n} from '../../src/spec/layout.js';\nimport { history, type PinnedReader, pinnedReader } from './pin.js';\nimport { type Question, type TaskAnswer, answersSection, questionsSection } from './questions.js';\nimport { type Ruling, ruledChangedLines, ruledSection } from './ruled.js';\nimport type { TaskRef } from './task.js';\n\n/**\n * A task's brief, assembled from the export (spec 12.2 `context`): what the change is for, what it changed in the\n * task's objects, where each object is now, and for the backend the criteria on the checklist and the operations of\n * its capabilities, for a UI track the screens, their contracts, pages and the channel's design. Texts only for what\n * the task changes; the rules, events and other criteria its capabilities name are an index of paths, so the agent\n * never reads more of the export than it needs. Every text is the one the task's change saw at its sign-off\n * (`pin.ts`, client 0.19.0): what later changes did to the objects the brief names is listed apart, as their tasks'\n * work, so a task's brief doesn't change when a rule it names does.\n */\n\nexport class ContextError extends Error {}\n\nexport interface Piece {\n /** The ID or key it is about. */\n id: string;\n /** The export path, relative to the export folder. */\n path: string;\n /** Its title, for a piece the brief only points to. */\n title?: string;\n /** Its text, for a piece the brief carries; without one the brief names its path. */\n text?: string;\n /** Whether the task changes it, so its delta is among the task's objects. */\n changed?: boolean;\n /** A line after the text, saying where the rest is. */\n rest?: string;\n /** A fact about it in one line (an entity's lifecycle), after the path. */\n note?: string;\n /** The later changes that touched it: the brief shows it as the task's change saw it. */\n since?: string[];\n /** A later change brought it into the export: the brief shows it as the export holds it now. */\n entered?: boolean;\n}\n\nexport interface ObjectBrief {\n key: string;\n /** Its file in the export now, or undefined when the export doesn't hold it. */\n file?: string;\n /** Its shards' folder, when it has one. */\n shards?: string;\n /** What the change did to it, in export terms; undefined when the delta has no entry for it. */\n change?: string;\n status?: { before?: string; after?: string };\n /** A line diff of its text before and after the change (the export's side of it), or one line saying why none. */\n diff?: string;\n /** Why the delta could not say, for an object the backfill could not recover. */\n unrecoverable?: string;\n /**\n * What moved since this change: the later signed-off changes that touched the object, in the order they did, and\n * whether the export's current text differs from this delta's after.\n */\n since?: { changes: string[]; differs: boolean };\n /** The file holding it as this change left it, when a later change touched it. */\n pinned?: string;\n}\n\n/** A later change that touched something the brief names. */\nexport interface LaterChange {\n id: string;\n title?: string;\n /** That change's task on this track, when it has one. */\n task?: string;\n /** Its delta, in the export. */\n delta?: string;\n}\n\n/** An object the brief names that later changes touched: their tasks' work, never this task's. */\nexport interface ChangedSince {\n key: string;\n title?: string;\n /** Whether the task changes the object, or only names it. */\n own?: boolean;\n /** The later changes, in the order they touched it; `fresh` on those the last read of the brief didn't show. */\n changes: { id: string; fresh?: boolean }[];\n /** The file holding the object as the task's change saw it. */\n pinned?: string;\n /** What the changes new since the last read did to it: from the text before the first of them to the export's now. */\n diff?: string;\n /** The export no longer holds it. */\n gone?: boolean;\n /** The export did not hold it when the task's change was signed off: the first of the changes brought it in. */\n entered?: boolean;\n /**\n * For an object this task changes: the check was made here, from the deltas, whether a later change removed or\n * reworded a line of this change's hunks. Absent for a binary file or an object the export did not hold then.\n */\n checked?: boolean;\n /** The later changes that removed or reworded lines this change wrote, with those lines. */\n lost?: { change: string; lines: string[] }[];\n}\n\nexport interface ChecklistItem {\n /** The item as `work.json` and the `Alterspec-Covers` trailer write it. */\n item: string;\n /** What it is, in one line. */\n what: string;\n /** The commit that covered it, as the dispatcher recorded it. */\n covered?: string;\n /**\n * Its weight on this track (work.json format 3 on): how much specified behaviour it is, reasoned at sign-off;\n * 0 (format 6 on): this track builds nothing of it, so it is read, never covered.\n */\n weight?: number;\n /** What a person calls it (work.json format 5): the words the dispatcher's lists show beside the ID. */\n label?: string;\n /** For an item of weight 0 whose object the export no longer holds: the later change that took it out. */\n removedBy?: string;\n}\n\nexport interface Checklist {\n items: ChecklistItem[];\n /** Whether the covered marks are the dispatcher's; false when it couldn't be asked. */\n known: boolean;\n /** Why the covered items are unknown. */\n note?: string;\n}\n\nexport interface CoveredState {\n /** Item → the commit that covered it, from the dispatcher's `task`. */\n covered?: Map<string, string>;\n /** The questions the task carries into the spec, built on its track or not (spec 8.4), from the same `task`. */\n answers?: TaskAnswer[];\n /** The done predecessors whose branch the work starts from (not in the main branch yet), from the same `task`. */\n startFrom?: StartFrom[];\n /** The task's items as the dispatcher holds them (its first list stands; the weights are the latest export's). */\n items?: DispatcherItem[];\n /** The change's tasks on the other tracks and their statuses (dispatcher decision 36); absent from an older one. */\n siblings?: Sibling[];\n /**\n * The questions the brief shows whole (`questions_full`: asked on this track, or answered with a change to an item\n * of this task); the others are one line. Absent from an older dispatcher: every question whole, as before.\n */\n questionsFull?: Set<string>;\n /**\n * The objects of this task a later change touched (`changed_since`: added, changed, removed, keys only). Absent from\n * an older dispatcher: the brief works it out from the deltas; empty: no part of this task changed.\n */\n changedSince?: Set<string>;\n /** Rulings on this task's objects the export doesn't hold yet (`ruled`); absent from an older dispatcher. */\n ruled?: Ruling[];\n /** Rulings this task saw that the product side has since replaced (`ruled_changed`, sent once). */\n ruledChanged?: Ruling[];\n /** Why the dispatcher couldn't be asked. */\n unknown?: string;\n}\n\n/** An item of a task as the dispatcher's `task` returns it. */\nexport interface DispatcherItem {\n item: string;\n weight?: number;\n label?: string;\n}\n\n/** A task of the same change on another track, as the dispatcher's `task` returns it (decision 36). */\nexport interface Sibling {\n id: string;\n track: string;\n status: string;\n commit?: string;\n branch?: string;\n in_main_at?: string;\n /**\n * The tracks whose behaviour this sibling's task alters (work.json format 9 `alters`, read from the export, not\n * the dispatcher); absent: unknown, as before format 9.\n */\n alters?: string[];\n}\n\n/** The dispatcher's `questions_full`: question IDs, as strings or objects with `id`; undefined when it sent none. */\nexport function parseQuestionsFull(value: unknown): Set<string> | undefined {\n if (!Array.isArray(value)) return undefined;\n return new Set(\n value.flatMap((v: unknown) => {\n const id = typeof v === 'string' ? v : (v as { id?: unknown } | null)?.id;\n return typeof id === 'string' && id ? [id] : [];\n }),\n );\n}\n\n/** The dispatcher's `changed_since { added, changed, removed }` as one set of keys; undefined when it sent none. */\nexport function parseChangedSince(value: unknown): Set<string> | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n const lists = ['added', 'changed', 'removed'].map((k) => (value as Record<string, unknown>)[k]);\n if (!lists.some(Array.isArray)) return undefined;\n return new Set(\n lists.flatMap((l) =>\n Array.isArray(l)\n ? l.flatMap((v: unknown) => {\n const key =\n typeof v === 'string'\n ? v\n : ((v as { key?: unknown; id?: unknown } | null)?.key ?? (v as { id?: unknown } | null)?.id);\n return typeof key === 'string' && key ? [key] : [];\n })\n : [],\n ),\n );\n}\n\n/** The dispatcher's `siblings`, the well-formed entries only; undefined when it sent none. */\nexport function parseSiblings(value: unknown): Sibling[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const str = (v: unknown) => (typeof v === 'string' && v ? v : undefined);\n return value.flatMap((v: Record<string, unknown>) => {\n const id = str(v?.id);\n const track = str(v?.track) ?? id?.split('/')[1];\n const status = str(v?.status);\n if (!id || !track || !status) return [];\n const commit = str(v.commit);\n const branch = str(v.branch);\n const inMain = str(v.in_main_at);\n return [\n {\n id,\n track,\n status,\n ...(commit ? { commit } : {}),\n ...(branch ? { branch } : {}),\n ...(inMain ? { in_main_at: inMain } : {}),\n },\n ];\n });\n}\n\n/** What the brief says about a compatibility (the proposal's \"## Compatibility\" section). */\nexport interface Compatibility {\n /** This change keeps the old behaviour while its other tracks build it: the section, its UI tracks, who ends it. */\n kept?: { text: string; tracks: string[]; endedBy: string[] };\n /** The compatibilities this task ends: another change's tasks on other tracks it waits for, by change. */\n ends?: { change: string; tracks: string[] }[];\n}\n\n/** A done predecessor on a pushed branch: the task's branch is based on it, not on the main branch. */\nexport interface StartFrom {\n /** The predecessor, e.g. `CHG-012/BE`. */\n id: string;\n /** The branch it was done on, e.g. `task/chg-012-be`. */\n branch: string;\n /** The commit it was done at. */\n commit?: string;\n}\n\n/**\n * The branches to start a task from, out of the dispatcher's `after` entries (of `next_task` or `task`): the done\n * predecessors of the same track whose branch isn't the main one (`branch` null), the predecessor's own track first.\n */\nexport function startFrom(track: string, after: unknown): StartFrom[] {\n if (!Array.isArray(after)) return [];\n const out: StartFrom[] = [];\n for (const a of after as { id?: unknown; commit?: unknown; branch?: unknown }[]) {\n if (typeof a?.id !== 'string' || typeof a.branch !== 'string' || !a.branch) continue;\n if (a.id.split('/')[1] !== track) continue;\n out.push({ id: a.id, branch: a.branch, ...(typeof a.commit === 'string' ? { commit: a.commit } : {}) });\n }\n return out;\n}\n\n/** Where the export uses an entity, or one attribute of it, that the task changes. */\nexport interface WhereUsed {\n entity: string;\n /** One attribute the task's diff names; absent for the entity as a whole. */\n attribute?: string;\n /** Screens whose fields show it. */\n screens: Piece[];\n /** Capabilities that take or return it (an attribute), or work with it (the entity). */\n capabilities: Piece[];\n /** Rules about the entity (rules name no attributes); only for the entity as a whole. */\n rules: Piece[];\n}\n\n/** The reach of a rule or role the task touches or names: where the export enforces, holds or shows it. */\nexport interface Reach {\n id: string;\n kind: 'rule' | 'role';\n title?: string;\n /** A rule: the capabilities that list it; a role: the capabilities it may perform, each with its scope. */\n capabilities: (Piece & { scope?: string })[];\n /** A rule: the criteria whose Covers name it, by capability; absent for a role. */\n criteria?: string[];\n /** A rule: the screens of those capabilities; a role: the screens it is on. */\n screens: Piece[];\n /** A rule: its row of the export's rule matrix (triggered by, reads, listed by, covered by, message shown on). */\n matrix?: string[];\n}\n\nexport interface TaskContext {\n task: string;\n /** The change's questions on every track, as the dispatcher keeps them; absent when it couldn't be asked. */\n questions?: Question[];\n /** The questions shown whole (the dispatcher's `questions_full`); absent: every question whole. */\n questionsFull?: string[];\n /** What this task carries into the spec and which of it the track built already; absent when none or unknown. */\n answers?: TaskAnswer[];\n /** What this track builds in this change, in a line and in two or three sentences (work.json format 5). */\n title?: string;\n summary?: string;\n /** The size of what this track builds in this change, 1–100 (work.json format 7), reasoned at sign-off. */\n weight?: number;\n /**\n * The initiative the change belongs to (work.json format 8): the whole it is part of, the idea and the problem it\n * solves, as the export holds it now. Why the work exists; never work of its own.\n */\n initiative?: { id: string; title: string; path: string; body: string };\n /** The task's items (work.json format 2 on, with weights from 3 and labels from 5); undefined for a format 1 export, which has none. */\n checklist?: Checklist;\n export: string;\n change: Pick<WorkChange, 'id' | 'title' | 'signed_off' | 'level' | 'depends_on'>;\n track: WorkTrack;\n after: WorkTask['after'];\n /** The done predecessors' branches the task's branch starts from; absent when none or the dispatcher wasn't asked. */\n startFrom?: StartFrom[];\n /** The change's tasks on other tracks, from the dispatcher; absent when it sent none. */\n siblings?: Sibling[];\n /** The compatibility this change keeps or this task ends; absent when neither. */\n compatibility?: Compatibility;\n /** Rulings on this task's objects not in the export yet, and those replaced since the last read (the dispatcher's). */\n ruled?: Ruling[];\n ruledChanged?: Ruling[];\n proposal: {\n path: string;\n why?: string;\n what?: string;\n /** The one-time data change the proposal declares; absent for \"None.\" (the backend's `CHG#data-change` item). */\n dataChange?: string;\n };\n delta?: string;\n objects: ObjectBrief[];\n /** Where the export uses the entities and attributes the task changes. */\n whereUsed?: WhereUsed[];\n /** Where the export enforces, holds or shows the rules and roles the task touches or its text names. */\n reach?: Reach[];\n /** The rule matrix's \"How to read\" lines for the rows shown under Reach. */\n matrixLegend?: string[];\n /** The backend track. */\n acceptance?: Piece[];\n rules?: Piece[];\n events?: Piece[];\n operations?: Piece[];\n /** The decisions the task's text names. */\n decisions?: Piece[];\n /** The glossary terms the change's text uses. */\n terms?: Piece[];\n /** The backend track: the entities its capabilities work with, by path, each with its lifecycle in one line. */\n entities?: Piece[];\n /** The backend track: the quality requirements and integrations the task touches or its text names. */\n nfr?: Piece[];\n integrations?: Piece[];\n /** A UI track. */\n screens?: { id: string; file?: string; contract?: string; page?: string }[];\n design?: { designSystem?: string; patterns?: string };\n /** The folder the pinned files are written to: an absolute path in the brief is under it. */\n pins?: string;\n /** The objects the brief names that later changes touched; absent when nothing moved since the change. */\n changedSince?: ChangedSince[];\n /** Those later changes, in the change map's order. */\n later?: LaterChange[];\n /**\n * With the dispatcher's `changed_since`: how many objects the brief names were changed by later changes that the\n * task doesn't cite (left out of \"Changed since\"), and whether none it cites was.\n */\n sinceElsewhere?: number;\n changedSinceNone?: boolean;\n}\n\n/** A shard's text without the comment naming its source. */\nconst shardText = (x: ExportReader, path: string | undefined) =>\n path\n ? x\n .read(path)\n ?.replace(/^<!-- source: [^\\n]*-->\\n\\n/, '')\n .trim()\n : undefined;\n/** A section shard's text without its `## ` heading, which the brief gives itself. */\nconst sectionText = (x: ExportReader, path: string | undefined) =>\n shardText(x, path)?.replace(/^## [^\\n]*\\n*/, '');\n\nconst screenOf = (key: string): string | undefined =>\n /^UX-(SCR-[A-Z]{2,6}-\\d{2})-[A-Z]{2,5}$/.exec(key)?.[1] ??\n /^file:experience\\/[a-z]{2,5}\\/mockups\\/(SCR-[A-Z]{2,6}-\\d{2})\\.html$/.exec(key)?.[1] ??\n (/^SCR-[A-Z]{2,6}-\\d{2}$/.test(key) ? key : undefined);\n\n/**\n * An object's text as the brief compares it: without the `version:` line the sign-off raises, the fingerprints a\n * contract keeps (`reviewed:`, `dry:`, `page:`) and the template's HTML comments, which tell an author what to write\n * and a builder nothing. Files (pages, design) stay whole.\n */\nexport const forDiff = (key: string, text: string | undefined) =>\n key.startsWith('file:')\n ? (text ?? '')\n : (text ?? '')\n .replace(/^[^\\S\\n]*<!--[\\s\\S]*?-->[^\\S\\n]*\\n/gm, '')\n .replace(/<!--[\\s\\S]*?-->/g, '')\n .replace(/^version:[^\\S\\n]*\\d+[^\\S\\n]*\\n/m, '')\n .replace(/^(?:reviewed|dry|page):[^\\n]*\\n/gm, '');\n\n/**\n * Each hunk header of a document's diff with the section it falls in, as git names the function: `@@ … @@ ## Main\n * flow`, `@@ … @@ ## Acceptance criteria › CAP-X-001-AC-02`, or `front-matter`, so the agent needn't open the file\n * to know where a change sits.\n */\nexport function withSections(diff: string, before: string, after: string): string {\n const where = (text: string, line: number) => {\n const lines = text.split('\\n');\n if (lines[0] === '---') {\n const end = lines.indexOf('---', 1);\n if (end > 0 && line - 1 <= end) return 'front-matter';\n }\n let sub: string | undefined;\n for (let i = Math.min(line, lines.length) - 1; i >= 0; i--) {\n const l = lines[i]!;\n if (sub === undefined && /^### /.test(l)) sub = l.slice(4).split(/\\s/)[0];\n if (/^## /.test(l)) return sub ? `${l} › ${sub}` : l;\n }\n return undefined;\n };\n const lines = diff.split('\\n');\n return lines\n .map((header, i) => {\n const m = /^@@ -(\\d+),\\d+ \\+(\\d+),\\d+ @@$/.exec(header);\n if (!m) return header;\n // The hunk's first changed line, not its first context line, names the section.\n let k = i + 1;\n while (lines[k]?.startsWith(' ')) k++;\n const skipped = k - i - 1;\n const name = lines[k]?.startsWith('+')\n ? where(after, Number(m[2]) + skipped)\n : where(before, Number(m[1]) + skipped);\n return name ? `${header} ${name}` : header;\n })\n .join('\\n');\n}\n\n/** Front-matter the tooling keeps (review and page fingerprints, status), which says nothing about the work. */\nconst BOOKKEEPING = /^(reviewed|page|dry|status|version|signed_off|base):/;\n\n/** The first line a text adds to another, as a sentence: no list marker, heading mark or emphasis. */\nconst firstAddedLine = (a: string, b: string) =>\n diffLines(a, b)\n .filter((l) => l.op === '+')\n .map((l) =>\n l.text\n .replace(/^\\s*(?:[-*]|#+|\\d+\\.)\\s+/, '')\n .replace(/\\*\\*/g, '')\n .trim(),\n )\n .find((t) => t && !/^(---|```)/.test(t) && !BOOKKEEPING.test(t));\n\nconst clipped = (line: string | undefined) => (line && line.length > 200 ? `${line.slice(0, 199)}…` : line);\n\n/** The first sentence the change added to an object's body, else to its front-matter; for a whole-object item. */\nfunction firstAdded(key: string, entry: DeltaEntry): string | undefined {\n const before = forDiff(key, entry.before);\n const after = forDiff(key, entry.after);\n return clipped(\n firstAddedLine(splitFrontMatter(before).body, splitFrontMatter(after).body) ??\n firstAddedLine(splitFrontMatter(before).raw ?? '', splitFrontMatter(after).raw ?? ''),\n );\n}\n\n/** An object's text in the export: an item's shard (without the comment naming its source), else its file. */\nfunction currentText(x: ExportReader, key: string): string | undefined {\n const file = x.fileOf(key);\n if (!file || !x.has(file)) return undefined;\n const shard = x.itemShard(file, key);\n return shard ? shardText(x, shard) : x.read(file);\n}\n\n/** The first file holding an object as the change saw it: an item's shard, a document's file. */\nconst pinnedPath = (x: PinnedReader, key: string): string | undefined =>\n x.pinnedFiles(key).keys().next().value;\n\nfunction objectBrief(\n x: PinnedReader,\n key: string,\n entry: DeltaEntry | undefined,\n why: string | undefined,\n at: (path: string) => string,\n): ObjectBrief {\n const now = x.current;\n const file = now.fileOf(key);\n const held = file !== undefined && now.has(file);\n const brief: ObjectBrief = { key, ...(held ? { file } : {}) };\n if (held && now.shards(file).length) brief.shards = now.shards(file)[0]!.replace(/\\/[^/]+$/, '');\n if (why) brief.unrecoverable = why;\n if (!entry) return brief;\n // What moved since the sign-off: a later change that touched it, or a current text that isn't this delta's after.\n const later = x.seen(key).later.map((l) => l.change);\n const text = currentText(now, key);\n const differs =\n held &&\n entry.exported.after &&\n entry.after !== undefined &&\n !entry.binary &&\n text !== undefined &&\n forDiff(key, entry.after).trim() !== forDiff(key, text).trim();\n if (later.length || differs) brief.since = { changes: later, differs: !!differs };\n const own = later.length ? pinnedPath(x, key) : undefined;\n if (own) brief.pinned = at(own);\n brief.change = exportChange(entry);\n if (entry.status) brief.status = entry.status;\n if (entry.before !== undefined || entry.after !== undefined) {\n const d = unifiedDiff(forDiff(key, entry.before), forDiff(key, entry.after));\n if (d)\n brief.diff = key.startsWith('file:')\n ? d\n : withSections(d, forDiff(key, entry.before), forDiff(key, entry.after));\n else if (unifiedDiff(entry.before ?? '', entry.after ?? ''))\n brief.diff = 'Only its version, its fingerprints or the template’s comments changed: nothing to build.';\n } else if (entry.binary) {\n brief.diff = `binary: ${[entry.binary.before, entry.binary.after].map((b) => (b ? `${b.size} bytes` : '—')).join(' → ')}`;\n }\n return brief;\n}\n\nconst KIND_WORDS: Partial<Record<IdKind, string>> = {\n app: 'the application',\n module: 'module',\n capability: 'capability',\n screen: 'screen',\n experience: 'experience screen',\n role: 'role',\n integration: 'integration',\n nfr: 'non-functional requirement',\n persona: 'persona',\n entity: 'entity',\n rule: 'rule',\n flow: 'flow',\n event: 'event',\n decision: 'decision',\n};\n\n/** The title of an object: its item shard's `## <ID> <title>`, else its file's first `# ` heading. */\nexport function titleOf(x: ExportReader, id: string): string | undefined {\n const file = x.fileOf(id);\n if (!file || !x.has(file)) return undefined;\n const shard = x.itemShard(file, id);\n if (shard) return /^## \\S+ (.+)$/m.exec(shardText(x, shard) ?? '')?.[1]?.trim();\n return /^# (.+)$/m.exec(splitFrontMatter(x.read(file)!).body)?.[1]?.trim();\n}\n\nconst named = (x: ExportReader, id: string) => {\n const title = titleOf(x, id);\n return title ? `${id} ${title}` : `${id} (not in the export now)`;\n};\n\n/**\n * What a criterion asks of a track, from the capability's Acceptance criteria shard: on `BE` its `Then` (and what\n * follows it but `Covers` and `Shown`), on a UI track its `Shown`; with a note when the other part is another task's.\n */\nfunction criterionOf(x: ExportReader, cap: string, id: string, track?: string): string | undefined {\n const file = x.fileOf(cap);\n const text = file && x.has(file) ? sectionText(x, x.sectionShard(file, 'Acceptance criteria')) : undefined;\n const chunk = text?.split(/^### /m).find((c) => c.split(/\\s/)[0] === id);\n if (!chunk) return undefined;\n const parts = criterionParts(chunk.split('\\n').slice(1).join('\\n'));\n const ui = track !== undefined && track !== BACKEND;\n const lines = (ui ? parts.shown : parts.system)\n .split('\\n')\n .map((l) =>\n l\n .replace(/^\\s*[-*]\\s*/, '')\n .replace(/\\*\\*/g, '')\n .trim(),\n )\n .filter(Boolean);\n const from = lines.findIndex((l) => (ui ? /^Shown\\b/ : /^Then\\b/).test(l));\n const kept = (from >= 0 ? lines.slice(from) : lines).filter((l) => !/^Covers:/.test(l));\n const note = ui\n ? parts.hasThen\n ? ' (what the system guarantees is the BE task’s)'\n : ''\n : parts.hasShown\n ? ' (what the screen shows is the UI task’s)'\n : '';\n return kept.length ? `${kept.join(' ')}${note}` : undefined;\n}\n\nconst BACKEND = 'BE';\n\n/**\n * One line saying what an item is, from the export (no YAML parsed: the client carries no YAML parser). An object\n * that is an item whole says what the change did to it, with the first sentence it added, so the line names the work\n * rather than the object.\n */\nexport function itemWhat(x: ExportReader, item: string, entry?: DeltaEntry, track?: string): string {\n const ac = /^((CAP-[A-Z]{2,6}-\\d{3})-AC-\\d{2})$/.exec(item);\n if (ac) {\n const then = criterionOf(x, ac[2]!, ac[1]!, track);\n return `acceptance criterion of ${named(x, ac[2]!)}${then ? `: ${then}` : ''}`;\n }\n const action = /^(SCR-[A-Z]{2,6}-\\d{2})\\.(A\\d{2})$/.exec(item);\n if (action) {\n const [, scr, a] = action;\n const file = x.fileOf(scr!);\n const actions = file && x.has(file) ? sectionText(x, x.sectionShard(file, 'Actions')) : undefined;\n const line = actions\n ?.split('\\n')\n .map((l) => l.replace(/^\\s*[-*]\\s*/, '').trim())\n .find((l) => l.startsWith(`${a} `));\n const label = line?.slice(a!.length).trim();\n return `action ${a}${label ? ` \"${label.replace(/\\s*→\\s*/, '\" → ')}` : ''}${label && !label.includes('→') ? '\"' : ''} on ${named(x, scr!)}`;\n }\n const state = /^(UX-(SCR-[A-Z]{2,6}-\\d{2})-([A-Z]{2,5}))#(.+)$/.exec(item);\n if (state) {\n const [, ux, scr, code, id] = state;\n const rule = /^rule-(.+)$/.exec(id!)?.[1];\n // The mockup shows a state by its URL, so the agent opens exactly what it builds.\n const page = mockupPath(code!, scr!);\n const open = x.has(page) ? `; open \\`${page}?state=${encodeURIComponent(id!)}\\`` : '';\n return `state \"${id}\" of ${ux} (${named(x, scr!)})${rule ? `: the message of RULE-${rule.toUpperCase()}` : ''}${open}`;\n }\n if (item.startsWith('file:')) {\n const path = item.slice(5);\n const page = /\\/mockups\\/(SCR-[A-Z]{2,6}-\\d{2})\\.html$/.exec(path)?.[1];\n const what = page\n ? `the mockup page of ${page}`\n : /\\/design-system\\.md$/.test(path)\n ? 'the channel’s design system'\n : /\\/patterns\\.md$/.test(path)\n ? 'the channel’s patterns'\n : 'a file of the channel’s experience';\n return `${what}: \\`${path}\\`${x.has(path) ? '' : ' (not in the export now)'}`;\n }\n if (item.startsWith('term:')) return `glossary term \"${item.slice(5)}\"`;\n if (DATA_CHANGE_RE.test(item))\n return `the one-time change to the records the product already holds (the proposal's \"${DATA_CHANGE_SECTION}\", below)`;\n // A part of an object with no part of its own kind: its front-matter, a section, a line (alterspec 0.30).\n const part = /^([^#]+)#([^#]+)$/.exec(item);\n if (part && !/^UX-/.test(item)) {\n const [, key, slug] = part as unknown as [string, string, string];\n const k = idKind(key);\n const owner = `${k && KIND_WORDS[k] ? `${KIND_WORDS[k]} ` : ''}${named(x, key)}`;\n const kind = entry?.kind === 'item' ? 'item' : 'doc';\n const after = entry?.after !== undefined ? objectParts(entry.after, kind).get(slug) : undefined;\n const before = entry?.before !== undefined ? objectParts(entry.before, kind).get(slug) : undefined;\n const label = !after\n ? `the part \"${slug}\"`\n : after.label === 'front-matter'\n ? 'the front-matter'\n : after.label === 'section'\n ? `the section \"${after.heading}\"`\n : `the line \"${after.heading}\"`;\n const line = after ? clipped(firstAddedLine(before?.text ?? '', after.text)) : undefined;\n return `${label} of ${owner}${line ? `: \"${line}\"` : ''}`;\n }\n const kind = idKind(item);\n const what = `${kind && KIND_WORDS[kind] ? `${KIND_WORDS[kind]} ` : ''}${named(x, item)}`;\n if (!entry) return what;\n const change = exportChange(entry);\n if (change !== 'modified') return `${what}, ${change}`;\n const line = firstAdded(item, entry);\n return line ? `${what}, modified: \"${line}\"` : `${what}, modified (see its delta)`;\n}\n\n/** The proposal's one-time data change, unless it says \"None.\" or nothing. */\nfunction dataChangeOf(text: string | undefined): { dataChange?: string } {\n const t = dataChangeText(text);\n return t ? { dataChange: t } : {};\n}\n\n/**\n * The attributes an entity's diff adds, removes or changes (`- name: X` and the lines under it); undefined when the\n * entity enters or leaves the export, when the whole of it is new or gone to the team.\n */\nfunction changedAttributes(entry: DeltaEntry | undefined): string[] | undefined {\n if (!entry || !entry.exported.before || !entry.exported.after) return undefined;\n if (entry.before === undefined || entry.after === undefined) return undefined;\n const names = (raw: string) =>\n new Map([...raw.matchAll(/^ {2}- name: (.+?)\\s*$/gm)].map((m) => [m[1]!, m.index!]));\n const before = splitFrontMatter(entry.before).raw ?? '';\n const after = splitFrontMatter(entry.after).raw ?? '';\n const attr = (raw: string, from: number) => {\n const chunk = raw.slice(from).split(/\\n(?! {4})/)[0] ?? '';\n return chunk.replace(/^\\s*- name: .*\\n?/, '');\n };\n const b = names(before);\n const a = names(after);\n const out = new Set<string>();\n for (const [n, i] of a) if (!b.has(n) || attr(before, b.get(n)!) !== attr(after, i)) out.add(n);\n for (const n of b.keys()) if (!a.has(n)) out.add(n);\n return [...out];\n}\n\n/**\n * Where the export uses what the task changes: for every entity among the task's objects, the screens, capabilities\n * and rules of the export (its `_generated/index.json`) that show, take, return or guard it, per changed attribute\n * and for the entity as a whole. Only what the export holds is listed: a screen not signed off isn't the team's yet.\n */\nfunction whereUsed(\n x: ExportReader,\n objects: readonly string[],\n entries: Map<string, DeltaEntry>,\n changed: Set<string>,\n): WhereUsed[] {\n const index = x.index();\n if (!index) return [];\n const piece = (id: string, title: string, file: string | undefined): Piece => ({\n id,\n path: file ?? '',\n title,\n ...(changed.has(id) ? { changed: true } : {}),\n });\n const out: WhereUsed[] = [];\n for (const entity of objects.filter((k) => idKind(k) === 'entity')) {\n const attributes = changedAttributes(entries.get(entity)) ?? [];\n for (const attribute of attributes)\n out.push({\n entity,\n attribute,\n screens: index.screens\n .filter((s) => s.fields.some((f) => f.entity === entity && f.attributes.includes(attribute)))\n .map((s) => piece(s.id, s.title, x.fileOf(s.id))),\n capabilities: index.capabilities\n .filter((c) =>\n [...(c.inputs ?? []), ...(c.outputs ?? [])].some(\n (d) => 'entity' in d && d.entity === entity && d.attributes.includes(attribute),\n ),\n )\n .map((c) => piece(c.id, c.title, x.fileOf(c.id))),\n rules: [],\n });\n out.push({\n entity,\n screens: index.screens\n .filter((s) => s.fields.some((f) => f.entity === entity))\n .map((s) => piece(s.id, s.title, x.fileOf(s.id))),\n capabilities: index.capabilities\n .filter((c) => c.entities.some((e) => e.entity === entity))\n .map((c) => piece(c.id, c.title, x.fileOf(c.id))),\n rules: index.rules\n .filter((r) => r.entities.includes(entity) || (r.guards ?? []).some((g) => g.entity === entity))\n .map((r) => piece(r.id, r.title, x.fileOf(r.id))),\n });\n }\n return out;\n}\n\n/** An entity's lifecycle in one line, from the index: its states, the initial one, its transitions and by what. */\nfunction lifecycleOf(x: ExportReader, id: string): string | undefined {\n const e = x.index()?.entities.find((e) => e.id === id);\n if (!e?.states?.length) return undefined;\n const states = e.states.map((s) => (s === e.initial_state ? `${s} (initial)` : s)).join(', ');\n const transitions = (e.transitions ?? [])\n .map((t) => `${t.from}->${t.to}${t.by === 'time' ? ` by time${t.at ? ` at ${t.at}` : ''}` : ''}`)\n .join(', ');\n return `states ${states}${transitions ? `; transitions ${transitions}` : '; no transitions'}`;\n}\n\n/** The lines of an object's text that count when two deltas are compared: trimmed, non-blank, no front-matter fence. */\nconst linesOf = (key: string, text: string | undefined): Set<string> =>\n new Set(\n forDiff(key, text)\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l && l !== '---'),\n );\n\n/** The lines of a rule's matrix row that say where it reaches; the rule's own text says the rest. */\nconst MATRIX_ROW =\n /^- \\*\\*(Triggered by|Reads the guarded entity|Listed by, without triggering a guard|Covered by|Message shown on)/;\n\ninterface Matrix {\n /** The \"How to read\" bullets of the rows' lines, each with its continuation lines. */\n legend: string[];\n /** Rule ID → its row's lines, links reduced to their text. */\n rows: Map<string, string[]>;\n}\n\nconst matrices = new WeakMap<ExportReader, Matrix>();\n\n/** The export's rule matrix, read once: the view the agents opened for every rule's reach. */\nfunction matrixOf(x: ExportReader): Matrix {\n const known = matrices.get(x);\n if (known) return known;\n const m: Matrix = { legend: [], rows: new Map() };\n const text = x.read(RULE_MATRIX_FILE);\n if (text) {\n const [head, ...blocks] = text.split(/^(?=## )/m);\n const legend = head!.split('How to read a rule:')[1] ?? '';\n const bullets = legend.split(/^(?=- )/m).map((b) => b.trimEnd());\n for (const b of bullets) if (MATRIX_ROW.test(b)) m.legend.push(...b.split('\\n'));\n for (const block of blocks) {\n const id = block.slice(3).split(/\\s/)[0];\n if (!id) continue;\n const rows = block\n .split('\\n')\n .filter((l) => MATRIX_ROW.test(l))\n .map((l) => l.replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1'));\n if (rows.length) m.rows.set(id, rows);\n }\n }\n matrices.set(x, m);\n return m;\n}\n\n/** Where the export enforces, holds or shows a rule or a role, from the index and the capabilities' criteria. */\nfunction reachOf(\n x: ExportReader,\n id: string,\n kind: 'rule' | 'role',\n changed: Set<string>,\n): Reach | undefined {\n const index = x.index();\n if (!index) return undefined;\n const piece = (pid: string, title: string | undefined, scope?: string): Piece & { scope?: string } => ({\n id: pid,\n path: x.fileOf(pid) ?? '',\n ...(title ? { title } : {}),\n ...(changed.has(pid) ? { changed: true } : {}),\n ...(scope ? { scope } : {}),\n });\n const screenPiece = (sid: string) =>\n piece(sid, index.screens.find((s) => s.id === sid)?.title ?? titleOf(x, sid));\n const title = titleOf(x, id);\n if (kind === 'rule') {\n const caps = index.capabilities.filter((c) => (c.rules ?? []).includes(id));\n const criteria = caps.flatMap((c) => {\n const file = x.fileOf(c.id);\n const text =\n file && x.has(file) ? sectionText(x, x.sectionShard(file, 'Acceptance criteria')) : undefined;\n return (text ?? '')\n .split(/^(?=### )/m)\n .filter(\n (chunk) =>\n chunk.startsWith('### ') &&\n new RegExp(`^\\\\s*[-*]?\\\\s*\\\\**Covers:?\\\\**[^\\\\n]*\\\\b${id}\\\\b`, 'm').test(chunk),\n )\n .map((chunk) => chunk.slice(4).split(/\\s/)[0]!);\n });\n const screens = [...new Set(caps.flatMap((c) => c.screens ?? []))].filter((sid) => x.sources.has(sid));\n const matrix = matrixOf(x).rows.get(id) ?? [];\n return {\n id,\n kind,\n ...(title ? { title } : {}),\n capabilities: caps.map((c) => piece(c.id, c.title)),\n criteria,\n screens: screens.map(screenPiece),\n ...(matrix.length ? { matrix } : {}),\n };\n }\n const caps = index.capabilities.filter((c) => (c.roles ?? []).some((r) => r.role === id));\n const screens = index.screens.filter((s) => (s.roles ?? []).some((r) => r.role === id));\n return {\n id,\n kind,\n ...(title ? { title } : {}),\n capabilities: caps.map((c) => piece(c.id, c.title, c.roles?.find((r) => r.role === id)?.scope)),\n screens: screens.map((s) => piece(s.id, s.title)),\n };\n}\n\ntype Edges = Pick<WorkTask, 'track' | 'after'>;\n\n/** The compatibility the task's change keeps (its proposal's section) and the ones this task ends (its `after`). */\nfunction compatibilityOf(\n x: ExportReader,\n change: { id: string; tasks?: Edges[] },\n work: Edges,\n proposal: string,\n): { compatibility?: Compatibility } {\n const text = compatibilityText(sectionText(x, x.sectionShard(proposal, COMPATIBILITY_SECTION)));\n // An edge that crosses both change and track is one only the end of a compatibility makes.\n const crosses = (owner: Edges, ownerChange: string, a: { change: string; track: string }) =>\n a.change !== ownerChange && a.track !== owner.track;\n const endedBy = x.work.changes.flatMap((other) =>\n (other.tasks ?? [])\n .filter((t) => t.after.some((a) => a.change === change.id && crosses(t, other.id, a)))\n .map((t) => `${other.id}/${t.track}`),\n );\n const kept = text\n ? { text, tracks: (change.tasks ?? []).filter((t) => t.track !== 'BE').map((t) => t.track), endedBy }\n : undefined;\n const byChange = new Map<string, string[]>();\n for (const a of work.after)\n if (crosses(work, change.id, a)) byChange.set(a.change, [...(byChange.get(a.change) ?? []), a.track]);\n const ends = [...byChange].map(([c, tracks]) => ({ change: c, tracks }));\n return kept || ends.length\n ? { compatibility: { ...(kept ? { kept } : {}), ...(ends.length ? { ends } : {}) } }\n : {};\n}\n\n/**\n * The later change that took an object out of the export, when the export no longer holds it: the last change of\n * its history whose entry leaves it out, signed off after the task's change.\n */\nfunction removedByOf(x: ExportReader, change: string, key: string): { removedBy?: string } {\n if (x.sources.has(key)) return {};\n const h = history(x, key);\n const at = h.findIndex((e) => e.change === change);\n const gone = h\n .slice(at + 1)\n .reverse()\n .find((e) => e.entry.exported.before && !e.entry.exported.after);\n return gone && gone.change !== change ? { removedBy: gone.change } : {};\n}\n\nexport function taskContext(\n current: ExportReader,\n task: TaskRef,\n exportDir: string,\n state: CoveredState = {},\n questions?: Question[],\n opts: {\n /** The folder the pinned files are written to: a pinned path is printed under it. */\n pins?: string;\n /** `<key><<change>` of what the last read of this brief showed as changed since. */\n shown?: ReadonlySet<string>;\n } = {},\n): TaskContext {\n // Texts are read as the task's change saw them; facts the export derives (the index, the operations) as they are.\n const x = pinnedReader(current, task.change);\n const at = (path: string) => (opts.pins && x.isPinned(path) ? `${opts.pins}/${path}` : path);\n /** The objects the brief names, to say which of them later changes touched. */\n const names = new Set<string>();\n const since = (key: string): { since?: string[]; entered?: boolean } => {\n names.add(key);\n const s = x.seen(key);\n return s.later.length\n ? { since: s.later.map((l) => l.change), ...(s.absent ? { entered: true } : {}) }\n : {};\n };\n const change = x.work.changes.find((c) => c.id === task.change);\n if (!change) throw new ContextError(`${task.change} is not in this export's work.json: pull the export.`);\n const work = (change.tasks ?? []).find((t) => t.track === task.track);\n if (!work)\n throw new ContextError(\n `${task.change} has no task on ${task.track}: its tracks are ${(change.tasks ?? []).map((t) => t.track).join(', ') || 'none'}.`,\n );\n const track = x.work.tracks.find((t) => t.code === task.track)!;\n const proposal = x.proposalPath(task.change);\n if (!proposal) throw new ContextError(`The export holds no archived proposal of ${task.change}.`);\n const delta = x.delta(task.change);\n const entries = new Map(delta?.objects.map((e) => [e.key, e]));\n const lost = new Map(delta?.unrecoverable?.map((u) => [u.key, u.why]));\n\n // The checklist is the dispatcher's list of the task's items when it answered (its first list stands, whatever a\n // newer alterspec derives; its weights follow the latest export), the export's own only when it couldn't be asked.\n const exported = work as { items?: string[]; weights?: Record<string, number> };\n const items = state.items?.length ? state.items.map((i) => i.item) : exported.items;\n const weights: Record<string, number> | undefined = state.items?.length\n ? Object.fromEntries(\n state.items.flatMap((i) => {\n const w = i.weight ?? exported.weights?.[i.item];\n return w === undefined ? [] : [[i.item, w] as const];\n }),\n )\n : exported.weights;\n const words = work as {\n title?: string;\n summary?: string;\n labels?: Record<string, string>;\n weight?: number;\n };\n /** An item's label: the dispatcher's, else the export's. */\n const labelOf = (item: string) => state.items?.find((i) => i.item === item)?.label ?? words.labels?.[item];\n const initiativeId = (change as { initiative?: string }).initiative;\n const initiative = initiativeId ? x.initiative(initiativeId) : undefined;\n const ctx: TaskContext = {\n task: task.id,\n ...(initiative ? { initiative: { ...initiative, path: initiativePath(initiative.id) } } : {}),\n ...(words.title ? { title: words.title } : {}),\n ...(words.summary ? { summary: words.summary } : {}),\n ...(words.weight === undefined ? {} : { weight: words.weight }),\n ...(questions ? { questions } : {}),\n ...(questions && state.questionsFull ? { questionsFull: [...state.questionsFull].sort() } : {}),\n ...(state.answers?.length ? { answers: state.answers } : {}),\n ...(items\n ? {\n checklist: {\n items: items.map((item) => {\n const covered = state.covered?.get(item);\n const weight = weights?.[item];\n return {\n item,\n what: itemWhat(x, item, entries.get(itemObject(item)), task.track),\n ...(covered ? { covered } : {}),\n ...(weight === undefined ? {} : { weight }),\n ...(labelOf(item) ? { label: labelOf(item) } : {}),\n ...(weight === 0 ? removedByOf(current, task.change, itemObject(item)) : {}),\n };\n }),\n known: state.covered !== undefined,\n ...(state.unknown ? { note: state.unknown } : {}),\n },\n }\n : {}),\n export: exportDir,\n change: {\n id: change.id,\n title: change.title,\n signed_off: change.signed_off,\n level: change.level,\n depends_on: change.depends_on,\n },\n track,\n after: work.after,\n ...(state.startFrom?.length ? { startFrom: state.startFrom } : {}),\n ...(state.siblings?.length\n ? {\n siblings: state.siblings.map((s) => {\n const alters = (\n (change.tasks ?? []).find((t) => t.track === s.track) as { alters?: string[] } | undefined\n )?.alters;\n return alters ? { ...s, alters } : s;\n }),\n }\n : {}),\n ...(state.ruled?.length ? { ruled: state.ruled } : {}),\n ...(state.ruledChanged?.length ? { ruledChanged: state.ruledChanged } : {}),\n ...compatibilityOf(x, change, work, proposal),\n proposal: {\n path: proposal,\n why: sectionText(x, x.sectionShard(proposal, 'Why')),\n what: sectionText(x, x.sectionShard(proposal, 'What changes')),\n ...dataChangeOf(sectionText(x, x.sectionShard(proposal, DATA_CHANGE_SECTION))),\n },\n ...(delta ? { delta: proposal.replace(/proposal\\.md$/, 'delta.md') } : {}),\n objects: work.objects.map((key) => objectBrief(x, key, entries.get(key), lost.get(key), at)),\n ...(opts.pins ? { pins: opts.pins } : {}),\n };\n for (const key of work.objects) names.add(key);\n\n // What bears on the work: the IDs the change wrote (its why and what, the lines it added to the task's objects) and,\n // for the backend, the criteria on the checklist. Those are carried whole; the rest the task names, by path.\n const added = work.objects\n .flatMap((key) => {\n const e = entries.get(key);\n return e ? diffLines(forDiff(key, e.before), forDiff(key, e.after)).filter((l) => l.op === '+') : [];\n })\n .map((l) => l.text);\n const written = [ctx.proposal.why ?? '', ctx.proposal.what ?? '', ...added];\n const changed = new Set(work.objects);\n /** Whether the task adds it, so its delta holds it whole. */\n const isNew = (id: string) => changed.has(id) && !entries.get(id)?.exported.before;\n /** An item of a collection, whole when it bears on the work (and isn't whole in the delta already), else by path. */\n const piece = (id: string, bears: boolean): Piece[] => {\n const file = x.fileOf(id);\n const path = file && x.itemShard(file, id);\n if (!path) return [];\n const title = titleOf(x, id);\n const text = bears && !isNew(id) ? sectionText(x, path) : undefined;\n return [\n {\n id,\n path: at(path),\n ...(title ? { title } : {}),\n ...(text ? { text } : {}),\n ...(changed.has(id) ? { changed: true } : {}),\n ...since(id),\n },\n ];\n };\n\n ctx.whereUsed = whereUsed(current, work.objects, entries, changed);\n\n const capabilities = work.objects.filter((k) => /^CAP-/.test(k) && x.fileOf(k) && x.has(x.fileOf(k)!));\n // On either track: the changed criteria on the checklist whole, since their diff shows only the lines that moved; a new one is\n // whole in its delta already. A format 1 export has no checklist, so it gets them all.\n const onList = items && new Set(items);\n ctx.acceptance = capabilities.flatMap((id): Piece[] => {\n const path = x.sectionShard(x.fileOf(id)!, 'Acceptance criteria');\n if (!path) return [];\n const chunks = (sectionText(x, path) ?? '').split(/^(?=### )/m).filter((c) => c.startsWith('### '));\n const existed = new Set([...(entries.get(id)?.before ?? '').matchAll(/^### (\\S+)/gm)].map((m) => m[1]));\n const idOf = (c: string) => c.slice(4).split(/\\s/)[0]!;\n const listed = onList ? chunks.filter((c) => onList.has(idOf(c))) : chunks;\n written.push(...listed);\n const kept = onList ? listed.filter((c) => existed.has(idOf(c))) : chunks;\n const added = listed.length - kept.length;\n const title = titleOf(x, id);\n const rest = [\n added\n ? `${added === 1 ? 'One new criterion is' : `${added} new criteria are`} whole in its delta above.`\n : '',\n chunks.length > listed.length ? `Its other criteria: \\`${at(path)}\\`.` : '',\n ]\n .filter(Boolean)\n .join(' ');\n return [\n {\n id,\n path: at(path),\n ...(title ? { title } : {}),\n ...(kept.length ? { text: kept.join('').trim() } : {}),\n ...(kept.length && rest ? { rest } : {}),\n },\n ];\n });\n if (!ctx.acceptance.length) delete ctx.acceptance;\n\n if (track.kind === 'backend') {\n const named = (kind: 'rule' | 'event') => [\n ...new Set([\n ...work.objects.filter((k) => idsIn(k, [kind]).length === 1 && idsIn(k, [kind])[0] === k),\n ...capabilities.flatMap((c) => idsIn(frontMatterOf(x.read(x.fileOf(c)!)!), [kind])),\n ]),\n ];\n const carried = (kind: 'rule' | 'event') => {\n const bearing = idsIn(written.join('\\n'), [kind]);\n return [...new Set([...named(kind), ...bearing])].flatMap((id) => piece(id, bearing.includes(id)));\n };\n ctx.rules = carried('rule');\n ctx.events = carried('event');\n const whole = (kind: 'nfr' | 'integration') => {\n const bearing = idsIn(written.join('\\n'), [kind]);\n const own = work.objects.filter((k) => idKind(k) === kind);\n return [...new Set([...own, ...bearing])].flatMap((id) => piece(id, true));\n };\n ctx.nfr = whole('nfr');\n ctx.integrations = whole('integration');\n ctx.entities = [\n ...new Set([\n ...work.objects.filter((k) => idKind(k) === 'entity'),\n ...capabilities.flatMap((c) => idsIn(frontMatterOf(x.read(x.fileOf(c)!)!), ['entity'])),\n ]),\n ].flatMap((id): Piece[] => {\n const file = x.fileOf(id);\n if (!file || !x.has(file)) return [];\n const title = titleOf(x, id);\n const note = lifecycleOf(current, id);\n return [\n {\n id,\n path: at(file),\n ...(title ? { title } : {}),\n ...(changed.has(id) ? { changed: true } : {}),\n ...(note ? { note } : {}),\n ...since(id),\n },\n ];\n });\n ctx.operations = current.has(OPERATIONS_FILE)\n ? capabilities.flatMap((id): Piece[] => {\n const path = current\n .shards(OPERATIONS_FILE)\n .find((p) => new RegExp(`/\\\\d{2}-${slug(id)}(-|\\\\.md$)`).test(p));\n return path ? [{ id, path, text: shardText(current, path) }] : [];\n })\n : [];\n } else {\n const existing = (p: string) => (x.has(p) ? at(p) : undefined);\n // The task's screens, and the screens of this channel that perform a capability the task changes (its criteria's\n // Shown is theirs to show).\n const performing = [...x.sources.keys()].filter(\n (id) =>\n /^SCR-/.test(id) &&\n x.has(contractPath(id, track.code)) &&\n idsIn(frontMatterOf(x.read(x.fileOf(id)!) ?? ''), ['capability']).some((c) =>\n capabilities.includes(c),\n ),\n );\n const screens = [\n ...new Set([...work.objects.map(screenOf).filter((s): s is string => !!s), ...performing]),\n ];\n ctx.screens = screens.map((id) => {\n for (const key of [id, `UX-${id}-${track.code}`, `file:${mockupPath(track.code, id)}`]) names.add(key);\n const file = x.fileOf(id);\n return {\n id,\n file: file && at(file),\n contract: existing(contractPath(id, track.code)),\n page: existing(mockupPath(track.code, id)),\n };\n });\n for (const path of [designSystemPath(track.code), patternsPath(track.code)]) names.add(`file:${path}`);\n ctx.design = {\n designSystem: existing(designSystemPath(track.code)),\n patterns: existing(patternsPath(track.code)),\n };\n }\n const bearing = idsIn(written.join('\\n'), ['decision']);\n const named = idsIn(work.objects.map((k) => entries.get(k)?.after ?? '').join('\\n'), ['decision']);\n ctx.decisions = [...new Set([...bearing, ...named])].flatMap((id) => piece(id, bearing.includes(id)));\n // The reach of the rules the task touches or carries whole, and of the roles it touches.\n const rules = [\n ...new Set([\n ...work.objects.filter((k) => idKind(k) === 'rule'),\n ...(ctx.rules ?? []).filter((r) => r.text).map((r) => r.id),\n ]),\n ];\n const roles = work.objects.filter((k) => idKind(k) === 'role');\n ctx.reach = [\n ...rules.map((id) => reachOf(current, id, 'rule', changed)),\n ...roles.map((id) => reachOf(current, id, 'role', changed)),\n ].filter((r): r is Reach => !!r);\n if (!ctx.reach.length) delete ctx.reach;\n if (ctx.reach?.some((r) => r.matrix?.length)) {\n const legend = matrixOf(current).legend;\n if (legend.length) ctx.matrixLegend = legend;\n }\n // The glossary terms the change's text uses, by their exact name (or its plural); a term the task changes is\n // among its objects.\n const glossary = x.fileOf('term:');\n const writtenText = written.join('\\n');\n ctx.terms = (glossary && x.has(glossary) ? x.shards(glossary) : [])\n .filter((path) => !/\\/\\d{2}-[^/]*$/.test(path))\n .flatMap((path): Piece[] => {\n const name = /^## (.+)$/m.exec(shardText(x, path) ?? '')?.[1]?.trim();\n if (!name || changed.has(`term:${name}`)) return [];\n const term = name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n if (!new RegExp(`(?<![\\\\w-])${term}(?:s|es)?(?![\\\\w-])`, 'i').test(writtenText)) return [];\n const text = sectionText(x, path);\n return [{ id: name, path: at(path), ...(text ? { text } : {}), ...since(`term:${name}`) }];\n });\n\n // What later changes did to the objects the brief names: their tasks' work, listed apart.\n const moved = [...names].flatMap((key): ChangedSince[] => {\n const s = x.seen(key);\n if (!s.later.length) return [];\n const now = currentText(current, key);\n const changes = s.later.map((l) => ({\n id: l.change,\n ...(opts.shown && !opts.shown.has(shownKey(key, l.change)) ? { fresh: true } : {}),\n }));\n // What is new since the last read: from the text before the first new change to the export's text now.\n const first = changes.findIndex((ch) => ch.fresh);\n const from =\n first < 0 || s.absent ? undefined : first === 0 ? s.text : textAfter(s.later[first - 1]!.entry);\n let diff: string | undefined;\n if (from !== undefined && now !== undefined) {\n const [a, b] = [forDiff(key, from), forDiff(key, now)];\n const d = unifiedDiff(a, b);\n if (d) diff = clippedDiff(key.startsWith('file:') ? d : withSections(d, a, b));\n }\n const title = key.includes(':') ? undefined : titleOf(current, key);\n const pinned = pinnedPath(x, key);\n // This task's own object: whether a later change removed or reworded a line this change wrote is settled here,\n // from the deltas, so the agent compares nothing.\n const mine = entries.get(key);\n let checked = false;\n let lost: ChangedSince['lost'];\n if (changed.has(key) && mine && !mine.binary && !s.absent) {\n checked = true;\n const wroteBefore = linesOf(key, mine.exported.before ? mine.before : undefined);\n const wrote = [...linesOf(key, mine.exported.after ? mine.after : undefined)].filter(\n (l) => !wroteBefore.has(l),\n );\n lost = s.later.flatMap((l) => {\n if (l.entry.binary) return [];\n const kept = linesOf(key, l.entry.exported.after ? l.entry.after : undefined);\n const gone = [...linesOf(key, l.entry.exported.before ? l.entry.before : undefined)].filter(\n (line) => wrote.includes(line) && !kept.has(line),\n );\n return gone.length ? [{ change: l.change, lines: gone }] : [];\n });\n }\n return [\n {\n key,\n ...(title ? { title } : {}),\n ...(changed.has(key) ? { own: true } : {}),\n changes,\n ...(pinned ? { pinned: at(pinned) } : {}),\n ...(diff ? { diff } : {}),\n ...(now === undefined ? { gone: true } : {}),\n ...(s.absent ? { entered: true } : {}),\n ...(checked ? { checked: true } : {}),\n ...(lost?.length ? { lost } : {}),\n },\n ];\n });\n // With the dispatcher's list (the keys the task cites that changed since), only those; objects that entered the\n // export after the change stay, since the brief shows them as they are now.\n const cited = state.changedSince;\n const kept = cited ? moved.filter((e) => e.entered || cited.has(e.key)) : moved;\n if (cited) {\n const elsewhere = moved.length - kept.length;\n if (elsewhere) ctx.sinceElsewhere = elsewhere;\n if (!kept.some((e) => !e.entered)) ctx.changedSinceNone = true;\n }\n if (kept.length) {\n ctx.changedSince = kept.sort(\n (a, b) => Number(!!b.own) - Number(!!a.own) || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0),\n );\n const touched = new Set(kept.flatMap((e) => e.changes.map((ch) => ch.id)));\n ctx.later = x.work.changes\n .filter((c) => touched.has(c.id))\n .map((c) => {\n const delta = x.proposalPath(c.id)?.replace(/proposal\\.md$/, 'delta.md');\n return {\n id: c.id,\n title: c.title,\n ...((c.tasks ?? []).some((t) => t.track === task.track) ? { task: `${c.id}/${task.track}` } : {}),\n ...(delta ? { delta } : {}),\n };\n });\n }\n return ctx;\n}\n\n/** How the client remembers that a brief showed a later change of an object. */\nexport const shownKey = (key: string, change: string) => `${key}<${change}`;\n\n/** What a brief showed as changed since, to mark what is new at its next read. */\nexport const shownOf = (c: TaskContext): string[] =>\n (c.changedSince ?? []).flatMap((e) => e.changes.map((ch) => shownKey(e.key, ch.id)));\n\n/**\n * The files holding the objects of a brief's \"Changed since\" as the task's change saw them, by export path: what\n * `context` writes to the pin folder so the paths the brief prints can be opened.\n */\nexport function pinFiles(current: ExportReader, c: TaskContext): Map<string, string> {\n const x = pinnedReader(current, c.change.id);\n const out = new Map<string, string>();\n for (const e of c.changedSince ?? []) for (const [path, text] of x.pinnedFiles(e.key)) out.set(path, text);\n return out;\n}\n\nconst textAfter = (e: DeltaEntry) => (e.exported.after ? e.after : undefined);\n\n/** A diff of at most this many lines in the brief; the rest is in the later changes' deltas. */\nconst DIFF_LINES = 40;\n/** The brief shows this many diffs of what is new; the other objects are named. */\nconst NEW_DIFFS = 12;\n/** How many lines of this task's hunks a later change removed are listed per change under \"Checked\". */\nconst LOST_LINES = 8;\nfunction clippedDiff(diff: string): string {\n const lines = diff.split('\\n');\n return lines.length <= DIFF_LINES\n ? diff\n : `${lines.slice(0, DIFF_LINES).join('\\n')}\\n… ${lines.length - DIFF_LINES} more lines: see the changes’ deltas.`;\n}\n\nconst fence = (text: string, lang = '') => {\n const ticks = '`'.repeat(Math.max(3, ...[...text.matchAll(/`+/g)].map((m) => m[0].length + 1)));\n return `${ticks}${lang}\\n${text}\\n${ticks}`;\n};\n\n/**\n * The initiative as the brief opens with it: its prose under one heading (its own title line dropped, its sections a\n * level down), and what it is for.\n */\nfunction initiativeSection(i: NonNullable<TaskContext['initiative']>): string[] {\n const prose = i.body\n .replace(/<!--[^]*?-->/g, '')\n .replace(/^\\s*# .*\\n/, '')\n .replace(/^(#{2,5}) /gm, '#$1 ')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n return [\n `## Initiative: ${i.title}`,\n '',\n `The whole this change is part of (\\`${i.path}\\`): why the work exists. It adds nothing to build beyond the checklist.`,\n '',\n ...(prose ? [prose, ''] : []),\n ];\n}\n\n/** The checklist as the brief shows it: the items, what each is, its weight and whether it is covered. */\nfunction checklistSection(c: TaskContext): string[] {\n const out: string[] = [];\n if (!c.checklist)\n out.push('This export has no checklist (work.json format 1): the task’s progress is its status only.');\n else {\n const list = c.checklist;\n // An item of weight 0 is nothing this track builds: it is read, and counts in neither total.\n const toBuild = list.items.filter((i) => i.weight !== 0);\n const readOnly = list.items.length - toBuild.length;\n const done = toBuild.filter((i) => i.covered).length;\n const weighed = list.items.some((i) => i.weight !== undefined);\n const sum = (items: ChecklistItem[]) => items.reduce((a, i) => a + (i.weight ?? 0), 0);\n const weight = weighed\n ? list.known\n ? `, ${sum(list.items.filter((i) => i.covered))} of ${sum(list.items)} weight`\n : `, ${sum(list.items)} weight`\n : '';\n out.push(\n `## Checklist (${list.known ? `${done} of ${toBuild.length} covered` : `${toBuild.length} item${toBuild.length === 1 ? '' : 's'}`}${weight}${readOnly ? `; ${readOnly} to read only` : ''})`,\n '',\n 'Name an item in `Alterspec-Covers` on the commit with which its tests pass.',\n ...(weighed\n ? [\n 'The weight (w) is how much specified behaviour an item is on this track, reasoned at the sign-off from the spec alone;',\n 'progress and the ETA count weight, not items. Start with the heavy ones.',\n ]\n : []),\n ...(readOnly\n ? [\n 'An item of weight 0 is nothing this track builds (another channel shows it, or it is a mockup file): read it,',\n 'build nothing for it and never name it in `Alterspec-Covers`. If your track does have work for it, say so with `/alterspec-spec-ask`.',\n ]\n : []),\n ...(list.note ? ['', `Covered items unknown: ${list.note}`] : []),\n '',\n ...list.items.map(\n (i) =>\n `- [${i.weight === 0 ? '-' : i.covered ? 'x' : ' '}] \\`${i.item}\\`${i.weight === undefined ? '' : i.weight === 0 ? (i.removedBy ? ` (w 0, removed by ${i.removedBy})` : ' (w 0, nothing to build on this track)') : ` (w ${i.weight})`}: ${i.label ? `**${i.label}** — ` : ''}${i.what}${i.covered ? ` (covered by ${i.covered.slice(0, 12)})` : ''}`,\n ),\n );\n }\n return out;\n}\n\n/** The questions the brief's Questions section prints whole: a ruling among them isn't printed again. */\nfunction wholeQuestions(c: TaskContext): Set<string> {\n const full = c.questionsFull ? new Set(c.questionsFull) : undefined;\n return new Set((c.questions ?? []).filter((q) => !full || full.has(q.id)).map((q) => q.id));\n}\n\n/**\n * The brief's head and checklist alone, for re-reading during the work: the task's questions and answers and its\n * items; no objects, no \"Changed since\" (so nothing is marked as shown), no paths to open.\n */\nexport function renderChecklist(c: TaskContext): string {\n const out: string[] = [\n `# ${c.task}: ${c.title ?? c.change.title}`,\n '',\n ...(c.summary ? [c.summary, ''] : []),\n ...(c.weight === undefined ? [] : [`Task weight ${c.weight} of 100.`, '']),\n ...ruledChangedLines(c.ruledChanged),\n ...shippedLines(c),\n ...(c.questions?.length\n ? questionsSection(c.questions, c.questionsFull ? new Set(c.questionsFull) : undefined)\n : []),\n ...ruledSection(c.ruled, wholeQuestions(c)),\n ...(c.answers?.length ? answersSection(c.answers) : []),\n ...checklistSection(c),\n '',\n `This task’s questions and checklist only; the full brief is \\`alterspec-client context ${c.task}\\`.`,\n ];\n return (\n out\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trimEnd() + '\\n'\n );\n}\n\n/**\n * What the brief says about the change's other tracks (decision 36) and a compatibility: a track that has shipped the\n * change (its tests of the old behaviour fail until this task is done, unless the server keeps it), one building it\n * now, what this change keeps and who ends it, what this task ends. Empty when none applies.\n */\nexport function shippedLines(c: TaskContext): string[] {\n const out: string[] = [];\n const kept = c.compatibility?.kept;\n for (const s of c.siblings ?? []) {\n if (s.status === 'done') {\n const where = [s.commit?.slice(0, 12), s.in_main_at ? 'in main' : (s.branch ?? 'main')]\n .filter(Boolean)\n .join(', ');\n // format 9 `alters` names the tracks whose behaviour the shipped task changes; absent, every track (decision 36).\n const additive = s.alters !== undefined && !s.alters.includes(c.track.code);\n out.push(\n `**${s.track} has shipped this change** (${where})` +\n (kept\n ? ': the server keeps the old behaviour this change’s Compatibility names until the other tracks’ tasks are done (below).'\n : additive\n ? `: it alters nothing ${c.track.code} already does, so no test of yours should fail because of it.`\n : ': tests that check the behaviour it removes or changes are expected to fail until this task is done; updating them is part of this task. This is not a question of task order: don’t ask about it, fix the tests with the work.'),\n '',\n );\n } else if (s.status === 'in_progress') out.push(`${s.track} is building this change now.`, '');\n }\n if (kept) {\n const ended = kept.endedBy.length\n ? `${kept.endedBy.join(', ')} ends it.`\n : 'The change that ends it is not signed off yet.';\n out.push(\n c.track.kind === 'backend'\n ? `**Compatibility**: ${kept.tracks.join(', ')} build this change too; the server keeps what the proposal’s Compatibility says until their tasks are done. ${ended}`\n : `**Compatibility**: the server keeps the old behaviour (${c.change.id}’s Compatibility) until this task is done. ${ended}`,\n '',\n kept.text,\n '',\n );\n }\n for (const e of c.compatibility?.ends ?? [])\n out.push(\n `**Ends a compatibility**: this task ends the compatibility ${e.change} kept for ${e.tracks.join(', ')}; it is available once their tasks are done. When to deploy it is the team’s call: old app versions stay in use after a task is done.`,\n '',\n );\n return out;\n}\n\n/** The brief as Markdown, for the agent. */\nexport function renderContext(c: TaskContext): string {\n const out: string[] = [\n `# ${c.task}: ${c.title ?? c.change.title}`,\n '',\n // The words the lists show for the task: what a person calls it, never what to build from.\n ...(c.summary ? [c.summary, ''] : []),\n ...(c.title ? [`Change: ${c.change.title}.`, ''] : []),\n ...(c.initiative ? initiativeSection(c.initiative) : []),\n `Track ${c.track.code} (${c.track.kind}${c.track.channels.length ? `: ${c.track.channels.join(', ')}` : ''}). ` +\n `Change ${c.change.id}, signed off ${c.change.signed_off}, level ${c.change.level}. ` +\n (c.weight === undefined ? '' : `Task weight ${c.weight} of 100. `) +\n `Paths are relative to the export, ${c.export}.`,\n ];\n const movedSince = (c.changedSince ?? []).filter((e) => !e.entered);\n if (movedSince.length) {\n const n = movedSince.length;\n const fresh = movedSince.filter((e) => e.changes.some((ch) => ch.fresh)).length;\n out.push(\n '',\n `This brief is the spec as ${c.change.id} saw it at its sign-off. ${n === 1 ? 'One object it names was' : `${n} objects it names were`} changed since by later changes` +\n `${fresh ? ` (${fresh} new since you last read this brief)` : ''}: those are the later changes’ tasks, listed under \"Changed since\" at the end, never this task’s work.` +\n (c.pins ? ` An absolute path under ${c.pins} is such an object as ${c.change.id} saw it.` : ''),\n );\n }\n if (c.after.length) out.push('', `Waits for: ${c.after.map((a) => `${a.change}/${a.track}`).join(', ')}.`);\n if (c.startFrom?.length)\n out.push(\n '',\n `Start from ${c.startFrom.map((s) => `\\`${s.branch}\\` (${s.id}${s.commit ? ` done at ${s.commit.slice(0, 12)}` : ''})`).join(', then ')}, not from the main branch: ` +\n `the predecessor's work is pushed there and not merged yet (fetch it and base your branch on \\`origin/${c.startFrom[c.startFrom.length - 1]!.branch}\\`).`,\n );\n out.push('', ...ruledChangedLines(c.ruledChanged), ...shippedLines(c));\n if (c.questions?.length)\n out.push(...questionsSection(c.questions, c.questionsFull ? new Set(c.questionsFull) : undefined));\n out.push(...ruledSection(c.ruled, wholeQuestions(c)));\n if (c.answers?.length) out.push(...answersSection(c.answers));\n out.push(...checklistSection(c));\n out.push('', `## Why (${c.proposal.path})`, '', c.proposal.why || '(none written)');\n out.push('', '## What changes', '', c.proposal.what || '(none written)');\n if (c.proposal.dataChange)\n out.push(\n '',\n `## ${DATA_CHANGE_SECTION}`,\n '',\n c.track.kind === 'backend'\n ? 'What the release does once to the records the product already holds; the backend’s `#data-change` item on the checklist.'\n : 'What the release does once to the records the product already holds; the backend’s work, here so the screens read it.',\n '',\n c.proposal.dataChange,\n );\n\n out.push('', '## The task’s objects', '');\n if (c.delta) out.push(`The whole record of the change: ${c.delta}.`, '');\n for (const o of c.objects) {\n const where = o.file\n ? `\\`${o.file}\\`${o.shards ? `, shards in \\`${o.shards}/\\`` : ''}`\n : 'not in the export now';\n const status =\n o.status && o.status.before !== o.status.after\n ? `, ${o.status.before ?? '—'} → ${o.status.after ?? '—'}`\n : '';\n out.push(`### ${o.key}`, '', `${o.change ?? 'no delta entry'}${status}; ${where}.`);\n if (o.unrecoverable) out.push('', `The delta could not recover it: ${o.unrecoverable}.`);\n if (o.since?.changes.length)\n out.push(\n '',\n `Changed since by ${o.since.changes.join(', ')}: their tasks’ work (see \"Changed since\"). Build it as ${c.change.id} left it` +\n `${o.pinned ? `: \\`${o.pinned}\\`` : ''}${o.since.differs ? '' : '; the export’s text equals that again'}.`,\n );\n else if (o.since)\n out.push(\n '',\n 'The export’s text differs from this delta’s after though no later change touched it: build to the export’s file.',\n );\n if (o.diff) out.push('', o.diff.startsWith('@@') ? fence(o.diff, 'diff') : o.diff);\n out.push('');\n }\n\n if (c.whereUsed?.length) {\n out.push(\n '## Where used',\n '',\n 'What the export shows, takes, returns or guards of the entities this task changes, per changed attribute and for the entity as a whole; a screen or capability not in the export isn’t listed.',\n '',\n );\n const list = (ps: Piece[]) =>\n ps.map((p) => `${p.id}${p.changed ? ' (this task changes it)' : ''}`).join(', ');\n for (const w of c.whereUsed) {\n if (w.attribute) {\n const parts = [\n w.screens.length ? `shown on ${list(w.screens)}` : 'no screen shows it',\n w.capabilities.length\n ? `taken or returned by ${list(w.capabilities)}`\n : 'no capability takes or returns it',\n ];\n out.push(`- ${w.entity}.${w.attribute}: ${parts.join('; ')}.`);\n } else {\n const parts = [\n w.screens.length ? `shown on ${list(w.screens)}` : 'no screen shows it',\n w.capabilities.length ? `worked with by ${list(w.capabilities)}` : 'no capability works with it',\n w.rules.length ? `rules about it: ${list(w.rules)}` : 'no rule about it',\n ];\n out.push(`- ${w.entity}: ${parts.join('; ')}.`);\n }\n }\n out.push('');\n }\n\n if (c.reach?.length) {\n out.push(\n '## Reach',\n '',\n 'Where the export enforces, holds or shows the rules and roles this task touches or names; a capability or screen not in the export isn’t listed.',\n '',\n );\n if (c.matrixLegend?.length)\n out.push(\n `Under a rule, its row of the rule matrix (\\`${RULE_MATRIX_FILE}\\`), so the matrix need not be opened. How to read it:`,\n '',\n ...c.matrixLegend,\n '',\n );\n const list = (ps: (Piece & { scope?: string })[]) =>\n ps\n .map((p) => `${p.id}${p.scope ? ` (${p.scope})` : ''}${p.changed ? ' (this task changes it)' : ''}`)\n .join(', ');\n for (const r of c.reach) {\n const name = `${r.id}${r.title ? ` ${r.title}` : ''}`;\n if (r.kind === 'rule') {\n const parts = [\n r.capabilities.length ? `enforced by ${list(r.capabilities)}` : 'no capability lists it',\n r.criteria?.length ? `covered by ${r.criteria.join(', ')}` : 'no criterion covers it',\n r.screens.length ? `on ${list(r.screens)}` : 'on no screen',\n ];\n out.push(`- ${name}: ${parts.join('; ')}.`);\n for (const line of r.matrix ?? []) out.push(` ${line}`);\n } else {\n const parts = [\n r.capabilities.length ? `may perform ${list(r.capabilities)}` : 'may perform no capability',\n r.screens.length ? `on ${list(r.screens)}` : 'on no screen',\n ];\n out.push(`- ${name}: ${parts.join('; ')}.`);\n }\n }\n out.push('');\n }\n\n const pieces = (title: string, list: Piece[] | undefined, intro?: string) => {\n if (!list?.length) return;\n out.push(`## ${title}`, '');\n if (intro) out.push(intro, '');\n const moved = (p: Piece) =>\n !p.since?.length\n ? ''\n : p.entered\n ? `signed off since, by ${p.since.join(', ')}; here as the export holds it now`\n : `changed since by ${p.since.join(', ')}; here as ${c.change.id} saw it`;\n for (const p of list.filter((p) => p.text))\n out.push(\n `### ${p.id}${p.title ? ` ${p.title}` : ''} (\\`${p.path}\\`)`,\n '',\n ...(moved(p) ? [`(${moved(p)})`, ''] : []),\n p.text!,\n ...(p.rest ? ['', p.rest] : []),\n '',\n );\n for (const p of list.filter((p) => !p.text))\n out.push(\n `- ${p.id}${p.title ? ` ${p.title}` : ''}: \\`${p.path}\\`${p.changed ? ' (this task changes it: its delta is above)' : ''}${p.note ? `; ${p.note}` : ''}${moved(p) ? ` (${moved(p)})` : ''}`,\n );\n out.push('');\n };\n pieces(\n 'Acceptance criteria',\n c.acceptance,\n c.checklist\n ? 'The changed criteria on the checklist, whole (new ones are whole in the delta above); the rest by shard.'\n : undefined,\n );\n pieces(\n 'Rules',\n c.rules,\n 'The rules the checklist’s criteria or the change’s text name, whole; the others the capabilities name, by path.',\n );\n pieces(\n 'Events',\n c.events,\n 'The events the checklist’s criteria or the change’s text name, whole; the others the capabilities name, by path.',\n );\n pieces(\n 'Entities',\n c.entities,\n 'The entities the task’s capabilities work with, each with its lifecycle; open one for its attributes.',\n );\n pieces(\n 'Quality requirements',\n c.nfr,\n 'The quality requirements the task touches or the change’s text names, whole (one the task adds is whole in its delta above).',\n );\n pieces(\n 'Integrations',\n c.integrations,\n 'The integrations the task touches or the change’s text names, whole (one the task adds is whole in its delta above).',\n );\n pieces('Operations for other systems', c.operations);\n pieces(\n 'Decisions',\n c.decisions,\n 'The decisions the change’s text names, whole; the others its objects name, by path.',\n );\n pieces('Terms', c.terms, 'The glossary terms the change’s text uses.');\n\n if (c.screens?.length) {\n out.push('## Screens', '');\n for (const s of c.screens) {\n out.push(`- **${s.id}**: \\`${s.file ?? 'not in the export'}\\``);\n if (s.contract) out.push(` - experience contract: \\`${s.contract}\\``);\n if (s.page) out.push(` - mockup page: \\`${s.page}\\``);\n }\n out.push('');\n if (c.design?.designSystem || c.design?.patterns)\n out.push(\n '## The channel’s design',\n '',\n ...[c.design.designSystem, c.design.patterns].filter(Boolean).map((p) => `- \\`${p}\\``),\n '',\n );\n }\n if (c.changedSinceNone && !movedSince.length)\n out.push(\n '## Changed since (other tasks’ work)',\n '',\n `No part of this task changed (the dispatcher’s list).${c.sinceElsewhere ? ` ${c.sinceElsewhere === 1 ? 'One other object' : `${c.sinceElsewhere} other objects`} the brief names ${c.sinceElsewhere === 1 ? 'was' : 'were'}, in other tasks’ work.` : ''}`,\n '',\n );\n if (c.changedSince?.length) {\n if (!(c.changedSinceNone && !movedSince.length)) out.push('## Changed since (other tasks’ work)', '');\n if (c.sinceElsewhere && movedSince.length)\n out.push(\n `Only the objects this task cites (the dispatcher’s list); ${c.sinceElsewhere === 1 ? 'one other object' : `${c.sinceElsewhere} other objects`} the brief names ${c.sinceElsewhere === 1 ? 'was' : 'were'} changed in other tasks’ work.`,\n '',\n );\n const names = (e: ChangedSince) =>\n `${e.key}${e.title ? ` ${e.title}` : ''}${e.own ? ' (this task changes it)' : ''}`;\n if (movedSince.length) {\n out.push(\n `Later changes touched what this brief names. Build this task to the text above: what a later change added is built in its own task.` +\n (movedSince.some((e) => e.own)\n ? ' For the objects this task changes, whether a later change removed or reworded a line of this task’s hunks is checked here, under \"Checked\": compare nothing yourself.'\n : ''),\n '',\n ...(c.later ?? []).map(\n (l) =>\n `- ${l.id}${l.title ? ` \"${l.title}\"` : ''}: ${l.task ? `its task ${l.task}` : 'no task on this track'}${l.delta ? `; \\`${l.delta}\\`` : ''}`,\n ),\n '',\n 'What each touched, in the order it did:',\n '',\n ...movedSince.map(\n (e) =>\n `- ${names(e)}: ${e.changes.map((ch) => `${ch.fresh ? '**new** ' : ''}${ch.id}`).join(', ')}${e.gone ? '; the export no longer holds it' : ''}`,\n ),\n '',\n );\n const own = movedSince.filter((e) => e.own);\n if (own.length)\n out.push(\n 'Checked: this task’s own lines against the later changes’ deltas.',\n '',\n ...own.map((e) => {\n if (!e.checked)\n return `- ${names(e)}: not checked (a binary file, or the export did not hold it then): compare the pinned file with the export’s.`;\n if (!e.lost?.length)\n return `- ${names(e)}: no line of this task’s hunks was removed or reworded by ${e.changes.map((ch) => ch.id).join(', ')}. Build it as the brief says.`;\n return [\n `- ${names(e)}: build these lines as the later change says, not as the brief has them, and say so in the commit’s body:`,\n ...e.lost.flatMap((l) => [\n ` - ${l.change} removed or reworded ${l.lines.length === 1 ? 'one line' : `${l.lines.length} lines`}:`,\n ...l.lines.slice(0, LOST_LINES).map((line) => ` - \\`${line.replace(/`/g, \"'\")}\\``),\n ...(l.lines.length > LOST_LINES\n ? [` - and ${l.lines.length - LOST_LINES} more (see its delta)`]\n : []),\n ]),\n ].join('\\n');\n }),\n '',\n );\n const fresh = movedSince.filter((e) => e.diff);\n if (fresh.length) {\n out.push(\n 'New since you last read this brief, from what it showed then to the export’s text now:',\n '',\n );\n for (const e of fresh.slice(0, NEW_DIFFS))\n out.push(`### ${names(e)}`, '', fence(e.diff!, 'diff'), '');\n if (fresh.length > NEW_DIFFS)\n out.push(\n `And ${fresh.length - NEW_DIFFS} more: ${fresh\n .slice(NEW_DIFFS)\n .map((e) => e.key)\n .join(', ')} (see the changes’ deltas).`,\n '',\n );\n }\n }\n const entered = c.changedSince.filter((e) => e.entered);\n if (entered.length)\n out.push(\n `Signed off after ${c.change.id}, so the export never held them as it saw them; the brief shows them as the export holds them now:`,\n '',\n ...entered.map((e) => {\n const [first, ...rest] = e.changes;\n const task = c.later?.find((l) => l.id === first!.id)?.task;\n return `- ${names(e)}: in the export since ${first!.id}${task ? ` (its task ${task})` : ''}${rest.length ? `, changed after by ${rest.map((ch) => ch.id).join(', ')}` : ''}`;\n }),\n '',\n );\n }\n return (\n out\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trimEnd() + '\\n'\n );\n}\n\n/**\n * The brief's size by section, for measuring it: characters and an estimate of tokens (a quarter of the characters,\n * the usual rule of thumb for English; a tokenizer counts a little differently).\n */\nexport function contextStats(markdown: string): string {\n const sections = markdown.split(/^(?=## )/m).map((part, i) => ({\n name: i === 0 ? '(heading)' : part.split('\\n')[0]!.slice(3),\n chars: part.length,\n }));\n const width = Math.max(...sections.map((x) => x.name.length), 'Total'.length);\n const row = (name: string, chars: number) =>\n `${name.padEnd(width)} ${String(Math.ceil(chars / 4)).padStart(7)} ${String(chars).padStart(8)}`;\n return (\n [\n `${'Section'.padEnd(width)} ${'~tokens'.padStart(7)} ${'chars'.padStart(8)}`,\n ...sections.map((x) => row(x.name, x.chars)),\n row('Total', markdown.length),\n ].join('\\n') + '\\n'\n );\n}\n","import { execFileSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { type TaskRef, folderOf } from './task.js';\n\n/**\n * What `context` keeps on disk for a brief (client 0.19.0): the files of the objects later changes touched, as the\n * task's change saw them, under `.alterspec-client/pins/<chg>-<track>/` in the folder that holds the configuration\n * (a few small files at their export paths, rewritten on every run, never to be committed), and, in the\n * repository's git folder next to the progress state, which later changes the brief already showed.\n */\n\nexport const PINS_DIR = '.alterspec-client/pins';\n\nexport const pinsDir = (root: string, task: TaskRef) => join(root, PINS_DIR, folderOf(task));\n\n/** Replace a task's pinned files; an empty set removes its folder. */\nexport function writePins(dir: string, files: ReadonlyMap<string, string>): void {\n rmSync(dir, { recursive: true, force: true });\n if (!files.size) return;\n const root = dirname(dir);\n mkdirSync(root, { recursive: true });\n // The folder ignores itself, so nothing in it is committed whatever the repository's own rules are.\n if (!existsSync(join(root, '.gitignore'))) writeFileSync(join(root, '.gitignore'), '*\\n');\n for (const [path, text] of files) {\n const to = join(dir, path);\n mkdirSync(dirname(to), { recursive: true });\n writeFileSync(to, text);\n }\n}\n\nfunction shownPath(repo: string, task: TaskRef): string | undefined {\n try {\n const common = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], {\n cwd: repo,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim();\n return common ? join(common, 'alterspec-client', `seen-${folderOf(task)}.json`) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** What the brief's earlier reads showed as changed since; undefined before its first read, or outside a repository. */\nexport function readShown(repo: string, task: TaskRef): Set<string> | undefined {\n const path = shownPath(repo, task);\n if (!path || !existsSync(path)) return undefined;\n try {\n const data = JSON.parse(readFileSync(path, 'utf8')) as { shown?: unknown };\n return new Set(\n Array.isArray(data.shown) ? data.shown.filter((s): s is string => typeof s === 'string') : [],\n );\n } catch {\n return undefined;\n }\n}\n\n/** Remember what this read showed, with what earlier reads did; never fails the command. */\nexport function writeShown(repo: string, task: TaskRef, shown: readonly string[], now = new Date()): void {\n const path = shownPath(repo, task);\n if (!path) return;\n try {\n const all = [...new Set([...(readShown(repo, task) ?? []), ...shown])].sort();\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify({ shown: all, at: now.toISOString() }) + '\\n');\n } catch {\n // a read-only repository: the next read marks the same changes as new again\n }\n}\n","/**\n * A task is one change on one track, written `CHG-012/BE` (spec 2), or one bug on one track, `BUG-3/BE` (spec 8.5).\n * Its branch is `task/chg-012-be` and its commits carry the trailer `Alterspec-Task: CHG-012/BE` (spec 12.2); only\n * the client spells either.\n */\n\nexport interface TaskRef {\n id: string;\n /** The change (`CHG-012`) or the bug (`BUG-3`) the task is of. */\n change: string;\n track: string;\n kind: 'change' | 'bug';\n}\n\nexport const TRAILER = 'Alterspec-Task';\n\nexport class TaskError extends Error {}\n\nexport function parseTask(text: string): TaskRef {\n const m = /^(CHG-\\d{3}|BUG-[1-9]\\d*)\\/([A-Z]{2,5})$/.exec(text.trim().toUpperCase());\n if (!m)\n throw new TaskError(\n `\"${text}\" is not a task: write it as CHG-012/BE (the change, a slash, the track), or BUG-3/BE for a bug's.`,\n );\n return {\n id: `${m[1]}/${m[2]}`,\n change: m[1]!,\n track: m[2]!,\n kind: m[1]!.startsWith('BUG-') ? 'bug' : 'change',\n };\n}\n\nexport const branchOf = (t: TaskRef) => `task/${t.change.toLowerCase()}-${t.track.toLowerCase()}`;\nexport const folderOf = (t: TaskRef) => `${t.change.toLowerCase()}-${t.track.toLowerCase()}`;\nexport const trailerOf = (t: TaskRef) => `${TRAILER}: ${t.id}`;\n\n/** The trailer naming the items a commit covers once their tests pass (spec 8.1): `Alterspec-Covers: A, B`. */\nexport const COVERS = 'Alterspec-Covers';\n\n/** The task whose branch this is (`task/chg-012-be` → `CHG-012/BE`), or undefined for any other branch. */\nexport function taskOfBranch(branch: string | undefined): TaskRef | undefined {\n const m = /^task\\/(chg-\\d{3}|bug-[1-9]\\d*)-([a-z]{2,5})$/.exec(branch?.trim() ?? '');\n return m ? parseTask(`${m[1]}/${m[2]}`) : undefined;\n}\n","import { execFileSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { type TaskRef, TRAILER, branchOf } from './task.js';\n\n/**\n * The git reading of the client (spec 12.2), with git only, whatever hosts the repositories: the export clone's head\n * and the commit to send the dispatcher, and the commit that brought a task into the track's main branch. The client\n * makes no branch, worktree or commit in the developer's repository (0.14.0): where and how they work is theirs.\n */\n\nexport class GitError extends Error {}\n\nfunction git(cwd: string, args: string[]): string {\n try {\n return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();\n } catch (e) {\n const stderr = String((e as { stderr?: unknown }).stderr ?? '').trim();\n throw new GitError(`git ${args.join(' ')} failed in ${cwd}${stderr ? `: ${stderr}` : ''}`);\n }\n}\n\nconst tryGit = (cwd: string, args: string[]): string | undefined => {\n try {\n return git(cwd, args);\n } catch {\n return undefined;\n }\n};\n\nconst isAncestor = (cwd: string, a: string, b: string) =>\n tryGit(cwd, ['merge-base', '--is-ancestor', a, b]) !== undefined;\n\nexport interface ExportHead {\n /** The clone's `HEAD` after the pull. */\n head: string;\n /** Whether `git pull --ff-only` succeeded. */\n pulled: boolean;\n /** The dispatcher's `latest_export`, when given. */\n latest?: string;\n /** The commit to send as `next_task`'s `export`. */\n send: string;\n /** Commits `HEAD` is behind `latest_export` (the pull failed); null when the clone doesn't have it to count. */\n behind: number | null;\n}\n\n/**\n * Pull the export clone and say which commit to send: `HEAD` when the dispatcher knows it or knows more,\n * `latest_export` when `HEAD` is ahead of it (pulled before the ingest finished). Refuses when neither is an\n * ancestor of the other: the export's history was rewritten.\n */\nexport function exportHead(dir: string, latest?: string): ExportHead {\n if (!existsSync(join(dir, '.git')) && tryGit(dir, ['rev-parse', '--git-dir']) === undefined)\n throw new GitError(`${dir} is not a clone of the export repository.`);\n const pulled = tryGit(dir, ['pull', '--ff-only', '--quiet']) !== undefined;\n const head = git(dir, ['rev-parse', 'HEAD']);\n if (!latest) return { head, pulled, send: head, behind: 0 };\n const known = tryGit(dir, ['rev-parse', '--verify', '--quiet', `${latest}^{commit}`]);\n if (!known) {\n if (!pulled) return { head, pulled, latest, send: head, behind: null };\n throw rewritten(latest);\n }\n if (known === head) return { head, pulled, latest, send: head, behind: 0 };\n if (isAncestor(dir, known, head)) return { head, pulled, latest, send: known, behind: 0 };\n if (isAncestor(dir, head, known))\n return {\n head,\n pulled,\n latest,\n send: head,\n behind: Number(git(dir, ['rev-list', '--count', `${head}..${known}`])),\n };\n throw rewritten(latest);\n}\n\nconst rewritten = (latest: string) =>\n new GitError(\n `The export's history was rewritten: the dispatcher's latest export ${latest.slice(0, 12)} and your clone don't follow each other. Stop and tell an admin.`,\n );\n\n/** The track's main branch: the configured one, else the remote's `HEAD`, else `main`. */\nexport function mainBranch(repo: string, configured?: string): string {\n if (configured) return configured;\n const head = tryGit(repo, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD']);\n return head?.replace(/^origin\\//, '') || 'main';\n}\n\nconst escape = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\/]/g, '\\\\$&');\n\nexport interface Merged {\n /** The commit to report `done` with. */\n commit: string;\n /** The pushed task branch the commit is the head of; absent when the commit is on the track's main branch. */\n branch?: string;\n}\n\n/**\n * What to report `done` with: the head of the pushed task branch `origin/task/<chg>-<track>` while it isn't in the\n * main branch yet (with the branch), else the commit on `origin/<main>` that brought the task in (no branch), else\n * the pushed head again (merged some other way). Undefined while the branch isn't pushed and nothing is merged.\n */\nexport function mergedCommit(repo: string, task: TaskRef, main: string): Merged | undefined {\n const branch = branchOf(task);\n tryGit(repo, ['fetch', '--quiet', 'origin', main]);\n // Fetched apart: one fetch of both would bring neither while the branch isn't pushed.\n tryGit(repo, ['fetch', '--quiet', 'origin', branch]);\n const target = `origin/${main}`;\n if (!tryGit(repo, ['rev-parse', '--verify', '--quiet', target]))\n throw new GitError(`There is no ${target} here: is \"${main}\" the track's main branch?`);\n const pushed = tryGit(repo, ['rev-parse', '--verify', '--quiet', `origin/${branch}^{commit}`]);\n if (pushed && !isAncestor(repo, pushed, target)) return { commit: pushed, branch };\n const merged = mergedInto(repo, task, target);\n if (merged) return { commit: merged };\n return pushed ? { commit: pushed, branch } : undefined;\n}\n\n/**\n * The commit on `origin/<main>` that brought the task in: on the branch's first-parent history, the newest commit\n * carrying the trailer `Alterspec-Task: <task>` (a squash, rebase or direct commit) or the merge of the branch\n * `task/<chg>-<track>` (GitHub's \"Merge pull request #1 from owner/task/…\", Bitbucket's \"Merged in task/…\", git's\n * \"Merge branch 'task/…'\"); else the first-parent commit that brought in a commit carrying the trailer. Undefined\n * while the work isn't on the main branch.\n */\nfunction mergedInto(repo: string, task: TaskRef, target: string): string | undefined {\n const trailer = new RegExp(`^${TRAILER}:\\\\s*${escape(task.id)}\\\\s*$`, 'mi');\n const branch = new RegExp(`(^|[\\\\s'\"/:])${escape(branchOf(task))}($|[\\\\s'\".,)])`, 'm');\n const log = git(repo, ['log', '--first-parent', '--format=%H%x1f%P%x1f%B%x1e', target]);\n for (const record of log.split('\\x1e')) {\n const [sha, parents, body] = record.trim().split('\\x1f');\n if (!sha || body === undefined) continue;\n if (trailer.test(body)) return sha;\n if (parents!.trim().includes(' ') && branch.test(body)) return sha;\n }\n const carrying = git(repo, ['log', '--format=%H', '-F', `--grep=${TRAILER}: ${task.id}`, target])\n .split('\\n')\n .filter(Boolean)\n .find((sha) => trailer.test(git(repo, ['show', '-s', '--format=%B', sha])));\n if (!carrying) return undefined;\n return git(repo, [\n 'rev-list',\n '--first-parent',\n '--ancestry-path',\n '--reverse',\n `${carrying}..${target}`,\n ]).split('\\n')[0];\n}\n","import { spawnSync } from 'node:child_process';\nimport {\n existsSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n realpathSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { type InstallResult, install } from '../../src/install/installer.js';\nimport type { PlannedFile } from '../../src/install/manifest.js';\nimport {\n CONFIG_FILE,\n type ClientConfig,\n ClientConfigSchema,\n ConfigError,\n isProduct,\n readConfigAt,\n writeConfig,\n} from './config.js';\nimport type { Role } from './role.js';\n\n/**\n * `init` (spec 12.1): the configuration, the `dispatcher` server in `.mcp.json` and its approval in the git-ignored\n * `.claude/settings.local.json`, the progress hook in `.claude/settings.json` and the skills and the answerer agent\n * with their prompts,\n * installed through alterspec's own installer (manifest, wrapper policy, removal of what an older version installed).\n *\n * `init --product` (spec 8.6, 12.4), in the spec project: the configuration with `dispatcher` and `key` only, the\n * server in `.mcp.json` and its approval, and nothing of the developer's: no hook, no skill, no prompt, no manifest.\n */\n\n/** The shipped skills and prompts, one level above both src/ (tests) and dist/ (built CLI). */\nexport const ASSETS_DIR = fileURLToPath(new URL('../assets', import.meta.url));\nexport const CLIENT_DIR = '.alterspec-client';\nexport const PROMPTS_DIR = `${CLIENT_DIR}/prompts`;\nexport const MANIFEST_PATH = `${CLIENT_DIR}/manifest.json`;\nexport const MCP_JSON = '.mcp.json';\n/** The server Claude Code starts: tools appear as `mcp__dispatcher__<tool>`. */\nexport const MCP_SERVER = 'dispatcher';\nexport const PACKAGE = '@alterset/alterspec-client';\n/** The invocation as the shipped skills and prompts spell it; `init` puts the project's npx flags into it. */\nexport const INVOCATION = `npx ${PACKAGE}`;\nexport const invocation = (npxArgs: string[] = []) => ['npx', ...npxArgs, PACKAGE].join(' ');\nexport const mcpEntry = (npxArgs: string[] = []) => ({ command: 'npx', args: [...npxArgs, PACKAGE, 'mcp'] });\nexport const MCP_ENTRY = mcpEntry();\n\nfunction walk(dir: string): string[] {\n return readdirSync(dir)\n .sort()\n .flatMap((n) => (statSync(join(dir, n)).isDirectory() ? walk(join(dir, n)) : [join(dir, n)]));\n}\n\nconst assetFiles = (sub: string) =>\n walk(join(ASSETS_DIR, sub)).map((f) => ({\n rel: relative(join(ASSETS_DIR, sub), f).split('\\\\').join('/'),\n content: readFileSync(f, 'utf8'),\n }));\n\n/**\n * What `init` installs. With npx flags of the project's (`npx.args` in its configuration) every invocation in the\n * skills and prompts carries them: a skill's `allowed-tools` pattern is matched as written, so the plain one would\n * not allow the command the project has to run. The manifest hashes this content, so it needs nothing more.\n */\nexport function buildClientPlan(version: string, npxArgs: string[] = []): PlannedFile[] {\n const plan = clientPlan(version);\n if (!npxArgs.length) return plan;\n return plan.map((f) => ({ ...f, content: f.content.split(INVOCATION).join(invocation(npxArgs)) }));\n}\n\nfunction clientPlan(version: string): PlannedFile[] {\n return [\n ...assetFiles('skills').map((f) => ({\n path: `.claude/skills/${f.rel}`,\n content: f.content,\n policy: 'wrapper' as const,\n })),\n ...assetFiles('agents').map((f) => ({\n path: `.claude/agents/${f.rel}`,\n content: f.content,\n policy: 'wrapper' as const,\n })),\n ...assetFiles('prompts').map((f) => ({\n path: `${PROMPTS_DIR}/${f.rel}`,\n content: f.content,\n policy: 'framework' as const,\n })),\n { path: `${CLIENT_DIR}/version`, content: `${version}\\n`, policy: 'framework' },\n ];\n}\n\nexport type Outcome = 'created' | 'updated' | 'unchanged';\n\n/** The `dispatcher` entry in `.mcp.json`, every other server kept. */\nexport function writeMcpJson(root: string, npxArgs: string[] = []): Outcome {\n const path = join(root, MCP_JSON);\n let data: { mcpServers?: Record<string, unknown> } & Record<string, unknown> = {};\n const before = existsSync(path) ? readFileSync(path, 'utf8') : undefined;\n if (before !== undefined)\n try {\n data = JSON.parse(before) as typeof data;\n } catch {\n throw new ConfigError(`${path} is not valid JSON: fix it, then run init again.`);\n }\n data.mcpServers = { ...(data.mcpServers ?? {}), [MCP_SERVER]: mcpEntry(npxArgs) };\n const after = JSON.stringify(data, null, 2) + '\\n';\n if (after === before) return 'unchanged';\n writeFileSync(path, after);\n return before === undefined ? 'created' : 'updated';\n}\n\nexport const CLAUDE_SETTINGS = '.claude/settings.json';\n/** The hook that reports progress after a commit (spec 12.1); found again by its command. */\nexport const hookEntry = (npxArgs: string[] = []) => ({\n type: 'command',\n if: 'Bash(git commit *)',\n command: `${invocation(npxArgs)} progress --hook`,\n timeout: 60,\n async: true,\n});\nexport const HOOK_ENTRY = hookEntry();\nexport const HOOK_COMMAND = HOOK_ENTRY.command;\n\ntype HookGroup = { matcher?: string; hooks?: Record<string, unknown>[] } & Record<string, unknown>;\nconst isOurs = (h: Record<string, unknown>) =>\n typeof h.command === 'string' && h.command.includes(`${PACKAGE} progress`);\n\n/**\n * The client's hook in `.claude/settings.json`: after Claude Code runs `git commit`, `progress --hook` in the\n * background. Merged: its own entry is replaced where it is, else added as a group of its own; nothing else changes.\n */\nexport function writeClaudeSettings(root: string, npxArgs: string[] = []): Outcome {\n const entry = hookEntry(npxArgs);\n const path = join(root, CLAUDE_SETTINGS);\n const before = existsSync(path) ? readFileSync(path, 'utf8') : undefined;\n let data: { hooks?: Record<string, unknown> } & Record<string, unknown> = {};\n if (before !== undefined)\n try {\n data = JSON.parse(before) as typeof data;\n } catch {\n throw new ConfigError(`${path} is not valid JSON: fix it, then run init again.`);\n }\n const hooks = (data.hooks ??= {});\n const groups = (hooks.PostToolUse ??= []) as HookGroup[];\n let found = false;\n for (const group of groups)\n group.hooks = group.hooks?.flatMap((h) => {\n if (!isOurs(h)) return [h];\n if (found) return [];\n found = true;\n return [entry];\n });\n if (!found) groups.push({ matcher: 'Bash', hooks: [entry] });\n const after = JSON.stringify(data, null, 2) + '\\n';\n if (before !== undefined && JSON.stringify(JSON.parse(before)) === JSON.stringify(data)) return 'unchanged';\n mkdirSync(join(root, '.claude'), { recursive: true });\n writeFileSync(path, after);\n return before === undefined ? 'created' : 'updated';\n}\n\nexport const CLAUDE_LOCAL_SETTINGS = '.claude/settings.local.json';\n\n/**\n * The approval of the `dispatcher` server in `.claude/settings.local.json`: Claude Code loads a server of a project's\n * `.mcp.json` only once approved, and honours an approval there only while git doesn't track the file. Merged: the\n * name is added to `enabledMcpjsonServers`, nothing else changes.\n */\nexport function writeLocalSettings(root: string): Outcome {\n const path = join(root, CLAUDE_LOCAL_SETTINGS);\n const before = existsSync(path) ? readFileSync(path, 'utf8') : undefined;\n let data: { enabledMcpjsonServers?: unknown } & Record<string, unknown> = {};\n if (before !== undefined)\n try {\n data = JSON.parse(before) as typeof data;\n } catch {\n throw new ConfigError(`${path} is not valid JSON: fix it, then run init again.`);\n }\n const enabled = Array.isArray(data.enabledMcpjsonServers) ? (data.enabledMcpjsonServers as unknown[]) : [];\n if (before !== undefined && enabled.includes(MCP_SERVER)) return 'unchanged';\n data.enabledMcpjsonServers = [...enabled, MCP_SERVER];\n mkdirSync(join(root, '.claude'), { recursive: true });\n writeFileSync(path, JSON.stringify(data, null, 2) + '\\n');\n return before === undefined ? 'created' : 'updated';\n}\n\n/**\n * The approval in the checkout a command runs in, when that is not the one holding the configuration: a task\n * worktree the developer made has what git tracks (`.mcp.json` declares the server) but not the git-ignored\n * approval, so Claude Code there would not load the dispatcher. Written only where `.mcp.json` exists, and never\n * through a `.claude` link that points nowhere; `unchanged` everywhere else, so the main checkout is never touched\n * here (0.14.0: the client makes no worktree, it only makes the ones the developer makes work).\n */\nexport function approveHere(configRoot: string, cwd = process.cwd()): { root: string; outcome: Outcome } {\n const top = spawnSync('git', ['rev-parse', '--show-toplevel'], {\n cwd,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).stdout?.trim();\n const same = (a: string, b: string) => {\n try {\n return realpathSync(a) === realpathSync(b);\n } catch {\n return a === b;\n }\n };\n if (!top || same(top, configRoot)) return { root: configRoot, outcome: 'unchanged' };\n if (!existsSync(join(top, MCP_JSON))) return { root: top, outcome: 'unchanged' };\n const claude = join(top, '.claude');\n try {\n if (lstatSync(claude).isSymbolicLink() && !existsSync(claude)) return { root: top, outcome: 'unchanged' };\n } catch {\n // no .claude yet: writeLocalSettings makes it\n }\n return { root: top, outcome: writeLocalSettings(top) };\n}\n\n/**\n * Whether git keeps `.claude/settings.local.json` out: `ignored` already, `added` to `.gitignore` now, `tracked`\n * (committed, so Claude Code ignores its approval), or `unknown` (no git repository, or `.claude` is a symlink git\n * can't look through).\n */\nexport type IgnoreOutcome = 'ignored' | 'added' | 'tracked' | 'unknown';\n\nexport function ignoreLocalSettings(root: string): IgnoreOutcome {\n const git = (...args: string[]) =>\n spawnSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).status;\n if (git('ls-files', '--error-unmatch', CLAUDE_LOCAL_SETTINGS) === 0) return 'tracked';\n const status = git('check-ignore', '-q', CLAUDE_LOCAL_SETTINGS);\n if (status === 0) return 'ignored';\n if (status !== 1) return 'unknown';\n const path = join(root, '.gitignore');\n const before = existsSync(path) ? readFileSync(path, 'utf8') : '';\n writeFileSync(path, `${before}${before && !before.endsWith('\\n') ? '\\n' : ''}${CLAUDE_LOCAL_SETTINGS}\\n`);\n return 'added';\n}\n\nexport interface InitOptions extends Partial<ClientConfig> {\n force?: boolean;\n /** The product side's set-up (spec 8.6): a dispatcher and a key, nothing of the developer's. */\n product?: boolean;\n}\n\nexport interface InitResult {\n /** What the repository is set up as; a product configuration is one without `export`. */\n role: Role;\n config: Outcome;\n mcp: Outcome;\n /** `none` for the product side, which gets no hook. */\n hook: Outcome | 'none';\n approval: Outcome;\n ignore: IgnoreOutcome;\n files: InstallResult;\n}\n\nconst NO_FILES: InstallResult = {\n created: [],\n updated: [],\n unchanged: [],\n kept: [],\n outdated: [],\n conflicts: [],\n removed: [],\n};\n\n/** The configuration as the file holds it: no empty `tracks` on the product side, no `npx` without flags. */\nfunction written(config: ClientConfig): ClientConfig {\n const out: ClientConfig = { ...config };\n if (!out.npx?.args.length) delete out.npx;\n if (isProduct(out) && !out.tracks.length) delete (out as Partial<ClientConfig>).tracks;\n return out;\n}\n\n/** Write what `init` writes; running it again with the same options changes nothing. */\nexport function initClient(root: string, opts: InitOptions, version: string): InitResult {\n const { force, product: asked, ...given } = opts;\n const existing = readConfigAt(root);\n const defined = Object.fromEntries(Object.entries(given).filter(([, v]) => v !== undefined));\n const developerFlags = given.export !== undefined || (given.tracks?.length ?? 0) > 0;\n // One key, one role (spec decision 29): a repository is set up for a developer or for the product side, and\n // `init` never turns one into the other in passing.\n if (asked && developerFlags)\n throw new ConfigError(\n 'init --product takes no --export and no --track: the product side has no export and builds no track.',\n );\n if (asked && existing && !isProduct(existing))\n throw new ConfigError(\n `This repository is set up for a developer (${CONFIG_FILE} has an export): remove that configuration first if it is to be the product side's.`,\n );\n if (!asked && existing && isProduct(existing) && developerFlags)\n throw new ConfigError(\n `This repository is set up for the product side (${CONFIG_FILE} has no export): remove that configuration first if a developer is to use it.`,\n );\n const product = asked || (existing !== undefined && isProduct(existing));\n const parsed = ClientConfigSchema.safeParse({ ...existing, ...defined });\n if (!parsed.success) {\n const missing = parsed.error.issues.map((i) => i.path.join('.')).filter(Boolean);\n throw new ConfigError(\n existing\n ? `The configuration would not be valid: ${parsed.error.issues.map((i) => `${i.path.join('.')} ${i.message}`).join('; ')}.`\n : product\n ? `init --product needs --dispatcher <url>${missing.length ? ` (missing or wrong: ${missing.join(', ')})` : ''}.`\n : `init needs --dispatcher <url> and --export <path to your clone of the export>${missing.length ? ` (missing or wrong: ${missing.join(', ')})` : ''}.`,\n );\n }\n if (!product && parsed.data.export === undefined)\n throw new ConfigError(\n 'init needs --export <path to your clone of the export> for a developer’s repository; the product side runs `init --product` instead.',\n );\n const next = written(parsed.data);\n const npxArgs = next.npx?.args ?? [];\n const before = existing && JSON.stringify(written(existing));\n const config: Outcome = !existing ? 'created' : before === JSON.stringify(next) ? 'unchanged' : 'updated';\n if (config !== 'unchanged') writeConfig(root, next);\n const mcp = writeMcpJson(root, npxArgs);\n const ignore = ignoreLocalSettings(root);\n const approval = writeLocalSettings(root);\n if (product) return { role: 'product', config, mcp, hook: 'none', approval, ignore, files: NO_FILES };\n const hook = writeClaudeSettings(root, npxArgs);\n const files = install(root, buildClientPlan(version, npxArgs), {\n mode: 'update',\n force,\n version,\n manifestPath: MANIFEST_PATH,\n emptiedFolder: /\\.claude\\/skills\\/alterspec-[^/]+$/,\n });\n return { role: 'developer', config, mcp, hook, approval, ignore, files };\n}\n","import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { sha256 } from './hash.js';\nimport type { PlannedFile } from './manifest.js';\n\nexport const MANIFEST_PATH = '.alterspec/manifest.json';\n\nexport interface Manifest {\n version: string;\n /** Hash of the content alterspec last wrote, per framework/wrapper file. */\n files: Record<string, string>;\n}\n\nexport interface InstallOptions {\n mode: 'init' | 'update';\n /** Overwrite wrappers the user modified. */\n force?: boolean;\n version: string;\n /** Where the manifest lives; alterspec's by default, the client keeps its own. */\n manifestPath?: string;\n /** A folder emptied by a removal that is removed too (a skill folder of a wrapper no longer shipped). */\n emptiedFolder?: RegExp;\n}\n\nexport interface InstallResult {\n created: string[];\n updated: string[];\n unchanged: string[];\n /** User-owned files that already existed. */\n kept: string[];\n /** Framework files that differ from this version (init only fills gaps; `update` refreshes them). */\n outdated: string[];\n /** Wrappers the user modified; skipped unless --force. */\n conflicts: string[];\n /** Framework files from an older version that are no longer shipped. */\n removed: string[];\n}\n\nexport function readManifest(root: string, path = MANIFEST_PATH): Manifest | undefined {\n const p = join(root, path);\n if (!existsSync(p)) return undefined;\n try {\n return JSON.parse(readFileSync(p, 'utf8')) as Manifest;\n } catch {\n return undefined;\n }\n}\n\nfunction write(root: string, path: string, content: string) {\n const full = join(root, path);\n mkdirSync(dirname(full), { recursive: true });\n writeFileSync(full, content);\n}\n\n/** Apply an install plan to a project. Never touches user-owned files that exist. */\nexport function install(root: string, plan: PlannedFile[], opts: InstallOptions): InstallResult {\n const result: InstallResult = {\n created: [],\n updated: [],\n unchanged: [],\n kept: [],\n outdated: [],\n conflicts: [],\n removed: [],\n };\n const manifestPath = opts.manifestPath ?? MANIFEST_PATH;\n const emptiedFolder = opts.emptiedFolder ?? /\\.claude\\/skills\\/[^/]+$/;\n const previous = readManifest(root, manifestPath);\n const next: Manifest = { version: opts.version, files: {} };\n\n for (const file of plan) {\n const full = join(root, file.path);\n const newHash = sha256(file.content);\n\n if (!existsSync(full)) {\n write(root, file.path, file.content);\n result.created.push(file.path);\n if (file.policy !== 'user') next.files[file.path] = newHash;\n continue;\n }\n\n if (file.policy === 'user') {\n result.kept.push(file.path);\n continue;\n }\n\n const diskHash = sha256(readFileSync(full, 'utf8'));\n if (diskHash === newHash) {\n result.unchanged.push(file.path);\n next.files[file.path] = newHash;\n continue;\n }\n\n if (opts.mode === 'init') {\n result.outdated.push(file.path);\n next.files[file.path] = previous?.files[file.path] ?? diskHash;\n continue;\n }\n\n // update\n const userModified = file.policy === 'wrapper' && previous?.files[file.path] !== diskHash;\n if (userModified && !opts.force) {\n result.conflicts.push(file.path);\n next.files[file.path] = previous?.files[file.path] ?? diskHash;\n continue;\n }\n write(root, file.path, file.content);\n result.updated.push(file.path);\n next.files[file.path] = newHash;\n }\n\n // Remove framework files and unmodified wrappers that this version no longer ships.\n if (opts.mode === 'update' && previous) {\n const planned = new Set(plan.map((f) => f.path));\n for (const [path, hash] of Object.entries(previous.files)) {\n if (planned.has(path)) continue;\n const full = join(root, path);\n if (!existsSync(full)) continue;\n if (sha256(readFileSync(full, 'utf8')) === hash) {\n rmSync(full);\n result.removed.push(path);\n // A skill folder of a wrapper this version no longer ships: drop it once it is empty.\n const folder = dirname(full);\n if (emptiedFolder.test(folder) && readdirSync(folder).length === 0)\n rmSync(folder, { recursive: true });\n } else {\n result.conflicts.push(path);\n }\n }\n }\n\n write(root, manifestPath, JSON.stringify(next, null, 2) + '\\n');\n return result;\n}\n","import { createHash } from 'node:crypto';\n\nexport const sha256 = (content: string): string => createHash('sha256').update(content).digest('hex');\n","/**\n * Names as people say them, matched against names as the spec writes them. Imports nothing: the reverse-spec\n * coverage and the client's `lookup` share it, and the client bundles no part of the spec model.\n */\n\n/** Case, spacing and punctuation don't matter; `full_name`, `Full-name` and `Full name` are the same name. */\nexport const normalizeName = (s: string) =>\n s\n .toLowerCase()\n .replace(/[_\\-./]+/g, ' ')\n .replace(/[^\\p{L}\\p{N} ]+/gu, '')\n .replace(/\\s+/g, ' ')\n .trim();\n\n/**\n * The names a thing may go by: its own, plus the glossary's view of it (a forbidden synonym matches the canonical\n * term and the other way round), so \"worker\" matches the spec's \"Employee\".\n */\nexport function aliasGroups(\n glossary: { term: string; forbidden?: string[] }[],\n): (name: string) => Set<string> {\n const groups: Set<string>[] = glossary.map(\n (g) => new Set([g.term, ...(g.forbidden ?? [])].map(normalizeName)),\n );\n return (name) => {\n const n = normalizeName(name);\n const out = new Set([n]);\n for (const g of groups) if (g.has(n)) for (const x of g) out.add(x);\n return out;\n };\n}\n","import { FRONT_MATTER_SHARD, shardDir } from '../../src/export/paths.js';\nimport { type ExportReader, frontMatterOf, idsIn } from '../../src/export/read.js';\nimport { aliasGroups, normalizeName } from '../../src/lib/names.js';\nimport { type IdKind, idKind } from '../../src/schemas/ids.js';\nimport { titleOf } from './context.js';\nimport type { TaskRef } from './task.js';\n\n/**\n * `lookup`: where in the export a question is answered. It resolves what the question names (IDs, glossary terms and\n * the synonyms people say, titles), follows the export's own links one hop, and prints the shards to read first, the\n * ones that must be opened before the export may be called silent, and the neighbours. Paths and titles only, never\n * spec text: the answerer reads, the CLI finds.\n */\n\n/** `_generated/index.json` as far as lookup follows it; every list may be absent in an older export. */\ninterface Index {\n capabilities?: {\n id: string;\n title: string;\n roles?: { role: string; scope?: string }[];\n screens?: string[];\n entities?: { entity: string; ops?: string[] }[];\n rules?: string[];\n events?: { emits?: string[]; consumes?: string[] };\n depends_on?: string[];\n flows?: string[];\n }[];\n screens?: {\n id: string;\n title: string;\n roles?: { role: string }[];\n fields?: { entity: string }[];\n actions?: { id: string; label?: string; capability?: string }[];\n }[];\n entities?: { id: string; title: string; attributes?: { name: string; references?: string }[] }[];\n rules?: { id: string; title: string; entities?: string[]; guards?: { entity: string; on?: string[] }[] }[];\n events?: { id: string; title: string; entities?: string[] }[];\n roles?: { id: string; title: string }[];\n personas?: { id: string; title: string; roles?: string[] }[];\n decisions?: { id: string; title: string; affects?: string[] }[];\n flows?: { id: string; title: string; steps?: { capability?: string }[] }[];\n glossary?: { term: string; forbidden?: string[] }[];\n}\n\nconst ID_KINDS: IdKind[] = [\n 'acceptance',\n 'screenAction',\n 'experience',\n 'capability',\n 'screen',\n 'entity',\n 'rule',\n 'event',\n 'decision',\n 'role',\n 'persona',\n 'flow',\n 'integration',\n 'nfr',\n 'module',\n];\n\n/** The sections that usually hold the answer, by the kind of object; the rest of its shards are in the same folder. */\nconst READ: Partial<Record<IdKind, string[]>> = {\n capability: [\n 'Acceptance criteria',\n 'Alternative and exception flows',\n 'Permissions and data visibility',\n 'Main flow',\n ],\n entity: ['Attributes', 'Lifecycle'],\n screen: ['Displayed data', 'Actions', 'Business states', 'Per-role differences'],\n experience: ['Interactions', 'Validation messages', 'Loading and errors'],\n flow: ['Steps'],\n};\n/** Where an object says what it deliberately leaves out, and what is still undecided about it. */\nconst SILENCE = ['Out of scope', 'Open questions'];\n\nconst VIEWS: [string, string][] = [\n ['_generated/role-matrix.md', 'who may perform a capability, and with which scope'],\n ['_generated/visibility.md', 'which states of a record a role sees'],\n ['_generated/rule-matrix.md', 'where a rule is enforced, what triggers it, which criteria cover it'],\n ['_generated/channel-matrix.md', 'on which channel and screen a capability is performed'],\n ['_generated/navigation.md', 'how a screen is reached and where its actions lead'],\n ['_generated/traceability.md', 'the order of a flow’s steps and what joins them'],\n ['_generated/operations.md', 'what other systems may do'],\n];\n\nexport interface About {\n id: string;\n title?: string;\n /** How the question named it, when not by its ID. */\n said?: string;\n /** The criterion, action or state the question is about. */\n focus?: string[];\n}\n\nexport interface Reading {\n id: string;\n title?: string;\n /** The shard folder (documents) or the item's shard (collections). */\n at: string;\n /** The shards of the folder to open first. */\n shards: string[];\n}\n\nexport interface Check {\n path: string;\n why: string;\n}\n\nexport interface Lookup {\n about: About[];\n /** IDs and references the question names that the export doesn't hold. */\n missing: string[];\n read: Reading[];\n check: Check[];\n neighbours: (Check & { id: string })[];\n views: Check[];\n}\n\nexport interface LookupOptions {\n refs?: string[];\n question?: string;\n task?: TaskRef;\n item?: string;\n}\n\nconst NEIGHBOURS = 15;\nconst ORDER: IdKind[] = ['rule', 'decision', 'capability', 'entity', 'screen', 'experience', 'event', 'role'];\n\nconst ownerOf = (id: string) =>\n /^(.+)-AC-\\d+$/.exec(id)?.[1] ?? /^(.+)\\.A\\d+$/.exec(id)?.[1] ?? id.replace(/#.*$/, '');\nconst screenOfUx = (id: string) => /^UX-(SCR-.+)-[A-Z]{2,5}$/.exec(id)?.[1];\n\nexport function lookup(x: ExportReader, opts: LookupOptions): Lookup {\n const index = (x.index() ?? {}) as unknown as Index;\n const caps = index.capabilities ?? [];\n const screens = index.screens ?? [];\n const entities = index.entities ?? [];\n const rules = index.rules ?? [];\n const events = index.events ?? [];\n const decisions = index.decisions ?? [];\n const text = [...(opts.refs ?? []), opts.question ?? ''].join(' ');\n\n // 1. What the question names.\n const about = new Map<string, About>();\n const missing: string[] = [];\n const add = (id: string, more: Partial<About> = {}) => {\n const owner = ownerOf(id);\n if (!x.sources.has(owner)) {\n if (!missing.includes(id)) missing.push(id);\n return;\n }\n const a = about.get(owner) ?? { id: owner, ...(titleOf(x, owner) ? { title: titleOf(x, owner)! } : {}) };\n if (owner !== id) a.focus = [...new Set([...(a.focus ?? []), id])];\n about.set(owner, { ...a, ...more });\n };\n for (const id of idsIn(text, ID_KINDS)) add(id);\n for (const m of text.matchAll(/(?<![\\w-])(UX-SCR-[A-Z0-9-]+#[\\w-]+|SCR-[A-Z0-9-]+\\.A\\d+)/g)) add(m[1]!);\n\n // Names: titles and glossary terms, and the synonyms the glossary knows people say.\n const aliases = aliasGroups(index.glossary ?? []);\n const names = new Map<string, { id: string; said?: string }>();\n const name = (said: string, id: string) => {\n for (const n of aliases(said))\n if (n.length > 2 && !names.has(n))\n names.set(n, { id, ...(n === normalizeName(said) ? {} : { said: n }) });\n };\n for (const list of [entities, screens, caps, rules, events, index.roles ?? [], index.personas ?? []])\n for (const o of list) name(o.title, o.id);\n for (const g of index.glossary ?? []) name(g.term, `term:${g.term}`);\n const spoken = ` ${normalizeName(text.replace(/\\b[A-Z]+(?:-[A-Z0-9]+)+\\b/g, ' '))} `;\n for (const [n, hit] of [...names].sort((a, b) => b[0].length - a[0].length))\n if (new RegExp(` ${n}(?:s|es)? `).test(spoken) && !about.has(hit.id))\n add(hit.id, hit.said ? { said: hit.said } : {});\n for (const ref of opts.refs ?? [])\n if (!idsIn(ref, ID_KINDS).length && !/#/.test(ref) && !names.has(normalizeName(ref))) {\n const plural = normalizeName(ref).replace(/e?s$/, '');\n if (!names.has(plural) && !missing.includes(ref)) missing.push(ref);\n }\n\n // A capability by what it does: its title's verb (\"Approve sales price\"), or the label of an action that performs\n // it, said about something the question already named (its role, its entity) or with another word of its title.\n const said = (word: string) => {\n const w = normalizeName(word);\n return w.length > 3 && new RegExp(` ${w.replace(/e$/, '')}(?:e|es|ed|d|s|ing)? `).test(spoken);\n };\n for (const c of caps) {\n if (about.has(c.id)) continue;\n const [verb, ...rest] = normalizeName(c.title).split(' ');\n const labels = screens.flatMap((sc) =>\n (sc.actions ?? []).filter((act) => act.capability === c.id).map((act) => act.label ?? ''),\n );\n const word = [verb!, ...labels].find(said);\n if (!word) continue;\n const near =\n c.roles?.some((r) => about.has(r.role)) ||\n c.entities?.some((e) => about.has(e.entity)) ||\n rest.some(said);\n if (near) add(c.id, { said: normalizeName(word) });\n }\n\n // The task's own objects, when the question named nothing; the item it is about, always.\n if (opts.item) add(opts.item);\n if (!about.size && opts.task) {\n const task = x.work.changes\n .find((c) => c.id === opts.task!.change)\n ?.tasks?.find((t) => t.track === opts.task!.track);\n for (const key of task?.objects ?? []) if (x.sources.has(key) && !key.startsWith('file:')) add(key);\n }\n\n // 2. One hop through the export's links, both ways.\n const links = (id: string): { id: string; why: string }[] => {\n const out: { id: string; why: string }[] = [];\n const cap = caps.find((c) => c.id === id);\n if (cap) {\n for (const r of cap.rules ?? []) out.push({ id: r, why: `a rule of ${id}` });\n for (const e of cap.entities ?? [])\n out.push({ id: e.entity, why: `${id} works with it${e.ops?.length ? ` (${e.ops.join('')})` : ''}` });\n for (const e of cap.events?.emits ?? []) out.push({ id: e, why: `emitted by ${id}` });\n for (const e of cap.events?.consumes ?? []) out.push({ id: e, why: `starts or informs ${id}` });\n for (const r of cap.roles ?? [])\n out.push({ id: r.role, why: `performs ${id}${r.scope ? `, scope ${r.scope}` : ''}` });\n for (const d of cap.depends_on ?? []) out.push({ id: d, why: `${id} depends on it` });\n }\n for (const s of screens) {\n const acts = (s.actions ?? []).filter((a) => a.capability === id);\n if (acts.length)\n out.push({\n id: s.id,\n why: `performs ${id} (${acts.map((a) => `${a.id}${a.label ? ` ${a.label}` : ''}`).join(', ')})`,\n });\n if (s.id === id) {\n for (const a of s.actions ?? [])\n if (a.capability) out.push({ id: a.capability, why: `${id}.${a.id} performs it` });\n for (const f of s.fields ?? []) out.push({ id: f.entity, why: `shown on ${id}` });\n } else if ((s.fields ?? []).some((f) => f.entity === id)) out.push({ id: s.id, why: `shows ${id}` });\n }\n for (const r of rules) {\n const guards = (r.guards ?? []).filter((g) => g.entity === id);\n if (r.id === id) {\n for (const c of caps) if (c.rules?.includes(id)) out.push({ id: c.id, why: `applies ${id}` });\n for (const e of new Set([...(r.entities ?? []), ...(r.guards ?? []).map((g) => g.entity)]))\n out.push({ id: e, why: `${id} is about it` });\n } else if (guards.length)\n out.push({\n id: r.id,\n why: `guards ${id} on ${guards.flatMap((g) => g.on ?? []).join(', ') || 'it'}`,\n });\n else if (r.entities?.includes(id)) out.push({ id: r.id, why: `is about ${id}` });\n }\n const ent = entities.find((e) => e.id === id);\n for (const a of ent?.attributes ?? [])\n if (a.references) out.push({ id: a.references, why: `${id}.${a.name} refers to it` });\n for (const e of entities)\n if (e.id !== id && e.attributes?.some((a) => a.references === id))\n out.push({ id: e.id, why: `refers to ${id}` });\n for (const c of caps) {\n if (c.id === id) continue;\n if (c.entities?.some((e) => e.entity === id)) out.push({ id: c.id, why: `works with ${id}` });\n if (c.events?.emits?.includes(id)) out.push({ id: c.id, why: `emits ${id}` });\n if (c.events?.consumes?.includes(id)) out.push({ id: c.id, why: `consumes ${id}` });\n if (c.roles?.some((r) => r.role === id)) out.push({ id: c.id, why: `${id} performs it` });\n if (c.depends_on?.includes(id)) out.push({ id: c.id, why: `depends on ${id}` });\n }\n for (const e of events.find((v) => v.id === id)?.entities ?? [])\n out.push({ id: e, why: `${id} is about it` });\n for (const d of decisions) {\n if (d.id === id) for (const a of d.affects ?? []) out.push({ id: a, why: `${id} affects it` });\n else if (d.affects?.includes(id)) out.push({ id: d.id, why: `decides about ${id}` });\n }\n const scr = screenOfUx(id);\n if (scr) out.push({ id: scr, why: `${id} is its design` });\n for (const s of x.sources.keys())\n if (screenOfUx(s) === id) out.push({ id: s, why: `the design of ${id}` });\n // An export without the index: what the object's own front-matter names.\n if (!x.index()) {\n const file = x.fileOf(id);\n for (const n of idsIn(frontMatterOf((file && x.read(file)) || ''), ID_KINDS))\n if (n !== id) out.push({ id: n, why: `named by ${id}` });\n }\n return out.filter((l) => x.sources.has(l.id));\n };\n\n // 3. The lists.\n const isDoc = (id: string) => {\n const file = x.fileOf(id);\n return !!file && x.has(`${shardDir(file)}/${FRONT_MATTER_SHARD}`);\n };\n const pathOf = (id: string): string | undefined => {\n const file = x.fileOf(id);\n if (!file) return undefined;\n return isDoc(id) ? `${shardDir(file)}/${FRONT_MATTER_SHARD}` : (x.itemShard(file, id) ?? file);\n };\n const resolved = [...about.keys()];\n const read: Reading[] = resolved.flatMap((id) => {\n const file = x.fileOf(id);\n const a = about.get(id)!;\n if (!file) return [];\n if (!isDoc(id)) return [{ id, ...(a.title ? { title: a.title } : {}), at: pathOf(id)!, shards: [] }];\n const folder = `${shardDir(file)}/`;\n const kind = idKind(id);\n const sections = (kind && READ[kind]) ?? [];\n return [\n {\n id,\n ...(a.title ? { title: a.title } : {}),\n at: folder,\n shards: [\n FRONT_MATTER_SHARD,\n ...sections.flatMap((h) => x.sectionShard(file, h)?.slice(folder.length) ?? []),\n ],\n },\n ];\n });\n\n const check = new Map<string, string>();\n const must = (path: string | undefined, why: string) => {\n if (path && x.has(path) && !check.has(path)) check.set(path, why);\n };\n const hop = new Map(resolved.map((id) => [id, links(id)]));\n for (const id of resolved) {\n const file = x.fileOf(id)!;\n if (isDoc(id)) {\n must(pathOf(id), `the facts of ${id}`);\n for (const h of SILENCE) must(x.sectionShard(file, h), `${id}: ${h.toLowerCase()}`);\n } else must(pathOf(id), id.startsWith('term:') ? `what \"${id.slice(5)}\" means` : `${id} itself`);\n }\n for (const id of resolved)\n for (const l of hop.get(id)!) if (idKind(l.id) === 'rule') must(pathOf(l.id), `${l.id}: ${l.why}`);\n // Decisions about what the question names, and about the entities and rules behind it.\n const behind = new Set(\n resolved\n .filter((id) => ['capability', 'screen'].includes(idKind(id) ?? ''))\n .flatMap((id) => hop.get(id)!.map((l) => l.id)),\n );\n for (const d of decisions)\n if (d.affects?.some((a) => resolved.includes(a))) must(pathOf(d.id), `${d.id} decides about it`);\n for (const d of decisions)\n if (d.affects?.some((a) => behind.has(a) && ['entity', 'rule'].includes(idKind(a) ?? '')))\n must(pathOf(d.id), `${d.id} decides about ${d.affects.find((a) => behind.has(a))}`);\n for (const id of resolved) {\n const last = (x.sources.get(id) as { changed_by?: string[] } | undefined)?.changed_by?.at(-1);\n must(last && x.proposalPath(last), `why ${id} is as it is (${last}, the last change of it)`);\n }\n must('_generated/open-items.md', 'what the spec itself holds open');\n\n const seen = new Set(resolved);\n const neighbours = resolved\n .flatMap((id) => hop.get(id)!)\n .filter((l) => !seen.has(l.id) && seen.add(l.id))\n .map((l) => ({ id: l.id, path: pathOf(l.id) ?? '', why: l.why }))\n .filter((l) => l.path && !check.has(l.path))\n .sort((a, b) => {\n const rank = (id: string) => (ORDER.indexOf(idKind(id)!) + 1 || ORDER.length + 1) - 1;\n return rank(a.id) - rank(b.id);\n })\n .slice(0, NEIGHBOURS);\n\n return {\n about: [...about.values()],\n missing,\n read,\n check: [...check].map(([path, why]) => ({ path, why })),\n neighbours,\n views: VIEWS.filter(([p]) => x.has(p)).map(([path, why]) => ({ path, why })),\n };\n}\n\n/**\n * The paths of `check` nobody opened. A path counts as opened when it was read itself, when the file it is a shard\n * of was read whole, or when the object was named by its ID.\n */\nexport function unread(x: ExportReader, found: Lookup, opened: string[]): Check[] {\n const dir = x.dir.replace(/\\/+$/, '');\n const given = opened.map((o) =>\n (o.startsWith(`${dir}/`) ? o.slice(dir.length + 1) : o).replace(/^\\.\\//, ''),\n );\n const covers = (path: string) =>\n given.some((g) => {\n if (g === path || path.endsWith(`/${g}`)) return true;\n if (g.endsWith('.md') && path.startsWith(`${shardDir(g)}/`)) return true;\n const file = x.sources.has(g) ? x.fileOf(g) : undefined;\n return !!file && (path.startsWith(`${shardDir(file)}/`) || path === file);\n });\n return found.check.filter((c) => !covers(c.path));\n}\n\nexport function renderLookup(l: Lookup): string {\n const out: string[] = [];\n if (!l.about.length)\n out.push(\n 'The question names nothing the export holds: no ID, glossary term or title of it. Rephrase it in the',\n 'export’s terms (glossary.md), or it is about something the product doesn’t have.',\n );\n else\n out.push(\n `About: ${l.about\n .map(\n (a) =>\n `${a.id}${a.title && !a.id.startsWith('term:') ? ` ${a.title}` : ''}${a.said ? ` (said as \"${a.said}\")` : ''}${a.focus ? ` [${a.focus.join(', ')}]` : ''}`,\n )\n .join('; ')}`,\n );\n if (l.missing.length) out.push(`Not in the export: ${l.missing.join(', ')}`);\n if (l.read.length)\n out.push(\n '',\n 'Read first:',\n ...l.read.map((r) => `- ${r.id}: ${r.at}${r.shards.length ? ` ${r.shards.join(', ')}` : ''}`),\n );\n if (l.check.length)\n out.push('', 'Open before calling the export silent:', ...l.check.map((c) => `- ${c.path} (${c.why})`));\n if (l.neighbours.length)\n out.push('', 'Neighbours, when one bears on it:', ...l.neighbours.map((n) => `- ${n.path} (${n.why})`));\n if (l.views.length)\n out.push('', 'Views, by the kind of question:', ...l.views.map((v) => `- ${v.path}: ${v.why}`));\n return out.join('\\n') + '\\n';\n}\n","import { spawn } from 'node:child_process';\nimport { DispatcherError, type Session } from './auth.js';\n\n/** What `open` opens: only the dispatcher's pages for now. */\nexport const OPENABLE = ['dispatcher'] as const;\n\nexport function openInBrowser(url: string): void {\n const [cmd, args] =\n process.platform === 'darwin'\n ? ['open', [url]]\n : process.platform === 'win32'\n ? ['cmd', ['/c', 'start', '', url]]\n : ['xdg-open', [url]];\n spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();\n}\n\n/** Sign in, ask for a one-time link to the dispatcher's pages (valid for a minute, used once) and open it. */\nexport async function openDispatcher(\n session: Session,\n open: (url: string) => void = openInBrowser,\n): Promise<string> {\n const res = await session.fetch('/auth/link', { method: 'POST' });\n if (!res.ok) throw new DispatcherError('HTTP_' + res.status, `The dispatcher answered ${res.status}.`);\n const { url } = (await res.json()) as { url: string };\n open(url);\n return url;\n}\n","import { execFileSync } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { DispatcherError, type Session } from './auth.js';\nimport { callTool } from './mcp.js';\nimport { COVERS, TRAILER, type TaskRef, folderOf, parseTask, taskOfBranch } from './task.js';\n\n/**\n * A task's progress, from the developer's commits (spec 8.1 and 12.2 `progress`): the commits reachable from `HEAD`\n * carrying the task's trailer name the items they cover in `Alterspec-Covers`, each with the first commit naming it,\n * and the dispatcher gets them with `report_progress`. The agent only names items; counting is the dispatcher's.\n */\n\nexport interface Covered {\n item: string;\n commit: string;\n}\n\nconst git = (cwd: string, args: string[]) =>\n execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();\n\n/**\n * The task being worked on in `repo`: the one of the task branch checked out, else the one the `Alterspec-Task`\n * trailer of the last commit names, since the client makes no branch and the developer may work on any.\n */\nexport function currentTask(repo: string): TaskRef | undefined {\n try {\n const task = taskOfBranch(git(repo, ['symbolic-ref', '--short', 'HEAD']));\n if (task) return task;\n } catch {\n // A detached HEAD: the trailer may still say.\n }\n try {\n const named = git(repo, [\n 'log',\n '-1',\n `--format=%(trailers:key=${TRAILER},valueonly,separator=%x1d)`,\n 'HEAD',\n ]);\n for (const id of named.split('\\x1d'))\n try {\n return parseTask(id.trim());\n } catch {\n // Not a task as the dispatcher writes it.\n }\n } catch {\n // No commit yet.\n }\n return undefined;\n}\n\n/**\n * The items the task's commits reachable from `HEAD` cover, sorted, each with the first (oldest) commit that named\n * it. Trailers are read by git itself, so only the message's trailer block counts.\n */\nexport function coveredItems(repo: string, task: TaskRef): Covered[] {\n const trailer = (key: string) => `%(trailers:key=${key},valueonly,separator=%x1d)`;\n const log = git(repo, [\n 'log',\n '--reverse',\n '--topo-order',\n `--format=%H%x1f${trailer(TRAILER)}%x1f${trailer(COVERS)}%x1e`,\n 'HEAD',\n ]);\n const first = new Map<string, string>();\n for (const record of log.split('\\x1e')) {\n const [sha, tasks = '', covers = ''] = record.trim().split('\\x1f');\n if (!sha) continue;\n if (!tasks.split('\\x1d').some((t) => t.trim().toUpperCase() === task.id)) continue;\n for (const item of covers\n .replaceAll('\\x1d', ',')\n .split(/[,\\s]+/)\n .filter(Boolean))\n if (!first.has(item)) first.set(item, sha);\n }\n return [...first]\n .map(([item, commit]) => ({ item, commit }))\n .sort((a, b) => (a.item < b.item ? -1 : a.item > b.item ? 1 : 0));\n}\n\n/** An item named without its section (`RULE-WH-018`) where the checklist holds parts of it (`RULE-WH-018#front-matter`). */\nexport interface Misnamed {\n item: string;\n /** The checklist's items of that object, as the trailer should name them. */\n forms: string[];\n}\n\nexport interface ProgressReport {\n task: string;\n covered: Covered[];\n /** Items the commits name that the task lacks: left out, said in one line. */\n unknown: string[];\n /** Items named without their section while the checklist holds parts of the object none of which is covered yet. */\n misnamed: Misnamed[];\n /**\n * Items named without their section whose parts some commit or earlier report covers in the checklist's form: an\n * old trailer can't be corrected, so these are left out without a word.\n */\n superseded: string[];\n /** The dispatcher's answer: the task with its progress and ETA. */\n answer: Record<string, unknown>;\n}\n\n/** The items `UNKNOWN_ITEM` names: the indented lines after its sentence. */\nconst unknownOf = (e: DispatcherError) =>\n e.message\n .split('\\n')\n .slice(1)\n .map((l) => l.trim())\n .filter(Boolean);\n\n/** The task's checklist from the dispatcher's `task`, with what it holds covered; empty when it can't be asked. */\nasync function checklistOf(session: Session, task: TaskRef) {\n try {\n const answer = await callTool(session, 'task', { id: task.id });\n return ((answer.items ?? []) as { item: string; covered_commit?: string | null }[]).map((i) => ({\n item: i.item,\n covered: !!i.covered_commit,\n }));\n } catch {\n return [];\n }\n}\n\n/**\n * Sort the refused items: a bare object ID whose parts are on the checklist is a name without its section, settled\n * when one of those parts is covered (by this report or an earlier one), else a hint with the form to use; the rest\n * are unknown.\n */\nexport function sortRefused(\n refused: string[],\n sent: string[],\n checklist: { item: string; covered: boolean }[],\n): Pick<ProgressReport, 'unknown' | 'misnamed' | 'superseded'> {\n const sentSet = new Set(sent);\n const out: Pick<ProgressReport, 'unknown' | 'misnamed' | 'superseded'> = {\n unknown: [],\n misnamed: [],\n superseded: [],\n };\n for (const item of refused) {\n const parts = item.includes('#') ? [] : checklist.filter((c) => c.item.startsWith(`${item}#`));\n if (!parts.length) out.unknown.push(item);\n else if (parts.some((p) => p.covered || sentSet.has(p.item))) out.superseded.push(item);\n else out.misnamed.push({ item, forms: parts.map((p) => p.item).sort() });\n }\n return out;\n}\n\n/**\n * Send the covered items. An item the task lacks is left out and the rest sent again: a pushed commit's trailer can't\n * be corrected, so one wrong name must not keep every later report out. The dispatcher stays strict (spec 8: exact\n * items); a name without its section is only worded here.\n */\nexport async function reportProgress(\n session: Session,\n task: TaskRef,\n covered: Covered[],\n): Promise<ProgressReport> {\n try {\n const answer = await callTool(session, 'report_progress', { id: task.id, covered });\n return { task: task.id, covered, unknown: [], misnamed: [], superseded: [], answer };\n } catch (e) {\n if (!(e instanceof DispatcherError) || e.code !== 'UNKNOWN_ITEM') throw e;\n const refused = unknownOf(e);\n const known = covered.filter((c) => !refused.includes(c.item));\n if (!refused.length || known.length === covered.length) throw e;\n const answer = await callTool(session, 'report_progress', { id: task.id, covered: known });\n const sorted = sortRefused(\n refused,\n known.map((c) => c.item),\n await checklistOf(session, task),\n );\n return { task: task.id, covered: known, ...sorted, answer };\n }\n}\n\ninterface Progress {\n covered: number;\n of: number;\n percent: number;\n}\n/** The dispatcher's weighed progress (its step 8): covered and total weight of the task's items. */\ninterface Weight {\n covered: number;\n total: number;\n}\ninterface Eta {\n date: string | null;\n at_least?: boolean;\n by?: string;\n computed?: { date: string | null };\n}\n\n/** The report in one or two lines: what the dispatcher counts, and what it refused. */\nexport function progressText(r: ProgressReport): string {\n const progress = r.answer.progress as Progress | null | undefined;\n const weight = r.answer.weight as Weight | null | undefined;\n const eta = r.answer.eta as Eta | undefined;\n const count = progress\n ? `${progress.covered} of ${progress.of} items covered (${progress.percent} %${weight ? `, ${weight.covered} of ${weight.total} weight` : ''})`\n : 'no checklist (its export predates task items)';\n const when = !eta\n ? ''\n : eta.by === 'done'\n ? '; done'\n : eta.date\n ? `; ETA ${eta.at_least ? 'at least ' : ''}${eta.date}${eta.by === 'developer' ? ` (yours; computed ${eta.computed?.date ?? 'unknown'})` : ''}`\n : '; ETA unknown';\n return [...refusedLines(r), `${r.task}: ${count}${when}.`].join('\\n') + '\\n';\n}\n\n/** What the dispatcher refused, in the words the developer acts on; nothing for names already settled. */\nexport const refusedLines = (r: Pick<ProgressReport, 'task' | 'unknown' | 'misnamed'>): string[] => [\n ...(r.unknown.length ? [unknownLine(r)] : []),\n ...r.misnamed.map(misnamedLine),\n];\n\nexport const unknownLine = (r: Pick<ProgressReport, 'task' | 'unknown'>) =>\n `${r.task} has no item ${r.unknown.join(', ')}; left out of the report: name only the task's items (context lists them).`;\n\nexport const misnamedLine = (m: Misnamed) =>\n `${m.item} is named without its section; the checklist writes it as ${m.forms.join(m.forms.length > 2 ? ', ' : ' or ')}: name ${m.forms.length === 1 ? 'that' : 'the part you covered'} in Alterspec-Covers (left out of the report).`;\n\n/** Report no more often than this from the hook. */\nexport const THROTTLE_MS = 15 * 60_000;\n\ninterface HookState {\n /** The hash of the covered items last reported. */\n reported: string;\n at: string;\n}\n\nconst statePath = (repo: string, task: TaskRef) =>\n join(\n git(repo, ['rev-parse', '--path-format=absolute', '--git-common-dir']),\n 'alterspec-client',\n `progress-${folderOf(task)}.json`,\n );\n\nconst hashOf = (covered: Covered[]) =>\n createHash('sha256').update(JSON.stringify(covered)).digest('hex').slice(0, 16);\n\nfunction readState(path: string): HookState | undefined {\n try {\n return existsSync(path) ? (JSON.parse(readFileSync(path, 'utf8')) as HookState) : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport type HookOutcome = 'off-task' | 'unchanged' | 'throttled' | 'reported' | 'failed';\n\n/**\n * `progress --hook`, after a commit in Claude Code: reports when it knows the task, when the covered items changed and\n * the last report is 15 minutes old; never fails, so it never fails the agent's turn.\n */\nexport async function progressHook(opts: {\n repo: string;\n session: () => Session;\n now?: () => number;\n /** Where to say what the last commit named wrongly (the hook's stdout). */\n say?: (text: string) => void;\n}): Promise<HookOutcome> {\n const now = opts.now ?? Date.now;\n try {\n const task = currentTask(opts.repo);\n if (!task) return 'off-task';\n const covered = coveredItems(opts.repo, task);\n const path = statePath(opts.repo, task);\n const state = readState(path);\n const hash = hashOf(covered);\n if (state?.reported === hash) return 'unchanged';\n if (state && now() - Date.parse(state.at) < THROTTLE_MS) return 'throttled';\n const report = await reportProgress(opts.session(), task, covered);\n const named = new Set(headCovers(opts.repo, task));\n const wrong = refusedLines({\n task: report.task,\n unknown: report.unknown.filter((i) => named.has(i)),\n misnamed: report.misnamed.filter((m) => named.has(m.item)),\n });\n if (wrong.length && opts.say) opts.say(hookContext(wrong.join('\\n')));\n mkdirSync(join(path, '..'), { recursive: true });\n writeFileSync(path, JSON.stringify({ reported: hash, at: new Date(now()).toISOString() }) + '\\n');\n return 'reported';\n } catch {\n return 'failed';\n }\n}\n\n/** The items the last commit's `Alterspec-Covers` names, when its `Alterspec-Task` is the task. */\nexport function headCovers(repo: string, task: TaskRef): string[] {\n const trailer = (key: string) => `%(trailers:key=${key},valueonly,separator=%x1d)`;\n const [tasks = '', covers = ''] = git(repo, [\n 'log',\n '-1',\n `--format=${trailer(TRAILER)}%x1f${trailer(COVERS)}`,\n 'HEAD',\n ]).split('\\x1f');\n if (!tasks.split('\\x1d').some((t) => t.trim().toUpperCase() === task.id)) return [];\n return covers\n .replaceAll('\\x1d', ',')\n .split(/[,\\s]+/)\n .filter(Boolean);\n}\n\n/**\n * The hook's answer to Claude: one line of JSON whose `additionalContext` an async hook's output delivers on the next\n * turn (code.claude.com/docs/en/hooks, \"Run hooks in the background\", checked 2026-11-21).\n */\nexport const hookContext = (text: string) =>\n JSON.stringify({\n hookSpecificOutput: {\n hookEventName: 'PostToolUse',\n additionalContext: `alterspec-client progress: ${text}`,\n },\n }) + '\\n';\n\n/** The folder the hook works in: the `cwd` of the hook's input on stdin, when Claude Code gives one. */\nexport async function hookCwd(input: NodeJS.ReadableStream & { isTTY?: boolean }, waitMs = 1000) {\n if (input.isTTY) return undefined;\n const text = await new Promise<string>((resolve) => {\n let data = '';\n const done = () => resolve(data);\n const timer = setTimeout(done, waitMs);\n input.on('data', (c: Buffer | string) => (data += c.toString()));\n input.on('end', () => {\n clearTimeout(timer);\n done();\n });\n input.on('error', done);\n });\n try {\n const cwd = (JSON.parse(text) as { cwd?: unknown }).cwd;\n return typeof cwd === 'string' && cwd ? cwd : undefined;\n } catch {\n return undefined;\n }\n}\n","import { readFileSync } from 'node:fs';\n\n/** The client's version, from its package.json, one level above both src/ (tests) and dist/ (built CLI). */\nexport function packageVersion(): string {\n const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as {\n version: string;\n };\n return pkg.version;\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB,SAAS,QAAAA,aAAY;;;ACDrB,SAAS,oBAAoB;AAC7B,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,YAAY,MAAM,eAAe;AAC7D,SAAS,KAAAC,UAAS;;;ACJlB,SAAS,SAAS;AAgBX,IAAM,YAAY,EAAE,OAAO,EAAE,MAAM,gBAAgB,EAAE,SAAS,+BAA+B,CAAC;AAQ9F,IAAM,aAAa,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAQlD,IAAM,aAAa,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAIlD,IAAM,YAAY,EAAE,OAAO,KAAK,SAAS,KAAK,OAAO,KAAK,MAAM,IAAI;AAG3E,IAAM,QAAQ,CAAC,QACb,EACG,OAAO,EACP,IAAI,KAAK,EAAE,SAAS,WAAW,GAAG,cAAc,CAAC,EACjD,MAAM,uBAAuB,EAAE,SAAS,6CAA6C,CAAC;AAGpF,IAAM,YAAY,MAAM,UAAU,KAAK;AAEvC,IAAM,cAAc,MAAM,UAAU,OAAO;AAE3C,IAAM,YAAY,MAAM,UAAU,KAAK;AAEvC,IAAM,WAAW,MAAM,UAAU,IAAI;AAE5C,IAAM,YA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AO;AAAA,MACb,KAAK,OACD,KAAK,UAAU,KAAK,IAAI,OACxB,MAAM,SACJ,GAAG,MAAM,MAAM,OAAO,MAAM,MAAM,oBAAoB,IAAI;AAAA,IAC1D,GAAG,MAAM,MAAM,OAAO,IAAI;AAAA;AAAA,IAClC;AAAA,EACF,CAAC;AACH;AAEF,MAAM,QAAQ,WAAW;","names":["join","z","z","execFileSync","existsSync","readFileSync","writeFileSync","homedir","join","z","z","z","z","z","z","z","Version","z","z","before","after","sectionText","sectionText","body","sections","sections","fence","existsSync","readFileSync","join","join","existsSync","readFileSync","i","j","day","keyOf","z","resolve","z","PART","seen","one","stateOf","str","seen","one","list","str","after","before","lines","line","what","slug","kind","e","linesOf","bullets","title","caps","screens","exportDir","words","written","idOf","kept","added","named","bearing","lost","delta","list","p","sections","z","one","exportDir","execFileSync","existsSync","readFileSync","rmSync","writeFileSync","dirname","join","join","rmSync","dirname","existsSync","writeFileSync","execFileSync","readFileSync","execFileSync","existsSync","join","git","execFileSync","existsSync","join","existsSync","mkdirSync","readFileSync","readdirSync","writeFileSync","join","existsSync","mkdirSync","readFileSync","readdirSync","rmSync","writeFileSync","dirname","join","createHash","join","existsSync","readFileSync","mkdirSync","dirname","writeFileSync","rmSync","readdirSync","MANIFEST_PATH","readdirSync","join","readFileSync","before","existsSync","after","writeFileSync","mkdirSync","git","said","list","sections","seen","execFileSync","createHash","existsSync","mkdirSync","readFileSync","writeFileSync","join","git","execFileSync","named","join","createHash","existsSync","readFileSync","mkdirSync","writeFileSync","resolve","readFileSync","join","ctx"]}