@alterset/alterspec-client 0.15.0 → 0.16.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/README.md +7 -1
- package/agent-instructions.md +2 -0
- package/assets/prompts/_shared.md +10 -3
- package/assets/prompts/bug.md +69 -0
- package/assets/prompts/task-context.md +7 -1
- package/assets/prompts/task-done.md +1 -1
- package/assets/prompts/task-next.md +2 -1
- package/assets/prompts/task-status.md +3 -1
- package/assets/skills/alterspec-bug/SKILL.md +10 -0
- package/developer-guide.md +28 -0
- package/dist/cli.js +315 -97
- package/dist/cli.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/config.ts","../../src/schemas/work.ts","../src/ssh.ts","../src/auth.ts","../../src/export/read.ts","../../src/schemas/delta.ts","../../src/schemas/change.ts","../../src/schemas/common.ts","../../src/schemas/ids.ts","../../src/changes/delta-record.ts","../../src/lib/frontmatter-split.ts","../../src/spec/layout.ts","../../src/export/paths.ts","../../src/changes/data-change.ts","../../src/changes/parts.ts","../../src/lib/diff.ts","../../src/lib/comments.ts","../../src/spec/criteria.ts","../src/questions.ts","../src/mcp.ts","../src/context.ts","../src/git.ts","../src/task.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 { readExport } from '../../src/export/read.js';\nimport { CONFIG_FILE, type LoadedConfig, exportDir, loadConfig, readConfigAt } from './config.js';\nimport { type CoveredState, contextStats, renderContext, startFrom, taskContext } from './context.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 { type TaskRef, branchOf, parseTask } from './task.js';\nimport { packageVersion } from './version.js';\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 { item: string; covered_commit: string | null }[];\n const answers = parseAnswers(answer.answers);\n const from = startFrom(task.track, answer.after);\n return {\n covered: new Map(items.flatMap((i) => (i.covered_commit ? [[i.item, i.covered_commit] as const] : []))),\n ...(answers ? { answers } : {}),\n ...(from.length ? { startFrom: from } : {}),\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',\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('--force', 'replace skills you modified')\n .action(\n run(\n (opts: {\n dispatcher?: string;\n export?: string;\n track?: string[];\n key?: string;\n branch?: string;\n force?: boolean;\n }) => {\n const root = process.cwd();\n const { track, ...rest } = opts;\n const tracks = track\n ?.flatMap((t) => t.split(','))\n .map((t) => t.trim().toUpperCase())\n .filter(Boolean);\n const r = initClient(root, { ...rest, ...(tracks ? { tracks } : {}) }, packageVersion());\n const f = r.files;\n const lines = [\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('', 'Send this public key to the dispatcher’s admin:', key.line, key.fingerprint);\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('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')\n .option('--json', 'print it as JSON')\n .option('--stats', 'print its size by section instead')\n .action(\n run(async (id: string, opts: { json?: boolean; stats?: boolean }) => {\n const loaded = loadConfig();\n approveWorktree(loaded);\n const dir = exportDir(loaded);\n const x = readExport(dir);\n const task = parseTask(id);\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 ctx = taskContext(\n x,\n task,\n dir,\n await coveredState(loaded, task),\n await changeQuestions(sessionOf(loaded), tasks),\n );\n process.stdout.write(\n opts.stats\n ? contextStats(renderContext(ctx))\n : opts.json\n ? JSON.stringify(ctx, null, 2) + '\\n'\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({ repo, session: () => sessionOf(loadConfig(repo)) });\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('print the questions the dispatcher keeps: a task’s, or without a task your own')\n .argument('[task]', 'the task, e.g. CHG-012/BE')\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 (id: string | undefined, opts: { open?: boolean; about?: string[]; json?: boolean }) => {\n const questions = await listQuestions(sessionOf(loadConfig()), {\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('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\nexport const ClientConfigSchema = z\n .object({\n /** The dispatcher's URL. */\n dispatcher: z.url(),\n /** The developer's clone of the export repository, relative to this file's folder or absolute. */\n export: z.string().min(1),\n /** The tracks this repository builds: the default of `next_task`. */\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 .strict();\nexport type ClientConfig = z.infer<typeof ClientConfigSchema>;\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.`,\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\nexport const exportDir = ({ root, config }: LoadedConfig) => configPath(root, config.export);\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 2 (alterspec 0.24.0) adds each task's `items`; format 1 is the same without them, and\n * a reader of both 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\nconst ChangeRef = z.string().regex(/^CHG-\\d{3,}$/);\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 .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 })\n .strict();\nexport type WorkChange = z.infer<typeof WorkChangeSchema>;\n\nexport const WORK_FORMAT = 2;\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 .strict();\nexport type Work = z.infer<typeof WorkSchema>;\n\n/** Format 1 (alterspec 0.23): the same without `items`. */\nexport const WorkTaskV1Schema = WorkTaskSchema.omit({ items: true });\nexport type WorkTaskV1 = z.infer<typeof WorkTaskV1Schema>;\n\nexport const WorkV1Schema = WorkSchema.extend({\n format: z.literal(1),\n changes: z.array(WorkChangeSchema.extend({ tasks: z.array(WorkTaskV1Schema) }).strict()),\n}).strict();\nexport type WorkV1 = z.infer<typeof WorkV1Schema>;\n\n/** Either format, told apart by `format`: what a reader of exports from several alterspec versions takes. */\nexport const AnyWorkSchema = z.discriminatedUnion('format', [WorkV1Schema, WorkSchema]);\nexport type AnyWork = z.infer<typeof AnyWorkSchema>;\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 { 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\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 /** 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 }\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 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. */\nexport const sessionOf = (loaded: LoadedConfig) => new Session(loaded.config.dispatcher, keyOf(loaded));\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, 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`, format 1 or 2. */\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}\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 };\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 { 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 { Title, list } from './common.js';\nimport { ChangeId, ID_REGEX, type IdKind } from './ids.js';\nimport { TrackCode } 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 * 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 /** 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 .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');\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","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 { 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\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`;\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\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","/**\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","/**\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","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","/** 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","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']),\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});\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 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.task ? { task: filter.task } : filter.about ? { about: filter.about } : { 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/** 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 state = 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 : 'open, waiting for the product side';\n const lines = [`- ${q.id} (${state}${about ? `; ${about}` : ''}): ${one(q.question)}`];\n if (q.outcome === 'assumed' && q.assumption) lines.push(` - Assumed: ${one(q.assumption)}`);\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/** The brief's section: what the task must read before it goes on. */\nexport function questionsSection(questions: Question[]): string[] {\n if (!questions.length) return [];\n const sorted = sortQuestions(questions);\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 '',\n ...sorted.flatMap(questionLines),\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';\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 developer'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 * 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 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 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(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 { 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 mockupPath,\n patternsPath,\n} from '../../src/spec/layout.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.\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}\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 (`changed_by` in\n * `export.json`, in the change map's order) and whether the export's current text differs from this delta's after.\n */\n since?: { changes: string[]; differs: boolean };\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\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 /** Why the dispatcher couldn't be asked. */\n unknown?: 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}\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 /** What this task carries into the spec and which of it the track built already; absent when none or unknown. */\n answers?: TaskAnswer[];\n /** The task's items (work.json format 2); 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 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 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}\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\nfunction objectBrief(\n x: ExportReader,\n key: string,\n entry: DeltaEntry | undefined,\n why?: string,\n later: string[] = [],\n): ObjectBrief {\n const file = x.fileOf(key);\n const held = file !== undefined && x.has(file);\n const brief: ObjectBrief = { key, ...(held ? { file } : {}) };\n if (held && x.shards(file).length) brief.shards = x.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 differs =\n held &&\n entry.exported.after &&\n entry.after !== undefined &&\n !entry.binary &&\n forDiff(key, entry.after).trim() !== forDiff(key, x.read(file)).trim();\n if (later.length || differs) brief.since = { changes: later, differs: !!differs };\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/** The signed-off changes after `change` in the map's order that touched the object (`changed_by` in `export.json`). */\nfunction laterChanges(x: ExportReader, change: string, key: string): string[] {\n const order = x.work.changes.map((c) => c.id);\n const at = order.indexOf(change);\n const touched = x.sources.get(key)?.changed_by ?? [];\n return touched.filter((c) => order.indexOf(c) > at).sort((a, b) => order.indexOf(a) - order.indexOf(b));\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/** 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 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 };\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\nexport function taskContext(\n x: ExportReader,\n task: TaskRef,\n exportDir: string,\n state: CoveredState = {},\n questions?: Question[],\n): TaskContext {\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 const items = (work as { items?: string[] }).items;\n const ctx: TaskContext = {\n task: task.id,\n ...(questions ? { questions } : {}),\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 return {\n item,\n what: itemWhat(x, item, entries.get(itemObject(item)), task.track),\n ...(covered ? { covered } : {}),\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 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) =>\n objectBrief(x, key, entries.get(key), lost.get(key), laterChanges(x, change.id, key)),\n ),\n };\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,\n ...(title ? { title } : {}),\n ...(text ? { text } : {}),\n ...(changed.has(id) ? { changed: true } : {}),\n },\n ];\n };\n\n ctx.whereUsed = whereUsed(x, 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: \\`${path}\\`.` : '',\n ]\n .filter(Boolean)\n .join(' ');\n return [\n {\n id,\n 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(x, id);\n return [\n {\n id,\n path: file,\n ...(title ? { title } : {}),\n ...(changed.has(id) ? { changed: true } : {}),\n ...(note ? { note } : {}),\n },\n ];\n });\n ctx.operations = x.has(OPERATIONS_FILE)\n ? capabilities.flatMap((id): Piece[] => {\n const path = x\n .shards(OPERATIONS_FILE)\n .find((p) => new RegExp(`/\\\\d{2}-${slug(id)}(-|\\\\.md$)`).test(p));\n return path ? [{ id, path, text: shardText(x, path) }] : [];\n })\n : [];\n } else {\n const existing = (p: string) => (x.has(p) ? 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 id,\n file: x.fileOf(id),\n contract: existing(contractPath(id, track.code)),\n page: existing(mockupPath(track.code, id)),\n }));\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(x, id, 'rule', changed)),\n ...roles.map((id) => reachOf(x, id, 'role', changed)),\n ].filter((r): r is Reach => !!r);\n if (!ctx.reach.length) delete ctx.reach;\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, ...(text ? { text } : {}) }];\n });\n return ctx;\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/** The brief as Markdown, for the agent. */\nexport function renderContext(c: TaskContext): string {\n const out: string[] = [\n `# ${c.task}: ${c.change.title}`,\n '',\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 `Paths are relative to the export, ${c.export}.`,\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('');\n if (c.questions?.length) out.push(...questionsSection(c.questions));\n if (c.answers?.length) out.push(...answersSection(c.answers));\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 const done = list.items.filter((i) => i.covered).length;\n out.push(\n `## Checklist (${list.known ? `${done} of ${list.items.length} covered` : `${list.items.length} item${list.items.length === 1 ? '' : 's'}`})`,\n '',\n 'Name an item in `Alterspec-Covers` on the commit with which its tests pass.',\n ...(list.note ? ['', `Covered items unknown: ${list.note}`] : []),\n '',\n ...list.items.map(\n (i) =>\n `- [${i.covered ? 'x' : ' '}] \\`${i.item}\\`: ${i.what}${i.covered ? ` (covered by ${i.covered.slice(0, 12)})` : ''}`,\n ),\n );\n }\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) {\n const later = o.since.changes.length\n ? `Changed since this sign-off by ${o.since.changes.join(', ')} (later in the change map; their deltas are next to their proposals). `\n : '';\n out.push(\n '',\n o.since.differs\n ? `${later}The current text differs from this delta’s after: build to the current file, the checklist follows the current text.`\n : `${later}The current text still equals this delta’s after.`,\n );\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 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 } 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 for (const p of list.filter((p) => p.text))\n out.push(\n `### ${p.id}${p.title ? ` ${p.title}` : ''} (\\`${p.path}\\`)`,\n '',\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}` : ''}`,\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 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 } 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","/**\n * A task is one change on one track, written `CHG-012/BE` (spec 2). Its branch is `task/chg-012-be` and its commits\n * carry the trailer `Alterspec-Task: CHG-012/BE` (spec 12.2); only the client spells either.\n */\n\nexport interface TaskRef {\n id: string;\n change: string;\n track: string;\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})\\/([A-Z]{2,5})$/.exec(text.trim().toUpperCase());\n if (!m)\n throw new TaskError(`\"${text}\" is not a task: write it as CHG-012/BE (the change, a slash, the track).`);\n return { id: `${m[1]}/${m[2]}`, change: m[1]!, track: m[2]! };\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})-([a-z]{2,5})$/.exec(branch?.trim() ?? '');\n return m ? parseTask(`${m[1]}/${m[2]}`) : undefined;\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 { type ClientConfig, ClientConfigSchema, ConfigError, readConfigAt, writeConfig } from './config.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\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 MCP_ENTRY = { command: 'npx', args: ['@alterset/alterspec-client', 'mcp'] };\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\nexport function buildClientPlan(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): 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]: MCP_ENTRY };\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 HOOK_COMMAND = 'npx @alterset/alterspec-client progress --hook';\nexport const HOOK_ENTRY = {\n type: 'command',\n if: 'Bash(git commit *)',\n command: HOOK_COMMAND,\n timeout: 60,\n async: true,\n};\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('@alterset/alterspec-client 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): Outcome {\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 [HOOK_ENTRY];\n });\n if (!found) groups.push({ matcher: 'Bash', hooks: [HOOK_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}\n\nexport interface InitResult {\n config: Outcome;\n mcp: Outcome;\n hook: Outcome;\n approval: Outcome;\n ignore: IgnoreOutcome;\n files: InstallResult;\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, ...given } = opts;\n const existing = readConfigAt(root);\n const defined = Object.fromEntries(Object.entries(given).filter(([, v]) => v !== undefined));\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 : `init needs --dispatcher <url> and --export <path to your clone of the export>${missing.length ? ` (missing or wrong: ${missing.join(', ')})` : ''}.`,\n );\n }\n const before = existing && JSON.stringify(existing);\n const config: Outcome = !existing\n ? 'created'\n : before === JSON.stringify(parsed.data)\n ? 'unchanged'\n : 'updated';\n if (config !== 'unchanged') writeConfig(root, parsed.data);\n const mcp = writeMcpJson(root);\n const hook = writeClaudeSettings(root);\n const ignore = ignoreLocalSettings(root);\n const approval = writeLocalSettings(root);\n const files = install(root, buildClientPlan(version), {\n mode: 'update',\n force,\n version,\n manifestPath: MANIFEST_PATH,\n emptiedFolder: /\\.claude\\/skills\\/alterspec-[^/]+$/,\n });\n return { 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\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 /** 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/**\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.\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: [], answer };\n } catch (e) {\n if (!(e instanceof DispatcherError) || e.code !== 'UNKNOWN_ITEM') throw e;\n const unknown = unknownOf(e);\n const known = covered.filter((c) => !unknown.includes(c.item));\n if (!unknown.length || known.length === covered.length) throw e;\n const answer = await callTool(session, 'report_progress', { id: task.id, covered: known });\n return { task: task.id, covered: known, unknown, answer };\n }\n}\n\ninterface Progress {\n covered: number;\n of: number;\n percent: 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 eta = r.answer.eta as Eta | undefined;\n const count = progress\n ? `${progress.covered} of ${progress.of} items covered (${progress.percent} %)`\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 const lines = [`${r.task}: ${count}${when}.`];\n if (r.unknown.length) lines.unshift(unknownLine(r));\n return lines.join('\\n') + '\\n';\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\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}): 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 await reportProgress(opts.session(), task, covered);\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 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;AAUX,IAAM,YAAY,EAAE,OAAO,EAAE,MAAM,gBAAgB,EAAE,SAAS,+BAA+B,CAAC;AAGrG,IAAM,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc;AACjD,IAAM,MAAM,EAAE,IAAI,KAAK;AAEhB,IAAM,kBAAkB,EAC5B,OAAO;AAAA,EACN,MAAM;AAAA,EACN,MAAM,EAAE,KAAK,CAAC,WAAW,IAAI,CAAC;AAAA;AAAA,EAE9B,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC;AAC9B,CAAC,EACA,OAAO;AAGH,IAAM,iBAAiB,EAC3B,OAAO;AAAA,EACN,OAAO;AAAA;AAAA,EAEP,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO3B,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE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AE,OAAO,KAAK,MAAM,IAAI,CAAC;AAAA,MAC1C,GAAI,KAAK,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;AAAA,IACpC,CAAC;AACD,YAAQ,OAAO,MAAM,KAAK,OAAO,KAAK,UAAU,WAAW,MAAM,CAAC,IAAI,OAAO,cAAc,SAAS,CAAC;AAAA,EACvG,CAAC;AACH;AAEF,QACG,QAAQ,QAAQ,EAChB;AAAA,EACC;AACF,EACC,SAAS,UAAU,2BAA2B,EAC9C,OAAO,UAAU,kCAAkC,EACnD;AAAA,EACC,IAAI,CAAC,IAAY,SAA6B;AAC5C,UAAM,SAAS,WAAW;AAC1B,UAAM,OAAO,WAAW,QAAQ,IAAI,GAAG,OAAO,OAAO,MAAM;AAC3D,UAAM,OAAO,UAAU,EAAE;AACzB,UAAM,QAAQ,aAAa,QAAQ,IAAI,GAAG,MAAM,IAAI;AACpD,QAAI,CAAC;AACH,YAAM,IAAI;AAAA,QACR,GAAG,KAAK,EAAE,uCAAuC,SAAS,IAAI,CAAC,sBAAsB,IAAI,sCAAsC,KAAK,EAAE;AAAA,MACxI;AACF,YAAQ,OAAO;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","existsSync","readFileSync","join","z","z","z","z","z","z","z","join","existsSync","readFileSync","sectionText","body","fence","i","j","z","resolve","z","PART","lines","line","what","slug","kind","e","title","caps","screens","exportDir","idOf","added","named","bearing","list","p","execFileSync","existsSync","join","git","execFileSync","existsSync","join","existsSync","mkdirSync","readFileSync","readdirSync","writeFileSync","join","existsSync","readFileSync","readdirSync","rmSync","writeFileSync","dirname","join","createHash","join","existsSync","readFileSync","dirname","writeFileSync","rmSync","readdirSync","MANIFEST_PATH","readdirSync","join","readFileSync","existsSync","writeFileSync","mkdirSync","git","said","list","execFileSync","createHash","existsSync","mkdirSync","readFileSync","writeFileSync","join","git","execFileSync","named","join","createHash","existsSync","readFileSync","mkdirSync","writeFileSync","resolve","readFileSync","join"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/config.ts","../../src/schemas/work.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/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/questions.ts","../src/mcp.ts","../src/context.ts","../src/git.ts","../src/task.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 { type CoveredState, contextStats, renderContext, startFrom, taskContext } from './context.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 { type TaskRef, branchOf, parseTask } from './task.js';\nimport { packageVersion } from './version.js';\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 { item: string; covered_commit: string | null }[];\n const answers = parseAnswers(answer.answers);\n const from = startFrom(task.track, answer.after);\n return {\n covered: new Map(items.flatMap((i) => (i.covered_commit ? [[i.item, i.covered_commit] as const] : []))),\n ...(answers ? { answers } : {}),\n ...(from.length ? { startFrom: from } : {}),\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',\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('--force', 'replace skills you modified')\n .action(\n run(\n (opts: {\n dispatcher?: string;\n export?: string;\n track?: string[];\n key?: string;\n branch?: string;\n force?: boolean;\n }) => {\n const root = process.cwd();\n const { track, ...rest } = opts;\n const tracks = track\n ?.flatMap((t) => t.split(','))\n .map((t) => t.trim().toUpperCase())\n .filter(Boolean);\n const r = initClient(root, { ...rest, ...(tracks ? { tracks } : {}) }, packageVersion());\n const f = r.files;\n const lines = [\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('', 'Send this public key to the dispatcher’s admin:', key.line, key.fingerprint);\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('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 .action(\n run(async (id: string, opts: { json?: boolean; stats?: 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 ctx = taskContext(\n x,\n task,\n dir,\n await coveredState(loaded, task),\n await changeQuestions(sessionOf(loaded), tasks),\n );\n process.stdout.write(\n opts.stats\n ? contextStats(renderContext(ctx))\n : opts.json\n ? JSON.stringify(ctx, null, 2) + '\\n'\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({ repo, session: () => sessionOf(loadConfig(repo)) });\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('print the questions the dispatcher keeps: a task’s, or without a task your own')\n .argument('[task]', 'the task, e.g. CHG-012/BE')\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 (id: string | undefined, opts: { open?: boolean; about?: string[]; json?: boolean }) => {\n const questions = await listQuestions(sessionOf(loadConfig()), {\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\nexport const ClientConfigSchema = z\n .object({\n /** The dispatcher's URL. */\n dispatcher: z.url(),\n /** The developer's clone of the export repository, relative to this file's folder or absolute. */\n export: z.string().min(1),\n /** The tracks this repository builds: the default of `next_task`. */\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 .strict();\nexport type ClientConfig = z.infer<typeof ClientConfigSchema>;\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.`,\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\nexport const exportDir = ({ root, config }: LoadedConfig) => configPath(root, config.export);\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 2 (alterspec 0.24.0) adds each task's `items`; format 1 is the same without them, and\n * a reader of both 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\nconst ChangeRef = z.string().regex(/^CHG-\\d{3,}$/);\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 .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 })\n .strict();\nexport type WorkChange = z.infer<typeof WorkChangeSchema>;\n\nexport const WORK_FORMAT = 2;\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 .strict();\nexport type Work = z.infer<typeof WorkSchema>;\n\n/** Format 1 (alterspec 0.23): the same without `items`. */\nexport const WorkTaskV1Schema = WorkTaskSchema.omit({ items: true });\nexport type WorkTaskV1 = z.infer<typeof WorkTaskV1Schema>;\n\nexport const WorkV1Schema = WorkSchema.extend({\n format: z.literal(1),\n changes: z.array(WorkChangeSchema.extend({ tasks: z.array(WorkTaskV1Schema) }).strict()),\n}).strict();\nexport type WorkV1 = z.infer<typeof WorkV1Schema>;\n\n/** Either format, told apart by `format`: what a reader of exports from several alterspec versions takes. */\nexport const AnyWorkSchema = z.discriminatedUnion('format', [WorkV1Schema, WorkSchema]);\nexport type AnyWork = z.infer<typeof AnyWorkSchema>;\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 { 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\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 /** 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 }\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 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. */\nexport const sessionOf = (loaded: LoadedConfig) => new Session(loaded.config.dispatcher, keyOf(loaded));\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 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 const keys = [\n ...new Set(state.objects.length ? state.objects : state.bug.cites.map((c) => objectOfItem(c, []))),\n ];\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: state.bug.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. 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 { Title, list } from './common.js';\nimport { ChangeId, ID_REGEX, type IdKind } from './ids.js';\nimport { TrackCode } 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 * 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 /** 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 .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');\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 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, 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`, format 1 or 2. */\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}\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 };\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\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`;\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\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","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']),\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});\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 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.task ? { task: filter.task } : filter.about ? { about: filter.about } : { 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/** 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 state = 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 : 'open, waiting for the product side';\n const lines = [`- ${q.id} (${state}${about ? `; ${about}` : ''}): ${one(q.question)}`];\n if (q.outcome === 'assumed' && q.assumption) lines.push(` - Assumed: ${one(q.assumption)}`);\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/** The brief's section: what the task must read before it goes on. */\nexport function questionsSection(questions: Question[]): string[] {\n if (!questions.length) return [];\n const sorted = sortQuestions(questions);\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 '',\n ...sorted.flatMap(questionLines),\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';\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 developer'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 * 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 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 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(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 { 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 mockupPath,\n patternsPath,\n} from '../../src/spec/layout.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.\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}\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 (`changed_by` in\n * `export.json`, in the change map's order) and whether the export's current text differs from this delta's after.\n */\n since?: { changes: string[]; differs: boolean };\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\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 /** Why the dispatcher couldn't be asked. */\n unknown?: 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}\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 /** What this task carries into the spec and which of it the track built already; absent when none or unknown. */\n answers?: TaskAnswer[];\n /** The task's items (work.json format 2); 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 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 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}\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\nfunction objectBrief(\n x: ExportReader,\n key: string,\n entry: DeltaEntry | undefined,\n why?: string,\n later: string[] = [],\n): ObjectBrief {\n const file = x.fileOf(key);\n const held = file !== undefined && x.has(file);\n const brief: ObjectBrief = { key, ...(held ? { file } : {}) };\n if (held && x.shards(file).length) brief.shards = x.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 differs =\n held &&\n entry.exported.after &&\n entry.after !== undefined &&\n !entry.binary &&\n forDiff(key, entry.after).trim() !== forDiff(key, x.read(file)).trim();\n if (later.length || differs) brief.since = { changes: later, differs: !!differs };\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/** The signed-off changes after `change` in the map's order that touched the object (`changed_by` in `export.json`). */\nfunction laterChanges(x: ExportReader, change: string, key: string): string[] {\n const order = x.work.changes.map((c) => c.id);\n const at = order.indexOf(change);\n const touched = x.sources.get(key)?.changed_by ?? [];\n return touched.filter((c) => order.indexOf(c) > at).sort((a, b) => order.indexOf(a) - order.indexOf(b));\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/** 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 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 };\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\nexport function taskContext(\n x: ExportReader,\n task: TaskRef,\n exportDir: string,\n state: CoveredState = {},\n questions?: Question[],\n): TaskContext {\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 const items = (work as { items?: string[] }).items;\n const ctx: TaskContext = {\n task: task.id,\n ...(questions ? { questions } : {}),\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 return {\n item,\n what: itemWhat(x, item, entries.get(itemObject(item)), task.track),\n ...(covered ? { covered } : {}),\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 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) =>\n objectBrief(x, key, entries.get(key), lost.get(key), laterChanges(x, change.id, key)),\n ),\n };\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,\n ...(title ? { title } : {}),\n ...(text ? { text } : {}),\n ...(changed.has(id) ? { changed: true } : {}),\n },\n ];\n };\n\n ctx.whereUsed = whereUsed(x, 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: \\`${path}\\`.` : '',\n ]\n .filter(Boolean)\n .join(' ');\n return [\n {\n id,\n 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(x, id);\n return [\n {\n id,\n path: file,\n ...(title ? { title } : {}),\n ...(changed.has(id) ? { changed: true } : {}),\n ...(note ? { note } : {}),\n },\n ];\n });\n ctx.operations = x.has(OPERATIONS_FILE)\n ? capabilities.flatMap((id): Piece[] => {\n const path = x\n .shards(OPERATIONS_FILE)\n .find((p) => new RegExp(`/\\\\d{2}-${slug(id)}(-|\\\\.md$)`).test(p));\n return path ? [{ id, path, text: shardText(x, path) }] : [];\n })\n : [];\n } else {\n const existing = (p: string) => (x.has(p) ? 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 id,\n file: x.fileOf(id),\n contract: existing(contractPath(id, track.code)),\n page: existing(mockupPath(track.code, id)),\n }));\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(x, id, 'rule', changed)),\n ...roles.map((id) => reachOf(x, id, 'role', changed)),\n ].filter((r): r is Reach => !!r);\n if (!ctx.reach.length) delete ctx.reach;\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, ...(text ? { text } : {}) }];\n });\n return ctx;\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/** The brief as Markdown, for the agent. */\nexport function renderContext(c: TaskContext): string {\n const out: string[] = [\n `# ${c.task}: ${c.change.title}`,\n '',\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 `Paths are relative to the export, ${c.export}.`,\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('');\n if (c.questions?.length) out.push(...questionsSection(c.questions));\n if (c.answers?.length) out.push(...answersSection(c.answers));\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 const done = list.items.filter((i) => i.covered).length;\n out.push(\n `## Checklist (${list.known ? `${done} of ${list.items.length} covered` : `${list.items.length} item${list.items.length === 1 ? '' : 's'}`})`,\n '',\n 'Name an item in `Alterspec-Covers` on the commit with which its tests pass.',\n ...(list.note ? ['', `Covered items unknown: ${list.note}`] : []),\n '',\n ...list.items.map(\n (i) =>\n `- [${i.covered ? 'x' : ' '}] \\`${i.item}\\`: ${i.what}${i.covered ? ` (covered by ${i.covered.slice(0, 12)})` : ''}`,\n ),\n );\n }\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) {\n const later = o.since.changes.length\n ? `Changed since this sign-off by ${o.since.changes.join(', ')} (later in the change map; their deltas are next to their proposals). `\n : '';\n out.push(\n '',\n o.since.differs\n ? `${later}The current text differs from this delta’s after: build to the current file, the checklist follows the current text.`\n : `${later}The current text still equals this delta’s after.`,\n );\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 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 } 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 for (const p of list.filter((p) => p.text))\n out.push(\n `### ${p.id}${p.title ? ` ${p.title}` : ''} (\\`${p.path}\\`)`,\n '',\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}` : ''}`,\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 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 } 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","/**\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 { 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 { type ClientConfig, ClientConfigSchema, ConfigError, readConfigAt, writeConfig } from './config.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\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 MCP_ENTRY = { command: 'npx', args: ['@alterset/alterspec-client', 'mcp'] };\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\nexport function buildClientPlan(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): 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]: MCP_ENTRY };\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 HOOK_COMMAND = 'npx @alterset/alterspec-client progress --hook';\nexport const HOOK_ENTRY = {\n type: 'command',\n if: 'Bash(git commit *)',\n command: HOOK_COMMAND,\n timeout: 60,\n async: true,\n};\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('@alterset/alterspec-client 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): Outcome {\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 [HOOK_ENTRY];\n });\n if (!found) groups.push({ matcher: 'Bash', hooks: [HOOK_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}\n\nexport interface InitResult {\n config: Outcome;\n mcp: Outcome;\n hook: Outcome;\n approval: Outcome;\n ignore: IgnoreOutcome;\n files: InstallResult;\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, ...given } = opts;\n const existing = readConfigAt(root);\n const defined = Object.fromEntries(Object.entries(given).filter(([, v]) => v !== undefined));\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 : `init needs --dispatcher <url> and --export <path to your clone of the export>${missing.length ? ` (missing or wrong: ${missing.join(', ')})` : ''}.`,\n );\n }\n const before = existing && JSON.stringify(existing);\n const config: Outcome = !existing\n ? 'created'\n : before === JSON.stringify(parsed.data)\n ? 'unchanged'\n : 'updated';\n if (config !== 'unchanged') writeConfig(root, parsed.data);\n const mcp = writeMcpJson(root);\n const hook = writeClaudeSettings(root);\n const ignore = ignoreLocalSettings(root);\n const approval = writeLocalSettings(root);\n const files = install(root, buildClientPlan(version), {\n mode: 'update',\n force,\n version,\n manifestPath: MANIFEST_PATH,\n emptiedFolder: /\\.claude\\/skills\\/alterspec-[^/]+$/,\n });\n return { 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\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 /** 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/**\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.\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: [], answer };\n } catch (e) {\n if (!(e instanceof DispatcherError) || e.code !== 'UNKNOWN_ITEM') throw e;\n const unknown = unknownOf(e);\n const known = covered.filter((c) => !unknown.includes(c.item));\n if (!unknown.length || known.length === covered.length) throw e;\n const answer = await callTool(session, 'report_progress', { id: task.id, covered: known });\n return { task: task.id, covered: known, unknown, answer };\n }\n}\n\ninterface Progress {\n covered: number;\n of: number;\n percent: 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 eta = r.answer.eta as Eta | undefined;\n const count = progress\n ? `${progress.covered} of ${progress.of} items covered (${progress.percent} %)`\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 const lines = [`${r.task}: ${count}${when}.`];\n if (r.unknown.length) lines.unshift(unknownLine(r));\n return lines.join('\\n') + '\\n';\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\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}): 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 await reportProgress(opts.session(), task, covered);\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 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,eAA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KAAK,MAAM,IAAI,CAAC;AAAA,MAC1C,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAwC,IAAI,CAAC;AAAA,MAC9E,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,YAAY,EAAE,IAAI,CAAC;AAAA,IAC1D,CAAC;AACD,YAAQ,OAAO,MAAM,KAAK,OAAO,KAAK,UAAU,MAAM,MAAM,CAAC,IAAI,OAAO,SAAS,IAAI,CAAC;AAAA,EACxF,CAAC;AACH;AAEF,QACG,QAAQ,QAAQ,EAChB;AAAA,EACC;AACF,EACC,SAAS,UAAU,2BAA2B,EAC9C,OAAO,UAAU,kCAAkC,EACnD;AAAA,EACC,IAAI,CAAC,IAAY,SAA6B;AAC5C,UAAM,SAAS,WAAW;AAC1B,UAAM,OAAO,WAAW,QAAQ,IAAI,GAAG,OAAO,OAAO,MAAM;AAC3D,UAAM,OAAO,UAAU,EAAE;AACzB,UAAM,QAAQ,aAAa,QAAQ,IAAI,GAAG,MAAM,IAAI;AACpD,QAAI,CAAC;AACH,YAAM,IAAI;AAAA,QACR,GAAG,KAAK,EAAE,uCAAuC,SAAS,IAAI,CAAC,sBAAsB,IAAI,sCAAsC,KAAK,EAAE;AAAA,MACxI;AACF,YAAQ,OAAO;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","z","sectionText","body","fence","existsSync","readFileSync","join","join","existsSync","readFileSync","i","j","z","resolve","z","PART","lines","line","what","slug","kind","e","title","caps","screens","exportDir","idOf","added","named","bearing","list","p","z","one","exportDir","execFileSync","existsSync","join","git","execFileSync","existsSync","join","existsSync","mkdirSync","readFileSync","readdirSync","writeFileSync","join","existsSync","readFileSync","readdirSync","rmSync","writeFileSync","dirname","join","createHash","join","existsSync","readFileSync","dirname","writeFileSync","rmSync","readdirSync","MANIFEST_PATH","readdirSync","join","readFileSync","existsSync","writeFileSync","mkdirSync","git","said","list","execFileSync","createHash","existsSync","mkdirSync","readFileSync","writeFileSync","join","git","execFileSync","named","join","createHash","existsSync","readFileSync","mkdirSync","writeFileSync","resolve","readFileSync","join","ctx"]}
|