@alterset/alterspec-client 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/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/schemas/work.ts","../../src/changes/delta-record.ts","../../src/lib/frontmatter-split.ts","../../src/spec/layout.ts","../../src/export/paths.ts","../src/config.ts","../../src/lib/diff.ts","../src/context.ts","../src/git.ts","../src/task.ts","../src/install.ts","../../src/install/installer.ts","../../src/install/hash.ts","../src/mcp.ts","../src/open.ts","../src/version.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { KeyRefused, Session } from './auth.js';\nimport { readExport } from '../../src/export/read.js';\nimport {\n CONFIG_FILE,\n type LoadedConfig,\n configPath,\n exportDir,\n loadConfig,\n readConfigAt,\n worktreesDir,\n} from './config.js';\nimport { renderContext, taskContext } from './context.js';\nimport { exportHead, mainBranch, mergedCommit, taskWorktree } from './git.js';\nimport { MCP_JSON, PROMPTS_DIR, initClient } from './install.js';\nimport { runProxy } from './mcp.js';\nimport { OPENABLE, openDispatcher } from './open.js';\nimport { type PublicKey, resolveKey } from './ssh.js';\nimport { 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/** The key of this repository's configuration, else the default one. */\nfunction 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/** 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\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('set the client up in this repository: configuration, the dispatcher in .mcp.json, the skills')\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('--worktrees <path>', 'where task worktrees go (default ../<repo>-tasks)')\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 worktrees?: 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 `Skills 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/skills/alterspec-* and .alterspec-client/, so task worktrees have them too.',\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(new Session(loaded.config.dispatcher, keyOf(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 = new Session(loaded.config.dispatcher, keyOf(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 head = exportHead(exportDir(loadConfig()), 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 .action(\n run((id: string, opts: { json?: boolean }) => {\n const dir = exportDir(loadConfig());\n const ctx = taskContext(readExport(dir), parseTask(id), dir);\n process.stdout.write(opts.json ? JSON.stringify(ctx, null, 2) + '\\n' : renderContext(ctx));\n }),\n );\n\nprogram\n .command('worktree')\n .description('create the task’s branch task/<chg>-<track> from origin/<main>, in a worktree of its own')\n .argument('<task>', 'the task, e.g. CHG-012/BE')\n .option('--here', 'make the branch in this checkout instead of a worktree')\n .action(\n run((id: string, opts: { here?: boolean }) => {\n const loaded = loadConfig();\n const wt = taskWorktree(process.cwd(), parseTask(id), {\n main: mainBranch(process.cwd(), loaded.config.branch),\n worktreesDir: worktreesDir(loaded),\n here: opts.here,\n });\n process.stdout.write(JSON.stringify(wt, null, 2) + '\\n');\n }),\n );\n\nprogram\n .command('merged')\n .description('print the commit on origin/<main> that brought the task in')\n .argument('<task>', 'the task, e.g. CHG-012/BE')\n .action(\n run((id: string) => {\n const loaded = loadConfig();\n const main = mainBranch(process.cwd(), loaded.config.branch);\n const task = parseTask(id);\n const sha = mergedCommit(process.cwd(), task, main);\n if (!sha)\n throw new Error(\n `${task.id} is not on origin/${main} yet: merge its branch, or commit with the trailer \"Alterspec-Task: ${task.id}\", and push.`,\n );\n process.stdout.write(sha + '\\n');\n }),\n );\n\nawait program.parseAsync();\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 PublicKey, 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","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 { 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}\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}\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 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 };\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 /** 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\nexport const ID_PATTERNS = {\n app: '^APP$',\n module: `^MOD-${CODE}$`,\n capability: `^CAP-${CODE}-\\\\d{3}$`,\n screen: `^SCR-${CODE}-\\\\d{2}$`,\n role: `^ROLE-${NAME}$`,\n persona: `^PER-${NAME}$`,\n entity: `^ENT-${NAME}$`,\n rule: `^RULE-(?:${CODE}-)?\\\\d{3}$`,\n flow: '^FLOW-\\\\d{3}$',\n event: `^EVT-${NAME}$`,\n decision: '^DEC-\\\\d{3}$',\n change: '^CHG-\\\\d{3}$',\n integration: `^INT-${NAME}$`,\n nfr: '^NFR-\\\\d{3}$',\n acceptance: `^CAP-${CODE}-\\\\d{3}-AC-\\\\d{2}$`,\n screenAction: '^A\\\\d{2}$',\n experience: `^UX-SCR-${CODE}-\\\\d{2}-${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","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. Sorted, never empty.\n */\n items: z.array(z.string().min(1)).min(1),\n /** The tasks this one waits for, resolved: the same change's `BE` task, and the track's tasks it builds on. */\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 { 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 } 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\nconst CONTRACT =\n /^modules\\/[^/]+\\/screens\\/(?<screen>SCR-[A-Z]{2,6}-\\d{2})\\/experience\\/(?<code>[a-z]{2,5})\\.md$/;\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","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 /** Where `worktree` puts a task's worktree; default `../<repo>-tasks`. */\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 const worktreesDir = ({ root, config }: LoadedConfig) =>\n configPath(root, config.worktrees ?? `../${basename(root)}-tasks`);\n\nexport function writeConfig(root: string, config: ClientConfig): void {\n writeFileSync(join(root, CONFIG_FILE), JSON.stringify(config, null, 2) + '\\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","import { exportChange } from '../../src/changes/delta-record.js';\nimport { type ExportReader, frontMatterOf, idsIn } from '../../src/export/read.js';\nimport { slug } from '../../src/export/paths.js';\nimport { unifiedDiff } from '../../src/lib/diff.js';\nimport type { DeltaEntry } from '../../src/schemas/delta.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 { 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 acceptance criteria, rules, events and\n * operations its capabilities name, for a UI track the screens, their contracts, pages and the channel's design.\n * Texts where the agent needs them to start, paths for the rest, so it 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 text?: 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). */\n diff?: string;\n /** Why the delta could not say, for an object the backfill could not recover. */\n unrecoverable?: string;\n}\n\nexport interface TaskContext {\n task: string;\n export: string;\n change: Pick<WorkChange, 'id' | 'title' | 'signed_off' | 'level' | 'depends_on'>;\n track: WorkTrack;\n after: WorkTask['after'];\n proposal: { path: string; why?: string; what?: string };\n delta?: string;\n objects: ObjectBrief[];\n /** The backend track. */\n acceptance?: Piece[];\n rules?: Piece[];\n events?: Piece[];\n operations?: 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\nfunction objectBrief(x: ExportReader, key: string, entry: DeltaEntry | undefined, why?: string): 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 brief.change = exportChange(entry);\n if (entry.status) brief.status = entry.status;\n if (entry.before !== undefined || entry.after !== undefined) {\n const d = unifiedDiff(entry.before ?? '', entry.after ?? '');\n if (d) brief.diff = d;\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\nexport function taskContext(x: ExportReader, task: TaskRef, exportDir: string): 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 ctx: TaskContext = {\n task: task.id,\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 proposal: {\n path: proposal,\n why: sectionText(x, x.sectionShard(proposal, 'Why')),\n what: sectionText(x, x.sectionShard(proposal, 'What changes')),\n },\n ...(delta ? { delta: proposal.replace(/proposal\\.md$/, 'delta.md') } : {}),\n objects: work.objects.map((key) => objectBrief(x, key, entries.get(key), lost.get(key))),\n };\n\n if (track.kind === 'backend') {\n const capabilities = work.objects.filter((k) => /^CAP-/.test(k) && x.fileOf(k) && x.has(x.fileOf(k)!));\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 items = (ids: string[]) =>\n ids.flatMap((id): Piece[] => {\n const file = x.fileOf(id);\n const path = file && x.itemShard(file, id);\n return path ? [{ id, path, text: shardText(x, path) }] : [];\n });\n ctx.acceptance = capabilities.flatMap((id): Piece[] => {\n const path = x.sectionShard(x.fileOf(id)!, 'Acceptance criteria');\n return path ? [{ id, path, text: sectionText(x, path) }] : [];\n });\n ctx.rules = items(named('rule'));\n ctx.events = items(named('event'));\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 const screens = [...new Set(work.objects.map(screenOf).filter((s): s is string => !!s))];\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 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 out.push('', `## Why (${c.proposal.path})`, '', c.proposal.why || '(none written)');\n out.push('', '## What changes', '', c.proposal.what || '(none written)');\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.diff) out.push('', o.diff.startsWith('binary:') ? o.diff : fence(o.diff, 'diff'));\n out.push('');\n }\n\n const pieces = (title: string, list: Piece[] | undefined) => {\n if (!list?.length) return;\n out.push(`## ${title}`, '');\n for (const p of list) out.push(`### ${p.id} (\\`${p.path}\\`)`, '', p.text ?? '', '');\n };\n pieces('Acceptance criteria', c.acceptance);\n pieces('Rules', c.rules);\n pieces('Events', c.events);\n pieces('Operations for other systems', c.operations);\n\n if (c.screens) {\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","import { execFileSync } from 'node:child_process';\nimport { existsSync, realpathSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { type TaskRef, TRAILER, branchOf, folderOf } from './task.js';\n\n/**\n * The git work 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, a task's branch or worktree, and the commit that brought a task into the\n * track's main branch.\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\nexport interface Worktree {\n path: string;\n branch: string;\n created: boolean;\n}\n\nconst branchExists = (repo: string, branch: string) =>\n tryGit(repo, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]) !== undefined;\n\n/**\n * The task's branch `task/<chg>-<track>` from `origin/<main>`: in a worktree of its own under `worktreesDir` (a task\n * worked in parallel), or `here`, in this checkout (refused while it has uncommitted work). Running it again finds\n * what the first run made.\n */\nexport function taskWorktree(\n repo: string,\n task: TaskRef,\n opts: { main: string; worktreesDir: string; here?: boolean },\n): Worktree {\n const branch = branchOf(task);\n tryGit(repo, ['fetch', '--quiet', 'origin', opts.main]);\n const base = `origin/${opts.main}`;\n if (opts.here) {\n const top = git(repo, ['rev-parse', '--show-toplevel']);\n if (tryGit(repo, ['symbolic-ref', '--short', 'HEAD']) === branch)\n return { path: top, branch, created: false };\n // Untracked files go along with a switch; only changes to tracked files would be in the way.\n if (git(repo, ['status', '--porcelain', '--untracked-files=no']))\n throw new GitError(\n `This checkout has uncommitted work: commit or stash it before switching to ${branch}.`,\n );\n if (branchExists(repo, branch)) {\n git(repo, ['switch', '--quiet', branch]);\n return { path: top, branch, created: false };\n }\n git(repo, ['switch', '--quiet', '--no-track', '-c', branch, base]);\n return { path: top, branch, created: true };\n }\n const path = resolve(opts.worktreesDir, folderOf(task));\n const listed = git(repo, ['worktree', 'list', '--porcelain'])\n .split('\\n')\n .filter((l) => l.startsWith('worktree '))\n .map((l) => real(l.slice('worktree '.length)));\n if (listed.includes(real(path))) return { path, branch, created: false };\n if (branchExists(repo, branch)) git(repo, ['worktree', 'add', '--quiet', path, branch]);\n else git(repo, ['worktree', 'add', '--quiet', '--no-track', '-b', branch, path, base]);\n return { path, branch, created: true };\n}\n\n/** A path with its symbolic links resolved (`/var` is `/private/var` on macOS), when it exists. */\nconst real = (path: string) => (existsSync(path) ? realpathSync(path) : resolve(path));\n\nconst escape = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\/]/g, '\\\\$&');\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 */\nexport function mergedCommit(repo: string, task: TaskRef, main: string): string | undefined {\n tryGit(repo, ['fetch', '--quiet', 'origin', main]);\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 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","import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } 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 the skills 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('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 interface InitOptions extends Partial<ClientConfig> {\n force?: boolean;\n}\n\nexport interface InitResult {\n config: Outcome;\n mcp: Outcome;\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 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, 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","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/** 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 { 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 { 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;;;ACAxB,SAAS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ClC,UAAM,MAAM,YAAY,WAAW,GAAG,GAAG,UAAU,EAAE,GAAG,GAAG;AAC3D,YAAQ,OAAO,MAAM,KAAK,OAAO,KAAK,UAAU,KAAK,MAAM,CAAC,IAAI,OAAO,cAAc,GAAG,CAAC;AAAA,EAC3F,CAAC;AACH;AAEF,QACG,QAAQ,UAAU,EAClB,YAAY,+FAA0F,EACtG,SAAS,UAAU,2BAA2B,EAC9C,OAAO,UAAU,wDAAwD,EACzE;AAAA,EACC,IAAI,CAAC,IAAY,SAA6B;AAC5C,UAAM,SAAS,WAAW;AAC1B,UAAM,KAAK,aAAa,QAAQ,IAAI,GAAG,UAAU,EAAE,GAAG;AAAA,MACpD,MAAM,WAAW,QAAQ,IAAI,GAAG,OAAO,OAAO,MAAM;AAAA,MACpD,cAAc,aAAa,MAAM;AAAA,MACjC,MAAM,KAAK;AAAA,IACb,CAAC;AACD,YAAQ,OAAO,MAAM,KAAK,UAAU,IAAI,MAAM,CAAC,IAAI,IAAI;AAAA,EACzD,CAAC;AACH;AAEF,QACG,QAAQ,QAAQ,EAChB,YAAY,4DAA4D,EACxE,SAAS,UAAU,2BAA2B,EAC9C;AAAA,EACC,IAAI,CAAC,OAAe;AAClB,UAAM,SAAS,WAAW;AAC1B,UAAM,OAAO,WAAW,QAAQ,IAAI,GAAG,OAAO,OAAO,MAAM;AAC3D,UAAM,OAAO,UAAU,EAAE;AACzB,UAAM,MAAM,aAAa,QAAQ,IAAI,GAAG,MAAM,IAAI;AAClD,QAAI,CAAC;AACH,YAAM,IAAI;AAAA,QACR,GAAG,KAAK,EAAE,qBAAqB,IAAI,uEAAuE,KAAK,EAAE;AAAA,MACnH;AACF,YAAQ,OAAO,MAAM,MAAM,IAAI;AAAA,EACjC,CAAC;AACH;AAEF,MAAM,QAAQ,WAAW;","names":["existsSync","readFileSync","join","z","z","z","z","z","z","z","join","existsSync","readFileSync","execFileSync","existsSync","readFileSync","writeFileSync","homedir","join","z","z","execFileSync","join","existsSync","readFileSync","homedir","writeFileSync","i","j","exportDir","list","execFileSync","existsSync","join","resolve","git","execFileSync","existsSync","join","resolve","existsSync","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","resolve","readFileSync"]}
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/lib/diff.ts","../src/context.ts","../src/git.ts","../src/task.ts","../src/install.ts","../../src/install/installer.ts","../../src/install/hash.ts","../src/mcp.ts","../src/open.ts","../src/progress.ts","../src/version.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { KeyRefused, keyOf, sessionOf } from './auth.js';\nimport { readExport } from '../../src/export/read.js';\nimport {\n CONFIG_FILE,\n type LoadedConfig,\n exportDir,\n loadConfig,\n readConfigAt,\n worktreesDir,\n} from './config.js';\nimport { type CoveredState, renderContext, taskContext } from './context.js';\nimport { exportHead, mainBranch, mergedCommit, taskWorktree } from './git.js';\nimport { CLAUDE_SETTINGS, MCP_JSON, PROMPTS_DIR, initClient } from './install.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 { type TaskRef, 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/** Which of the task's items the dispatcher holds covered, or why it couldn't be asked (the brief goes on). */\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 return {\n covered: new Map(items.flatMap((i) => (i.covered_commit ? [[i.item, i.covered_commit] as const] : []))),\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\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('--worktrees <path>', 'where task worktrees go (default ../<repo>-tasks)')\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 worktrees?: 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 `Skills 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-* and .alterspec-client/, so task worktrees have them too.',\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 head = exportHead(exportDir(loadConfig()), 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 .action(\n run(async (id: string, opts: { json?: boolean }) => {\n const loaded = loadConfig();\n const dir = exportDir(loaded);\n const x = readExport(dir);\n const task = parseTask(id);\n const ctx = taskContext(x, task, dir, await coveredState(loaded, task));\n process.stdout.write(opts.json ? JSON.stringify(ctx, null, 2) + '\\n' : renderContext(ctx));\n }),\n );\n\nprogram\n .command('progress')\n .description('report the items the task’s commits cover to the dispatcher')\n .argument('[task]', 'the task, e.g. CHG-012/BE; default the one of the current branch task/<chg>-<track>')\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 'This branch is no task branch (task/<chg>-<track>): name the task, 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('worktree')\n .description('create the task’s branch task/<chg>-<track> from origin/<main>, in a worktree of its own')\n .argument('<task>', 'the task, e.g. CHG-012/BE')\n .option('--here', 'make the branch in this checkout instead of a worktree')\n .action(\n run((id: string, opts: { here?: boolean }) => {\n const loaded = loadConfig();\n const wt = taskWorktree(process.cwd(), parseTask(id), {\n main: mainBranch(process.cwd(), loaded.config.branch),\n worktreesDir: worktreesDir(loaded),\n here: opts.here,\n });\n process.stdout.write(JSON.stringify(wt, null, 2) + '\\n');\n }),\n );\n\nprogram\n .command('merged')\n .description('print the commit on origin/<main> that brought the task in')\n .argument('<task>', 'the task, e.g. CHG-012/BE')\n .action(\n run((id: string) => {\n const loaded = loadConfig();\n const main = mainBranch(process.cwd(), loaded.config.branch);\n const task = parseTask(id);\n const sha = mergedCommit(process.cwd(), task, main);\n if (!sha)\n throw new Error(\n `${task.id} is not on origin/${main} yet: merge its branch, or commit with the trailer \"Alterspec-Task: ${task.id}\", and push.`,\n );\n process.stdout.write(sha + '\\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 /** Where `worktree` puts a task's worktree; default `../<repo>-tasks`. */\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 const worktreesDir = ({ root, config }: LoadedConfig) =>\n configPath(root, config.worktrees ?? `../${basename(root)}-tasks`);\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. Sorted, never empty.\n */\n items: z.array(z.string().min(1)).min(1),\n /** The tasks this one waits for, resolved: the same change's `BE` task, and the track's tasks it builds on. */\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 { 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}\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}\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 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 };\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 /** 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\nexport const ID_PATTERNS = {\n app: '^APP$',\n module: `^MOD-${CODE}$`,\n capability: `^CAP-${CODE}-\\\\d{3}$`,\n screen: `^SCR-${CODE}-\\\\d{2}$`,\n role: `^ROLE-${NAME}$`,\n persona: `^PER-${NAME}$`,\n entity: `^ENT-${NAME}$`,\n rule: `^RULE-(?:${CODE}-)?\\\\d{3}$`,\n flow: '^FLOW-\\\\d{3}$',\n event: `^EVT-${NAME}$`,\n decision: '^DEC-\\\\d{3}$',\n change: '^CHG-\\\\d{3}$',\n integration: `^INT-${NAME}$`,\n nfr: '^NFR-\\\\d{3}$',\n acceptance: `^CAP-${CODE}-\\\\d{3}-AC-\\\\d{2}$`,\n screenAction: '^A\\\\d{2}$',\n experience: `^UX-SCR-${CODE}-\\\\d{2}-${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","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 } 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\nconst CONTRACT =\n /^modules\\/[^/]+\\/screens\\/(?<screen>SCR-[A-Z]{2,6}-\\d{2})\\/experience\\/(?<code>[a-z]{2,5})\\.md$/;\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","/** 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","import { exportChange } from '../../src/changes/delta-record.js';\nimport { type ExportReader, frontMatterOf, idsIn } from '../../src/export/read.js';\nimport { slug } from '../../src/export/paths.js';\nimport { unifiedDiff } from '../../src/lib/diff.js';\nimport { splitFrontMatter } from '../../src/lib/frontmatter-split.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 { 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 acceptance criteria, rules, events and\n * operations its capabilities name, for a UI track the screens, their contracts, pages and the channel's design.\n * Texts where the agent needs them to start, paths for the rest, so it 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 text?: 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). */\n diff?: string;\n /** Why the delta could not say, for an object the backfill could not recover. */\n unrecoverable?: string;\n}\n\nexport interface ChecklistItem {\n /** The item as `work.json` and the `Alterspec-Covers` trailer write it. */\n item: string;\n /** What it is, in one line. */\n what: string;\n /** The commit that covered it, as the dispatcher recorded it. */\n covered?: string;\n}\n\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 /** Why the dispatcher couldn't be asked. */\n unknown?: string;\n}\n\nexport interface TaskContext {\n task: string;\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 proposal: { path: string; why?: string; what?: string };\n delta?: string;\n objects: ObjectBrief[];\n /** The backend track. */\n acceptance?: Piece[];\n rules?: Piece[];\n events?: Piece[];\n operations?: 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\nfunction objectBrief(x: ExportReader, key: string, entry: DeltaEntry | undefined, why?: string): 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 brief.change = exportChange(entry);\n if (entry.status) brief.status = entry.status;\n if (entry.before !== undefined || entry.after !== undefined) {\n const d = unifiedDiff(entry.before ?? '', entry.after ?? '');\n if (d) brief.diff = d;\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. */\nfunction 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/** A criterion's `Then` (and what follows it but `Covers`), from the capability's Acceptance criteria shard. */\nfunction criterionOf(x: ExportReader, cap: string, id: 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 lines = chunk\n .split('\\n')\n .slice(1)\n .map((l) =>\n l\n .replace(/^\\s*[-*]\\s*/, '')\n .replace(/\\*\\*/g, '')\n .trim(),\n )\n .filter(Boolean);\n const then = lines.findIndex((l) => /^Then\\b/.test(l));\n const kept = (then >= 0 ? lines.slice(then) : lines).filter((l) => !/^Covers:/.test(l));\n return kept.join(' ') || undefined;\n}\n\n/** One line saying what an item is, from the export (no YAML parsed: the client carries no YAML parser). */\nexport function itemWhat(x: ExportReader, item: 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]!);\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, id] = state;\n const rule = /^rule-(.+)$/.exec(id!)?.[1];\n return `state \"${id}\" of ${ux} (${named(x, scr!)})${rule ? `: the message of RULE-${rule.toUpperCase()}` : ''}`;\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 const kind = idKind(item);\n return `${kind && KIND_WORDS[kind] ? `${KIND_WORDS[kind]} ` : ''}${named(x, item)}`;\n}\n\nexport function taskContext(\n x: ExportReader,\n task: TaskRef,\n exportDir: string,\n state: CoveredState = {},\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 ...(items\n ? {\n checklist: {\n items: items.map((item) => {\n const covered = state.covered?.get(item);\n return { item, what: itemWhat(x, item), ...(covered ? { covered } : {}) };\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 proposal: {\n path: proposal,\n why: sectionText(x, x.sectionShard(proposal, 'Why')),\n what: sectionText(x, x.sectionShard(proposal, 'What changes')),\n },\n ...(delta ? { delta: proposal.replace(/proposal\\.md$/, 'delta.md') } : {}),\n objects: work.objects.map((key) => objectBrief(x, key, entries.get(key), lost.get(key))),\n };\n\n if (track.kind === 'backend') {\n const capabilities = work.objects.filter((k) => /^CAP-/.test(k) && x.fileOf(k) && x.has(x.fileOf(k)!));\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 items = (ids: string[]) =>\n ids.flatMap((id): Piece[] => {\n const file = x.fileOf(id);\n const path = file && x.itemShard(file, id);\n return path ? [{ id, path, text: shardText(x, path) }] : [];\n });\n ctx.acceptance = capabilities.flatMap((id): Piece[] => {\n const path = x.sectionShard(x.fileOf(id)!, 'Acceptance criteria');\n return path ? [{ id, path, text: sectionText(x, path) }] : [];\n });\n ctx.rules = items(named('rule'));\n ctx.events = items(named('event'));\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 const screens = [...new Set(work.objects.map(screenOf).filter((s): s is string => !!s))];\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 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 out.push('');\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\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.diff) out.push('', o.diff.startsWith('binary:') ? o.diff : fence(o.diff, 'diff'));\n out.push('');\n }\n\n const pieces = (title: string, list: Piece[] | undefined) => {\n if (!list?.length) return;\n out.push(`## ${title}`, '');\n for (const p of list) out.push(`### ${p.id} (\\`${p.path}\\`)`, '', p.text ?? '', '');\n };\n pieces('Acceptance criteria', c.acceptance);\n pieces('Rules', c.rules);\n pieces('Events', c.events);\n pieces('Operations for other systems', c.operations);\n\n if (c.screens) {\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","import { execFileSync } from 'node:child_process';\nimport { existsSync, realpathSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { type TaskRef, TRAILER, branchOf, folderOf } from './task.js';\n\n/**\n * The git work 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, a task's branch or worktree, and the commit that brought a task into the\n * track's main branch.\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\nexport interface Worktree {\n path: string;\n branch: string;\n created: boolean;\n}\n\nconst branchExists = (repo: string, branch: string) =>\n tryGit(repo, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]) !== undefined;\n\n/**\n * The task's branch `task/<chg>-<track>` from `origin/<main>`: in a worktree of its own under `worktreesDir` (a task\n * worked in parallel), or `here`, in this checkout (refused while it has uncommitted work). Running it again finds\n * what the first run made.\n */\nexport function taskWorktree(\n repo: string,\n task: TaskRef,\n opts: { main: string; worktreesDir: string; here?: boolean },\n): Worktree {\n const branch = branchOf(task);\n tryGit(repo, ['fetch', '--quiet', 'origin', opts.main]);\n const base = `origin/${opts.main}`;\n if (opts.here) {\n const top = git(repo, ['rev-parse', '--show-toplevel']);\n if (tryGit(repo, ['symbolic-ref', '--short', 'HEAD']) === branch)\n return { path: top, branch, created: false };\n // Untracked files go along with a switch; only changes to tracked files would be in the way.\n if (git(repo, ['status', '--porcelain', '--untracked-files=no']))\n throw new GitError(\n `This checkout has uncommitted work: commit or stash it before switching to ${branch}.`,\n );\n if (branchExists(repo, branch)) {\n git(repo, ['switch', '--quiet', branch]);\n return { path: top, branch, created: false };\n }\n git(repo, ['switch', '--quiet', '--no-track', '-c', branch, base]);\n return { path: top, branch, created: true };\n }\n const path = resolve(opts.worktreesDir, folderOf(task));\n const listed = git(repo, ['worktree', 'list', '--porcelain'])\n .split('\\n')\n .filter((l) => l.startsWith('worktree '))\n .map((l) => real(l.slice('worktree '.length)));\n if (listed.includes(real(path))) return { path, branch, created: false };\n if (branchExists(repo, branch)) git(repo, ['worktree', 'add', '--quiet', path, branch]);\n else git(repo, ['worktree', 'add', '--quiet', '--no-track', '-b', branch, path, base]);\n return { path, branch, created: true };\n}\n\n/** A path with its symbolic links resolved (`/var` is `/private/var` on macOS), when it exists. */\nconst real = (path: string) => (existsSync(path) ? realpathSync(path) : resolve(path));\n\nconst escape = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\/]/g, '\\\\$&');\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 */\nexport function mergedCommit(repo: string, task: TaskRef, main: string): string | undefined {\n tryGit(repo, ['fetch', '--quiet', 'origin', main]);\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 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 { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } 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`, the progress hook in\n * `.claude/settings.json` and the skills 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('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 interface InitOptions extends Partial<ClientConfig> {\n force?: boolean;\n}\n\nexport interface InitResult {\n config: Outcome;\n mcp: Outcome;\n hook: Outcome;\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 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, 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","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 { 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, 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/** The task of the branch checked out in `repo`, or undefined off a task branch. */\nexport function currentTask(repo: string): TaskRef | undefined {\n try {\n return taskOfBranch(git(repo, ['symbolic-ref', '--short', 'HEAD']));\n } catch {\n return undefined;\n }\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 on a task branch, 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;;;ACAxB,SAAS,oBAAoB;AAC7B,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,YAAY,MAAM,eAAe;AAC7D,SAAS,KAAAA,UAAS;;;ACJlB,SAAS,SAAS;AAUX,IAAM,YAAY,EAAE,OAAO,EAAE,MAAM,gBAAgB,EAAE,SAAS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ACF,UAAM,SAAS,MAAM,eAAe,UAAU,WAAW,CAAC,GAAG,MAAM,aAAa,MAAM,IAAI,CAAC;AAC3F,YAAQ,OAAO,MAAM,KAAK,OAAO,KAAK,UAAU,QAAQ,MAAM,CAAC,IAAI,OAAO,aAAa,MAAM,CAAC;AAAA,EAChG,CAAC,EAAE;AACL,CAAC;AAEH,QACG,QAAQ,UAAU,EAClB,YAAY,+FAA0F,EACtG,SAAS,UAAU,2BAA2B,EAC9C,OAAO,UAAU,wDAAwD,EACzE;AAAA,EACC,IAAI,CAAC,IAAY,SAA6B;AAC5C,UAAM,SAAS,WAAW;AAC1B,UAAM,KAAK,aAAa,QAAQ,IAAI,GAAG,UAAU,EAAE,GAAG;AAAA,MACpD,MAAM,WAAW,QAAQ,IAAI,GAAG,OAAO,OAAO,MAAM;AAAA,MACpD,cAAc,aAAa,MAAM;AAAA,MACjC,MAAM,KAAK;AAAA,IACb,CAAC;AACD,YAAQ,OAAO,MAAM,KAAK,UAAU,IAAI,MAAM,CAAC,IAAI,IAAI;AAAA,EACzD,CAAC;AACH;AAEF,QACG,QAAQ,QAAQ,EAChB,YAAY,4DAA4D,EACxE,SAAS,UAAU,2BAA2B,EAC9C;AAAA,EACC,IAAI,CAAC,OAAe;AAClB,UAAM,SAAS,WAAW;AAC1B,UAAM,OAAO,WAAW,QAAQ,IAAI,GAAG,OAAO,OAAO,MAAM;AAC3D,UAAM,OAAO,UAAU,EAAE;AACzB,UAAM,MAAM,aAAa,QAAQ,IAAI,GAAG,MAAM,IAAI;AAClD,QAAI,CAAC;AACH,YAAM,IAAI;AAAA,QACR,GAAG,KAAK,EAAE,qBAAqB,IAAI,uEAAuE,KAAK,EAAE;AAAA,MACnH;AACF,YAAQ,OAAO,MAAM,MAAM,IAAI;AAAA,EACjC,CAAC;AACH;AAEF,MAAM,QAAQ,WAAW;","names":["z","z","execFileSync","existsSync","readFileSync","writeFileSync","homedir","join","existsSync","readFileSync","join","z","z","z","z","z","z","z","join","existsSync","readFileSync","i","j","exportDir","named","items","list","execFileSync","existsSync","join","resolve","git","execFileSync","existsSync","join","resolve","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","resolve","execFileSync","createHash","existsSync","mkdirSync","readFileSync","writeFileSync","join","git","execFileSync","join","createHash","existsSync","readFileSync","mkdirSync","writeFileSync","resolve","readFileSync"]}