@titan-design/active-work 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/aw.js +75 -32
- package/dist/aw.js.map +1 -1
- package/dist/{chunk-FM2KVFDO.js → chunk-HSGZOWS3.js} +391 -232
- package/dist/chunk-HSGZOWS3.js.map +1 -0
- package/dist/cli.js +2318 -1117
- package/dist/cli.js.map +1 -1
- package/dist/dashboard/index.html +13 -5
- package/docs/cli-reference.md +1090 -0
- package/package.json +20 -2
- package/scripts/gen-cli-reference.mjs +23 -2
- package/dist/chunk-FM2KVFDO.js.map +0 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/commands/archive.ts","../src/commands/new.ts","../src/utils/slug.ts","../src/commands/paths.ts","../src/commands/rename.ts","../src/commands/set.ts","../src/commands/touch.ts","../src/commands/focus.ts","../src/commands/_focus-helpers.ts","../src/commands/pause.ts","../src/commands/unfocus.ts","../src/commands/unpause.ts","../src/commands/task-add.ts","../src/commands/task-delete.ts","../src/commands/task-done.ts","../src/commands/task-edit.ts","../src/commands/task-list.ts","../src/commands/task-reorder.ts","../src/commands/loops.ts","../src/lint/load-tasks.ts","../src/commands/preflight.ts","../src/wrap/sweep.ts","../src/utils/git-worktrees.ts","../src/commands/session-list.ts","../src/commands/sessions-browser.ts","../src/commands/wrap.ts","../src/sessions/session-file.ts","../src/commands/note-add.ts","../src/commands/note-list.ts","../src/commands/artifact-add-branch.ts","../src/commands/artifact-add-stash.ts","../src/commands/artifact-list.ts","../src/commands/artifact-note.ts","../src/commands/artifact-prune.ts","../src/commands/artifact-status.ts","../src/commands/source-list.ts","../src/sources/list.ts","../src/lint/sources.ts","../src/commands/audit.ts","../src/commands/context-graph.ts","../src/commands/list.ts","../src/commands/worktree-set.ts","../src/commands/worktree-set-default.ts","../src/commands/discover.ts","../src/discover/index.ts","../src/discover/run-command.ts","../src/discover/github.ts","../src/discover/git.ts","../src/discover/projects.ts","../src/discover/claude.ts","../src/commands/drop.ts","../src/discover/triaged-log.ts","../src/commands/fold.ts","../src/commands/track.ts","../src/commands/prompt.ts","../src/commands/edit.ts","../src/commands/mcp-serve.ts","../src/server/mcp.ts","../src/server/daemon.ts","../src/server/http.ts","../src/server/health.ts","../src/server/dashboard-routes.ts","../src/server/logger.ts","../src/server/events.ts","../src/server/file-watch.ts","../src/commands/mcp-stop.ts","../src/commands/mcp-restart.ts","../src/commands/mcp-status.ts","../src/commands/mcp-logs.ts","../src/commands/setup.ts","../src/setup/steps.ts","../src/schemas/state.ts","../src/migrations/v1-to-v2-artifacts.ts","../src/migrations/v2-to-v3-open-loops.ts","../src/migrations/v3-proposal.ts","../src/migrations/data/v3-open-loops-proposal.ts","../src/migrations/v3-repairs.ts","../src/migrations/v3-to-v4-worktrees.ts","../src/migrations/index.ts","../src/setup/supervision-systemd.ts","../src/setup/supervision-launchd.ts","../src/setup/supervision.ts","../src/commands/uninstall.ts","../src/commands/doctor.ts","../src/doctor.ts","../src/lint/index.ts","../src/lint/brief.ts","../src/lint/hashes.ts","../src/lint/open-loops.ts","../src/lint/task.ts","../src/lint/zero-loops.ts","../src/commands/migrate.ts","../src/commands/sync.ts","../src/commands/index.ts","../src/registry/cli-options.ts","../src/utils/usage-log.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command, CommanderError } from 'commander';\nimport type { ZodSchema, ZodTypeAny } from 'zod';\nimport { registry } from './registry/index.js';\nimport './commands/index.js'; // populates the registry via side effect\nimport { getActiveRoot } from './utils/paths.js';\nimport { formatError, EXIT } from './errors.js';\nimport {\n successEnvelope,\n errorEnvelope,\n type AnyCommand,\n type CliMeta,\n type CommandContext,\n} from './registry/index.js';\nimport { readCommanderOption } from './registry/cli-options.js';\nimport { color } from './utils/color.js';\nimport { appendUsage } from './utils/usage-log.js';\n\n/**\n * Look up the inner zod type, skipping optional/nullable/default wrappers.\n *\n * Returns the unwrapped def type string (e.g. `'string'`, `'number'`,\n * `'array'`, `'boolean'`, `'enum'`) so the dispatcher can decide how to\n * coerce a raw commander value before zod parsing.\n */\nfunction unwrapZodType(schema: ZodTypeAny | undefined): string | undefined {\n if (!schema) return undefined;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let def = (schema as any)?._zod?.def;\n while (def && (def.type === 'optional' || def.type === 'nullable' || def.type === 'default')) {\n def = def.innerType?._zod?.def;\n }\n return def?.type as string | undefined;\n}\n\n/**\n * Pull the per-field zod schema out of a top-level `z.object({...})`.\n *\n * Returns `undefined` when the schema isn't an object or the field is\n * absent — callers fall back to treating the value as a plain string.\n */\nfunction fieldSchema(args: ZodSchema, name: string): ZodTypeAny | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const shape = (args as any)?._zod?.def?.shape;\n if (!shape) return undefined;\n return shape[name] as ZodTypeAny | undefined;\n}\n\n/** Coerce a raw commander value (string | boolean | undefined) to the type implied by zod. */\nfunction coerce(value: unknown, zodType: string | undefined): unknown {\n if (value === undefined) return undefined;\n if (zodType === 'boolean') {\n return value === true || value === 'true';\n }\n if (zodType === 'number') {\n if (typeof value === 'number') return value;\n const n = Number(value);\n return Number.isNaN(n) ? value : n;\n }\n if (zodType === 'array') {\n if (Array.isArray(value)) return value;\n return String(value)\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n return value;\n}\n\n/** Split a registry command name like `task.add` into commander sub-command path parts. */\nfunction splitName(name: string): string[] {\n return name.split('.');\n}\n\n/**\n * Walk/create a chain of `commander` sub-commands for the given group\n * parts (e.g. `['task']` for `task.add`). Returns the leaf parent so the\n * caller can attach the final action sub-command.\n */\nfunction ensureGroup(root: Command, parts: string[]): Command {\n let current = root;\n for (const part of parts) {\n const existing = current.commands.find((c) => c.name() === part);\n if (existing) {\n current = existing;\n continue;\n }\n const next = current.command(part).description(`${part} commands`);\n current = next;\n }\n return current;\n}\n\n/** Convert a hyphenated CLI flag/positional name to its `args` camelCase / snake_case key. */\nfunction flagToKey(long: string): string {\n // `--ship-target` -> `ship_target` to match zod schemas (snake_case\n // convention in this codebase).\n return long.replace(/^--/, '').replace(/-/g, '_');\n}\n\ninterface InvocationOutput {\n exitCode: number;\n success: boolean;\n}\n\nasync function emitSuccess(cmd: AnyCommand, result: unknown, ctx: CommandContext): Promise<void> {\n if (ctx.format === 'json') {\n process.stdout.write(JSON.stringify(successEnvelope(result, ctx.warnings)) + '\\n');\n return;\n }\n // Human mode: a bare string result is printed raw (e.g. `prompt` dumps the\n // bootstrap text); everything else is pretty-printed JSON for now. Commands\n // can layer richer output later by checking ctx.format themselves.\n if (typeof result === 'string') {\n process.stdout.write(result.endsWith('\\n') ? result : result + '\\n');\n } else if (result !== undefined && result !== null) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n');\n }\n // Touch cmd to avoid an unused-parameter warning when extending later.\n void cmd;\n}\n\nfunction emitError(message: string, code: number, format: 'human' | 'json'): void {\n if (format === 'json') {\n process.stdout.write(JSON.stringify(errorEnvelope(message, code)) + '\\n');\n return;\n }\n process.stderr.write(color.red('error: ' + message) + '\\n');\n}\n\n/**\n * Build the action handler for a single registry command.\n *\n * Captures positionals + options into a plain object, coerces values to\n * the types implied by the command's zod schema, runs the schema, then\n * invokes `cmd.run`. Always writes a usage-log line and exits with the\n * appropriate sysexits code.\n */\nfunction makeAction(\n cmd: AnyCommand,\n rootProgram: Command,\n): (...handlerArgs: unknown[]) => Promise<void> {\n const meta: CliMeta = cmd.cli ?? {};\n const positionalNames = meta.positional ?? [];\n\n return async (...handlerArgs: unknown[]) => {\n const start = Date.now();\n const optsFromCommander = (handlerArgs[positionalNames.length] ?? {}) as Record<\n string,\n unknown\n >;\n const rootOpts = rootProgram.opts() as { json?: boolean };\n const format: 'human' | 'json' = rootOpts.json ? 'json' : 'human';\n\n const raw: Record<string, unknown> = {};\n\n // Positionals: handlerArgs[0..positionalNames.length-1]\n positionalNames.forEach((pname, i) => {\n const value = handlerArgs[i];\n if (value !== undefined) {\n const t = unwrapZodType(fieldSchema(cmd.args, pname));\n raw[pname] = coerce(value, t);\n }\n });\n\n // Options\n if (meta.options) {\n for (const [key, opt] of Object.entries(meta.options)) {\n const value = readCommanderOption(optsFromCommander, opt.long, flagToKey);\n if (value !== undefined) {\n const t = unwrapZodType(fieldSchema(cmd.args, key));\n raw[key] = coerce(value, t);\n }\n }\n }\n\n const ctx: CommandContext = {\n activeRoot: getActiveRoot(),\n warnings: [],\n format,\n cwd: process.cwd(),\n };\n\n const result = await invoke(cmd, raw, ctx, format);\n const duration = Date.now() - start;\n await appendUsage({\n ts: new Date().toISOString(),\n command: cmd.name,\n args: raw,\n duration_ms: duration,\n success: result.success,\n exit_code: result.exitCode,\n });\n process.exit(result.exitCode);\n };\n}\n\nasync function invoke(\n cmd: AnyCommand,\n raw: Record<string, unknown>,\n ctx: CommandContext,\n format: 'human' | 'json',\n): Promise<InvocationOutput> {\n let parsed: unknown;\n try {\n parsed = cmd.args.parse(raw);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n emitError(`invalid arguments: ${message}`, EXIT.USAGE, format);\n return { exitCode: EXIT.USAGE, success: false };\n }\n\n try {\n const result = await cmd.run(parsed, ctx);\n await emitSuccess(cmd, result, ctx);\n return { exitCode: EXIT.OK, success: true };\n } catch (err) {\n const { message, code } = formatError(err);\n emitError(message, code, format);\n return { exitCode: code, success: false };\n }\n}\n\n/**\n * Translate a registry `CliMeta` description of a single option into the\n * commander option-spec string. Boolean zod fields become bare flags\n * (`--flag`); everything else takes an option-argument (`--flag <value>`).\n */\nfunction buildOptionFlags(\n cmd: AnyCommand,\n key: string,\n opt: CliMeta['options'] extends infer M ? (M extends Record<string, infer O> ? O : never) : never,\n): string {\n const zodType = unwrapZodType(fieldSchema(cmd.args, key));\n const short = opt.short ? `${opt.short}, ` : '';\n if (zodType === 'boolean') {\n return `${short}${opt.long}`;\n }\n return `${short}${opt.long} <value>`;\n}\n\n/** Attach one registry command as a sub-command under its appropriate parent. */\nfunction attachCommand(root: Command, cmd: AnyCommand): void {\n const parts = splitName(cmd.name);\n const leafName = parts[parts.length - 1]!;\n const parent = ensureGroup(root, parts.slice(0, -1));\n const sub = parent.command(leafName).description(cmd.description);\n\n const meta: CliMeta = cmd.cli ?? {};\n for (const pname of meta.positional ?? []) {\n const zType = unwrapZodType(fieldSchema(cmd.args, pname));\n const optional =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (fieldSchema(cmd.args, pname) as any)?._zod?.def?.type === 'optional';\n const display = optional ? `[${pname}]` : `<${pname}>`;\n sub.argument(display, `${pname}${zType ? ` (${zType})` : ''}`);\n }\n\n if (meta.options) {\n for (const [key, opt] of Object.entries(meta.options)) {\n const flags = buildOptionFlags(cmd, key, opt);\n if (opt.required) {\n sub.requiredOption(flags, opt.description);\n } else {\n sub.option(flags, opt.description);\n }\n }\n }\n\n sub.action(makeAction(cmd, root));\n}\n\nfunction buildProgram(): Command {\n const program = new Command();\n // exitOverride must be set before sub-commands are created so the\n // setting is inherited via `copyInheritedSettings`. Sub-commands then\n // throw a `CommanderError` instead of calling `process.exit` directly.\n program.exitOverride();\n program\n .name('active-work')\n .description('active-work CLI — durable workspace state for engineering work')\n .version('0.1.0')\n .option('--json', 'emit machine-readable JSON envelope on stdout')\n .addHelpText(\n 'after',\n '\\nRun `active-work <command> --help` for command-specific options.\\n' +\n 'Tip: `aw [slug]` launches Claude with the bootstrap prompt.\\n',\n );\n\n // Sort commands so help output is stable.\n const cmds = Array.from(registry.values()).sort((a, b) => a.name.localeCompare(b.name));\n for (const cmd of cmds) {\n attachCommand(program, cmd);\n }\n\n return program;\n}\n\n/**\n * Entry point. Builds the program and dispatches argv. Commander errors\n * (e.g. unknown command, missing required option) are mapped to the\n * USAGE exit code; everything else surfaces via the per-command action.\n */\nexport async function main(argv: string[]): Promise<void> {\n const program = buildProgram();\n try {\n await program.parseAsync(argv);\n } catch (err) {\n if (err instanceof CommanderError) {\n // Commander already wrote to stderr for help / version. Just exit.\n if (err.code === 'commander.helpDisplayed' || err.code === 'commander.version') {\n process.exit(0);\n }\n process.exit(EXIT.USAGE);\n }\n const { message, code } = formatError(err);\n emitError(message, code, 'human');\n process.exit(code);\n }\n}\n\nvoid main(process.argv);\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { NotFoundError, UsageError, ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n domain: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n from: z.string(),\n to: z.string(),\n});\n\nasync function dirExists(p: string): Promise<boolean> {\n try {\n const stat = await fs.stat(p);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction isInside(child: string, parent: string): boolean {\n const rel = path.relative(parent, child);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n}\n\nfunction yearMonth(): string {\n const d = new Date();\n const y = d.getFullYear();\n const m = String(d.getMonth() + 1).padStart(2, '0');\n return `${y}-${m}`;\n}\n\nexport default defineCommand({\n name: 'archive',\n description: 'Move an initiative out of active root into <archiveRoot>/<domain>/archive/.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug', 'domain'],\n usage: 'active-work archive <slug> <domain>',\n },\n async run(args, ctx) {\n const from = path.resolve(path.join(ctx.activeRoot, args.slug));\n if (!(await dirExists(from))) {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n\n const cwd = path.resolve(process.cwd());\n if (isInside(cwd, from)) {\n throw new UsageError(\n `Refusing to archive: current working directory is inside ${from}. cd elsewhere first.`,\n );\n }\n\n const archiveRoot = path.resolve(ctx.activeRoot, '..');\n const destDir = path.join(archiveRoot, args.domain, 'archive');\n const to = path.join(destDir, `${args.slug}-${yearMonth()}`);\n\n if (await dirExists(to)) {\n throw new ValidationError(`Archive destination already exists: ${to}`);\n }\n\n await fs.mkdir(destDir, { recursive: true });\n\n try {\n await fs.rename(from, to);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'EXDEV') {\n await fs.cp(from, to, { recursive: true });\n await fs.rm(from, { recursive: true, force: true });\n } else {\n throw err;\n }\n }\n\n return { from, to };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport matter from 'gray-matter';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { ArtifactsSchema } from '../schemas/artifacts.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { writeYaml } from '../utils/yaml-io.js';\nimport { today } from '../utils/today.js';\nimport { validateSlug, derivePrefix } from '../utils/slug.js';\nimport { ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n title: z.string().min(1),\n ship_target: z.string().min(1).optional(),\n owner: z.string().min(1).optional(),\n worktree: z.string().min(1).optional(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n dir: z.string(),\n rank: z.number().int().positive(),\n task_prefix: z.string(),\n});\n\nasync function dirExists(p: string): Promise<boolean> {\n try {\n const stat = await fs.stat(p);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\nasync function computeNextRank(activeRoot: string): Promise<number> {\n let entries: string[];\n try {\n entries = await fs.readdir(activeRoot);\n } catch {\n return 1;\n }\n let max = 0;\n for (const entry of entries) {\n if (entry.startsWith('.')) continue;\n const briefPath = path.join(activeRoot, entry, 'brief.md');\n let raw: string;\n try {\n raw = await fs.readFile(briefPath, 'utf8');\n } catch {\n continue;\n }\n const parsed = matter(raw);\n const data = parsed.data as Record<string, unknown>;\n if (data.state === 'focused' && typeof data.rank === 'number' && data.rank > max) {\n max = data.rank;\n }\n }\n return max + 1;\n}\n\nexport default defineCommand({\n name: 'new',\n description: 'Scaffold a new initiative directory.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n title: { long: '--title', description: 'Initiative title', required: true },\n ship_target: { long: '--ship-target', description: 'Ship target (e.g., 2026-Q3)' },\n owner: { long: '--owner', description: 'Owner / handle' },\n worktree: { long: '--worktree', description: 'Default worktree path' },\n },\n usage:\n 'active-work new <slug> --title <title> [--ship-target <t>] [--owner <o>] [--worktree <path>]',\n },\n async run(args, ctx) {\n const slugCheck = validateSlug(args.slug);\n if (!slugCheck.ok) {\n throw new ValidationError(`Invalid slug \"${args.slug}\": ${slugCheck.error}`);\n }\n\n const dir = path.join(ctx.activeRoot, args.slug);\n if (await dirExists(dir)) {\n throw new ValidationError(`Initiative already exists: ${args.slug} (${dir})`);\n }\n\n const rank = await computeNextRank(ctx.activeRoot);\n const task_prefix = derivePrefix(args.slug);\n\n const frontmatter: BriefFrontmatter = {\n schema_version: 1,\n title: args.title,\n updated: today(),\n state: 'focused',\n rank,\n task_prefix,\n ...(args.ship_target ? { ship_target: args.ship_target } : {}),\n ...(args.owner ? { owner: args.owner } : {}),\n };\n\n await fs.mkdir(dir, { recursive: true });\n await fs.mkdir(path.join(dir, 'tasks'), { recursive: true });\n await fs.mkdir(path.join(dir, 'sessions'), { recursive: true });\n await fs.mkdir(path.join(dir, 'sources'), { recursive: true });\n\n const briefBody = `# ${args.title}\\n\\nWhy: ...\\n`;\n await writeFrontmatter(\n path.join(dir, 'brief.md'),\n frontmatter,\n briefBody,\n BriefFrontmatterSchema,\n );\n\n await writeYaml(\n path.join(dir, 'artifacts.yml'),\n ArtifactsSchema.parse({\n // A worktree given at creation is registered, not merely observed, so\n // `aw` resolves a cwd into it and starts there (AW-67).\n worktrees: args.worktree\n ? [\n {\n path: args.worktree,\n repo: args.worktree,\n name: 'main',\n default: true,\n },\n ]\n : [],\n }),\n ArtifactsSchema,\n );\n\n return {\n slug: args.slug,\n dir,\n rank,\n task_prefix,\n };\n },\n});\n","const SLUG_PATTERN = /^[a-z][a-z0-9-]*[a-z0-9]$/;\nconst MIN_LEN = 2;\nconst MAX_LEN = 60;\nconst MAX_PREFIX_LEN = 8;\n\nexport type SlugValidation = { ok: true } | { ok: false; error: string };\n\n/**\n * Validate a kebab-case slug.\n *\n * Rules:\n * - 2-60 characters long\n * - lowercase letters, digits, and `-` only\n * - starts with a letter, ends with a letter or digit\n * - no consecutive dashes\n */\nexport function validateSlug(s: string): SlugValidation {\n if (typeof s !== 'string' || s.length === 0) {\n return { ok: false, error: 'slug must be a non-empty string' };\n }\n if (s.length < MIN_LEN) {\n return { ok: false, error: `slug must be at least ${MIN_LEN} characters` };\n }\n if (s.length > MAX_LEN) {\n return { ok: false, error: `slug must be at most ${MAX_LEN} characters` };\n }\n if (s.includes('--')) {\n return { ok: false, error: 'slug must not contain consecutive dashes' };\n }\n if (!SLUG_PATTERN.test(s)) {\n return {\n ok: false,\n error:\n 'slug must be lowercase kebab-case: start with a letter, end with a letter or digit, allow [a-z0-9-]',\n };\n }\n return { ok: true };\n}\n\n/**\n * Derive a Jira-style task prefix from a slug.\n *\n * Takes the first character of each `-`-separated segment, uppercases each,\n * and concatenates. Truncates to 8 characters.\n *\n * @example\n * derivePrefix('ec-personalization') // 'EP'\n * derivePrefix('inbox') // 'I'\n * derivePrefix('auth-service-v2') // 'ASV'\n */\nexport function derivePrefix(slug: string): string {\n const letters = slug\n .split('-')\n .filter((segment) => segment.length > 0)\n .map((segment) => segment[0]!.toUpperCase())\n .join('');\n return letters.slice(0, MAX_PREFIX_LEN);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { NotFoundError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n brief: z.string(),\n tasks_dir: z.string(),\n sessions_dir: z.string(),\n artifacts: z.string(),\n sources_dir: z.string(),\n});\n\nexport default defineCommand({\n name: 'paths',\n description: 'Print all artifact paths for an initiative.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n usage: 'active-work paths <slug>',\n },\n async run(args, ctx) {\n const dir = path.join(ctx.activeRoot, args.slug);\n try {\n const stat = await fs.stat(dir);\n if (!stat.isDirectory()) {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n } catch (err) {\n if (err instanceof NotFoundError) throw err;\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n\n return {\n brief: path.join(dir, 'brief.md'),\n tasks_dir: path.join(dir, 'tasks'),\n sessions_dir: path.join(dir, 'sessions'),\n artifacts: path.join(dir, 'artifacts.yml'),\n sources_dir: path.join(dir, 'sources'),\n };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { validateSlug } from '../utils/slug.js';\nimport { NotFoundError, ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n old_slug: z.string().min(1),\n new_slug: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n from: z.string(),\n to: z.string(),\n});\n\nasync function dirExists(p: string): Promise<boolean> {\n try {\n const stat = await fs.stat(p);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\nexport default defineCommand({\n name: 'rename',\n description: 'Rename an initiative slug (moves the directory; task_prefix unchanged).',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['old_slug', 'new_slug'],\n usage: 'active-work rename <old-slug> <new-slug>',\n },\n async run(args, ctx) {\n const check = validateSlug(args.new_slug);\n if (!check.ok) {\n throw new ValidationError(`Invalid new slug \"${args.new_slug}\": ${check.error}`);\n }\n\n const from = path.join(ctx.activeRoot, args.old_slug);\n const to = path.join(ctx.activeRoot, args.new_slug);\n\n if (!(await dirExists(from))) {\n throw new NotFoundError(`Initiative not found: ${args.old_slug}`);\n }\n if (await dirExists(to)) {\n throw new ValidationError(`Destination already exists: ${args.new_slug}`);\n }\n\n await fs.rename(from, to);\n return { from, to };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema } from '../schemas/brief.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readRawFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n field: z.string().min(1),\n value: z.unknown(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n field: z.string(),\n value: z.unknown(),\n});\n\nfunction setPath(target: Record<string, unknown>, dotted: string, value: unknown): void {\n const parts = dotted.split('.').filter((p) => p.length > 0);\n if (parts.length === 0) {\n throw new ValidationError('Field path must not be empty');\n }\n let cursor: Record<string, unknown> = target;\n for (let i = 0; i < parts.length - 1; i++) {\n const key = parts[i]!;\n const next = cursor[key];\n if (next === undefined || next === null || typeof next !== 'object' || Array.isArray(next)) {\n const fresh: Record<string, unknown> = {};\n cursor[key] = fresh;\n cursor = fresh;\n } else {\n cursor = next as Record<string, unknown>;\n }\n }\n cursor[parts[parts.length - 1]!] = value;\n}\n\nexport default defineCommand({\n name: 'set',\n description: 'Set a single field on an initiative brief.md frontmatter.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug', 'field', 'value'],\n usage: 'active-work set <slug> <field> <value>',\n },\n async run(args, ctx) {\n const dir = path.join(ctx.activeRoot, args.slug);\n const briefPath = path.join(dir, 'brief.md');\n try {\n await fs.access(briefPath);\n } catch {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n\n await withFileLock(getLockPath(args.slug), async () => {\n const { frontmatter, body } = await readRawFrontmatter(briefPath);\n setPath(frontmatter, args.field, args.value);\n frontmatter.updated = today();\n try {\n await writeFrontmatter(briefPath, frontmatter, body, BriefFrontmatterSchema);\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n throw new ValidationError(\n `Cannot set ${args.field}=${JSON.stringify(args.value)}: ${reason}`,\n );\n }\n });\n\n return { slug: args.slug, field: args.field, value: args.value };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema } from '../schemas/brief.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readRawFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n updated: z.string(),\n});\n\nexport default defineCommand({\n name: 'touch',\n description: \"Stamp `updated: today()` on an initiative's brief.md.\",\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n usage: 'active-work touch <slug>',\n },\n async run(args, ctx) {\n const briefPath = path.join(ctx.activeRoot, args.slug, 'brief.md');\n try {\n await fs.access(briefPath);\n } catch {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n\n const updated = today();\n await withFileLock(getLockPath(args.slug), async () => {\n const { frontmatter, body } = await readRawFrontmatter(briefPath);\n frontmatter.updated = updated;\n await writeFrontmatter(briefPath, frontmatter, body, BriefFrontmatterSchema);\n });\n\n return { slug: args.slug, updated };\n },\n});\n","import { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, UsageError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\nimport { loadAllBriefs, sortSlugs, type InitiativeBrief } from './_focus-helpers.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n rank: z.number().int().positive().optional(),\n});\n\nconst ShiftEntrySchema = z.object({\n slug: z.string(),\n from: z.number().int().positive().optional(),\n to: z.number().int().positive(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n rank: z.number().int().positive(),\n shifted: z.array(ShiftEntrySchema),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\ninterface RankedSlug {\n slug: string;\n rank: number;\n}\n\nfunction buildRanking(briefs: InitiativeBrief[]): RankedSlug[] {\n return briefs\n .filter((b) => b.frontmatter.state === 'focused')\n .map((b) => {\n // schema guarantees rank is present when state is focused\n const rank = b.frontmatter.rank;\n if (rank === undefined) {\n throw new Error(`Focused initiative ${b.slug} is missing rank in brief.md`);\n }\n return { slug: b.slug, rank };\n })\n .sort((a, b) => a.rank - b.rank);\n}\n\nexport default defineCommand<Args, Result>({\n name: 'focus',\n description: 'Promote an initiative into the focused list at a given rank.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n rank: {\n long: '--rank',\n description: 'Target rank (positive integer). Defaults to end of list.',\n },\n },\n usage: 'active-work focus <slug> [--rank N]',\n },\n async run({ slug, rank }) {\n const briefs = await loadAllBriefs();\n const target = briefs.find((b) => b.slug === slug);\n if (!target) {\n throw new NotFoundError(`Initiative not found: ${slug}`);\n }\n\n const ranked = buildRanking(briefs);\n const currentRank = ranked.find((r) => r.slug === slug)?.rank;\n const withoutTarget = ranked.filter((r) => r.slug !== slug);\n\n let desired: number;\n if (rank === undefined) {\n // Append: 1 if no one focused (excluding target), else max+1.\n desired = withoutTarget.length === 0 ? 1 : Math.max(...withoutTarget.map((r) => r.rank)) + 1;\n } else {\n const maxAllowed = withoutTarget.length + 1;\n if (rank > maxAllowed) {\n throw new UsageError(`rank ${rank} exceeds maximum of ${maxAllowed} for the focused list`);\n }\n desired = rank;\n }\n\n // Compute the new ranking.\n const finalRanking: RankedSlug[] = withoutTarget.map((r) => ({\n slug: r.slug,\n rank: r.rank >= desired ? r.rank + 1 : r.rank,\n }));\n finalRanking.push({ slug, rank: desired });\n finalRanking.sort((a, b) => a.rank - b.rank);\n\n // Determine which briefs actually changed so we only rewrite those.\n const changes = new Map<string, { from?: number; to: number }>();\n for (const entry of finalRanking) {\n const prior = ranked.find((r) => r.slug === entry.slug)?.rank;\n const sameState =\n entry.slug === slug\n ? target.frontmatter.state === 'focused' && prior === entry.rank\n : prior === entry.rank;\n if (!sameState) {\n changes.set(entry.slug, { from: prior, to: entry.rank });\n }\n }\n\n // Always include target if it wasn't focused before, even if rank\n // somehow matches (defensive).\n if (!changes.has(slug)) {\n changes.set(slug, { from: currentRank, to: desired });\n }\n\n const updateDate = today();\n const lockOrder = sortSlugs(changes.keys());\n await applyLocked(lockOrder, async () => {\n for (const slugToWrite of lockOrder) {\n const change = changes.get(slugToWrite);\n if (!change) continue;\n const brief = briefs.find((b) => b.slug === slugToWrite);\n if (!brief) {\n throw new NotFoundError(`Initiative ${slugToWrite} disappeared mid-update`);\n }\n const next: BriefFrontmatter = {\n ...brief.frontmatter,\n state: 'focused',\n rank: change.to,\n updated: updateDate,\n };\n // Clear paused-only fields just in case target was paused; safe noop\n // for already-focused entries.\n delete (next as Partial<BriefFrontmatter>).paused_since;\n delete (next as Partial<BriefFrontmatter>).restart_trigger;\n await writeFrontmatter(brief.briefPath, next, brief.body, BriefFrontmatterSchema);\n }\n });\n\n const shifted = [...changes.entries()]\n .filter(([s]) => s !== slug)\n .map(([s, c]) => ({ slug: s, from: c.from, to: c.to }))\n .sort((a, b) => a.to - b.to);\n\n return { slug, rank: desired, shifted };\n },\n});\n\nasync function applyLocked(slugs: string[], fn: () => Promise<void>): Promise<void> {\n // Acquire all locks in deterministic order. Nest withFileLock calls so\n // releases happen in reverse order.\n const recurse = async (index: number): Promise<void> => {\n if (index === slugs.length) {\n await fn();\n return;\n }\n await withFileLock(getLockPath(slugs[index]), () => recurse(index + 1));\n };\n await recurse(0);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getActiveRoot, getInitiativeDir } from '../utils/paths.js';\nimport { readFrontmatter } from '../utils/gray-matter-io.js';\n\nexport interface InitiativeBrief {\n slug: string;\n briefPath: string;\n frontmatter: BriefFrontmatter;\n body: string;\n}\n\n/**\n * Resolve the path to an initiative's `brief.md` for a given slug.\n */\nexport function briefPathFor(slug: string): string {\n return path.join(getInitiativeDir(slug), 'brief.md');\n}\n\n/**\n * Enumerate every initiative directory under the active root by looking for\n * `brief.md`. Returns the parsed and schema-validated frontmatter for each.\n *\n * Directories with no `brief.md` are skipped silently — those are not\n * initiatives. Hidden files (e.g. `.schema-version`) are ignored.\n */\nexport async function loadAllBriefs(): Promise<InitiativeBrief[]> {\n const root = getActiveRoot();\n let entries: string[];\n try {\n entries = await fs.readdir(root);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n\n const briefs: InitiativeBrief[] = [];\n for (const name of entries) {\n if (name.startsWith('.')) continue;\n const briefPath = path.join(root, name, 'brief.md');\n let stat;\n try {\n stat = await fs.stat(briefPath);\n } catch {\n continue;\n }\n if (!stat.isFile()) continue;\n const { frontmatter, body } = await readFrontmatter(briefPath, BriefFrontmatterSchema);\n briefs.push({ slug: name, briefPath, frontmatter, body });\n }\n briefs.sort((a, b) => a.slug.localeCompare(b.slug));\n return briefs;\n}\n\n/**\n * Sort a list of slugs into a deterministic order suitable for locking\n * multiple initiatives' brief.md files simultaneously without deadlock.\n */\nexport function sortSlugs(slugs: Iterable<string>): string[] {\n return [...new Set(slugs)].sort();\n}\n","import { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\nimport { loadAllBriefs, sortSlugs } from './_focus-helpers.js';\n\nconst ISO_DATE_REGEX = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nconst isoDate = z\n .string()\n .regex(ISO_DATE_REGEX, 'since must be YYYY-MM-DD')\n .refine((v) => {\n const parsed = new Date(v);\n if (Number.isNaN(parsed.getTime())) return false;\n return parsed.toISOString().slice(0, 10) === v;\n }, 'since must be a valid calendar date');\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n since: isoDate,\n restart_trigger: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n paused_since: z.string(),\n restart_trigger: z.string(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'pause',\n description: 'Mark an initiative as paused with required restart metadata.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n since: {\n long: '--since',\n description: 'Pause-since date (YYYY-MM-DD).',\n required: true,\n },\n 'restart-trigger': {\n long: '--restart-trigger',\n description: 'What event should cause this initiative to resume.',\n required: true,\n },\n },\n usage: 'active-work pause <slug> --since YYYY-MM-DD --restart-trigger \"...\"',\n },\n async run({ slug, since, restart_trigger }) {\n const briefs = await loadAllBriefs();\n const target = briefs.find((b) => b.slug === slug);\n if (!target) {\n throw new NotFoundError(`Initiative not found: ${slug}`);\n }\n\n const wasFocused = target.frontmatter.state === 'focused';\n const survivors = wasFocused\n ? briefs\n .filter((b) => b.frontmatter.state === 'focused' && b.slug !== slug)\n .map((b) => {\n if (b.frontmatter.rank === undefined) {\n throw new Error(`Focused initiative ${b.slug} missing rank`);\n }\n return { slug: b.slug, rank: b.frontmatter.rank };\n })\n .sort((a, b) => a.rank - b.rank)\n : [];\n\n const renumberOps: { slug: string; to: number }[] = [];\n survivors.forEach((s, i) => {\n const newRank = i + 1;\n if (s.rank !== newRank) {\n renumberOps.push({ slug: s.slug, to: newRank });\n }\n });\n\n const updateDate = today();\n const slugsToLock = sortSlugs([slug, ...renumberOps.map((r) => r.slug)]);\n\n await applyLocked(slugsToLock, async () => {\n const paused: BriefFrontmatter = {\n ...target.frontmatter,\n state: 'paused',\n paused_since: since,\n restart_trigger,\n updated: updateDate,\n };\n delete (paused as Partial<BriefFrontmatter>).rank;\n await writeFrontmatter(target.briefPath, paused, target.body, BriefFrontmatterSchema);\n\n for (const op of renumberOps) {\n const brief = briefs.find((b) => b.slug === op.slug);\n if (!brief) continue;\n const next: BriefFrontmatter = {\n ...brief.frontmatter,\n state: 'focused',\n rank: op.to,\n updated: updateDate,\n };\n await writeFrontmatter(brief.briefPath, next, brief.body, BriefFrontmatterSchema);\n }\n });\n\n return { slug, paused_since: since, restart_trigger };\n },\n});\n\nasync function applyLocked(slugs: string[], fn: () => Promise<void>): Promise<void> {\n const recurse = async (index: number): Promise<void> => {\n if (index === slugs.length) {\n await fn();\n return;\n }\n await withFileLock(getLockPath(slugs[index]), () => recurse(index + 1));\n };\n await recurse(0);\n}\n","import { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, UsageError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\nimport { loadAllBriefs, sortSlugs } from './_focus-helpers.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n});\n\nconst RenumberEntrySchema = z.object({\n slug: z.string(),\n from: z.number().int().positive(),\n to: z.number().int().positive(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n renumbered: z.array(RenumberEntrySchema),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'unfocus',\n description: 'Demote a focused initiative to backburner and renumber survivors.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n usage: 'active-work unfocus <slug>',\n },\n async run({ slug }) {\n const briefs = await loadAllBriefs();\n const target = briefs.find((b) => b.slug === slug);\n if (!target) {\n throw new NotFoundError(`Initiative not found: ${slug}`);\n }\n if (target.frontmatter.state !== 'focused') {\n throw new UsageError(`Cannot unfocus ${slug}: state is ${target.frontmatter.state}`);\n }\n\n const survivors = briefs\n .filter((b) => b.frontmatter.state === 'focused' && b.slug !== slug)\n .map((b) => {\n if (b.frontmatter.rank === undefined) {\n throw new Error(`Focused initiative ${b.slug} missing rank`);\n }\n return { slug: b.slug, rank: b.frontmatter.rank };\n })\n .sort((a, b) => a.rank - b.rank);\n\n const renumberOps: { slug: string; from: number; to: number }[] = [];\n survivors.forEach((s, i) => {\n const newRank = i + 1;\n if (s.rank !== newRank) {\n renumberOps.push({ slug: s.slug, from: s.rank, to: newRank });\n }\n });\n\n const updateDate = today();\n const slugsToLock = sortSlugs([slug, ...renumberOps.map((r) => r.slug)]);\n\n await applyLocked(slugsToLock, async () => {\n // Write target.\n const cleared: BriefFrontmatter = {\n ...target.frontmatter,\n state: 'backburner',\n updated: updateDate,\n };\n delete (cleared as Partial<BriefFrontmatter>).rank;\n await writeFrontmatter(target.briefPath, cleared, target.body, BriefFrontmatterSchema);\n\n // Renumber survivors that actually moved.\n for (const op of renumberOps) {\n const brief = briefs.find((b) => b.slug === op.slug);\n if (!brief) continue;\n const next: BriefFrontmatter = {\n ...brief.frontmatter,\n state: 'focused',\n rank: op.to,\n updated: updateDate,\n };\n await writeFrontmatter(brief.briefPath, next, brief.body, BriefFrontmatterSchema);\n }\n });\n\n return { slug, renumbered: renumberOps };\n },\n});\n\nasync function applyLocked(slugs: string[], fn: () => Promise<void>): Promise<void> {\n const recurse = async (index: number): Promise<void> => {\n if (index === slugs.length) {\n await fn();\n return;\n }\n await withFileLock(getLockPath(slugs[index]), () => recurse(index + 1));\n };\n await recurse(0);\n}\n","import { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, UsageError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\nimport { loadAllBriefs } from './_focus-helpers.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'unpause',\n description: 'Move a paused initiative back to backburner.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n usage: 'active-work unpause <slug>',\n },\n async run({ slug }) {\n const briefs = await loadAllBriefs();\n const target = briefs.find((b) => b.slug === slug);\n if (!target) {\n throw new NotFoundError(`Initiative not found: ${slug}`);\n }\n if (target.frontmatter.state !== 'paused') {\n throw new UsageError(`Cannot unpause ${slug}: state is ${target.frontmatter.state}`);\n }\n\n await withFileLock(getLockPath(slug), async () => {\n const next: BriefFrontmatter = {\n ...target.frontmatter,\n state: 'backburner',\n updated: today(),\n };\n delete (next as Partial<BriefFrontmatter>).paused_since;\n delete (next as Partial<BriefFrontmatter>).restart_trigger;\n delete (next as Partial<BriefFrontmatter>).rank;\n await writeFrontmatter(target.briefPath, next, target.body, BriefFrontmatterSchema);\n });\n\n return { slug };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { TaskSchema, type Task } from '../schemas/task.js';\nimport { getActiveRoot, getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readRawFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { BriefFrontmatterSchema, TaskSeqSchema } from '../schemas/brief.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, ValidationError } from '../errors.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n title: z.string().min(1),\n priority: z.number().int().positive().optional(),\n severity: z.enum(['critical', 'high', 'medium', 'low']).optional(),\n estimate: z.number().positive().optional(),\n done_when: z.string().min(1).optional(),\n tags: z.array(z.string()).optional(),\n notes: z.string().optional(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst PREFIX_RE = /^[A-Z][A-Z0-9]*$/;\n\ninterface Brief {\n slug: string;\n path: string;\n frontmatter: Record<string, unknown>;\n body: string;\n prefix: string;\n}\n\nasync function loadBrief(slug: string): Promise<Brief> {\n const briefPath = path.join(getInitiativeDir(slug), 'brief.md');\n let raw: { frontmatter: Record<string, unknown>; body: string };\n try {\n raw = await readRawFrontmatter(briefPath);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new NotFoundError(`Initiative not found: ${slug}`);\n }\n throw err;\n }\n const prefix = raw.frontmatter.task_prefix;\n if (typeof prefix !== 'string' || !PREFIX_RE.test(prefix)) {\n throw new ValidationError(`Brief at ${briefPath} is missing a valid task_prefix`);\n }\n return {\n slug,\n path: briefPath,\n frontmatter: raw.frontmatter,\n body: raw.body,\n prefix,\n };\n}\n\nasync function listTaskFiles(slug: string): Promise<string[]> {\n const dir = path.join(getInitiativeDir(slug), 'tasks');\n try {\n const entries = await fs.readdir(dir);\n return entries.filter((e) => e.endsWith('.yml'));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n}\n\nasync function loadExistingTasks(slug: string): Promise<Task[]> {\n const files = await listTaskFiles(slug);\n const dir = path.join(getInitiativeDir(slug), 'tasks');\n const tasks: Task[] = [];\n for (const file of files) {\n const task = await readYaml(path.join(dir, file), TaskSchema);\n tasks.push(task);\n }\n return tasks;\n}\n\nfunction maxOnDiskTaskNumber(prefix: string, existing: Task[]): number {\n let max = 0;\n const re = new RegExp(`^${prefix}-(\\\\d+)$`);\n for (const t of existing) {\n const m = re.exec(t.id);\n if (m) {\n const n = Number.parseInt(m[1]!, 10);\n if (n > max) max = n;\n }\n }\n return max;\n}\n\n// `Infinity` and `NaN` both stringify to `null` through JSON, which would hide\n// the very value the operator has to find in the file.\nfunction describeValue(value: unknown): string {\n return typeof value === 'number' ? String(value) : JSON.stringify(value);\n}\n\nfunction taskSeqRepair(brief: Brief, value: unknown, onDisk: number): string {\n return (\n `Invalid task_seq (${describeValue(value)}) in ${brief.path}. ` +\n 'task_seq is the high-water mark for task ids and must be a positive whole ' +\n 'number no larger than Number.MAX_SAFE_INTEGER. Task ids cannot be allocated ' +\n `until it is repaired: the highest id on disk is ${brief.prefix}-${onDisk}, so run ` +\n `\\`active-work set ${brief.slug} task_seq <n>\\` with n at least ${Math.max(onDisk, 1)} ` +\n '— higher if ids above that were issued and their tasks later deleted.'\n );\n}\n\n/**\n * ABSENT is a legitimate back-compat path: briefs written before the field\n * existed allocate from the on-disk max. Any other invalid value is corruption,\n * and silently falling back would \"repair\" it *downward* — below an id that has\n * already been issued — so it is reported instead of guessed at.\n */\nfunction readTaskSeq(brief: Brief, onDisk: number): number {\n const raw = brief.frontmatter.task_seq;\n if (raw === undefined) return 0;\n const parsed = TaskSeqSchema.safeParse(raw);\n if (!parsed.success) {\n throw new ValidationError(taskSeqRepair(brief, raw, onDisk));\n }\n return parsed.data;\n}\n\n// Ids must never be reissued, even after `task delete` removes the file\n// that used the highest number. Allocate from the persisted `task_seq`\n// high-water mark (falling back to the on-disk max for briefs written\n// before the field existed) and persist the new mark before returning.\nasync function allocateTaskNumber(brief: Brief, existing: Task[]): Promise<number> {\n const onDisk = maxOnDiskTaskNumber(brief.prefix, existing);\n const next = Math.max(readTaskSeq(brief, onDisk), onDisk) + 1;\n const frontmatter: Record<string, unknown> = {\n ...brief.frontmatter,\n task_seq: next,\n };\n await writeFrontmatter(brief.path, frontmatter, brief.body, BriefFrontmatterSchema);\n return next;\n}\n\nfunction nextPriority(existing: Task[]): number {\n let max = 0;\n for (const t of existing) {\n if (t.priority > max) max = t.priority;\n }\n return max + 1;\n}\n\nexport default defineCommand<Args, Task>({\n name: 'task.add',\n description: 'Create a new task in an initiative',\n args: ArgsSchema,\n result: TaskSchema,\n cli: {\n positional: ['slug'],\n options: {\n title: { long: '--title', description: 'Task title', required: true },\n priority: { long: '--priority', description: 'Priority (positive int)' },\n severity: {\n long: '--severity',\n description: 'critical|high|medium|low',\n },\n estimate: { long: '--estimate', description: 'Estimate (hours)' },\n done_when: {\n long: '--done-when',\n description: 'Definition of done',\n },\n tags: { long: '--tags', description: 'Comma-separated tag list' },\n notes: { long: '--notes', description: 'Free-form notes' },\n },\n },\n async run(args) {\n // Touch activeRoot so it's resolved before locking.\n getActiveRoot();\n return withFileLock(getLockPath(args.slug), async () => {\n const brief = await loadBrief(args.slug);\n const existing = await loadExistingTasks(args.slug);\n const n = await allocateTaskNumber(brief, existing);\n const id = `${brief.prefix}-${n}`;\n const priority = args.priority ?? nextPriority(existing);\n const date = today();\n const task: Task = {\n id,\n title: args.title,\n priority,\n severity: args.severity,\n estimate: args.estimate,\n done_when: args.done_when,\n status: 'open',\n tags: args.tags,\n notes: args.notes,\n created: date,\n updated: date,\n done_at: null,\n };\n const taskDir = path.join(getInitiativeDir(args.slug), 'tasks');\n await fs.mkdir(taskDir, { recursive: true });\n await writeYaml(path.join(taskDir, `${id}.yml`), task, TaskSchema);\n return task;\n });\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { getActiveRoot, getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { NotFoundError } from '../errors.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n id: z.string().min(1),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n id: z.string(),\n deleted: z.literal(true),\n});\n\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'task.delete',\n description: 'Hard delete a task file (prefer task.done in normal use)',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug', 'id'],\n },\n async run(args) {\n getActiveRoot();\n return withFileLock(getLockPath(args.slug), async () => {\n const file = path.join(getInitiativeDir(args.slug), 'tasks', `${args.id}.yml`);\n try {\n await fs.unlink(file);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new NotFoundError(`Task not found: ${args.id}`);\n }\n throw err;\n }\n return { id: args.id, deleted: true };\n });\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { TaskSchema, type Task } from '../schemas/task.js';\nimport { getActiveRoot, getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError } from '../errors.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n id: z.string().min(1),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\nexport default defineCommand<Args, Task>({\n name: 'task.done',\n description: 'Mark a task as done',\n args: ArgsSchema,\n result: TaskSchema,\n cli: {\n positional: ['slug', 'id'],\n },\n async run(args) {\n getActiveRoot();\n return withFileLock(getLockPath(args.slug), async () => {\n const file = path.join(getInitiativeDir(args.slug), 'tasks', `${args.id}.yml`);\n let task: Task;\n try {\n task = await readYaml(file, TaskSchema);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new NotFoundError(`Task not found: ${args.id}`);\n }\n throw err;\n }\n const date = today();\n const updated: Task = {\n ...task,\n status: 'done',\n done_at: date,\n updated: date,\n };\n await writeYaml(file, updated, TaskSchema);\n return updated;\n });\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { TaskSchema, type Task } from '../schemas/task.js';\nimport { getActiveRoot, getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, UsageError, ValidationError } from '../errors.js';\n\nconst EDITABLE_FIELDS = [\n 'title',\n 'priority',\n 'severity',\n 'estimate',\n 'done_when',\n 'tags',\n 'notes',\n 'status',\n] as const;\n\ntype EditableField = (typeof EDITABLE_FIELDS)[number];\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n id: z.string().min(1),\n field: z.string().min(1),\n value: z.unknown(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\nfunction isEditable(field: string): field is EditableField {\n return (EDITABLE_FIELDS as readonly string[]).includes(field);\n}\n\nexport default defineCommand<Args, Task>({\n name: 'task.edit',\n description: 'Edit a single field on a task',\n args: ArgsSchema,\n result: TaskSchema,\n cli: {\n positional: ['slug', 'id', 'field', 'value'],\n },\n async run(args) {\n if (!isEditable(args.field)) {\n throw new UsageError(\n `Field is not editable: ${args.field} (allowed: ${EDITABLE_FIELDS.join(', ')})`,\n );\n }\n getActiveRoot();\n return withFileLock(getLockPath(args.slug), async () => {\n const file = path.join(getInitiativeDir(args.slug), 'tasks', `${args.id}.yml`);\n let task: Task;\n try {\n task = await readYaml(file, TaskSchema);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new NotFoundError(`Task not found: ${args.id}`);\n }\n throw err;\n }\n const date = today();\n const next: Record<string, unknown> = { ...task, [args.field]: args.value };\n next.updated = date;\n if (args.field === 'status' && args.value === 'done') {\n next.done_at = date;\n }\n const parsed = TaskSchema.safeParse(next);\n if (!parsed.success) {\n throw new ValidationError(`Invalid value for ${args.field}: ${parsed.error.message}`);\n }\n await writeYaml(file, parsed.data, TaskSchema);\n return parsed.data;\n });\n },\n});\n","import { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { TaskSchema, type Task } from '../schemas/task.js';\nimport { getActiveRoot, getInitiativeDir } from '../utils/paths.js';\nimport { readYaml } from '../utils/yaml-io.js';\nimport { UsageError } from '../errors.js';\n\nconst StatusFilter = z.enum(['open', 'done', 'all']).default('open');\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1).optional(),\n all_initiatives: z.boolean().optional(),\n tag: z.string().optional(),\n severity: z.enum(['critical', 'high', 'medium', 'low']).optional(),\n status: StatusFilter.optional(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\ntype TaskWithSlug = Task & { slug: string };\n\nconst ResultSchema = z.object({\n tasks: z.array(TaskSchema.extend({ slug: z.string() })),\n});\n\ntype Result = z.infer<typeof ResultSchema>;\n\nasync function listSlugs(): Promise<string[]> {\n const root = getActiveRoot();\n let entries: Dirent[];\n try {\n entries = await fs.readdir(root, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n return entries.filter((e) => e.isDirectory()).map((e) => e.name);\n}\n\nasync function loadTasksForSlug(slug: string): Promise<TaskWithSlug[]> {\n const dir = path.join(getInitiativeDir(slug), 'tasks');\n let files: string[];\n try {\n files = await fs.readdir(dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const tasks: TaskWithSlug[] = [];\n for (const file of files) {\n if (!file.endsWith('.yml')) continue;\n const task = await readYaml(path.join(dir, file), TaskSchema);\n tasks.push({ ...task, slug });\n }\n return tasks;\n}\n\nexport default defineCommand<Args, Result>({\n name: 'task.list',\n description: 'List tasks for an initiative or across all initiatives',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n all_initiatives: {\n long: '--all-initiatives',\n description: 'Scan every initiative under the active root',\n },\n tag: { long: '--tag', description: 'Filter by tag membership' },\n severity: {\n long: '--severity',\n description: 'Filter by severity (critical|high|medium|low)',\n },\n status: {\n long: '--status',\n description: 'open (default), done, or all',\n },\n },\n },\n async run(args) {\n const status = args.status ?? 'open';\n const slugs: string[] = args.all_initiatives\n ? await listSlugs()\n : (() => {\n if (!args.slug) {\n throw new UsageError('task.list requires --all-initiatives or a slug');\n }\n return [args.slug];\n })();\n\n let collected: TaskWithSlug[] = [];\n for (const slug of slugs) {\n const tasks = await loadTasksForSlug(slug);\n collected = collected.concat(tasks);\n }\n\n const filtered = collected.filter((t) => {\n if (status !== 'all' && t.status !== status) return false;\n if (args.tag && !(t.tags ?? []).includes(args.tag)) return false;\n if (args.severity && t.severity !== args.severity) return false;\n return true;\n });\n\n filtered.sort((a, b) => a.priority - b.priority);\n return { tasks: filtered };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { TaskSchema, type Task } from '../schemas/task.js';\nimport { getActiveRoot, getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError } from '../errors.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n id: z.string().min(1),\n new_priority: z.number().int().positive(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ShiftedSchema = z.object({\n id: z.string(),\n from: z.number().int(),\n to: z.number().int(),\n});\n\nconst ResultSchema = z.object({\n id: z.string(),\n from: z.number().int(),\n to: z.number().int(),\n shifted: z.array(ShiftedSchema),\n});\n\ntype Result = z.infer<typeof ResultSchema>;\n\nasync function loadAllTasks(slug: string): Promise<Array<{ task: Task; file: string }>> {\n const dir = path.join(getInitiativeDir(slug), 'tasks');\n let files: string[];\n try {\n files = await fs.readdir(dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const out: Array<{ task: Task; file: string }> = [];\n for (const file of files) {\n if (!file.endsWith('.yml')) continue;\n const full = path.join(dir, file);\n out.push({ task: await readYaml(full, TaskSchema), file: full });\n }\n return out;\n}\n\nexport default defineCommand<Args, Result>({\n name: 'task.reorder',\n description: 'Move a task to a new priority and shift siblings down',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug', 'id', 'new_priority'],\n },\n async run(args) {\n getActiveRoot();\n return withFileLock(getLockPath(args.slug), async () => {\n const entries = await loadAllTasks(args.slug);\n const target = entries.find((e) => e.task.id === args.id);\n if (!target) {\n throw new NotFoundError(`Task not found: ${args.id}`);\n }\n const oldPriority = target.task.priority;\n const newPriority = args.new_priority;\n const shifted: Array<{ id: string; from: number; to: number }> = [];\n const date = today();\n\n if (oldPriority === newPriority) {\n return { id: args.id, from: oldPriority, to: newPriority, shifted };\n }\n\n const writes: Array<{ task: Task; file: string }> = [];\n\n for (const entry of entries) {\n if (entry.task.id === args.id) continue;\n if (entry.task.priority >= newPriority) {\n const before = entry.task.priority;\n const after = before + 1;\n const next: Task = {\n ...entry.task,\n priority: after,\n updated: date,\n };\n writes.push({ task: next, file: entry.file });\n shifted.push({ id: entry.task.id, from: before, to: after });\n }\n }\n\n const targetNext: Task = {\n ...target.task,\n priority: newPriority,\n updated: date,\n };\n writes.push({ task: targetNext, file: target.file });\n\n for (const w of writes) {\n await writeYaml(w.file, w.task, TaskSchema);\n }\n\n return { id: args.id, from: oldPriority, to: newPriority, shifted };\n });\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport {\n deriveOpenLoopsFrom,\n deriveResolvedLoopsFrom,\n loadSessionsFromDir,\n} from '../sessions/open-loops.js';\nimport { loadTasks } from '../lint/load-tasks.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n state: z.enum(['open', 'resolved', 'abandoned', 'all']).default('open'),\n});\n\nconst OpenLoopSchema = z.object({\n ref: z.string(),\n text: z.string(),\n kind: z.enum(['task', 'pr', 'prose']),\n target_ref: z.string().optional(),\n session_file: z.string(),\n opened_at: z.string(),\n age_days: z.number().int().nonnegative(),\n});\n\nconst ResolvedLoopSchema = z.object({\n ref: z.string(),\n text: z.string(),\n kind: z.enum(['task', 'pr', 'prose']),\n outcome: z.enum(['done', 'abandoned']),\n note: z.string().optional(),\n session_file: z.string(),\n closed_by: z.string(),\n opened_at: z.string(),\n closed_at: z.string(),\n age_days: z.number().int().nonnegative(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n open: z.array(OpenLoopSchema),\n resolved: z.array(ResolvedLoopSchema),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'loops',\n description:\n \"List an initiative's open-loop ledger. Open loops are the unresolved remainder; resolved ones carry the outcome and the reason they were closed, which the bootstrap only surfaces for recent abandonments.\",\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n state: {\n long: '--state',\n description: \"'open' (default) | 'resolved' | 'abandoned' | 'all'\",\n },\n },\n usage: 'active-work loops <slug> [--state open|resolved|abandoned|all]',\n },\n async run(args, ctx) {\n const initiativeDir = path.join(ctx.activeRoot, args.slug);\n const [loaded, tasks] = await Promise.all([\n loadSessionsFromDir(initiativeDir),\n loadTasks(initiativeDir),\n ]);\n const opts = { now: new Date(), tasks };\n const wantOpen = args.state === 'open' || args.state === 'all';\n const wantResolved = args.state !== 'open';\n\n const open = wantOpen\n ? deriveOpenLoopsFrom(loaded, opts).map((loop) => ({\n ref: loop.ref,\n text: loop.text,\n kind: loop.kind,\n ...(loop.targetRef !== undefined ? { target_ref: loop.targetRef } : {}),\n session_file: loop.sessionFile,\n opened_at: loop.openedAt,\n age_days: loop.ageDays,\n }))\n : [];\n\n const resolved = wantResolved\n ? deriveResolvedLoopsFrom(loaded, opts)\n .filter((loop) => args.state !== 'abandoned' || loop.outcome === 'abandoned')\n .map((loop) => ({\n ref: loop.ref,\n text: loop.text,\n kind: loop.kind,\n outcome: loop.outcome,\n ...(loop.note !== undefined ? { note: loop.note } : {}),\n session_file: loop.sessionFile,\n closed_by: loop.closedBy,\n opened_at: loop.openedAt,\n closed_at: loop.closedAt,\n age_days: loop.ageDays,\n }))\n : [];\n\n return { slug: args.slug, open, resolved };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { TaskSchema, type Task } from '../schemas/task.js';\nimport { readYaml } from '../utils/yaml-io.js';\n\n/**\n * Load every task under `<initiativeDir>/tasks/*.yml`.\n *\n * Shared by lint and doctor: both need `kind: 'task'` loops matched against\n * real tasks, and both are best-effort consumers — a malformed task file is\n * skipped rather than thrown, since neither is the source of truth for task\n * validity (schema-validating writers are).\n */\nexport async function loadTasks(initiativeDir: string): Promise<Task[]> {\n const tasksDir = path.join(initiativeDir, 'tasks');\n let entries: string[];\n try {\n entries = await fs.readdir(tasksDir);\n } catch {\n return [];\n }\n const tasks: Task[] = [];\n for (const filename of entries.filter((n) => n.endsWith('.yml') || n.endsWith('.yaml'))) {\n try {\n tasks.push(await readYaml(path.join(tasksDir, filename), TaskSchema));\n } catch {\n // Skip malformed task files.\n }\n }\n return tasks;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { BranchEntrySchema, StashEntrySchema, WorktreeEntrySchema } from '../schemas/artifacts.js';\nimport { NotFoundError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\nimport { sweepInitiative } from '../wrap/sweep.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n cwd: z.string().min(1).optional(),\n});\n\nconst DirtyTreeSchema = z.object({\n path: z.string(),\n repo: z.string(),\n /** Null when git could not read the tree — unknown, not clean. */\n files_changed: z.number().int().nonnegative().nullable(),\n});\n\nconst UnpushedBranchSchema = z.object({\n path: z.string(),\n repo: z.string(),\n branch: z.string(),\n ahead: z.number().int().nonnegative(),\n no_upstream: z.boolean(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n repos: z.array(z.string()),\n unrecorded: z.object({\n worktrees: z.array(WorktreeEntrySchema),\n branches: z.array(BranchEntrySchema),\n stashes: z.array(StashEntrySchema),\n }),\n dirty: z.array(DirtyTreeSchema),\n unpushed: z.array(UnpushedBranchSchema),\n checklist: z.array(z.string()),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\n/**\n * The categories a wrap has to answer. Git state is swept deterministically;\n * these are the four things only the session itself knows.\n */\nconst CHECKLIST = [\n 'open loops: what this session leaves hanging, filed as wrap --next-steps, plus the prior loops it closed via --resolves',\n 'durable notes: anything learned that outlives the session, filed with note.add',\n 'tasks filed: work you named but did not do, filed with task.add',\n 'worktree/artifact state: what each dirty or unpushed worktree is holding, and whether every branch and stash worth keeping is recorded',\n];\n\nexport default defineCommand<Args, Result>({\n name: 'preflight',\n description:\n 'Read-only pre-wrap sweep: the uncommitted trees, unpushed branches, and worktrees/branches/stashes present in git but missing from artifacts.yml, plus the checklist a wrap must answer. Writes nothing.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n cwd: {\n long: '--cwd',\n description: 'Directory to include in the swept repo set (default: current directory).',\n },\n },\n usage: 'active-work preflight <slug> [--cwd <dir>]',\n },\n async run(args, ctx) {\n const briefPath = path.join(ctx.activeRoot, args.slug, 'brief.md');\n try {\n await fs.access(briefPath);\n } catch {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n const cwd = args.cwd ?? ctx.cwd ?? process.cwd();\n const sweep = await sweepInitiative(args.slug, ctx.activeRoot, cwd);\n return { slug: args.slug, ...sweep, checklist: CHECKLIST };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport {\n ArtifactsSchema,\n type Artifacts,\n type BranchEntry,\n type StashEntry,\n type WorktreeEntry,\n} from '../schemas/artifacts.js';\nimport { registeredOf } from '../utils/registered-worktrees.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { expandTilde } from '../utils/paths.js';\nimport { resolveLocalRepoPath } from '../utils/git-gh.js';\nimport {\n discoverWorktrees,\n listStashes,\n readWorktreeState,\n type DiscoveredWorktree,\n type WorktreeState,\n} from '../utils/git-worktrees.js';\n\n/**\n * Pre-wrap sweep: the git state a session leaves behind that nobody recorded.\n *\n * The repo set is bounded and derived, never searched: the worktree paths in\n * `brief.md`, the `repo` values already in `artifacts.yml`, and the caller's\n * cwd. Everything else is read live through `getGitRunner()` (via\n * `src/utils/git-worktrees.ts`), so a repo that has moved contributes nothing\n * rather than aborting the sweep.\n */\n\nexport interface UnrecordedState {\n worktrees: WorktreeEntry[];\n branches: BranchEntry[];\n stashes: StashEntry[];\n}\n\nexport interface DirtyTree {\n path: string;\n repo: string;\n /** Null when git could not say — the tree is unknown, not clean. */\n files_changed: number | null;\n}\n\nexport interface UnpushedBranch {\n path: string;\n repo: string;\n branch: string;\n /** Commits that exist on no remote. */\n ahead: number;\n /**\n * True when the branch tracks nothing. Not a lesser case of `ahead > 0` but\n * the worse one: nothing about the branch exists anywhere but this disk.\n */\n no_upstream: boolean;\n}\n\nexport interface SweepResult {\n repos: string[];\n unrecorded: UnrecordedState;\n dirty: DirtyTree[];\n unpushed: UnpushedBranch[];\n}\n\ninterface LiveState {\n worktrees: WorktreeEntry[];\n branches: BranchEntry[];\n stashes: StashEntry[];\n dirty: DirtyTree[];\n unpushed: UnpushedBranch[];\n}\n\ninterface RepoSweep extends LiveState {\n /** The path we swept from — a repo root or any worktree attached to it. */\n sweptPath: string;\n /**\n * The repository this path belongs to, as git reports it (the main worktree\n * of the set). Two swept paths sharing a root are one repository.\n */\n root: string | null;\n}\n\nconst EMPTY_STATE = (): LiveState => ({\n worktrees: [],\n branches: [],\n stashes: [],\n dirty: [],\n unpushed: [],\n});\n\nconst emptySweep = (sweptPath: string): RepoSweep => ({\n ...EMPTY_STATE(),\n sweptPath,\n root: null,\n});\n\nfunction normalizePath(value: string): string {\n return path.resolve(expandTilde(value));\n}\n\n/** Stable identity for a `repo` field, which may be a path or `org/repo`. */\nfunction repoKey(repo: string): string {\n return resolveLocalRepoPath(repo) ?? repo;\n}\n\nfunction artifactsPath(initiativeDir: string): string {\n return path.join(initiativeDir, 'artifacts.yml');\n}\n\n/**\n * Missing `artifacts.yml` reads as empty; a malformed one still throws, so a\n * later append can never silently overwrite content it failed to parse.\n */\nasync function readArtifacts(initiativeDir: string): Promise<Artifacts> {\n const file = artifactsPath(initiativeDir);\n try {\n await fs.access(file);\n } catch {\n return { branches: [], stashes: [], worktrees: [] };\n }\n return readYaml(file, ArtifactsSchema);\n}\n\n/**\n * Registered worktree paths seed the repo set. Since v4 these live in\n * artifacts.yml alongside the swept ones (AW-67), so they arrive with the rest\n * of the artifacts read and need no separate file.\n */\nfunction registeredWorktreePaths(artifacts: Artifacts): string[] {\n return registeredOf(artifacts).map((entry) => entry.path);\n}\n\n/**\n * Absolute repo path -> the label to write into new artifact entries. Seeded\n * from `artifacts.yml` first so recorded spellings (`~/code/sample`) win over\n * the resolved absolute path.\n */\nfunction collectRepoLabels(\n artifacts: Artifacts,\n briefPaths: string[],\n cwd: string,\n): Map<string, string> {\n const labels = new Map<string, string>();\n const add = (value: string): void => {\n const abs = resolveLocalRepoPath(value);\n if (abs && !labels.has(abs)) labels.set(abs, value);\n };\n for (const branch of artifacts.branches) add(branch.repo);\n for (const stash of artifacts.stashes) add(stash.repo);\n for (const worktree of artifacts.worktrees) add(worktree.repo);\n for (const worktreePath of briefPaths) add(worktreePath);\n add(cwd);\n return labels;\n}\n\n/**\n * Collect one worktree's contribution to the sweep. Every live worktree is\n * recorded — its path and purpose are identity, and git cannot re-derive what\n * it is parked on — while branches, dirt, and unpushed commits are filtered.\n */\nfunction collectWorktree(\n discovered: DiscoveredWorktree,\n label: string,\n state: WorktreeState,\n into: RepoSweep,\n): void {\n const branch = state.branch ?? discovered.branch ?? undefined;\n // Never `?? 0`: a failed probe means unknown, and defaulting it to zero\n // reports the most dangerous branch — one that exists on no remote — as the\n // safest. Unknown counts as unpushed.\n // A failed `--not --remotes` probe falls back to `ahead`, and only then to 1\n // as \"unknown but non-zero\" — a tracked branch 3 ahead must not read as clean\n // just because the remote-wide count could not be taken.\n const stranded = state.unpushed ?? state.ahead ?? 1;\n const isUnpushed = stranded > 0;\n into.worktrees.push({\n path: discovered.path,\n repo: label,\n ...(branch ? { branch } : {}),\n });\n // `dirty: null` means git could not answer, which is reported rather than\n // skipped: treating an unreadable tree as clean hides exactly the\n // uncommitted work this sweep exists to surface.\n const dirtyUnknown = state.dirty === null;\n if (state.dirty || dirtyUnknown) {\n into.dirty.push({\n path: discovered.path,\n repo: label,\n files_changed: state.files_changed,\n });\n }\n if (!branch) return;\n if (isUnpushed) {\n into.unpushed.push({\n path: discovered.path,\n repo: label,\n branch,\n ahead: stranded,\n no_upstream: !state.has_upstream,\n });\n }\n // A checked-out branch is worth recording only when it carries work that\n // lives nowhere else — unpushed commits or an uncommitted tree. Recording\n // every branch git happens to have checked out would bury the ones that\n // matter.\n if (state.dirty !== false || isUnpushed) {\n into.branches.push({ repo: label, name: branch });\n }\n}\n\nasync function sweepRepo(repoPath: string, label: string): Promise<RepoSweep> {\n const [discovered, stashes] = await Promise.all([\n discoverWorktrees(repoPath),\n listStashes(repoPath),\n ]);\n const out = emptySweep(repoPath);\n // git lists the main worktree first; it identifies the repository the swept\n // path belongs to, whichever worktree of the set we were pointed at.\n out.root = discovered[0]?.path ?? null;\n for (const worktree of discovered) {\n if (worktree.bare) continue;\n const state = await readWorktreeState(worktree.path);\n if (!state.present) continue;\n collectWorktree(worktree, label, state, out);\n }\n out.stashes = stashes.map((stash) => ({\n repo: label,\n label: stash.label,\n sha: stash.sha,\n }));\n return out;\n}\n\n/** First occurrence wins, so the chosen `repo` label is stable across runs. */\nfunction dedupeBy<T>(items: T[], key: (item: T) => string): T[] {\n const seen = new Set<string>();\n return items.filter((item) => {\n const k = key(item);\n if (seen.has(k)) return false;\n seen.add(k);\n return true;\n });\n}\n\nconst worktreeKey = (entry: { path: string }): string => normalizePath(entry.path);\nconst branchKey = (entry: BranchEntry): string => `${repoKey(entry.repo)} ${entry.name}`;\nconst stashKey = (entry: StashEntry): string =>\n `${repoKey(entry.repo)} ${entry.sha ?? entry.label}`;\n\n/**\n * Which repository a sweep covered. Falls back to the swept path when git could\n * not say — a path that answers nothing cannot be merged with anything else.\n */\nconst repositoryOf = (sweep: RepoSweep): string => sweep.root ?? sweep.sweptPath;\n\n/**\n * `git worktree list` and `git stash list` are per-repository, and the repo set\n * can legitimately hold two paths belonging to one repo — a main checkout plus\n * a registered linked worktree. Sweeping both yields every worktree and stash\n * twice under different labels, so candidates must be deduped against each\n * other and not merely against what is already recorded.\n */\nfunction mergeSweeps(sweeps: RepoSweep[]): LiveState {\n const merged = EMPTY_STATE();\n for (const sweep of sweeps) {\n merged.worktrees.push(...sweep.worktrees);\n merged.branches.push(...sweep.branches);\n merged.stashes.push(...sweep.stashes);\n merged.dirty.push(...sweep.dirty);\n merged.unpushed.push(...sweep.unpushed);\n }\n return {\n worktrees: dedupeBy(merged.worktrees, worktreeKey),\n branches: dedupeBy(merged.branches, branchKey),\n stashes: dedupeBy(merged.stashes, stashKey),\n dirty: dedupeBy(merged.dirty, worktreeKey),\n unpushed: dedupeBy(merged.unpushed, worktreeKey),\n };\n}\n\nfunction unrecordedWorktrees(\n candidates: WorktreeEntry[],\n recorded: WorktreeEntry[],\n): WorktreeEntry[] {\n const seen = new Set(recorded.map((entry) => normalizePath(entry.path)));\n return candidates.filter((entry) => !seen.has(normalizePath(entry.path)));\n}\n\nfunction unrecordedBranches(candidates: BranchEntry[], recorded: BranchEntry[]): BranchEntry[] {\n const key = (repo: string, name: string): string => `${repoKey(repo)}\u0000${name}`;\n const seen = new Set(recorded.map((entry) => key(entry.repo, entry.name)));\n return candidates.filter((entry) => !seen.has(key(entry.repo, entry.name)));\n}\n\n/**\n * Stashes are matched on `repo` + `sha`, falling back to `label` for entries\n * recorded before a sha was known — a recorded stash with no sha is otherwise\n * invisible to the sweep and gets appended a second time on every wrap.\n */\nfunction unrecordedStashes(candidates: StashEntry[], recorded: StashEntry[]): StashEntry[] {\n const key = (repo: string, tail: string): string => `${repoKey(repo)}\u0000${tail}`;\n const shas = new Set<string>();\n const labels = new Set<string>();\n for (const entry of recorded) {\n if (entry.sha) shas.add(key(entry.repo, entry.sha));\n else labels.add(key(entry.repo, entry.label));\n }\n return candidates.filter(\n (entry) =>\n !(entry.sha && shas.has(key(entry.repo, entry.sha))) &&\n !labels.has(key(entry.repo, entry.label)),\n );\n}\n\n/** Read-only. Never writes. */\nexport async function sweepInitiative(\n slug: string,\n activeRoot: string,\n cwd: string,\n): Promise<SweepResult> {\n const initiativeDir = path.join(activeRoot, slug);\n const artifacts = await readArtifacts(initiativeDir);\n const labels = collectRepoLabels(artifacts, registeredWorktreePaths(artifacts), cwd);\n const swept = await Promise.all(\n [...labels].map(([repoPath, label]) => sweepRepo(repoPath, label)),\n );\n const distinct = dedupeBy(swept, repositoryOf);\n const live = mergeSweeps(distinct);\n return {\n repos: distinct.map(repositoryOf),\n unrecorded: {\n worktrees: unrecordedWorktrees(live.worktrees, artifacts.worktrees),\n branches: unrecordedBranches(live.branches, artifacts.branches),\n stashes: unrecordedStashes(live.stashes, artifacts.stashes),\n },\n dirty: live.dirty,\n unpushed: live.unpushed,\n };\n}\n\n/**\n * Appends `unrecorded` into artifacts.yml and returns how many of each were\n * added. CALLER MUST ALREADY HOLD THE INITIATIVE LOCK — this function must NOT\n * call withFileLock itself or it will deadlock inside wrap's existing lock.\n */\nexport async function recordUnrecorded(\n slug: string,\n activeRoot: string,\n unrecorded: UnrecordedState,\n): Promise<{ worktrees: number; branches: number; stashes: number }> {\n const initiativeDir = path.join(activeRoot, slug);\n const current = await readArtifacts(initiativeDir);\n const worktrees = unrecordedWorktrees(unrecorded.worktrees, current.worktrees);\n const branches = unrecordedBranches(unrecorded.branches, current.branches);\n const stashes = unrecordedStashes(unrecorded.stashes, current.stashes);\n const added = {\n worktrees: worktrees.length,\n branches: branches.length,\n stashes: stashes.length,\n };\n if (worktrees.length + branches.length + stashes.length === 0) return added;\n await writeYaml(\n artifactsPath(initiativeDir),\n {\n branches: [...current.branches, ...branches],\n stashes: [...current.stashes, ...stashes],\n worktrees: [...current.worktrees, ...worktrees],\n },\n ArtifactsSchema,\n );\n return added;\n}\n","import { getGitRunner } from './git-gh.js';\n\n/**\n * Live git worktree reads for `artifact.status`.\n *\n * Nothing here is persisted: `artifacts.yml` records only worktree identity\n * and purpose (see `src/schemas/artifacts.ts`), and everything volatile —\n * dirty flag, files changed, ahead/behind — is pulled at read time.\n *\n * Like `git-gh.ts`, every helper is failure-tolerant: a repo that has been\n * moved or deleted yields empty/null data rather than aborting the sweep.\n * All git calls go through `getGitRunner()` so tests can inject a fake.\n */\n\nexport interface DiscoveredWorktree {\n path: string;\n head: string | null;\n branch: string | null;\n detached: boolean;\n bare: boolean;\n}\n\nexport interface WorktreeState {\n /**\n * False when the path is gone or is no longer a git worktree. Without this a\n * deleted worktree reads exactly like a clean one — no dirt, no files, no\n * upstream — and silently drops out of the operator's attention.\n */\n present: boolean;\n /**\n * Null when `git status` could not answer. A failed probe is not a clean\n * tree: reporting it as clean is the same mistake `ahead` avoids below, and\n * it silences the one warning that says uncommitted work is about to be left\n * behind.\n */\n dirty: boolean | null;\n /** Null whenever `dirty` is null — an unknown tree has an unknown file count. */\n files_changed: number | null;\n branch: string | null;\n /** Null when there is no upstream — meaning unknown, never \"nothing to push\". */\n ahead: number | null;\n behind: number | null;\n /**\n * Whether the branch tracks a remote, probed directly. Deriving this from\n * `ahead !== null` conflated \"no upstream configured\" with \"the rev-list call\n * failed\", so a transient git failure reported a tracked branch as untracked.\n */\n has_upstream: boolean;\n /**\n * Commits reachable from HEAD that exist on no remote at all. This is the\n * honest \"what would be lost if this disk died\" number, and unlike `ahead`\n * it is defined for a branch that was never pushed anywhere.\n */\n unpushed: number | null;\n}\n\nexport interface StashRef {\n label: string;\n sha: string;\n}\n\nconst NO_UPSTREAM = { ahead: null, behind: null } as const;\n\nfunction shortBranch(ref: string): string {\n return ref.replace(/^refs\\/heads\\//, '');\n}\n\nfunction emptyWorktree(path: string): DiscoveredWorktree {\n return { path, head: null, branch: null, detached: false, bare: false };\n}\n\n/**\n * Parse `git worktree list --porcelain` output. Records are separated by\n * blank lines and always open with a `worktree <path>` line. Exported for\n * testing.\n */\nexport function parseWorktreePorcelain(stdout: string): DiscoveredWorktree[] {\n const out: DiscoveredWorktree[] = [];\n let current: DiscoveredWorktree | null = null;\n for (const rawLine of stdout.split('\\n')) {\n const line = rawLine.trimEnd();\n const [key, ...rest] = line.split(' ');\n const value = rest.join(' ');\n if (key === 'worktree') {\n current = emptyWorktree(value);\n out.push(current);\n } else if (!current) {\n continue;\n } else if (key === 'HEAD') {\n current.head = value || null;\n } else if (key === 'branch') {\n current.branch = shortBranch(value);\n } else if (key === 'detached') {\n current.detached = true;\n } else if (key === 'bare') {\n current.bare = true;\n }\n }\n return out;\n}\n\n/** Enumerate the worktrees attached to `repoPath`. Empty on failure. */\nexport async function discoverWorktrees(repoPath: string): Promise<DiscoveredWorktree[]> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', repoPath, 'worktree', 'list', '--porcelain']);\n if (res.code !== 0) return [];\n return parseWorktreePorcelain(res.stdout);\n } catch {\n return [];\n }\n}\n\nconst DIRT_UNKNOWN = { dirty: null, files_changed: null } as const;\n\nasync function readDirty(\n worktreePath: string,\n): Promise<{ dirty: boolean | null; files_changed: number | null }> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', worktreePath, 'status', '--porcelain']);\n if (res.code !== 0) return { ...DIRT_UNKNOWN };\n const lines = res.stdout.split('\\n').filter((line) => line.trim().length > 0);\n return { dirty: lines.length > 0, files_changed: lines.length };\n } catch {\n return { ...DIRT_UNKNOWN };\n }\n}\n\n/** Whether the current branch tracks a remote. Probed, never inferred. */\nasync function readHasUpstream(worktreePath: string): Promise<boolean> {\n const git = getGitRunner();\n try {\n const res = await git('git', [\n '-C',\n worktreePath,\n 'rev-parse',\n '--abbrev-ref',\n '--symbolic-full-name',\n '@{u}',\n ]);\n return res.code === 0 && res.stdout.trim().length > 0;\n } catch {\n return false;\n }\n}\n\n/** Current branch of a worktree, or null when HEAD is detached. */\nasync function readBranch(worktreePath: string): Promise<string | null> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', worktreePath, 'rev-parse', '--abbrev-ref', 'HEAD']);\n if (res.code !== 0) return null;\n const name = res.stdout.trim();\n return name && name !== 'HEAD' ? name : null;\n } catch {\n return null;\n }\n}\n\nasync function countRevs(\n worktreePath: string,\n range: string,\n extra: string[] = [],\n): Promise<number | null> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', worktreePath, 'rev-list', '--count', range, ...extra]);\n if (res.code !== 0) return null;\n const count = Number(res.stdout.trim());\n return Number.isFinite(count) ? count : null;\n } catch {\n return null;\n }\n}\n\n/** Ahead/behind versus the tracking branch; nulls when there is no upstream. */\nasync function readAheadBehind(\n worktreePath: string,\n): Promise<{ ahead: number | null; behind: number | null }> {\n const ahead = await countRevs(worktreePath, '@{u}..HEAD');\n if (ahead === null) return { ...NO_UPSTREAM };\n const behind = await countRevs(worktreePath, 'HEAD..@{u}');\n return { ahead, behind };\n}\n\n/** Whether `worktreePath` still resolves inside a git working tree. */\nasync function isPresent(worktreePath: string): Promise<boolean> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', worktreePath, 'rev-parse', '--is-inside-work-tree']);\n return res.code === 0 && res.stdout.trim() === 'true';\n } catch {\n return false;\n }\n}\n\n// An absent worktree states `dirty: null` rather than `false` for the same\n// reason a failed probe does: there is no tree to be clean.\nconst ABSENT: WorktreeState = {\n present: false,\n dirty: null,\n files_changed: null,\n branch: null,\n ahead: null,\n behind: null,\n has_upstream: false,\n unpushed: null,\n};\n\n/** Commits on HEAD that no remote has. Defined even with no upstream set. */\nasync function readUnpushed(worktreePath: string): Promise<number | null> {\n return countRevs(worktreePath, 'HEAD', ['--not', '--remotes']);\n}\n\n/** Live, non-persisted state of a single worktree. */\nexport async function readWorktreeState(worktreePath: string): Promise<WorktreeState> {\n if (!(await isPresent(worktreePath))) return { ...ABSENT };\n const [{ dirty, files_changed }, branch, { ahead, behind }, unpushed, has_upstream] =\n await Promise.all([\n readDirty(worktreePath),\n readBranch(worktreePath),\n readAheadBehind(worktreePath),\n readUnpushed(worktreePath),\n readHasUpstream(worktreePath),\n ]);\n return {\n present: true,\n dirty,\n files_changed,\n branch,\n ahead,\n behind,\n has_upstream,\n unpushed,\n };\n}\n\n/** Stashes present in `repoPath`, newest first. Empty on failure. */\nexport async function listStashes(repoPath: string): Promise<StashRef[]> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', repoPath, 'stash', 'list', '--format=%H%x09%gs']);\n if (res.code !== 0) return [];\n return res.stdout\n .split('\\n')\n .map((line) => line.split('\\t'))\n .filter((parts): parts is [string, string] => Boolean(parts[0]?.trim() && parts[1]))\n .map(([sha, label]) => ({ sha: sha.trim(), label: label.trim() }));\n } catch {\n return [];\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport matter from 'gray-matter';\nimport { SessionFrontmatterSchema } from '../schemas/session.js';\nimport type { SessionFrontmatter } from '../schemas/session.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n limit: z.number().int().positive().optional(),\n});\n\nconst SessionEntrySchema = z.object({\n filename: z.string(),\n frontmatter: SessionFrontmatterSchema,\n first_line: z.string(),\n});\n\nconst ResultSchema = z.object({\n sessions: z.array(SessionEntrySchema),\n errors: z.array(z.object({ filename: z.string(), error: z.string() })),\n});\n\nconst DEFAULT_LIMIT = 100;\nconst MAX_FIRST_LINE = 120;\n\nfunction extractFirstLine(body: string): string {\n const lines = body.split(/\\r?\\n/);\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length === 0) continue;\n return trimmed.length > MAX_FIRST_LINE ? trimmed.slice(0, MAX_FIRST_LINE) : trimmed;\n }\n return '';\n}\n\ninterface ListEntry {\n filename: string;\n frontmatter: SessionFrontmatter;\n first_line: string;\n}\n\ninterface ListError {\n filename: string;\n error: string;\n}\n\nasync function listSessionFiles(dir: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(dir);\n return entries.filter((e) => e.endsWith('.md')).sort();\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n}\n\n/**\n * YAML parses unquoted ISO 8601 timestamps as `Date` instances. The session\n * schema expects ISO strings, so coerce known timestamp fields back to their\n * string form before validation.\n */\nfunction coerceTimestamps(raw: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = { ...raw };\n for (const field of ['started', 'ended'] as const) {\n const value = out[field];\n if (value instanceof Date) {\n out[field] = value.toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n }\n }\n return out;\n}\n\nasync function readSession(\n filePath: string,\n): Promise<{ frontmatter: SessionFrontmatter; body: string }> {\n const raw = await fs.readFile(filePath, 'utf8');\n const parsed = matter(raw);\n const coerced = coerceTimestamps(parsed.data as Record<string, unknown>);\n const result = SessionFrontmatterSchema.safeParse(coerced);\n if (!result.success) {\n throw new Error(`Frontmatter validation failed for ${filePath}: ${result.error.message}`);\n }\n return { frontmatter: result.data, body: parsed.content };\n}\n\nexport default defineCommand({\n name: 'session.list',\n description: 'List session summaries for an initiative, sorted by end time',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n limit: {\n long: '--limit',\n description: `Maximum sessions to return (default ${DEFAULT_LIMIT})`,\n },\n },\n usage: 'session.list <slug> [--limit N]',\n },\n async run(args) {\n const limit = args.limit ?? DEFAULT_LIMIT;\n const sessionsDir = path.join(getInitiativeDir(args.slug), 'sessions');\n const filenames = await listSessionFiles(sessionsDir);\n\n const entries: ListEntry[] = [];\n const errors: ListError[] = [];\n\n for (const filename of filenames) {\n const fullPath = path.join(sessionsDir, filename);\n try {\n const { frontmatter, body } = await readSession(fullPath);\n entries.push({\n filename,\n frontmatter,\n first_line: extractFirstLine(body),\n });\n } catch (err) {\n errors.push({\n filename,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n entries.sort((a, b) => {\n const aEnded = new Date(a.frontmatter.ended).getTime();\n const bEnded = new Date(b.frontmatter.ended).getTime();\n return bEnded - aEnded;\n });\n\n return { sessions: entries.slice(0, limit), errors };\n },\n});\n","import { promises as fs, createReadStream } from 'node:fs';\nimport type { Dirent } from 'node:fs';\nimport path from 'node:path';\nimport os from 'node:os';\nimport readline from 'node:readline';\nimport { z } from 'zod';\nimport { getActiveRoot, expandTilde } from '../utils/paths.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n limit: z.number().int().positive().optional(),\n include_active: z.boolean().optional(),\n});\n\nconst SessionEntrySchema = z.object({\n session_id: z.string(),\n cwd: z.string(),\n ended: z.string(),\n summary: z.string(),\n});\n\nconst ResultSchema = z.object({\n sessions: z.array(SessionEntrySchema),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\ntype SessionEntry = z.infer<typeof SessionEntrySchema>;\n\nconst DEFAULT_LIMIT = 50;\nconst SUMMARY_MAX = 150;\nconst CONTINUATION_MARKER = 'This session is being continued from a previous conversation';\n\nfunction claudeProjectsRoot(): string {\n const override = process.env.CLAUDE_PROJECTS_ROOT;\n if (override && override.length > 0) {\n return path.resolve(expandTilde(override));\n }\n return path.join(os.homedir(), '.claude', 'projects');\n}\n\ninterface ScannedSession {\n sessionId: string;\n cwd: string;\n mtimeMs: number;\n filePath: string;\n}\n\n/**\n * Walk the projects root looking for `*.jsonl` session files. Each\n * subdirectory under projects root holds sessions for one safe-encoded\n * working directory.\n */\nasync function listJsonlFiles(root: string): Promise<string[]> {\n let projectDirs: string[];\n try {\n projectDirs = await fs\n .readdir(root, { withFileTypes: true })\n .then((entries) =>\n entries.filter((e) => e.isDirectory()).map((e) => path.join(root, e.name)),\n );\n } catch {\n return [];\n }\n const all: string[] = [];\n for (const dir of projectDirs) {\n let files: string[];\n try {\n files = await fs.readdir(dir);\n } catch {\n continue;\n }\n for (const f of files) {\n if (f.endsWith('.jsonl')) {\n all.push(path.join(dir, f));\n }\n }\n }\n return all;\n}\n\n/**\n * Read the first line containing a `\"cwd\"` field without slurping the\n * whole file. Returns `null` when no such line is found.\n */\nasync function lightScanCwd(filePath: string): Promise<string | null> {\n const stream = createReadStream(filePath, { encoding: 'utf8' });\n const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });\n try {\n for await (const line of rl) {\n if (!line.includes('\"cwd\"')) continue;\n try {\n const parsed = JSON.parse(line) as Record<string, unknown>;\n const cwd = parsed.cwd;\n if (typeof cwd === 'string' && cwd.length > 0) {\n return cwd;\n }\n } catch {\n // ignore malformed line; keep scanning\n }\n }\n return null;\n } finally {\n rl.close();\n stream.destroy();\n }\n}\n\nasync function scanSession(filePath: string): Promise<ScannedSession | null> {\n const cwd = await lightScanCwd(filePath);\n if (!cwd) return null;\n const stat = await fs.stat(filePath);\n const sessionId = path.basename(filePath, '.jsonl');\n return { sessionId, cwd, mtimeMs: stat.mtimeMs, filePath };\n}\n\nasync function listActiveInitiativeRoots(): Promise<string[]> {\n const activeRoot = getActiveRoot();\n let entries: Dirent[];\n try {\n entries = await fs.readdir(activeRoot, { withFileTypes: true });\n } catch {\n return [];\n }\n return entries\n .filter((e) => e.isDirectory() && !e.name.startsWith('.'))\n .map((e) => path.join(activeRoot, e.name));\n}\n\nfunction isPathPrefix(parent: string, child: string): boolean {\n const p = path.resolve(parent);\n const c = path.resolve(child);\n if (p === c) return true;\n const withSep = p.endsWith(path.sep) ? p : p + path.sep;\n return c.startsWith(withSep);\n}\n\nfunction extractFirstUserText(line: string): string | null {\n try {\n const parsed = JSON.parse(line) as Record<string, unknown>;\n if (parsed.type !== 'user') return null;\n const message = parsed.message as Record<string, unknown> | undefined;\n if (!message) return null;\n const content = message.content;\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n for (const part of content) {\n if (\n part &&\n typeof part === 'object' &&\n 'text' in part &&\n typeof (part as { text: unknown }).text === 'string'\n ) {\n return (part as { text: string }).text;\n }\n }\n }\n return null;\n } catch {\n return null;\n }\n}\n\nfunction truncate(text: string, max: number): string {\n const trimmed = text.replace(/\\s+/g, ' ').trim();\n if (trimmed.length <= max) return trimmed;\n return trimmed.slice(0, max);\n}\n\n/**\n * Stream the jsonl file to extract a summary: prefer the most recent\n * compaction-continuation marker, otherwise fall back to the first\n * user message text.\n */\nasync function extractSummary(filePath: string): Promise<string> {\n const stream = createReadStream(filePath, { encoding: 'utf8' });\n const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });\n let latestContinuation: string | null = null;\n let firstUser: string | null = null;\n try {\n for await (const line of rl) {\n if (line.includes(CONTINUATION_MARKER)) {\n const text = extractFirstUserText(line);\n if (text) latestContinuation = text;\n } else if (firstUser === null) {\n const text = extractFirstUserText(line);\n if (text) firstUser = text;\n }\n }\n } finally {\n rl.close();\n stream.destroy();\n }\n const raw = latestContinuation ?? firstUser ?? '';\n return truncate(raw, SUMMARY_MAX);\n}\n\nexport async function runSessions(args: Args): Promise<Result> {\n const limit = args.limit ?? DEFAULT_LIMIT;\n const includeActive = args.include_active ?? false;\n\n const root = claudeProjectsRoot();\n const files = await listJsonlFiles(root);\n\n const scanned: ScannedSession[] = [];\n for (const f of files) {\n try {\n const entry = await scanSession(f);\n if (entry) scanned.push(entry);\n } catch {\n // ignore unreadable files\n }\n }\n\n let filtered = scanned;\n if (!includeActive) {\n const activeRoots = await listActiveInitiativeRoots();\n if (activeRoots.length > 0) {\n filtered = scanned.filter((s) => !activeRoots.some((root) => isPathPrefix(root, s.cwd)));\n }\n }\n\n filtered.sort((a, b) => b.mtimeMs - a.mtimeMs);\n const top = filtered.slice(0, limit);\n\n const sessions: SessionEntry[] = [];\n for (const entry of top) {\n const summary = await extractSummary(entry.filePath);\n sessions.push({\n session_id: entry.sessionId,\n cwd: entry.cwd,\n ended: new Date(entry.mtimeMs).toISOString(),\n summary,\n });\n }\n\n return { sessions };\n}\n\nconst sessions = defineCommand<Args, Result>({\n name: 'sessions',\n description: 'Browse recent Claude sessions discovered under ~/.claude/projects.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n limit: { long: '--limit', description: 'Max sessions to return (default 50).' },\n include_active: {\n long: '--include-active',\n description: 'Include sessions whose cwd lives under an active initiative.',\n },\n },\n usage: 'active-work sessions [--limit N] [--include-active]',\n },\n async run(args) {\n return runSessions(args);\n },\n});\n\nexport default sessions;\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema } from '../schemas/brief.js';\nimport { NoteKindSchema } from '../schemas/note.js';\nimport {\n NextStepSchema,\n SessionIdSchema,\n SessionResolveSchema,\n type NextStep,\n type SessionResolve,\n} from '../schemas/session.js';\nimport { writeSessionFile } from '../sessions/session-file.js';\nimport { findDanglingResolves, type DanglingKind } from '../sessions/open-loops.js';\nimport { writeNoteFile } from '../notes/note-file.js';\nimport { loadTasks } from '../lint/load-tasks.js';\nimport { recordUnrecorded, sweepInitiative, type SweepResult } from '../wrap/sweep.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readRawFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst NextStepsSchema = z.array(NextStepSchema);\nconst ResolvesSchema = z.array(SessionResolveSchema);\n\nconst NoteInputSchema = z.object({\n kind: NoteKindSchema,\n title: z.string().min(1),\n body: z.string().min(1),\n tags: z.array(z.string().min(1)).optional(),\n});\nconst NotesSchema = z.array(NoteInputSchema);\nconst TaskIdsSchema = z.array(z.string().min(1));\n\n// MCP callers pass structured arrays; the CLI passes a JSON string through a\n// single flag, since comma-splitting cannot express nested objects.\nconst nextStepsArg = z.union([z.string(), NextStepsSchema]);\nconst resolvesArg = z.union([z.string(), ResolvesSchema]);\nconst notesArg = z.union([z.string(), NotesSchema]);\nconst taskIdsArg = z.union([z.string(), TaskIdsSchema]);\n\nconst ArgsSchema = z\n .object({\n slug: z.string().min(1),\n session_id: SessionIdSchema,\n started: z.string().min(1),\n ended: z.string().min(1),\n track: z.enum(['canonical', 'sidecar', 'adhoc']).default('canonical'),\n body: z.string().optional(),\n body_file: z.string().optional(),\n next_steps: nextStepsArg.optional(),\n resolves: resolvesArg.optional(),\n no_loops: z.boolean().optional(),\n notes: notesArg.optional(),\n no_notes: z.boolean().optional(),\n tasks_filed: taskIdsArg.optional(),\n no_tasks: z.boolean().optional(),\n })\n .superRefine((value, ctx) => {\n const hasBody = value.body !== undefined;\n const hasFile = value.body_file !== undefined;\n if (!hasBody && !hasFile) {\n ctx.addIssue({\n code: 'custom',\n path: ['body'],\n message: 'Exactly one of --body or --body-file is required',\n });\n }\n if (hasBody && hasFile) {\n ctx.addIssue({\n code: 'custom',\n path: ['body'],\n message: '--body and --body-file are mutually exclusive',\n });\n }\n });\n\nconst RejectedResolveSchema = z.object({\n ref: z.string(),\n kind: z.enum(['missing', 'not-prior', 'self']),\n});\n\nconst FiledSchema = z.object({\n next_steps: z.number().int().nonnegative(),\n notes: z.number().int().nonnegative(),\n tasks: z.number().int().nonnegative(),\n worktrees: z.number().int().nonnegative(),\n branches: z.number().int().nonnegative(),\n stashes: z.number().int().nonnegative(),\n});\n\nconst ResultSchema = z.object({\n path: z.string(),\n filename: z.string(),\n /** False only when some `resolves` ref closed nothing and must be re-filed. */\n ready_to_end: z.boolean(),\n filed: FiledSchema,\n // Not `resolves`: the count of refs passed says nothing about how many closed\n // a loop, and the caller acts on the difference.\n closed: z.object({ resolves_applied: z.number().int().nonnegative() }),\n resolves_rejected: z.array(RejectedResolveSchema),\n /** The date stamped into `brief.updated`. */\n updated: z.string(),\n /** Files this wrap touched, relative to the initiative directory. */\n files_updated: z.array(z.string()),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\ntype RejectedResolve = z.infer<typeof RejectedResolveSchema>;\ntype NoteInput = z.infer<typeof NoteInputSchema>;\ntype Filed = z.infer<typeof FiledSchema>;\n\ninterface Ledger {\n next_steps: NextStep[];\n resolves: SessionResolve[];\n}\n\nfunction parseLedger<T>(raw: string | T[] | undefined, schema: z.ZodType<T[]>, field: string): T[] {\n if (raw === undefined) return [];\n if (Array.isArray(raw)) return schema.parse(raw);\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n throw new ValidationError(`--${field} must be a JSON array`);\n }\n const result = schema.safeParse(json);\n if (!result.success) {\n throw new ValidationError(`Invalid --${field}: ${result.error.message}`);\n }\n return result.data;\n}\n\n/**\n * Every category a session can leave behind needs an explicit answer, because\n * the alternative — silent omission — is the failure this command exists to\n * prevent. Each `empty` message deliberately does not name its own `--no-*`\n * escape hatch: an agent that reaches the error should be pointed at the work\n * of filing, not at the flag that silences the check. The flags are documented\n * in `--help` for the caller who genuinely has nothing to file.\n */\nconst GATES = {\n loops: {\n empty:\n 'Refusing to wrap with an empty ledger. Pass --next-steps with the loops this ' +\n 'session leaves open (anything a future session would need to pick up: ' +\n 'unfinished work, open PRs, unanswered questions) and/or --resolves with the ' +\n 'refs of prior loops it closed.',\n both: '--no-loops asserts an empty ledger; drop it to file --next-steps or --resolves.',\n },\n notes: {\n empty:\n 'Refusing to wrap without an answer for durable notes. Pass --notes with what ' +\n 'this session learned that no task would ever carry: process lessons, gotchas ' +\n 'that cost time, decisions and why they were made, FYIs about the state of the ' +\n 'worktree or the docs.',\n both: '--no-notes asserts this session produced no durable notes; drop it to file --notes.',\n },\n tasks: {\n empty:\n 'Refusing to wrap without an answer for tasks. Pass --tasks-filed with the ids of ' +\n 'the tasks created during this session — anything actionable that surfaced and ' +\n 'must outlive the session must be a task before wrap returns.',\n both: '--no-tasks asserts no tasks were filed this session; drop it to file --tasks-filed.',\n },\n} as const;\n\nfunction requireAnswer(\n filled: boolean,\n none: boolean,\n messages: { empty: string; both: string },\n): void {\n if (none) {\n if (filled) throw new ValidationError(messages.both);\n return;\n }\n if (!filled) throw new ValidationError(messages.empty);\n}\n\nfunction requireAnswers(args: Args, ledger: Ledger, notes: NoteInput[], taskIds: string[]): void {\n const hasLoops = ledger.next_steps.length > 0 || ledger.resolves.length > 0;\n requireAnswer(hasLoops, args.no_loops ?? false, GATES.loops);\n requireAnswer(notes.length > 0, args.no_notes ?? false, GATES.notes);\n requireAnswer(taskIds.length > 0, args.no_tasks ?? false, GATES.tasks);\n}\n\n/**\n * A fabricated id is worse than no id: it reads as filed work that does not\n * exist. Only existence is checkable here, and the message says so rather than\n * implying the ids were confirmed to be this session's.\n */\nasync function verifyTaskIds(initiativeDir: string, ids: string[]): Promise<void> {\n if (ids.length === 0) return;\n const known = new Set((await loadTasks(initiativeDir)).map((task) => task.id));\n const unknown = ids.filter((id) => !known.has(id));\n if (unknown.length === 0) return;\n throw new ValidationError(\n `--tasks-filed names ${unknown.length} id(s) with no task file in this initiative: ` +\n `${unknown.join(', ')}. File the task, then wrap. (Only existence is checked — ` +\n 'that a task was created during this session is not verifiable.)',\n );\n}\n\nasync function stampBriefUpdated(briefPath: string): Promise<string> {\n const updated = today();\n const { frontmatter, body } = await readRawFrontmatter(briefPath);\n frontmatter.updated = updated;\n await writeFrontmatter(briefPath, frontmatter, body, BriefFrontmatterSchema);\n return updated;\n}\n\n/**\n * Write the session file, then bump `brief.updated`. If the brief write fails\n * the session file is removed again, so a wrap is all-or-nothing rather than\n * merely discouraged from being partial.\n */\nasync function writeWrap(\n args: Args,\n briefPath: string,\n body: string,\n ledger: Ledger,\n): Promise<{ path: string; filename: string; updated: string }> {\n const session = await writeSessionFile({\n slug: args.slug,\n session_id: args.session_id,\n started: args.started,\n ended: args.ended,\n track: args.track,\n body,\n next_steps: ledger.next_steps,\n resolves: ledger.resolves,\n ...(args.no_loops === true ? { no_loops: true as const } : {}),\n });\n try {\n const updated = await stampBriefUpdated(briefPath);\n return { ...session, updated };\n } catch (err) {\n await fs.rm(session.path, { force: true });\n throw err;\n }\n}\n\n/** Note paths written, so a later failure can unwind them. */\nasync function fileNotes(\n initiativeDir: string,\n notes: NoteInput[],\n created: string,\n): Promise<string[]> {\n const written: string[] = [];\n for (const note of notes) {\n const result = await writeNoteFile(\n initiativeDir,\n {\n kind: note.kind,\n title: note.title,\n created,\n ...(note.tags === undefined ? {} : { tags: note.tags }),\n },\n note.body,\n );\n written.push(result.path);\n }\n return written;\n}\n\nconst NOTHING_RECORDED = { worktrees: 0, branches: 0, stashes: 0 };\n\n/**\n * Dirty trees and unpushed branches cannot be recorded anywhere — only the tree\n * itself knows. They are surfaced as warnings rather than gating the wrap.\n */\nfunction warnUnrecordable(sweep: SweepResult, warnings: string[]): void {\n for (const tree of sweep.dirty) {\n warnings.push(\n tree.files_changed === null\n ? `Could not read the working tree in ${tree.path} (${tree.repo}); it may hold uncommitted work. Check it before relying on this wrap.`\n : `Uncommitted work in ${tree.path} (${tree.repo}): ${tree.files_changed} file(s) changed.`,\n );\n }\n for (const branch of sweep.unpushed) {\n warnings.push(\n `${branch.branch} in ${branch.path} (${branch.repo}) is ${branch.ahead} commit(s) ahead of its remote.`,\n );\n }\n}\n\n/**\n * Record whatever git state the initiative has not written down. The operator\n * chose recording over refusing: a wrap never fails because a worktree was\n * untracked, only because writing the record itself failed.\n *\n * MUST run inside the initiative lock — `recordUnrecorded` takes none of its own.\n */\nasync function sweepAndRecord(\n slug: string,\n activeRoot: string,\n warnings: string[],\n): Promise<typeof NOTHING_RECORDED> {\n let sweep: SweepResult;\n try {\n sweep = await sweepInitiative(slug, activeRoot, process.cwd());\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n warnings.push(`Could not sweep git state for unrecorded artifacts: ${reason}`);\n return NOTHING_RECORDED;\n }\n warnUnrecordable(sweep, warnings);\n return recordUnrecorded(slug, activeRoot, sweep.unrecorded);\n}\n\n/**\n * Which `resolves` entries of the session just written closed nothing, and why.\n *\n * Derived by re-running the canonical derivation over the initiative rather\n * than re-implementing the rules: a second classifier that disagreed with\n * `deriveOpenLoops` would report a close that bootstrap still shows as open.\n */\nasync function rejectedResolves(\n initiativeDir: string,\n filename: string,\n): Promise<RejectedResolve[]> {\n const stem = filename.replace(/\\.md$/, '');\n const dangling = await findDanglingResolves(initiativeDir);\n return dangling\n .filter((entry) => entry.sessionFile === stem)\n .map(({ ref, kind }) => ({ ref, kind }));\n}\n\nconst REMEDY: Record<DanglingKind, string> = {\n missing: 'no loop carries that ref — check the session-file stem and the next_steps id',\n 'not-prior':\n 'the loop was opened by a session that did not end strictly before this one — re-file the resolve from a later session',\n self: 'a session cannot close a loop it opened — carry it as a next_step instead',\n};\n\n/**\n * The session is on disk by the time this runs and the message says so: an\n * agent that typo'd one ref should re-file that ref, not re-run the wrap and\n * duplicate the narrative.\n *\n * This rides `ctx.warnings` rather than a thrown error. Throwing discarded the\n * receipt — the one case `ready_to_end: false` and `resolves_rejected[]` exist\n * to describe was also the one case no caller could read them, leaving the\n * machine-readable half of the contract available only as prose to parse.\n */\nfunction rejectionReport(sessionPath: string, rejected: RejectedResolve[], total: number): string {\n const lines = rejected.map((r) => ` - ${r.ref} (${r.kind}): ${REMEDY[r.kind]}`);\n return (\n `Session written to ${sessionPath}, but ${rejected.length} of ${total} ` +\n `--resolves entries closed no loop:\\n${lines.join('\\n')}\\n` +\n 'The session file and brief.updated are committed, so ready_to_end is false: ' +\n 're-file only the rejected refs from a later session.'\n );\n}\n\nfunction filesUpdated(initiativeDir: string, notePaths: string[], recorded: Filed): string[] {\n const files = ['brief.md'];\n if (recorded.worktrees + recorded.branches + recorded.stashes > 0) {\n files.push('artifacts.yml');\n }\n return files.concat(notePaths.map((p) => path.relative(initiativeDir, p)));\n}\n\nexport default defineCommand<Args, Result>({\n name: 'wrap',\n description:\n 'The last thing a session does. Treat it as the moment the process exits: everything ' +\n 'not persisted before wrap returns is lost, so file it first and wrap last. Every ' +\n 'category the session can leave behind needs an explicit answer, and omitting one is ' +\n 'an error rather than a default — open loops (--next-steps / --resolves, or --no-loops), ' +\n 'durable notes (--notes or --no-notes), and tasks created this session (--tasks-filed or ' +\n '--no-tasks). Writes the session file and its ledger, files the notes under ' +\n 'sources/notes/, records any worktrees, branches and stashes the initiative had not ' +\n \"written down, stamps the brief's updated date, and returns a receipt of what was filed.\",\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n session_id: {\n long: '--session-id',\n description: 'Claude session identifier',\n required: true,\n },\n started: {\n long: '--started',\n description: 'ISO 8601 session start timestamp',\n required: true,\n },\n ended: {\n long: '--ended',\n description: 'ISO 8601 session end timestamp',\n required: true,\n },\n track: {\n long: '--track',\n description:\n \"'canonical' (mainline thread) | 'sidecar' (folded/derived) | 'adhoc' (parallel ad-hoc work) (default: canonical)\",\n },\n body: {\n long: '--body',\n description: 'Raw markdown body (session narrative)',\n },\n body_file: {\n long: '--body-file',\n description: 'Path to a file containing the markdown body',\n },\n next_steps: {\n long: '--next-steps',\n description:\n 'JSON array of loops this session opens: [{\"id\",\"text\",\"kind\":\"task|pr|prose\",\"ref\"?}]',\n },\n resolves: {\n long: '--resolves',\n description:\n 'JSON array of loops this session closes: [{\"ref\":\"<session-file-stem>#<id>\",\"outcome\":\"done|abandoned\",\"note\"?}]',\n },\n no_loops: {\n long: '--no-loops',\n description:\n 'Assert that this session leaves nothing hanging. Records no_loops: true so a deliberate empty ledger is distinguishable from an unfiled one. Mutually exclusive with --next-steps / --resolves.',\n },\n notes: {\n long: '--notes',\n description:\n 'JSON array of durable notes to file under sources/notes/: [{\"kind\":\"process|gotcha|fyi|decision\",\"title\",\"body\",\"tags\"?}]',\n },\n no_notes: {\n long: '--no-notes',\n description:\n 'Assert that this session produced no durable knowledge worth keeping. Mutually exclusive with --notes.',\n },\n tasks_filed: {\n long: '--tasks-filed',\n description:\n 'JSON array of task ids created during this session, e.g. [\"AW-66\",\"AW-67\"]. Each must already exist in the initiative.',\n },\n no_tasks: {\n long: '--no-tasks',\n description:\n 'Assert that this session filed no tasks. Mutually exclusive with --tasks-filed.',\n },\n },\n usage:\n 'active-work wrap <slug> --session-id <id> --started <iso> --ended <iso> [--track canonical|sidecar|adhoc] (--body <text> | --body-file <path>) (--next-steps <json> | --resolves <json> | --no-loops) (--notes <json> | --no-notes) (--tasks-filed <json> | --no-tasks)',\n },\n async run(args, ctx) {\n const initiativeDir = path.join(ctx.activeRoot, args.slug);\n const briefPath = path.join(initiativeDir, 'brief.md');\n try {\n await fs.access(briefPath);\n } catch {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n\n const ledger: Ledger = {\n next_steps: parseLedger(args.next_steps, NextStepsSchema, 'next-steps'),\n resolves: parseLedger(args.resolves, ResolvesSchema, 'resolves'),\n };\n const notes = parseLedger(args.notes, NotesSchema, 'notes');\n const taskIds = parseLedger(args.tasks_filed, TaskIdsSchema, 'tasks-filed');\n requireAnswers(args, ledger, notes, taskIds);\n const body = args.body ?? (await fs.readFile(args.body_file!, 'utf8'));\n\n return withFileLock(getLockPath(args.slug), async () => {\n await verifyTaskIds(initiativeDir, taskIds);\n const written = await writeWrap(args, briefPath, body, ledger);\n let notePaths: string[] = [];\n let recorded = NOTHING_RECORDED;\n try {\n notePaths = await fileNotes(initiativeDir, notes, written.updated);\n recorded = await sweepAndRecord(args.slug, ctx.activeRoot, ctx.warnings);\n } catch (err) {\n await Promise.all([...notePaths, written.path].map((p) => fs.rm(p, { force: true })));\n throw err;\n }\n\n const total = ledger.resolves.length;\n const rejected = await rejectedResolves(initiativeDir, written.filename);\n const filed: Filed = {\n next_steps: ledger.next_steps.length,\n notes: notePaths.length,\n tasks: taskIds.length,\n ...recorded,\n };\n const result: Result = {\n path: written.path,\n filename: written.filename,\n ready_to_end: rejected.length === 0,\n filed,\n closed: { resolves_applied: total - rejected.length },\n resolves_rejected: rejected,\n updated: written.updated,\n files_updated: filesUpdated(initiativeDir, notePaths, filed),\n };\n if (rejected.length > 0) {\n ctx.warnings.push(rejectionReport(written.path, rejected, total));\n }\n return result;\n });\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport {\n SessionFrontmatterSchema,\n type NextStep,\n type SessionResolve,\n} from '../schemas/session.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { ValidationError } from '../errors.js';\n\nexport interface SessionWriteInput {\n slug: string;\n session_id: string;\n started: string;\n ended: string;\n track: 'canonical' | 'sidecar' | 'adhoc';\n body: string;\n next_steps?: NextStep[];\n resolves?: SessionResolve[];\n no_loops?: true;\n /**\n * Override the resolved active root. Migrations are handed the root they\n * operate on as an argument and must not fall back to the process-wide\n * `getActiveRoot()`, which would write into the operator's live data.\n */\n activeRoot?: string;\n}\n\nexport interface SessionWriteResult {\n path: string;\n filename: string;\n}\n\nfunction formatStartedStamp(started: string): string {\n const parsed = new Date(started);\n if (Number.isNaN(parsed.getTime())) {\n throw new ValidationError(`Invalid started timestamp: ${started}`);\n }\n const yyyy = parsed.getUTCFullYear().toString().padStart(4, '0');\n const mm = (parsed.getUTCMonth() + 1).toString().padStart(2, '0');\n const dd = parsed.getUTCDate().toString().padStart(2, '0');\n const hh = parsed.getUTCHours().toString().padStart(2, '0');\n const min = parsed.getUTCMinutes().toString().padStart(2, '0');\n return `${yyyy}-${mm}-${dd}-${hh}${min}`;\n}\n\n/**\n * The filename stem a session gets from its `started` + `session_id`, minus\n * the `.md` extension and any de-duplication suffix. This is the first half\n * of a loop ref (`<stem>#<next_step id>`), so callers that need to predict a\n * session's path — the v2→v3 migration, which keys idempotence on the exact\n * target path — must derive it from here rather than reimplementing it.\n */\nexport function buildSessionStem(started: string, sessionId: string): string {\n return `${formatStartedStamp(started)}-${sessionId}`;\n}\n\n/** Absolute path a session with this stem would occupy on a first write. */\nexport function sessionFilePathForStem(slug: string, stem: string, activeRoot?: string): string {\n return path.join(resolveSessionsDir(slug, activeRoot), `${stem}.md`);\n}\n\nfunction resolveSessionsDir(slug: string, activeRoot?: string): string {\n const dir = activeRoot === undefined ? getInitiativeDir(slug) : path.join(activeRoot, slug);\n return path.join(dir, 'sessions');\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function pickAvailableFilename(\n dir: string,\n baseName: string,\n): Promise<{ filename: string; fullPath: string }> {\n const initial = `${baseName}.md`;\n const initialPath = path.join(dir, initial);\n if (!(await exists(initialPath))) {\n return { filename: initial, fullPath: initialPath };\n }\n for (let i = 1; i < 10_000; i++) {\n const candidate = `${baseName}-${i}.md`;\n const candidatePath = path.join(dir, candidate);\n if (!(await exists(candidatePath))) {\n return { filename: candidate, fullPath: candidatePath };\n }\n }\n throw new Error(`Could not find an available filename for ${baseName}`);\n}\n\n/**\n * Write `<slug>/sessions/<YYYY-MM-DD-HHMM>-<session_id>.md`, validating the\n * frontmatter first. `wrap` is the only command that writes sessions through\n * here; `fold` writes its derived sidecars directly.\n */\nexport async function writeSessionFile(input: SessionWriteInput): Promise<SessionWriteResult> {\n const sessionsDir = resolveSessionsDir(input.slug, input.activeRoot);\n await fs.mkdir(sessionsDir, { recursive: true });\n\n const baseName = buildSessionStem(input.started, input.session_id);\n const { filename, fullPath } = await pickAvailableFilename(sessionsDir, baseName);\n\n await writeFrontmatter(\n fullPath,\n {\n session_id: input.session_id,\n started: input.started,\n ended: input.ended,\n track: input.track,\n next_steps: input.next_steps ?? [],\n resolves: input.resolves ?? [],\n ...(input.no_loops === true ? { no_loops: true } : {}),\n },\n input.body,\n SessionFrontmatterSchema,\n );\n\n return { path: fullPath, filename };\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { NOTE_TITLE_MAX_LENGTH, NoteKindSchema } from '../schemas/note.js';\nimport { writeNoteFile } from '../notes/note-file.js';\nimport { getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z\n .object({\n slug: z.string().min(1),\n kind: NoteKindSchema,\n title: z\n .string()\n .min(1)\n .max(NOTE_TITLE_MAX_LENGTH, {\n message: `Title must be at most ${NOTE_TITLE_MAX_LENGTH} characters — it is slugified into the filename`,\n }),\n body: z.string().optional(),\n body_file: z.string().optional(),\n tags: z.array(z.string().min(1)).optional(),\n })\n .superRefine((value, ctx) => {\n const hasBody = value.body !== undefined;\n const hasFile = value.body_file !== undefined;\n if (!hasBody && !hasFile) {\n ctx.addIssue({\n code: 'custom',\n path: ['body'],\n message: 'Exactly one of --body or --body-file is required',\n });\n }\n if (hasBody && hasFile) {\n ctx.addIssue({\n code: 'custom',\n path: ['body'],\n message: '--body and --body-file are mutually exclusive',\n });\n }\n });\n\nconst ResultSchema = z.object({\n path: z.string(),\n filename: z.string(),\n kind: NoteKindSchema,\n title: z.string(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'note.add',\n description:\n 'File a durable note under <slug>/sources/notes/ — a process lesson, gotcha, decision, or FYI that a future session needs but that no task would carry. Actionable work belongs in `task add` instead.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n kind: {\n long: '--kind',\n description: 'process | gotcha | fyi | decision',\n required: true,\n },\n title: {\n long: '--title',\n description: `Short title, at most ${NOTE_TITLE_MAX_LENGTH} chars (slugified into the filename)`,\n required: true,\n },\n body: { long: '--body', description: 'Raw markdown body' },\n body_file: {\n long: '--body-file',\n description: 'Path to a file containing the markdown body',\n },\n tags: { long: '--tags', description: 'Comma-separated tags' },\n },\n usage:\n 'active-work note add <slug> --kind <process|gotcha|fyi|decision> --title <text> (--body <text> | --body-file <path>) [--tags a,b]',\n },\n async run(args) {\n const initiativeDir = getInitiativeDir(args.slug);\n try {\n await fs.access(path.join(initiativeDir, 'brief.md'));\n } catch {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n\n const body = args.body ?? (await fs.readFile(args.body_file!, 'utf8'));\n const frontmatter = {\n kind: args.kind,\n title: args.title,\n created: today(),\n ...(args.tags && args.tags.length > 0 ? { tags: args.tags } : {}),\n };\n\n return withFileLock(getLockPath(args.slug), async () => {\n const written = await writeNoteFile(initiativeDir, frontmatter, body);\n return { ...written, kind: args.kind, title: args.title };\n });\n },\n});\n","import { z } from 'zod';\nimport { NoteKindSchema } from '../schemas/note.js';\nimport { loadNotesFromDir } from '../notes/note-file.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n kind: NoteKindSchema.optional(),\n});\n\nconst NoteEntrySchema = z.object({\n filename: z.string(),\n path: z.string(),\n kind: NoteKindSchema,\n title: z.string(),\n created: z.string(),\n tags: z.array(z.string()).optional(),\n});\n\nconst ResultSchema = z.object({\n notes: z.array(NoteEntrySchema),\n // Unreadable files are reported, never dropped: a note that silently\n // disappears is exactly the knowledge loss notes exist to prevent.\n errors: z.array(z.object({ filename: z.string(), error: z.string() })),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'note.list',\n description: 'List durable notes for an initiative, newest first.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n kind: {\n long: '--kind',\n description: 'Only notes of this kind: process | gotcha | fyi | decision',\n },\n },\n usage: 'active-work note list <slug> [--kind process|gotcha|fyi|decision]',\n },\n async run(args) {\n const { notes, malformed } = await loadNotesFromDir(getInitiativeDir(args.slug));\n const selected = args.kind\n ? notes.filter((note) => note.frontmatter.kind === args.kind)\n : notes;\n return {\n notes: selected.map((note) => ({\n filename: note.filename,\n path: note.path,\n kind: note.frontmatter.kind,\n title: note.frontmatter.title,\n created: note.frontmatter.created,\n ...(note.frontmatter.tags ? { tags: note.frontmatter.tags } : {}),\n })),\n errors: malformed.map((entry) => ({\n filename: entry.file,\n error: entry.reason,\n })),\n };\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { ArtifactsSchema } from '../schemas/artifacts.js';\nimport { getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n repo: z.string().min(1),\n name: z.string().min(1),\n note: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n branch: z.object({\n repo: z.string(),\n name: z.string(),\n note: z.string().optional(),\n }),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'artifact.add-branch',\n description: 'Append or upsert a branch entry in artifacts.yml.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n repo: { long: '--repo', description: 'Repo path or org/repo', required: true },\n name: { long: '--name', description: 'Branch name', required: true },\n note: { long: '--note', description: 'Why this branch is worth tracking' },\n },\n },\n async run(args) {\n const artifactsPath = path.join(getInitiativeDir(args.slug), 'artifacts.yml');\n return withFileLock(getLockPath(args.slug), async () => {\n const current = await readYaml(artifactsPath, ArtifactsSchema);\n const entry = {\n repo: args.repo,\n name: args.name,\n ...(args.note ? { note: args.note } : {}),\n };\n const idx = current.branches.findIndex((b) => b.repo === args.repo && b.name === args.name);\n if (idx >= 0) {\n // Preserve the prior note unless the caller supplied a new one.\n const prior = current.branches[idx]!;\n current.branches[idx] = {\n repo: args.repo,\n name: args.name,\n ...(args.note !== undefined\n ? { note: args.note }\n : prior.note !== undefined\n ? { note: prior.note }\n : {}),\n };\n } else {\n current.branches.push(entry);\n }\n await writeYaml(artifactsPath, current, ArtifactsSchema);\n return {\n slug: args.slug,\n branch: current.branches[idx >= 0 ? idx : current.branches.length - 1]!,\n };\n });\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { ArtifactsSchema } from '../schemas/artifacts.js';\nimport { getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n repo: z.string().min(1),\n label: z.string().min(1),\n sha: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n stash: z.object({\n repo: z.string(),\n label: z.string(),\n sha: z.string().optional(),\n }),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'artifact.add-stash',\n description: 'Append a stash entry to artifacts.yml.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n repo: { long: '--repo', description: 'Repo path', required: true },\n label: { long: '--label', description: 'Stash label', required: true },\n sha: { long: '--sha', description: 'Stash SHA, if known' },\n },\n },\n async run(args) {\n const artifactsPath = path.join(getInitiativeDir(args.slug), 'artifacts.yml');\n return withFileLock(getLockPath(args.slug), async () => {\n const current = await readYaml(artifactsPath, ArtifactsSchema);\n const entry = {\n repo: args.repo,\n label: args.label,\n ...(args.sha ? { sha: args.sha } : {}),\n };\n current.stashes.push(entry);\n await writeYaml(artifactsPath, current, ArtifactsSchema);\n return { slug: args.slug, stash: entry };\n });\n },\n});\n","import { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { ArtifactsSchema, type Artifacts } from '../schemas/artifacts.js';\nimport { getActiveRoot, getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml } from '../utils/yaml-io.js';\nimport { UsageError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().optional(),\n all_initiatives: z.boolean().optional(),\n});\n\nconst ItemSchema = z.object({\n slug: z.string(),\n artifacts: ArtifactsSchema,\n});\n\nconst ResultSchema = z.object({\n items: z.array(ItemSchema),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nasync function readForSlug(slug: string): Promise<Artifacts> {\n const artifactsPath = path.join(getInitiativeDir(slug), 'artifacts.yml');\n return withFileLock(getLockPath(slug), () => readYaml(artifactsPath, ArtifactsSchema));\n}\n\nasync function listInitiativeSlugs(): Promise<string[]> {\n const root = getActiveRoot();\n let entries: Dirent[];\n try {\n entries = await fs.readdir(root, { withFileTypes: true });\n } catch {\n return [];\n }\n const slugs: string[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (entry.name.startsWith('.')) continue;\n const artifactsPath = path.join(root, entry.name, 'artifacts.yml');\n try {\n await fs.access(artifactsPath);\n slugs.push(entry.name);\n } catch {\n // skip dirs without artifacts.yml\n }\n }\n slugs.sort();\n return slugs;\n}\n\nexport default defineCommand<Args, Result>({\n name: 'artifact.list',\n description: 'List artifacts for a slug or across all initiatives.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n all_initiatives: {\n long: '--all-initiatives',\n description: 'Return artifacts for every initiative',\n },\n },\n },\n async run(args) {\n if (args.all_initiatives) {\n const slugs = await listInitiativeSlugs();\n const items: Array<{ slug: string; artifacts: Artifacts }> = [];\n for (const slug of slugs) {\n items.push({ slug, artifacts: await readForSlug(slug) });\n }\n return { items };\n }\n if (!args.slug) {\n throw new UsageError('artifact.list requires <slug> or --all-initiatives');\n }\n const artifacts = await readForSlug(args.slug);\n return { items: [{ slug: args.slug, artifacts }] };\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { ArtifactsSchema } from '../schemas/artifacts.js';\nimport { getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { UsageError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n repo: z.string().min(1),\n name: z.string().min(1),\n note: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n branch: z.object({\n repo: z.string(),\n name: z.string(),\n note: z.string(),\n }),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'artifact.note',\n description: 'Set or update the free-form note on a tracked branch.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n repo: { long: '--repo', description: 'Repo path or org/repo', required: true },\n name: { long: '--name', description: 'Branch name', required: true },\n note: { long: '--note', description: 'Note text', required: true },\n },\n },\n async run(args) {\n const artifactsPath = path.join(getInitiativeDir(args.slug), 'artifacts.yml');\n return withFileLock(getLockPath(args.slug), async () => {\n const current = await readYaml(artifactsPath, ArtifactsSchema);\n const idx = current.branches.findIndex((b) => b.repo === args.repo && b.name === args.name);\n if (idx < 0) {\n throw new UsageError(\n `No tracked branch '${args.name}' in repo '${args.repo}'. Add it first via 'artifact add-branch'.`,\n );\n }\n const updated = { repo: args.repo, name: args.name, note: args.note };\n current.branches[idx] = updated;\n await writeYaml(artifactsPath, current, ArtifactsSchema);\n return { slug: args.slug, branch: updated };\n });\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { ArtifactsSchema, type BranchEntry } from '../schemas/artifacts.js';\nimport { getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { defineCommand } from '../registry/index.js';\nimport { getGitRunner, resolveLocalRepoPath } from '../utils/git-gh.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n apply: z.boolean().optional(),\n});\n\nconst PrunedSchema = z.object({\n repo: z.string(),\n name: z.string(),\n reason: z.string(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n applied: z.boolean(),\n pruned: z.array(PrunedSchema),\n kept_count: z.number().int().nonnegative(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nasync function branchExists(repoPath: string, name: string): Promise<boolean> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', repoPath, 'rev-parse', '--verify', `refs/heads/${name}`]);\n return res.code === 0;\n } catch {\n return false;\n }\n}\n\nasync function classifyBranch(\n branch: BranchEntry,\n): Promise<{ keep: true } | { keep: false; reason: string }> {\n const repoPath = resolveLocalRepoPath(branch.repo);\n if (!repoPath) {\n // `org/repo` style — we have no local clone to verify against, so\n // keep it: prune should never delete a tracked branch we can't see.\n return { keep: true };\n }\n const present = await branchExists(repoPath, branch.name);\n if (present) return { keep: true };\n return { keep: false, reason: 'branch missing in local repo' };\n}\n\nconst artifactPrune = defineCommand<Args, Result>({\n name: 'artifact.prune',\n description: 'List (default) or remove (--apply) tracked branches that no longer exist locally.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n apply: {\n long: '--apply',\n description: 'Write the pruned artifacts.yml. Without this, dry-run only.',\n },\n },\n },\n async run(args) {\n const artifactsPath = path.join(getInitiativeDir(args.slug), 'artifacts.yml');\n const apply = args.apply ?? false;\n return withFileLock(getLockPath(args.slug), async () => {\n const current = await readYaml(artifactsPath, ArtifactsSchema);\n const keep: BranchEntry[] = [];\n const pruned: Array<{ repo: string; name: string; reason: string }> = [];\n for (const branch of current.branches) {\n const verdict = await classifyBranch(branch);\n if (verdict.keep) {\n keep.push(branch);\n } else {\n pruned.push({ repo: branch.repo, name: branch.name, reason: verdict.reason });\n }\n }\n if (apply && pruned.length > 0) {\n current.branches = keep;\n await writeYaml(artifactsPath, current, ArtifactsSchema);\n }\n return {\n slug: args.slug,\n applied: apply && pruned.length > 0,\n pruned,\n kept_count: keep.length,\n };\n });\n },\n});\n\nexport default artifactPrune;\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { ArtifactsSchema, type WorktreeEntry } from '../schemas/artifacts.js';\nimport { getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml } from '../utils/yaml-io.js';\nimport { defineCommand } from '../registry/index.js';\nimport {\n getGhRunner,\n getGitRunner,\n resolveLocalRepoPath,\n resolveOrgRepo,\n} from '../utils/git-gh.js';\nimport { readWorktreeState } from '../utils/git-worktrees.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n});\n\nconst PrInfoSchema = z.object({\n number: z.number().int(),\n state: z.string(),\n title: z.string(),\n url: z.string(),\n checks: z.string().optional(),\n});\n\nconst BranchStatusSchema = z.object({\n repo: z.string(),\n name: z.string(),\n note: z.string().optional(),\n present: z.boolean(),\n last_commit_iso: z.string().nullable(),\n ahead: z.number().int().nullable(),\n behind: z.number().int().nullable(),\n pr: PrInfoSchema.nullable(),\n error: z.string().optional(),\n});\n\n/**\n * Persisted worktree identity plus live state read from git. The live half\n * is never written back to `artifacts.yml` — see `src/schemas/artifacts.ts`.\n */\nconst WorktreeStatusSchema = z.object({\n path: z.string(),\n repo: z.string(),\n branch: z.string().nullable(),\n holding: z.string().optional(),\n pr: z.number().int().optional(),\n note: z.string().optional(),\n present: z.boolean(),\n /** Null when git could not read the tree. Unknown is not clean. */\n dirty: z.boolean().nullable(),\n files_changed: z.number().int().nullable(),\n ahead: z.number().int().nullable(),\n behind: z.number().int().nullable(),\n has_upstream: z.boolean(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n branches: z.array(BranchStatusSchema),\n worktrees: z.array(WorktreeStatusSchema),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\ntype BranchStatus = z.infer<typeof BranchStatusSchema>;\ntype WorktreeStatus = z.infer<typeof WorktreeStatusSchema>;\ntype PrInfo = z.infer<typeof PrInfoSchema>;\n\ninterface BranchInput {\n repo: string;\n name: string;\n note?: string;\n}\n\nconst MAX_CONCURRENCY = 8;\n\nexport { setGitRunner, setGhRunner, resetRunners } from '../utils/git-gh.js';\n\n/**\n * Bounded-parallel map. Runs `worker(item)` for each item in `items`,\n * with at most `concurrency` in-flight at any time. Preserves order.\n */\nasync function mapConcurrent<I, O>(\n items: I[],\n concurrency: number,\n worker: (item: I, index: number) => Promise<O>,\n): Promise<O[]> {\n const results: O[] = new Array(items.length);\n let cursor = 0;\n async function pump(): Promise<void> {\n while (true) {\n const i = cursor++;\n if (i >= items.length) return;\n results[i] = await worker(items[i]!, i);\n }\n }\n const lanes = Array.from({ length: Math.min(concurrency, items.length) }, () => pump());\n await Promise.all(lanes);\n return results;\n}\n\nasync function checkBranchPresent(repoPath: string, name: string): Promise<boolean> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', repoPath, 'rev-parse', '--verify', `refs/heads/${name}`]);\n return res.code === 0;\n } catch {\n return false;\n }\n}\n\nasync function lastCommitIso(repoPath: string, name: string): Promise<string | null> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', repoPath, 'log', '-1', '--format=%cI', name]);\n if (res.code !== 0) return null;\n const stamp = res.stdout.trim();\n return stamp.length > 0 ? stamp : null;\n } catch {\n return null;\n }\n}\n\nasync function detectDefaultBase(repoPath: string): Promise<string | null> {\n const git = getGitRunner();\n for (const candidate of ['main', 'master']) {\n try {\n const res = await git('git', [\n '-C',\n repoPath,\n 'rev-parse',\n '--verify',\n `refs/remotes/origin/${candidate}`,\n ]);\n if (res.code === 0) return candidate;\n } catch {\n // continue\n }\n }\n return null;\n}\n\nasync function aheadBehind(\n repoPath: string,\n name: string,\n): Promise<{ ahead: number | null; behind: number | null }> {\n const base = await detectDefaultBase(repoPath);\n if (!base) return { ahead: null, behind: null };\n const git = getGitRunner();\n try {\n const res = await git('git', [\n '-C',\n repoPath,\n 'rev-list',\n '--left-right',\n '--count',\n `origin/${base}...${name}`,\n ]);\n if (res.code !== 0) return { ahead: null, behind: null };\n // Output is \"<behind>\\t<ahead>\" (left is base, right is branch).\n const parts = res.stdout.trim().split(/\\s+/);\n if (parts.length !== 2) return { ahead: null, behind: null };\n const behind = Number(parts[0]);\n const ahead = Number(parts[1]);\n if (!Number.isFinite(behind) || !Number.isFinite(ahead)) {\n return { ahead: null, behind: null };\n }\n return { ahead, behind };\n } catch {\n return { ahead: null, behind: null };\n }\n}\n\nasync function fetchPrInfo(orgRepo: string, name: string): Promise<PrInfo | null> {\n const gh = getGhRunner();\n try {\n const res = await gh('gh', [\n 'pr',\n 'list',\n '--head',\n name,\n '--repo',\n orgRepo,\n '--json',\n 'number,state,title,url,statusCheckRollup',\n '--limit',\n '1',\n ]);\n if (res.code !== 0) return null;\n const parsed = JSON.parse(res.stdout) as Array<{\n number?: number;\n state?: string;\n title?: string;\n url?: string;\n statusCheckRollup?: Array<{ conclusion?: string; state?: string }>;\n }>;\n if (!Array.isArray(parsed) || parsed.length === 0) return null;\n const first = parsed[0]!;\n if (\n typeof first.number !== 'number' ||\n typeof first.state !== 'string' ||\n typeof first.title !== 'string' ||\n typeof first.url !== 'string'\n ) {\n return null;\n }\n const checks = summarizeChecks(first.statusCheckRollup ?? []);\n return {\n number: first.number,\n state: first.state,\n title: first.title,\n url: first.url,\n ...(checks ? { checks } : {}),\n };\n } catch {\n return null;\n }\n}\n\nfunction summarizeChecks(\n rollup: Array<{ conclusion?: string; state?: string }>,\n): string | undefined {\n if (rollup.length === 0) return undefined;\n let pass = 0;\n let fail = 0;\n let pending = 0;\n for (const entry of rollup) {\n const tag = (entry.conclusion ?? entry.state ?? '').toUpperCase();\n if (tag === 'SUCCESS') pass++;\n else if (tag === 'FAILURE' || tag === 'CANCELLED' || tag === 'TIMED_OUT') fail++;\n else pending++;\n }\n if (fail > 0) return `fail (${fail}/${rollup.length})`;\n if (pending > 0) return `pending (${pending}/${rollup.length})`;\n return `pass (${pass}/${rollup.length})`;\n}\n\nasync function statusForBranch(branch: BranchInput): Promise<BranchStatus> {\n const out: BranchStatus = {\n repo: branch.repo,\n name: branch.name,\n ...(branch.note ? { note: branch.note } : {}),\n present: false,\n last_commit_iso: null,\n ahead: null,\n behind: null,\n pr: null,\n };\n\n const repoPath = resolveLocalRepoPath(branch.repo);\n\n try {\n if (repoPath) {\n out.present = await checkBranchPresent(repoPath, branch.name);\n if (out.present) {\n out.last_commit_iso = await lastCommitIso(repoPath, branch.name);\n const { ahead, behind } = await aheadBehind(repoPath, branch.name);\n out.ahead = ahead;\n out.behind = behind;\n }\n }\n\n const orgRepo = await resolveOrgRepo(branch.repo);\n if (orgRepo) {\n out.pr = await fetchPrInfo(orgRepo, branch.name);\n }\n } catch (err) {\n out.error = err instanceof Error ? err.message : String(err);\n }\n\n return out;\n}\n\nasync function statusForWorktree(entry: WorktreeEntry): Promise<WorktreeStatus> {\n const live = await readWorktreeState(entry.path);\n return {\n path: entry.path,\n repo: entry.repo,\n branch: live.branch ?? entry.branch ?? null,\n ...(entry.holding ? { holding: entry.holding } : {}),\n ...(entry.pr ? { pr: entry.pr } : {}),\n ...(entry.note ? { note: entry.note } : {}),\n present: live.present,\n dirty: live.dirty,\n files_changed: live.files_changed,\n ahead: live.ahead,\n behind: live.behind,\n has_upstream: live.has_upstream,\n };\n}\n\nconst artifactStatus = defineCommand<Args, Result>({\n name: 'artifact.status',\n description: 'Pull live PR and branch state for the initiative via `git` + `gh`. Read-only.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n },\n async run(args) {\n const artifactsPath = path.join(getInitiativeDir(args.slug), 'artifacts.yml');\n const current = await withFileLock(getLockPath(args.slug), () =>\n readYaml(artifactsPath, ArtifactsSchema),\n );\n const branches = await mapConcurrent(current.branches, MAX_CONCURRENCY, statusForBranch);\n const worktrees = await mapConcurrent(current.worktrees, MAX_CONCURRENCY, statusForWorktree);\n return { slug: args.slug, branches, worktrees };\n },\n});\n\nexport default artifactStatus;\n","import { z } from 'zod';\nimport { listSources } from '../sources/list.js';\nimport { lintSources } from '../lint/sources.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n type: z.enum(['pr', 'deepdive', 'session', 'pointer']).optional(),\n});\n\nconst SourceEntrySchema = z.object({\n filename: z.string(),\n path: z.string(),\n type: z.enum(['pr', 'deepdive', 'session', 'pointer']),\n title: z.string(),\n});\n\nconst ResultSchema = z.object({\n sources: z.array(SourceEntrySchema),\n // Drift between the directory and brief.md's hand-written references. Empty\n // when the brief keeps no reference list at all.\n drift: z.array(z.string()),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'source.list',\n description:\n \"List an initiative's sources, derived by reading sources/*.md — never a stored index.\",\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n type: {\n long: '--type',\n description: 'Only sources of this type: pr | deepdive | session | pointer',\n },\n },\n usage: 'active-work source list <slug> [--type pr|deepdive|session|pointer]',\n },\n async run(args) {\n const initiativeDir = getInitiativeDir(args.slug);\n const sources = await listSources(initiativeDir);\n const selected = args.type ? sources.filter((entry) => entry.type === args.type) : sources;\n const findings = await lintSources(args.slug, initiativeDir);\n return {\n sources: selected,\n drift: findings.map((finding) => finding.message),\n };\n },\n});\n","/**\n * Sources are the external material an initiative accumulates: PR write-ups,\n * deep dives, session transcripts, pointers. They live as plain files under\n * `<initiative>/sources/`.\n *\n * There is deliberately no sidecar index and no `sources:` frontmatter field.\n * The listing is derived by reading the directory every time it is asked for,\n * so it cannot drift from what is actually on disk — a hand-maintained list\n * always eventually omits a file someone dropped in by hand (AW-80).\n */\n\nimport { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\n\n/** Naming conventions written by `source add`; see `deriveFilename` there. */\nexport type SourceType = 'pr' | 'deepdive' | 'session' | 'pointer';\n\nexport interface SourceEntry {\n /** Filename including `.md`. */\n filename: string;\n path: string;\n type: SourceType;\n /** First markdown heading, falling back to the filename stem. */\n title: string;\n}\n\n/** Resolve the sources directory for an initiative directory. */\nexport function getSourcesDir(initiativeDir: string): string {\n return path.join(initiativeDir, 'sources');\n}\n\nconst PR_FILENAME = /^pr-(\\d+)-/;\nconst DEEPDIVE_FILENAME = /^deepdive-/;\nconst SESSION_FILENAME = /^\\d{4}-\\d{2}-\\d{2}-/;\n\nfunction inferType(filename: string): SourceType {\n if (PR_FILENAME.test(filename)) return 'pr';\n if (DEEPDIVE_FILENAME.test(filename)) return 'deepdive';\n if (SESSION_FILENAME.test(filename)) return 'session';\n return 'pointer';\n}\n\nfunction firstHeading(contents: string): string | undefined {\n for (const line of contents.split('\\n', 200)) {\n const match = /^#{1,6}\\s+(.+?)\\s*$/.exec(line);\n if (match) return match[1];\n }\n return undefined;\n}\n\nasync function readTitle(filePath: string, filename: string): Promise<string> {\n const stem = filename.replace(/\\.md$/, '');\n try {\n const contents = await fs.readFile(filePath, 'utf8');\n return firstHeading(contents) ?? stem;\n } catch {\n return stem;\n }\n}\n\n/**\n * List an initiative's sources by reading `sources/*.md` at call time.\n *\n * Top-level files only: `sources/notes/` is the durable-notes store with its\n * own reader (`loadNotesFromDir`) and its own place in the bootstrap, so\n * folding it in here would double-report it. A missing `sources/` yields an\n * empty list rather than throwing — every caller treats \"no sources\" and \"no\n * directory yet\" the same way.\n */\nexport async function listSources(initiativeDir: string): Promise<SourceEntry[]> {\n const dir = getSourcesDir(initiativeDir);\n let entries: Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return [];\n }\n const filenames = entries\n .filter((e) => e.isFile() && e.name.endsWith('.md') && !e.name.startsWith('.'))\n .map((e) => e.name)\n .sort();\n\n return Promise.all(\n filenames.map(async (filename) => {\n const fullPath = path.join(dir, filename);\n return {\n filename,\n path: fullPath,\n type: inferType(filename),\n title: await readTitle(fullPath, filename),\n };\n }),\n );\n}\n\n/** Every `sources/...md` path mentioned in a chunk of markdown, deduped. */\nexport function extractSourceReferences(body: string): string[] {\n const matches = body.matchAll(/sources\\/([A-Za-z0-9._/-]+\\.md)/g);\n const seen = new Set<string>();\n for (const match of matches) {\n seen.add(match[1]);\n }\n return [...seen].sort();\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readRawFrontmatter } from '../utils/gray-matter-io.js';\nimport { extractSourceReferences, listSources } from '../sources/list.js';\nimport type { LintFinding } from './types.js';\n\nasync function fileExists(target: string): Promise<boolean> {\n try {\n await fs.access(target);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Flag drift between `sources/` on disk and the references hand-written in\n * `brief.md`.\n *\n * The listing itself is always derived from the directory (`source list`), so\n * this rule is about the prose: a brief that keeps a References section is\n * making a promise it has to keep. Two ways it breaks:\n *\n * - it links a `sources/...md` that no longer exists (rename, delete, typo);\n * - a file lands in `sources/` and never gets mentioned — the case that\n * actually bit us, where the References list silently under-reported what\n * the initiative knew.\n *\n * The unmentioned-file rule only fires once a brief references *some* source,\n * because that is the signal it maintains a list at all. Briefs that never\n * link into `sources/` are not silently broken and must not be nagged.\n */\nexport async function lintSources(slug: string, initiativeDir: string): Promise<LintFinding[]> {\n const briefPath = path.join(initiativeDir, 'brief.md');\n if (!(await fileExists(briefPath))) return [];\n\n const { body } = await readRawFrontmatter(briefPath);\n const referenced = extractSourceReferences(body);\n if (referenced.length === 0) return [];\n\n const findings: LintFinding[] = [];\n\n for (const ref of referenced) {\n const target = path.join(initiativeDir, 'sources', ref);\n if (!(await fileExists(target))) {\n findings.push({\n level: 'warn',\n slug,\n file: 'brief.md',\n message: `references sources/${ref}, which does not exist — fix the link or restore the file`,\n });\n }\n }\n\n const onDisk = await listSources(initiativeDir);\n const missing = onDisk\n .map((entry) => entry.filename)\n .filter((filename) => !referenced.includes(filename));\n\n if (missing.length > 0) {\n findings.push({\n level: 'warn',\n slug,\n file: 'brief.md',\n message:\n `references some sources but not ${missing.map((m) => `sources/${m}`).join(', ')} — ` +\n `the hand-written list drifted; \\`active-work source list ${slug}\\` derives it from the directory`,\n });\n }\n\n return findings;\n}\n","import path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport type { Dirent } from 'node:fs';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getActiveRoot, expandTilde } from '../utils/paths.js';\nimport { readRegisteredWorktrees, type RegisteredWorktree } from '../utils/registered-worktrees.js';\nimport { readFrontmatter } from '../utils/gray-matter-io.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst argsSchema = z.object({}).strict();\n\nconst initiativeSummarySchema = z.object({\n slug: z.string(),\n title: z.string(),\n state: z.enum(['focused', 'backburner', 'paused', 'done']),\n rank: z.number().int().positive().optional(),\n updated: z.string(),\n ship_target: z.string().optional(),\n});\n\nconst parseErrorSchema = z.object({\n slug: z.string(),\n error: z.string(),\n});\n\nconst conflictSchema = z.object({\n path: z.string(),\n slugs: z.array(z.string()),\n});\n\nconst resultSchema = z.object({\n initiatives: z.array(initiativeSummarySchema),\n parse_errors: z.array(parseErrorSchema),\n worktree_conflicts: z.array(conflictSchema),\n});\n\nconst STATE_ORDER: Record<BriefFrontmatter['state'], number> = {\n focused: 0,\n backburner: 1,\n paused: 2,\n done: 3,\n};\n\nexport interface ScanEntry {\n slug: string;\n frontmatter: BriefFrontmatter;\n /** Registered worktrees, which moved to artifacts.yml in v4 (AW-67). */\n worktrees: RegisteredWorktree[];\n}\n\nexport interface ScanError {\n slug: string;\n error: string;\n}\n\nexport interface ScanResult {\n entries: ScanEntry[];\n errors: ScanError[];\n}\n\nexport async function scanInitiatives(activeRoot: string): Promise<ScanResult> {\n let dirents: Dirent[];\n try {\n dirents = await fs.readdir(activeRoot, { withFileTypes: true });\n } catch {\n return { entries: [], errors: [] };\n }\n\n const entries: ScanEntry[] = [];\n const errors: ScanError[] = [];\n\n for (const dirent of dirents) {\n if (!dirent.isDirectory()) continue;\n if (dirent.name.startsWith('.')) continue;\n const slug = dirent.name;\n const briefPath = path.join(activeRoot, slug, 'brief.md');\n try {\n await fs.access(briefPath);\n } catch {\n continue;\n }\n try {\n const { frontmatter } = await readFrontmatter(briefPath, BriefFrontmatterSchema);\n const worktrees = await readRegisteredWorktrees(path.join(activeRoot, slug));\n entries.push({ slug, frontmatter, worktrees });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n errors.push({ slug, error: message });\n }\n }\n\n return { entries, errors };\n}\n\nfunction detectWorktreeConflicts(entries: ScanEntry[]): Array<{ path: string; slugs: string[] }> {\n const byPath = new Map<string, Set<string>>();\n for (const { slug, worktrees } of entries) {\n // Only registered worktrees conflict. Two initiatives whose sweeps both\n // observed the same directory have not laid claim to it.\n for (const entry of worktrees) {\n const resolved = path.resolve(expandTilde(entry.path));\n let bucket = byPath.get(resolved);\n if (!bucket) {\n bucket = new Set();\n byPath.set(resolved, bucket);\n }\n bucket.add(slug);\n }\n }\n const conflicts: Array<{ path: string; slugs: string[] }> = [];\n for (const [resolved, slugs] of byPath) {\n if (slugs.size > 1) {\n conflicts.push({ path: resolved, slugs: [...slugs].sort() });\n }\n }\n conflicts.sort((a, b) => a.path.localeCompare(b.path));\n return conflicts;\n}\n\nfunction compareInitiatives(a: ScanEntry, b: ScanEntry): number {\n const aRank = a.frontmatter.rank ?? Number.POSITIVE_INFINITY;\n const bRank = b.frontmatter.rank ?? Number.POSITIVE_INFINITY;\n if (aRank !== bRank) return aRank - bRank;\n const aState = STATE_ORDER[a.frontmatter.state];\n const bState = STATE_ORDER[b.frontmatter.state];\n if (aState !== bState) return aState - bState;\n return a.slug.localeCompare(b.slug);\n}\n\nexport default defineCommand({\n name: 'audit',\n description:\n 'Cross-initiative summary: lists every initiative, parse failures, and worktree path conflicts.',\n args: argsSchema,\n result: resultSchema,\n cli: {},\n async run() {\n const activeRoot = getActiveRoot();\n const { entries, errors } = await scanInitiatives(activeRoot);\n const initiatives = [...entries].sort(compareInitiatives).map(({ slug, frontmatter }) => ({\n slug,\n title: frontmatter.title,\n state: frontmatter.state,\n ...(frontmatter.rank !== undefined ? { rank: frontmatter.rank } : {}),\n updated: frontmatter.updated,\n ...(frontmatter.ship_target !== undefined ? { ship_target: frontmatter.ship_target } : {}),\n }));\n return {\n initiatives,\n parse_errors: errors,\n worktree_conflicts: detectWorktreeConflicts(entries),\n };\n },\n});\n","/**\n * Deterministic ID-join lookup across an active root (AW-85).\n *\n * The data model cross-references by ID — task ids (`AW-12`), loop refs\n * (`<session file stem>#<next_step id>`), and artifact branch/worktree names\n * that embed a task id. Tracing those links used to mean hand-rolled grep.\n *\n * This command is *exact-join only*: every match is a literal, token-bounded\n * occurrence of the queried id. Topic/paraphrase similarity (\"related sources\n * by topic\") is deliberately NOT here — it is a separate, fuzzy concern and\n * bundling it would make these results non-deterministic.\n */\nimport { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { TaskSchema } from '../schemas/task.js';\nimport { SessionFrontmatterSchema } from '../schemas/session.js';\nimport { ArtifactsSchema, type Artifacts } from '../schemas/artifacts.js';\nimport { getActiveRoot, getInitiativeDir } from '../utils/paths.js';\nimport { readYaml } from '../utils/yaml-io.js';\nimport { readFrontmatter } from '../utils/gray-matter-io.js';\n\nconst TASK_ID_REGEX = /^[A-Z][A-Z0-9]*-\\d+$/;\nconst MAX_SNIPPET = 160;\n\nconst ArgsSchema = z.object({\n id: z.string().min(1),\n slug: z.string().min(1).optional(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ReferenceSchema = z.object({\n slug: z.string(),\n source: z.enum(['task', 'session', 'artifacts']),\n /** Path relative to the initiative directory. */\n file: z.string(),\n /** Dotted/indexed path of the field that carried the match. */\n field: z.string(),\n text: z.string(),\n});\n\nconst SubjectSchema = z.object({\n kind: z.enum(['task', 'session', 'loop']),\n slug: z.string(),\n file: z.string(),\n title: z.string(),\n});\n\nconst ResultSchema = z.object({\n id: z.string(),\n kind: z.enum(['task', 'session', 'loop']),\n subject: SubjectSchema.nullable(),\n references: z.array(ReferenceSchema),\n initiatives_scanned: z.array(z.string()),\n errors: z.array(z.object({ file: z.string(), error: z.string() })),\n});\n\ntype Reference = z.infer<typeof ReferenceSchema>;\ntype Subject = z.infer<typeof SubjectSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\n/** Accumulates one initiative's worth of findings. */\ninterface Scan {\n references: Reference[];\n errors: { file: string; error: string }[];\n subject: Subject | null;\n}\n\n/**\n * Classify the query lexically. `#` is the loop-ref separator and is banned\n * from both halves of a ref, so its presence is unambiguous.\n */\nfunction classify(id: string): 'task' | 'loop' | 'session' {\n if (id.includes('#')) return 'loop';\n if (TASK_ID_REGEX.test(id)) return 'task';\n return 'session';\n}\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Token-bounded, case-insensitive matcher. Case-insensitive because task ids\n * appear lowercased inside branch names (`feat/aw-85-context-graph`); the\n * alphanumeric guards keep `AW-8` from matching `AW-85`.\n */\nfunction buildMatcher(id: string): RegExp {\n return new RegExp(`(?<![A-Za-z0-9])${escapeRegex(id)}(?![A-Za-z0-9])`, 'i');\n}\n\nfunction snippet(text: string): string {\n const trimmed = text.trim();\n return trimmed.length > MAX_SNIPPET ? `${trimmed.slice(0, MAX_SNIPPET)}…` : trimmed;\n}\n\nasync function listSlugs(): Promise<string[]> {\n let entries: Dirent[];\n try {\n entries = await fs.readdir(getActiveRoot(), { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n return entries\n .filter((e) => e.isDirectory() && !e.name.startsWith('.'))\n .map((e) => e.name)\n .sort();\n}\n\nasync function listFiles(dir: string, ext: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(dir);\n return entries.filter((e) => e.endsWith(ext)).sort();\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n}\n\n/** Emit a reference for every free-text field that literally contains the id. */\nfunction matchFields(\n match: RegExp,\n base: Omit<Reference, 'field' | 'text'>,\n fields: [field: string, value: string | undefined][],\n): Reference[] {\n const out: Reference[] = [];\n for (const [field, value] of fields) {\n if (value && match.test(value)) {\n out.push({ ...base, field, text: snippet(value) });\n }\n }\n return out;\n}\n\nasync function scanTasks(slug: string, id: string, match: RegExp, scan: Scan) {\n const dir = path.join(getInitiativeDir(slug), 'tasks');\n for (const file of await listFiles(dir, '.yml')) {\n const rel = path.join('tasks', file);\n try {\n const task = await readYaml(path.join(dir, file), TaskSchema);\n if (task.id === id) {\n scan.subject = { kind: 'task', slug, file: rel, title: task.title };\n continue;\n }\n const base = { slug, source: 'task' as const, file: rel };\n scan.references.push(\n ...matchFields(match, base, [\n ['title', task.title],\n ['done_when', task.done_when],\n ['notes', task.notes],\n ['tags', (task.tags ?? []).join(', ')],\n ]),\n );\n } catch (err) {\n scan.errors.push({ file: rel, error: errorText(err) });\n }\n }\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Body matches are reported per line so the caller gets a locatable hit. */\nfunction matchBody(\n match: RegExp,\n base: Omit<Reference, 'field' | 'text'>,\n body: string,\n): Reference[] {\n const out: Reference[] = [];\n body.split(/\\r?\\n/).forEach((line, index) => {\n if (match.test(line)) {\n out.push({ ...base, field: `body:L${index + 1}`, text: snippet(line) });\n }\n });\n return out;\n}\n\ninterface SessionScanInput {\n slug: string;\n stem: string;\n rel: string;\n id: string;\n match: RegExp;\n frontmatter: z.infer<typeof SessionFrontmatterSchema>;\n body: string;\n}\n\n/**\n * The loop a `<stem>#<step id>` query names is the *subject*, not a reference\n * to itself — everything else in the same file is still fair game.\n */\nfunction scanSessionFile(input: SessionScanInput, scan: Scan): void {\n const { slug, stem, rel, id, match, frontmatter, body } = input;\n const base = { slug, source: 'session' as const, file: rel };\n\n if (id === stem || id === frontmatter.session_id) {\n scan.subject = { kind: 'session', slug, file: rel, title: stem };\n }\n\n frontmatter.next_steps.forEach((step, i) => {\n if (`${stem}#${step.id}` === id) {\n scan.subject = { kind: 'loop', slug, file: rel, title: step.text };\n return;\n }\n scan.references.push(\n ...matchFields(match, base, [\n [`next_steps[${i}].ref`, step.ref],\n [`next_steps[${i}].text`, step.text],\n ]),\n );\n });\n\n frontmatter.resolves.forEach((entry, i) => {\n scan.references.push(\n ...matchFields(match, base, [\n [`resolves[${i}].ref`, entry.ref],\n [`resolves[${i}].note`, entry.note],\n ]),\n );\n });\n\n scan.references.push(...matchBody(match, base, body));\n}\n\nasync function scanSessions(slug: string, id: string, match: RegExp, scan: Scan) {\n const dir = path.join(getInitiativeDir(slug), 'sessions');\n for (const file of await listFiles(dir, '.md')) {\n const rel = path.join('sessions', file);\n try {\n const { frontmatter, body } = await readFrontmatter(\n path.join(dir, file),\n SessionFrontmatterSchema,\n );\n const stem = file.slice(0, -'.md'.length);\n scanSessionFile({ slug, stem, rel, id, match, frontmatter, body }, scan);\n } catch (err) {\n scan.errors.push({ file: rel, error: errorText(err) });\n }\n }\n}\n\nfunction artifactFields(artifacts: Artifacts): [field: string, value: string | undefined][] {\n const fields: [string, string | undefined][] = [];\n artifacts.branches.forEach((b, i) => {\n fields.push([`branches[${i}].name`, b.name], [`branches[${i}].note`, b.note]);\n });\n artifacts.stashes.forEach((s, i) => {\n fields.push([`stashes[${i}].label`, s.label]);\n });\n artifacts.worktrees.forEach((w, i) => {\n fields.push(\n [`worktrees[${i}].branch`, w.branch],\n [`worktrees[${i}].holding`, w.holding],\n [`worktrees[${i}].note`, w.note],\n );\n });\n return fields;\n}\n\nasync function scanArtifacts(slug: string, match: RegExp, scan: Scan) {\n const rel = 'artifacts.yml';\n const file = path.join(getInitiativeDir(slug), rel);\n try {\n await fs.access(file);\n } catch {\n return;\n }\n try {\n const artifacts = await readYaml(file, ArtifactsSchema);\n const base = { slug, source: 'artifacts' as const, file: rel };\n scan.references.push(...matchFields(match, base, artifactFields(artifacts)));\n } catch (err) {\n scan.errors.push({ file: rel, error: errorText(err) });\n }\n}\n\nexport default defineCommand<Args, Result>({\n name: 'context.graph',\n description:\n 'Trace every exact-ID reference to a task id, session, or loop ref across tasks, sessions, and artifacts',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['id'],\n options: {\n slug: {\n long: '--slug',\n description: 'Limit the scan to one initiative (default: every initiative)',\n },\n },\n usage: 'context graph <id> [--slug SLUG]',\n },\n async run(args) {\n const match = buildMatcher(args.id);\n const slugs = args.slug ? [args.slug] : await listSlugs();\n\n const scan: Scan = { references: [], errors: [], subject: null };\n for (const slug of slugs) {\n await scanTasks(slug, args.id, match, scan);\n await scanSessions(slug, args.id, match, scan);\n await scanArtifacts(slug, match, scan);\n }\n\n return {\n id: args.id,\n kind: classify(args.id),\n subject: scan.subject,\n references: scan.references,\n initiatives_scanned: slugs,\n errors: scan.errors,\n };\n },\n});\n","import { z } from 'zod';\nimport type { BriefFrontmatter } from '../schemas/brief.js';\nimport { getActiveRoot } from '../utils/paths.js';\nimport { scanInitiatives } from './audit.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst argsSchema = z.object({}).strict();\n\nconst itemSchema = z.object({\n slug: z.string(),\n title: z.string(),\n state: z.enum(['focused', 'backburner', 'paused', 'done']),\n rank: z.number().int().positive().optional(),\n ship_target: z.string().optional(),\n paused_since: z.string().optional(),\n updated: z.string(),\n});\n\nconst sectionSchema = z.object({\n heading: z.string(),\n items: z.array(itemSchema),\n});\n\nconst parseErrorSchema = z.object({\n slug: z.string(),\n error: z.string(),\n});\n\nconst resultSchema = z.object({\n sections: z.array(sectionSchema),\n parse_errors: z.array(parseErrorSchema),\n});\n\ninterface Item {\n slug: string;\n title: string;\n state: BriefFrontmatter['state'];\n rank?: number;\n ship_target?: string;\n paused_since?: string;\n updated: string;\n}\n\nfunction toItem(slug: string, fm: BriefFrontmatter): Item {\n return {\n slug,\n title: fm.title,\n state: fm.state,\n ...(fm.rank !== undefined ? { rank: fm.rank } : {}),\n ...(fm.ship_target !== undefined ? { ship_target: fm.ship_target } : {}),\n ...(fm.paused_since !== undefined ? { paused_since: fm.paused_since } : {}),\n updated: fm.updated,\n };\n}\n\nexport default defineCommand({\n name: 'list',\n description: 'List every initiative grouped by state. Replaces the legacy INDEX.md dump.',\n args: argsSchema,\n result: resultSchema,\n cli: {\n usage: 'list',\n },\n async run() {\n const activeRoot = getActiveRoot();\n const { entries, errors } = await scanInitiatives(activeRoot);\n\n const focused: Item[] = [];\n const backburner: Item[] = [];\n const paused: Item[] = [];\n const done: Item[] = [];\n\n for (const { slug, frontmatter } of entries) {\n const item = toItem(slug, frontmatter);\n switch (frontmatter.state) {\n case 'focused':\n focused.push(item);\n break;\n case 'backburner':\n backburner.push(item);\n break;\n case 'paused':\n paused.push(item);\n break;\n case 'done':\n done.push(item);\n break;\n }\n }\n\n focused.sort((a, b) => {\n const aRank = a.rank ?? Number.POSITIVE_INFINITY;\n const bRank = b.rank ?? Number.POSITIVE_INFINITY;\n if (aRank !== bRank) return aRank - bRank;\n return a.slug.localeCompare(b.slug);\n });\n backburner.sort((a, b) => a.slug.localeCompare(b.slug));\n paused.sort((a, b) => {\n const aPaused = a.paused_since ?? '';\n const bPaused = b.paused_since ?? '';\n if (aPaused !== bPaused) return aPaused.localeCompare(bPaused);\n return a.slug.localeCompare(b.slug);\n });\n done.sort((a, b) => {\n if (a.updated !== b.updated) return b.updated.localeCompare(a.updated);\n return a.slug.localeCompare(b.slug);\n });\n\n return {\n sections: [\n { heading: 'Focused', items: focused },\n { heading: 'Backburner', items: backburner },\n { heading: 'Paused', items: paused },\n { heading: 'Done', items: done },\n ],\n parse_errors: errors,\n };\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport type { WorktreeEntry } from '../schemas/artifacts.js';\nimport { getActiveRoot, getLockPath, expandTilde } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readArtifactsFile, writeArtifactsFile } from '../utils/registered-worktrees.js';\nimport { readFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst argsSchema = z.object({\n slug: z.string().min(1),\n path: z.string().min(1),\n label: z.string().min(1).optional(),\n default: z.boolean().optional(),\n});\n\nconst resultSchema = z.object({\n slug: z.string(),\n label: z.string(),\n path: z.string(),\n default: z.boolean(),\n /** True when this promoted a worktree `wrap` had already swept (AW-67). */\n promoted: z.boolean(),\n});\n\nconst DEFAULT_LABEL = 'main';\n\nconst samePath = (a: string, b: string): boolean =>\n path.resolve(expandTilde(a)) === path.resolve(expandTilde(b));\n\nexport default defineCommand({\n name: 'worktree.set',\n description:\n 'Add or update a registered worktree on an existing initiative. A lone worktree is made default automatically; use --default to promote an added one. Registered worktrees live in artifacts.yml alongside the ones wrap sweeps, and are what `aw` resolves a cwd against.',\n args: argsSchema,\n result: resultSchema,\n cli: {\n positional: ['slug', 'path'],\n options: {\n label: {\n long: '--label',\n description: `Worktree label (default: ${DEFAULT_LABEL}).`,\n },\n default: {\n long: '--default',\n description: 'Mark this worktree as the default, clearing default on others.',\n },\n },\n usage: 'active-work worktree.set <slug> <path> [--label <label>] [--default]',\n },\n async run(args) {\n const label = args.label ?? DEFAULT_LABEL;\n const initiativeDir = path.join(getActiveRoot(), args.slug);\n const briefPath = path.join(initiativeDir, 'brief.md');\n return withFileLock(getLockPath(args.slug), async () => {\n let frontmatter: BriefFrontmatter;\n let body: string;\n try {\n ({ frontmatter, body } = await readFrontmatter(briefPath, BriefFrontmatterSchema));\n } catch (err) {\n throw new ValidationError(err instanceof Error ? err.message : String(err));\n }\n\n const artifacts = await readArtifactsFile(initiativeDir);\n const byLabel = artifacts.worktrees.find((entry) => entry.name === label);\n // An unnamed entry at this path was swept by `wrap`. Naming it promotes it\n // in place rather than adding a second record of the same directory.\n const swept = artifacts.worktrees.find(\n (entry) => entry.name === undefined && samePath(entry.path, args.path),\n );\n const target = byLabel ?? swept;\n\n // Default when: explicitly requested, this is the only registered\n // worktree, or we're updating a label that was already the default (don't\n // silently demote it).\n const named = artifacts.worktrees.filter((e) => e.name !== undefined);\n const hadOthers = named.some((entry) => entry.name !== label);\n const makeDefault = args.default === true || !hadOthers || byLabel?.default === true;\n\n const updated: WorktreeEntry = {\n ...(target ?? {}),\n path: args.path,\n repo: target?.repo ?? args.path,\n name: label,\n ...(makeDefault ? { default: true } : {}),\n };\n if (!makeDefault) delete updated.default;\n\n const rest = artifacts.worktrees\n .filter((entry) => entry !== target)\n .map((entry) => {\n if (!makeDefault || entry.default !== true) return entry;\n // A new default clears the flag everywhere else.\n const cleared = { ...entry };\n delete cleared.default;\n return cleared;\n });\n\n await writeArtifactsFile(initiativeDir, {\n ...artifacts,\n worktrees: [...rest, updated],\n });\n await writeFrontmatter(\n briefPath,\n { ...frontmatter, updated: today() },\n body,\n BriefFrontmatterSchema,\n );\n return {\n slug: args.slug,\n label,\n path: args.path,\n default: makeDefault,\n promoted: byLabel === undefined && swept !== undefined,\n };\n });\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getActiveRoot, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readArtifactsFile, writeArtifactsFile } from '../utils/registered-worktrees.js';\nimport { readFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst argsSchema = z.object({\n slug: z.string().min(1),\n label: z.string().min(1),\n});\n\nconst resultSchema = z.object({\n slug: z.string(),\n default_label: z.string(),\n});\n\nexport default defineCommand({\n name: 'worktree.set-default',\n description:\n 'Mark the named worktree label as default for an initiative; clears default on other labels.',\n args: argsSchema,\n result: resultSchema,\n cli: {\n positional: ['slug', 'label'],\n },\n async run({ slug, label }) {\n const initiativeDir = path.join(getActiveRoot(), slug);\n const briefPath = path.join(initiativeDir, 'brief.md');\n return withFileLock(getLockPath(slug), async () => {\n let frontmatter: BriefFrontmatter;\n let body: string;\n try {\n ({ frontmatter, body } = await readFrontmatter(briefPath, BriefFrontmatterSchema));\n } catch (err) {\n throw new ValidationError(err instanceof Error ? err.message : String(err));\n }\n const artifacts = await readArtifactsFile(initiativeDir);\n if (!artifacts.worktrees.some((entry) => entry.name === label)) {\n throw new NotFoundError(`Worktree label \"${label}\" is not registered for \"${slug}\"`);\n }\n const worktrees = artifacts.worktrees.map((entry) => {\n const next = { ...entry };\n delete next.default;\n return entry.name === label ? { ...next, default: true } : next;\n });\n await writeArtifactsFile(initiativeDir, { ...artifacts, worktrees });\n await writeFrontmatter(\n briefPath,\n { ...frontmatter, updated: today() },\n body,\n BriefFrontmatterSchema,\n );\n return { slug, default_label: label };\n });\n },\n});\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { runDiscovery } from '../discover/index.js';\n\n/**\n * `active-work discover` — orchestrates every configured discovery source and emits\n * a flat list of hits. Always non-interactive; Claude is the primary\n * caller, and a human can pipe to a picker.\n */\n\nconst ArgsSchema = z.object({\n github_repos: z.array(z.string().min(1)).optional(),\n local_repos: z.array(z.string().min(1)).optional(),\n projects_root: z.string().optional(),\n});\n\nconst HitSchema = z.object({\n source: z.string(),\n ref: z.string(),\n detail: z.string(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n slug_match: z.string().optional(),\n untracked: z.boolean().optional(),\n});\n\nconst ResultSchema = z.object({\n hits: z.array(HitSchema),\n errors: z.array(z.object({ source: z.string(), error: z.string() })),\n});\n\nexport default defineCommand({\n name: 'discover',\n description:\n 'Scan configured sources (gh PRs, local git, projects root, Claude sessions) and emit unfiltered discovery hits.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n github_repos: {\n long: '--github-repos',\n description: 'Comma-separated owner/repo list for gh PR discovery',\n },\n local_repos: {\n long: '--local-repos',\n description: 'Comma-separated repo paths for local git discovery',\n },\n projects_root: {\n long: '--projects-root',\n description: 'Root directory whose subdirs are scanned as projects',\n },\n },\n },\n async run(args) {\n return runDiscovery({\n github_repos: args.github_repos,\n local_repos: args.local_repos,\n projects_root: args.projects_root,\n });\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { getActiveRoot } from '../utils/paths.js';\nimport type {\n DiscoveryConfig,\n DiscoveryHit,\n DiscoveryResult,\n DiscoverySourceError,\n} from './types.js';\nimport { discoverGitHub } from './github.js';\nimport { discoverGit } from './git.js';\nimport { discoverProjects } from './projects.js';\nimport { discoverClaudeSessions } from './claude.js';\n\n/**\n * Run every discovery source the config asks for, aggregate hits, then\n * cross-reference against the set of known initiative slugs sitting in\n * `<activeRoot>/*` and suppress anything already triaged via\n * `<activeRoot>/.triaged.log`.\n */\n\nexport async function runDiscovery(config: DiscoveryConfig): Promise<DiscoveryResult> {\n const allHits: DiscoveryHit[] = [];\n const allErrors: DiscoverySourceError[] = [];\n\n const githubRepos = config.github_repos ?? [];\n const localRepos = config.local_repos ?? [];\n const projectsRoot = config.projects_root ?? '';\n\n if (githubRepos.length > 0) {\n const r = await discoverGitHub(githubRepos);\n allHits.push(...r.hits);\n allErrors.push(...r.errors);\n }\n if (localRepos.length > 0) {\n const r = await discoverGit(localRepos);\n allHits.push(...r.hits);\n allErrors.push(...r.errors);\n }\n if (projectsRoot.length > 0) {\n const r = await discoverProjects(projectsRoot);\n allHits.push(...r.hits);\n allErrors.push(...r.errors);\n }\n // Claude session scanning is cheap and config-free, so always run it.\n const claude = await discoverClaudeSessions();\n allHits.push(...claude.hits);\n allErrors.push(...claude.errors);\n\n const activeRoot = getActiveRoot();\n const slugs = await loadSlugs(activeRoot);\n const suppressed = await loadTriagedRefs(activeRoot);\n\n const filtered: DiscoveryHit[] = [];\n for (const hit of allHits) {\n if (suppressed.has(hit.ref)) continue;\n const match = matchSlug(hit, slugs);\n if (match) {\n hit.slug_match = match;\n hit.untracked = false;\n } else {\n hit.untracked = true;\n }\n filtered.push(hit);\n }\n\n return { hits: filtered, errors: allErrors };\n}\n\nasync function loadSlugs(activeRoot: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(activeRoot, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory() && !e.name.startsWith('.')).map((e) => e.name);\n } catch {\n return [];\n }\n}\n\nasync function loadTriagedRefs(activeRoot: string): Promise<Set<string>> {\n const logPath = path.join(activeRoot, '.triaged.log');\n const refs = new Set<string>();\n try {\n const raw = await fs.readFile(logPath, 'utf8');\n for (const line of raw.split('\\n')) {\n if (!line.trim()) continue;\n const parts = line.split('\\t');\n // Format: <iso>\\t<action>\\t<ref>\\t<extra>\n const ref = parts[2];\n if (ref) refs.add(ref);\n }\n } catch {\n // No log yet — nothing to suppress.\n }\n return refs;\n}\n\nfunction matchSlug(hit: DiscoveryHit, slugs: string[]): string | undefined {\n const haystacks: string[] = [hit.ref.toLowerCase()];\n const cwd = hit.metadata?.cwd;\n if (typeof cwd === 'string') haystacks.push(cwd.toLowerCase());\n for (const slug of slugs) {\n const needle = slug.toLowerCase();\n if (haystacks.some((h) => h.includes(needle))) return slug;\n }\n return undefined;\n}\n\nexport type { DiscoveryConfig, DiscoveryHit, DiscoveryResult } from './types.js';\n","import { spawn } from 'node:child_process';\n\n/**\n * Minimal subprocess runner used by the discovery sources.\n *\n * Captures stdout/stderr separately. Resolves with the exit code so callers\n * can decide how to treat non-zero exits per-source.\n */\n\nexport interface CommandResult {\n code: number | null;\n stdout: string;\n stderr: string;\n}\n\nexport interface CommandOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n /** Max ms before the child is killed; defaults to 15s. */\n timeoutMs?: number;\n}\n\nexport type RunCommand = (\n bin: string,\n args: string[],\n opts?: CommandOptions,\n) => Promise<CommandResult>;\n\nconst DEFAULT_TIMEOUT_MS = 15_000;\n\nexport const runCommand: RunCommand = (bin, args, opts = {}) => {\n return new Promise<CommandResult>((resolve, reject) => {\n const child = spawn(bin, args, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n let settled = false;\n\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n child.kill('SIGKILL');\n reject(new Error(`${bin} timed out after ${opts.timeoutMs ?? DEFAULT_TIMEOUT_MS}ms`));\n }, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n\n child.stdout?.on('data', (chunk: Buffer) => stdoutChunks.push(chunk));\n child.stderr?.on('data', (chunk: Buffer) => stderrChunks.push(chunk));\n child.on('error', (err) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n reject(err);\n });\n child.on('close', (code) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve({\n code,\n stdout: Buffer.concat(stdoutChunks).toString('utf8'),\n stderr: Buffer.concat(stderrChunks).toString('utf8'),\n });\n });\n });\n};\n","import type { DiscoveryHit, DiscoverySourceError } from './types.js';\nimport { runCommand, type RunCommand } from './run-command.js';\n\n/**\n * Discover open PRs authored by the current user, per repo.\n *\n * Shells out to `gh pr list --author @me --state open` and converts each\n * PR to a `DiscoveryHit`. Failures (gh missing, auth, network) are\n * captured per-repo and never thrown.\n */\n\ninterface GhPullRequest {\n number: number;\n title: string;\n isDraft: boolean;\n headRefName: string;\n updatedAt: string;\n}\n\nexport interface DiscoverGitHubResult {\n hits: DiscoveryHit[];\n errors: DiscoverySourceError[];\n}\n\nexport async function discoverGitHub(\n repos: string[],\n run: RunCommand = runCommand,\n): Promise<DiscoverGitHubResult> {\n const hits: DiscoveryHit[] = [];\n const errors: DiscoverySourceError[] = [];\n\n for (const repo of repos) {\n const sourceId = `gh:${repo}`;\n try {\n const result = await run('gh', [\n 'pr',\n 'list',\n '--author',\n '@me',\n '--state',\n 'open',\n '--limit',\n '100',\n '--repo',\n repo,\n '--json',\n 'number,title,isDraft,headRefName,updatedAt',\n ]);\n if (result.code !== 0) {\n errors.push({\n source: sourceId,\n error: result.stderr.trim() || `gh exited with code ${result.code}`,\n });\n continue;\n }\n const parsed = JSON.parse(result.stdout) as GhPullRequest[];\n for (const pr of parsed) {\n hits.push({\n source: sourceId,\n ref: pr.headRefName,\n detail: `${pr.isDraft ? '[draft] ' : ''}#${pr.number} ${pr.title}`,\n metadata: {\n repo,\n number: pr.number,\n title: pr.title,\n isDraft: pr.isDraft,\n headRefName: pr.headRefName,\n updatedAt: pr.updatedAt,\n },\n });\n }\n } catch (err) {\n errors.push({\n source: sourceId,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n return { hits, errors };\n}\n","import path from 'node:path';\nimport type { DiscoveryHit, DiscoverySourceError } from './types.js';\nimport { runCommand, type RunCommand } from './run-command.js';\n\n/**\n * Discover local git activity (recent branches, worktrees, stashes) across\n * one or more repo paths. Each repo is queried independently so a failure\n * in one repo doesn't suppress hits from the others.\n */\n\nexport interface DiscoverGitResult {\n hits: DiscoveryHit[];\n errors: DiscoverySourceError[];\n}\n\nconst BRANCH_LIMIT = 20;\n\nexport async function discoverGit(\n repoPaths: string[],\n run: RunCommand = runCommand,\n): Promise<DiscoverGitResult> {\n const hits: DiscoveryHit[] = [];\n const errors: DiscoverySourceError[] = [];\n\n for (const repoPath of repoPaths) {\n const repoName = path.basename(repoPath);\n await collectBranches(repoPath, repoName, hits, errors, run);\n await collectWorktrees(repoPath, repoName, hits, errors, run);\n await collectStashes(repoPath, repoName, hits, errors, run);\n }\n\n return { hits, errors };\n}\n\nasync function collectBranches(\n repoPath: string,\n repoName: string,\n hits: DiscoveryHit[],\n errors: DiscoverySourceError[],\n run: RunCommand,\n): Promise<void> {\n const sourceId = `branch:${repoName}`;\n try {\n const result = await run('git', [\n '-C',\n repoPath,\n 'for-each-ref',\n '--sort=-committerdate',\n `--count=${BRANCH_LIMIT}`,\n '--format=%(refname:short)|%(committerdate:short)|%(subject)',\n 'refs/heads/',\n ]);\n if (result.code !== 0) {\n errors.push({ source: sourceId, error: errMsg(result.stderr, result.code) });\n return;\n }\n for (const line of splitLines(result.stdout)) {\n const [name, date, ...rest] = line.split('|');\n if (!name) continue;\n const subject = rest.join('|');\n hits.push({\n source: sourceId,\n ref: name,\n detail: `${name} @ ${date ?? ''} — ${subject}`,\n metadata: { repo: repoName, repoPath, name, date, subject },\n });\n }\n } catch (err) {\n errors.push({ source: sourceId, error: errStr(err) });\n }\n}\n\nasync function collectWorktrees(\n repoPath: string,\n repoName: string,\n hits: DiscoveryHit[],\n errors: DiscoverySourceError[],\n run: RunCommand,\n): Promise<void> {\n const sourceId = `worktree:${repoName}`;\n try {\n const result = await run('git', ['-C', repoPath, 'worktree', 'list', '--porcelain']);\n if (result.code !== 0) {\n errors.push({ source: sourceId, error: errMsg(result.stderr, result.code) });\n return;\n }\n for (const entry of parseWorktreePorcelain(result.stdout)) {\n // Skip the main worktree (== repoPath); only surface auxiliary ones.\n if (entry.path && entry.path !== repoPath && entry.branch) {\n hits.push({\n source: sourceId,\n ref: entry.branch,\n detail: `worktree ${entry.path} on ${entry.branch}`,\n metadata: { repo: repoName, repoPath, ...entry },\n });\n }\n }\n } catch (err) {\n errors.push({ source: sourceId, error: errStr(err) });\n }\n}\n\nasync function collectStashes(\n repoPath: string,\n repoName: string,\n hits: DiscoveryHit[],\n errors: DiscoverySourceError[],\n run: RunCommand,\n): Promise<void> {\n const sourceId = `stash:${repoName}`;\n try {\n const result = await run('git', ['-C', repoPath, 'stash', 'list']);\n if (result.code !== 0) {\n errors.push({ source: sourceId, error: errMsg(result.stderr, result.code) });\n return;\n }\n for (const line of splitLines(result.stdout)) {\n // Format: stash@{N}: WIP on <branch>: <hash> <subject>\n const refMatch = line.match(/^(stash@\\{\\d+\\}):\\s*(.*)$/);\n if (!refMatch) continue;\n const [, ref, message] = refMatch;\n hits.push({\n source: sourceId,\n ref: ref!,\n detail: message ?? line,\n metadata: { repo: repoName, repoPath, ref, message },\n });\n }\n } catch (err) {\n errors.push({ source: sourceId, error: errStr(err) });\n }\n}\n\ninterface WorktreeEntry {\n path?: string;\n head?: string;\n branch?: string;\n}\n\nfunction parseWorktreePorcelain(stdout: string): WorktreeEntry[] {\n const entries: WorktreeEntry[] = [];\n let current: WorktreeEntry = {};\n for (const rawLine of stdout.split('\\n')) {\n const line = rawLine.trimEnd();\n if (line === '') {\n if (Object.keys(current).length > 0) entries.push(current);\n current = {};\n continue;\n }\n if (line.startsWith('worktree ')) current.path = line.slice('worktree '.length);\n else if (line.startsWith('HEAD ')) current.head = line.slice('HEAD '.length);\n else if (line.startsWith('branch ')) {\n const ref = line.slice('branch '.length);\n current.branch = ref.replace(/^refs\\/heads\\//, '');\n }\n }\n if (Object.keys(current).length > 0) entries.push(current);\n return entries;\n}\n\nfunction splitLines(s: string): string[] {\n return s\n .split('\\n')\n .map((l) => l.trimEnd())\n .filter((l) => l.length > 0);\n}\n\nfunction errMsg(stderr: string, code: number | null): string {\n return stderr.trim() || `git exited with code ${code}`;\n}\n\nfunction errStr(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","import { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\nimport type { DiscoveryHit, DiscoverySourceError } from './types.js';\nimport { expandTilde } from '../utils/paths.js';\n\n/**\n * Scan a \"projects root\" directory (e.g. `~/code`) and surface each\n * top-level subdir as a potential work item. Skips dotfiles and the\n * conventional `active` worktree-staging dir.\n */\n\nexport interface DiscoverProjectsResult {\n hits: DiscoveryHit[];\n errors: DiscoverySourceError[];\n}\n\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\nconst RECENT_THRESHOLD_DAYS = 30;\n\nexport async function discoverProjects(projectsRoot: string): Promise<DiscoverProjectsResult> {\n const hits: DiscoveryHit[] = [];\n const errors: DiscoverySourceError[] = [];\n\n if (!projectsRoot) return { hits, errors };\n\n const resolved = path.resolve(expandTilde(projectsRoot));\n let entries: Dirent[];\n try {\n entries = await fs.readdir(resolved, { withFileTypes: true });\n } catch (err) {\n errors.push({\n source: 'projects',\n error: err instanceof Error ? err.message : String(err),\n });\n return { hits, errors };\n }\n\n const now = Date.now();\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (entry.name.startsWith('.')) continue;\n if (entry.name === 'active') continue;\n\n const fullPath = path.join(resolved, entry.name);\n let mtimeMs = 0;\n try {\n const stat = await fs.stat(fullPath);\n mtimeMs = stat.mtimeMs;\n } catch (err) {\n errors.push({\n source: `projects:${entry.name}`,\n error: err instanceof Error ? err.message : String(err),\n });\n continue;\n }\n const ageDays = (now - mtimeMs) / MS_PER_DAY;\n const recency =\n ageDays <= RECENT_THRESHOLD_DAYS ? `modified <${RECENT_THRESHOLD_DAYS}d ago` : 'older';\n hits.push({\n source: 'projects',\n ref: entry.name,\n detail: `${entry.name} (${recency})`,\n metadata: {\n name: entry.name,\n path: fullPath,\n mtime: new Date(mtimeMs).toISOString(),\n ageDays: Math.round(ageDays),\n recency,\n },\n });\n }\n\n return { hits, errors };\n}\n","import { promises as fs, type Dirent } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport type { DiscoveryHit, DiscoverySourceError } from './types.js';\n\n/**\n * Scan `~/.claude/projects/` for recent session JSONLs and surface one hit\n * per unique `cwd`. Honors `CLAUDE_PROJECTS_ROOT` for test injection.\n *\n * We do a light scan of each session file — just enough to extract `cwd`,\n * a subject (first user message or last compaction summary), and an mtime.\n * We do NOT filter against claimed slugs here; that's the orchestrator's\n * cross-reference step.\n */\n\nexport interface DiscoverClaudeResult {\n hits: DiscoveryHit[];\n errors: DiscoverySourceError[];\n}\n\ninterface CwdAggregate {\n cwd: string;\n sessionCount: number;\n lastMtimeMs: number;\n subject: string;\n lastSessionId: string;\n}\n\nconst MAX_SCAN_LINES = 200;\nconst COMPACTION_SUBJECT_PREFIX = '[compaction] ';\n\nexport async function discoverClaudeSessions(): Promise<DiscoverClaudeResult> {\n const root = process.env.CLAUDE_PROJECTS_ROOT ?? path.join(os.homedir(), '.claude', 'projects');\n const hits: DiscoveryHit[] = [];\n const errors: DiscoverySourceError[] = [];\n\n let projectDirs: Dirent[];\n try {\n projectDirs = await fs.readdir(root, { withFileTypes: true });\n } catch (err) {\n // No claude projects dir at all? That's not an error — return empty.\n const e = err as NodeJS.ErrnoException;\n if (e.code === 'ENOENT') return { hits, errors };\n errors.push({ source: 'claude-session', error: e.message ?? String(err) });\n return { hits, errors };\n }\n\n const byCwd = new Map<string, CwdAggregate>();\n\n for (const dir of projectDirs) {\n if (!dir.isDirectory()) continue;\n const dirPath = path.join(root, dir.name);\n let files: Dirent[];\n try {\n files = await fs.readdir(dirPath, { withFileTypes: true });\n } catch (err) {\n errors.push({\n source: `claude-session:${dir.name}`,\n error: err instanceof Error ? err.message : String(err),\n });\n continue;\n }\n for (const file of files) {\n if (!file.isFile() || !file.name.endsWith('.jsonl')) continue;\n const filePath = path.join(dirPath, file.name);\n try {\n await aggregateSession(filePath, byCwd);\n } catch (err) {\n errors.push({\n source: `claude-session:${file.name}`,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n }\n\n for (const agg of byCwd.values()) {\n hits.push({\n source: 'claude-session',\n ref: agg.cwd,\n detail: `${agg.sessionCount} session(s) at ${agg.cwd}${\n agg.subject ? ` — ${agg.subject}` : ''\n }`,\n metadata: {\n cwd: agg.cwd,\n sessionCount: agg.sessionCount,\n lastMtime: new Date(agg.lastMtimeMs).toISOString(),\n lastSessionId: agg.lastSessionId,\n subject: agg.subject,\n },\n });\n }\n\n return { hits, errors };\n}\n\nasync function aggregateSession(filePath: string, byCwd: Map<string, CwdAggregate>): Promise<void> {\n const stat = await fs.stat(filePath);\n // Read up to MAX_SCAN_LINES; this is a light scan, not a parser.\n const raw = await fs.readFile(filePath, 'utf8');\n const lines = raw.split('\\n').slice(0, MAX_SCAN_LINES);\n\n let cwd: string | undefined;\n let firstUserMessage: string | undefined;\n let lastCompactionSummary: string | undefined;\n\n for (const line of lines) {\n if (!line) continue;\n let record: unknown;\n try {\n record = JSON.parse(line);\n } catch {\n continue;\n }\n if (!record || typeof record !== 'object') continue;\n const rec = record as Record<string, unknown>;\n if (!cwd && typeof rec.cwd === 'string' && rec.cwd.length > 0) {\n cwd = rec.cwd;\n }\n if (!firstUserMessage) {\n const text = extractUserMessageText(rec);\n if (text) firstUserMessage = text;\n }\n const summary = extractCompactionSummary(rec);\n if (summary) lastCompactionSummary = summary;\n }\n\n if (!cwd) return;\n const subject = lastCompactionSummary\n ? `${COMPACTION_SUBJECT_PREFIX}${truncate(lastCompactionSummary, 120)}`\n : firstUserMessage\n ? truncate(firstUserMessage, 120)\n : '';\n const sessionId = path.basename(filePath, '.jsonl');\n\n const existing = byCwd.get(cwd);\n if (!existing) {\n byCwd.set(cwd, {\n cwd,\n sessionCount: 1,\n lastMtimeMs: stat.mtimeMs,\n subject,\n lastSessionId: sessionId,\n });\n return;\n }\n existing.sessionCount += 1;\n if (stat.mtimeMs > existing.lastMtimeMs) {\n existing.lastMtimeMs = stat.mtimeMs;\n existing.lastSessionId = sessionId;\n if (subject) existing.subject = subject;\n } else if (!existing.subject && subject) {\n existing.subject = subject;\n }\n}\n\nfunction extractUserMessageText(rec: Record<string, unknown>): string | undefined {\n if (rec.type !== 'user') return undefined;\n const message = rec.message;\n if (!message || typeof message !== 'object') return undefined;\n const content = (message as Record<string, unknown>).content;\n if (typeof content === 'string') return content.trim() || undefined;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (\n block &&\n typeof block === 'object' &&\n (block as Record<string, unknown>).type === 'text' &&\n typeof (block as Record<string, unknown>).text === 'string'\n ) {\n const text = ((block as Record<string, unknown>).text as string).trim();\n if (text) return text;\n }\n }\n }\n return undefined;\n}\n\nfunction extractCompactionSummary(rec: Record<string, unknown>): string | undefined {\n if (rec.type !== 'summary') return undefined;\n if (typeof rec.summary === 'string' && rec.summary.trim().length > 0) {\n return rec.summary.trim();\n }\n return undefined;\n}\n\nfunction truncate(s: string, max: number): string {\n const oneline = s.replace(/\\s+/g, ' ').trim();\n return oneline.length > max ? `${oneline.slice(0, max - 1)}…` : oneline;\n}\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { appendTriagedLog } from '../discover/triaged-log.js';\n\n/**\n * `active-work drop <ref>` — silently dismiss a discover hit. The orchestrator\n * reads `.triaged.log` and skips refs already marked dropped.\n */\n\nconst ArgsSchema = z.object({\n ref: z.string().min(1),\n reason: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n ref: z.string(),\n});\n\nexport default defineCommand({\n name: 'drop',\n description: 'Mark a discover hit as dropped so future discovers suppress it.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['ref'],\n options: {\n reason: {\n long: '--reason',\n description: 'Optional one-line reason recorded in the triage log',\n },\n },\n },\n async run(args) {\n await appendTriagedLog('drop', args.ref, args.reason ?? '-');\n return { ref: args.ref };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { atomicWrite } from '../utils/fs-atomic.js';\nimport { getActiveRoot } from '../utils/paths.js';\nimport { nowIso } from '../utils/today.js';\n\n/**\n * Append a single triage decision to `<activeRoot>/.triaged.log`.\n *\n * Format: `<nowIso()>\\t<action>\\t<ref>\\t<extra>` — one line per decision.\n * The orchestrator reads this file to suppress already-decided refs from\n * future discoveries.\n */\nexport async function appendTriagedLog(\n action: 'fold' | 'drop' | 'track',\n ref: string,\n extra: string,\n): Promise<void> {\n const root = getActiveRoot();\n await fs.mkdir(root, { recursive: true });\n const logPath = path.join(root, '.triaged.log');\n let existing = '';\n try {\n existing = await fs.readFile(logPath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n const line = `${nowIso()}\\t${action}\\t${ref}\\t${extra}\\n`;\n await atomicWrite(logPath, existing + line);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { SessionFrontmatterSchema } from '../schemas/session.js';\nimport { NotFoundError } from '../errors.js';\nimport { nowIso } from '../utils/today.js';\nimport { appendTriagedLog } from '../discover/triaged-log.js';\n\n/**\n * `active-work fold <ref> --into <slug>` — record that a discover hit has been\n * absorbed by an existing initiative.\n *\n * Side effects:\n * - writes a `sidecar`-track session file under the initiative's\n * `sessions/` so the fold is visible in the audit trail\n * - appends a `fold` line to `<activeRoot>/.triaged.log` so future\n * discovers suppress this ref\n */\n\nconst ArgsSchema = z.object({\n ref: z.string().min(1),\n into: z.string().min(1),\n note: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n ref: z.string(),\n into: z.string(),\n session_file: z.string(),\n});\n\nexport default defineCommand({\n name: 'fold',\n description: 'Mark a discover hit as folded into an existing initiative.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['ref'],\n options: {\n into: {\n long: '--into',\n description: 'Slug of the initiative this hit is folded into',\n required: true,\n },\n note: {\n long: '--note',\n description: 'Optional human note describing the fold',\n },\n },\n },\n async run(args) {\n const initiativeDir = getInitiativeDir(args.into);\n try {\n const stat = await fs.stat(initiativeDir);\n if (!stat.isDirectory()) {\n throw new NotFoundError(`Initiative not found: ${args.into}`);\n }\n } catch (err) {\n if (err instanceof NotFoundError) throw err;\n throw new NotFoundError(`Initiative not found: ${args.into}`);\n }\n\n const sessionsDir = path.join(initiativeDir, 'sessions');\n await fs.mkdir(sessionsDir, { recursive: true });\n\n const startedIso = nowIso();\n const filename = buildSessionFilename(startedIso, args.ref);\n const sessionFile = path.join(sessionsDir, filename);\n\n const body = [\n `Folded hit \\`${args.ref}\\` into initiative \\`${args.into}\\`.`,\n '',\n args.note ? args.note : '_No note provided._',\n ].join('\\n');\n\n await writeFrontmatter(\n sessionFile,\n {\n session_id: `folded-${sanitizeRef(args.ref)}`,\n started: startedIso,\n ended: startedIso,\n track: 'sidecar' as const,\n next_steps: [],\n resolves: [],\n },\n body,\n SessionFrontmatterSchema,\n );\n\n await appendTriagedLog('fold', args.ref, `into:${args.into}`);\n\n return { ref: args.ref, into: args.into, session_file: sessionFile };\n },\n});\n\nfunction buildSessionFilename(iso: string, ref: string): string {\n // iso: 2026-05-12T15:23:45.000Z → 2026-05-12-1523\n const stamp = iso.slice(0, 16).replace('T', '-').replace(':', '');\n return `${stamp}-folded-${sanitizeRef(ref)}.md`;\n}\n\nfunction sanitizeRef(ref: string): string {\n return (\n ref\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40) || 'ref'\n );\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { BriefFrontmatterSchema } from '../schemas/brief.js';\nimport { ArtifactsSchema } from '../schemas/artifacts.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { atomicWrite } from '../utils/fs-atomic.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { derivePrefix, validateSlug } from '../utils/slug.js';\nimport { today } from '../utils/today.js';\nimport { UsageError, ValidationError } from '../errors.js';\nimport { stringify as yamlStringify } from 'yaml';\nimport { appendTriagedLog } from '../discover/triaged-log.js';\n\n/**\n * `active-work track <ref> --slug <slug>` — scaffold a fresh initiative from a\n * discover hit. The original `ref` is preserved in the brief body so\n * future readers can trace where the initiative came from.\n *\n * This deliberately re-implements directory scaffolding inline rather\n * than importing `active-work new`; the parallel-work split means `new` lives on a\n * branch this one can't reach.\n */\n\nconst ArgsSchema = z.object({\n ref: z.string().min(1),\n slug: z.string().min(1),\n title: z.string().optional(),\n ship_target: z.string().optional(),\n owner: z.string().optional(),\n worktree: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n dir: z.string(),\n ref: z.string(),\n});\n\nexport default defineCommand({\n name: 'track',\n description: 'Scaffold a new initiative from a discover hit.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['ref'],\n options: {\n slug: {\n long: '--slug',\n description: 'Kebab-case slug for the new initiative',\n required: true,\n },\n title: { long: '--title', description: 'Human-readable initiative title' },\n ship_target: { long: '--ship-target', description: 'Target ship window (e.g. 2026-Q3)' },\n owner: { long: '--owner', description: 'Initiative owner handle' },\n worktree: {\n long: '--worktree',\n description: 'Default worktree path to record on the brief',\n },\n },\n },\n async run(args) {\n const validation = validateSlug(args.slug);\n if (!validation.ok) {\n throw new ValidationError(validation.error);\n }\n const dir = getInitiativeDir(args.slug);\n\n if (await dirExists(dir)) {\n throw new UsageError(`Initiative already exists: ${args.slug}`);\n }\n await fs.mkdir(path.join(dir, 'tasks'), { recursive: true });\n await fs.mkdir(path.join(dir, 'sessions'), { recursive: true });\n await fs.mkdir(path.join(dir, 'sources'), { recursive: true });\n\n const title = args.title ?? deriveTitle(args.slug);\n const briefBody = buildBriefBody(title, args.ref);\n\n await writeFrontmatter(\n path.join(dir, 'brief.md'),\n {\n schema_version: 1,\n title,\n updated: today(),\n state: 'backburner' as const,\n ...(args.ship_target ? { ship_target: args.ship_target } : {}),\n ...(args.owner ? { owner: args.owner } : {}),\n task_prefix: derivePrefix(args.slug),\n },\n briefBody,\n BriefFrontmatterSchema,\n );\n\n // A worktree given at track time is registered, not merely observed (AW-67).\n const artifacts = ArtifactsSchema.parse({\n worktrees: args.worktree\n ? [{ path: args.worktree, repo: args.worktree, name: 'main', default: true }]\n : [],\n });\n await atomicWrite(path.join(dir, 'artifacts.yml'), yamlStringify(artifacts));\n await atomicWrite(path.join(dir, 'sources', '.gitkeep'), '');\n\n await appendTriagedLog('track', args.ref, `slug:${args.slug}`);\n\n return { slug: args.slug, dir, ref: args.ref };\n },\n});\n\nasync function dirExists(p: string): Promise<boolean> {\n try {\n const stat = await fs.stat(p);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction deriveTitle(slug: string): string {\n return slug\n .split('-')\n .filter(Boolean)\n .map((s) => s[0]!.toUpperCase() + s.slice(1))\n .join(' ');\n}\n\nfunction buildBriefBody(title: string, ref: string): string {\n return [\n `# ${title}`,\n '',\n `Source: ${ref}`,\n '',\n 'This initiative was scaffolded from a discover hit. Replace this',\n 'placeholder body with the actual brief before promoting from',\n 'backburner to focused.',\n '',\n ].join('\\n');\n}\n","import { z } from 'zod';\nimport { getActiveRoot } from '../utils/paths.js';\nimport { NotFoundError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\nimport { assembleBootstrap } from '../bootstrap/prompt.js';\nimport { resolveSlug, resolveSlugFromCwd } from './_open-helpers.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1).optional(),\n offline: z.boolean().optional(),\n // Directory to resolve the initiative from when no slug is given. Falls back\n // to the interactive-surface context cwd; unset for daemon/MCP callers.\n cwd: z.string().min(1).optional(),\n // Frame the prompt as ad-hoc work on the workstream rather than a\n // continuation of its handoff / top task.\n adhoc: z.boolean().optional(),\n // Skip the check for another session already live on this initiative.\n no_sibling_check: z.boolean().optional(),\n});\n\ntype PromptArgs = z.infer<typeof ArgsSchema>;\n\nconst promptCommand = defineCommand<PromptArgs, string>({\n name: 'prompt',\n description:\n \"Print the bootstrap prompt for an initiative — the same text `aw` feeds Claude at launch — without any side effects. Resolves the initiative from a slug or the caller's cwd. Use it to re-seed context in a running session.\",\n args: ArgsSchema,\n result: z.string(),\n cli: {\n positional: ['slug'],\n options: {\n offline: {\n long: '--offline',\n description: 'Skip the live `gh`/`git` artifact lookup; render artifacts statically.',\n },\n cwd: {\n long: '--cwd',\n description:\n 'Directory to resolve the initiative from when no slug is given (default: current directory).',\n },\n adhoc: {\n long: '--adhoc',\n description:\n 'Frame the prompt as ad-hoc work on the workstream, awaiting the user’s task, not a continuation of the handoff / top task.',\n },\n no_sibling_check: {\n long: '--no-sibling-check',\n description: 'Skip the check for another session already live on this initiative.',\n },\n },\n usage: 'active-work prompt [slug] [--offline] [--cwd <dir>] [--adhoc] [--no-sibling-check]',\n },\n async run(args, ctx) {\n const activeRoot = ctx.activeRoot ?? getActiveRoot();\n\n let slug: string;\n if (args.slug) {\n slug = await resolveSlug(activeRoot, args.slug);\n } else {\n const cwd = args.cwd ?? ctx.cwd;\n const matched = cwd ? await resolveSlugFromCwd(activeRoot, cwd) : null;\n if (!matched) {\n throw new NotFoundError(\n 'Could not determine an initiative from the current directory. ' +\n 'Pass a slug: `active-work prompt <slug>`.',\n );\n }\n slug = matched.slug;\n }\n\n // Deliberately no archiveStaleTasks, and deliberately no `acquireLease`:\n // `prompt` is a read-only view. It *detects* siblings — re-seeding context\n // mid-session is exactly when you want to know another session is live —\n // but recording a lease would make every re-seed look like a new session\n // to the next bootstrap.\n const { prompt } = await assembleBootstrap({\n activeRoot,\n slug,\n includeLiveStatus: !args.offline,\n adhoc: args.adhoc,\n detectSiblings: !args.no_sibling_check && !args.offline,\n ...(process.env.AW_LEASE_ID ? { ownLeaseId: process.env.AW_LEASE_ID } : {}),\n });\n return prompt;\n },\n});\n\nexport default promptCommand;\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { spawn } from 'node:child_process';\nimport type { ChildProcess, SpawnOptions } from 'node:child_process';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema } from '../schemas/brief.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { readFrontmatter } from '../utils/gray-matter-io.js';\nimport { NotFoundError, ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\n// `handoff` was the other target until v3 retired handoff.md. The enum is\n// kept (rather than dropped for a bare slug) so the CLI shape survives and a\n// stale `edit <slug> handoff` fails with a schema error naming the target.\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n target: z.enum(['brief']).default('brief'),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n target: z.enum(['brief']),\n file: z.string(),\n validated: z.boolean(),\n aborted: z.boolean().optional(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport interface EditorCommand {\n command: string;\n args: string[];\n}\n\nexport type EditorResolver = (filePath: string) => Promise<EditorCommand>;\n\nexport type EditorSpawner = (\n command: string,\n args: string[],\n options: SpawnOptions,\n) => Promise<number>;\n\n/**\n * Resolve which editor to launch using the cascading fallback:\n * 1. `$EDITOR` (invoked via `sh -c` so multi-token values like\n * `nvim --noplugin` split correctly).\n * 2. `code --wait` when the `code` binary resolves on PATH.\n * 3. `vi` as the universal last resort.\n */\nexport async function resolveEditor(filePath: string): Promise<EditorCommand> {\n const editorEnv = process.env.EDITOR;\n if (editorEnv && editorEnv.length > 0) {\n return { command: 'sh', args: ['-c', '$EDITOR \"$0\"', filePath] };\n }\n if (await commandExists('code')) {\n return { command: 'code', args: ['--wait', filePath] };\n }\n return { command: 'vi', args: [filePath] };\n}\n\nasync function commandExists(name: string): Promise<boolean> {\n return new Promise((resolve) => {\n const child = spawn('/bin/sh', ['-c', `command -v ${name}`], {\n stdio: 'ignore',\n });\n child.on('exit', (code) => resolve(code === 0));\n child.on('error', () => resolve(false));\n });\n}\n\n/**\n * Default child-process spawner. Inherits stdio so the editor takes\n * over the operator's TTY, and resolves with the exit code on close.\n */\nexport const defaultSpawner: EditorSpawner = (command, args, options) => {\n return new Promise((resolve, reject) => {\n let child: ChildProcess;\n try {\n child = spawn(command, args, options);\n } catch (err) {\n reject(err);\n return;\n }\n child.on('error', reject);\n child.on('exit', (code) => resolve(code ?? 1));\n });\n};\n\nexport interface RunEditDeps {\n resolveEditor: EditorResolver;\n spawner: EditorSpawner;\n}\n\nconst defaultDeps: RunEditDeps = {\n resolveEditor,\n spawner: defaultSpawner,\n};\n\nfunction targetFile(slug: string): string {\n return path.join(getInitiativeDir(slug), 'brief.md');\n}\n\nasync function fileExists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function runEdit(args: Args, deps: RunEditDeps = defaultDeps): Promise<Result> {\n const file = targetFile(args.slug);\n if (!(await fileExists(file))) {\n throw new NotFoundError(`brief.md not found for initiative \"${args.slug}\" (expected ${file})`);\n }\n\n const editor = await deps.resolveEditor(file);\n const exitCode = await deps.spawner(editor.command, editor.args, {\n stdio: 'inherit',\n });\n\n if (exitCode !== 0) {\n return {\n slug: args.slug,\n target: args.target,\n file,\n validated: false,\n aborted: true,\n };\n }\n\n try {\n await readFrontmatter(file, BriefFrontmatterSchema);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ValidationError(\n `Brief frontmatter is invalid after editing. Re-run \\`active-work edit ${args.slug}\\` to fix.\\n${message}`,\n { cause: err },\n );\n }\n\n return {\n slug: args.slug,\n target: args.target,\n file,\n validated: true,\n };\n}\n\nconst edit = defineCommand<Args, Result>({\n name: 'edit',\n description: \"Open the operator's editor on brief.md.\",\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug', 'target'],\n usage: 'active-work edit <slug> [brief]',\n },\n async run(args) {\n return runEdit(args);\n },\n});\n\nexport default edit;\n","import { spawn } from 'node:child_process';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { runMcpStdio } from '../server/mcp.js';\nimport { runDaemon } from '../server/daemon.js';\n\n/**\n * `active-work mcp serve` — start the MCP server.\n *\n * - `--stdio`: speak JSON-RPC over stdio (for `claude mcp add`).\n * - `--detach`: fork a child running `active-work mcp serve` in the background.\n * - default: run the HTTP daemon in the foreground on `--port` (default 7400).\n */\n\nconst ArgsSchema = z.object({\n stdio: z.boolean().optional(),\n detach: z.boolean().optional(),\n port: z.number().int().positive().optional(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n mode: z.enum(['stdio', 'http', 'detached']),\n pid: z.number().optional(),\n port: z.number().optional(),\n});\n\ntype Result = z.infer<typeof ResultSchema>;\n\nfunction detachedSpawn(port: number | undefined): { pid: number; port: number } {\n const entry = process.argv[1];\n if (!entry) {\n throw new Error('Cannot determine CLI entrypoint for detach');\n }\n const args = ['mcp', 'serve'];\n if (port !== undefined) {\n args.push('--port', String(port));\n }\n const child = spawn(process.execPath, [entry, ...args], {\n detached: true,\n stdio: 'ignore',\n env: process.env,\n });\n child.unref();\n return { pid: child.pid ?? -1, port: port ?? 7400 };\n}\n\nexport default defineCommand<Args, Result>({\n name: 'mcp.serve',\n description:\n 'Start the MCP server. --stdio for stdio mode; --detach to fork the HTTP daemon; otherwise runs the HTTP daemon in the foreground.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n stdio: {\n long: '--stdio',\n description: 'Run in stdio mode for Claude Code `claude mcp add`.',\n },\n detach: {\n long: '--detach',\n description: 'Spawn the HTTP daemon in the background and return.',\n },\n port: {\n long: '--port',\n description: 'TCP port for the HTTP daemon (default 7400).',\n },\n },\n },\n async run(args) {\n if (args.stdio) {\n await runMcpStdio();\n return { mode: 'stdio' };\n }\n if (args.detach) {\n const { pid, port } = detachedSpawn(args.port);\n return { mode: 'detached', pid, port };\n }\n await runDaemon({ port: args.port });\n return { mode: 'http', port: args.port };\n },\n});\n","/**\n * MCP stdio server.\n *\n * Exposes every Command registered in `src/registry/` as an MCP tool, with\n * inputSchema derived from the command's zod args. Tool name is the\n * hierarchical command name with dots replaced by double underscores and\n * an `active__` prefix (e.g. `task.add` -> `active__task__add`).\n *\n * Wave 3 ships the stdio transport only; Wave 4 will wrap the same handlers\n * in an HTTP transport hosted by the daemon.\n */\n\nimport { z } from 'zod';\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';\nimport {\n registry,\n successEnvelope,\n errorEnvelope,\n type AnyCommand,\n type CommandContext,\n type JsonEnvelope,\n} from '../registry/index.js';\nimport '../commands/index.js'; // populates registry on import\nimport { formatError } from '../errors.js';\nimport { getActiveRoot } from '../utils/paths.js';\n\nconst TOOL_NAME_PREFIX = 'active__';\n\nexport interface McpTool {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\n/** Convert a command name (e.g. `task.add`) to a tool name (`active__task__add`). */\nexport function commandNameToToolName(commandName: string): string {\n return TOOL_NAME_PREFIX + commandName.replaceAll('.', '__');\n}\n\n/** Convert a tool name back to a command name. Returns null if it isn't ours. */\nexport function toolNameToCommandName(toolName: string): string | null {\n if (!toolName.startsWith(TOOL_NAME_PREFIX)) return null;\n return toolName.slice(TOOL_NAME_PREFIX.length).replaceAll('__', '.');\n}\n\n/**\n * Strip top-level `$schema` / `definitions` keys that the MCP client doesn't\n * need (and some clients reject when present at the root of inputSchema).\n */\nfunction stripJsonSchemaCruft(schema: Record<string, unknown>): Record<string, unknown> {\n const { $schema: _schema, definitions: _defs, ...rest } = schema;\n void _schema;\n void _defs;\n return rest;\n}\n\n/**\n * Build an MCP tool descriptor from a command. Uses Zod 4's native\n * `z.toJSONSchema` (the spec-mentioned `zod-to-json-schema` package only\n * supports Zod v3 schemas; this repo is on Zod 4).\n */\nexport function commandToTool(cmd: AnyCommand): McpTool {\n // z.toJSONSchema accepts any zod schema; cast away the registry's generic.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const raw = z.toJSONSchema(cmd.args as any) as Record<string, unknown>;\n const inputSchema = stripJsonSchemaCruft(raw);\n // MCP requires inputSchema.type === 'object'. Every registered command's\n // args is a z.object(...), so this is satisfied; assert defensively.\n if (inputSchema.type !== 'object') {\n inputSchema.type = 'object';\n }\n return {\n name: commandNameToToolName(cmd.name),\n description: cmd.description,\n inputSchema,\n };\n}\n\n/** List every registered command as an MCP tool. */\nexport function listTools(): McpTool[] {\n return Array.from(registry.values()).map(commandToTool);\n}\n\ninterface ToolCallOutcome {\n isError: boolean;\n envelope: JsonEnvelope<unknown>;\n}\n\n/**\n * Resolve a tool name to its command, parse args, and invoke `run()`.\n * Always returns an envelope; errors are wrapped, never thrown.\n */\nexport async function invokeTool(toolName: string, rawArgs: unknown): Promise<ToolCallOutcome> {\n const commandName = toolNameToCommandName(toolName);\n const cmd = commandName ? registry.get(commandName) : undefined;\n if (!cmd) {\n const err = formatError(new Error(`Unknown tool: ${toolName}`));\n return { isError: true, envelope: errorEnvelope(err.message, err.code) };\n }\n\n let parsedArgs: unknown;\n try {\n parsedArgs = cmd.args.parse(rawArgs ?? {});\n } catch (err) {\n const f = formatError(err);\n const message = err instanceof z.ZodError ? `Invalid arguments: ${f.message}` : f.message;\n return { isError: true, envelope: errorEnvelope(message, f.code) };\n }\n\n const ctx: CommandContext = {\n activeRoot: getActiveRoot(),\n warnings: [],\n format: 'json',\n };\n\n try {\n const result = await cmd.run(parsedArgs, ctx);\n return { isError: false, envelope: successEnvelope(result, ctx.warnings) };\n } catch (err) {\n const f = formatError(err);\n return { isError: true, envelope: errorEnvelope(f.message, f.code) };\n }\n}\n\n/** Wire MCP request handlers onto a server instance. Exposed for testing. */\nexport function attachHandlers(server: Server): void {\n server.setRequestHandler(ListToolsRequestSchema, () => {\n return { tools: listTools() };\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n const { isError, envelope } = await invokeTool(name, args);\n return {\n isError,\n content: [{ type: 'text', text: JSON.stringify(envelope) }],\n };\n });\n}\n\n/** Construct a fully-wired MCP server, sans transport. */\nexport function createMcpServer(): Server {\n const server = new Server(\n {\n name: '@hjewkes/active-work',\n version: '0.1.0',\n },\n {\n capabilities: {\n tools: {},\n },\n },\n );\n attachHandlers(server);\n return server;\n}\n\n/**\n * Run the MCP server over stdio. Resolves when the transport closes\n * (i.e. when the client disconnects).\n */\nexport async function runMcpStdio(): Promise<void> {\n const server = createMcpServer();\n const transport = new StdioServerTransport();\n await server.connect(transport);\n await new Promise<void>((resolve) => {\n const original = transport.onclose;\n transport.onclose = () => {\n try {\n original?.();\n } finally {\n resolve();\n }\n };\n });\n}\n","/**\n * Daemon entrypoint.\n *\n * `runDaemon` binds the hono app to 127.0.0.1:<port>, writes a PID\n * file, and stays running until SIGTERM/SIGINT. It does not call\n * `process.exit` — the caller decides how the process terminates.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { serve, type ServerType } from '@hono/node-server';\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport { DaemonError } from '../errors.js';\nimport { getActiveRoot } from '../utils/paths.js';\nimport { buildHttpApp } from './http.js';\nimport { DAEMON_VERSION } from './health.js';\nimport { getLogger } from './logger.js';\nimport { createMcpServer } from './mcp.js';\nimport { EventHub } from './events.js';\nimport { watchTree, type TreeWatcher } from './file-watch.js';\nimport {\n isProcessAlive,\n readPidFile,\n removePidFile,\n resolveDaemonPort,\n writePidFile,\n} from './lifecycle.js';\n\nexport interface RunDaemonOptions {\n port?: number;\n}\n\nconst HOSTNAME = '127.0.0.1';\n\nfunction resolvePort(options: RunDaemonOptions): number {\n if (typeof options.port === 'number' && Number.isFinite(options.port)) {\n return options.port;\n }\n return resolveDaemonPort();\n}\n\nasync function assertNotAlreadyRunning(): Promise<void> {\n const existing = await readPidFile();\n if (existing && isProcessAlive(existing.pid)) {\n throw new DaemonError(\n `Daemon already running (pid ${existing.pid}, port ${existing.meta.port})`,\n );\n }\n if (existing) {\n // Stale PID file — clean it up so writePidFile lands cleanly. Naming the\n // dead pid keeps the removal scoped to the file we just inspected.\n await removePidFile(existing.pid);\n }\n}\n\nasync function readJsonBody(req: IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on('data', (c: Buffer) => chunks.push(c));\n req.on('end', () => {\n const raw = Buffer.concat(chunks).toString('utf8');\n if (raw.length === 0) {\n resolve(undefined);\n return;\n }\n try {\n resolve(JSON.parse(raw));\n } catch (err) {\n reject(err);\n }\n });\n req.on('error', reject);\n });\n}\n\n/**\n * Handle a /mcp request by spinning up a fresh MCP server + transport\n * and letting the transport write directly to the Node response. We\n * bypass hono for this route because the transport assumes ownership\n * of the response object.\n */\nasync function handleMcpRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const server = createMcpServer();\n const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });\n let body: unknown;\n if (req.method === 'POST') {\n try {\n body = await readJsonBody(req);\n } catch {\n res.statusCode = 400;\n res.end(JSON.stringify({ ok: false, error: 'Invalid JSON body' }));\n return;\n }\n }\n res.on('close', () => {\n void transport.close();\n void server.close();\n });\n await server.connect(transport);\n await transport.handleRequest(req, res, body);\n}\n\nfunction listenOn(app: ReturnType<typeof buildHttpApp>, port: number): Promise<ServerType> {\n return new Promise((resolve) => {\n const server = serve(\n {\n fetch: app.fetch,\n hostname: HOSTNAME,\n port,\n },\n () => resolve(server),\n );\n // Replace the request handler: route /mcp to the MCP transport\n // directly, falling through to hono for everything else.\n const honoHandler = server.listeners('request')[0] as\n | ((req: IncomingMessage, res: ServerResponse) => void)\n | undefined;\n server.removeAllListeners('request');\n server.on('request', (req: IncomingMessage, res: ServerResponse) => {\n const url = req.url ?? '';\n if (url === '/mcp' || url.startsWith('/mcp?') || url.startsWith('/mcp/')) {\n void handleMcpRequest(req, res).catch((err) => {\n if (!res.headersSent) {\n res.statusCode = 500;\n res.end(String(err));\n } else {\n res.destroy();\n }\n });\n return;\n }\n if (honoHandler) honoHandler(req, res);\n });\n });\n}\n\nfunction closeServer(server: ServerType): Promise<void> {\n return new Promise((resolve, reject) => {\n server.close((err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n}\n\nexport async function runDaemon(options: RunDaemonOptions = {}): Promise<void> {\n const log = getLogger();\n await assertNotAlreadyRunning();\n\n const port = resolvePort(options);\n const hub = new EventHub();\n const app = buildHttpApp({ port, hub });\n const server = await listenOn(app, port);\n const started = new Date().toISOString();\n\n const activeRoot = getActiveRoot();\n let watcher: TreeWatcher | null = null;\n try {\n watcher = watchTree(activeRoot, () => hub.broadcast({ event: 'change', data: 'active-root' }), {\n onError: (err) => log.warn({ err }, 'file watcher error'),\n });\n log.info({ activeRoot }, 'watching active root for live reload');\n } catch (err) {\n // Live reload is a nicety; never let a watcher failure abort the daemon.\n log.warn({ err, activeRoot }, 'live-reload watcher unavailable');\n }\n\n await writePidFile(process.pid, {\n port,\n version: DAEMON_VERSION,\n started,\n });\n log.info({ pid: process.pid, port, started }, 'daemon started');\n\n await new Promise<void>((resolve) => {\n let shuttingDown = false;\n const shutdown = (signal: NodeJS.Signals): void => {\n if (shuttingDown) return;\n shuttingDown = true;\n log.info({ signal }, 'shutting down');\n void (async () => {\n try {\n watcher?.close();\n } catch (err) {\n log.error({ err }, 'error closing file watcher');\n }\n try {\n await closeServer(server);\n } catch (err) {\n log.error({ err }, 'error closing server');\n }\n try {\n // Only ours: a launchd successor may already own the PID file.\n await removePidFile(process.pid);\n } catch (err) {\n log.error({ err }, 'error removing pid file');\n }\n log.info('stopped');\n resolve();\n })();\n };\n\n process.once('SIGTERM', shutdown);\n process.once('SIGINT', shutdown);\n });\n}\n","/**\n * HTTP daemon: hono app that exposes the command registry, MCP-over-HTTP,\n * health/version endpoints, and a static dashboard placeholder.\n *\n * The app is intentionally pure — it constructs and returns a `Hono`\n * instance without binding a port; `daemon.ts` handles the lifecycle.\n */\nimport { Hono } from 'hono';\nimport { streamSSE } from 'hono/streaming';\nimport { z } from 'zod';\nimport { registry, successEnvelope, errorEnvelope } from '../registry/index.js';\nimport type { CommandContext } from '../registry/index.js';\nimport '../commands/index.js'; // populate the registry on import\nimport { formatError, EXIT } from '../errors.js';\nimport { getActiveRoot } from '../utils/paths.js';\nimport { buildHealthPayload, DAEMON_VERSION } from './health.js';\nimport { handleDashboard } from './dashboard-routes.js';\nimport type { EventHub } from './events.js';\n\nexport interface BuildHttpAppOptions {\n port: number;\n /**\n * Optional event hub for live-reload SSE. When present, `/events` streams\n * change notifications; when absent (e.g. unit tests), `/events` still\n * connects but only emits heartbeats.\n */\n hub?: EventHub;\n}\n\n/** Interval between SSE keep-alive comments (ms). */\nconst HEARTBEAT_MS = 25_000;\n\nexport function buildHttpApp(options: BuildHttpAppOptions): Hono {\n const app = new Hono();\n\n app.get('/health', (c) => c.json(buildHealthPayload(options.port)));\n\n app.get('/version', (c) => c.json({ version: DAEMON_VERSION }));\n\n app.get('/events', (c) =>\n streamSSE(c, async (stream) => {\n await stream.writeSSE({ event: 'ready', data: 'connected' });\n const unsubscribe = options.hub?.subscribe((message) => stream.writeSSE(message));\n stream.onAbort(() => unsubscribe?.());\n // Hold the connection open, emitting periodic heartbeats so proxies and\n // dead-peer detection keep the stream healthy until the client aborts.\n while (!stream.aborted) {\n await stream.sleep(HEARTBEAT_MS);\n if (stream.aborted) break;\n await stream.writeSSE({ event: 'ping', data: String(Date.now()) });\n }\n unsubscribe?.();\n }),\n );\n\n app.post('/rpc/:name', async (c) => {\n const name = c.req.param('name');\n const cmd = registry.get(name);\n if (!cmd) {\n return c.json(errorEnvelope(`Unknown command: ${name}`, EXIT.USAGE), 404);\n }\n\n let rawArgs: unknown = {};\n const contentLength = c.req.header('content-length');\n if (contentLength && contentLength !== '0') {\n try {\n rawArgs = await c.req.json();\n } catch {\n return c.json(errorEnvelope('Invalid JSON body', EXIT.USAGE), 400);\n }\n }\n\n let parsed: unknown;\n try {\n parsed = cmd.args.parse(rawArgs ?? {});\n } catch (err) {\n const f = formatError(err);\n const message = err instanceof z.ZodError ? `Invalid arguments: ${f.message}` : f.message;\n return c.json(errorEnvelope(message, EXIT.DATAERR), 400);\n }\n\n const ctx: CommandContext = {\n activeRoot: getActiveRoot(),\n warnings: [],\n format: 'json',\n };\n\n try {\n const result = await cmd.run(parsed, ctx);\n return c.json(successEnvelope(result, ctx.warnings));\n } catch (err) {\n const f = formatError(err);\n return c.json(errorEnvelope(f.message, f.code), 500);\n }\n });\n\n app.get('/ui', (c) => handleDashboard(c));\n app.get('/ui/*', (c) => handleDashboard(c));\n\n return app;\n}\n","/**\n * Health endpoint state.\n *\n * `startedAt` is captured at module load so `/health` can report\n * uptime relative to daemon start without threading it through the\n * route builder.\n */\n\n// TODO: read version from package.json at build time; hardcoded for v0.\nexport const DAEMON_VERSION = '0.1.0';\n\nexport const startedAt = Date.now();\n\nexport interface HealthPayload {\n ok: true;\n version: string;\n pid: number;\n uptime_ms: number;\n port: number;\n}\n\nexport function buildHealthPayload(port: number): HealthPayload {\n return {\n ok: true,\n version: DAEMON_VERSION,\n pid: process.pid,\n uptime_ms: Date.now() - startedAt,\n port,\n };\n}\n","/**\n * Dashboard static-asset handler.\n *\n * If `dist/dashboard/` exists (produced by a future `pnpm build:dashboard`),\n * we serve its contents under `/ui/*`. Otherwise we return a friendly\n * placeholder page so first-run users know what to do.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Context } from 'hono';\n\nconst PLACEHOLDER_HTML = `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>active-work dashboard</title>\n <style>\n body { font-family: system-ui, sans-serif; max-width: 36rem; margin: 4rem auto; padding: 0 1rem; color: #222; }\n code { background: #f4f4f5; padding: 0.1rem 0.3rem; border-radius: 4px; }\n </style>\n </head>\n <body>\n <h1>active-work</h1>\n <p>Dashboard not built yet — run <code>pnpm build:dashboard</code>.</p>\n <p>The daemon is running; use the CLI or MCP for now.</p>\n </body>\n</html>`;\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.htm': 'text/html; charset=utf-8',\n '.js': 'application/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n};\n\nfunction contentTypeFor(filename: string): string {\n const ext = path.extname(filename).toLowerCase();\n return CONTENT_TYPES[ext] ?? 'application/octet-stream';\n}\n\n/**\n * Candidate locations for the built dashboard bundle (`dist/dashboard/`).\n *\n * `tsup` bundles the daemon into `dist/cli.js`, so at runtime the compiled\n * file sits at `dist/` and the dashboard is a sibling (`here/dashboard`). In\n * dev (tsx) the source runs from `src/server/`, and the built dashboard lives\n * at `<repo>/dist/dashboard`. We probe both plus the legacy `dist/server`\n * layout and use the first that exists.\n */\nfunction dashboardDirCandidates(): string[] {\n const here = path.dirname(fileURLToPath(import.meta.url));\n return [\n path.resolve(here, 'dashboard'), // bundled: dist/cli.js -> dist/dashboard\n path.resolve(here, '..', 'dashboard'), // legacy: dist/server -> dist/dashboard\n path.resolve(here, '..', '..', 'dist', 'dashboard'), // dev: src/server -> dist/dashboard\n ];\n}\n\nasync function safeStat(p: string): Promise<{ exists: boolean; isFile: boolean }> {\n try {\n const stat = await fs.stat(p);\n return { exists: true, isFile: stat.isFile() };\n } catch {\n return { exists: false, isFile: false };\n }\n}\n\n/** First candidate directory that exists, or null if none is built yet. */\nasync function resolveDashboardDir(): Promise<string | null> {\n for (const dir of dashboardDirCandidates()) {\n if ((await safeStat(dir)).exists) return dir;\n }\n return null;\n}\n\nexport async function handleDashboard(c: Context): Promise<Response> {\n const root = await resolveDashboardDir();\n if (!root) {\n return c.html(PLACEHOLDER_HTML, 200);\n }\n\n // Strip the route prefix to get the asset-relative path.\n const url = new URL(c.req.url);\n const subpath = url.pathname.replace(/^\\/ui\\/?/, '');\n const relative = subpath === '' ? 'index.html' : subpath;\n\n // Guard against path traversal.\n const target = path.resolve(root, relative);\n if (!target.startsWith(root + path.sep) && target !== root) {\n return c.text('forbidden', 403);\n }\n\n const stat = await safeStat(target);\n if (!stat.exists || !stat.isFile) {\n // Fall back to index.html for SPA routing.\n const indexPath = path.join(root, 'index.html');\n const indexStat = await safeStat(indexPath);\n if (!indexStat.exists) {\n return c.html(PLACEHOLDER_HTML, 200);\n }\n const body = await fs.readFile(indexPath);\n return c.body(new Uint8Array(body), 200, {\n 'content-type': 'text/html; charset=utf-8',\n });\n }\n\n const body = await fs.readFile(target);\n return c.body(new Uint8Array(body), 200, {\n 'content-type': contentTypeFor(target),\n });\n}\n","/**\n * pino logger for the daemon.\n *\n * Logs to stderr (pretty when TTY, JSON otherwise) and additionally\n * appends a JSON record to `<state>/daemon.log`. Rotation is not yet\n * implemented; a future wave can layer pino-roll on top.\n */\nimport { mkdirSync, createWriteStream } from 'node:fs';\nimport path from 'node:path';\nimport pino, { type Logger, multistream, type StreamEntry } from 'pino';\nimport { getStateRoot } from '../utils/paths.js';\n\nlet cachedLogger: Logger | undefined;\n\nfunction buildLogger(): Logger {\n const stateRoot = getStateRoot();\n mkdirSync(stateRoot, { recursive: true });\n const logPath = path.join(stateRoot, 'daemon.log');\n\n const fileStream = createWriteStream(logPath, { flags: 'a' });\n\n const stderrIsTTY = process.stderr.isTTY === true;\n const stderrStream: NodeJS.WritableStream = stderrIsTTY\n ? (pino.transport({\n target: 'pino-pretty',\n options: { destination: 2, colorize: true },\n }) as unknown as NodeJS.WritableStream)\n : process.stderr;\n\n const streams: StreamEntry[] = [{ stream: stderrStream }, { stream: fileStream }];\n\n return pino({ level: process.env.AW_LOG_LEVEL ?? 'info' }, multistream(streams));\n}\n\nexport function getLogger(): Logger {\n cachedLogger ??= buildLogger();\n return cachedLogger;\n}\n\n/** Reset the cached logger. Used by tests that need a clean instance. */\nexport function resetLogger(): void {\n cachedLogger = undefined;\n}\n","/**\n * Event hub: fan-out of daemon-side events to connected dashboard clients\n * over Server-Sent Events.\n *\n * The hub is transport-agnostic — a subscriber is just an async `send`\n * function. `http.ts` wires each SSE connection's `writeSSE` in as a\n * subscriber; `daemon.ts` feeds `broadcast` from the filesystem watcher.\n */\n\nexport interface SseMessage {\n event: string;\n data: string;\n}\n\nexport type Subscriber = (message: SseMessage) => void | Promise<void>;\n\nexport class EventHub {\n private readonly subscribers = new Set<Subscriber>();\n\n /** Register a subscriber; returns an unsubscribe function. */\n subscribe(send: Subscriber): () => void {\n this.subscribers.add(send);\n return () => {\n this.subscribers.delete(send);\n };\n }\n\n /** Number of currently-connected clients (exposed for /health + tests). */\n get size(): number {\n return this.subscribers.size;\n }\n\n /**\n * Push a message to every subscriber. A slow or broken subscriber never\n * blocks the others and never throws out of `broadcast`; failures drop that\n * subscriber so a dead connection can't wedge future broadcasts.\n */\n broadcast(message: SseMessage): void {\n for (const send of this.subscribers) {\n try {\n const result = send(message);\n if (result && typeof result.then === 'function') {\n result.catch(() => this.subscribers.delete(send));\n }\n } catch {\n this.subscribers.delete(send);\n }\n }\n }\n}\n","/**\n * Recursive filesystem watcher for the active root.\n *\n * Node's `fs.watch(dir, { recursive: true })` is only reliable on macOS and\n * Windows; on Linux recursive support is version-dependent. To stay portable\n * we build the recursion ourselves: watch the root plus every current\n * subdirectory, and re-scan (adding watchers for freshly-created dirs) whenever\n * a change lands. Change events are debounced into a single callback so a burst\n * of atomic writes (temp file + rename) collapses into one broadcast.\n */\nimport { watch, readdirSync, promises as fs, type FSWatcher } from 'node:fs';\nimport path from 'node:path';\n\nexport interface WatchTreeOptions {\n /** Coalesce bursts of events within this window (ms). */\n debounceMs?: number;\n /** Surface watcher errors (e.g. EMFILE) without crashing the daemon. */\n onError?: (err: unknown) => void;\n}\n\nexport interface TreeWatcher {\n close: () => void;\n}\n\nconst DEFAULT_DEBOUNCE_MS = 200;\n\n/**\n * Watch `root` and all nested directories, invoking `onChange` (debounced)\n * whenever any file or directory under the tree changes. Returns a handle\n * whose `close()` tears down every underlying watcher.\n */\nexport function watchTree(\n root: string,\n onChange: () => void,\n options: WatchTreeOptions = {},\n): TreeWatcher {\n const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n const watchers = new Map<string, FSWatcher>();\n let debounceTimer: NodeJS.Timeout | null = null;\n let rescanTimer: NodeJS.Timeout | null = null;\n let closed = false;\n\n const fire = (): void => {\n if (closed) return;\n if (debounceTimer) clearTimeout(debounceTimer);\n debounceTimer = setTimeout(() => {\n debounceTimer = null;\n if (!closed) onChange();\n }, debounceMs);\n };\n\n const watchDir = (dir: string): void => {\n if (closed || watchers.has(dir)) return;\n let w: FSWatcher;\n try {\n w = watch(dir, { persistent: false });\n } catch (err) {\n options.onError?.(err);\n return;\n }\n w.on('error', (err) => options.onError?.(err));\n w.on('change', () => {\n fire();\n // A new subdirectory may have appeared; pick it up on the next tick.\n scheduleRescan();\n });\n watchers.set(dir, w);\n };\n\n const scheduleRescan = (): void => {\n if (closed || rescanTimer) return;\n rescanTimer = setTimeout(() => {\n rescanTimer = null;\n void addNewDirs(root);\n }, debounceMs);\n };\n\n const addNewDirs = async (dir: string): Promise<void> => {\n if (closed) return;\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch (err) {\n options.onError?.(err);\n return;\n }\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const child = path.join(dir, entry.name);\n const isNew = !watchers.has(child);\n watchDir(child);\n if (isNew) await addNewDirs(child);\n }\n };\n\n // Attach watchers for the whole existing tree *synchronously* so no edit can\n // slip through the gap between `watchTree` returning and an async scan\n // completing — this matters on Linux, where the root watch is non-recursive\n // and nested changes are only seen via the per-directory watchers.\n const addExistingDirsSync = (dir: string): void => {\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch (err) {\n options.onError?.(err);\n return;\n }\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const child = path.join(dir, entry.name);\n watchDir(child);\n addExistingDirsSync(child);\n }\n };\n\n watchDir(root);\n addExistingDirsSync(root);\n\n return {\n close(): void {\n closed = true;\n if (debounceTimer) clearTimeout(debounceTimer);\n if (rescanTimer) clearTimeout(rescanTimer);\n for (const w of watchers.values()) w.close();\n watchers.clear();\n },\n };\n}\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { isProcessAlive, readPidFile, removePidFile } from '../server/lifecycle.js';\n\n/**\n * `active-work mcp stop` — send SIGTERM to the daemon and wait for it to exit.\n *\n * Returns `{ stopped: false, reason: 'not running' }` when no PID file\n * exists or the recorded process has already died.\n */\n\nconst ArgsSchema = z.object({});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.union([\n z.object({ stopped: z.literal(true), pid: z.number() }),\n z.object({ stopped: z.literal(false), reason: z.string() }),\n]);\ntype Result = z.infer<typeof ResultSchema>;\n\nconst SHUTDOWN_TIMEOUT_MS = 3000;\nconst POLL_INTERVAL_MS = 100;\n\nasync function waitForExit(pid: number, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (!isProcessAlive(pid)) return true;\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n return !isProcessAlive(pid);\n}\n\nexport default defineCommand<Args, Result>({\n name: 'mcp.stop',\n description: 'Stop the running MCP HTTP daemon (sends SIGTERM, waits for exit).',\n args: ArgsSchema,\n result: ResultSchema,\n async run() {\n const pidEntry = await readPidFile();\n if (!pidEntry) {\n return { stopped: false, reason: 'not running' };\n }\n const { pid } = pidEntry;\n if (!isProcessAlive(pid)) {\n await removePidFile(pid);\n return { stopped: false, reason: 'not running' };\n }\n try {\n process.kill(pid, 'SIGTERM');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ESRCH') {\n await removePidFile(pid);\n return { stopped: false, reason: 'not running' };\n }\n throw err;\n }\n await waitForExit(pid, SHUTDOWN_TIMEOUT_MS);\n // Scoped to the pid we killed: a supervisor may have already replaced it.\n await removePidFile(pid);\n return { stopped: true, pid };\n },\n});\n","import { spawn } from 'node:child_process';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport {\n DEFAULT_DAEMON_PORT,\n isProcessAlive,\n readPidFile,\n removePidFile,\n} from '../server/lifecycle.js';\n\n/**\n * `active-work mcp restart` — stop the running daemon (if any) then spawn a new\n * detached daemon. Honors the previously-bound port when not overridden.\n */\n\nconst ArgsSchema = z.object({\n port: z.number().int().positive().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n pid: z.number(),\n port: z.number(),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nconst SHUTDOWN_TIMEOUT_MS = 3000;\nconst POLL_INTERVAL_MS = 100;\n\nasync function waitForExit(pid: number, timeoutMs: number): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (!isProcessAlive(pid)) return;\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n}\n\nasync function stopExisting(): Promise<number | undefined> {\n const entry = await readPidFile();\n if (!entry) return undefined;\n const { pid, meta } = entry;\n if (isProcessAlive(pid)) {\n try {\n process.kill(pid, 'SIGTERM');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ESRCH') throw err;\n }\n await waitForExit(pid, SHUTDOWN_TIMEOUT_MS);\n }\n // Scoped to the pid we killed: a supervisor may have already replaced it.\n await removePidFile(pid);\n return meta.port;\n}\n\nfunction detachedSpawn(port: number): { pid: number; port: number } {\n const entry = process.argv[1];\n if (!entry) {\n throw new Error('Cannot determine CLI entrypoint for restart');\n }\n const child = spawn(process.execPath, [entry, 'mcp', 'serve', '--port', String(port)], {\n detached: true,\n stdio: 'ignore',\n env: process.env,\n });\n child.unref();\n return { pid: child.pid ?? -1, port };\n}\n\nexport default defineCommand<Args, Result>({\n name: 'mcp.restart',\n description: 'Restart the MCP HTTP daemon (stop, then spawn a fresh detached instance).',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n port: {\n long: '--port',\n description: 'Port for the restarted daemon (default: previous port or 7400).',\n },\n },\n },\n async run(args) {\n const prevPort = await stopExisting();\n const port = args.port ?? prevPort ?? DEFAULT_DAEMON_PORT;\n return detachedSpawn(port);\n },\n});\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport {\n isProcessAlive,\n probeHealth,\n readPidFile,\n resolveDaemonPort,\n} from '../server/lifecycle.js';\n\n/**\n * `active-work mcp status` — report whether the daemon is running, plus a\n * snapshot of `/health` if it answers.\n */\n\nconst ArgsSchema = z.object({});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n running: z.boolean(),\n pid: z.number().optional(),\n port: z.number().optional(),\n version: z.string().optional(),\n uptime_ms: z.number().optional(),\n healthy: z.boolean().optional(),\n /** Answering `/health` with no PID file naming it — see `removePidFile`. */\n orphaned: z.boolean().optional(),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\n/**\n * No usable PID file: probe the port anyway. Reporting \"not running\" purely\n * because the file is gone is how a live daemon disappeared from this command\n * while still serving requests (AW-76). `port` on a negative answer names what\n * we actually tried, since a daemon on a non-default `--port` with no file to\n * record it cannot be found from here.\n */\nasync function statusByPort(port: number): Promise<Result> {\n const health = await probeHealth(port);\n if (!health) return { running: false, port };\n return {\n running: true,\n healthy: true,\n orphaned: true,\n pid: health.pid,\n port: health.port,\n version: health.version,\n uptime_ms: health.uptime_ms,\n };\n}\n\nexport default defineCommand<Args, Result>({\n name: 'mcp.status',\n description: 'Report the MCP HTTP daemon status (pid, port, version, uptime).',\n args: ArgsSchema,\n result: ResultSchema,\n async run() {\n const entry = await readPidFile();\n if (!entry) {\n return statusByPort(resolveDaemonPort());\n }\n const { pid, meta } = entry;\n if (!isProcessAlive(pid)) {\n // A pre-meta pid file records port 0; fall back to where a daemon would be.\n return statusByPort(meta.port || resolveDaemonPort());\n }\n const health = await probeHealth(meta.port);\n if (health) {\n return {\n running: true,\n pid: health.pid,\n port: health.port,\n version: health.version,\n uptime_ms: health.uptime_ms,\n healthy: true,\n };\n }\n return {\n running: true,\n pid,\n port: meta.port,\n version: meta.version,\n healthy: false,\n };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { getStateRoot } from '../utils/paths.js';\n\n/**\n * `active-work mcp logs` — return the tail of `daemon.log`.\n *\n * No `--follow` support in v0; callers that need streaming can `tail -f`\n * the file directly.\n */\n\nconst ArgsSchema = z.object({\n lines: z.number().int().positive().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n lines: z.array(z.string()),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nconst DEFAULT_LINES = 50;\n\nexport default defineCommand<Args, Result>({\n name: 'mcp.logs',\n description: 'Return the last N lines of the daemon log (default 50).',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n lines: {\n long: '--lines',\n description: 'Number of trailing lines to return (default 50).',\n },\n },\n },\n async run(args) {\n const n = args.lines ?? DEFAULT_LINES;\n const logPath = path.join(getStateRoot(), 'daemon.log');\n let content: string;\n try {\n content = await fs.readFile(logPath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return { lines: [] };\n }\n throw err;\n }\n const allLines = content.split(/\\r?\\n/);\n // Drop trailing empty line(s) from the final newline.\n while (allLines.length > 0 && allLines[allLines.length - 1] === '') {\n allLines.pop();\n }\n return { lines: allLines.slice(-n) };\n },\n});\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { runSetup } from '../setup/steps.js';\nimport { color } from '../utils/color.js';\n\n/**\n * `active-work setup` — interactive wizard that walks a fresh machine to a working state.\n *\n * Each step runs in sequence and short-circuits on the first hard failure.\n * `--yes` skips interactive prompts (assumes no for daemon start / ingestion).\n * `--update` re-runs idempotently and may overwrite the config stub.\n */\n\nconst ArgsSchema = z.object({\n update: z.boolean().optional(),\n yes: z.boolean().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst StepSchema = z.object({\n name: z.string(),\n ok: z.boolean(),\n done: z.boolean().optional(),\n message: z.string().optional(),\n error: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n banner: z.string(),\n steps: z.array(StepSchema),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nfunction printStep(step: Result['steps'][number]): void {\n if (step.ok) {\n const mark = color.green('OK');\n const msg = step.message ?? '';\n process.stderr.write(` ${mark} ${step.name}${msg ? ` — ${msg}` : ''}\\n`);\n } else {\n const mark = color.red('FAIL');\n process.stderr.write(` ${mark} ${step.name} — ${step.error ?? 'failed'}\\n`);\n }\n}\n\nexport default defineCommand<Args, Result>({\n name: 'setup',\n description:\n 'Interactive wizard: verifies Node, scaffolds directories, registers the MCP server, and optionally starts the daemon and walks through ingestion.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n update: {\n long: '--update',\n description: 'Re-run setup idempotently (may overwrite the config stub).',\n },\n yes: {\n long: '--yes',\n short: '-y',\n description: 'Skip all prompts; use defaults (no daemon, no ingestion).',\n },\n },\n },\n async run(args, ctx) {\n const banner = color.bold('active-work setup');\n if (ctx.format !== 'json') {\n process.stderr.write(banner + '\\n');\n }\n const report = await runSetup({\n yes: args.yes ?? false,\n update: args.update ?? false,\n });\n if (ctx.format !== 'json') {\n for (const step of report.steps) printStep(step);\n }\n const failed = report.steps.find((s) => !s.ok);\n if (failed) {\n throw new Error(`setup failed at step '${failed.name}': ${failed.error}`);\n }\n return report;\n },\n});\n","/**\n * Individual setup steps used by `active-work setup` and `active-work uninstall`.\n *\n * Each step is a small async function that accepts a `SetupDeps` bag\n * (filesystem, spawn, prompts, paths). Tests inject stubs; production\n * callers let everything default. Steps never throw on failure — they\n * return a tagged result so the orchestrator can short-circuit cleanly.\n */\nimport { promises as fsp, existsSync } from 'node:fs';\nimport nodePath from 'node:path';\nimport { spawn as nodeSpawn } from 'node:child_process';\nimport os from 'node:os';\nimport { fileURLToPath } from 'node:url';\nimport * as clackPrompts from '@clack/prompts';\nimport { ensureSchemaVersion } from '../schemas/state.js';\nimport { getActiveRoot, getStateRoot, getConfigRoot } from '../utils/paths.js';\nimport { STEP_SUPERVISION } from './supervision-systemd.js';\nimport { getSupervisor } from './supervision.js';\n\nfunction findRepoRoot(): string {\n let cursor = nodePath.dirname(fileURLToPath(import.meta.url));\n for (let depth = 0; depth < 6; depth++) {\n if (existsSync(nodePath.join(cursor, 'package.json'))) return cursor;\n const parent = nodePath.dirname(cursor);\n if (parent === cursor) break;\n cursor = parent;\n }\n // Fallback: two up from current file (covers source layout).\n return nodePath.resolve(nodePath.dirname(fileURLToPath(import.meta.url)), '..', '..');\n}\n\nexport interface StepPaths {\n activeRoot: string;\n stateRoot: string;\n configRoot: string;\n homeDir: string;\n}\n\nexport interface SetupDeps {\n fs?: typeof fsp;\n spawn?: typeof nodeSpawn;\n prompts?: typeof clackPrompts;\n paths?: StepPaths;\n /** When true, skip interactive prompts and assume yes. */\n yes?: boolean;\n /** When true, allow overwrite of existing user files. */\n update?: boolean;\n /** Optional override for repo root (where bundled skill lives). */\n repoRoot?: string;\n /** Optional override for the CLI entrypoint (for spawn calls). */\n cliEntry?: string;\n /**\n * Whether a supervisor already owns the daemon; null when the platform has\n * no integration. Defaults to probing launchctl/systemctl, so tests inject\n * it instead of reading the host's real supervision state.\n */\n supervisorActive?: () => Promise<{ kind: string; active: boolean } | null>;\n}\n\nexport interface StepOk {\n ok: true;\n name: string;\n done: boolean;\n message: string;\n}\n\nexport interface StepErr {\n ok: false;\n name: string;\n error: string;\n}\n\nexport type StepResult = StepOk | StepErr;\n\n/** Resolve every defaultable dep so each step has a complete bag. */\nfunction resolveDeps(deps: SetupDeps): Required<\n Omit<SetupDeps, 'yes' | 'update' | 'repoRoot' | 'cliEntry' | 'supervisorActive'>\n> & {\n yes: boolean;\n update: boolean;\n repoRoot: string;\n cliEntry: string;\n} {\n const fs = deps.fs ?? fsp;\n const spawn = deps.spawn ?? nodeSpawn;\n const prompts = deps.prompts ?? clackPrompts;\n const homeDir = deps.paths?.homeDir ?? os.homedir();\n const paths: StepPaths = deps.paths ?? {\n activeRoot: getActiveRoot(),\n stateRoot: getStateRoot(),\n configRoot: getConfigRoot(),\n homeDir,\n };\n // The bundled skill lives at `<repoRoot>/skill`. Find it by walking up\n // from this module until we hit a directory containing `package.json`\n // — works both for source (`src/setup/steps.ts`) and bundled\n // (`dist/cli.js`) layouts.\n const repoRoot = deps.repoRoot ?? findRepoRoot();\n const cliEntry = deps.cliEntry ?? process.argv[1] ?? 'active-work';\n return {\n fs,\n spawn,\n prompts,\n paths,\n yes: deps.yes ?? false,\n update: deps.update ?? false,\n repoRoot,\n cliEntry,\n };\n}\n\nconst STEP_CHECK_NODE = 'check-node';\nconst STEP_CREATE_ACTIVE = 'create-active-root';\nconst STEP_SCHEMA = 'write-schema-version';\nconst STEP_CONFIG = 'write-config-stub';\nconst STEP_SKILL = 'install-skill';\nconst STEP_COMMAND = 'install-command';\nconst STEP_MCP = 'register-mcp';\nconst STEP_DAEMON = 'start-daemon';\nconst STEP_INGEST = 'ingestion';\n\nexport const STEP_NAMES = {\n CHECK_NODE: STEP_CHECK_NODE,\n CREATE_ACTIVE: STEP_CREATE_ACTIVE,\n SCHEMA: STEP_SCHEMA,\n CONFIG: STEP_CONFIG,\n SKILL: STEP_SKILL,\n COMMAND: STEP_COMMAND,\n MCP: STEP_MCP,\n SUPERVISION: STEP_SUPERVISION,\n DAEMON: STEP_DAEMON,\n INGEST: STEP_INGEST,\n} as const;\n\nconst MIN_NODE_MAJOR = 22;\n\nfunction parseNodeMajor(version: string): number {\n const cleaned = version.startsWith('v') ? version.slice(1) : version;\n const major = Number(cleaned.split('.')[0]);\n return Number.isFinite(major) ? major : 0;\n}\n\nexport async function stepCheckNode(deps: SetupDeps = {}): Promise<StepResult> {\n void deps;\n const major = parseNodeMajor(process.versions.node);\n if (major < MIN_NODE_MAJOR) {\n return {\n ok: false,\n name: STEP_CHECK_NODE,\n error: `Node ${MIN_NODE_MAJOR}+ required, found v${process.versions.node}`,\n };\n }\n return {\n ok: true,\n name: STEP_CHECK_NODE,\n done: true,\n message: `Node v${process.versions.node} OK`,\n };\n}\n\nasync function ensureDir(fs: typeof fsp, dir: string): Promise<{ created: boolean }> {\n try {\n const stat = await fs.stat(dir);\n if (stat.isDirectory()) return { created: false };\n throw new Error(`${dir} exists but is not a directory`);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== 'ENOENT') throw err;\n }\n await fs.mkdir(dir, { recursive: true });\n return { created: true };\n}\n\nexport async function stepCreateActiveRoot(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, paths } = resolveDeps(deps);\n try {\n const created: string[] = [];\n for (const dir of [paths.activeRoot, paths.stateRoot, paths.configRoot]) {\n const { created: didCreate } = await ensureDir(fs, dir);\n if (didCreate) created.push(dir);\n }\n const message =\n created.length === 0\n ? `Active/state/config dirs already present`\n : `Created ${created.length} dir(s)`;\n return {\n ok: true,\n name: STEP_CREATE_ACTIVE,\n done: created.length > 0,\n message,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_CREATE_ACTIVE,\n error: (err as Error).message,\n };\n }\n}\n\nexport async function stepWriteSchemaVersion(deps: SetupDeps = {}): Promise<StepResult> {\n const { paths } = resolveDeps(deps);\n try {\n const result = await ensureSchemaVersion(paths.activeRoot);\n const message = result.migrated\n ? `Migrated v${result.before} -> v${result.after}`\n : `Schema at v${result.after}`;\n return {\n ok: true,\n name: STEP_SCHEMA,\n done: result.migrated,\n message,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_SCHEMA,\n error: (err as Error).message,\n };\n }\n}\n\nconst CONFIG_STUB = {\n discovery: {\n githubRepos: [] as string[],\n localRepos: [] as string[],\n projectsRoot: '~/Documents/projects',\n },\n};\n\nexport async function stepWriteConfigStub(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, paths, update } = resolveDeps(deps);\n const configPath = nodePath.join(paths.configRoot, 'config.json');\n try {\n await ensureDir(fs, paths.configRoot);\n let exists = false;\n try {\n await fs.stat(configPath);\n exists = true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n if (exists && !update) {\n return {\n ok: true,\n name: STEP_CONFIG,\n done: false,\n message: `Config exists at ${configPath} (left untouched)`,\n };\n }\n await fs.writeFile(configPath, JSON.stringify(CONFIG_STUB, null, 2) + '\\n', 'utf8');\n return {\n ok: true,\n name: STEP_CONFIG,\n done: true,\n message: `Wrote config stub to ${configPath}`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_CONFIG,\n error: (err as Error).message,\n };\n }\n}\n\nasync function pathExists(fs: typeof fsp, p: string): Promise<boolean> {\n try {\n await fs.stat(p);\n return true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return false;\n throw err;\n }\n}\n\nasync function copyTree(fs: typeof fsp, src: string, dest: string): Promise<void> {\n // node:fs/promises has cp() in Node 22+.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const cp = (fs as any).cp as\n | undefined\n | ((from: string, to: string, opts: { recursive: boolean }) => Promise<void>);\n if (cp) {\n await cp(src, dest, { recursive: true });\n return;\n }\n // Fallback: shallow copy of files only (test envs may stub fs).\n await fs.mkdir(dest, { recursive: true });\n const entries = await fs.readdir(src, { withFileTypes: true });\n for (const entry of entries) {\n const from = nodePath.join(src, entry.name);\n const to = nodePath.join(dest, entry.name);\n if (entry.isDirectory()) {\n await copyTree(fs, from, to);\n } else {\n await fs.copyFile(from, to);\n }\n }\n}\n\nexport async function stepInstallSkill(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, paths, repoRoot } = resolveDeps(deps);\n const targetDir = nodePath.join(paths.homeDir, '.claude', 'skills', 'active-work');\n const targetMarker = nodePath.join(targetDir, 'SKILL.md');\n const sourceDir = nodePath.join(repoRoot, 'skill');\n try {\n if (await pathExists(fs, targetMarker)) {\n return {\n ok: true,\n name: STEP_SKILL,\n done: false,\n message: `Skill already installed at ${targetDir}`,\n };\n }\n if (!(await pathExists(fs, sourceDir))) {\n return {\n ok: true,\n name: STEP_SKILL,\n done: false,\n message: `Skill source not found at ${sourceDir}; skipping`,\n };\n }\n await fs.mkdir(nodePath.dirname(targetDir), { recursive: true });\n await copyTree(fs, sourceDir, targetDir);\n return {\n ok: true,\n name: STEP_SKILL,\n done: true,\n message: `Installed skill to ${targetDir}`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_SKILL,\n error: (err as Error).message,\n };\n }\n}\n\nexport async function stepInstallCommand(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, paths, repoRoot } = resolveDeps(deps);\n const targetDir = nodePath.join(paths.homeDir, '.claude', 'commands');\n const target = nodePath.join(targetDir, 'aw-prompt.md');\n const source = nodePath.join(repoRoot, 'claude-commands', 'aw-prompt.md');\n try {\n if (!(await pathExists(fs, source))) {\n return {\n ok: true,\n name: STEP_COMMAND,\n done: false,\n message: `Command source not found at ${source}; skipping`,\n };\n }\n await fs.mkdir(targetDir, { recursive: true });\n // Overwrite unconditionally (unlike the skill step, which skips if present):\n // the command is a single version-bundled file, so setup should refresh it.\n await fs.copyFile(source, target);\n return {\n ok: true,\n name: STEP_COMMAND,\n done: true,\n message: `Installed /aw-prompt command to ${target}`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_COMMAND,\n error: (err as Error).message,\n };\n }\n}\n\n/** Spawn a process and capture its exit code + stderr. */\nfunction runOnce(\n spawn: typeof nodeSpawn,\n cmd: string,\n args: string[],\n): Promise<{ code: number | null; stderr: string; spawnError?: Error }> {\n return new Promise((resolve) => {\n let stderr = '';\n let settled = false;\n try {\n const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });\n child.stderr?.on('data', (chunk: Buffer | string) => {\n stderr += chunk.toString();\n });\n child.on('error', (err) => {\n if (settled) return;\n settled = true;\n resolve({ code: null, stderr, spawnError: err });\n });\n child.on('close', (code) => {\n if (settled) return;\n settled = true;\n resolve({ code, stderr });\n });\n } catch (err) {\n if (settled) return;\n settled = true;\n resolve({ code: null, stderr, spawnError: err as Error });\n }\n });\n}\n\nconst MCP_FALLBACK_SNIPPET = `{\n \"active-work\": {\n \"command\": \"active-work\",\n \"args\": [\"mcp\", \"serve\", \"--stdio\"]\n }\n}`;\n\nexport async function stepRegisterMcp(deps: SetupDeps = {}): Promise<StepResult> {\n const { spawn } = resolveDeps(deps);\n const result = await runOnce(spawn, 'claude', [\n 'mcp',\n 'add',\n '--user',\n '@hjewkes/active-work',\n '--',\n 'active-work',\n 'mcp',\n 'serve',\n '--stdio',\n ]);\n if (result.spawnError && (result.spawnError as NodeJS.ErrnoException).code === 'ENOENT') {\n return {\n ok: true,\n name: STEP_MCP,\n done: false,\n message:\n '`claude` CLI not found. Add this to ~/.claude.json mcpServers section:\\n' +\n MCP_FALLBACK_SNIPPET,\n };\n }\n if (result.spawnError) {\n return {\n ok: true,\n name: STEP_MCP,\n done: false,\n message: `MCP registration skipped: ${result.spawnError.message}`,\n };\n }\n if (result.code === 0) {\n return {\n ok: true,\n name: STEP_MCP,\n done: true,\n message: 'Registered MCP server with Claude Code',\n };\n }\n return {\n ok: true,\n name: STEP_MCP,\n done: false,\n message:\n `claude mcp add exited with code ${result.code ?? 'null'}. ` +\n 'If already registered, this is safe. Otherwise add manually:\\n' +\n MCP_FALLBACK_SNIPPET,\n };\n}\n\n/**\n * Offer to install a user-level supervisor (systemd on Linux, launchd on\n * macOS) that keeps the daemon running across logins. No-op on platforms\n * without an integration.\n */\nexport async function stepSupervision(deps: SetupDeps = {}): Promise<StepResult> {\n const { prompts, yes } = resolveDeps(deps);\n const supervisor = getSupervisor();\n if (!supervisor) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Skipped: no daemon supervisor is integrated for ${process.platform}`,\n };\n }\n if (!yes) {\n const answer = await prompts.confirm({\n message: supervisor.installPrompt,\n initialValue: true,\n });\n if (prompts.isCancel(answer) || answer !== true) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: 'Supervision install skipped',\n };\n }\n }\n // Supervision is an optional enhancement, not a prerequisite. Like\n // `stepStartDaemon`, a runtime failure (no user session, container, CI) must\n // not abort the whole setup — the unit/plist is still written, so downgrade\n // an install failure to a non-fatal warning that tells the user how to finish\n // enabling it by hand.\n const result = await supervisor.install(deps);\n if (!result.ok) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Daemon supervision not enabled (${result.error}); run \\`${supervisor.enableHint}\\` once a user session is available`,\n };\n }\n return result;\n}\n\n/** Probe the platform supervisor; null when the platform has no integration. */\nasync function probeSupervisor(deps: SetupDeps): Promise<{ kind: string; active: boolean } | null> {\n const supervisor = getSupervisor();\n if (!supervisor) return null;\n return { kind: supervisor.kind, active: await supervisor.isActive(deps) };\n}\n\n/** Spawn `active-work mcp serve --detach` (best-effort). */\nexport async function stepStartDaemon(deps: SetupDeps = {}): Promise<StepResult> {\n const { spawn, prompts, yes, cliEntry } = resolveDeps(deps);\n // If a supervisor already owns the daemon, skip the manual spawn — restarting\n // it is the supervisor's job (e.g. `systemctl --user restart` / `launchctl\n // kickstart`).\n const probe = deps.supervisorActive ?? (() => probeSupervisor(deps));\n const supervisor = await probe();\n if (supervisor?.active) {\n return {\n ok: true,\n name: STEP_DAEMON,\n done: false,\n message: `Daemon already supervised by ${supervisor.kind}; manual start skipped`,\n };\n }\n if (!yes) {\n const answer = await prompts.confirm({\n message: 'Start the HTTP daemon now? (background process)',\n initialValue: true,\n });\n if (prompts.isCancel(answer) || answer !== true) {\n return {\n ok: true,\n name: STEP_DAEMON,\n done: false,\n message: 'Daemon start skipped',\n };\n }\n } else {\n return {\n ok: true,\n name: STEP_DAEMON,\n done: false,\n message: 'Daemon start skipped (--yes)',\n };\n }\n try {\n const child = spawn(process.execPath, [cliEntry, 'mcp', 'serve', '--detach'], {\n detached: true,\n stdio: 'ignore',\n });\n child.unref?.();\n return {\n ok: true,\n name: STEP_DAEMON,\n done: true,\n message: `Daemon launched (pid=${child.pid ?? 'unknown'})`,\n };\n } catch (err) {\n return {\n ok: true,\n name: STEP_DAEMON,\n done: false,\n message: `Daemon launch skipped: ${(err as Error).message}`,\n };\n }\n}\n\nexport async function stepIngestion(deps: SetupDeps = {}): Promise<StepResult> {\n const { prompts, yes, paths } = resolveDeps(deps);\n if (yes) {\n return {\n ok: true,\n name: STEP_INGEST,\n done: false,\n message:\n `Skipped ingestion walkthrough. Run \\`claude\\` in ${paths.activeRoot} ` +\n 'and ask it to run `active-work discover` followed by `active-work fold` / `active-work drop` / `active-work track`.',\n };\n }\n const answer = await prompts.confirm({\n message: 'Walk through existing work with Claude now?',\n initialValue: false,\n });\n if (prompts.isCancel(answer) || answer !== true) {\n return {\n ok: true,\n name: STEP_INGEST,\n done: false,\n message:\n `Ingestion skipped. Later: run \\`claude\\` in ${paths.activeRoot} and ask it to ` +\n 'invoke `active-work discover` to scan your work.',\n };\n }\n return {\n ok: true,\n name: STEP_INGEST,\n done: true,\n message:\n `Run \\`claude\\` in ${paths.activeRoot} and paste this prompt: ` +\n '\"Please run `active-work discover`, then walk me through `active-work fold` / `active-work drop` / `active-work track` for each hit.\"',\n };\n}\n\nexport interface SetupReport {\n banner: string;\n steps: Array<{\n name: string;\n ok: boolean;\n done?: boolean;\n message?: string;\n error?: string;\n }>;\n}\n\n/** Run every setup step in order, short-circuiting on the first failure. */\nexport async function runSetup(deps: SetupDeps = {}): Promise<SetupReport> {\n const banner = 'active-work setup';\n const steps: SetupReport['steps'] = [];\n const ordered = [\n stepCheckNode,\n stepCreateActiveRoot,\n stepWriteSchemaVersion,\n stepWriteConfigStub,\n stepInstallSkill,\n stepInstallCommand,\n stepRegisterMcp,\n stepSupervision,\n stepStartDaemon,\n stepIngestion,\n ];\n for (const step of ordered) {\n const result = await step(deps);\n if (result.ok) {\n steps.push({\n name: result.name,\n ok: true,\n done: result.done,\n message: result.message,\n });\n } else {\n steps.push({ name: result.name, ok: false, error: result.error });\n break;\n }\n }\n return { banner, steps };\n}\n\n// ----- Uninstall ----------------------------------------------------------\n\nexport interface UninstallReport {\n steps: Array<{ name: string; done: boolean; message?: string; error?: string }>;\n activeRootPreservedAt: string;\n}\n\nasync function confirmStep(\n prompts: typeof clackPrompts,\n yes: boolean,\n message: string,\n initial = true,\n): Promise<boolean> {\n if (yes) return true;\n const answer = await prompts.confirm({ message, initialValue: initial });\n if (prompts.isCancel(answer)) return false;\n return answer === true;\n}\n\nexport async function uninstallSkill(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, paths } = resolveDeps(deps);\n const target = nodePath.join(paths.homeDir, '.claude', 'skills', 'active-work');\n try {\n if (!(await pathExists(fs, target))) {\n return {\n ok: true,\n name: STEP_SKILL,\n done: false,\n message: `Skill not present at ${target}`,\n };\n }\n await fs.rm(target, { recursive: true, force: true });\n return {\n ok: true,\n name: STEP_SKILL,\n done: true,\n message: `Removed skill from ${target}`,\n };\n } catch (err) {\n return { ok: false, name: STEP_SKILL, error: (err as Error).message };\n }\n}\n\nexport async function uninstallCommand(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, paths } = resolveDeps(deps);\n const target = nodePath.join(paths.homeDir, '.claude', 'commands', 'aw-prompt.md');\n try {\n if (!(await pathExists(fs, target))) {\n return {\n ok: true,\n name: STEP_COMMAND,\n done: false,\n message: `Command not present at ${target}`,\n };\n }\n await fs.rm(target, { force: true });\n return {\n ok: true,\n name: STEP_COMMAND,\n done: true,\n message: `Removed /aw-prompt command from ${target}`,\n };\n } catch (err) {\n return { ok: false, name: STEP_COMMAND, error: (err as Error).message };\n }\n}\n\nexport async function uninstallStopDaemon(deps: SetupDeps = {}): Promise<StepResult> {\n const { spawn, cliEntry } = resolveDeps(deps);\n const result = await runOnce(spawn, process.execPath, [cliEntry, 'mcp', 'stop']);\n if (result.spawnError) {\n return {\n ok: true,\n name: STEP_DAEMON,\n done: false,\n message: `Daemon stop skipped: ${result.spawnError.message}`,\n };\n }\n return {\n ok: true,\n name: STEP_DAEMON,\n done: result.code === 0,\n message: result.code === 0 ? 'Daemon stopped' : `Daemon stop exited ${result.code ?? 'null'}`,\n };\n}\n\nexport async function uninstallMcp(deps: SetupDeps = {}): Promise<StepResult> {\n const { spawn } = resolveDeps(deps);\n const result = await runOnce(spawn, 'claude', [\n 'mcp',\n 'remove',\n '--user',\n '@hjewkes/active-work',\n ]);\n if (result.spawnError && (result.spawnError as NodeJS.ErrnoException).code === 'ENOENT') {\n return {\n ok: true,\n name: STEP_MCP,\n done: false,\n message: '`claude` CLI not found. Remove the entry manually from ~/.claude.json',\n };\n }\n if (result.spawnError) {\n return {\n ok: true,\n name: STEP_MCP,\n done: false,\n message: `MCP unregister skipped: ${result.spawnError.message}`,\n };\n }\n return {\n ok: true,\n name: STEP_MCP,\n done: result.code === 0,\n message:\n result.code === 0\n ? 'Unregistered MCP server from Claude Code'\n : `claude mcp remove exited with code ${result.code ?? 'null'}`,\n };\n}\n\nexport async function runUninstall(deps: SetupDeps = {}): Promise<UninstallReport> {\n const resolved = resolveDeps(deps);\n const steps: UninstallReport['steps'] = [];\n\n const wantSkill = await confirmStep(\n resolved.prompts,\n resolved.yes,\n 'Remove the active-work skill from ~/.claude/skills/?',\n );\n if (wantSkill) {\n const r = await uninstallSkill(deps);\n steps.push({\n name: r.name,\n done: r.ok ? r.done : false,\n ...(r.ok ? { message: r.message } : { error: r.error }),\n });\n } else {\n steps.push({ name: STEP_SKILL, done: false, message: 'Skipped' });\n }\n\n const wantCommand = await confirmStep(\n resolved.prompts,\n resolved.yes,\n 'Remove the /aw-prompt command from ~/.claude/commands/?',\n );\n if (wantCommand) {\n const r = await uninstallCommand(deps);\n steps.push({\n name: r.name,\n done: r.ok ? r.done : false,\n ...(r.ok ? { message: r.message } : { error: r.error }),\n });\n } else {\n steps.push({ name: STEP_COMMAND, done: false, message: 'Skipped' });\n }\n\n const supervisor = getSupervisor();\n if (supervisor) {\n const wantSupervision = await confirmStep(\n resolved.prompts,\n resolved.yes,\n supervisor.uninstallPrompt,\n );\n if (wantSupervision) {\n const r = await supervisor.uninstall(deps);\n steps.push({\n name: r.name,\n done: r.ok ? r.done : false,\n ...(r.ok ? { message: r.message } : { error: r.error }),\n });\n } else {\n steps.push({ name: STEP_SUPERVISION, done: false, message: 'Skipped' });\n }\n }\n\n const wantDaemon = await confirmStep(resolved.prompts, resolved.yes, 'Stop the daemon?');\n if (wantDaemon) {\n const r = await uninstallStopDaemon(deps);\n steps.push({\n name: r.name,\n done: r.ok ? r.done : false,\n ...(r.ok ? { message: r.message } : { error: r.error }),\n });\n } else {\n steps.push({ name: STEP_DAEMON, done: false, message: 'Skipped' });\n }\n\n const wantMcp = await confirmStep(\n resolved.prompts,\n resolved.yes,\n 'Unregister MCP from Claude Code?',\n );\n if (wantMcp) {\n const r = await uninstallMcp(deps);\n steps.push({\n name: r.name,\n done: r.ok ? r.done : false,\n ...(r.ok ? { message: r.message } : { error: r.error }),\n });\n } else {\n steps.push({ name: STEP_MCP, done: false, message: 'Skipped' });\n }\n\n return {\n steps,\n activeRootPreservedAt: resolved.paths.activeRoot,\n };\n}\n","import { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport { CURRENT_VERSION, runMigrations } from '../migrations/index.js';\n\nconst SCHEMA_VERSION_FILENAME = '.schema-version';\n\nconst schemaVersionPath = (activeRoot: string): string => join(activeRoot, SCHEMA_VERSION_FILENAME);\n\nconst isNodeErrnoException = (err: unknown): err is NodeJS.ErrnoException =>\n typeof err === 'object' && err !== null && 'code' in err;\n\nexport async function readSchemaVersion(activeRoot: string): Promise<number> {\n const path = schemaVersionPath(activeRoot);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (isNodeErrnoException(err) && err.code === 'ENOENT') {\n return 0;\n }\n throw err;\n }\n\n const trimmed = raw.trim();\n if (trimmed === '' || !/^\\d+$/.test(trimmed)) {\n throw new Error(\n `Invalid schema version in ${path}: expected a positive integer, got ${JSON.stringify(raw)}`,\n );\n }\n\n const parsed = Number(trimmed);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(\n `Invalid schema version in ${path}: expected a positive integer, got ${JSON.stringify(raw)}`,\n );\n }\n return parsed;\n}\n\nexport async function writeSchemaVersion(activeRoot: string, version: number): Promise<void> {\n if (!Number.isInteger(version) || version <= 0) {\n throw new Error(`Schema version must be a positive integer, got ${version}`);\n }\n await writeFile(schemaVersionPath(activeRoot), `${version}\\n`, 'utf8');\n}\n\nasync function readRawSchemaVersion(\n activeRoot: string,\n): Promise<{ present: false } | { present: true; version: number }> {\n const path = schemaVersionPath(activeRoot);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (isNodeErrnoException(err) && err.code === 'ENOENT') {\n return { present: false };\n }\n throw err;\n }\n\n const trimmed = raw.trim();\n if (trimmed === '' || !/^\\d+$/.test(trimmed)) {\n throw new Error(\n `Invalid schema version in ${path}: expected a non-negative integer, got ${JSON.stringify(raw)}`,\n );\n }\n\n const parsed = Number(trimmed);\n if (!Number.isInteger(parsed) || parsed < 0) {\n throw new Error(\n `Invalid schema version in ${path}: expected a non-negative integer, got ${JSON.stringify(raw)}`,\n );\n }\n return { present: true, version: parsed };\n}\n\n/**\n * Ensures the schema version file is present and up to date.\n *\n * - If the file is missing: writes `CURRENT_VERSION` (fresh install).\n * - If the file equals `CURRENT_VERSION`: no-op.\n * - If the file is older than `CURRENT_VERSION`: runs migrations in\n * order, then writes the new version.\n * - If the file is newer than `CURRENT_VERSION`: throws (downgrade not\n * supported).\n *\n * The summary is shaped for CLI/MCP startup logs.\n */\nexport async function ensureSchemaVersion(activeRoot: string): Promise<{\n before: number;\n after: number;\n migrated: boolean;\n ran: Array<{ from: number; to: number; description: string }>;\n}> {\n const raw = await readRawSchemaVersion(activeRoot);\n\n if (!raw.present) {\n await writeSchemaVersion(activeRoot, CURRENT_VERSION);\n return {\n before: CURRENT_VERSION,\n after: CURRENT_VERSION,\n migrated: false,\n ran: [],\n };\n }\n\n const before = raw.version;\n\n if (before === CURRENT_VERSION) {\n return { before, after: before, migrated: false, ran: [] };\n }\n\n const { ran } = await runMigrations(activeRoot, before);\n await writeSchemaVersion(activeRoot, CURRENT_VERSION);\n\n return {\n before,\n after: CURRENT_VERSION,\n migrated: ran.length > 0,\n ran: ran.map((m) => ({ from: m.from, to: m.to, description: m.description })),\n };\n}\n","import { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\nimport YAML from 'yaml';\nimport { ArtifactsSchema } from '../schemas/artifacts.js';\nimport { writeYaml } from '../utils/yaml-io.js';\nimport type { Migration } from './types.js';\n\n/**\n * v1 → v2 (AW-15): collapse `artifacts.yml` to a branches+stashes-only\n * schema and surface dropped PR entries via a migration log.\n *\n * Per-file transforms:\n * - `prs:` is dropped entirely. Each entry is logged at WARN to\n * `<activeRoot>/.migrations.log` so the user can reconcile manually.\n * - `branches[].last_commit` is dropped.\n * - `stashes[].message` → `stashes[].label`; `created` is dropped; `sha`\n * is preserved if present.\n *\n * The walk covers active-root initiatives and (best-effort) archived ones\n * under `<archiveRoot>/<domain>/archive/<slug>/artifacts.yml`, where\n * `archiveRoot` is the parent directory of the active root.\n *\n * Idempotent: re-running on already-v2 files leaves them unchanged\n * (extraneous keys like `prs:` simply aren't present in the v2 input).\n */\n\ninterface V1Pr {\n number?: number;\n repo?: string;\n title?: string;\n status?: string;\n}\n\ninterface V1Branch {\n repo?: string;\n name?: string;\n last_commit?: string;\n note?: string;\n}\n\ninterface V1Stash {\n repo?: string;\n message?: string;\n label?: string;\n created?: string;\n sha?: string;\n}\n\ninterface RawArtifacts {\n prs?: V1Pr[];\n branches?: V1Branch[];\n stashes?: V1Stash[];\n [key: string]: unknown;\n}\n\nfunction asArray<T>(value: unknown): T[] {\n return Array.isArray(value) ? (value as T[]) : [];\n}\n\nfunction normaliseBranch(b: V1Branch): { repo: string; name: string; note?: string } | null {\n if (typeof b.repo !== 'string' || typeof b.name !== 'string') return null;\n if (b.repo.length === 0 || b.name.length === 0) return null;\n const out: { repo: string; name: string; note?: string } = {\n repo: b.repo,\n name: b.name,\n };\n if (typeof b.note === 'string' && b.note.length > 0) out.note = b.note;\n return out;\n}\n\nfunction normaliseStash(s: V1Stash): { repo: string; label: string; sha?: string } | null {\n if (typeof s.repo !== 'string' || s.repo.length === 0) return null;\n // v1 used `message`; v2 uses `label`. Prefer label if both present.\n const label =\n typeof s.label === 'string' && s.label.length > 0\n ? s.label\n : typeof s.message === 'string'\n ? s.message\n : '';\n if (label.length === 0) return null;\n const out: { repo: string; label: string; sha?: string } = { repo: s.repo, label };\n if (typeof s.sha === 'string' && s.sha.length > 0) out.sha = s.sha;\n return out;\n}\n\ninterface MigrateOneResult {\n changed: boolean;\n droppedPrs: V1Pr[];\n}\n\nasync function migrateOne(filePath: string): Promise<MigrateOneResult> {\n let raw: string;\n try {\n raw = await fs.readFile(filePath, 'utf8');\n } catch {\n return { changed: false, droppedPrs: [] };\n }\n\n let parsed: RawArtifacts;\n try {\n parsed = (YAML.parse(raw) ?? {}) as RawArtifacts;\n } catch {\n // Malformed YAML — leave it; user will see it on next read.\n return { changed: false, droppedPrs: [] };\n }\n\n const droppedPrs = asArray<V1Pr>(parsed.prs);\n const branches = asArray<V1Branch>(parsed.branches)\n .map(normaliseBranch)\n .filter((b): b is { repo: string; name: string; note?: string } => b !== null);\n const stashes = asArray<V1Stash>(parsed.stashes)\n .map(normaliseStash)\n .filter((s): s is { repo: string; label: string; sha?: string } => s !== null);\n\n // Detect a no-op: prs absent, no last_commit on branches, no message-only stashes.\n const branchHadLegacy = asArray<V1Branch>(parsed.branches).some(\n (b) => typeof b.last_commit === 'string',\n );\n const stashHadLegacy = asArray<V1Stash>(parsed.stashes).some(\n (s) => typeof s.message === 'string' || typeof s.created === 'string',\n );\n const hadPrs = droppedPrs.length > 0 || parsed.prs !== undefined;\n if (!branchHadLegacy && !stashHadLegacy && !hadPrs) {\n return { changed: false, droppedPrs: [] };\n }\n\n const next = ArtifactsSchema.parse({ branches, stashes });\n await writeYaml(filePath, next, ArtifactsSchema);\n return { changed: true, droppedPrs };\n}\n\nasync function walkArtifactsFiles(activeRoot: string): Promise<string[]> {\n const out: string[] = [];\n\n // Active initiatives: <activeRoot>/<slug>/artifacts.yml\n try {\n const entries = await fs.readdir(activeRoot, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (entry.name.startsWith('.')) continue;\n const candidate = path.join(activeRoot, entry.name, 'artifacts.yml');\n try {\n await fs.access(candidate);\n out.push(candidate);\n } catch {\n // skip\n }\n }\n } catch {\n // active root may not exist; nothing to migrate.\n }\n\n // Archived initiatives: <archiveRoot>/<domain>/archive/<slug-YYYY-MM>/artifacts.yml\n const archiveRoot = path.resolve(activeRoot, '..');\n try {\n const domains = await fs.readdir(archiveRoot, { withFileTypes: true });\n for (const domain of domains) {\n if (!domain.isDirectory()) continue;\n if (domain.name.startsWith('.')) continue;\n // Skip the active root itself when scanning its parent.\n if (path.join(archiveRoot, domain.name) === path.resolve(activeRoot)) continue;\n const archiveDir = path.join(archiveRoot, domain.name, 'archive');\n let archived: Dirent[];\n try {\n archived = await fs.readdir(archiveDir, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const entry of archived) {\n if (!entry.isDirectory()) continue;\n const candidate = path.join(archiveDir, entry.name, 'artifacts.yml');\n try {\n await fs.access(candidate);\n out.push(candidate);\n } catch {\n // skip\n }\n }\n }\n } catch {\n // best-effort\n }\n\n return out;\n}\n\nasync function appendMigrationLog(activeRoot: string, lines: string[]): Promise<void> {\n if (lines.length === 0) return;\n const logPath = path.join(activeRoot, '.migrations.log');\n const stamp = new Date().toISOString();\n const body = lines.map((l) => `${stamp}\\tv1->v2\\t${l}\\n`).join('');\n try {\n await fs.mkdir(activeRoot, { recursive: true });\n } catch {\n // ignore\n }\n await fs.appendFile(logPath, body, 'utf8');\n}\n\nexport const v1ToV2Artifacts: Migration = {\n from: 1,\n to: 2,\n description: 'Drop prs[] / last_commit / stash.message from artifacts.yml',\n async run(activeRoot: string): Promise<void> {\n const files = await walkArtifactsFiles(activeRoot);\n const logEntries: string[] = [];\n for (const file of files) {\n const { droppedPrs } = await migrateOne(file);\n for (const pr of droppedPrs) {\n const num = typeof pr.number === 'number' ? `#${pr.number}` : '#?';\n const repo = pr.repo ?? '(unknown repo)';\n const title = pr.title ?? '(no title)';\n logEntries.push(`${file}\\t${num} (${repo}) ${title}`);\n }\n }\n await appendMigrationLog(activeRoot, logEntries);\n },\n};\n\nexport default v1ToV2Artifacts;\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { ValidationError } from '../errors.js';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { SessionFrontmatterSchema, type SessionFrontmatter } from '../schemas/session.js';\nimport {\n buildSessionStem,\n sessionFilePathForStem,\n writeSessionFile,\n} from '../sessions/session-file.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readRawFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { loadProposal, type Proposal, type ProposalInitiative } from './v3-proposal.js';\nimport {\n KNOWN_REPAIRS,\n applyRepair,\n planRepairs,\n repairBriefFrontmatter,\n type RepairPlan,\n} from './v3-repairs.js';\nimport type { Migration } from './types.js';\n\n/**\n * v2 → v3 (AW-38): retire `handoff.md` in favour of the session open-loops\n * ledger.\n *\n * Per initiative, driven entirely by the hand-authored proposal data file:\n * - write a back-dated `track: sidecar` session carrying the handoff's\n * next-actions as `next_steps`, so they enter the ledger and start aging\n * from their real last-touch;\n * - where the proposal marks a loop `abandoned`, write a *second* sidecar\n * session, stamped later, whose `resolves` closes it (see below);\n * - repair known-broken brief fields, then backfill `task_seq`;\n * - copy `handoff.md` to `sources/handoff-archive.md`, then delete it;\n * - repair the two known-malformed session files (see `v3-repairs.ts`).\n *\n * **This module writes sessions via `writeSessionFile` directly rather than\n * through `wrap`, which `SKILL.md` otherwise names as the only session\n * writer.** `wrap` stamps `brief.updated = today()`. Running it 17 times would\n * mark every initiative touched today and destroy the exact staleness signal\n * the back-dating exists to preserve. This is the sanctioned exception; no\n * other caller should copy it.\n *\n * **Why abandonment takes a second session.** A loop that was already dead\n * when the handoff was written must still be *opened* — the ledger's job is to\n * show that it existed — and then closed by a decision that is itself dated.\n * Migrating it as live would leave a loop whose own text reads \"do not chase\"\n * aging in the ledger forever and tripping the 30-day warning. Since only a\n * strictly later session may resolve an earlier one's loops, the closing\n * session is stamped with the proposal's `abandoned_at` — a fixed value, not\n * the clock, because the filename derives from it and idempotence keys on the\n * exact path.\n *\n * Two-phase by construction: `planV2ToV3` builds and schema-validates every\n * initiative in memory and throws on the first problem; nothing is written\n * until the whole batch passes. A rejected `session_id` therefore fails before\n * anything lands rather than half way through, which matters because a\n * half-run leaves `.schema-version` un-bumped and the next CLI invocation\n * re-runs from the top.\n *\n * Idempotent by exact target path: every synthetic session has a deterministic\n * `started` + `session_id`, so its filename is reproducible and an existing\n * file is a skip — checked per session, so an interrupted run that wrote the\n * opening session but not the abandonment one completes correctly.\n * `writeSessionFile`'s own de-duplication (which appends `-1`) is deliberately\n * never allowed to fire; it would duplicate every migrated loop under fresh\n * refs on a re-run.\n *\n * Synthetic sessions never set `no_loops`. An empty ledger here means \"the\n * handoff had nothing extractable\", not \"the operator confirmed nothing is\n * hanging\", and the migration is not entitled to make the second claim.\n */\n\nconst HANDOFF_FILE = 'handoff.md';\nconst HANDOFF_ARCHIVE = path.join('sources', 'handoff-archive.md');\n\n/** Distinguishes the back-dated opening session from the later closing one. */\nexport type SessionKind = 'open' | 'abandon';\n\nexport type HandoffDisposition = 'archive-and-remove' | 'archive-exists' | 'absent';\n\nexport interface SessionPlan {\n kind: SessionKind;\n stem: string;\n path: string;\n frontmatter: SessionFrontmatter;\n body: string;\n exists: boolean;\n}\n\n/** A single validated brief write carrying both repairs and the backfill. */\nexport interface BriefWrite {\n frontmatter: BriefFrontmatter;\n body: string;\n /** Value written, or `null` when only field repairs applied. */\n taskSeq: number | null;\n repairs: string[];\n}\n\nexport interface InitiativePlan {\n slug: string;\n /** Empty when uncovered; one session normally; two when loops are abandoned. */\n sessions: SessionPlan[];\n /** Set when no proposal entry covers this initiative; no session is written. */\n uncoveredReason?: string;\n brief: BriefWrite | null;\n /** Set when the brief cannot be rewritten; skipped, not fatal. */\n briefBlocked?: string;\n handoff: HandoffDisposition;\n}\n\nexport interface MigrationPlan {\n proposalOrigin: string;\n initiatives: InitiativePlan[];\n repairs: RepairPlan[];\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function listInitiativeSlugs(activeRoot: string): Promise<string[]> {\n let entries;\n try {\n entries = await fs.readdir(activeRoot, { withFileTypes: true });\n } catch {\n return [];\n }\n const slugs: string[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith('.')) continue;\n if (await pathExists(path.join(activeRoot, entry.name, 'brief.md'))) {\n slugs.push(entry.name);\n }\n }\n return slugs.sort();\n}\n\n/**\n * Highest task number ever visible on disk, including `tasks/archive/`.\n * `task add` only scans `tasks/`, so archiving the highest-numbered task\n * currently lowers its allocation floor; seeding the high-water mark from\n * both directories closes that hole at the same instant as the reuse window.\n */\nasync function maxOnDiskTaskNumber(initiativeDir: string, prefix: string): Promise<number> {\n const re = new RegExp(`^${prefix}-(\\\\d+)\\\\.yml$`);\n const tasksDir = path.join(initiativeDir, 'tasks');\n let max = 0;\n for (const dir of [tasksDir, path.join(tasksDir, 'archive')]) {\n let names: string[];\n try {\n names = await fs.readdir(dir);\n } catch {\n continue;\n }\n for (const name of names) {\n const m = re.exec(name);\n if (m) max = Math.max(max, Number.parseInt(m[1]!, 10));\n }\n }\n return max;\n}\n\nasync function nextTaskSeq(\n initiativeDir: string,\n frontmatter: Record<string, unknown>,\n): Promise<number | null> {\n if (frontmatter.task_seq !== undefined) return null;\n const prefix = frontmatter.task_prefix;\n if (typeof prefix !== 'string' || prefix.length === 0) return null;\n const max = await maxOnDiskTaskNumber(initiativeDir, prefix);\n return max > 0 ? max : null;\n}\n\n/**\n * The brief to write, or `null` when nothing changes. Field repairs run first\n * so an initiative whose brief is currently invalid — `health`, which carries\n * an out-of-enum `state` — stops being skipped by the backfill.\n *\n * Spread-then-set preserves every other field, `updated` included: neither a\n * repair nor a backfill is a touch of the work.\n */\nasync function planBrief(\n initiativeDir: string,\n slug: string,\n): Promise<{ write: BriefWrite | null; blocked?: string }> {\n const raw = await readRawFrontmatter(path.join(initiativeDir, 'brief.md'));\n const repaired = repairBriefFrontmatter(slug, raw.frontmatter);\n const taskSeq = await nextTaskSeq(initiativeDir, repaired.frontmatter);\n if (taskSeq === null && repaired.applied.length === 0) return { write: null };\n\n const merged = {\n ...repaired.frontmatter,\n ...(taskSeq === null ? {} : { task_seq: taskSeq }),\n };\n // A brief still invalid for some *other* reason is reported and skipped: one\n // malformed brief must not block the other sixteen initiatives.\n const parsed = BriefFrontmatterSchema.safeParse(merged);\n if (!parsed.success) {\n return { write: null, blocked: `brief.md is invalid: ${parsed.error.message}` };\n }\n return {\n write: { frontmatter: parsed.data, body: raw.body, taskSeq, repairs: repaired.applied },\n };\n}\n\nasync function planHandoff(initiativeDir: string): Promise<HandoffDisposition> {\n if (!(await pathExists(path.join(initiativeDir, HANDOFF_FILE)))) return 'absent';\n // An archive already sitting next to a live handoff means a previous run\n // stopped mid-initiative, or the operator has begun the manual split. Either\n // way the archive is not ours to overwrite, and deleting the handoff without\n // archiving it would destroy the only copy.\n if (await pathExists(path.join(initiativeDir, HANDOFF_ARCHIVE))) return 'archive-exists';\n return 'archive-and-remove';\n}\n\nfunction buildOpenSession(entry: ProposalInitiative): Omit<SessionPlan, 'path' | 'exists'> {\n const frontmatter = SessionFrontmatterSchema.parse({\n session_id: entry.session_id,\n // A synthetic session is an instant, not an interval: it stands for a\n // state read off the handoff, so `started === ended`.\n started: entry.ended,\n ended: entry.ended,\n track: 'sidecar',\n // `abandoned` is proposal-only bookkeeping and must not reach the file.\n next_steps: entry.next_steps.map(({ abandoned: _abandoned, ...step }) => step),\n resolves: [],\n });\n const stem = buildSessionStem(entry.ended, entry.session_id);\n return { kind: 'open', stem, frontmatter, body: buildOpenBody(entry, stem) };\n}\n\nfunction buildAbandonSession(\n entry: ProposalInitiative,\n openStem: string,\n abandonedAt: string,\n): Omit<SessionPlan, 'path' | 'exists'> {\n const sessionId = `${entry.session_id}-abandonment`;\n const frontmatter = SessionFrontmatterSchema.parse({\n session_id: sessionId,\n started: abandonedAt,\n ended: abandonedAt,\n track: 'sidecar',\n next_steps: [],\n resolves: entry.next_steps\n .filter((step) => step.abandoned !== undefined)\n .map((step) => ({\n ref: `${openStem}#${step.id}`,\n outcome: 'abandoned' as const,\n note: step.abandoned!.note,\n })),\n });\n const stem = buildSessionStem(abandonedAt, sessionId);\n return {\n kind: 'abandon',\n stem,\n frontmatter,\n body: buildAbandonBody(entry, openStem, stem),\n };\n}\n\nconst PERMANENCE_NOTE = (stem: string): string =>\n `_This file is permanent. Deleting it frees the stem \\`${stem}\\` for reuse by` +\n ` any later session sharing its minute and \\`session_id\\`, silently` +\n ` retargeting every ref filed against it._`;\n\nfunction buildOpenBody(entry: ProposalInitiative, stem: string): string {\n return [\n entry.body.trimEnd(),\n '',\n '---',\n '',\n `_Synthetic session written by the v2→v3 open-loops migration from this` +\n ` initiative's \\`handoff.md\\` (archived at \\`sources/handoff-archive.md\\`)._`,\n PERMANENCE_NOTE(stem),\n '',\n ].join('\\n');\n}\n\nfunction buildAbandonBody(entry: ProposalInitiative, openStem: string, stem: string): string {\n const dead = entry.next_steps.filter((s) => s.abandoned !== undefined);\n return [\n '# Abandoned on arrival',\n '',\n `The v2→v3 open-loops migration opened ${entry.slug}'s loops in \\`${openStem}\\`,`,\n 'back-dated to its real last-touch. The items below were already dead when that',\n 'handoff was written — the window each depended on had closed — so this session',\n 'closes them immediately rather than leaving loops in the ledger that their own',\n 'text tells a future session not to chase.',\n '',\n ...dead.flatMap((step) => [`- \\`${openStem}#${step.id}\\` — ${step.abandoned!.note}`, '']),\n '---',\n '',\n PERMANENCE_NOTE(stem),\n '',\n ].join('\\n');\n}\n\nasync function locateSessions(\n activeRoot: string,\n slug: string,\n drafts: Array<Omit<SessionPlan, 'path' | 'exists'>>,\n): Promise<SessionPlan[]> {\n const located: SessionPlan[] = [];\n for (const draft of drafts) {\n const full = sessionFilePathForStem(slug, draft.stem, activeRoot);\n located.push({ ...draft, path: full, exists: await pathExists(full) });\n }\n return located;\n}\n\nfunction draftSessions(\n entry: ProposalInitiative,\n abandonedAt: string | undefined,\n): Array<Omit<SessionPlan, 'path' | 'exists'>> {\n const open = buildOpenSession(entry);\n const hasAbandoned = entry.next_steps.some((s) => s.abandoned !== undefined);\n if (!hasAbandoned) return [open];\n // Guaranteed by ProposalSchema's refinement; re-asserted so a future caller\n // constructing a Proposal by hand cannot skip the ordering guarantee.\n if (abandonedAt === undefined) {\n throw new ValidationError(\n `${entry.slug} marks a next_step abandoned but the proposal has no abandoned_at`,\n );\n }\n return [open, buildAbandonSession(entry, open.stem, abandonedAt)];\n}\n\nasync function planInitiative(\n activeRoot: string,\n slug: string,\n entry: ProposalInitiative | undefined,\n abandonedAt: string | undefined,\n): Promise<InitiativePlan> {\n const initiativeDir = path.join(activeRoot, slug);\n const brief = await planBrief(initiativeDir, slug);\n const base = {\n slug,\n brief: brief.write,\n ...(brief.blocked === undefined ? {} : { briefBlocked: brief.blocked }),\n handoff: await planHandoff(initiativeDir),\n };\n if (entry === undefined) {\n return { ...base, sessions: [], uncoveredReason: 'no entry in the migration proposal' };\n }\n return {\n ...base,\n sessions: await locateSessions(activeRoot, slug, draftSessions(entry, abandonedAt)),\n };\n}\n\nfunction assertProposalSlugsExist(proposal: Proposal, known: string[]): void {\n const set = new Set(known);\n const missing = proposal.initiatives.filter((i) => !set.has(i.slug)).map((i) => i.slug);\n if (missing.length > 0) {\n throw new ValidationError(\n `v2→v3 migration proposal names initiatives that do not exist: ${missing.join(', ')}`,\n );\n }\n}\n\n/**\n * Phase one. Reads everything, validates everything, writes nothing. Throws\n * on the first invalid entry so a bad proposal is a pre-run error.\n */\nexport async function planV2ToV3(activeRoot: string): Promise<MigrationPlan> {\n const { proposal, origin } = await loadProposal();\n const slugs = await listInitiativeSlugs(activeRoot);\n assertProposalSlugsExist(proposal, slugs);\n\n const byslug = new Map(proposal.initiatives.map((i) => [i.slug, i]));\n const initiatives: InitiativePlan[] = [];\n for (const slug of slugs) {\n initiatives.push(\n await planInitiative(activeRoot, slug, byslug.get(slug), proposal.abandoned_at),\n );\n }\n return { proposalOrigin: origin, initiatives, repairs: await planRepairs(activeRoot) };\n}\n\nasync function archiveHandoff(initiativeDir: string): Promise<void> {\n const source = path.join(initiativeDir, HANDOFF_FILE);\n const target = path.join(initiativeDir, HANDOFF_ARCHIVE);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.copyFile(source, target);\n await fs.rm(source);\n}\n\nasync function writePlannedSession(\n activeRoot: string,\n slug: string,\n session: SessionPlan,\n): Promise<void> {\n const fm = session.frontmatter;\n await writeSessionFile({\n slug,\n activeRoot,\n session_id: fm.session_id,\n started: fm.started,\n ended: fm.ended,\n track: fm.track,\n next_steps: fm.next_steps,\n resolves: fm.resolves,\n body: session.body,\n });\n}\n\nasync function applyInitiative(activeRoot: string, plan: InitiativePlan): Promise<void> {\n const initiativeDir = path.join(activeRoot, plan.slug);\n await withFileLock(path.join(initiativeDir, '.lock'), async () => {\n // Ordered: the opening session must exist before the one that resolves it.\n for (const session of plan.sessions) {\n if (session.exists) continue;\n await writePlannedSession(activeRoot, plan.slug, session);\n }\n if (plan.brief !== null) {\n await writeFrontmatter(\n path.join(initiativeDir, 'brief.md'),\n plan.brief.frontmatter,\n plan.brief.body,\n BriefFrontmatterSchema,\n );\n }\n if (plan.handoff === 'archive-and-remove') {\n await archiveHandoff(initiativeDir);\n }\n });\n}\n\n/** Phase two. Writes only what phase one already validated. */\nexport async function applyV2ToV3(activeRoot: string, plan: MigrationPlan): Promise<void> {\n for (const initiative of plan.initiatives) {\n await applyInitiative(activeRoot, initiative);\n }\n for (const repair of plan.repairs) {\n await applyRepair(activeRoot, repair);\n }\n}\n\nexport const v2ToV3OpenLoops: Migration = {\n from: 2,\n to: 3,\n description: 'Retire handoff.md into synthetic back-dated open-loop sessions',\n async run(activeRoot: string): Promise<void> {\n const plan = await planV2ToV3(activeRoot);\n await applyV2ToV3(activeRoot, plan);\n },\n};\n\nexport { KNOWN_REPAIRS };\nexport default v2ToV3OpenLoops;\n","import { promises as fs } from 'node:fs';\nimport { z } from 'zod';\nimport { ValidationError } from '../errors.js';\nimport { NextStepSchema, SessionIdSchema } from '../schemas/session.js';\nimport { V3_OPEN_LOOPS_PROPOSAL } from './data/v3-open-loops-proposal.js';\n\n/**\n * The data file the v2→v3 migration consumes.\n *\n * The migration is deliberately mechanical: it does not read handoff prose,\n * does not infer back-dates, and does not decide what a loop is. Those are\n * per-initiative judgement calls made ahead of time and recorded here, so the\n * code that touches the operator's data has no discretion left in it.\n */\n\n// A synthetic `session_id` also becomes part of the filename and the first\n// half of every ref the session mints. The schema-level rule only bans\n// `#`, whitespace and `/`; kebab-case is narrower on purpose, because a\n// hand-authored proposal naturally reaches for spaces and slashes and the\n// resulting failure would otherwise land mid-run.\nconst KEBAB_SESSION_ID = SessionIdSchema.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, {\n message: 'session_id must be kebab-case ([a-z0-9-], no leading/trailing dash)',\n});\n\nconst ISO_INSTANT = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/;\n\n/**\n * A loop that is dead on arrival — the handoff recorded it, but the window it\n * depended on has since closed. It is still *opened* by the back-dated session\n * (the ledger should show it existed) and then closed by a second, later\n * session carrying this note. Recording it as live would leave a loop whose\n * own text says \"do not chase\" sitting in the ledger forever.\n */\nconst AbandonedSchema = z.object({ note: z.string().min(1) });\n\nconst ProposalNextStepSchema = NextStepSchema.extend({\n abandoned: AbandonedSchema.optional(),\n});\n\nconst ProposalInitiativeSchema = z.object({\n slug: z.string().min(1),\n /**\n * Real last-touch of the initiative, hand-supplied. Never `Date.now()` and\n * never file mtime — several initiatives have mtimes months adrift from\n * their true last-touch, and the whole point of back-dating is to preserve\n * the staleness signal.\n */\n ended: z.string().regex(ISO_INSTANT, {\n message: 'ended must be an ISO 8601 instant with timezone',\n }),\n session_id: KEBAB_SESSION_ID,\n body: z.string().min(1),\n next_steps: z.array(ProposalNextStepSchema).default([]),\n});\n\nexport const ProposalSchema = z\n .object({\n /**\n * When the abandonment decision was made. Hand-supplied rather than read\n * from the clock: the second session's filename derives from it, and the\n * migration keys idempotence on exact paths, so `Date.now()` would mint a\n * fresh path — and a duplicate abandonment session — on every re-run.\n */\n abandoned_at: z\n .string()\n .regex(ISO_INSTANT, {\n message: 'abandoned_at must be an ISO 8601 instant with timezone',\n })\n .optional(),\n initiatives: z.array(ProposalInitiativeSchema),\n })\n .superRefine((value, ctx) => {\n const withAbandoned = value.initiatives.filter((i) =>\n i.next_steps.some((n) => n.abandoned !== undefined),\n );\n if (withAbandoned.length === 0) return;\n if (value.abandoned_at === undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['abandoned_at'],\n message: 'abandoned_at is required when any next_step is marked abandoned',\n });\n return;\n }\n // Only a strictly later session may resolve an earlier one's loops.\n const at = new Date(value.abandoned_at).getTime();\n for (const initiative of withAbandoned) {\n if (at <= new Date(initiative.ended).getTime()) {\n ctx.addIssue({\n code: 'custom',\n path: ['abandoned_at'],\n message:\n `abandoned_at (${value.abandoned_at}) must be strictly after ` +\n `${initiative.slug}'s ended (${initiative.ended}), or the abandonment ` +\n 'session cannot resolve the loops it opens',\n });\n }\n }\n });\n\nexport type ProposalInitiative = z.infer<typeof ProposalSchema>['initiatives'][number];\nexport type ProposalNextStep = z.infer<typeof ProposalNextStepSchema>;\nexport type Proposal = z.infer<typeof ProposalSchema>;\n\n/** Env var pointing at a JSON proposal, overriding the bundled default. */\nexport const PROPOSAL_PATH_ENV = 'AW_V3_PROPOSAL';\n\nfunction parseProposal(input: unknown, origin: string): Proposal {\n const result = ProposalSchema.safeParse(input);\n if (!result.success) {\n throw new ValidationError(\n `Invalid v2→v3 migration proposal (${origin}): ${result.error.message}`,\n );\n }\n const seen = new Set<string>();\n for (const initiative of result.data.initiatives) {\n if (seen.has(initiative.slug)) {\n throw new ValidationError(\n `Invalid v2→v3 migration proposal (${origin}): duplicate slug ${initiative.slug}`,\n );\n }\n seen.add(initiative.slug);\n }\n return result.data;\n}\n\n/**\n * Load and validate the proposal. Prefers `$AW_V3_PROPOSAL` (a JSON file) so\n * the operator can stage and dry-run a revised proposal without a rebuild;\n * otherwise uses the copy bundled with this release.\n */\nexport async function loadProposal(): Promise<{ proposal: Proposal; origin: string }> {\n const override = process.env[PROPOSAL_PATH_ENV];\n if (override !== undefined && override.length > 0) {\n let raw: string;\n try {\n raw = await fs.readFile(override, 'utf8');\n } catch {\n throw new ValidationError(`${PROPOSAL_PATH_ENV} points at an unreadable file: ${override}`);\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw new ValidationError(\n `${PROPOSAL_PATH_ENV} is not valid JSON (${override}): ${(err as Error).message}`,\n );\n }\n return { proposal: parseProposal(json, override), origin: override };\n }\n return {\n proposal: parseProposal(V3_OPEN_LOOPS_PROPOSAL, 'bundled'),\n origin: 'bundled',\n };\n}\n","/**\n * Per-initiative input to the v2→v3 open-loops migration.\n *\n * Authored by hand (one pass per initiative, reviewing its `handoff.md`), not\n * generated at run time. Typed `unknown` so it can only be used after passing\n * `ProposalSchema` — the migration validates the whole batch before it writes\n * anything, and a data file that typechecks is not thereby trusted.\n *\n * Shape: see `ProposalSchema` in `../v3-proposal.ts`.\n *\n * `ended` is each initiative's real last-touch, and never the clock. It is\n * normally read off the handoff's own content; where that is silent it is\n * taken from the covering session's recorded `ended`, and only as a last\n * resort from file mtime (many mtimes are months adrift from the true\n * last-touch, which is exactly what back-dating exists to preserve). The\n * loops below are therefore born already aged, and the eight initiatives last\n * touched in May trip the 30-day stale-loop warning on day one. That is the\n * intended outcome, not a defect.\n *\n * A `next_step` carrying `abandoned` is opened by the back-dated session and\n * then closed by a second session stamped `abandoned_at`, so the ledger shows\n * the loop existed and shows who killed it.\n *\n * An initiative absent from this list is SKIPPED: its `handoff.md` is still\n * archived to `sources/handoff-archive.md`, but no synthetic session is\n * written and its next-actions do not enter the ledger. The migration reports\n * every such skip loudly rather than guessing at content.\n *\n * ## Refreshed 2026-07-29 (AW-65)\n *\n * This file was authored 2026-07-28 12:28, *mid-session* for several\n * initiatives, and four of them then kept working and rewrote the handoff it\n * had just been derived from: `relay`, `active-work`, `claude-channels` and\n * `voltras-workspace`. Those four entries were re-derived against the handoffs\n * as they then stood; the other 13 predate 12:28 and are untouched. Each\n * changed entry carries a comment saying what moved and why.\n *\n * **It then had to happen a SECOND time the same day.** Between the refresh and\n * the apply window, further sessions rewrote `relay` (19:27Z) and\n * `voltras-workspace` (19:09Z) again, closed `R-24` and `CC-31`, and merged\n * `VMCP-01.72` part (a). A hand-authored proposal cannot stay current for an\n * initiative that is being actively worked: **re-validate immediately before\n * applying, in a window where nothing else is running, and treat any gap\n * between refresh and apply as invalidating.** The mechanical checks below are\n * the cheap part; the content drift is not.\n *\n * Four rules these passes established, worth keeping if this is ever redone:\n *\n * - **A loop for finished work cannot be expressed here.** The only resolve\n * this file can emit is `abandoned` (`v2-to-v3-open-loops.ts`), so a loop\n * whose work *completed* must be DROPPED, never marked abandoned — that\n * would invert the distinction AW-59 added.\n * - **`kind: pr` never auto-resolves.** Bootstrap leaves `mergedPrs`\n * unsupplied on purpose to stay offline (`bootstrap/prompt.ts`), so a PR\n * loop hangs forever regardless of merge state. Prefer prose.\n * - **Never point a loop at a `done` task whose work is not done.** It\n * auto-resolves on arrival and deletes the item from the ledger silently.\n * `claude-channels` teleport is the live example: CC-20 covered the design\n * and is closed, but the implementation — second on that board — has no\n * open task, so it is carried as prose.\n * - **Re-check every `kind: task` ref against task STATUS at apply time, not\n * just existence.** `relay` n9 pointed at R-24, which closed hours after the\n * first refresh; the loop would have vanished on arrival and taken the\n * recurring obligation with it (it is prose now). Where a task closes and the\n * work genuinely is finished, DROP the loop instead — filing one that\n * auto-resolves is noise, which is why `claude-channels` n1 is gone.\n */\nexport const V3_OPEN_LOOPS_PROPOSAL: unknown = {\n abandoned_at: '2026-07-28T18:00:00Z',\n initiatives: [\n {\n slug: 'active-work',\n // DELIBERATELY NOT the handoff's last-touch (2026-07-28T18:52Z), unlike\n // every other entry refreshed on 2026-07-29. The 2026-07-28 session\n // rewrote this handoff end to end, and the rewrite silently dropped the\n // miner/release thread below — AW-23, AW-28 and AW-34 are all still\n // `status: open` and appear nowhere in the current file. 2026-07-15 is\n // their real hang date; `tasks/` records no such thing. Stamping this\n // session 07-28 would reset that age to zero and defeat the back-dating.\n //\n // The current handoff's own next-actions (AW-65, AW-38, inbox) are NOT\n // migrated here: the 2026-07-28 and 2026-07-29 wraps already filed them\n // as live loops, and re-filing would double-count them — the specific\n // hazard AW-65 was raised to catch.\n ended: '2026-07-15T00:00:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-07-15\\n\\nSession-mining tooling now lives in active-work, its proper home, and the miner roadmap is moving. active-work is published to npm as `@titan-design/active-work@0.1.0`; `main` is clean.\\n\\nTwo PRs are open, neither merged: **active-work#56** (`feat/session-miner-tooling` — the byte-identical miner port into `tools/`, plus AW-24 cost rollups and AW-27 the eval harness, both done) and **titan-design#110** (the design-repo copy, reduced to dashboard specimens). The eval immediately caught a real miner bug — junk branch names `/` and `HEAD:main` — filed as AW-34.\\n\\nThe v0.1 publish shipped under the org scope, not the planned `@hjewkes` scope, and releasing is now tag-triggered OIDC trusted publishing (#54) with changesets removed (#55). The first tagged run has never been exercised end to end.\\n\\nOne pre-existing flake: `__tests__/server/file-watch.test.ts` (timing/debounce, matches AW-12), passes on re-run.\\n\\n_This state is 13 days behind the initiative's newest real session (2026-07-28)._\\n\\n_Refreshed 2026-07-29 (AW-65): the 2026-07-28 handoff rewrite dropped this thread without closing it, so it is carried here from the 07-15 state and ages from there. PR #56 merged 2026-07-29 and its loop was removed rather than migrated._\",\n next_steps: [\n {\n id: 'n1',\n text: 'AW-28 Drain error-atlas sourcing (est 8) is the next miner build and the first piece to land in src/ as real TypeScript — native Drain port, do not shell to Python. Recipe in sources/deepdive-session-mining-build-specs.md §C1.',\n kind: 'task',\n ref: 'AW-28',\n },\n {\n id: 'n2',\n text: 'AW-34 is the quick one (est 2) — fix the junk branch names the eval caught, then regression-check with `pnpm eval:miner`.',\n kind: 'task',\n ref: 'AW-34',\n },\n {\n id: 'n3',\n text: \"AW-23 production session-signal index (est 8) is now unblocked by AW-27's eval gate and unlocks the Phase-3 backlog AW-29 through AW-33.\",\n kind: 'task',\n ref: 'AW-23',\n },\n // n4 (merge active-work#56) is deliberately absent. The PR merged\n // 2026-07-29T03:46:53Z, so the loop is dead on arrival — but it\n // *completed*, and this file can only express `abandoned`\n // (v2-to-v3-open-loops.ts:261). Recording a merged PR as abandoned\n // would invert the very distinction AW-59 added. Nor can it be left\n // live: bootstrap leaves `mergedPrs` unsupplied on purpose so\n // derivation stays offline (bootstrap/prompt.ts:743), so a `kind: pr`\n // loop never auto-resolves and this one would hang forever. Dropped.\n {\n id: 'n5',\n text: 'Merge titan-design#110 — the design-repo copy with miner tools removed; the lab/active-work-dashboard branch is pushed as a full-history archive. Verified still open 2026-07-29 (active-work#56, its former companion, has since merged).',\n kind: 'prose',\n },\n {\n id: 'n6',\n text: 'Eyeball the first tagged release run: it is the first real end-to-end exercise of the OIDC trusted-publisher config, and nothing has pushed a vX.Y.Z tag yet.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'ai-investing-workflow',\n ended: '2026-05-26T23:59:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-05-26\\n\\nResearch phase complete. Three async agents (institutional ceiling, retail toolkit, empirical edge) reported and were synthesized into a unified position. The prior hypothesis — \\\"retail can't compete with institutional AI\\\" — was confirmed half-right and refined: the right benchmark is the median active fund (which most institutions also lose to) and one's own un-AI'd behaviour, not Citadel.\\n\\nNext phase is execution: pick sources to subscribe to, decide tooling spend, build 2–3 concrete LLM workflows (10-K diff, earnings-call execution-credibility, pre-mortem) and establish behavioural guardrails before any of it touches real capital decisions.\\n\\nCore allocation stays passive/indexed regardless. This work is about being a more literate observer of macro, and possibly supporting a small active sleeve in small/mid-cap names where AI-assisted research can plausibly close information gaps.\\n\\nNothing has moved since. Eight AIW-* tasks are filed and all are open.\",\n next_steps: [\n {\n id: 'n1',\n text: 'Decide: pay for FT now, or trial the free Overshoot + Slok weekly deck first. This gates AIW-1 and is the only thing standing between research and execution.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Answer whether an active sleeve exists today or the small-active-sleeve idea is still entirely hypothetical — everything downstream is sized by this.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Confirm whether direct indexing is already in place in the tax-advantaged accounts before evaluating Wealthfront/Betterment (the measured after-tax uplift is ~1.8%).',\n kind: 'task',\n ref: 'AIW-6',\n },\n ],\n },\n {\n slug: 'audiobook',\n ended: '2026-07-26T00:00:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-07-26\\n\\nThe autopull pipeline (main track) runs fully unattended and is healthy. Book 7 is complete, 12/12 chapters exported. No open engineering blockers on either track.\\n\\nA separate `feat/tts-quality` branch (local, unpushed, HEAD `6680bee`, 153 tests passing) carries TTS-quality work: chunker boundary-hallucination fix, currency/decimal/punctuation normalization, stats-table roster rephrasing, self-heal of hallucinated takes wired into the worker (~68% babble reduction), and a new MP3→m4b packaging tool. The Book 7 Ch 16 appendix was re-rendered clean and replaced in the R2 feed on 2026-07-23 (stable GUID — delete+refresh in Overcast to re-pull).\\n\\nThe m4b tool delivered Soccer Supremo Book 1 as two m4bs in `~/Downloads/Soccer Supremo 1/`, awaiting an Apple Books playback check.\\n\\nPRs #4, #5 and #6 are merged to main with green CI: the pipeline event store + FastMCP server, the book-discovery gap plus lock cleanup, and the cheap precheck gate at a 15-minute cadence.',\n next_steps: [\n {\n id: 'n1',\n text: 'Close the partial-generation recovery gap: a chapter downloaded + normalized + chunked but interrupted mid-TTS (has normalized.txt, no audio.wav) is not re-picked by the precheck or find_new_chapters — both key off raw-without-normalized.',\n kind: 'task',\n ref: 'A-2',\n },\n {\n id: 'n2',\n text: '/api/scraper/preview returns 422 — fiction_id is declared a Path param but is absent from the route path. Latent; unused by autopull.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: \"Decide the fate of parked code: PR #1's cloud infra (Docker/k8s/Terraform/S3/SQS/Postgres) contradicts the single-user filesystem-only design and sits under parked/ — keep as reference or delete. The dialogue/speaker module is parked too; revive only if wanted.\",\n kind: 'prose',\n },\n {\n id: 'n4',\n text: \"Check Soccer Supremo Book 1's two m4bs actually play in Apple Books — the AAC-vs-MP3-remux split exists precisely because Apple Books plays MP3-in-m4b silent, and this was never confirmed.\",\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'brain',\n ended: '2026-05-12T00:00:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-05-12\\n\\nHEAD is on `spike/2026-05-platform`, pointing at the same SHA as `main` (`6da9d96`, 2026-05-02). Two active tracks.\\n\\n**Platform redesign spike** — Spike 1 critical-subset checkboxes pass. Restate + Claude Agent SDK + a custom YAML compiler validated end to end across 10 packages, ~3,500 LOC, 42 unit tests, 3 e2e smokes (cancellation reaches the Claude Code child in 201ms; the planning workflow walks 4 nodes in 22ms). `07-spike-1-decision-memo.md` recommends adopting Path 1.\\n\\n**Main-line autonomy/PM work** — the last 30 commits on main are VNM-56 worktree/merge-lifecycle (#215–#221) and VNM-48 dispatch/file-ownership. Phase 1 stabilization is done; Phase 2 (parallel dispatch on real workstreams) is unblocked.\\n\\nThe working tree is dirty in a non-trivial way: ~80+ untracked files under `docs/plans/` and `docs/pm-module/diagnostic/v*`, plus a top-level `platform-redesign-2026-05.zip` (358K) and a mirror directory duplicating content already in the repo.\\n\\n⚠️ Contested since: titan-platform\\'s 2026-07-13 round-2 research concluded the spike is a **design, not a built or adopted platform**, and that the \"decision memo\" framing was wrong.',\n next_steps: [\n {\n id: 'n1',\n text: 'Read docs/architecture/2026-05-platform-redesign/07-handoff-spike-1-continuation.md and 07-spike-1-decision-memo.md first — they are the freshest authoritative state — then spike-1-notes.md for per-checkbox status.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: \"THE gating decision: adopt Path 1 and scope a migration of src/modules/workflow/ (and consumers) onto the spike's Step contract + Restate; or defer and keep investing in the homegrown runtime; or abandon the spike. Deferred items are enumerated in the decision memo § 'What's deferred to migration'. Weigh this against titan-platform's later finding that the spike was never actually adopted.\",\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'If continuing the spike: (3) HITL awakeable wiring is the highest-value remaining critical-subset coverage; (4) real leaves and (5) parallel-spawn fan-out make the artifact stronger. The side-by-side and decision memo are already written.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'If executing the migration: scope which existing modules (pm, agents, sessions, workflow, codebase) become leaves on the Step contract vs stay outside it. Side-by-side §5 enumerates the surfaces.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'Housekeeping on the dirty tree: classify docs/plans/* (commit canonical, gitignore ephemeral — pattern set by #210 691fcf1), then decide whether platform-redesign-2026-05.zip and its mirror dir are a discardable backup or content to commit.',\n kind: 'prose',\n },\n {\n id: 'n6',\n text: 'Root-cause the embedding dimension mismatch (Expected 384 dimensions but received 768) that intermittently breaks PM-via-MCP — likely DB-init vs embedder-config drift. Not blocking via CLI but it degrades autonomy.',\n kind: 'prose',\n },\n {\n id: 'n7',\n text: 'Reconcile PM state: three tasks from the 2026-04-27 parallel test still show in-progress/stuck despite merged PRs. Verify #218 (VNM-56.71) actually cleared the backlog, or file a follow-up.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'claude-channels',\n // Refreshed 2026-07-29 (AW-65). Was 2026-07-28T16:29:00Z — authored\n // mid-session, ~2.7h before the covering session's own recorded\n // `ended: 2026-07-28T19:10:00Z`, and before CC-30 closed, CC-31 was\n // filed and teleport was designed. Anchored to the session's end.\n ended: '2026-07-28T19:10:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-07-28\\n\\n**Agent teams work.** CC-17 closed: a spawned agent is a durable, addressable peer that outlives its spawner, launchable headless or in a terminal under normal permissions — and spawned agents have now done real work (one found a lifecycle race, three found a security gap, two live defects, a false test). **CC-30 closed** too: ordinary sessions now have durable identity.\\n\\n`feat/plugin-packaging` pushed at `a12c1fc`, clean tree, 323 tests green, tsc and prettier clean. The broker runs properly detached in its own process group, so it survives the session that started it. **CC-24 closed** — the headless hang is gone, and the fix was not A8's stream.jsonl: the streams are discarded, because Claude Code already writes a full structured transcript per session and we assign the session id ourselves. §9 and A8 in agent-teams.md are marked superseded.\\n\\n**CC-28 has since closed**, so confinement is real and the planned wave items stand on their own. Confinement turned out to be schema-level: a denied tool is ABSENT from the model's schema rather than refused, so there is **no denial frame at all** for a toolset-confined agent — whereas settings-level denials ARE observable (`is_error: true` plus a `toolDenialKind` marker). Any feature here must say which of the two it covers.\\n\\n**CC-31 is the most important new finding of the session:** severing a session's bus produces no noticeable dead bus — Claude Code restarts the MCP server and the session ends up silently absent from a *working* bus, unable to tell.\\n\\nTeleport (CC-20) is now fully designed, with all five decisions recorded in the task, but **not implemented**.\\n\\nThe title is legacy: the subject is general agent orchestration, and the logic will eventually fold into relay. Keep the orchestration logic separable from the local broker / event log / registry.\\n\\n_Refreshed 2026-07-29 (AW-65) against the handoff as it stood at session close._\",\n next_steps: [\n // The original n1 (build the live-spawn harness) duplicated n4's CC-27\n // content and was dropped. The first 2026-07-29 pass replaced it with\n // CC-31, the handoff's \"Top of the board\" item — and CC-31 then CLOSED\n // later the same day: re-measured, the `CLAUDE_CODE_SESSION_ID` gate\n // answered, and the two failure states it had conflated separated.\n // Leaving it as a task ref would file a loop that auto-resolves on\n // arrival and never surfaces, so the slot is simply empty. Nothing is\n // lost: this initiative's 14:32 session filed four live loops through\n // `wrap`, so its current work is already in the ledger.\n {\n id: 'n2',\n text: 'CC-25 — the spawn-rate budget §11.3 promises and that does not exist. Named as a §11 defence that turned out to be prose.',\n kind: 'task',\n ref: 'CC-25',\n },\n {\n id: 'n3',\n text: 'CC-26 — agent_ready + spawnedBy. Design is fully worked out in the task and the subscription machinery shipped in bd31bad, so this is one protocol selector plus a default.',\n kind: 'task',\n ref: 'CC-26',\n },\n {\n id: 'n4',\n text: 'CC-27 — the opt-in iTerm placement test EXISTS (83271dd) but has never had a clean verified end-to-end run; it was stopped partway, on purpose. Run it cleanly and unattended. It stays gated behind an env var so it never fires on CI or by default — that gating is load-bearing, since an ungated iterm-pane test once opened real windows on the laptop (fixed in aa08d86). Do not hand this to an agent: it takes focus (see the ~20-run incident).',\n kind: 'task',\n ref: 'CC-27',\n },\n {\n id: 'n5',\n text: 'CC-29 needs a DECISION, not more probing — its empirical half is closed (two live probes settled it 2026-07-28). Pairing option (2) `agent logs`, settings-level only, with option (4) surface deny lists at spawn time covers both failure kinds; either alone covers only one.',\n kind: 'task',\n ref: 'CC-29',\n },\n {\n id: 'n6',\n // Deliberately `prose`, NOT `kind: task, ref: CC-20`. CC-20 is\n // `status: done` — it covered the DESIGN — but teleport is not\n // implemented: the handoff ranks it second on the board and its\n // branch `feat/teleport-identity` is 6 commits UNPUSHED. A task ref\n // here would auto-resolve on migration and delete the #2 item from\n // the ledger without anyone deciding to. No open task represents\n // the implementation; this loop is the only thing carrying it.\n text: \"Implement teleport — second on the board behind CC-31. It is fully DESIGNED (CC-20, now closed; all five decisions recorded there), but NOT built: branch `feat/teleport-identity` is 6 commits and UNPUSHED, main untouched on purpose. No open task covers the implementation. Related: CC-23 (headless↔terminal switching) rides the same substrate and is partly gated on CC-29, since 'notice an agent is stuck and surface it into a terminal' presupposes noticing.\",\n kind: 'prose',\n },\n // Old n7 (Service Steps 3/4 parallelism) dropped: \"Service Steps\",\n // \"CLI restructure\" and \"HTTP reads\" appear nowhere in the current\n // 93-line handoff, and nothing else corroborates them. Migrating an\n // unverifiable loop would put a permanently unanswerable item in the\n // ledger; the text survives in sources/handoff-archive.md if needed.\n ],\n },\n {\n slug: 'codewatch',\n ended: '2026-07-06T23:49:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-07-06 (session 30 wrap)\\n\\nShipped the C-88 gate(a) query-time capability surface the session-29 gates authorized — PR #121, self-merged once CI went green under standing authorization.\\n\\n`packages/graph/src/embeddings.ts` + migration v5 add an `embedding` table content-addressed by (model, text_hash), deliberately not snapshot-scoped: vectors are found by rebuilding text→hash at read time, so incremental reuse is free (843/843 reused, zero ollama calls), vectors never duplicate across snapshots, and the indexer is untouched. New `graph embed`, `graph index --embed`, and `graph similar <intent>` returning top-K candidates-not-verdicts. Read API 1.1.0→1.2.0 plus MCP `find_similar`. 1276 tests green, typecheck clean, fitness gate 0-new.\\n\\nAn owner-directed injection eval ran the same session (sources/c88-injection-eval.md). Verdict: the duplication-prevention delta is SMALL on the documented surface — A0 already reuses 9/12. The real measured value is −28% cost ($8.82→$6.31) and 19.5→16.1 avg turns as the search phase collapses, plus A1 consolidating tRPC\\'s real getQueryKeyInternal twin-duplication onto one shared impl.\\n\\nThe file below this block was ~1,750 lines of reverse-chronological session diary back to 2026-07-04; every \"NEXT\" in it was acted on by the following session.',\n next_steps: [\n {\n id: 'n1',\n text: \"C-88 gate(b), cost-gated: coarse hierarchical Leiden on the resolved file graph → LLM community summaries at capability altitude → a 'how does this repo do X' convention surface, reusable for the C-90 bundle. Gate on a cost budget — summarize the coarse level only, or lazily.\",\n kind: 'task',\n ref: 'C-88',\n },\n {\n id: 'n2',\n text: 'C-92 codewatch plugin (injection delivery), now evidence-framed by the injection eval: a SessionStart/plan-time hook injecting find_similar + context. Frame the value as cost/latency/reliability and consolidation, NOT duplication prevention.',\n kind: 'task',\n ref: 'C-92',\n },\n {\n id: 'n3',\n text: 'C-90 compact context-bundle (p7) — ranked file-line citations, and it can now include similar-capability candidates.',\n kind: 'task',\n ref: 'C-90',\n },\n {\n id: 'n4',\n text: 'These three were an explicit pick-ONE, not a queue. Conditional: the duplication-prevention claim needs the undocumented surface (where sig-only retrieval is also weaker) — only build that stratified eval if C-92 ships.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'OPERATOR-ONLY, orphaned: the npm publish is still not done. C-6 shipped a publish-READY distribution (all 7 packages, verified end-to-end via local verdaccio) but the actual publish needs the @codewatch npm org/scope created plus auth, then `pnpm release` or the Release action with dry_run=false and an NPM_TOKEN secret. C-6 is closed, so this lives in no task.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'computer-organization',\n ended: '2026-05-12T00:00:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-05-12\\n\\nInitiative scaffolded from the `aw discover` triage pass. 22 per-directory triage tasks filed (CO-1..CO-22), all open, severity low, priority matching the CO number. Nothing decided yet — every legacy directory is still sitting in ~/Documents/projects/ untouched.\\n\\nState is `backburner`: this drains opportunistically, not on a deadline. All work happens on the filesystem; no repo, no CI, no tests.\\n\\nThe one thing that exists here and nowhere else is the first-pass triage judgment — which specific directories are obvious deletes, which are obvious archives, and which need investigation before anything is touched. The CO-*.yml tasks are all still generically titled \"archive, integrate, or delete\" with no disposition recorded, so the calls below are the only record of that work.',\n next_steps: [\n {\n id: 'n1',\n text: 'Pick ONE canonical archive destination (e.g. ~/Documents/projects/.archive/ vs an external cold-storage path) and record it before moving anything, or the triage fragments across destinations.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Fast-DELETE candidates from the first pass, pending spot-check: `test` (CO-16), `bookmarks-demo` (CO-2), `webfetch` (CO-21).',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Fast-ARCHIVE candidates from the first pass: `experimentation_docs` (CO-5), `rp-university-transcripts` (CO-14), `kaizen-analysis` (CO-10).',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'Investigate the three name-collision dirs — `titan-design` (CO-18), `voltras` (CO-19), `workflow-improvement` (CO-22) — by reading README and git log to establish their relationship to the live counterparts, then decide confirm-then-merge vs treat-as-stale-and-delete.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'Decide the home-infra consolidation question: promote `home` (CO-7), `home_server` (CO-8) and `homeassistant_samba` (CO-9) into one initiative and close all three with pointers, or triage each in isolation.',\n kind: 'prose',\n },\n {\n id: 'n6',\n text: 'Decide whether the container dirs `nd projects` (CO-12), `personal_projects` (CO-13) and `split_projects` (CO-15) need their own sub-triage or can be classified wholesale.',\n kind: 'prose',\n },\n {\n id: 'n7',\n text: 'Then work the remaining CO tasks individually, recording the chosen disposition in each YAML before any destructive operation, and re-run `aw discover` after each batch to confirm dirs have dropped off the untracked list.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'denver-rezzy',\n ended: '2026-05-12T00:00:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-05-12\\n\\nPhase 1 skeleton complete and exercised end to end on **synthetic data**. The MCP server boots, all three tools (search_restaurants, get_restaurant, auth_status) work over stdio, and orchestrator + caching + ranking + tool plumbing are real. The vitest MCP-handshake smoke test passes.\\n\\nResy and OpenTable probes still return stub data behind REZZY_USE_STUB_RESY / REZZY_USE_STUB_OPENTABLE. The Tock probe deliberately errors as \"Phase 3, not implemented\".\\n\\nMost recent source-tree activity ran Apr 30 → May 2: src/commands/seed.ts, scripts/discover-resy.mjs and scripts/verify-opentable-rids.mjs modified May 2; src/probes/resy/ folder mtime May 2 05:31; src/core/search.ts updated May 2 06:21. It reads as mid-Task-4 (platform-listings backfill) with early Resy probe scaffolding underway.\\n\\n**There is no .git/ directory.** Nothing is committed anywhere; the work lives only on disk, so Task 4\\'s actual completion state can only be established by querying the database. This handoff was the sole record of the remaining Phase 1 plan — tasks/ was empty.',\n next_steps: [\n {\n id: 'n1',\n text: 'Before writing any code, inventory what already exists — no git means the DB is the only evidence. Run `npm run dev auth-status`, `SELECT count(*) FROM platform_listings` (target >= 40), and diff src/probes/resy/index.ts against the stub to see how much of Task 2 is already there.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Decide on git initialization, recommended before any further change, and what the initial commit should encompass. Without it there is no rollback, no diff and no branch isolation for the Resy / OpenTable implementations.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Auth is not captured: `rezzy auth-status` will be empty for resy and opentable until `rezzy auth-capture <platform>` is run, and that is required before Tasks 2/3 can produce real data.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'Phase 1 remainder, in order: real Resy probe (ref lgrees/resy-cli) → real OpenTable probe (mobile-api.opentable.com/api/v3/restaurant/availability, ref jonluca/OpenTable-Reservation-Maker) → backfill platform_listings for the 29 seed restaurants using the existing discover/verify scripts, flagging likely Tock-only venues (Beckon, Bruto, Margot, Kizaki) → flip both stub toggles to false and run the end-to-end real-data smoke test in Claude Desktop. Proposed as DR-1..DR-7.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: \"Run `npm run typecheck` before declaring any task done, per the repo's CLAUDE.md.\",\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'health',\n ended: '2026-07-27T22:59:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-07-27\\n\\nScope decided and the first two builds shipped. `/Users/hjewkes/Documents/health` is live: TypeScript, 35 tests passing, typecheck and production build clean, three commits on branch `feat/macro-calculator` — unmerged, nothing pushed, there is no remote.\\n\\n**Macro planner** (src/core/) — a pure calculation chain ported from the weight-loss spreadsheet: composition → Katch-McArdle BMR → TDEE → deficit → macro split → projection, composed by buildPlan(). A golden test reproduces the spreadsheet's figures exactly. The projection bug is fixed: the sheet extrapolated a fixed daily loss, but the target is a percentage of current bodyweight, so the curve is exponential — the estimate moves from 110 days (Nov 14) to 117 days (Nov 21), and both are shown in the minimal web UI in src/ui/.\\n\\n**Instacart ingest** (src/ingest/instacart/) — parses order receipts out of Gmail into structured orders, plus a merge step repairing email-truncated item lists from the web receipt. 33 orders parsed; the last 20 Costco orders at full coverage (287 items, 2025-05 → 2026-07, $5,243).\\n\\nNext session was to be meal planning.\",\n next_steps: [\n {\n id: 'n1',\n text: 'Meal planning: build plans against the macro targets from buildPlan() using the real Costco basket in data/instacart-orders.json rather than invented recipes, and emit a shopping list. No task exists for this — H-4 only covers turning a list into an Instacart cart.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Consider cost-per-gram-of-protein, now that both price and purchase data exist in the same place.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Merge feat/macro-calculator once the user has reviewed it — three commits, nothing pushed, no remote exists.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: \"Unresolved and cosmetic: the spreadsheet's BMI cell (33.57) disagrees with its own Ideal BMI Weight cell (223.1 lb, which pins height at 83.5 in and implies BMI 32.52). No calorie or macro target uses height, so nothing is blocked, but the true height is still unconfirmed.\",\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'herald',\n ended: '2026-05-29T05:59:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-05-28 (superseded — recorded for the record)\\n\\nDesign phase complete, build started. S1 done (H-1): src restructured into core/drivers/transports, 186 tests green, committed on `feat/harness-pivot` @ 896d3bb. Working tree clean, nothing pushed. The plan at the time was S2 (H-2) quarantine the backlog, then S3 (H-3) the Plugin/BrainDriver/Transport contract, then S4/M0 the Slack echo round-trip on the phone.\\n\\n**Almost all of this is now stale.** H-2 and H-3 both closed in the 2026-05-29 and 2026-06-02 sessions. Nothing has happened in this initiative since 2026-06-02, roughly eight weeks.\\n\\nThe one item that survived — and the reason this record exists — is a blocker containing a time-sensitive deadline that has silently expired. It is recorded below as ABANDONED rather than migrated as live work, so a future session does not chase it.\\n\\nDecisions remain locked in the brief: library-first TS harness; service-owns-loop with a swappable BrainDriver; ChannelDriver as the v0 default with SdkDriver for isolated/triage workloads; Slack v0 behind a transport adapter; diet coach as the first vertical.',\n next_steps: [\n {\n id: 'n1',\n text: 'The \"~June 8 Agent SDK credit (June 15 billing change)\" window lapsed. The credit is gone; any cost assumption predating the June 15 billing change needs rechecking before the SdkDriver metered path is priced.',\n kind: 'prose',\n abandoned: {\n note: 'The Agent SDK credit claim window (~June 8, ahead of the June 15 billing change) lapsed roughly seven weeks before the migration; the credit is gone. Recorded as abandoned rather than migrated live so no future session chases it. The surviving follow-up — rechecking cost assumptions that predate the June 15 billing change before pricing the SdkDriver metered path — belongs to the brief, not the ledger.',\n },\n },\n ],\n },\n {\n slug: 'home-assistant',\n ended: '2026-05-13T00:00:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-05-13\\n\\n`main` last commit `7758913` (\"fix: remove dead src.core.config_utils import breaking all MCP tools\"). Working tree dirty: three ha_config/ files modified (automations_dir/automations.yaml, configuration.yaml, scenes_lighting.yaml) plus untracked .brain/, .claude/settings.local.json, ha_config/custom_templates/, ha_config/dashboards/home_overview.yaml and tools/screenshot.py.\\n\\nThe initiative is on the back burner — no active coding push — but the brain PM `HOME` instance has 31 pending tasks across 8 workstreams (21 done), so there is plenty queued when attention returns. The most recent work landed the MCP server, SSH config-sync tooling, legacy src/ cleanup, and a Jinja2/stale-entity sweep.\\n\\n⚠️ That dirty-tree file list is now roughly 2.5 months old and this is a live home-automation system, so treat it as a hint, not a fact. The handoff\\'s own guard applies: run `make config-status` and `make config-diff` before deciding anything — live /config/ is authoritative.\\n\\nNote: HOME-* ids below live in the external brain PM instance, not in this initiative\\'s tasks/, which is empty.',\n next_steps: [\n {\n id: 'n1',\n text: 'Reconcile the uncommitted ha_config/ edits: run `make config-status`, decide the pull-or-push direction, then commit the local-side delta. Never push or pull blindly — live /config/ is authoritative.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Decide the fate of src/ (brain PM HOME-07.17): only config.py and exceptions.py remain. This gates the tools/ test work so the tests target the right layer, and HOME-07.14 / HOME-07.15 are duplicates — close one.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Triage the HOME-08 design backlog — pick one or two of climate (08.05), presence/away (08.06), goodnight/morning (08.07) as the next active design thread.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'Two small unblockers worth knocking out together: HOME-03.05 add-on updates and HOME-04.01 DHCP reservation for the PowerView hub.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'HOME-03.01 Roborock re-auth is blocked on a UI action — it must be done from Settings → Devices & Services and cannot be scripted.',\n kind: 'prose',\n },\n {\n id: 'n6',\n text: 'Opportunistic: HOME-09.03, archive the three stale debug dashboards next time dashboards are open.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'logan',\n ended: '2026-07-17T17:59:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-07-17\\n\\nA full session took the backyard treehouse / play structure from open question to a ready-to-submit HOA packet. It settled as an open-sided children\\'s play structure (not an enclosed playhouse) in the south side yard, which keeps it a Greenwood Village 5 ft-setback, permit-exempt \"playground equipment\" (Lot 28 = R-1.0 PUD, per Ordinance 03/2021). Analysis lives in docs/treehouse-*; the assembled packet is in property-records/hoa/\"ACC Submission - Play Structure/\". Only the neighbour signature is left before it goes to the new ACC members. The owner is not pulling a city building permit, and is building to code regardless. The project folder moved to ~/projects/logan, out of the TCC-blocked ~/Documents.\\n\\nFrom a tooling standpoint this initiative is on the back burner: the folder is maintained by hand, not by any pipeline. Active construction is real — the kitchen contract is signed at $93,346.85, trenching began 2026-04-22, junipers were scheduled the same day. The docs/ knowledge base was last edited 2026-04-18 and is behind reality.\\n\\nSeveral vendor decisions are sitting undecided in bids/ with no record of a call either way.',\n next_steps: [\n {\n id: 'n1',\n text: \"Submit the treehouse ACC packet: print property-records/hoa/'ACC Submission - Play Structure/', get Deb/Nolan Pratt (5185 S Logan) to sign line 1, then send to ACC members Caitlin Tesoriero and Kathy Martinez. Everything else in the packet is ready.\",\n kind: 'task',\n ref: 'L-1',\n },\n {\n id: 'n2',\n text: \"Chase Wiley/DBS for the electrician's heater breakout (DBS #8635.2) — ceiling-mount vs recessed is a ~$18K swing and the make/model is still unspecified. If it is still missing, request a second bid.\",\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Plumbing quotes QU0543 / QU0545 for the steam shower are still unsigned — sign or decline.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'Finish selections still open: concrete countertop colour (samples were due 2026-04-22) against Sapphire cabinets and the existing brick; the $5,556 countertop allowance — confirm L-shape coverage, cutouts and overage handling; and brick sourcing for the backsplash, where an exact match is not guaranteed and samples need viewing.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'Decide the remaining un-contracted vendors — painting, flooring, Hall Marble stone, all sitting in bids/ with no decision recorded — or explicitly defer them in docs/open-questions.md.',\n kind: 'prose',\n },\n {\n id: 'n6',\n text: 'Refresh docs/open-questions.md against reality post-2026-04-22 (trenching, tree-placement walkthrough, sample reviews). It was last edited 2026-04-18.',\n kind: 'prose',\n },\n {\n id: 'n7',\n text: 'File the 4-29 DBS L3 drawing and the CO #3 bid (synthetic turf, additional trees, steps, timber walls) into docs/bid-analysis.md — check the 2026-07-20 DBS scope/payments sessions first, they may have covered part of this.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'relay',\n // Refreshed TWICE on 2026-07-29 (AW-65). First pass moved this off\n // 16:19:00Z, which predated even its covering session's own `ended`. A\n // further session then ran and rewrote the handoff again at 19:27Z —\n // later than either of that day's session ends — to record the\n // R-3-step-2 branch state, R-49/R-50 being filed and R-24 closing. The\n // loops below were not all true until that edit, so `ended` follows it.\n ended: '2026-07-29T19:27:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-07-29\\n\\n**R-3 step 2 is built and fully verified, and it is sitting on an unmerged branch.** Dispatch exists in the schema and the storage seam: an item is handed to an agent by setting its GTD context to `agent`, and a runner claims it by appending to one append-only `events` log. No daemon exists yet, nothing executes, nothing is deployed. 386 tests across 17 files, `tsc` clean, `make check` exit 0, and the compatibility suite at 66/66 local AND hosted — local/hosted divergence still measures zero, now across 66 constructs.\\n\\n**Production is untouched by this work:** 24 objects, no `events` table, migration 0008 applied to LOCAL D1 only. Production still holds the 111 imported items plus the two test captures (ids 113, 114).\\n\\nEarlier context that still holds: R-33 is decided and R-38 shipped it — type-specific attributes live in a registry-validated `meta` column enforced by database triggers that both writer doors inherit. Both MCP surfaces are deployed; production is Worker version `119a7987`.\\n\\nThe model in four lines: a narrow typed core with type-specific facets in one meta JSON column; `type_schemas` is a TABLE, so registering a kind or attribute is an INSERT; BEFORE INSERT/UPDATE triggers enforce registered keys and allowed values, so both doors and a hand-run `wrangler d1 execute` all obey; hot attributes promote to generated columns, derived so they cannot drift.\\n\\nThe session that produced this handoff left R-23 Part B half-answered — OAuth completed but the six admin verbs never attached. R-23, R-27 and R-36 all closed later the same day, so the headline NEXT ACTION and the first two operator-only items are no longer live and are excluded below.\\n\\n**READ THIS BEFORE TRUSTING ANY CLOSED SECURITY TICKET. R-20 closed by RE-SCOPE, not by resolving the risk.** The mascot-madness token still reaches relay's D1 and Worker; the blast radius is unchanged. **R-44 (account separation) is the real precondition**, and the handoff names it as the one thing an operator might want to do first, because the cost grows with every new surface pointed at the hostname.\\n\\n_Refreshed twice on 2026-07-29 (AW-65); this reflects the handoff as rewritten at 19:27Z, after R-3 step 2 was verified, R-49/R-50 were filed and R-24 closed._\",\n next_steps: [\n {\n id: 'n1',\n text: '`disabledMcpServers: [\"claude.ai Relay\"]` is currently SET for this project in ~/.claude.json, left over from probe 4. Claude Code sessions have no relay tools until it is removed.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'R-32 is the highest-leverage thing available: the 1-bit sign sketch takes recall@10 from 55.8% to 96.6% with no schema change, is orthogonal to everything else, and is the candidate generator R-40 needs. Do it first.',\n kind: 'task',\n ref: 'R-32',\n },\n {\n id: 'n3',\n text: \"R-40 second — reference content as the second real kind. `note` exists but is a task in disguise (0005 gave it the identical six attributes), so R-33's central ~0-shared-attributes claim is still untested. 'Look up' is a capability relay does not have at all: list_items filters, it does not search.\",\n kind: 'task',\n ref: 'R-40',\n },\n {\n id: 'n4',\n text: \"R-39 third — registry-driven MCP tools, the fast-follow that R-40 exercises. This is also what makes R-33's no-deploy property real rather than half-real.\",\n kind: 'task',\n ref: 'R-39',\n },\n {\n id: 'n5',\n text: 'R-35 (entities) is deliberately sequenced AFTER R-40 by the operator — do not pull it forward.',\n kind: 'task',\n ref: 'R-35',\n },\n {\n id: 'n6',\n text: 'R-37 is about an hour and now covers TWO detectors sequenced together — the index-drift check plus the new R-41 schema-drift check. It is the deciding evidence for the one genuine unfixable-on-D1 defect, and index drift has never been observed or ruled out. Take it any time.',\n kind: 'task',\n ref: 'R-37',\n },\n {\n id: 'n7',\n text: 'R-34 (R2 blob tier) is gated on R-36 (logan data-handling), which has closed — so it is unblocked. It also inherits the hard preconditions C1/C2 from docs/logan-corpus-decision.md §5; check those before starting. (It was never gated on R-20, despite an earlier note conflating the two.)',\n kind: 'task',\n ref: 'R-34',\n },\n {\n id: 'n8',\n text: \"R-28 is operator-only and cannot be delegated: capture 'Fix list_items paging' from the phone and listen to whether the readback says 'list underscore items', 'list items' or 'listitems'. The three mean different things — record which.\",\n kind: 'task',\n ref: 'R-28',\n },\n // Was `kind: task, ref: R-24`. R-24 closed 2026-07-29 (66/66 hosted),\n // so the ref would have auto-resolved this loop the moment the\n // migration ran and deleted it before anyone read it. What survives\n // R-24's closure is the RECURRING obligation, which no task carries —\n // hence prose.\n {\n id: 'n9',\n text: 'Recurring, and owned by nobody: `make check-compat-remote` is operator-only (it refuses a non-TTY by design) and must be re-run after ANY change to the SQL constructs relay depends on. The one-off run closed as R-24 on 2026-07-29 at 66/66 hosted, with local/hosted divergence still measuring zero — but the obligation did not close with it.',\n kind: 'prose',\n },\n {\n id: 'n10',\n text: 'Voice `list_items` and `complete_item` have still never run from a phone — only capture has. No task covers this verification gap.',\n kind: 'prose',\n },\n // Was standalone prose reading \"delete 113/114 when convenient\". The\n // handoff records that this was pulled into task R-47 precisely\n // because \"when convenient\" survived two handoffs unactioned, and\n // R-47 also covers closing/annotating the already-built #104/#106.\n {\n id: 'n11',\n text: 'R-47 housekeeping, filed because \"delete when convenient\" survived two handoffs unactioned: delete production test captures ids 113 and 114, AND close/annotate items #104 and #106, which are already built.',\n kind: 'task',\n ref: 'R-47',\n },\n {\n id: 'n12',\n text: \"R-44 (account separation) is the one thing an operator might want to do FIRST. R-20 closed by re-scope rather than by resolving the risk — the mascot-madness token still reaches relay's D1 and Worker — and R-44 is the real precondition, now also gating step 6 specifically. Cost grows with every new surface pointed at the hostname, so deferring it gets more expensive, not less.\",\n kind: 'task',\n ref: 'R-44',\n },\n // n13-n15 added in the second 2026-07-29 refresh pass. A further\n // session rewrote this handoff at 19:27Z, and the headline it left —\n // an entire built-and-verified feature waiting on a merge decision —\n // was covered by none of the twelve loops above.\n //\n // Prose, not `kind: pr`: there is no PR, only an unpushed branch, and\n // a `kind: pr` loop could never auto-resolve anyway.\n {\n id: 'n13',\n text: 'DECIDE WHETHER R-3 STEP 2 LANDS. `feat/agent-dispatch-events` holds four commits, NOT merged and NOT pushed: agent as a GTD context (not a kind or assignee), an append-only `events` log with an atomic claim, both design docs corrected, and the claim verified on hosted D1 at 66/66. Nothing is mid-flight and nothing needs a restart — the branch is green and self-consistent, so the only open question is merge/push/deploy. Migration 0008 is applied to LOCAL D1 only; production is untouched. One live consequence to weigh: voice cannot set context=agent until R-49 lands.',\n kind: 'prose',\n },\n {\n id: 'n14',\n text: 'R-49 — a dedicated voice `dispatch_to_agent` tool, sequenced to land with R-3 step 3. This is what restores the ability to hand an item to an agent by voice once step 2 makes `agent` a context.',\n kind: 'task',\n ref: 'R-49',\n },\n {\n id: 'n15',\n text: 'R-50 — scope note on R-39: the registry drives ATTRIBUTES, never the verb set. Worth reading before starting R-39 so the no-deploy property does not get overstated.',\n kind: 'task',\n ref: 'R-50',\n },\n ],\n },\n {\n slug: 'taxes',\n ended: '2026-05-12T00:00:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-05-12\\n\\nThe 2025 return is on extension. The bulk of documents were uploaded to SafeSend in early April 2026 ahead of Carolynn's Apr 10 cutoff; extension paperwork came back from her on Apr 15 (in 2025/extension-from-carolynn/) and the federal, CO and AZ extension payments have been made.\\n\\nAwaiting CPA work-up. Nothing was required from the owner at the time unless a still-needed document surfaced.\\n\\nThe extended filing deadline is Oct 2026, so the actions below are still live — but this record is about 2.5 months old and Carolynn may have moved the draft along since. Confirm status with her before re-doing any of it.\\n\\nThe open-items list (Walmart 1099-DIV, missed 2025 quarterlies, Colorado 1099-G, the underpayment-penalty estimate, the CP503 notice and the E-Trade cost-basis flag) is already restated near-verbatim in the brief's Open questions / risks section and is not duplicated here.\",\n next_steps: [\n {\n id: 'n1',\n text: 'Log into Computershare and pull the Walmart 1099-DIV, or screenshot account-no-activity if the shares were already divested, then tell Carolynn to estimate.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Pull IRS / CO / OR payment-history screenshots showing 2025 calendar-year activity into 2025/estimated-payments/, and confirm Carolynn has them. No 2025 quarterlies were made (federal $14K/qtr, CO $460/qtr); what the portals do show is the small nanny-payroll federal payments plus the April extension payments already saved.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Resolve the IRS CP503 notice (2024 balance, $19,499) sitting in 2025/estimated-payments/ — call the IRS or check the transcript — and file the confirmation.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'When Carolynn returns the draft return, review it against 2025/CHECKLIST.md totals before signing, and verify the final return uses the E-Trade Stock Plan Supplement basis rather than the 1099-B noncovered figures.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'After filing, mirror the final return PDF into 2025/ and update INDEX.md with the filing date and delivery method.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'titan-platform',\n ended: '2026-07-13T23:16:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-07-13\\n\\nAudit complete, round-2 research complete, architecture not yet started. No code written, nothing extracted — this initiative is audit + design only so far.\\n\\nRound 1 audited all sibling agentic projects via parallel agents, producing six cited docs in sources/ plus the extraction map in sources/00-index.md. The conclusion: the platform is mostly an EXTRACTION problem. Nearly every tier already exists somewhere — registry/daemon from active-work; embed, agent, retrieval, sessions, memory and pm from brain; store and code-graph from codewatch; dashboard-kit from titan-design, already shared. `cluster` and `locator` are the only genuinely-new tier-0 pieces, and codewatch is the monorepo template to copy.\\n\\nRound 2 closed the pre-architecture gaps and all six results are persisted as sources/research-*.md. Its most consequential correction: the brain spike is a DESIGN, not a built or adopted platform — only agent-submission was built, it is untracked, Restate was never integrated, and there was no adoption decision. The earlier \"decision memo\" claim was wrong and is now corrected everywhere.\\n\\nTP-1..TP-15 have since been filed, so the handoff\\'s \"create TP-* tasks\" action is already done. The session-miner build (active-work AW-23/27/28) proceeds in parallel and is the first likely consumer of the extracted store / session-read / registry packages.',\n next_steps: [\n {\n id: 'n1',\n text: 'The architecture phase is awaiting owner go-ahead. With the full picture in hand, draft the concrete @titan-design/* package DAG plus extraction sequencing before starting any TP-* build.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Decide monorepo vs multirepo, and settle the npm-scope inconsistency (@codewatch/* vs @titan-design/*). Both are open and recorded nowhere else.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: \"Settle the workflow-runtime approach: a light scheduler for the miner (herald patterns) now, defer the durable engine to tier-2/product, and when choosing prefer MIT/Apache (DBOS, Hatchet, Trigger) over Restate's BUSL. The SDK is a leaf, not a substrate.\",\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'Optional before starting architecture: pull the final agent-sdk report.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'TP-10 carries two unresolved decisions worth naming: @titan-design/react-ui is real and published but has a single stale consumer (codewatch@0.2.7) and brain never adopted it — it needs a generic-vs-Voltras split AND an RN-Web platform decision.',\n kind: 'task',\n ref: 'TP-10',\n },\n ],\n },\n {\n slug: 'voltras-workspace',\n // Refreshed TWICE on 2026-07-29 (AW-65). The first pass moved this off\n // 17:29:00Z, which matched only a session-close doc while an\n // undocumented session had run afterwards. A second large session then\n // ran the same day — nine PRs across three repos, three npm releases,\n // VW-101 and VW-106 closed, VMCP-01.72 part (a) merged — so this now\n // follows that session's recorded end.\n ended: '2026-07-29T19:15:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-07-29 (second session)\\n\\nSix agents, **nine PRs merged across three repos, plus three npm releases**. `voltra-playground` main `e4a5bd1`, `voltras-mcp` main `1f010d9`, `voltra-node-sdk` main `a53804e` with tags v0.12.1/2/3 and npm at `@voltras/node-sdk@0.12.3`. Every repo clean, nothing unpushed, no worktrees left behind — but agents leave an UNTRACKED `.agent-notes/` in `voltras-mcp` that is not gitignored, so their reports do not survive a clean.\\n\\n**`VW-101` is fully closed, and it took THREE releases — that is the lesson.** 0.12.1 made `voltra-manager.ts`'s requires opaque to Metro; gates were green and Metro's own `collectDependencies` was clean over that file, **and it still did not work**, because `index.ts` value-exports `createBLEAdapter` from the adapters BARREL, which statically re-exports `NobleHost` — a second door nobody looked for. Two instrument lessons worth keeping: the 90-second check that would have caught it first try is bundling the real app with the workaround REMOVED (now the acceptance test: iOS bundles, 2125 modules, `@stoprocent/noble` 0); and read the sourcemap `sources` array, never grep the Hermes `.hbc`, which returned 0 both for the forbidden strings and for strings that had to be there — a blind instrument that reads as a pass.\\n\\n**`VMCP-01.72` part (a) is merged** (`1f010d9`, #220): the eight per-exercise read paths now scope by the set's own `exercise_id`. Part (b) is `VW-114`.\\n\\nEarlier the same day: `LiveFatiguePanel` wiring landed, and `VW-106` is done: `coordination/` is deleted, its 472 files reorganized into this initiative's `sources/` tree, and every path reference across six repos, brain, the skills and these docs rewritten. Snapshot at `~/projects/_archive/voltras-coordination-snapshot-2026-07-29.tar.gz`. **handoff.md is now the session surface — dated `HANDOFF-*.md` / `NEXT-SESSION-*.md` docs are retired and must not be recreated.**\\n\\nThe five-branch stack and `VW-105` have since landed. Earlier context that still holds: @titan-design/react-ui@0.12.0 is live on npm and voltras-mcp main is on it (7094aa1, PR #213); VW-99 passed all four rows on the wall. The diverging dual stage is built and merged (VMCP-04.05, voltras-mcp #214, main 3382496) — tempo and the exertion alert are shared rather than per-limb, and sets/reps/load stays on the page-level ExerciseHeader. The SPA works end to end on real hardware single-arm; the dual-arm view is still behind `?variant=live-dual`.\\n\\nThe 07-27 postmortem is why this file was rewritten: handoff.md was 12 days stale and the brief's in-flight efforts 22 days stale, bootstrap's priority ordering pointed at VW-68 (since demoted to p30), and the file titled \\\"start here\\\" was never opened. That cost a full session.\\n\\n_Refreshed twice on 2026-07-29 (AW-65). Only headline next actions are migrated as loops; the rest of the open ticket table stays in `tasks/` by decision, to keep the ledger readable._\",\n next_steps: [\n // n1 has now been re-pointed twice. Originally \"wire LiveFatiguePanel\"\n // (ref VW-76), which was already done while VW-76.yml still read\n // `status: open` — so it would NOT have auto-resolved and would have\n // migrated live. The first refresh replaced it with VMCP-01.72 as\n // prose, because VMCP-* tickets live in voltras-mcp and a ref would\n // have dangled. Part (a) has since merged (1f010d9, #220), and the\n // remainder now HAS a local task — VW-114, priority 1, open — so this\n // is finally a real task ref.\n {\n id: 'n1',\n // Text must not restate its own ref — the bootstrap label already\n // supplies it, and restating renders it twice (AW-71).\n text: \"FIRST — VMCP-01.72 part (b): implement `session.set_exercise` so one workout can hold multiple exercises without fragmenting across session rows. Part (a) is merged (1f010d9, #220): the eight per-exercise read paths now scope by the set's own `exercise_id`. Both user decisions on shape are recorded on the ticket. The original defect: a session's exercise was write-once at session.start and set.start took no exercise argument, so advancing exercises required session.end → session.start.\",\n kind: 'task',\n ref: 'VW-114',\n },\n // Added in the second 2026-07-29 pass. Prose because VMCP-* tickets\n // are tracked in voltras-mcp, not this initiative's `tasks/`.\n // Admitted past the narrow-entry policy because it is a fresh\n // high-severity regression caused BY the merges that just landed —\n // exactly what a headline-only ledger should surface.\n {\n id: 'n2b',\n text: \"REGRESSION from today's merges: VMCP-04.15 (high) — the dual REST stage renders COMPLETELY BLANK, body empty at 0:02 and 0:05. Dual telemetry is now the DEFAULT view for any bilateral rig, so every real two-limb session hits this.\",\n kind: 'prose',\n },\n // Old n3 (decide the fate of mapStoreToDualModel) dropped: the handoff\n // records \"RESOLVED 2026-07-28 — mapStoreToDualModel is DELETED with\n // its tests\", along with five downstream functions.\n {\n id: 'n2',\n text: \"The 07-27 postmortem's standing guard — 'read the newest coordination/NEXT-SESSION-*.md before trusting bootstrap's priority ordering' — is INVALIDATED and needs a replacement. VW-106 deleted coordination/ and retired dated session-close docs; handoff.md is the session surface now. The underlying failure the guard existed for is unfixed: priority ordering is stale by default, and two things the operator cared about had no VW-level task at all. Decide what enforces that now.\",\n kind: 'prose',\n },\n {\n id: 'n4',\n text: \"VW-95 demo video is no longer blocked — the titan publish was the gate and the SPA is now on 0.12.0, so a camera sees the current UI. What remains is content, not plumbing: no script and no shot list exist. Before filming with cues on, decide VMCP-05.01 (critical, safety): the mic is deaf during TTS/cues, including the 'stop' phrase.\",\n kind: 'task',\n ref: 'VW-95',\n },\n {\n id: 'n5',\n text: 'VW-92 experience_tier is still the cross-cutting blocker. The SCHEMA half is done — training_profile with a declared_tier column shipped in the v9 wave (sqlite-store.ts:369-371) — but the derivation logic and any reader or writer are missing: empty DDL, zero call sites. The design exists in coordination/tier-signal-design.md with no code written. B05/B06/B07/B14/B25/B31 all branch on tier.',\n kind: 'task',\n ref: 'VW-92',\n },\n {\n id: 'n6',\n text: 'VW-96 storage Wave 3 is not started, deliberately: training_profile and exercise_baselines are empty DDL with zero call sites. The WA audit rates baselines the single highest-leverage addition (14 downstream items), and it is a prerequisite for the RP tier work.',\n kind: 'task',\n ref: 'VW-96',\n },\n {\n id: 'n7',\n text: 'RP build order, starting with this one: B15 drift guard is the foundation → B56/B57 baselines → VW-91 (B04 two-session underperformance/MRV detector, rated highest value: high impact, small effort, buildable now, zero new instrumentation) → B16 → B09/B14. Also real and stalled: VMCP-02.25, plan_suggest_progression is VBT-blind and recommends +5 lb after near-failure sets.',\n kind: 'task',\n ref: 'VW-90',\n },\n {\n id: 'n8',\n text: \"Unowned and will fall through the cracks: VMCP-05.19 position→metres conversion — hard serialization, nobody bumps WA to 2.0.0 before this is written or position_units starts lying. Also unowned: the WA 2.0.0 consumer migration, drift-tolerance fit (needs no hardware), and 'what is a setup?' (setup_id / exercise_setups exist on main and are empty).\",\n kind: 'prose',\n },\n {\n id: 'n9',\n text: \"The bench sitting is the common unblocker. Run all FOUR checklists — they do NOT supersede each other, and two were written the same evening without referencing each other, so 'newest wins' silently drops a gate: validation-runbooks/BENCH-2026-07-26-consolidated.md, the two BENCH-ADDENDUM sweeps, and validation-runbooks/2026-07-27-vw68-write-lease-hardware-bench.md (added 07-27). Order: Q1 chains direction (frees the stuck WA 2.0.0 publish) → isometric calibration VMCP-02.82 (5 min) → voice/deaf-window → v9 capture run → rep-count and peak-power → guided-load wedge LAST, it may need a power cycle. The titan visual gate is done (VW-85, VW-99) — do not re-run it.\",\n kind: 'prose',\n },\n {\n id: 'n10',\n text: '⚠️ The live DB is at v8 and code on main is v9; the next MCP restart migrates it. Back up first — it is a one-way door and a v8 build cannot reopen a v9 file.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'youtube',\n ended: '2026-07-27T00:00:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-07-27\\n\\nThe extractor is stable and did its job — 84 RP University lectures (~267K words) plus 22 others under sources/out/. Tool-level tasks Y-1/Y-2/Y-3 are unchanged and low priority. The active work is now downstream of the transcripts, not in the tool.\\n\\nThe last working session (2026-07-26, ~3h, 20 agents, 6 waves) started as \"mine the RP transcripts into brain\" and became a full foundation audit that redesigned the Voltras data layer. Design complete, zero code written — deliberately, because each audit kept finding the wanted features sat on a foundation that could not support them correctly. That ratio should now flip to building.\\n\\nDone and durable: the knowledge base is LIVE (386 notes in the voltras-workspace brain instance, all 84 lectures, 2,298 graph edges, 7 retrieval probes passing, entry point rp-cross-cutting-synthesis); a 60-item scored backlog; and ten design/audit docs.\\n\\nThe MVS has since shipped — voltras-mcp main is at SCHEMA_VERSION = 9 and the putSet INSERT OR REPLACE landmine is defused, so the v5-collision and unrecoverable-data warnings that used to sit here are both resolved. Six backlog items were filed as VW-89..VW-94 in voltras-workspace; the remaining ~50 stay in the backlog doc rather than becoming tickets nobody can start.',\n next_steps: [\n {\n id: 'n1',\n text: \"NEXT is hardware, not code: not one capture field has been seen populating from real hardware — everything was verified against mock adapters and DB copies. Run coordination/BENCH-CHECKLIST-v7-capture-and-open-questions.md alongside validation-runbooks/BENCH-2026-07-26-consolidated.md; NEITHER supersedes the other, and 'newest wins' silently drops the titan release gate and the voice deaf-window safety measurement. Back up the DB first — v9 is a one-way door.\",\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Four decisions are blocked on measurements only the wall can give, one of which (Q1 chains direction) is holding a workout-analytics 2.0.0 npm publish.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Plan Y-10, Y-11 and Y-12 as ONE schema-and-capture wave — they keep landing on the same tables from different directions.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'Operator decision: the weight_lbs = 0 backfill. Recommendation is NULLIF, with the reasoning in the build handoff; six more decisions sit in migration plan §7.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'Operator decisions still open after the 07-26 pass: the diet-phase tag, the B42 legal review, and ratifying performance-gated deloads. (Settled and not open: advisory-only for stop-set/deload, multi-user now, experiment waits for capture, validate the higher sample rate.)',\n kind: 'prose',\n },\n {\n id: 'n6',\n text: 'The program-level phase plan — sizing phases 1–4 the way phase 0 was sized — was offered but never started. It is what makes the milestone-timing question answerable.',\n kind: 'prose',\n },\n ],\n },\n ],\n};\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { SessionFrontmatterSchema, type SessionFrontmatter } from '../schemas/session.js';\nimport { readRawFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\n\n/**\n * Two session files in the live data predate the schema and fail it. v3 turns\n * unreadable session files into a standing `doctor` warning, so unless these\n * are repaired in the same pass the new integrity check starts life crying\n * wolf — and a permanent false positive masks the real reports it exists for.\n *\n * They are addressed by exact path rather than by a general rule: \"any session\n * with an out-of-enum `track` becomes adhoc\" would silently rewrite files the\n * operator has not looked at. Each repair re-checks its precondition, so a\n * file already fixed by hand is left alone and a re-run is a no-op.\n */\n\nexport type RepairAction = 'retrack' | 'relocate' | 'skip';\n\nexport interface RepairPlan {\n action: RepairAction;\n /** Path relative to the active root. */\n file: string;\n target?: string;\n detail: string;\n /** Validated replacement content, populated by `retrack` plans only. */\n repaired?: { frontmatter: SessionFrontmatter; body: string };\n}\n\ninterface KnownRepair {\n file: string;\n kind: 'retrack' | 'relocate';\n target?: string;\n why: string;\n}\n\nexport const KNOWN_REPAIRS: KnownRepair[] = [\n {\n file: path.join('audiobook', 'sessions', '2026-07-23-0549-2026-07-26-book1-m4b-packaging.md'),\n kind: 'retrack',\n why: \"track is a branch name ('feat/tts-quality'), not one of canonical|sidecar|adhoc\",\n },\n {\n file: path.join('voltras-workspace', 'sessions', 'ARCHIVED-handoff-through-2026-07-15.md'),\n kind: 'relocate',\n target: path.join('voltras-workspace', 'sources', 'ARCHIVED-handoff-through-2026-07-15.md'),\n why: 'not a session file — a hand-archived handoff parked in sessions/',\n },\n];\n\nconst TRACKS = new Set(['canonical', 'sidecar', 'adhoc']);\n\n/**\n * Brief-level repairs, applied before the `task_seq` backfill so a brief that\n * currently fails validation can still be rewritten.\n *\n * `health` carries `state: active`, which has never been in the enum, so every\n * validating writer refuses it — `active-work touch health` errors today. The\n * operator's chosen resolution is `focused` at rank 11 (1–10 are taken).\n * Guarded by the exact broken value, so a hand-fix beforehand wins.\n */\nconst BRIEF_REPAIRS: Record<\n string,\n (fm: Record<string, unknown>) => { patch: Record<string, unknown>; detail: string } | null\n> = {\n health(fm) {\n if (fm.state !== 'active') return null;\n return {\n patch: { state: 'focused', ...(fm.rank === undefined ? { rank: 11 } : {}) },\n detail: \"state 'active' (not in the enum) -> 'focused', rank 11\",\n };\n },\n};\n\n/**\n * Apply any known repair for `slug` to raw brief frontmatter. Returns the\n * frontmatter unchanged (and an empty `applied`) when nothing matches.\n */\nexport function repairBriefFrontmatter(\n slug: string,\n frontmatter: Record<string, unknown>,\n): { frontmatter: Record<string, unknown>; applied: string[] } {\n const repair = BRIEF_REPAIRS[slug]?.(frontmatter);\n if (repair == null) return { frontmatter, applied: [] };\n return {\n frontmatter: { ...frontmatter, ...repair.patch },\n applied: [repair.detail],\n };\n}\n\n/**\n * An out-of-enum `track` is the only thing this repair is allowed to fix, so\n * the repaired frontmatter is validated here, in phase one. A file that is\n * still invalid for some *other* reason is reported and left alone rather\n * than throwing half way through the write phase.\n */\nasync function planRetrack(fullPath: string, repair: KnownRepair): Promise<RepairPlan> {\n let raw: { frontmatter: Record<string, unknown>; body: string };\n try {\n raw = await readRawFrontmatter(fullPath);\n } catch {\n return { action: 'skip', file: repair.file, detail: 'unreadable; left for the operator' };\n }\n const track = raw.frontmatter.track;\n if (typeof track === 'string' && TRACKS.has(track)) {\n return { action: 'skip', file: repair.file, detail: `track already ${track}` };\n }\n const parsed = SessionFrontmatterSchema.safeParse({ ...raw.frontmatter, track: 'adhoc' });\n if (!parsed.success) {\n return {\n action: 'skip',\n file: repair.file,\n detail: `still invalid after retrack; left for the operator: ${parsed.error.message}`,\n };\n }\n return {\n action: 'retrack',\n file: repair.file,\n detail: `track ${JSON.stringify(track)} -> \"adhoc\" (${repair.why})`,\n repaired: { frontmatter: parsed.data, body: raw.body },\n };\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function planRepairs(activeRoot: string): Promise<RepairPlan[]> {\n const plans: RepairPlan[] = [];\n for (const repair of KNOWN_REPAIRS) {\n const fullPath = path.join(activeRoot, repair.file);\n if (!(await exists(fullPath))) {\n plans.push({ action: 'skip', file: repair.file, detail: 'already absent' });\n continue;\n }\n if (repair.kind === 'retrack') {\n plans.push(await planRetrack(fullPath, repair));\n continue;\n }\n const target = repair.target!;\n if (await exists(path.join(activeRoot, target))) {\n plans.push({\n action: 'skip',\n file: repair.file,\n target,\n detail: 'target already occupied; left for the operator',\n });\n continue;\n }\n plans.push({ action: 'relocate', file: repair.file, target, detail: repair.why });\n }\n return plans;\n}\n\nexport async function applyRepair(activeRoot: string, plan: RepairPlan): Promise<void> {\n const fullPath = path.join(activeRoot, plan.file);\n if (plan.action === 'retrack' && plan.repaired !== undefined) {\n await writeFrontmatter(\n fullPath,\n plan.repaired.frontmatter,\n plan.repaired.body,\n SessionFrontmatterSchema,\n );\n return;\n }\n if (plan.action === 'relocate') {\n const target = path.join(activeRoot, plan.target!);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.rename(fullPath, target);\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport matter from 'gray-matter';\nimport YAML from 'yaml';\nimport { ArtifactsSchema, type WorktreeEntry } from '../schemas/artifacts.js';\nimport { writeYaml } from '../utils/yaml-io.js';\nimport { atomicWrite } from '../utils/fs-atomic.js';\nimport type { Migration } from './types.js';\n\n/**\n * v3 → v4 (AW-67): move `brief.worktrees` into `artifacts.yml`.\n *\n * A worktree had two homes: a curated map in the brief keyed by label, and the\n * list `wrap` sweeps from git. They now share one list, with `name` marking the\n * entries an operator registered — see `src/schemas/artifacts.ts`.\n *\n * Per initiative:\n * - each `brief.worktrees[label]` becomes an `artifacts.worktrees[]` entry with\n * `name: label` and its `default` flag preserved\n * - a swept entry already at that path is *promoted* in place rather than\n * duplicated, so the pairing survives a wrap that ran before the migration\n * - `repo` is required by the schema and the brief never carried one, so a\n * promoted entry keeps the repo the sweep found and a fresh entry falls back\n * to its own path\n * - `worktrees` is removed from the brief frontmatter\n *\n * Idempotent: a brief with no `worktrees` key is left untouched, and a second\n * run finds nothing to move. Only the frontmatter is rewritten; brief prose is\n * preserved byte-for-byte.\n */\n\ninterface RawBriefWorktree {\n path?: unknown;\n default?: unknown;\n}\n\n/** Same-path comparison without tilde expansion surprises. */\nfunction normalize(value: string): string {\n const expanded = value.startsWith('~')\n ? path.join(process.env.HOME ?? '', value.slice(1))\n : value;\n return path.resolve(expanded);\n}\n\nfunction toEntries(raw: unknown): Array<{ name: string; path: string; default: boolean }> {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return [];\n const out: Array<{ name: string; path: string; default: boolean }> = [];\n for (const [name, value] of Object.entries(raw as Record<string, RawBriefWorktree>)) {\n const wtPath = value?.path;\n if (typeof wtPath !== 'string' || wtPath.length === 0) continue;\n out.push({ name, path: wtPath, default: value?.default === true });\n }\n return out;\n}\n\n/**\n * Merge migrated entries into whatever the sweep already recorded. At most one\n * `default` survives: the brief could only express one, but a promoted entry\n * plus a stale flag elsewhere could otherwise produce two and fail validation.\n */\nfunction mergeWorktrees(\n existing: WorktreeEntry[],\n incoming: Array<{ name: string; path: string; default: boolean }>,\n): WorktreeEntry[] {\n const out = existing.map((entry) => ({ ...entry }));\n for (const wt of incoming) {\n const match = out.find(\n (entry) => entry.name === undefined && normalize(entry.path) === normalize(wt.path),\n );\n const target = match ?? { path: wt.path, repo: wt.path };\n target.name = wt.name;\n if (wt.default) target.default = true;\n else delete target.default;\n if (!match) out.push(target);\n }\n if (out.filter((entry) => entry.default === true).length > 1) {\n let kept = false;\n for (const entry of out) {\n if (entry.default !== true) continue;\n if (kept) delete entry.default;\n kept = true;\n }\n }\n return out;\n}\n\nasync function readArtifacts(file: string): Promise<{\n branches: unknown[];\n stashes: unknown[];\n worktrees: WorktreeEntry[];\n}> {\n try {\n const raw = YAML.parse(await fs.readFile(file, 'utf8')) as Record<string, unknown>;\n return {\n branches: Array.isArray(raw?.branches) ? raw.branches : [],\n stashes: Array.isArray(raw?.stashes) ? raw.stashes : [],\n worktrees: Array.isArray(raw?.worktrees) ? (raw.worktrees as WorktreeEntry[]) : [],\n };\n } catch {\n return { branches: [], stashes: [], worktrees: [] };\n }\n}\n\n/** Returns how many worktrees moved out of this brief. */\nasync function migrateOne(initiativeDir: string): Promise<number> {\n const briefPath = path.join(initiativeDir, 'brief.md');\n let raw: string;\n try {\n raw = await fs.readFile(briefPath, 'utf8');\n } catch {\n return 0;\n }\n const parsed = matter(raw);\n const data = parsed.data as Record<string, unknown>;\n if (!('worktrees' in data)) return 0;\n\n const incoming = toEntries(data.worktrees);\n delete data.worktrees;\n\n if (incoming.length > 0) {\n const artifactsPath = path.join(initiativeDir, 'artifacts.yml');\n const current = await readArtifacts(artifactsPath);\n await writeYaml(\n artifactsPath,\n ArtifactsSchema.parse({\n branches: current.branches,\n stashes: current.stashes,\n worktrees: mergeWorktrees(current.worktrees, incoming),\n }),\n ArtifactsSchema,\n );\n }\n\n // Rewrite the brief frontmatter only; `matter.stringify` preserves the body.\n await atomicWrite(briefPath, matter.stringify(parsed.content, data));\n return incoming.length;\n}\n\nasync function initiativeDirs(activeRoot: string): Promise<string[]> {\n const out: string[] = [];\n let entries;\n try {\n entries = await fs.readdir(activeRoot, { withFileTypes: true });\n } catch {\n return out;\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith('.')) continue;\n const dir = path.join(activeRoot, entry.name);\n try {\n await fs.access(path.join(dir, 'brief.md'));\n out.push(dir);\n } catch {\n // not an initiative\n }\n }\n return out;\n}\n\nexport const v3ToV4Worktrees: Migration = {\n from: 3,\n to: 4,\n description: 'Move brief.worktrees into artifacts.yml as named worktree entries',\n async run(activeRoot: string): Promise<void> {\n const moved: string[] = [];\n for (const dir of await initiativeDirs(activeRoot)) {\n const count = await migrateOne(dir);\n if (count > 0) moved.push(`${path.basename(dir)}\\t${count} worktree(s)`);\n }\n if (moved.length === 0) return;\n const stamp = new Date().toISOString();\n await fs.appendFile(\n path.join(activeRoot, '.migrations.log'),\n moved.map((line) => `${stamp}\\tv3->v4\\t${line}\\n`).join(''),\n 'utf8',\n );\n },\n};\n\nexport default v3ToV4Worktrees;\n","import { ConfigError } from '../errors.js';\nimport type { Migration } from './types.js';\nimport { v1ToV2Artifacts } from './v1-to-v2-artifacts.js';\nimport { v2ToV3OpenLoops } from './v2-to-v3-open-loops.js';\nimport { v3ToV4Worktrees } from './v3-to-v4-worktrees.js';\n\nexport type { Migration } from './types.js';\n\n/**\n * The schema version this build of the code expects.\n *\n * Bump this whenever the on-disk layout changes, and add a matching\n * entry to {@link MIGRATIONS} that walks data from the previous version\n * to the new one.\n */\nexport const CURRENT_VERSION = 4;\n\n/**\n * Migrations registry. Add an entry when bumping {@link CURRENT_VERSION}.\n * Keep entries sorted by `from` ascending.\n *\n * v1 is the baseline. There is intentionally no v0 -> v1 migrator: the\n * plan's fresh-start policy says v0 data is not auto-migrated. Setup\n * stamps `CURRENT_VERSION` on first run; an existing `.schema-version`\n * file containing `0` is treated as an error so the user notices.\n */\nexport const MIGRATIONS: Migration[] = [v1ToV2Artifacts, v2ToV3OpenLoops, v3ToV4Worktrees];\n\n/**\n * Runs every migrator needed to bring `activeRoot` from `fromVersion`\n * to {@link CURRENT_VERSION}. Throws {@link ConfigError} if no\n * contiguous chain exists, or if `fromVersion` is newer than what this\n * build understands.\n *\n * The `migrations` parameter exists for dependency injection in tests;\n * production callers should rely on the default.\n */\nexport async function runMigrations(\n activeRoot: string,\n fromVersion: number,\n migrations: Migration[] = MIGRATIONS,\n): Promise<{ ran: Migration[] }> {\n if (fromVersion === CURRENT_VERSION) {\n return { ran: [] };\n }\n\n if (fromVersion > CURRENT_VERSION) {\n throw new ConfigError(\n `Schema version ${fromVersion} is newer than this build (${CURRENT_VERSION}); ` +\n `downgrade not supported. Upgrade the active-work CLI to match.`,\n );\n }\n\n const ran: Migration[] = [];\n let cursor = fromVersion;\n\n while (cursor < CURRENT_VERSION) {\n const next = migrations.find((m) => m.from === cursor);\n if (!next) {\n throw new ConfigError(\n `No migration registered from schema version ${cursor} to ${CURRENT_VERSION}. ` +\n `Gap at v${cursor} -> v${cursor + 1}.`,\n );\n }\n if (next.to <= next.from) {\n throw new ConfigError(\n `Invalid migration: ${next.description} (from=${next.from}, to=${next.to}) does not advance the version.`,\n );\n }\n await next.run(activeRoot);\n ran.push(next);\n cursor = next.to;\n }\n\n if (cursor !== CURRENT_VERSION) {\n throw new ConfigError(`Migration chain ended at v${cursor}, expected v${CURRENT_VERSION}.`);\n }\n\n return { ran };\n}\n","/**\n * Linux user-level systemd supervision for the active-work daemon.\n *\n * Installs a `~/.config/systemd/user/active-work.service` unit that runs\n * `active-work mcp serve` in the foreground; systemd handles restart on\n * crash. Also enables lingering (`loginctl enable-linger`) so the daemon\n * survives logout and starts at boot. On non-Linux platforms every step here\n * is a no-op.\n */\nimport { promises as fsp } from 'node:fs';\nimport nodePath from 'node:path';\nimport { spawn as nodeSpawn } from 'node:child_process';\nimport os from 'node:os';\nimport type { SetupDeps, StepPaths, StepResult } from './steps.js';\n\nexport const UNIT_NAME = 'active-work.service';\nexport const STEP_SUPERVISION = 'install-supervision';\n\nfunction isLinux(platform: NodeJS.Platform = process.platform): boolean {\n return platform === 'linux';\n}\n\nfunction resolveLocalDeps(deps: SetupDeps): {\n fs: typeof fsp;\n spawn: typeof nodeSpawn;\n paths: StepPaths;\n cliEntry: string;\n platform: NodeJS.Platform;\n} {\n const fs = deps.fs ?? fsp;\n const spawn = deps.spawn ?? nodeSpawn;\n const homeDir = deps.paths?.homeDir ?? os.homedir();\n const paths: StepPaths =\n deps.paths ??\n ({\n activeRoot: '',\n stateRoot: '',\n configRoot: '',\n homeDir,\n } as StepPaths);\n const cliEntry = deps.cliEntry ?? process.argv[1] ?? 'active-work';\n return { fs, spawn, paths, cliEntry, platform: process.platform };\n}\n\nexport function getUnitDir(homeDir: string): string {\n return nodePath.join(homeDir, '.config', 'systemd', 'user');\n}\n\nexport function getUnitPath(homeDir: string): string {\n return nodePath.join(getUnitDir(homeDir), UNIT_NAME);\n}\n\nexport interface UnitOptions {\n cliEntry: string;\n port?: number;\n nodeBin?: string;\n}\n\n/** Render the systemd unit file content. */\nexport function renderUnit(opts: UnitOptions): string {\n const node = opts.nodeBin ?? process.execPath;\n const args = ['mcp', 'serve'];\n if (opts.port !== undefined) {\n args.push('--port', String(opts.port));\n }\n // ExecStart must use absolute paths. Quote the node binary and entrypoint\n // in case they contain spaces (common on macOS dev paths, less so on Linux,\n // but cheap insurance).\n const execStart = [quoteIfNeeded(node), quoteIfNeeded(opts.cliEntry), ...args].join(' ');\n return [\n '[Unit]',\n 'Description=active-work HTTP daemon (MCP + REST + dashboard)',\n 'After=network.target',\n '',\n '[Service]',\n 'Type=simple',\n `ExecStart=${execStart}`,\n 'Restart=on-failure',\n 'RestartSec=5',\n 'Environment=NODE_ENV=production',\n '',\n '[Install]',\n 'WantedBy=default.target',\n '',\n ].join('\\n');\n}\n\nfunction quoteIfNeeded(value: string): string {\n if (!/\\s/.test(value)) return value;\n // systemd unit files support double-quoted argv elements; escape any embedded\n // double quotes and backslashes.\n const escaped = value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n return `\"${escaped}\"`;\n}\n\n/** Spawn a process and capture its exit code + stderr. */\nfunction runOnce(\n spawn: typeof nodeSpawn,\n cmd: string,\n args: string[],\n): Promise<{ code: number | null; stderr: string; spawnError?: Error }> {\n return new Promise((resolve) => {\n let stderr = '';\n let settled = false;\n try {\n const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });\n child.stderr?.on('data', (chunk: Buffer | string) => {\n stderr += chunk.toString();\n });\n child.on('error', (err) => {\n if (settled) return;\n settled = true;\n resolve({ code: null, stderr, spawnError: err });\n });\n child.on('close', (code) => {\n if (settled) return;\n settled = true;\n resolve({ code, stderr });\n });\n } catch (err) {\n if (settled) return;\n settled = true;\n resolve({ code: null, stderr, spawnError: err as Error });\n }\n });\n}\n\n/**\n * Probe whether the user-level systemd unit is currently active.\n * Returns false (without error) on non-Linux or when `systemctl` is missing.\n */\nexport async function isUnitActive(deps: SetupDeps = {}): Promise<boolean> {\n const { spawn, platform } = resolveLocalDeps(deps);\n if (!isLinux(platform)) return false;\n const result = await runOnce(spawn, 'systemctl', ['--user', 'is-active', '--quiet', UNIT_NAME]);\n if (result.spawnError) return false;\n return result.code === 0;\n}\n\nexport interface InstallSupervisionOptions {\n /** Override the port baked into the unit's ExecStart. */\n port?: number;\n}\n\n/**\n * Install (or refresh) the user-level systemd unit and enable+start it.\n *\n * No-op on non-Linux. On Linux it writes the unit, reloads the daemon,\n * and runs `enable --now`. Idempotent: if the unit is already active and\n * its content matches, returns done:false.\n */\nexport async function stepInstallSupervision(\n deps: SetupDeps = {},\n opts: InstallSupervisionOptions = {},\n): Promise<StepResult> {\n const { fs, spawn, paths, cliEntry, platform } = resolveLocalDeps(deps);\n if (!isLinux(platform)) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Skipped: systemd supervision only applies on Linux (this host is ${platform})`,\n };\n }\n const unitDir = getUnitDir(paths.homeDir);\n const unitPath = getUnitPath(paths.homeDir);\n const desired = renderUnit({ cliEntry, port: opts.port });\n\n try {\n await fs.mkdir(unitDir, { recursive: true });\n let existing: string | null = null;\n try {\n existing = await fs.readFile(unitPath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n const unchanged = existing === desired;\n if (!unchanged) {\n await fs.writeFile(unitPath, desired, 'utf8');\n }\n\n const reload = await runOnce(spawn, 'systemctl', ['--user', 'daemon-reload']);\n if (reload.spawnError) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Wrote ${unitPath} but \\`systemctl\\` is unavailable (${reload.spawnError.message}). Run \\`systemctl --user daemon-reload && systemctl --user enable --now ${UNIT_NAME}\\` manually.`,\n };\n }\n if (reload.code !== 0) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: `systemctl --user daemon-reload exited ${reload.code ?? 'null'}: ${reload.stderr.trim()}`,\n };\n }\n\n // Enable lingering so the user manager — and thus the daemon — persists\n // across logout and starts at boot. Without it a `--user` unit is torn down\n // when the user's last session ends, so the daemon would not survive logout.\n //\n // Pass the username explicitly: the bare `loginctl enable-linger` form needs\n // an active login session to resolve \"self\" (it errors \"No such device\" when\n // run outside one), whereas the explicit form still routes through polkit's\n // `set-self-linger` action when the target is the caller. Best-effort:\n // enabling linger can require privileges, so a failure degrades to a note\n // rather than failing the install.\n let lingerUser: string | undefined;\n try {\n lingerUser = os.userInfo().username;\n } catch {\n lingerUser = undefined;\n }\n const linger = await runOnce(spawn, 'loginctl', [\n 'enable-linger',\n ...(lingerUser ? [lingerUser] : []),\n ]);\n const lingerEnabled = !linger.spawnError && linger.code === 0;\n\n const enable = await runOnce(spawn, 'systemctl', ['--user', 'enable', '--now', UNIT_NAME]);\n if (enable.spawnError) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: `systemctl --user enable --now ${UNIT_NAME} failed to spawn: ${enable.spawnError.message}`,\n };\n }\n if (enable.code !== 0) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: `systemctl --user enable --now ${UNIT_NAME} exited ${enable.code ?? 'null'}: ${enable.stderr.trim()}`,\n };\n }\n\n const action = unchanged ? 'refreshed' : 'installed';\n const lingerCmd = `loginctl enable-linger${lingerUser ? ` ${lingerUser}` : ''}`;\n const lingerNote = lingerEnabled\n ? ' Lingering enabled — survives logout and starts at boot.'\n : ` NOTE: could not enable lingering; run \\`sudo ${lingerCmd}\\` so the daemon survives logout and starts at boot (without it, it stops when your session ends).`;\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: !unchanged,\n message: `Systemd unit ${action} at ${unitPath} and enabled.${lingerNote}`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: (err as Error).message,\n };\n }\n}\n\n/**\n * Disable the user-level unit and remove the file.\n * No-op on non-Linux or when the unit is absent.\n */\nexport async function uninstallSupervision(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, spawn, paths, platform } = resolveLocalDeps(deps);\n if (!isLinux(platform)) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Skipped: systemd supervision only applies on Linux (this host is ${platform})`,\n };\n }\n const unitPath = getUnitPath(paths.homeDir);\n try {\n let present = true;\n try {\n await fs.stat(unitPath);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') present = false;\n else throw err;\n }\n if (!present) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `No systemd unit at ${unitPath}`,\n };\n }\n const disable = await runOnce(spawn, 'systemctl', ['--user', 'disable', '--now', UNIT_NAME]);\n if (disable.spawnError) {\n // systemctl missing — still try to remove the file so re-install is clean.\n await fs.rm(unitPath, { force: true });\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: true,\n message: `Removed ${unitPath} (systemctl unavailable: ${disable.spawnError.message})`,\n };\n }\n // Non-zero exit from `disable` is non-fatal (unit may already be inactive).\n await fs.rm(unitPath, { force: true });\n const reload = await runOnce(spawn, 'systemctl', ['--user', 'daemon-reload']);\n if (reload.code !== 0 && !reload.spawnError) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: true,\n message: `Removed ${unitPath}; daemon-reload exited ${reload.code ?? 'null'}`,\n };\n }\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: true,\n message: `Disabled and removed ${unitPath}`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: (err as Error).message,\n };\n }\n}\n","/**\n * macOS user-level launchd supervision for the active-work daemon (AW-2).\n *\n * Installs a `~/Library/LaunchAgents/dev.hjewkes.active-work.plist` LaunchAgent\n * that runs `active-work mcp serve`; launchd handles restart on crash and\n * relaunch at login. On non-macOS platforms every step here is a no-op — the\n * Linux equivalent lives in `supervision-systemd.ts`.\n */\nimport { promises as fsp } from 'node:fs';\nimport nodePath from 'node:path';\nimport { spawn as nodeSpawn } from 'node:child_process';\nimport os from 'node:os';\nimport { STEP_SUPERVISION } from './supervision-systemd.js';\nimport type { SetupDeps, StepPaths, StepResult } from './steps.js';\n\nexport const PLIST_LABEL = 'dev.hjewkes.active-work';\nexport const PLIST_NAME = `${PLIST_LABEL}.plist`;\n\nfunction isDarwin(platform: NodeJS.Platform = process.platform): boolean {\n return platform === 'darwin';\n}\n\nfunction resolveLocalDeps(deps: SetupDeps): {\n fs: typeof fsp;\n spawn: typeof nodeSpawn;\n paths: StepPaths;\n cliEntry: string;\n uid: number;\n platform: NodeJS.Platform;\n} {\n const fs = deps.fs ?? fsp;\n const spawn = deps.spawn ?? nodeSpawn;\n const homeDir = deps.paths?.homeDir ?? os.homedir();\n const paths: StepPaths =\n deps.paths ??\n ({\n activeRoot: '',\n stateRoot: '',\n configRoot: '',\n homeDir,\n } as StepPaths);\n const cliEntry = deps.cliEntry ?? process.argv[1] ?? 'active-work';\n const uid = process.getuid?.() ?? 0;\n return { fs, spawn, paths, cliEntry, uid, platform: process.platform };\n}\n\nexport function getAgentDir(homeDir: string): string {\n return nodePath.join(homeDir, 'Library', 'LaunchAgents');\n}\n\nexport function getPlistPath(homeDir: string): string {\n return nodePath.join(getAgentDir(homeDir), PLIST_NAME);\n}\n\nfunction getLogDir(homeDir: string): string {\n return nodePath.join(homeDir, 'Library', 'Logs', 'active-work');\n}\n\n/** The `gui/<uid>/<label>` service target used by `launchctl`. */\nfunction serviceTarget(uid: number): string {\n return `gui/${uid}/${PLIST_LABEL}`;\n}\n\nfunction escapeXml(value: string): string {\n return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n}\n\nexport interface PlistOptions {\n cliEntry: string;\n homeDir: string;\n port?: number;\n nodeBin?: string;\n}\n\n/** Render the launchd plist for the daemon. */\nexport function renderPlist(opts: PlistOptions): string {\n const node = opts.nodeBin ?? process.execPath;\n const argv = [node, opts.cliEntry, 'mcp', 'serve'];\n if (opts.port !== undefined) argv.push('--port', String(opts.port));\n const logDir = getLogDir(opts.homeDir);\n const programArgs = argv.map((a) => ` <string>${escapeXml(a)}</string>`).join('\\n');\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">',\n '<plist version=\"1.0\">',\n '<dict>',\n ' <key>Label</key>',\n ` <string>${PLIST_LABEL}</string>`,\n ' <key>ProgramArguments</key>',\n ' <array>',\n programArgs,\n ' </array>',\n ' <key>RunAtLoad</key>',\n ' <true/>',\n ' <key>KeepAlive</key>',\n ' <true/>',\n ' <key>ProcessType</key>',\n ' <string>Background</string>',\n ' <key>EnvironmentVariables</key>',\n ' <dict>',\n ' <key>NODE_ENV</key>',\n ' <string>production</string>',\n ' </dict>',\n ' <key>StandardOutPath</key>',\n ` <string>${escapeXml(nodePath.join(logDir, 'daemon.out.log'))}</string>`,\n ' <key>StandardErrorPath</key>',\n ` <string>${escapeXml(nodePath.join(logDir, 'daemon.err.log'))}</string>`,\n '</dict>',\n '</plist>',\n '',\n ].join('\\n');\n}\n\n/** Spawn a process and capture its exit code + stderr. */\nfunction runOnce(\n spawn: typeof nodeSpawn,\n cmd: string,\n args: string[],\n): Promise<{ code: number | null; stderr: string; spawnError?: Error }> {\n return new Promise((resolve) => {\n let stderr = '';\n let settled = false;\n try {\n const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });\n child.stderr?.on('data', (chunk: Buffer | string) => {\n stderr += chunk.toString();\n });\n child.on('error', (err) => {\n if (settled) return;\n settled = true;\n resolve({ code: null, stderr, spawnError: err });\n });\n child.on('close', (code) => {\n if (settled) return;\n settled = true;\n resolve({ code, stderr });\n });\n } catch (err) {\n if (settled) return;\n settled = true;\n resolve({ code: null, stderr, spawnError: err as Error });\n }\n });\n}\n\n/**\n * Probe whether the launchd agent is currently loaded.\n * Returns false (without error) on non-macOS or when `launchctl` is missing.\n */\nexport async function isAgentLoaded(deps: SetupDeps = {}): Promise<boolean> {\n const { spawn, uid, platform } = resolveLocalDeps(deps);\n if (!isDarwin(platform)) return false;\n const result = await runOnce(spawn, 'launchctl', ['print', serviceTarget(uid)]);\n if (result.spawnError) return false;\n return result.code === 0;\n}\n\nexport interface InstallLaunchAgentOptions {\n /** Override the port baked into the plist's ProgramArguments. */\n port?: number;\n}\n\n/**\n * Install (or refresh) the user LaunchAgent and load it.\n *\n * No-op on non-macOS. On macOS it writes the plist, boots out any stale copy,\n * and bootstraps it into the `gui/<uid>` domain. Idempotent: if the plist is\n * unchanged and already loaded, returns done:false.\n */\nexport async function installLaunchAgent(\n deps: SetupDeps = {},\n opts: InstallLaunchAgentOptions = {},\n): Promise<StepResult> {\n const { fs, spawn, paths, cliEntry, uid, platform } = resolveLocalDeps(deps);\n if (!isDarwin(platform)) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Skipped: launchd supervision only applies on macOS (this host is ${platform})`,\n };\n }\n const plistPath = getPlistPath(paths.homeDir);\n const desired = renderPlist({ cliEntry, homeDir: paths.homeDir, port: opts.port });\n\n try {\n await fs.mkdir(getAgentDir(paths.homeDir), { recursive: true });\n await fs.mkdir(getLogDir(paths.homeDir), { recursive: true });\n\n let existing: string | null = null;\n try {\n existing = await fs.readFile(plistPath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n const unchanged = existing === desired;\n if (unchanged && (await isAgentLoaded(deps))) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `launchd agent already loaded from ${plistPath}`,\n };\n }\n if (!unchanged) {\n await fs.writeFile(plistPath, desired, 'utf8');\n }\n\n // Boot out any stale instance first so bootstrap is idempotent. A missing\n // service exits non-zero (\"No such process\") — that is expected, not fatal.\n const bootout = await runOnce(spawn, 'launchctl', ['bootout', serviceTarget(uid)]);\n if (bootout.spawnError) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Wrote ${plistPath} but \\`launchctl\\` is unavailable (${bootout.spawnError.message}). Load it manually with \\`launchctl bootstrap gui/${uid} ${plistPath}\\`.`,\n };\n }\n\n const bootstrap = await runOnce(spawn, 'launchctl', ['bootstrap', `gui/${uid}`, plistPath]);\n if (bootstrap.spawnError) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: `launchctl bootstrap failed to spawn: ${bootstrap.spawnError.message}`,\n };\n }\n if (bootstrap.code !== 0) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: `launchctl bootstrap gui/${uid} exited ${bootstrap.code ?? 'null'}: ${bootstrap.stderr.trim()}`,\n };\n }\n\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: true,\n message: `launchd agent installed at ${plistPath} and loaded`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: (err as Error).message,\n };\n }\n}\n\n/**\n * Boot out the LaunchAgent and remove the plist.\n * No-op on non-macOS or when the plist is absent.\n */\nexport async function uninstallLaunchAgent(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, spawn, paths, uid, platform } = resolveLocalDeps(deps);\n if (!isDarwin(platform)) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Skipped: launchd supervision only applies on macOS (this host is ${platform})`,\n };\n }\n const plistPath = getPlistPath(paths.homeDir);\n try {\n let present = true;\n try {\n await fs.stat(plistPath);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') present = false;\n else throw err;\n }\n if (!present) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `No launchd agent at ${plistPath}`,\n };\n }\n // Best-effort bootout; a not-loaded agent exits non-zero, which is fine.\n const bootout = await runOnce(spawn, 'launchctl', ['bootout', serviceTarget(uid)]);\n await fs.rm(plistPath, { force: true });\n if (bootout.spawnError) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: true,\n message: `Removed ${plistPath} (launchctl unavailable: ${bootout.spawnError.message})`,\n };\n }\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: true,\n message: `Booted out and removed ${plistPath}`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: (err as Error).message,\n };\n }\n}\n","/**\n * Platform dispatcher for daemon supervision.\n *\n * `setup`/`uninstall` should not care whether a host uses systemd or launchd —\n * they ask `getSupervisor()` for the local implementation and drive it through\n * this common interface. Linux → systemd (`supervision-systemd.ts`),\n * macOS → launchd (`supervision-launchd.ts`), everything else → no supervisor.\n */\nimport {\n UNIT_NAME,\n stepInstallSupervision,\n uninstallSupervision,\n isUnitActive,\n} from './supervision-systemd.js';\nimport {\n PLIST_LABEL,\n installLaunchAgent,\n uninstallLaunchAgent,\n isAgentLoaded,\n} from './supervision-launchd.js';\nimport type { SetupDeps, StepResult } from './steps.js';\n\nexport interface Supervisor {\n readonly kind: 'systemd' | 'launchd';\n /** One-line prompt shown when offering to install supervision. */\n readonly installPrompt: string;\n /** One-line prompt shown when offering to remove supervision. */\n readonly uninstallPrompt: string;\n /** Manual command that finishes enabling if the runtime step fails. */\n readonly enableHint: string;\n install(deps: SetupDeps, opts?: { port?: number }): Promise<StepResult>;\n uninstall(deps: SetupDeps): Promise<StepResult>;\n /** True when the daemon is already supervised (so manual start is skipped). */\n isActive(deps: SetupDeps): Promise<boolean>;\n}\n\nconst systemdSupervisor: Supervisor = {\n kind: 'systemd',\n installPrompt: 'Install user systemd unit to keep the daemon running across logins?',\n uninstallPrompt: 'Disable and remove the systemd user unit (active-work.service)?',\n enableHint: `systemctl --user enable --now ${UNIT_NAME}`,\n install: (deps, opts) => stepInstallSupervision(deps, opts),\n uninstall: (deps) => uninstallSupervision(deps),\n isActive: (deps) => isUnitActive(deps),\n};\n\nconst launchdSupervisor: Supervisor = {\n kind: 'launchd',\n installPrompt: 'Install a launchd agent to keep the daemon running across logins?',\n uninstallPrompt: `Boot out and remove the launchd agent (${PLIST_LABEL})?`,\n enableHint: `launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/${PLIST_LABEL}.plist`,\n install: (deps, opts) => installLaunchAgent(deps, opts),\n uninstall: (deps) => uninstallLaunchAgent(deps),\n isActive: (deps) => isAgentLoaded(deps),\n};\n\n/** Return the supervisor for `platform`, or null when none is integrated. */\nexport function getSupervisor(platform: NodeJS.Platform = process.platform): Supervisor | null {\n if (platform === 'linux') return systemdSupervisor;\n if (platform === 'darwin') return launchdSupervisor;\n return null;\n}\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { runUninstall } from '../setup/steps.js';\nimport { color } from '../utils/color.js';\n\n/**\n * `active-work uninstall` — reverse what setup did. Asks for confirmation before each\n * destructive action (or --yes to skip prompts). Does NOT touch the active\n * root: that's operator data, and removing it should be a deliberate act.\n */\n\nconst ArgsSchema = z.object({\n yes: z.boolean().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst StepSchema = z.object({\n name: z.string(),\n done: z.boolean(),\n message: z.string().optional(),\n error: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n steps: z.array(StepSchema),\n activeRootPreservedAt: z.string(),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'uninstall',\n description:\n 'Reverse what setup did: remove the skill, stop the daemon, unregister MCP. Preserves the active root.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n yes: {\n long: '--yes',\n short: '-y',\n description: 'Skip all prompts; assume yes.',\n },\n },\n },\n async run(args, ctx) {\n const report = await runUninstall({ yes: args.yes ?? false });\n if (ctx.format !== 'json') {\n for (const step of report.steps) {\n const mark = step.error ? color.red('FAIL') : color.green('OK');\n const trailing = step.error ?? step.message ?? '';\n process.stderr.write(` ${mark} ${step.name}${trailing ? ` — ${trailing}` : ''}\\n`);\n }\n process.stderr.write(\n '\\n' +\n color.dim(\n `Your active root at ${report.activeRootPreservedAt} is preserved. ` +\n 'Remove manually if you want.',\n ) +\n '\\n',\n );\n }\n return report;\n },\n});\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { runDoctor, type CheckStatus } from '../doctor.js';\nimport { color } from '../utils/color.js';\n\n/**\n * `active-work doctor` — health-check the local install.\n *\n * Returns a structured report (exit 0; scripts read the `ok` field) and, in\n * human mode, prints a readable table to stderr like `active-work setup`.\n */\n\nconst ArgsSchema = z.object({});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst CheckSchema = z.object({\n name: z.string(),\n status: z.enum(['ok', 'warn', 'fail']),\n detail: z.string(),\n});\n\nconst ResultSchema = z.object({\n ok: z.boolean(),\n checks: z.array(CheckSchema),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nfunction badge(status: CheckStatus): string {\n if (status === 'ok') return color.green('OK ');\n if (status === 'warn') return color.yellow('WARN');\n return color.red('FAIL');\n}\n\nexport default defineCommand<Args, Result>({\n name: 'doctor',\n description:\n 'Health-check the install: Node, active root, daemon, MCP registration, skill, and supervision.',\n args: ArgsSchema,\n result: ResultSchema,\n async run(_args, ctx) {\n const report = await runDoctor();\n if (ctx.format !== 'json') {\n process.stderr.write(color.bold('active-work doctor') + '\\n');\n for (const check of report.checks) {\n process.stderr.write(` ${badge(check.status)} ${check.name} — ${check.detail}\\n`);\n }\n const summary = report.ok\n ? color.green('All checks passed (warnings are advisory).')\n : color.red('One or more checks failed.');\n process.stderr.write(summary + '\\n');\n }\n return report;\n },\n});\n","/**\n * `active-work doctor` — aggregate health checks for a local install (AW-4).\n *\n * Verifies the pieces `active-work setup` wires up: Node version, the active\n * root + schema version, the MCP daemon, Claude Code MCP registration, the\n * installed skill, and (if the platform supports it) daemon supervision.\n *\n * Every probe is injectable so the checks are unit-testable without a real\n * daemon, filesystem layout, or service manager.\n */\nimport { promises as fsp } from 'node:fs';\nimport nodePath from 'node:path';\nimport os from 'node:os';\nimport { getActiveRoot } from './utils/paths.js';\nimport { isProcessAlive, probeHealth, readPidFile, resolveDaemonPort } from './server/lifecycle.js';\nimport { getSupervisor } from './setup/supervision.js';\nimport { lintHashes, listInitiativeSlugs } from './lint/index.js';\nimport { loadTasks } from './lint/load-tasks.js';\nimport { loadNotesFromDir } from './notes/note-file.js';\nimport { NOTE_TITLE_MAX_LENGTH } from './schemas/note.js';\nimport { sweepAllLeases, type LeaseSweepResult } from './sessions/lease.js';\nimport {\n deriveOpenLoops,\n findSessionIssues,\n type DanglingKind,\n type DanglingResolve,\n type MalformedSession,\n} from './sessions/open-loops.js';\n\nexport type CheckStatus = 'ok' | 'warn' | 'fail';\n\nexport interface DoctorCheck {\n name: string;\n status: CheckStatus;\n detail: string;\n}\n\nexport interface DoctorReport {\n ok: boolean;\n checks: DoctorCheck[];\n}\n\nexport interface DaemonProbe {\n running: boolean;\n healthy: boolean;\n port?: number;\n version?: string;\n pid?: number;\n /** True when `/health` answered but no PID file names the daemon. */\n orphaned?: boolean;\n}\n\nexport interface DoctorDeps {\n fs?: typeof fsp;\n activeRoot?: string;\n homeDir?: string;\n /** Node version string like `process.version` (`v22.4.0`). */\n nodeVersion?: string;\n /** Minimum supported Node major (defaults to 22). */\n minNodeMajor?: number;\n /** Probe the daemon; defaults to reading the pid file + `/health`. */\n probeDaemon?: () => Promise<DaemonProbe>;\n /** Whether a supervisor already owns the daemon; null when unsupported. */\n supervisorActive?: () => Promise<{ kind: string; active: boolean } | null>;\n /** Sweep session leases; defaults to the real `.sessions/` walk. */\n sweepLeases?: (activeRoot: string) => Promise<LeaseSweepResult>;\n}\n\n/**\n * Probe by port alone, for when the PID file is absent or names a dead\n * process. A missing file used to read as \"not running\" outright, which is how\n * a live daemon whose file its predecessor clobbered became indistinguishable\n * from no daemon at all (AW-76). Something answering `/health` outranks the\n * bookkeeping, so adopt the pid/port/version it reports.\n */\nasync function probeByPort(port: number): Promise<DaemonProbe> {\n const health = await probeHealth(port);\n if (!health) return { running: false, healthy: false, port };\n return {\n running: true,\n healthy: true,\n orphaned: true,\n pid: health.pid,\n port: health.port,\n version: health.version,\n };\n}\n\nasync function defaultProbeDaemon(): Promise<DaemonProbe> {\n const entry = await readPidFile();\n if (!entry) return probeByPort(resolveDaemonPort());\n if (!isProcessAlive(entry.pid)) {\n // A pre-meta pid file records port 0; fall back to where a daemon would be.\n return probeByPort(entry.meta.port || resolveDaemonPort());\n }\n const health = await probeHealth(entry.meta.port);\n if (health) {\n return {\n running: true,\n healthy: true,\n pid: health.pid,\n port: health.port,\n version: health.version,\n };\n }\n return {\n running: true,\n healthy: false,\n pid: entry.pid,\n port: entry.meta.port,\n version: entry.meta.version,\n };\n}\n\nasync function defaultSupervisorActive(): Promise<{\n kind: string;\n active: boolean;\n} | null> {\n const supervisor = getSupervisor();\n if (!supervisor) return null;\n return { kind: supervisor.kind, active: await supervisor.isActive({}) };\n}\n\nfunction parseMajor(version: string): number {\n const match = /^v?(\\d+)\\./.exec(version);\n return match ? Number(match[1]) : 0;\n}\n\nasync function fileExists(fs: typeof fsp, target: string): Promise<boolean> {\n try {\n await fs.access(target);\n return true;\n } catch {\n return false;\n }\n}\n\n// `setup` registers the server as `@hjewkes/active-work` (stdio), but users\n// commonly wire it as `active-work` (http, pointed at the daemon). Accept\n// either name.\nconst MCP_SERVER_NAMES = ['@hjewkes/active-work', 'active-work'];\n\nasync function readMcpRegistered(fs: typeof fsp, homeDir: string): Promise<boolean> {\n const configPath = nodePath.join(homeDir, '.claude.json');\n try {\n const raw = await fs.readFile(configPath, 'utf8');\n const parsed = JSON.parse(raw) as {\n mcpServers?: Record<string, unknown>;\n };\n const servers = parsed.mcpServers ?? {};\n return MCP_SERVER_NAMES.some((name) => Boolean(servers[name]));\n } catch {\n return false;\n }\n}\n\nasync function checkNode(deps: DoctorDeps): Promise<DoctorCheck> {\n const version = deps.nodeVersion ?? process.version;\n const min = deps.minNodeMajor ?? 22;\n const major = parseMajor(version);\n if (major >= min) {\n return { name: 'node', status: 'ok', detail: `${version} (>= ${min})` };\n }\n return {\n name: 'node',\n status: 'fail',\n detail: `${version} is older than the required Node ${min}`,\n };\n}\n\nasync function checkActiveRoot(deps: DoctorDeps): Promise<DoctorCheck> {\n const fs = deps.fs ?? fsp;\n const activeRoot = deps.activeRoot ?? getActiveRoot();\n if (!(await fileExists(fs, activeRoot))) {\n return {\n name: 'active-root',\n status: 'fail',\n detail: `${activeRoot} does not exist — run \\`active-work setup\\``,\n };\n }\n const schemaFile = nodePath.join(activeRoot, '.schema-version');\n if (!(await fileExists(fs, schemaFile))) {\n return {\n name: 'active-root',\n status: 'warn',\n detail: `${activeRoot} exists but has no .schema-version`,\n };\n }\n return { name: 'active-root', status: 'ok', detail: activeRoot };\n}\n\nasync function checkDaemon(deps: DoctorDeps): Promise<DoctorCheck> {\n const probe = await (deps.probeDaemon ?? defaultProbeDaemon)();\n const where = `pid ${probe.pid ?? '?'}, port ${probe.port ?? '?'}, v${probe.version ?? '?'}`;\n if (probe.running && probe.healthy && probe.orphaned === true) {\n // Answering but unfiled: `mcp stop`/`mcp restart` key off the PID file and\n // will not find it, so this needs saying even though the daemon is fine.\n return {\n name: 'daemon',\n status: 'warn',\n detail:\n `running (${where}) but no pid file — \\`mcp stop\\`/\\`mcp restart\\` ` +\n 'cannot see it; restart it through your supervisor to re-file it',\n };\n }\n if (probe.running && probe.healthy) {\n return { name: 'daemon', status: 'ok', detail: `running (${where})` };\n }\n if (probe.running && !probe.healthy) {\n return {\n name: 'daemon',\n status: 'warn',\n detail: `pid ${probe.pid ?? '?'} is alive but /health did not answer`,\n };\n }\n // Name the port we probed: a daemon started on a non-default `--port` with\n // no pid file to record it is invisible here, and that beats implying none.\n const probed = probe.port === undefined ? '' : ` (nothing answered port ${probe.port})`;\n return {\n name: 'daemon',\n status: 'warn',\n detail: `not running${probed} — start it with \\`active-work mcp serve --detach\\``,\n };\n}\n\nasync function checkMcp(deps: DoctorDeps): Promise<DoctorCheck> {\n const fs = deps.fs ?? fsp;\n const homeDir = deps.homeDir ?? os.homedir();\n if (await readMcpRegistered(fs, homeDir)) {\n return { name: 'mcp-registration', status: 'ok', detail: 'registered in ~/.claude.json' };\n }\n return {\n name: 'mcp-registration',\n status: 'warn',\n detail: 'not registered with Claude Code — run `active-work setup`',\n };\n}\n\nasync function checkSkill(deps: DoctorDeps): Promise<DoctorCheck> {\n const fs = deps.fs ?? fsp;\n const homeDir = deps.homeDir ?? os.homedir();\n const skill = nodePath.join(homeDir, '.claude', 'skills', 'active-work', 'SKILL.md');\n if (await fileExists(fs, skill)) {\n return { name: 'skill', status: 'ok', detail: skill };\n }\n return {\n name: 'skill',\n status: 'warn',\n detail: 'skill not installed in ~/.claude/skills — run `active-work setup`',\n };\n}\n\nasync function checkSupervisor(deps: DoctorDeps): Promise<DoctorCheck> {\n const result = await (deps.supervisorActive ?? defaultSupervisorActive)();\n if (!result) {\n return {\n name: 'supervision',\n status: 'ok',\n detail: `no supervisor integration for ${process.platform} (optional)`,\n };\n }\n if (result.active) {\n return { name: 'supervision', status: 'ok', detail: `${result.kind} agent is loaded` };\n }\n return {\n name: 'supervision',\n status: 'warn',\n detail: `${result.kind} supervisor not active — re-run \\`active-work setup\\` to enable`,\n };\n}\n\n/** Each rejection kind has a different remedy, so each gets its own sentence. */\nconst DANGLING_REMEDY: Record<DanglingKind, string> = {\n missing: 'no such next_step — fix or drop the ref',\n 'not-prior':\n 'target session ended at or after the resolver, so the close was rejected — re-file the resolve from a later session',\n self: 'a session cannot resolve its own loop — resolve it from a later session',\n};\n\nfunction describeDangling(kind: DanglingKind, entries: string[]): string {\n return `${DANGLING_REMEDY[kind]}: ${entries.join(', ')}`;\n}\n\nfunction openLoopsCheck(byKind: Map<DanglingKind, string[]>): DoctorCheck {\n if (byKind.size === 0) {\n return { name: 'open-loops', status: 'ok', detail: 'no dangling resolves' };\n }\n const parts = [...byKind.entries()].map(([kind, refs]) => describeDangling(kind, refs));\n return { name: 'open-loops', status: 'warn', detail: parts.join('; ') };\n}\n\nfunction taskRefsCheck(entries: string[]): DoctorCheck {\n if (entries.length === 0) {\n return { name: 'task-refs', status: 'ok', detail: 'every next_steps task ref resolves' };\n }\n return {\n name: 'task-refs',\n status: 'warn',\n // Mirrors dangling resolves, but for the other half of the ledger: unlike\n // a bad `resolves` ref, a bad `next_steps` ref is never rejected — the\n // loop just stays open and silent forever.\n detail: `next_steps reference a task that does not exist: ${entries.join('; ')}`,\n };\n}\n\n/** `kind: 'task'` open loops whose `ref` names no task in this initiative. */\nasync function collectBadTaskRefs(\n slug: string,\n initiativeDir: string,\n now: Date,\n): Promise<string[]> {\n const tasks = await loadTasks(initiativeDir);\n const taskIds = new Set(tasks.map((t) => t.id));\n const loops = await deriveOpenLoops(initiativeDir, { now, tasks });\n return loops\n .filter((loop) => loop.kind === 'task' && loop.targetRef !== undefined)\n .filter((loop) => !taskIds.has(loop.targetRef as string))\n .map(\n (loop) =>\n `${slug}/sessions/${loop.sessionFile}.md ${loop.ref} -> ${loop.targetRef} (no such task)`,\n );\n}\n\nfunction sessionFilesCheck(malformed: string[]): DoctorCheck {\n if (malformed.length === 0) {\n return { name: 'session-files', status: 'ok', detail: 'every session file parses' };\n }\n return {\n name: 'session-files',\n status: 'warn',\n // These files are invisible in the ledger: their loops vanish and the loops\n // they closed come back. Only this check can surface them.\n detail: `${malformed.length} session file(s) unreadable — their loops are missing from the ledger: ${malformed.join('; ')}`,\n };\n}\n\n/**\n * Walk every initiative once and report both integrity signals derivation\n * cannot express in the ledger: rejected `resolves` and unparseable sessions.\n */\nasync function checkSessions(deps: DoctorDeps): Promise<DoctorCheck[]> {\n const activeRoot = deps.activeRoot ?? getActiveRoot();\n const slugs = await listInitiativeSlugs(activeRoot);\n const byKind = new Map<DanglingKind, string[]>();\n const malformed: string[] = [];\n const badTaskRefs: string[] = [];\n const now = new Date();\n for (const slug of slugs) {\n const initiativeDir = nodePath.join(activeRoot, slug);\n const issues = await findSessionIssues(initiativeDir);\n for (const entry of issues.dangling) collectDangling(byKind, slug, entry);\n for (const entry of issues.malformed) malformed.push(describeMalformed(slug, entry));\n badTaskRefs.push(...(await collectBadTaskRefs(slug, initiativeDir, now)));\n }\n return [openLoopsCheck(byKind), sessionFilesCheck(malformed), taskRefsCheck(badTaskRefs)];\n}\n\nfunction collectDangling(\n byKind: Map<DanglingKind, string[]>,\n slug: string,\n entry: DanglingResolve,\n): void {\n const line = `${slug}/sessions/${entry.sessionFile}.md resolves ${entry.ref}`;\n const existing = byKind.get(entry.kind);\n if (existing) existing.push(line);\n else byKind.set(entry.kind, [line]);\n}\n\nfunction describeMalformed(slug: string, entry: MalformedSession): string {\n return `${slug}/sessions/${entry.file} (${entry.reason})`;\n}\n\nfunction noteTitlesCheck(entries: string[]): DoctorCheck {\n if (entries.length === 0) {\n return {\n name: 'note-titles',\n status: 'ok',\n detail: `every note title is at most ${NOTE_TITLE_MAX_LENGTH} characters`,\n };\n }\n return {\n name: 'note-titles',\n status: 'warn',\n // `note.add` rejects these now, so anything here predates the bound: the\n // read path stays permissive on purpose, and this is the only place those\n // notes get named.\n detail:\n `note title longer than ${NOTE_TITLE_MAX_LENGTH} characters ` +\n `(rename the title in the file's frontmatter): ${entries.join('; ')}`,\n };\n}\n\n/** Notes whose stored title exceeds the write-time bound. */\nasync function checkNoteTitles(deps: DoctorDeps): Promise<DoctorCheck> {\n const activeRoot = deps.activeRoot ?? getActiveRoot();\n const slugs = await listInitiativeSlugs(activeRoot);\n const overlong: string[] = [];\n for (const slug of slugs) {\n const { notes } = await loadNotesFromDir(nodePath.join(activeRoot, slug));\n for (const note of notes) {\n if (note.frontmatter.title.length <= NOTE_TITLE_MAX_LENGTH) continue;\n overlong.push(\n `${slug}/sources/notes/${note.filename} (${note.frontmatter.title.length} chars)`,\n );\n }\n }\n return noteTitlesCheck(overlong);\n}\n\n/**\n * Session leases under `<activeRoot>/.sessions/` (CC-9).\n *\n * Dead leases are swept by whoever next bootstraps the initiative, so this is\n * mostly a visibility check — but a directory that cannot be pruned means the\n * sibling warning would eventually fire on every launch forever, and that is\n * worth naming before the operator starts ignoring the warning. Never `fail`:\n * leases are advisory, and an install is not broken because one is stuck.\n */\nasync function checkLeases(deps: DoctorDeps): Promise<DoctorCheck> {\n const activeRoot = deps.activeRoot ?? getActiveRoot();\n const result = await (deps.sweepLeases ?? sweepAllLeases)(activeRoot);\n const counts = `${result.live} live, ${result.pruned} pruned`;\n if (result.error) {\n return {\n name: 'session-leases',\n status: 'warn',\n detail: `could not sweep ${nodePath.join(activeRoot, '.sessions')} (${result.error}) — stale leases will keep warning every bootstrap`,\n };\n }\n return { name: 'session-leases', status: 'ok', detail: counts };\n}\n\nfunction artifactHashesCheck(drifted: string[]): DoctorCheck {\n if (drifted.length === 0) {\n return {\n name: 'artifact-hashes',\n status: 'ok',\n detail: 'no hand-edits detected in tracked structured artifacts',\n };\n }\n return {\n name: 'artifact-hashes',\n status: 'warn',\n detail: `hand-edited outside active-work: ${drifted.join('; ')}`,\n };\n}\n\n/** Structured artifacts (tasks/*.yml, artifacts.yml, brief.md) whose content no longer matches the last CLI write (AW-66). */\nasync function checkArtifactHashes(deps: DoctorDeps): Promise<DoctorCheck> {\n const activeRoot = deps.activeRoot ?? getActiveRoot();\n const slugs = await listInitiativeSlugs(activeRoot);\n const drifted: string[] = [];\n for (const slug of slugs) {\n const findings = await lintHashes(slug, nodePath.join(activeRoot, slug));\n drifted.push(...findings.map((f) => `${slug}/${f.file}`));\n }\n return artifactHashesCheck(drifted);\n}\n\n/** Run all health checks and return a report. `ok` is false iff any check failed. */\nexport async function runDoctor(deps: DoctorDeps = {}): Promise<DoctorReport> {\n const [installChecks, sessionChecks, noteTitles, artifactHashes, leases] = await Promise.all([\n Promise.all([\n checkNode(deps),\n checkActiveRoot(deps),\n checkDaemon(deps),\n checkMcp(deps),\n checkSkill(deps),\n checkSupervisor(deps),\n ]),\n checkSessions(deps),\n checkNoteTitles(deps),\n checkArtifactHashes(deps),\n checkLeases(deps),\n ]);\n const checks = [...installChecks, ...sessionChecks, noteTitles, artifactHashes, leases];\n return { ok: checks.every((c) => c.status !== 'fail'), checks };\n}\n","import { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\nimport { getActiveRoot } from '../utils/paths.js';\nimport { lintBrief } from './brief.js';\nimport { lintHashes } from './hashes.js';\nimport { lintOpenLoops } from './open-loops.js';\nimport { lintSources } from './sources.js';\nimport { lintTasks } from './task.js';\nimport { lintZeroLoops } from './zero-loops.js';\nimport { DEFAULT_LIMITS, type LintFinding, type LintLimits } from './types.js';\n\nexport type { LintFinding, LintLevel, LintLimits } from './types.js';\nexport { DEFAULT_LIMITS } from './types.js';\nexport { lintBrief } from './brief.js';\nexport { lintTasks } from './task.js';\nexport { lintOpenLoops } from './open-loops.js';\nexport { lintZeroLoops } from './zero-loops.js';\nexport { lintSources } from './sources.js';\nexport { lintHashes } from './hashes.js';\n\ninterface LintOptions {\n activeRoot?: string;\n limits?: LintLimits;\n /** Injected for determinism; defaults to `new Date()`. */\n now?: Date;\n}\n\n/**\n * Run every lint against a single initiative and concatenate the findings.\n *\n * Per-lint errors propagate; missing artifacts (handled inside each lint)\n * simply yield no findings.\n */\nexport async function lintSlug(slug: string, options: LintOptions = {}): Promise<LintFinding[]> {\n const activeRoot = options.activeRoot ?? getActiveRoot();\n const limits = options.limits ?? DEFAULT_LIMITS;\n const now = options.now ?? new Date();\n const initiativeDir = path.join(activeRoot, slug);\n const [brief, tasks, openLoops, zeroLoops, sources, hashes] = await Promise.all([\n lintBrief(slug, initiativeDir, limits),\n lintTasks(slug, initiativeDir, limits),\n lintOpenLoops(slug, initiativeDir, limits, now),\n lintZeroLoops(slug, initiativeDir),\n lintSources(slug, initiativeDir),\n lintHashes(slug, initiativeDir),\n ]);\n return [...brief, ...tasks, ...openLoops, ...zeroLoops, ...sources, ...hashes];\n}\n\nexport async function listInitiativeSlugs(activeRoot: string): Promise<string[]> {\n let entries: Dirent[];\n try {\n entries = await fs.readdir(activeRoot, { withFileTypes: true });\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') return [];\n throw err;\n }\n return entries\n .filter((e) => e.isDirectory() && !e.name.startsWith('.'))\n .map((e) => e.name)\n .sort();\n}\n\n/**\n * Lint every initiative under `activeRoot` and return the aggregated\n * findings ordered by slug.\n */\nexport async function lintAll(options: LintOptions = {}): Promise<LintFinding[]> {\n const activeRoot = options.activeRoot ?? getActiveRoot();\n const slugs = await listInitiativeSlugs(activeRoot);\n const findings: LintFinding[] = [];\n for (const slug of slugs) {\n const slugFindings = await lintSlug(slug, {\n activeRoot,\n limits: options.limits,\n now: options.now,\n });\n findings.push(...slugFindings);\n }\n return findings;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readRawFrontmatter } from '../utils/gray-matter-io.js';\nimport { DEFAULT_LIMITS, type LintFinding, type LintLimits } from './types.js';\n\nfunction countBodyLines(body: string): number {\n const lines = body.split('\\n');\n while (lines.length > 0 && lines[lines.length - 1].trim() === '') {\n lines.pop();\n }\n return lines.length;\n}\n\n/**\n * Read `brief.md` and emit warnings about its prose body.\n *\n * Parses with `readRawFrontmatter` so schema-invalid briefs still get linted\n * — fixing schema issues is the writer's job; lint stays advisory.\n */\nexport async function lintBrief(\n slug: string,\n initiativeDir: string,\n limits: LintLimits = DEFAULT_LIMITS,\n): Promise<LintFinding[]> {\n const filePath = path.join(initiativeDir, 'brief.md');\n try {\n await fs.access(filePath);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') return [];\n throw err;\n }\n\n const { body } = await readRawFrontmatter(filePath);\n const bodyLines = countBodyLines(body);\n if (bodyLines <= limits.briefMaxBodyLines) return [];\n\n return [\n {\n level: 'warn',\n slug,\n file: 'brief.md',\n message: `body is ${bodyLines} lines (> ${limits.briefMaxBodyLines}). Move resolved/archival content to a purpose-named file under sources/ and trim the brief.`,\n },\n ];\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { hashContent, readArtifactHashes } from '../utils/artifact-hash.js';\nimport type { LintFinding } from './types.js';\n\n/**\n * Compare each tracked structured artifact's on-disk content against the\n * hash recorded at its last CLI write. Files with no manifest entry (never\n * CLI-written, or predating AW-66) are silently skipped rather than flagged\n * — an empty manifest must never read as \"everything drifted\".\n *\n * A manifest entry whose file has since been deleted (e.g. `task delete`,\n * which does not route through `writeYaml`) is also skipped: absence is not\n * drift.\n */\nexport async function lintHashes(slug: string, initiativeDir: string): Promise<LintFinding[]> {\n const manifest = await readArtifactHashes(initiativeDir);\n const findings: LintFinding[] = [];\n\n for (const [relPath, storedHash] of Object.entries(manifest)) {\n let content: string;\n try {\n content = await fs.readFile(path.join(initiativeDir, relPath), 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') continue;\n throw err;\n }\n if (hashContent(content) === storedHash) continue;\n findings.push({\n level: 'warn',\n slug,\n file: relPath,\n message: `${relPath} was hand-edited outside active-work (content no longer matches the last CLI write) — re-apply the change through the CLI/MCP tools instead of editing the file directly`,\n });\n }\n\n return findings;\n}\n","import path from 'node:path';\nimport { deriveOpenLoops } from '../sessions/open-loops.js';\nimport { loadTasks } from './load-tasks.js';\nimport { DEFAULT_LIMITS, type LintFinding, type LintLimits } from './types.js';\n\n/**\n * A `kind: 'task'` loop closes itself when its task is marked done, because\n * derivation is handed the task list. A `kind: 'pr'` loop has no such luck:\n * `isAutoResolved` can close one, but only when given `mergedPrs`, and\n * bootstrap deliberately withholds that to stay offline on every launch. So a\n * PR loop never closes on its own however long ago its PR merged — it just\n * ages until it trips the cap below, where the generic advice (\"resolve with\n * outcome: abandoned\") is exactly wrong for work that in fact shipped (AW-74).\n */\nfunction staleLoopAdvice(kind: string): string {\n if (kind === 'pr') {\n return (\n 'work it or resolve it explicitly — note that a pr loop can never ' +\n 'close itself (loop derivation stays offline and never checks merge ' +\n 'state), so if the PR has already merged, resolve it with outcome: ' +\n 'done rather than abandoned'\n );\n }\n return 'work it or resolve it with outcome: abandoned';\n}\n\n/**\n * Warn about open loops that have aged past the cap.\n *\n * Derivation is best-effort by construction (malformed sessions are skipped\n * inside `deriveOpenLoops`), so this rule never throws on a broken initiative\n * — it just reports whatever loops it could derive.\n */\nexport async function lintOpenLoops(\n slug: string,\n initiativeDir: string,\n limits: LintLimits = DEFAULT_LIMITS,\n now: Date = new Date(),\n): Promise<LintFinding[]> {\n const tasks = await loadTasks(initiativeDir);\n const loops = await deriveOpenLoops(initiativeDir, { now, tasks });\n\n return loops\n .filter((loop) => loop.ageDays > limits.openLoopMaxAgeDays)\n .map((loop) => ({\n level: 'warn',\n slug,\n file: path.posix.join('sessions', `${loop.sessionFile}.md`),\n message: `open loop ${loop.ref} (\"${loop.text}\") is ${loop.ageDays} days old (> ${limits.openLoopMaxAgeDays}) — ${staleLoopAdvice(loop.kind)}`,\n }));\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport YAML from 'yaml';\nimport { DEFAULT_LIMITS, type LintFinding, type LintLimits } from './types.js';\n\nfunction countNotesLines(notes: string): number {\n const lines = notes.split('\\n');\n while (lines.length > 0 && lines[lines.length - 1].trim() === '') {\n lines.pop();\n }\n return lines.length;\n}\n\nasync function listTaskFiles(tasksDir: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(tasksDir);\n return entries.filter((n) => n.endsWith('.yml')).sort();\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') return [];\n throw err;\n }\n}\n\n/**\n * Walk `tasks/*.yml` and warn when a task's `notes` field exceeds the limit.\n *\n * Files that fail to parse are silently skipped — those are hard failures\n * surfaced by reader-side schema validation elsewhere; lint is warn-only.\n */\nexport async function lintTasks(\n slug: string,\n initiativeDir: string,\n limits: LintLimits = DEFAULT_LIMITS,\n): Promise<LintFinding[]> {\n const tasksDir = path.join(initiativeDir, 'tasks');\n const files = await listTaskFiles(tasksDir);\n const findings: LintFinding[] = [];\n\n for (const filename of files) {\n const filePath = path.join(tasksDir, filename);\n let raw: string;\n try {\n raw = await fs.readFile(filePath, 'utf8');\n } catch {\n continue;\n }\n\n let parsed: unknown;\n try {\n parsed = YAML.parse(raw);\n } catch {\n continue;\n }\n\n if (!parsed || typeof parsed !== 'object') continue;\n const record = parsed as Record<string, unknown>;\n const notes = record.notes;\n if (typeof notes !== 'string' || notes.length === 0) continue;\n\n const lineCount = countNotesLines(notes);\n if (lineCount <= limits.taskNotesMaxLines) continue;\n\n const id = typeof record.id === 'string' ? record.id : filename.replace(/\\.yml$/, '');\n findings.push({\n level: 'warn',\n slug,\n file: path.posix.join('tasks', filename),\n message: `task ${id} notes are ${lineCount} lines — consider summarizing into done_when or a sources/ file`,\n });\n }\n\n return findings;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport YAML from 'yaml';\nimport { SessionFrontmatterSchema, type SessionFrontmatter } from '../schemas/session.js';\nimport type { LintFinding } from './types.js';\n\nconst FRONTMATTER_DELIM = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/;\n\nasync function readSessionFrontmatter(filePath: string): Promise<SessionFrontmatter | null> {\n let raw: string;\n try {\n raw = await fs.readFile(filePath, 'utf8');\n } catch {\n return null;\n }\n const match = FRONTMATTER_DELIM.exec(raw);\n if (!match) return null;\n let parsed: unknown;\n try {\n parsed = YAML.parse(match[1] ?? '');\n } catch {\n return null;\n }\n const result = SessionFrontmatterSchema.safeParse(parsed);\n return result.success ? result.data : null;\n}\n\n/**\n * Warn when a session records an empty ledger — no `next_steps`, no\n * `resolves` — without the `no_loops` marker.\n *\n * An unmarked empty ledger is indistinguishable from a wrap that simply\n * forgot to file anything; `no_loops: true` (written by `wrap --no-loops`) is\n * the only way to say \"deliberately clear\" instead. `track: 'sidecar'` is\n * exempt: `fold` writes sidecar sessions to import already-discovered work,\n * not to record a wrap-up, so every one of them has an empty ledger with no\n * marker by construction — warning on those would be permanent, unactionable\n * noise.\n *\n * Malformed session files are skipped: this rule is warn-only and must never\n * throw on a broken initiative.\n */\nexport async function lintZeroLoops(slug: string, initiativeDir: string): Promise<LintFinding[]> {\n const sessionsDir = path.join(initiativeDir, 'sessions');\n let entries: string[];\n try {\n entries = await fs.readdir(sessionsDir);\n } catch {\n return [];\n }\n\n const findings: LintFinding[] = [];\n for (const filename of entries.filter((n) => n.endsWith('.md')).sort()) {\n const frontmatter = await readSessionFrontmatter(path.join(sessionsDir, filename));\n if (!frontmatter || frontmatter.track === 'sidecar' || frontmatter.no_loops === true) {\n continue;\n }\n if (frontmatter.next_steps.length > 0 || frontmatter.resolves.length > 0) continue;\n\n findings.push({\n level: 'warn',\n slug,\n file: path.posix.join('sessions', filename),\n message:\n 'session recorded an empty ledger (no next_steps, no resolves) without no_loops: true — ' +\n 're-wrap with --no-loops if that was deliberate, or file the loops that were missed',\n });\n }\n return findings;\n}\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { UsageError } from '../errors.js';\nimport { CURRENT_VERSION } from '../migrations/index.js';\nimport { applyV2ToV3, planV2ToV3 } from '../migrations/v2-to-v3-open-loops.js';\nimport { readSchemaVersion, writeSchemaVersion } from '../schemas/state.js';\nimport { color } from '../utils/color.js';\n\n/**\n * `active-work migrate --dry-run` — report exactly what the pending v2→v3\n * open-loops migration would change, per initiative, writing nothing.\n *\n * The migration otherwise runs unattended under `active-work setup`, which is\n * the only command that migrates — no ordinary command does. This surface\n * exists because v3 rewrites session history: it is reviewed before it runs,\n * and a dry run is the review artifact. Applying is opt-in (`--apply`) so the\n * command cannot mutate data by being run bare.\n */\n\nconst ArgsSchema = z.object({\n dry_run: z.boolean().optional(),\n apply: z.boolean().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst SessionSchema = z.object({\n kind: z.enum(['open', 'abandon']),\n action: z.enum(['write', 'exists']),\n file: z.string(),\n ended: z.string(),\n loops: z.number().int().nonnegative(),\n resolves: z.number().int().nonnegative(),\n});\n\nconst InitiativeSchema = z.object({\n slug: z.string(),\n sessions: z.array(SessionSchema),\n task_seq_backfill: z.number().int().positive().nullable(),\n brief_repairs: z.array(z.string()),\n brief_blocked: z.string().optional(),\n handoff: z.enum(['archive-and-remove', 'archive-exists', 'absent']),\n note: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n applied: z.boolean(),\n proposal: z.string(),\n initiatives: z.array(InitiativeSchema),\n repairs: z.array(z.object({ action: z.string(), file: z.string(), detail: z.string() })),\n uncovered: z.array(z.string()),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\ntype Initiative = z.infer<typeof InitiativeSchema>;\n\nfunction describe(plan: Awaited<ReturnType<typeof planV2ToV3>>, applied: boolean): Result {\n const initiatives: Initiative[] = plan.initiatives.map((i) => ({\n slug: i.slug,\n sessions: i.sessions.map((s) => ({\n kind: s.kind,\n action: s.exists ? ('exists' as const) : ('write' as const),\n file: s.path,\n ended: s.frontmatter.ended,\n loops: s.frontmatter.next_steps.length,\n resolves: s.frontmatter.resolves.length,\n })),\n task_seq_backfill: i.brief?.taskSeq ?? null,\n brief_repairs: i.brief?.repairs ?? [],\n ...(i.briefBlocked === undefined ? {} : { brief_blocked: i.briefBlocked }),\n handoff: i.handoff,\n ...(i.uncoveredReason === undefined ? {} : { note: i.uncoveredReason }),\n }));\n return {\n applied,\n proposal: plan.proposalOrigin,\n initiatives,\n repairs: plan.repairs.map((r) => ({\n action: r.action,\n file: r.file,\n detail: r.detail,\n })),\n uncovered: initiatives.filter((i) => i.sessions.length === 0).map((i) => i.slug),\n };\n}\n\nfunction renderSession(s: Initiative['sessions'][number]): string {\n const what = s.kind === 'open' ? `opens ${s.loops} loop(s)` : `abandons ${s.resolves} loop(s)`;\n const verb = s.action === 'exists' ? 'already present — skip' : 'write';\n return `session (${s.kind}) ${verb}: ${s.file} — ${what}, ended ${s.ended}`;\n}\n\nfunction renderInitiative(i: Initiative): string {\n const parts: string[] = i.sessions.map(renderSession);\n if (i.sessions.length === 0) {\n parts.push(color.yellow(`NO SYNTHETIC SESSION — ${i.note}`));\n }\n for (const repair of i.brief_repairs) parts.push(`brief repair: ${repair}`);\n if (i.task_seq_backfill !== null) parts.push(`task_seq -> ${i.task_seq_backfill}`);\n if (i.brief_blocked !== undefined) {\n parts.push(color.yellow(`brief NOT rewritten — ${i.brief_blocked}`));\n }\n if (i.handoff === 'archive-and-remove') {\n parts.push('handoff.md -> sources/handoff-archive.md, then delete');\n }\n if (i.handoff === 'archive-exists') {\n parts.push(color.yellow('handoff.md kept — sources/handoff-archive.md already exists'));\n }\n if (parts.length === 0) parts.push('nothing to do');\n return ` ${color.bold(i.slug)}\\n${parts.map((p) => ` - ${p}`).join('\\n')}`;\n}\n\nfunction render(result: Result): string {\n const lines = [\n color.bold(result.applied ? 'active-work migrate (applied)' : 'active-work migrate --dry-run'),\n ` proposal: ${result.proposal}`,\n ...result.initiatives.map(renderInitiative),\n color.bold(' repairs'),\n ...result.repairs.map((r) => ` - ${r.action}: ${r.file} — ${r.detail}`),\n ];\n if (result.uncovered.length > 0) {\n lines.push(\n color.yellow(\n ` ${result.uncovered.length} initiative(s) have no proposal entry and will keep ` +\n `their next-actions only in sources/handoff-archive.md: ${result.uncovered.join(', ')}`,\n ),\n );\n }\n return lines.join('\\n') + '\\n';\n}\n\nexport default defineCommand<Args, Result>({\n name: 'migrate',\n description: 'Preview (or apply) the pending v2→v3 open-loops migration.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n dry_run: { long: '--dry-run', description: 'Report what would change; write nothing' },\n apply: { long: '--apply', description: 'Actually run the migration' },\n },\n usage: 'active-work migrate --dry-run | --apply',\n },\n async run(args, ctx) {\n if (args.apply !== true) {\n const plan = await planV2ToV3(ctx.activeRoot);\n const result = describe(plan, false);\n if (ctx.format !== 'json') process.stderr.write(render(result));\n return result;\n }\n if (args.dry_run === true) {\n throw new UsageError('--dry-run and --apply are mutually exclusive');\n }\n // This command runs one step of the chain. Stamping v3 over data that has\n // not been through v1→v2 would strand the artifacts migration forever.\n const before = await readSchemaVersion(ctx.activeRoot);\n if (before !== CURRENT_VERSION - 1) {\n throw new UsageError(\n `--apply runs only the v2→v3 step, but this root is at schema v${before}. ` +\n 'Run `active-work setup` to work through the pending chain first — it is ' +\n 'the only command that migrates; ordinary commands (`list`, `open`, …) ' +\n 'do not.',\n );\n }\n const plan = await planV2ToV3(ctx.activeRoot);\n await applyV2ToV3(ctx.activeRoot, plan);\n await writeSchemaVersion(ctx.activeRoot, CURRENT_VERSION);\n const result = describe(plan, true);\n if (ctx.format !== 'json') process.stderr.write(render(result));\n return result;\n },\n});\n","import os from 'node:os';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { ActiveWorkError, UsageError } from '../errors.js';\nimport { getGitRunner, type CommandResult } from '../utils/git-gh.js';\nimport { color } from '../utils/color.js';\n\n/**\n * `active-work sync` — multi-machine git sync for the active root (AW-5).\n *\n * Runs `git pull --rebase && git push` from inside the active root so a\n * git-backed workspace stays in step across machines. Uncommitted local edits\n * are auto-committed first (this is the normal state — you just touched a\n * task), and rebase conflicts are surfaced clearly and left in place for the\n * user to resolve rather than silently aborted.\n */\n\nconst ArgsSchema = z.object({\n message: z.string().min(1).optional(),\n require_clean: z.boolean().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n branch: z.string(),\n committed: z.boolean(),\n committed_files: z.number().int(),\n rebased: z.boolean(),\n pushed: z.boolean(),\n summary: z.string(),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nexport { setGitRunner, resetRunners } from '../utils/git-gh.js';\n\n/** Run git in the active root; timeouts/spawn failures become clear errors. */\nasync function git(root: string, args: string[]): Promise<CommandResult> {\n return getGitRunner()('git', ['-C', root, ...args]);\n}\n\nasync function assertGitRepo(root: string): Promise<void> {\n let res: CommandResult;\n try {\n res = await git(root, ['rev-parse', '--is-inside-work-tree']);\n } catch (err) {\n throw new ActiveWorkError(\n `could not run git in ${root}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (res.code !== 0 || res.stdout.trim() !== 'true') {\n throw new UsageError(\n `active root is not a git repository: ${root}\\n` +\n 'Initialize it and add a remote, then retry:\\n' +\n ` git -C \"${root}\" init && git -C \"${root}\" remote add origin <url>`,\n );\n }\n}\n\nasync function currentBranch(root: string): Promise<string> {\n const res = await git(root, ['rev-parse', '--abbrev-ref', 'HEAD']);\n const branch = res.stdout.trim();\n if (res.code !== 0 || !branch || branch === 'HEAD') {\n throw new UsageError(\n 'could not determine the current branch (detached HEAD?). ' +\n 'Check out a branch before syncing.',\n );\n }\n return branch;\n}\n\nasync function assertUpstream(root: string, branch: string): Promise<void> {\n const res = await git(root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);\n if (res.code !== 0) {\n throw new UsageError(\n `branch \"${branch}\" has no upstream configured.\\n` +\n `Set one, then retry:\\n` +\n ` git -C \"${root}\" push -u origin ${branch}`,\n );\n }\n}\n\n/** True when the working tree (tracked or untracked) has changes to commit. */\nasync function isDirty(root: string): Promise<boolean> {\n const res = await git(root, ['status', '--porcelain']);\n return res.stdout.trim().length > 0;\n}\n\nfunction defaultMessage(): string {\n return `aw sync: ${new Date().toISOString()} (${os.hostname()})`;\n}\n\n/** Stage and commit everything. Returns the number of files committed. */\nasync function commitAll(root: string, message: string): Promise<number> {\n const add = await git(root, ['add', '-A']);\n if (add.code !== 0) {\n throw new ActiveWorkError(`git add failed: ${add.stderr.trim() || 'unknown error'}`);\n }\n // Nothing actually staged (e.g. only ignored files touched) — skip commit.\n const staged = await git(root, ['diff', '--cached', '--name-only']);\n const files = staged.stdout.trim().split('\\n').filter(Boolean);\n if (files.length === 0) return 0;\n\n const commit = await git(root, ['commit', '-m', message]);\n if (commit.code !== 0) {\n throw new ActiveWorkError(`git commit failed: ${commit.stderr.trim() || 'unknown error'}`);\n }\n return files.length;\n}\n\n/** Names of files with unresolved merge conflicts. */\nasync function conflictedFiles(root: string): Promise<string[]> {\n const res = await git(root, ['diff', '--name-only', '--diff-filter=U']);\n return res.stdout.trim().split('\\n').filter(Boolean);\n}\n\nasync function headSha(root: string): Promise<string> {\n return (await git(root, ['rev-parse', 'HEAD'])).stdout.trim();\n}\n\nasync function pullRebase(root: string): Promise<{ rebased: boolean }> {\n // Compare HEAD before/after rather than scraping git's (version-dependent)\n // \"up to date\" wording: HEAD moves iff upstream actually had new commits.\n const before = await headSha(root);\n const res = await git(root, ['pull', '--rebase']);\n if (res.code === 0) {\n return { rebased: (await headSha(root)) !== before };\n }\n\n const conflicts = await conflictedFiles(root);\n if (conflicts.length > 0) {\n throw new ActiveWorkError(\n 'sync stopped on a rebase conflict — your local changes are committed and safe.\\n' +\n `Conflicted files:\\n${conflicts.map((f) => ` - ${f}`).join('\\n')}\\n` +\n 'Resolve them, then either continue or undo:\\n' +\n ` git -C \"${root}\" add <files> && git -C \"${root}\" rebase --continue && aw sync\\n` +\n ` git -C \"${root}\" rebase --abort # to undo the pull`,\n );\n }\n throw new ActiveWorkError(\n `git pull --rebase failed: ${res.stderr.trim() || res.stdout.trim() || 'unknown error'}`,\n );\n}\n\nasync function push(root: string): Promise<void> {\n const res = await git(root, ['push']);\n if (res.code !== 0) {\n throw new ActiveWorkError(\n `git push failed: ${res.stderr.trim() || res.stdout.trim() || 'unknown error'}`,\n );\n }\n}\n\nexport default defineCommand<Args, Result>({\n name: 'sync',\n description: 'Sync the active root over git: auto-commit local edits, pull --rebase, then push.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n message: {\n long: '--message',\n short: '-m',\n description: 'Commit message for the auto-commit (default: timestamp + host)',\n },\n require_clean: {\n long: '--require-clean',\n description: 'Fail instead of auto-committing when the tree is dirty',\n },\n },\n },\n async run(args, ctx) {\n const root = ctx.activeRoot;\n await assertGitRepo(root);\n const branch = await currentBranch(root);\n await assertUpstream(root, branch);\n\n let committed = false;\n let committedFiles = 0;\n if (await isDirty(root)) {\n if (args.require_clean) {\n throw new UsageError(\n 'active root has uncommitted changes and --require-clean was given.\\n' +\n 'Commit or stash them, or drop --require-clean to auto-commit.',\n );\n }\n committedFiles = await commitAll(root, args.message ?? defaultMessage());\n committed = committedFiles > 0;\n }\n\n const { rebased } = await pullRebase(root);\n await push(root);\n\n const summary =\n `${committed ? `committed ${committedFiles} file(s), ` : ''}` +\n `${rebased ? 'rebased onto upstream, ' : 'already up to date, '}` +\n 'pushed';\n const result: Result = {\n branch,\n committed,\n committed_files: committedFiles,\n rebased,\n pushed: true,\n summary,\n };\n\n if (ctx.format !== 'json') {\n process.stderr.write(color.green(`✓ sync (${branch}): ${summary}`) + '\\n');\n }\n return result;\n },\n});\n","/**\n * Imports every command module and registers its default export with the\n * shared registry. The CLI dispatcher (Wave 3.1) and MCP server (Wave 3.2)\n * import this module first so the registry is populated.\n *\n * Order doesn't affect runtime behavior (the registry is a Map keyed by\n * command name), but is kept alphabetical for readability.\n */\nimport { register, type AnyCommand } from '../registry/index.js';\n\n// Lifecycle\nimport archive from './archive.js';\nimport cmdNew from './new.js';\nimport paths from './paths.js';\nimport rename from './rename.js';\nimport set from './set.js';\nimport touch from './touch.js';\n\n// Focus / pause\nimport focus from './focus.js';\nimport pause from './pause.js';\nimport unfocus from './unfocus.js';\nimport unpause from './unpause.js';\n\n// Tasks\nimport taskAdd from './task-add.js';\nimport taskDelete from './task-delete.js';\nimport taskDone from './task-done.js';\nimport taskEdit from './task-edit.js';\nimport taskList from './task-list.js';\nimport taskReorder from './task-reorder.js';\n\n// Sessions\nimport loops from './loops.js';\nimport preflight from './preflight.js';\nimport sessionList from './session-list.js';\nimport sessionsBrowser from './sessions-browser.js';\nimport wrap from './wrap.js';\n\n// Notes\nimport noteAdd from './note-add.js';\nimport noteList from './note-list.js';\n\n// Sources / artifacts\nimport artifactAddBranch from './artifact-add-branch.js';\nimport artifactAddStash from './artifact-add-stash.js';\nimport artifactList from './artifact-list.js';\nimport artifactNote from './artifact-note.js';\nimport artifactPrune from './artifact-prune.js';\nimport artifactStatus from './artifact-status.js';\nimport sourceAdd from './source-add.js';\nimport sourceList from './source-list.js';\n\n// Worktree / cross-initiative reads\nimport audit from './audit.js';\nimport contextGraph from './context-graph.js';\nimport list from './list.js';\nimport worktreeSet from './worktree-set.js';\nimport worktreeSetDefault from './worktree-set-default.js';\n\n// Discover / triage\nimport discover from './discover.js';\nimport drop from './drop.js';\nimport fold from './fold.js';\nimport track from './track.js';\n\n// Bootstrap / picker\nimport open from './open.js';\nimport prompt from './prompt.js';\n\n// Editor\nimport edit from './edit.js';\n\n// MCP server\nimport mcpServe from './mcp-serve.js';\nimport mcpStop from './mcp-stop.js';\nimport mcpRestart from './mcp-restart.js';\nimport mcpStatus from './mcp-status.js';\nimport mcpLogs from './mcp-logs.js';\n\n// Setup / uninstall\nimport setup from './setup.js';\nimport uninstall from './uninstall.js';\nimport doctor from './doctor.js';\nimport migrate from './migrate.js';\nimport sync from './sync.js';\n\nconst ALL_COMMANDS: AnyCommand[] = [\n // lifecycle\n cmdNew,\n set,\n touch,\n paths,\n rename,\n archive,\n // focus / pause\n focus,\n unfocus,\n pause,\n unpause,\n // tasks\n taskAdd,\n taskDone,\n taskList,\n taskEdit,\n taskReorder,\n taskDelete,\n // sessions\n sessionList,\n sessionsBrowser,\n loops,\n preflight,\n wrap,\n // notes\n noteAdd,\n noteList,\n // sources / artifacts\n sourceAdd,\n sourceList,\n artifactAddBranch,\n artifactAddStash,\n artifactList,\n artifactStatus,\n artifactPrune,\n artifactNote,\n // worktree / cross-initiative\n worktreeSet,\n worktreeSetDefault,\n audit,\n list,\n contextGraph,\n // discover / triage\n discover,\n fold,\n drop,\n track,\n // bootstrap\n open,\n prompt,\n // editor\n edit,\n // mcp server\n mcpServe,\n mcpStop,\n mcpRestart,\n mcpStatus,\n mcpLogs,\n // setup / uninstall\n setup,\n uninstall,\n doctor,\n migrate,\n sync,\n];\n\nfor (const cmd of ALL_COMMANDS) {\n register(cmd);\n}\n\nexport { ALL_COMMANDS };\n","/**\n * Reading registry options back out of commander's parsed opts.\n *\n * Lives apart from `src/cli.ts` because that module invokes `main()` on\n * import and so cannot be pulled into a unit test.\n */\n\n/** commander camelCases long flag names, dropping the leading `--`. */\nexport function camelizeFlagKey(flagKey: string): string {\n return flagKey.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());\n}\n\n/**\n * Read one registry option out of commander's parsed opts.\n *\n * commander implements `--no-thing` as the *negation* of `--thing`: it stores\n * `false` under `thing` and never defines a `noThing` key at all. A registry\n * flag declared as `--no-x` therefore has to be read back off `x === false`.\n * Reading it by its own name — which is what this used to do — always yielded\n * `undefined`, so every `--no-*` flag silently did nothing when passed on the\n * CLI, while working fine over MCP where args arrive already structured.\n * `wrap --no-loops` shipped broken for exactly this reason.\n *\n * The paired value flag must also ignore that `false`, or `--no-notes` would\n * be handed to `--notes` as a boolean and fail schema validation instead.\n */\nexport function readCommanderOption(\n opts: Record<string, unknown>,\n long: string,\n flagToKey: (long: string) => string,\n): unknown {\n if (long.startsWith('--no-')) {\n const stem = camelizeFlagKey(flagToKey(`--${long.slice('--no-'.length)}`));\n return opts[stem] === false ? true : undefined;\n }\n const flagKey = flagToKey(long);\n const value = opts[camelizeFlagKey(flagKey)] ?? opts[flagKey];\n return value === false ? undefined : value;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { getStateRoot } from './paths.js';\n\n/**\n * Single line in `$XDG_STATE_HOME/active-work/usage.jsonl`.\n *\n * The log is fire-and-forget telemetry written by the CLI dispatcher for\n * later self-reflection. Failures to write must never break the user's\n * command, so `appendUsage` swallows all errors.\n */\nexport interface UsageRecord {\n ts: string; // ISO 8601\n command: string; // registry name\n args?: Record<string, unknown>;\n duration_ms?: number;\n success: boolean;\n exit_code: number;\n}\n\n/** Resolve the on-disk path of the usage log. */\nexport function usageLogPath(): string {\n return path.join(getStateRoot(), 'usage.jsonl');\n}\n\n/**\n * Append a single JSON-encoded record + newline to the usage log.\n *\n * Silent on any error: telemetry must never fail a user-facing command.\n */\nexport async function appendUsage(rec: UsageRecord): Promise<void> {\n try {\n const file = usageLogPath();\n await fs.mkdir(path.dirname(file), { recursive: true });\n await fs.appendFile(file, JSON.stringify(rec) + '\\n', 'utf8');\n } catch {\n // Intentionally silent.\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,SAAS,sBAAsB;;;ACDxC,SAAS,YAAY,UAAU;AAC/B,OAAO,UAAU;AACjB,SAAS,SAAS;AAIlB,IAAM,aAAa,EAAE,OAAO;AAAA,EAC1B,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACtB,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC;AAC1B,CAAC;AAED,IAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,MAAM,EAAE,OAAO;AAAA,EACf,IAAI,EAAE,OAAO;AACf,CAAC;AAED,eAAe,UAAU,GAA6B;AACpD,MAAI;AACF,UAAM,OAAO,MAAM,GAAG,KAAK,CAAC;AAC5B,WAAO,KAAK,YAAY;AAAA,EAC1B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAA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AM,QAAQ,WAAW,IAAI;AAAA,EAC/B,SAAS,KAAK;AACZ,QAAI,eAAe,gBAAgB;AAEjC,UAAI,IAAI,SAAS,6BAA6B,IAAI,SAAS,qBAAqB;AAC9E,gBAAQ,KAAK,CAAC;AAAA,MAChB;AACA,cAAQ,KAAK,KAAK,KAAK;AAAA,IACzB;AACA,UAAM,EAAE,SAAS,KAAK,IAAI,YAAY,GAAG;AACzC,cAAU,SAAS,MAAM,OAAO;AAChC,YAAQ,KAAK,IAAI;AAAA,EACnB;AACF;AAEA,KAAK,KAAK,QAAQ,IAAI;","names":["fs","path","z","ArgsSchema","z","ResultSchema","dirExists","fs","path","fs","path","z","ArgsSchema","z","ResultSchema","path","fs","fs","path","z","ArgsSchema","z","ResultSchema","dirExists","fs","path","fs","path","z","ArgsSchema","z","ResultSchema","path","fs","fs","path","z","ArgsSchema","z","ResultSchema","path","fs","z","fs","path","fs","path","ArgsSchema","z","ResultSchema","z","z","ArgsSchema","ResultSchema","applyLocked","z","ArgsSchema","z","ResultSchema","applyLocked","z","ArgsSchema","z","ResultSchema","fs","path","z","ArgsSchema","z","path","fs","fs","path","z","ArgsSchema","z","ResultSchema","path","fs","path","z","ArgsSchema","z","path","path","z","ArgsSchema","z","path","fs","path","z","z","ArgsSchema","ResultSchema","fs","path","fs","path","z","ArgsSchema","z","ResultSchema","path","fs","path","z","fs","path","path","fs","ArgsSchema","z","ResultSchema","path","fs","path","z","fs","path","path","git","path","fs","ArgsSchema","z","ResultSchema","path","fs","fs","path","z","matter","ArgsSchema","z","ResultSchema","fs","matter","path","fs","path","z","ArgsSchema","z","SessionEntrySchema","ResultSchema","DEFAULT_LIMIT","path","fs","root","sessions","fs","path","z","fs","path","path","fs","z","ArgsSchema","ResultSchema","fs","path","fs","path","z","ArgsSchema","z","ResultSchema","fs","path","z","ArgsSchema","z","ResultSchema","path","z","ArgsSchema","z","ResultSchema","artifactsPath","path","path","z","ArgsSchema","z","ResultSchema","artifactsPath","path","fs","path","z","ArgsSchema","z","ResultSchema","artifactsPath","path","fs","path","z","ArgsSchema","z","ResultSchema","artifactsPath","path","path","z","ArgsSchema","z","ResultSchema","git","artifactsPath","path","path","z","ArgsSchema","z","ResultSchema","git","artifactsPath","path","z","fs","path","fs","path","fs","path","ArgsSchema","z","ResultSchema","path","fs","z","z","fs","path","fs","path","z","ArgsSchema","z","ResultSchema","listSlugs","fs","path","z","argsSchema","z","parseErrorSchema","resultSchema","path","z","argsSchema","z","resultSchema","path","path","z","argsSchema","z","resultSchema","path","z","fs","path","path","path","parseWorktreePorcelain","fs","path","path","fs","fs","os","path","truncate","fs","path","ArgsSchema","z","ResultSchema","z","fs","path","fs","path","ArgsSchema","z","ResultSchema","fs","path","z","ArgsSchema","z","ResultSchema","fs","path","fs","path","z","ArgsSchema","z","ResultSchema","dirExists","fs","path","z","ArgsSchema","z","fs","path","spawn","z","ArgsSchema","z","ResultSchema","spawn","path","fileExists","fs","spawn","z","z","z","z","fs","path","body","z","path","path","fs","path","ArgsSchema","z","ResultSchema","spawn","z","ArgsSchema","z","ResultSchema","spawn","z","ArgsSchema","z","ResultSchema","SHUTDOWN_TIMEOUT_MS","POLL_INTERVAL_MS","waitForExit","detachedSpawn","spawn","z","ArgsSchema","z","ResultSchema","fs","path","z","ArgsSchema","z","ResultSchema","path","fs","z","fsp","nodePath","nodeSpawn","os","fileURLToPath","fs","path","fs","path","fs","path","fs","z","z","fs","fs","path","path","exists","fs","path","fs","listInitiativeSlugs","maxOnDiskTaskNumber","fs","path","matter","YAML","path","readArtifacts","YAML","fs","migrateOne","matter","artifactsPath","path","os","fs","spawn","fsp","nodePath","nodeSpawn","os","resolveLocalDeps","fs","fsp","spawn","nodeSpawn","os","nodePath","runOnce","nodePath","fileURLToPath","fs","fsp","spawn","nodeSpawn","os","fs","nodePath","exists","pathExists","runOnce","spawn","ArgsSchema","z","ResultSchema","z","ArgsSchema","z","StepSchema","ResultSchema","z","fsp","nodePath","os","fs","path","fs","path","fs","path","fs","path","path","fs","path","YAML","fs","path","YAML","listInitiativeSlugs","fs","fileExists","fs","nodePath","fsp","os","listInitiativeSlugs","ArgsSchema","z","ResultSchema","z","ArgsSchema","z","ResultSchema","plan","result","os","z","ArgsSchema","z","ResultSchema","os","flagToKey","fs","path","path","fs"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/commands/archive.ts","../src/commands/new.ts","../src/utils/slug.ts","../src/commands/paths.ts","../src/commands/rename.ts","../src/commands/set.ts","../src/commands/touch.ts","../src/commands/focus.ts","../src/commands/_focus-helpers.ts","../src/commands/pause.ts","../src/commands/unfocus.ts","../src/commands/unpause.ts","../src/commands/task-add.ts","../src/utils/task-seq.ts","../src/commands/task-delete.ts","../src/commands/task-done.ts","../src/commands/task-edit.ts","../src/commands/task-list.ts","../src/commands/task-reorder.ts","../src/commands/loops.ts","../src/lint/load-tasks.ts","../src/commands/preflight.ts","../src/wrap/sweep.ts","../src/utils/git-worktrees.ts","../src/commands/session-list.ts","../src/commands/sessions-browser.ts","../src/commands/wrap.ts","../src/sessions/session-file.ts","../src/commands/note-add.ts","../src/commands/note-list.ts","../src/commands/artifact-add-branch.ts","../src/commands/artifact-add-stash.ts","../src/commands/artifact-list.ts","../src/commands/artifact-note.ts","../src/commands/artifact-prune.ts","../src/commands/artifact-status.ts","../src/commands/source-list.ts","../src/sources/list.ts","../src/lint/sources.ts","../src/commands/audit.ts","../src/commands/context-graph.ts","../src/commands/list.ts","../src/commands/worktree-set.ts","../src/commands/worktree-set-default.ts","../src/commands/discover.ts","../src/discover/index.ts","../src/discover/run-command.ts","../src/discover/github.ts","../src/discover/git.ts","../src/discover/projects.ts","../src/discover/claude.ts","../src/commands/drop.ts","../src/discover/triaged-log.ts","../src/commands/fold.ts","../src/commands/track.ts","../src/commands/prompt.ts","../src/commands/edit.ts","../src/commands/mcp-serve.ts","../src/server/mcp.ts","../src/server/health.ts","../src/server/daemon.ts","../src/server/dashboard-routes.ts","../src/server/logger.ts","../src/server/session-index-watch.ts","../src/session-index/graph.ts","../src/session-index/refresh.ts","../src/session-index/tasks.ts","../src/session-index/scheduler.ts","../src/commands/mcp-stop.ts","../src/commands/mcp-restart.ts","../src/commands/mcp-status.ts","../src/commands/mcp-logs.ts","../src/commands/miner-drain-ingest.ts","../src/drain/transcript-reader.ts","../src/drain/ingestor.ts","../src/drain/store.ts","../src/schemas/template.ts","../src/drain/tree-store.ts","../src/drain/blob-extract.ts","../src/drain/partition.ts","../src/drain/reader-state.ts","../src/commands/miner-refresh.ts","../src/commands/miner-liveness.ts","../src/session-index/liveness.ts","../src/commands/miner-status.ts","../src/commands/hooks-agent-chat-spawn.ts","../src/utils/read-stdin-json.ts","../src/utils/agent-chat-hook-state.ts","../src/commands/hooks-agent-chat-complete.ts","../src/commands/setup.ts","../src/setup/steps.ts","../src/schemas/state.ts","../src/migrations/v1-to-v2-artifacts.ts","../src/migrations/v2-to-v3-open-loops.ts","../src/migrations/v3-proposal.ts","../src/migrations/data/v3-open-loops-proposal.ts","../src/migrations/v3-repairs.ts","../src/migrations/v3-to-v4-worktrees.ts","../src/migrations/index.ts","../src/setup/supervision-systemd.ts","../src/setup/supervision-launchd.ts","../src/setup/supervision.ts","../src/commands/uninstall.ts","../src/commands/doctor.ts","../src/doctor.ts","../src/lint/index.ts","../src/lint/brief.ts","../src/lint/hashes.ts","../src/lint/open-loops.ts","../src/lint/task.ts","../src/lint/zero-loops.ts","../src/commands/migrate.ts","../src/commands/sync.ts","../src/commands/index.ts","../src/utils/usage-log.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command, CommanderError } from 'commander';\nimport type { ZodSchema, ZodTypeAny } from 'zod';\nimport { registry } from './registry/index.js';\nimport './commands/index.js'; // populates the registry via side effect\nimport { getActiveRoot } from './utils/paths.js';\nimport { formatError, EXIT } from './errors.js';\nimport {\n successEnvelope,\n errorEnvelope,\n type AnyCommand,\n type CliMeta,\n type CommandContext,\n} from './registry/index.js';\nimport { readCommanderOption } from '@titan-design/registry';\nimport { color } from './utils/color.js';\nimport { appendUsage } from './utils/usage-log.js';\n\n/**\n * Look up the inner zod type, skipping optional/nullable/default wrappers.\n *\n * Returns the unwrapped def type string (e.g. `'string'`, `'number'`,\n * `'array'`, `'boolean'`, `'enum'`) so the dispatcher can decide how to\n * coerce a raw commander value before zod parsing.\n */\nfunction unwrapZodType(schema: ZodTypeAny | undefined): string | undefined {\n if (!schema) return undefined;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let def = (schema as any)?._zod?.def;\n while (def && (def.type === 'optional' || def.type === 'nullable' || def.type === 'default')) {\n def = def.innerType?._zod?.def;\n }\n return def?.type as string | undefined;\n}\n\n/**\n * Pull the per-field zod schema out of a top-level `z.object({...})`.\n *\n * Returns `undefined` when the schema isn't an object or the field is\n * absent — callers fall back to treating the value as a plain string.\n */\nfunction fieldSchema(args: ZodSchema, name: string): ZodTypeAny | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const shape = (args as any)?._zod?.def?.shape;\n if (!shape) return undefined;\n return shape[name] as ZodTypeAny | undefined;\n}\n\n/** Coerce a raw commander value (string | boolean | undefined) to the type implied by zod. */\nfunction coerce(value: unknown, zodType: string | undefined): unknown {\n if (value === undefined) return undefined;\n if (zodType === 'boolean') {\n return value === true || value === 'true';\n }\n if (zodType === 'number') {\n if (typeof value === 'number') return value;\n const n = Number(value);\n return Number.isNaN(n) ? value : n;\n }\n if (zodType === 'array') {\n if (Array.isArray(value)) return value;\n return String(value)\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n return value;\n}\n\n/** Split a registry command name like `task.add` into commander sub-command path parts. */\nfunction splitName(name: string): string[] {\n return name.split('.');\n}\n\n/**\n * Walk/create a chain of `commander` sub-commands for the given group\n * parts (e.g. `['task']` for `task.add`). Returns the leaf parent so the\n * caller can attach the final action sub-command.\n */\nfunction ensureGroup(root: Command, parts: string[]): Command {\n let current = root;\n for (const part of parts) {\n const existing = current.commands.find((c) => c.name() === part);\n if (existing) {\n current = existing;\n continue;\n }\n const next = current.command(part).description(`${part} commands`);\n current = next;\n }\n return current;\n}\n\ninterface InvocationOutput {\n exitCode: number;\n success: boolean;\n}\n\nasync function emitSuccess(cmd: AnyCommand, result: unknown, ctx: CommandContext): Promise<void> {\n if (ctx.format === 'json') {\n process.stdout.write(JSON.stringify(successEnvelope(result, ctx.warnings)) + '\\n');\n return;\n }\n // Human mode: a bare string result is printed raw (e.g. `prompt` dumps the\n // bootstrap text); everything else is pretty-printed JSON for now. Commands\n // can layer richer output later by checking ctx.format themselves.\n if (typeof result === 'string') {\n process.stdout.write(result.endsWith('\\n') ? result : result + '\\n');\n } else if (result !== undefined && result !== null) {\n process.stdout.write(JSON.stringify(result, null, 2) + '\\n');\n }\n // Touch cmd to avoid an unused-parameter warning when extending later.\n void cmd;\n}\n\nfunction emitError(message: string, code: number, format: 'human' | 'json'): void {\n if (format === 'json') {\n process.stdout.write(JSON.stringify(errorEnvelope(message, code)) + '\\n');\n return;\n }\n process.stderr.write(color.red('error: ' + message) + '\\n');\n}\n\n/**\n * Build the action handler for a single registry command.\n *\n * Captures positionals + options into a plain object, coerces values to\n * the types implied by the command's zod schema, runs the schema, then\n * invokes `cmd.run`. Always writes a usage-log line and exits with the\n * appropriate sysexits code.\n */\nfunction makeAction(\n cmd: AnyCommand,\n rootProgram: Command,\n): (...handlerArgs: unknown[]) => Promise<void> {\n const meta: CliMeta = cmd.cli ?? {};\n const positionalNames = meta.positional ?? [];\n\n return async (...handlerArgs: unknown[]) => {\n const start = Date.now();\n const optsFromCommander = (handlerArgs[positionalNames.length] ?? {}) as Record<\n string,\n unknown\n >;\n const rootOpts = rootProgram.opts() as { json?: boolean };\n const format: 'human' | 'json' = rootOpts.json ? 'json' : 'human';\n\n const raw: Record<string, unknown> = {};\n\n // Positionals: handlerArgs[0..positionalNames.length-1]\n positionalNames.forEach((pname, i) => {\n const value = handlerArgs[i];\n if (value !== undefined) {\n const t = unwrapZodType(fieldSchema(cmd.args, pname));\n raw[pname] = coerce(value, t);\n }\n });\n\n // Options\n if (meta.options) {\n for (const [key, opt] of Object.entries(meta.options)) {\n const value = readCommanderOption(optsFromCommander, opt.long);\n if (value !== undefined) {\n const t = unwrapZodType(fieldSchema(cmd.args, key));\n raw[key] = coerce(value, t);\n }\n }\n }\n\n const ctx: CommandContext = {\n activeRoot: getActiveRoot(),\n warnings: [],\n format,\n cwd: process.cwd(),\n };\n\n const result = await invoke(cmd, raw, ctx, format);\n const duration = Date.now() - start;\n await appendUsage({\n ts: new Date().toISOString(),\n command: cmd.name,\n args: raw,\n duration_ms: duration,\n success: result.success,\n exit_code: result.exitCode,\n });\n process.exit(result.exitCode);\n };\n}\n\nasync function invoke(\n cmd: AnyCommand,\n raw: Record<string, unknown>,\n ctx: CommandContext,\n format: 'human' | 'json',\n): Promise<InvocationOutput> {\n let parsed: unknown;\n try {\n parsed = cmd.args.parse(raw);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n emitError(`invalid arguments: ${message}`, EXIT.USAGE, format);\n return { exitCode: EXIT.USAGE, success: false };\n }\n\n try {\n const result = await cmd.run(parsed, ctx);\n await emitSuccess(cmd, result, ctx);\n return { exitCode: EXIT.OK, success: true };\n } catch (err) {\n const { message, code } = formatError(err);\n emitError(message, code, format);\n return { exitCode: code, success: false };\n }\n}\n\n/**\n * Translate a registry `CliMeta` description of a single option into the\n * commander option-spec string. Boolean zod fields become bare flags\n * (`--flag`); everything else takes an option-argument (`--flag <value>`).\n */\nfunction buildOptionFlags(\n cmd: AnyCommand,\n key: string,\n opt: CliMeta['options'] extends infer M ? (M extends Record<string, infer O> ? O : never) : never,\n): string {\n const zodType = unwrapZodType(fieldSchema(cmd.args, key));\n const short = opt.short ? `${opt.short}, ` : '';\n if (zodType === 'boolean') {\n return `${short}${opt.long}`;\n }\n return `${short}${opt.long} <value>`;\n}\n\n/** Attach one registry command as a sub-command under its appropriate parent. */\nfunction attachCommand(root: Command, cmd: AnyCommand): void {\n const parts = splitName(cmd.name);\n const leafName = parts[parts.length - 1]!;\n const parent = ensureGroup(root, parts.slice(0, -1));\n const sub = parent.command(leafName).description(cmd.description);\n\n const meta: CliMeta = cmd.cli ?? {};\n for (const pname of meta.positional ?? []) {\n const zType = unwrapZodType(fieldSchema(cmd.args, pname));\n const optional =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (fieldSchema(cmd.args, pname) as any)?._zod?.def?.type === 'optional';\n const display = optional ? `[${pname}]` : `<${pname}>`;\n sub.argument(display, `${pname}${zType ? ` (${zType})` : ''}`);\n }\n\n if (meta.options) {\n for (const [key, opt] of Object.entries(meta.options)) {\n const flags = buildOptionFlags(cmd, key, opt);\n if (opt.required) {\n sub.requiredOption(flags, opt.description);\n } else {\n sub.option(flags, opt.description);\n }\n }\n }\n\n sub.action(makeAction(cmd, root));\n}\n\nfunction buildProgram(): Command {\n const program = new Command();\n // exitOverride must be set before sub-commands are created so the\n // setting is inherited via `copyInheritedSettings`. Sub-commands then\n // throw a `CommanderError` instead of calling `process.exit` directly.\n program.exitOverride();\n program\n .name('active-work')\n .description('active-work CLI — durable workspace state for engineering work')\n .version('0.1.0')\n .option('--json', 'emit machine-readable JSON envelope on stdout')\n .addHelpText(\n 'after',\n '\\nRun `active-work <command> --help` for command-specific options.\\n' +\n 'Tip: `aw [slug]` launches Claude with the bootstrap prompt.\\n',\n );\n\n // Sort commands so help output is stable.\n const cmds = registry.list();\n for (const cmd of cmds) {\n attachCommand(program, cmd);\n }\n\n return program;\n}\n\n/**\n * Entry point. Builds the program and dispatches argv. Commander errors\n * (e.g. unknown command, missing required option) are mapped to the\n * USAGE exit code; everything else surfaces via the per-command action.\n */\nexport async function main(argv: string[]): Promise<void> {\n const program = buildProgram();\n try {\n await program.parseAsync(argv);\n } catch (err) {\n if (err instanceof CommanderError) {\n // Commander already wrote to stderr for help / version. Just exit.\n if (err.code === 'commander.helpDisplayed' || err.code === 'commander.version') {\n process.exit(0);\n }\n process.exit(EXIT.USAGE);\n }\n const { message, code } = formatError(err);\n emitError(message, code, 'human');\n process.exit(code);\n }\n}\n\nvoid main(process.argv);\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { NotFoundError, UsageError, ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n domain: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n from: z.string(),\n to: z.string(),\n});\n\nasync function dirExists(p: string): Promise<boolean> {\n try {\n const stat = await fs.stat(p);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction isInside(child: string, parent: string): boolean {\n const rel = path.relative(parent, child);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n}\n\nfunction yearMonth(): string {\n const d = new Date();\n const y = d.getFullYear();\n const m = String(d.getMonth() + 1).padStart(2, '0');\n return `${y}-${m}`;\n}\n\nexport default defineCommand({\n name: 'archive',\n description: 'Move an initiative out of active root into <archiveRoot>/<domain>/archive/.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug', 'domain'],\n usage: 'active-work archive <slug> <domain>',\n },\n async run(args, ctx) {\n const from = path.resolve(path.join(ctx.activeRoot, args.slug));\n if (!(await dirExists(from))) {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n\n const cwd = path.resolve(process.cwd());\n if (isInside(cwd, from)) {\n throw new UsageError(\n `Refusing to archive: current working directory is inside ${from}. cd elsewhere first.`,\n );\n }\n\n const archiveRoot = path.resolve(ctx.activeRoot, '..');\n const destDir = path.join(archiveRoot, args.domain, 'archive');\n const to = path.join(destDir, `${args.slug}-${yearMonth()}`);\n\n if (await dirExists(to)) {\n throw new ValidationError(`Archive destination already exists: ${to}`);\n }\n\n await fs.mkdir(destDir, { recursive: true });\n\n try {\n await fs.rename(from, to);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'EXDEV') {\n await fs.cp(from, to, { recursive: true });\n await fs.rm(from, { recursive: true, force: true });\n } else {\n throw err;\n }\n }\n\n return { from, to };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport matter from 'gray-matter';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { ArtifactsSchema } from '../schemas/artifacts.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { writeYaml } from '../utils/yaml-io.js';\nimport { today } from '../utils/today.js';\nimport { validateSlug, derivePrefix } from '../utils/slug.js';\nimport { ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n title: z.string().min(1),\n ship_target: z.string().min(1).optional(),\n owner: z.string().min(1).optional(),\n worktree: z.string().min(1).optional(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n dir: z.string(),\n rank: z.number().int().positive(),\n task_prefix: z.string(),\n});\n\nasync function dirExists(p: string): Promise<boolean> {\n try {\n const stat = await fs.stat(p);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\nasync function computeNextRank(activeRoot: string): Promise<number> {\n let entries: string[];\n try {\n entries = await fs.readdir(activeRoot);\n } catch {\n return 1;\n }\n let max = 0;\n for (const entry of entries) {\n if (entry.startsWith('.')) continue;\n const briefPath = path.join(activeRoot, entry, 'brief.md');\n let raw: string;\n try {\n raw = await fs.readFile(briefPath, 'utf8');\n } catch {\n continue;\n }\n const parsed = matter(raw);\n const data = parsed.data as Record<string, unknown>;\n if (data.state === 'focused' && typeof data.rank === 'number' && data.rank > max) {\n max = data.rank;\n }\n }\n return max + 1;\n}\n\nexport default defineCommand({\n name: 'new',\n description: 'Scaffold a new initiative directory.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n title: { long: '--title', description: 'Initiative title', required: true },\n ship_target: { long: '--ship-target', description: 'Ship target (e.g., 2026-Q3)' },\n owner: { long: '--owner', description: 'Owner / handle' },\n worktree: { long: '--worktree', description: 'Default worktree path' },\n },\n usage:\n 'active-work new <slug> --title <title> [--ship-target <t>] [--owner <o>] [--worktree <path>]',\n },\n async run(args, ctx) {\n const slugCheck = validateSlug(args.slug);\n if (!slugCheck.ok) {\n throw new ValidationError(`Invalid slug \"${args.slug}\": ${slugCheck.error}`);\n }\n\n const dir = path.join(ctx.activeRoot, args.slug);\n if (await dirExists(dir)) {\n throw new ValidationError(`Initiative already exists: ${args.slug} (${dir})`);\n }\n\n const rank = await computeNextRank(ctx.activeRoot);\n const task_prefix = derivePrefix(args.slug);\n\n const frontmatter: BriefFrontmatter = {\n schema_version: 1,\n title: args.title,\n updated: today(),\n state: 'focused',\n rank,\n task_prefix,\n ...(args.ship_target ? { ship_target: args.ship_target } : {}),\n ...(args.owner ? { owner: args.owner } : {}),\n };\n\n await fs.mkdir(dir, { recursive: true });\n await fs.mkdir(path.join(dir, 'tasks'), { recursive: true });\n await fs.mkdir(path.join(dir, 'sessions'), { recursive: true });\n await fs.mkdir(path.join(dir, 'sources'), { recursive: true });\n\n const briefBody = `# ${args.title}\\n\\nWhy: ...\\n`;\n await writeFrontmatter(\n path.join(dir, 'brief.md'),\n frontmatter,\n briefBody,\n BriefFrontmatterSchema,\n );\n\n await writeYaml(\n path.join(dir, 'artifacts.yml'),\n ArtifactsSchema.parse({\n // A worktree given at creation is registered, not merely observed, so\n // `aw` resolves a cwd into it and starts there (AW-67).\n worktrees: args.worktree\n ? [\n {\n path: args.worktree,\n repo: args.worktree,\n name: 'main',\n default: true,\n },\n ]\n : [],\n }),\n ArtifactsSchema,\n );\n\n return {\n slug: args.slug,\n dir,\n rank,\n task_prefix,\n };\n },\n});\n","const SLUG_PATTERN = /^[a-z][a-z0-9-]*[a-z0-9]$/;\nconst MIN_LEN = 2;\nconst MAX_LEN = 60;\nconst MAX_PREFIX_LEN = 8;\n\nexport type SlugValidation = { ok: true } | { ok: false; error: string };\n\n/**\n * Validate a kebab-case slug.\n *\n * Rules:\n * - 2-60 characters long\n * - lowercase letters, digits, and `-` only\n * - starts with a letter, ends with a letter or digit\n * - no consecutive dashes\n */\nexport function validateSlug(s: string): SlugValidation {\n if (typeof s !== 'string' || s.length === 0) {\n return { ok: false, error: 'slug must be a non-empty string' };\n }\n if (s.length < MIN_LEN) {\n return { ok: false, error: `slug must be at least ${MIN_LEN} characters` };\n }\n if (s.length > MAX_LEN) {\n return { ok: false, error: `slug must be at most ${MAX_LEN} characters` };\n }\n if (s.includes('--')) {\n return { ok: false, error: 'slug must not contain consecutive dashes' };\n }\n if (!SLUG_PATTERN.test(s)) {\n return {\n ok: false,\n error:\n 'slug must be lowercase kebab-case: start with a letter, end with a letter or digit, allow [a-z0-9-]',\n };\n }\n return { ok: true };\n}\n\n/**\n * Derive a Jira-style task prefix from a slug.\n *\n * Takes the first character of each `-`-separated segment, uppercases each,\n * and concatenates. Truncates to 8 characters.\n *\n * @example\n * derivePrefix('ec-personalization') // 'EP'\n * derivePrefix('inbox') // 'I'\n * derivePrefix('auth-service-v2') // 'ASV'\n */\nexport function derivePrefix(slug: string): string {\n const letters = slug\n .split('-')\n .filter((segment) => segment.length > 0)\n .map((segment) => segment[0]!.toUpperCase())\n .join('');\n return letters.slice(0, MAX_PREFIX_LEN);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { NotFoundError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n brief: z.string(),\n tasks_dir: z.string(),\n sessions_dir: z.string(),\n artifacts: z.string(),\n sources_dir: z.string(),\n});\n\nexport default defineCommand({\n name: 'paths',\n description: 'Print all artifact paths for an initiative.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n usage: 'active-work paths <slug>',\n },\n async run(args, ctx) {\n const dir = path.join(ctx.activeRoot, args.slug);\n try {\n const stat = await fs.stat(dir);\n if (!stat.isDirectory()) {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n } catch (err) {\n if (err instanceof NotFoundError) throw err;\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n\n return {\n brief: path.join(dir, 'brief.md'),\n tasks_dir: path.join(dir, 'tasks'),\n sessions_dir: path.join(dir, 'sessions'),\n artifacts: path.join(dir, 'artifacts.yml'),\n sources_dir: path.join(dir, 'sources'),\n };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { validateSlug } from '../utils/slug.js';\nimport { NotFoundError, ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n old_slug: z.string().min(1),\n new_slug: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n from: z.string(),\n to: z.string(),\n});\n\nasync function dirExists(p: string): Promise<boolean> {\n try {\n const stat = await fs.stat(p);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\nexport default defineCommand({\n name: 'rename',\n description: 'Rename an initiative slug (moves the directory; task_prefix unchanged).',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['old_slug', 'new_slug'],\n usage: 'active-work rename <old-slug> <new-slug>',\n },\n async run(args, ctx) {\n const check = validateSlug(args.new_slug);\n if (!check.ok) {\n throw new ValidationError(`Invalid new slug \"${args.new_slug}\": ${check.error}`);\n }\n\n const from = path.join(ctx.activeRoot, args.old_slug);\n const to = path.join(ctx.activeRoot, args.new_slug);\n\n if (!(await dirExists(from))) {\n throw new NotFoundError(`Initiative not found: ${args.old_slug}`);\n }\n if (await dirExists(to)) {\n throw new ValidationError(`Destination already exists: ${args.new_slug}`);\n }\n\n await fs.rename(from, to);\n return { from, to };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema } from '../schemas/brief.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readRawFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n field: z.string().min(1),\n value: z.unknown(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n field: z.string(),\n value: z.unknown(),\n});\n\nfunction setPath(target: Record<string, unknown>, dotted: string, value: unknown): void {\n const parts = dotted.split('.').filter((p) => p.length > 0);\n if (parts.length === 0) {\n throw new ValidationError('Field path must not be empty');\n }\n let cursor: Record<string, unknown> = target;\n for (let i = 0; i < parts.length - 1; i++) {\n const key = parts[i]!;\n const next = cursor[key];\n if (next === undefined || next === null || typeof next !== 'object' || Array.isArray(next)) {\n const fresh: Record<string, unknown> = {};\n cursor[key] = fresh;\n cursor = fresh;\n } else {\n cursor = next as Record<string, unknown>;\n }\n }\n cursor[parts[parts.length - 1]!] = value;\n}\n\nexport default defineCommand({\n name: 'set',\n description: 'Set a single field on an initiative brief.md frontmatter.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug', 'field', 'value'],\n usage: 'active-work set <slug> <field> <value>',\n },\n async run(args, ctx) {\n const dir = path.join(ctx.activeRoot, args.slug);\n const briefPath = path.join(dir, 'brief.md');\n try {\n await fs.access(briefPath);\n } catch {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n\n await withFileLock(getLockPath(args.slug), async () => {\n const { frontmatter, body } = await readRawFrontmatter(briefPath);\n setPath(frontmatter, args.field, args.value);\n frontmatter.updated = today();\n try {\n await writeFrontmatter(briefPath, frontmatter, body, BriefFrontmatterSchema);\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n throw new ValidationError(\n `Cannot set ${args.field}=${JSON.stringify(args.value)}: ${reason}`,\n );\n }\n });\n\n return { slug: args.slug, field: args.field, value: args.value };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema } from '../schemas/brief.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readRawFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n updated: z.string(),\n});\n\nexport default defineCommand({\n name: 'touch',\n description: \"Stamp `updated: today()` on an initiative's brief.md.\",\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n usage: 'active-work touch <slug>',\n },\n async run(args, ctx) {\n const briefPath = path.join(ctx.activeRoot, args.slug, 'brief.md');\n try {\n await fs.access(briefPath);\n } catch {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n\n const updated = today();\n await withFileLock(getLockPath(args.slug), async () => {\n const { frontmatter, body } = await readRawFrontmatter(briefPath);\n frontmatter.updated = updated;\n await writeFrontmatter(briefPath, frontmatter, body, BriefFrontmatterSchema);\n });\n\n return { slug: args.slug, updated };\n },\n});\n","import { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, UsageError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\nimport { loadAllBriefs, sortSlugs, type InitiativeBrief } from './_focus-helpers.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n rank: z.number().int().positive().optional(),\n});\n\nconst ShiftEntrySchema = z.object({\n slug: z.string(),\n from: z.number().int().positive().optional(),\n to: z.number().int().positive(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n rank: z.number().int().positive(),\n shifted: z.array(ShiftEntrySchema),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\ninterface RankedSlug {\n slug: string;\n rank: number;\n}\n\nfunction buildRanking(briefs: InitiativeBrief[]): RankedSlug[] {\n return briefs\n .filter((b) => b.frontmatter.state === 'focused')\n .map((b) => {\n // schema guarantees rank is present when state is focused\n const rank = b.frontmatter.rank;\n if (rank === undefined) {\n throw new Error(`Focused initiative ${b.slug} is missing rank in brief.md`);\n }\n return { slug: b.slug, rank };\n })\n .sort((a, b) => a.rank - b.rank);\n}\n\nexport default defineCommand<Args, Result>({\n name: 'focus',\n description: 'Promote an initiative into the focused list at a given rank.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n rank: {\n long: '--rank',\n description: 'Target rank (positive integer). Defaults to end of list.',\n },\n },\n usage: 'active-work focus <slug> [--rank N]',\n },\n async run({ slug, rank }) {\n const briefs = await loadAllBriefs();\n const target = briefs.find((b) => b.slug === slug);\n if (!target) {\n throw new NotFoundError(`Initiative not found: ${slug}`);\n }\n\n const ranked = buildRanking(briefs);\n const currentRank = ranked.find((r) => r.slug === slug)?.rank;\n const withoutTarget = ranked.filter((r) => r.slug !== slug);\n\n let desired: number;\n if (rank === undefined) {\n // Append: 1 if no one focused (excluding target), else max+1.\n desired = withoutTarget.length === 0 ? 1 : Math.max(...withoutTarget.map((r) => r.rank)) + 1;\n } else {\n const maxAllowed = withoutTarget.length + 1;\n if (rank > maxAllowed) {\n throw new UsageError(`rank ${rank} exceeds maximum of ${maxAllowed} for the focused list`);\n }\n desired = rank;\n }\n\n // Compute the new ranking.\n const finalRanking: RankedSlug[] = withoutTarget.map((r) => ({\n slug: r.slug,\n rank: r.rank >= desired ? r.rank + 1 : r.rank,\n }));\n finalRanking.push({ slug, rank: desired });\n finalRanking.sort((a, b) => a.rank - b.rank);\n\n // Determine which briefs actually changed so we only rewrite those.\n const changes = new Map<string, { from?: number; to: number }>();\n for (const entry of finalRanking) {\n const prior = ranked.find((r) => r.slug === entry.slug)?.rank;\n const sameState =\n entry.slug === slug\n ? target.frontmatter.state === 'focused' && prior === entry.rank\n : prior === entry.rank;\n if (!sameState) {\n changes.set(entry.slug, { from: prior, to: entry.rank });\n }\n }\n\n // Always include target if it wasn't focused before, even if rank\n // somehow matches (defensive).\n if (!changes.has(slug)) {\n changes.set(slug, { from: currentRank, to: desired });\n }\n\n const updateDate = today();\n const lockOrder = sortSlugs(changes.keys());\n await applyLocked(lockOrder, async () => {\n for (const slugToWrite of lockOrder) {\n const change = changes.get(slugToWrite);\n if (!change) continue;\n const brief = briefs.find((b) => b.slug === slugToWrite);\n if (!brief) {\n throw new NotFoundError(`Initiative ${slugToWrite} disappeared mid-update`);\n }\n const next: BriefFrontmatter = {\n ...brief.frontmatter,\n state: 'focused',\n rank: change.to,\n updated: updateDate,\n };\n // Clear paused-only fields just in case target was paused; safe noop\n // for already-focused entries.\n delete (next as Partial<BriefFrontmatter>).paused_since;\n delete (next as Partial<BriefFrontmatter>).restart_trigger;\n await writeFrontmatter(brief.briefPath, next, brief.body, BriefFrontmatterSchema);\n }\n });\n\n const shifted = [...changes.entries()]\n .filter(([s]) => s !== slug)\n .map(([s, c]) => ({ slug: s, from: c.from, to: c.to }))\n .sort((a, b) => a.to - b.to);\n\n return { slug, rank: desired, shifted };\n },\n});\n\nasync function applyLocked(slugs: string[], fn: () => Promise<void>): Promise<void> {\n // Acquire all locks in deterministic order. Nest withFileLock calls so\n // releases happen in reverse order.\n const recurse = async (index: number): Promise<void> => {\n if (index === slugs.length) {\n await fn();\n return;\n }\n await withFileLock(getLockPath(slugs[index]), () => recurse(index + 1));\n };\n await recurse(0);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getActiveRoot, getInitiativeDir } from '../utils/paths.js';\nimport { readFrontmatter } from '../utils/gray-matter-io.js';\n\nexport interface InitiativeBrief {\n slug: string;\n briefPath: string;\n frontmatter: BriefFrontmatter;\n body: string;\n}\n\n/**\n * Resolve the path to an initiative's `brief.md` for a given slug.\n */\nexport function briefPathFor(slug: string): string {\n return path.join(getInitiativeDir(slug), 'brief.md');\n}\n\n/**\n * Enumerate every initiative directory under the active root by looking for\n * `brief.md`. Returns the parsed and schema-validated frontmatter for each.\n *\n * Directories with no `brief.md` are skipped silently — those are not\n * initiatives. Hidden files (e.g. `.schema-version`) are ignored.\n */\nexport async function loadAllBriefs(): Promise<InitiativeBrief[]> {\n const root = getActiveRoot();\n let entries: string[];\n try {\n entries = await fs.readdir(root);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n\n const briefs: InitiativeBrief[] = [];\n for (const name of entries) {\n if (name.startsWith('.')) continue;\n const briefPath = path.join(root, name, 'brief.md');\n let stat;\n try {\n stat = await fs.stat(briefPath);\n } catch {\n continue;\n }\n if (!stat.isFile()) continue;\n const { frontmatter, body } = await readFrontmatter(briefPath, BriefFrontmatterSchema);\n briefs.push({ slug: name, briefPath, frontmatter, body });\n }\n briefs.sort((a, b) => a.slug.localeCompare(b.slug));\n return briefs;\n}\n\n/**\n * Sort a list of slugs into a deterministic order suitable for locking\n * multiple initiatives' brief.md files simultaneously without deadlock.\n */\nexport function sortSlugs(slugs: Iterable<string>): string[] {\n return [...new Set(slugs)].sort();\n}\n","import { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\nimport { loadAllBriefs, sortSlugs } from './_focus-helpers.js';\n\nconst ISO_DATE_REGEX = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nconst isoDate = z\n .string()\n .regex(ISO_DATE_REGEX, 'since must be YYYY-MM-DD')\n .refine((v) => {\n const parsed = new Date(v);\n if (Number.isNaN(parsed.getTime())) return false;\n return parsed.toISOString().slice(0, 10) === v;\n }, 'since must be a valid calendar date');\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n since: isoDate,\n restart_trigger: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n paused_since: z.string(),\n restart_trigger: z.string(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'pause',\n description: 'Mark an initiative as paused with required restart metadata.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n since: {\n long: '--since',\n description: 'Pause-since date (YYYY-MM-DD).',\n required: true,\n },\n 'restart-trigger': {\n long: '--restart-trigger',\n description: 'What event should cause this initiative to resume.',\n required: true,\n },\n },\n usage: 'active-work pause <slug> --since YYYY-MM-DD --restart-trigger \"...\"',\n },\n async run({ slug, since, restart_trigger }) {\n const briefs = await loadAllBriefs();\n const target = briefs.find((b) => b.slug === slug);\n if (!target) {\n throw new NotFoundError(`Initiative not found: ${slug}`);\n }\n\n const wasFocused = target.frontmatter.state === 'focused';\n const survivors = wasFocused\n ? briefs\n .filter((b) => b.frontmatter.state === 'focused' && b.slug !== slug)\n .map((b) => {\n if (b.frontmatter.rank === undefined) {\n throw new Error(`Focused initiative ${b.slug} missing rank`);\n }\n return { slug: b.slug, rank: b.frontmatter.rank };\n })\n .sort((a, b) => a.rank - b.rank)\n : [];\n\n const renumberOps: { slug: string; to: number }[] = [];\n survivors.forEach((s, i) => {\n const newRank = i + 1;\n if (s.rank !== newRank) {\n renumberOps.push({ slug: s.slug, to: newRank });\n }\n });\n\n const updateDate = today();\n const slugsToLock = sortSlugs([slug, ...renumberOps.map((r) => r.slug)]);\n\n await applyLocked(slugsToLock, async () => {\n const paused: BriefFrontmatter = {\n ...target.frontmatter,\n state: 'paused',\n paused_since: since,\n restart_trigger,\n updated: updateDate,\n };\n delete (paused as Partial<BriefFrontmatter>).rank;\n await writeFrontmatter(target.briefPath, paused, target.body, BriefFrontmatterSchema);\n\n for (const op of renumberOps) {\n const brief = briefs.find((b) => b.slug === op.slug);\n if (!brief) continue;\n const next: BriefFrontmatter = {\n ...brief.frontmatter,\n state: 'focused',\n rank: op.to,\n updated: updateDate,\n };\n await writeFrontmatter(brief.briefPath, next, brief.body, BriefFrontmatterSchema);\n }\n });\n\n return { slug, paused_since: since, restart_trigger };\n },\n});\n\nasync function applyLocked(slugs: string[], fn: () => Promise<void>): Promise<void> {\n const recurse = async (index: number): Promise<void> => {\n if (index === slugs.length) {\n await fn();\n return;\n }\n await withFileLock(getLockPath(slugs[index]), () => recurse(index + 1));\n };\n await recurse(0);\n}\n","import { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, UsageError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\nimport { loadAllBriefs, sortSlugs } from './_focus-helpers.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n});\n\nconst RenumberEntrySchema = z.object({\n slug: z.string(),\n from: z.number().int().positive(),\n to: z.number().int().positive(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n renumbered: z.array(RenumberEntrySchema),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'unfocus',\n description: 'Demote a focused initiative to backburner and renumber survivors.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n usage: 'active-work unfocus <slug>',\n },\n async run({ slug }) {\n const briefs = await loadAllBriefs();\n const target = briefs.find((b) => b.slug === slug);\n if (!target) {\n throw new NotFoundError(`Initiative not found: ${slug}`);\n }\n if (target.frontmatter.state !== 'focused') {\n throw new UsageError(`Cannot unfocus ${slug}: state is ${target.frontmatter.state}`);\n }\n\n const survivors = briefs\n .filter((b) => b.frontmatter.state === 'focused' && b.slug !== slug)\n .map((b) => {\n if (b.frontmatter.rank === undefined) {\n throw new Error(`Focused initiative ${b.slug} missing rank`);\n }\n return { slug: b.slug, rank: b.frontmatter.rank };\n })\n .sort((a, b) => a.rank - b.rank);\n\n const renumberOps: { slug: string; from: number; to: number }[] = [];\n survivors.forEach((s, i) => {\n const newRank = i + 1;\n if (s.rank !== newRank) {\n renumberOps.push({ slug: s.slug, from: s.rank, to: newRank });\n }\n });\n\n const updateDate = today();\n const slugsToLock = sortSlugs([slug, ...renumberOps.map((r) => r.slug)]);\n\n await applyLocked(slugsToLock, async () => {\n // Write target.\n const cleared: BriefFrontmatter = {\n ...target.frontmatter,\n state: 'backburner',\n updated: updateDate,\n };\n delete (cleared as Partial<BriefFrontmatter>).rank;\n await writeFrontmatter(target.briefPath, cleared, target.body, BriefFrontmatterSchema);\n\n // Renumber survivors that actually moved.\n for (const op of renumberOps) {\n const brief = briefs.find((b) => b.slug === op.slug);\n if (!brief) continue;\n const next: BriefFrontmatter = {\n ...brief.frontmatter,\n state: 'focused',\n rank: op.to,\n updated: updateDate,\n };\n await writeFrontmatter(brief.briefPath, next, brief.body, BriefFrontmatterSchema);\n }\n });\n\n return { slug, renumbered: renumberOps };\n },\n});\n\nasync function applyLocked(slugs: string[], fn: () => Promise<void>): Promise<void> {\n const recurse = async (index: number): Promise<void> => {\n if (index === slugs.length) {\n await fn();\n return;\n }\n await withFileLock(getLockPath(slugs[index]), () => recurse(index + 1));\n };\n await recurse(0);\n}\n","import { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, UsageError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\nimport { loadAllBriefs } from './_focus-helpers.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'unpause',\n description: 'Move a paused initiative back to backburner.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n usage: 'active-work unpause <slug>',\n },\n async run({ slug }) {\n const briefs = await loadAllBriefs();\n const target = briefs.find((b) => b.slug === slug);\n if (!target) {\n throw new NotFoundError(`Initiative not found: ${slug}`);\n }\n if (target.frontmatter.state !== 'paused') {\n throw new UsageError(`Cannot unpause ${slug}: state is ${target.frontmatter.state}`);\n }\n\n await withFileLock(getLockPath(slug), async () => {\n const next: BriefFrontmatter = {\n ...target.frontmatter,\n state: 'backburner',\n updated: today(),\n };\n delete (next as Partial<BriefFrontmatter>).paused_since;\n delete (next as Partial<BriefFrontmatter>).restart_trigger;\n delete (next as Partial<BriefFrontmatter>).rank;\n await writeFrontmatter(target.briefPath, next, target.body, BriefFrontmatterSchema);\n });\n\n return { slug };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { TaskSchema, type Task } from '../schemas/task.js';\nimport { getActiveRoot, getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport {\n loadBrief,\n loadExistingTasks,\n maxOnDiskTaskNumber,\n readTaskSeq,\n} from '../utils/task-seq.js';\nimport { writeYaml } from '../utils/yaml-io.js';\nimport { today } from '../utils/today.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n title: z.string().min(1),\n priority: z.number().int().positive().optional(),\n severity: z.enum(['critical', 'high', 'medium', 'low']).optional(),\n estimate: z.number().positive().optional(),\n done_when: z.string().min(1).optional(),\n tags: z.array(z.string()).optional(),\n notes: z.string().optional(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\n// Ids must never be reissued, even after `task delete` removes the file that\n// used the highest number. `task_seq` is the persisted high-water mark for\n// that case; it only needs to move when a delete removes the current highest\n// id (see task-delete.ts), so `task.add` itself never has to write brief.md\n// (AW-94) — it only reads the mark to guard against a stale on-disk scan.\nfunction allocateTaskNumber(\n brief: Awaited<ReturnType<typeof loadBrief>>,\n existing: Task[],\n): number {\n const onDisk = maxOnDiskTaskNumber(brief.prefix, existing);\n return Math.max(readTaskSeq(brief, onDisk), onDisk) + 1;\n}\n\nfunction nextPriority(existing: Task[]): number {\n let max = 0;\n for (const t of existing) {\n if (t.priority > max) max = t.priority;\n }\n return max + 1;\n}\n\nexport default defineCommand<Args, Task>({\n name: 'task.add',\n description: 'Create a new task in an initiative',\n args: ArgsSchema,\n result: TaskSchema,\n cli: {\n positional: ['slug'],\n options: {\n title: { long: '--title', description: 'Task title', required: true },\n priority: { long: '--priority', description: 'Priority (positive int)' },\n severity: {\n long: '--severity',\n description: 'critical|high|medium|low',\n },\n estimate: { long: '--estimate', description: 'Estimate (hours)' },\n done_when: {\n long: '--done-when',\n description: 'Definition of done',\n },\n tags: { long: '--tags', description: 'Comma-separated tag list' },\n notes: { long: '--notes', description: 'Free-form notes' },\n },\n },\n async run(args) {\n // Touch activeRoot so it's resolved before locking.\n getActiveRoot();\n return withFileLock(getLockPath(args.slug), async () => {\n const brief = await loadBrief(args.slug);\n const existing = await loadExistingTasks(args.slug);\n const n = allocateTaskNumber(brief, existing);\n const id = `${brief.prefix}-${n}`;\n const priority = args.priority ?? nextPriority(existing);\n const date = today();\n const task: Task = {\n id,\n title: args.title,\n priority,\n severity: args.severity,\n estimate: args.estimate,\n done_when: args.done_when,\n status: 'open',\n tags: args.tags,\n notes: args.notes,\n created: date,\n updated: date,\n done_at: null,\n };\n const taskDir = path.join(getInitiativeDir(args.slug), 'tasks');\n await fs.mkdir(taskDir, { recursive: true });\n await writeYaml(path.join(taskDir, `${id}.yml`), task, TaskSchema);\n return task;\n });\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { TaskSchema, type Task } from '../schemas/task.js';\nimport { TaskSeqSchema } from '../schemas/brief.js';\nimport { getInitiativeDir } from './paths.js';\nimport { readRawFrontmatter } from './gray-matter-io.js';\nimport { readYaml } from './yaml-io.js';\nimport { NotFoundError, ValidationError } from '../errors.js';\n\nconst PREFIX_RE = /^[A-Z][A-Z0-9]*$/;\n\nexport interface Brief {\n slug: string;\n path: string;\n frontmatter: Record<string, unknown>;\n body: string;\n prefix: string;\n}\n\nexport async function loadBrief(slug: string): Promise<Brief> {\n const briefPath = path.join(getInitiativeDir(slug), 'brief.md');\n let raw: { frontmatter: Record<string, unknown>; body: string };\n try {\n raw = await readRawFrontmatter(briefPath);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new NotFoundError(`Initiative not found: ${slug}`);\n }\n throw err;\n }\n const prefix = raw.frontmatter.task_prefix;\n if (typeof prefix !== 'string' || !PREFIX_RE.test(prefix)) {\n throw new ValidationError(`Brief at ${briefPath} is missing a valid task_prefix`);\n }\n return {\n slug,\n path: briefPath,\n frontmatter: raw.frontmatter,\n body: raw.body,\n prefix,\n };\n}\n\nexport async function loadExistingTasks(slug: string): Promise<Task[]> {\n const dir = path.join(getInitiativeDir(slug), 'tasks');\n let entries: string[];\n try {\n entries = (await fs.readdir(dir)).filter((e) => e.endsWith('.yml'));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const tasks: Task[] = [];\n for (const file of entries) {\n tasks.push(await readYaml(path.join(dir, file), TaskSchema));\n }\n return tasks;\n}\n\n// Scans task filenames directly rather than parsing every task file's YAML.\n// Used by task.delete, which must not fail to delete a task just because some\n// unrelated task file in the same directory happens to be malformed.\nexport async function maxOnDiskTaskNumberFromFilenames(\n prefix: string,\n slug: string,\n): Promise<number> {\n const dir = path.join(getInitiativeDir(slug), 'tasks');\n let entries: string[];\n try {\n entries = await fs.readdir(dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return 0;\n throw err;\n }\n const re = new RegExp(`^${prefix}-(\\\\d+)\\\\.yml$`);\n let max = 0;\n for (const entry of entries) {\n const m = re.exec(entry);\n if (m) {\n const n = Number.parseInt(m[1]!, 10);\n if (n > max) max = n;\n }\n }\n return max;\n}\n\nexport function maxOnDiskTaskNumber(prefix: string, existing: Task[]): number {\n let max = 0;\n const re = new RegExp(`^${prefix}-(\\\\d+)$`);\n for (const t of existing) {\n const m = re.exec(t.id);\n if (m) {\n const n = Number.parseInt(m[1]!, 10);\n if (n > max) max = n;\n }\n }\n return max;\n}\n\n// Extracts the numeric suffix from an id matching this initiative's\n// task_prefix, or null if the id doesn't match (e.g. wrong prefix, malformed).\nexport function taskNumber(prefix: string, id: string): number | null {\n const m = new RegExp(`^${prefix}-(\\\\d+)$`).exec(id);\n return m ? Number.parseInt(m[1]!, 10) : null;\n}\n\n// `Infinity` and `NaN` both stringify to `null` through JSON, which would hide\n// the very value the operator has to find in the file.\nfunction describeValue(value: unknown): string {\n return typeof value === 'number' ? String(value) : JSON.stringify(value);\n}\n\nfunction taskSeqRepair(brief: Brief, value: unknown, onDisk: number): string {\n return (\n `Invalid task_seq (${describeValue(value)}) in ${brief.path}. ` +\n 'task_seq is the high-water mark for task ids and must be a positive whole ' +\n 'number no larger than Number.MAX_SAFE_INTEGER. Task ids cannot be allocated ' +\n `until it is repaired: the highest id on disk is ${brief.prefix}-${onDisk}, so run ` +\n `\\`active-work set ${brief.slug} task_seq <n>\\` with n at least ${Math.max(onDisk, 1)} ` +\n '— higher if ids above that were issued and their tasks later deleted.'\n );\n}\n\n/**\n * ABSENT is a legitimate back-compat path: briefs written before the field\n * existed allocate from the on-disk max. Any other invalid value is corruption,\n * and silently falling back would \"repair\" it *downward* — below an id that has\n * already been issued — so it is reported instead of guessed at.\n */\nexport function readTaskSeq(brief: Brief, onDisk: number): number {\n const raw = brief.frontmatter.task_seq;\n if (raw === undefined) return 0;\n const parsed = TaskSeqSchema.safeParse(raw);\n if (!parsed.success) {\n throw new ValidationError(taskSeqRepair(brief, raw, onDisk));\n }\n return parsed.data;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { getActiveRoot, getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { BriefFrontmatterSchema } from '../schemas/brief.js';\nimport {\n loadBrief,\n maxOnDiskTaskNumberFromFilenames,\n readTaskSeq,\n taskNumber,\n} from '../utils/task-seq.js';\nimport { NotFoundError } from '../errors.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n id: z.string().min(1),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n id: z.string(),\n deleted: z.literal(true),\n});\n\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'task.delete',\n description: 'Hard delete a task file (prefer task.done in normal use)',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug', 'id'],\n },\n async run(args) {\n getActiveRoot();\n return withFileLock(getLockPath(args.slug), async () => {\n const file = path.join(getInitiativeDir(args.slug), 'tasks', `${args.id}.yml`);\n try {\n await fs.access(file);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new NotFoundError(`Task not found: ${args.id}`);\n }\n throw err;\n }\n\n // Deleting the current highest id would let task.add reissue it on the\n // next call, since its on-disk scan can no longer see this file (AW-94:\n // task_seq now moves here instead of on every task.add). Bump the\n // high-water mark *before* unlinking, so a crash between the two never\n // leaves it stale.\n const brief = await loadBrief(args.slug);\n const onDiskMax = await maxOnDiskTaskNumberFromFilenames(brief.prefix, args.slug);\n const n = taskNumber(brief.prefix, args.id);\n if (n !== null && n === onDiskMax) {\n const stored = readTaskSeq(brief, onDiskMax);\n if (stored < n) {\n const frontmatter: Record<string, unknown> = {\n ...brief.frontmatter,\n task_seq: n,\n };\n await writeFrontmatter(brief.path, frontmatter, brief.body, BriefFrontmatterSchema);\n }\n }\n\n await fs.unlink(file);\n return { id: args.id, deleted: true };\n });\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { TaskSchema, type Task } from '../schemas/task.js';\nimport { getActiveRoot, getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError } from '../errors.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n id: z.string().min(1),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\nexport default defineCommand<Args, Task>({\n name: 'task.done',\n description: 'Mark a task as done',\n args: ArgsSchema,\n result: TaskSchema,\n cli: {\n positional: ['slug', 'id'],\n },\n async run(args) {\n getActiveRoot();\n return withFileLock(getLockPath(args.slug), async () => {\n const file = path.join(getInitiativeDir(args.slug), 'tasks', `${args.id}.yml`);\n let task: Task;\n try {\n task = await readYaml(file, TaskSchema);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new NotFoundError(`Task not found: ${args.id}`);\n }\n throw err;\n }\n const date = today();\n const updated: Task = {\n ...task,\n status: 'done',\n done_at: date,\n updated: date,\n };\n await writeYaml(file, updated, TaskSchema);\n return updated;\n });\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { TaskSchema, type Task } from '../schemas/task.js';\nimport { getActiveRoot, getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, UsageError, ValidationError } from '../errors.js';\n\nconst EDITABLE_FIELDS = [\n 'title',\n 'priority',\n 'severity',\n 'estimate',\n 'done_when',\n 'tags',\n 'notes',\n 'status',\n] as const;\n\ntype EditableField = (typeof EDITABLE_FIELDS)[number];\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n id: z.string().min(1),\n field: z.string().min(1),\n value: z.unknown(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\nfunction isEditable(field: string): field is EditableField {\n return (EDITABLE_FIELDS as readonly string[]).includes(field);\n}\n\n/**\n * The CLI/MCP dispatcher can't coerce `value` generically because its type\n * depends on `field` at runtime (unlike other commands, where each arg has\n * a fixed zod type). Coerce here, against the field it's actually landing on.\n */\nfunction coerceValue(field: EditableField, value: unknown): unknown {\n if (typeof value !== 'string') return value;\n if (field === 'priority' || field === 'estimate') {\n const n = Number(value);\n return Number.isNaN(n) ? value : n;\n }\n if (field === 'tags') {\n return value\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n }\n return value;\n}\n\nexport default defineCommand<Args, Task>({\n name: 'task.edit',\n description: 'Edit a single field on a task',\n args: ArgsSchema,\n result: TaskSchema,\n cli: {\n positional: ['slug', 'id', 'field', 'value'],\n },\n async run(args) {\n const { field } = args;\n if (!isEditable(field)) {\n throw new UsageError(\n `Field is not editable: ${field} (allowed: ${EDITABLE_FIELDS.join(', ')})`,\n );\n }\n getActiveRoot();\n return withFileLock(getLockPath(args.slug), async () => {\n const file = path.join(getInitiativeDir(args.slug), 'tasks', `${args.id}.yml`);\n let task: Task;\n try {\n task = await readYaml(file, TaskSchema);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new NotFoundError(`Task not found: ${args.id}`);\n }\n throw err;\n }\n const date = today();\n const next: Record<string, unknown> = {\n ...task,\n [field]: coerceValue(field, args.value),\n };\n next.updated = date;\n if (args.field === 'status' && args.value === 'done') {\n next.done_at = date;\n }\n const parsed = TaskSchema.safeParse(next);\n if (!parsed.success) {\n throw new ValidationError(`Invalid value for ${args.field}: ${parsed.error.message}`);\n }\n await writeYaml(file, parsed.data, TaskSchema);\n return parsed.data;\n });\n },\n});\n","import { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { TaskSchema, type Task } from '../schemas/task.js';\nimport { getActiveRoot, getInitiativeDir } from '../utils/paths.js';\nimport { readYaml } from '../utils/yaml-io.js';\nimport { UsageError } from '../errors.js';\n\nconst StatusFilter = z.enum(['open', 'done', 'all']).default('open');\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1).optional(),\n all_initiatives: z.boolean().optional(),\n tag: z.string().optional(),\n severity: z.enum(['critical', 'high', 'medium', 'low']).optional(),\n status: StatusFilter.optional(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\ntype TaskWithSlug = Task & { slug: string };\n\nconst ResultSchema = z.object({\n tasks: z.array(TaskSchema.extend({ slug: z.string() })),\n});\n\ntype Result = z.infer<typeof ResultSchema>;\n\nasync function listSlugs(): Promise<string[]> {\n const root = getActiveRoot();\n let entries: Dirent[];\n try {\n entries = await fs.readdir(root, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n return entries.filter((e) => e.isDirectory()).map((e) => e.name);\n}\n\nasync function loadTasksForSlug(slug: string): Promise<TaskWithSlug[]> {\n const dir = path.join(getInitiativeDir(slug), 'tasks');\n let files: string[];\n try {\n files = await fs.readdir(dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const tasks: TaskWithSlug[] = [];\n for (const file of files) {\n if (!file.endsWith('.yml')) continue;\n const task = await readYaml(path.join(dir, file), TaskSchema);\n tasks.push({ ...task, slug });\n }\n return tasks;\n}\n\nexport default defineCommand<Args, Result>({\n name: 'task.list',\n description: 'List tasks for an initiative or across all initiatives',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n all_initiatives: {\n long: '--all-initiatives',\n description: 'Scan every initiative under the active root',\n },\n tag: { long: '--tag', description: 'Filter by tag membership' },\n severity: {\n long: '--severity',\n description: 'Filter by severity (critical|high|medium|low)',\n },\n status: {\n long: '--status',\n description: 'open (default), done, or all',\n },\n },\n },\n async run(args) {\n const status = args.status ?? 'open';\n const slugs: string[] = args.all_initiatives\n ? await listSlugs()\n : (() => {\n if (!args.slug) {\n throw new UsageError('task.list requires --all-initiatives or a slug');\n }\n return [args.slug];\n })();\n\n let collected: TaskWithSlug[] = [];\n for (const slug of slugs) {\n const tasks = await loadTasksForSlug(slug);\n collected = collected.concat(tasks);\n }\n\n const filtered = collected.filter((t) => {\n if (status !== 'all' && t.status !== status) return false;\n if (args.tag && !(t.tags ?? []).includes(args.tag)) return false;\n if (args.severity && t.severity !== args.severity) return false;\n return true;\n });\n\n filtered.sort((a, b) => a.priority - b.priority);\n return { tasks: filtered };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { TaskSchema, type Task } from '../schemas/task.js';\nimport { getActiveRoot, getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError } from '../errors.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n id: z.string().min(1),\n new_priority: z.number().int().positive(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ShiftedSchema = z.object({\n id: z.string(),\n from: z.number().int(),\n to: z.number().int(),\n});\n\nconst ResultSchema = z.object({\n id: z.string(),\n from: z.number().int(),\n to: z.number().int(),\n shifted: z.array(ShiftedSchema),\n});\n\ntype Result = z.infer<typeof ResultSchema>;\n\nasync function loadAllTasks(slug: string): Promise<Array<{ task: Task; file: string }>> {\n const dir = path.join(getInitiativeDir(slug), 'tasks');\n let files: string[];\n try {\n files = await fs.readdir(dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const out: Array<{ task: Task; file: string }> = [];\n for (const file of files) {\n if (!file.endsWith('.yml')) continue;\n const full = path.join(dir, file);\n out.push({ task: await readYaml(full, TaskSchema), file: full });\n }\n return out;\n}\n\nexport default defineCommand<Args, Result>({\n name: 'task.reorder',\n description: 'Move a task to a new priority and shift siblings down',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug', 'id', 'new_priority'],\n },\n async run(args) {\n getActiveRoot();\n return withFileLock(getLockPath(args.slug), async () => {\n const entries = await loadAllTasks(args.slug);\n const target = entries.find((e) => e.task.id === args.id);\n if (!target) {\n throw new NotFoundError(`Task not found: ${args.id}`);\n }\n const oldPriority = target.task.priority;\n const newPriority = args.new_priority;\n const shifted: Array<{ id: string; from: number; to: number }> = [];\n const date = today();\n\n if (oldPriority === newPriority) {\n return { id: args.id, from: oldPriority, to: newPriority, shifted };\n }\n\n const writes: Array<{ task: Task; file: string }> = [];\n\n for (const entry of entries) {\n if (entry.task.id === args.id) continue;\n if (entry.task.priority >= newPriority) {\n const before = entry.task.priority;\n const after = before + 1;\n const next: Task = {\n ...entry.task,\n priority: after,\n updated: date,\n };\n writes.push({ task: next, file: entry.file });\n shifted.push({ id: entry.task.id, from: before, to: after });\n }\n }\n\n const targetNext: Task = {\n ...target.task,\n priority: newPriority,\n updated: date,\n };\n writes.push({ task: targetNext, file: target.file });\n\n for (const w of writes) {\n await writeYaml(w.file, w.task, TaskSchema);\n }\n\n return { id: args.id, from: oldPriority, to: newPriority, shifted };\n });\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport {\n deriveOpenLoopsFrom,\n deriveResolvedLoopsFrom,\n loadSessionsFromDir,\n} from '../sessions/open-loops.js';\nimport { loadTasks } from '../lint/load-tasks.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n state: z.enum(['open', 'resolved', 'abandoned', 'all']).default('open'),\n});\n\nconst OpenLoopSchema = z.object({\n ref: z.string(),\n text: z.string(),\n kind: z.enum(['task', 'pr', 'prose']),\n target_ref: z.string().optional(),\n session_file: z.string(),\n opened_at: z.string(),\n age_days: z.number().int().nonnegative(),\n});\n\nconst ResolvedLoopSchema = z.object({\n ref: z.string(),\n text: z.string(),\n kind: z.enum(['task', 'pr', 'prose']),\n outcome: z.enum(['done', 'abandoned']),\n note: z.string().optional(),\n session_file: z.string(),\n closed_by: z.string(),\n opened_at: z.string(),\n closed_at: z.string(),\n age_days: z.number().int().nonnegative(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n open: z.array(OpenLoopSchema),\n resolved: z.array(ResolvedLoopSchema),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'loops',\n description:\n \"List an initiative's open-loop ledger. Open loops are the unresolved remainder; resolved ones carry the outcome and the reason they were closed, which the bootstrap only surfaces for recent abandonments.\",\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n state: {\n long: '--state',\n description: \"'open' (default) | 'resolved' | 'abandoned' | 'all'\",\n },\n },\n usage: 'active-work loops <slug> [--state open|resolved|abandoned|all]',\n },\n async run(args, ctx) {\n const initiativeDir = path.join(ctx.activeRoot, args.slug);\n const [loaded, tasks] = await Promise.all([\n loadSessionsFromDir(initiativeDir),\n loadTasks(initiativeDir),\n ]);\n const opts = { now: new Date(), tasks };\n const wantOpen = args.state === 'open' || args.state === 'all';\n const wantResolved = args.state !== 'open';\n\n const open = wantOpen\n ? deriveOpenLoopsFrom(loaded, opts).map((loop) => ({\n ref: loop.ref,\n text: loop.text,\n kind: loop.kind,\n ...(loop.targetRef !== undefined ? { target_ref: loop.targetRef } : {}),\n session_file: loop.sessionFile,\n opened_at: loop.openedAt,\n age_days: loop.ageDays,\n }))\n : [];\n\n const resolved = wantResolved\n ? deriveResolvedLoopsFrom(loaded, opts)\n .filter((loop) => args.state !== 'abandoned' || loop.outcome === 'abandoned')\n .map((loop) => ({\n ref: loop.ref,\n text: loop.text,\n kind: loop.kind,\n outcome: loop.outcome,\n ...(loop.note !== undefined ? { note: loop.note } : {}),\n session_file: loop.sessionFile,\n closed_by: loop.closedBy,\n opened_at: loop.openedAt,\n closed_at: loop.closedAt,\n age_days: loop.ageDays,\n }))\n : [];\n\n return { slug: args.slug, open, resolved };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { TaskSchema, type Task } from '../schemas/task.js';\nimport { readYaml } from '../utils/yaml-io.js';\n\n/**\n * Load every task under `<initiativeDir>/tasks/*.yml`.\n *\n * Shared by lint and doctor: both need `kind: 'task'` loops matched against\n * real tasks, and both are best-effort consumers — a malformed task file is\n * skipped rather than thrown, since neither is the source of truth for task\n * validity (schema-validating writers are).\n */\nexport async function loadTasks(initiativeDir: string): Promise<Task[]> {\n const tasksDir = path.join(initiativeDir, 'tasks');\n let entries: string[];\n try {\n entries = await fs.readdir(tasksDir);\n } catch {\n return [];\n }\n const tasks: Task[] = [];\n for (const filename of entries.filter((n) => n.endsWith('.yml') || n.endsWith('.yaml'))) {\n try {\n tasks.push(await readYaml(path.join(tasksDir, filename), TaskSchema));\n } catch {\n // Skip malformed task files.\n }\n }\n return tasks;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { BranchEntrySchema, StashEntrySchema, WorktreeEntrySchema } from '../schemas/artifacts.js';\nimport { NotFoundError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\nimport { sweepInitiative } from '../wrap/sweep.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n cwd: z.string().min(1).optional(),\n});\n\nconst DirtyTreeSchema = z.object({\n path: z.string(),\n repo: z.string(),\n /** Null when git could not read the tree — unknown, not clean. */\n files_changed: z.number().int().nonnegative().nullable(),\n});\n\nconst UnpushedBranchSchema = z.object({\n path: z.string(),\n repo: z.string(),\n branch: z.string(),\n ahead: z.number().int().nonnegative(),\n no_upstream: z.boolean(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n repos: z.array(z.string()),\n unrecorded: z.object({\n worktrees: z.array(WorktreeEntrySchema),\n branches: z.array(BranchEntrySchema),\n stashes: z.array(StashEntrySchema),\n }),\n dirty: z.array(DirtyTreeSchema),\n unpushed: z.array(UnpushedBranchSchema),\n checklist: z.array(z.string()),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\n/**\n * The categories a wrap has to answer. Git state is swept deterministically;\n * these are the four things only the session itself knows.\n */\nconst CHECKLIST = [\n 'open loops: what this session leaves hanging, filed as wrap --next-steps, plus the prior loops it closed via --resolves',\n 'durable notes: anything learned that outlives the session, filed with note.add',\n 'tasks filed: work you named but did not do, filed with task.add',\n 'worktree/artifact state: what each dirty or unpushed worktree is holding, and whether every branch and stash worth keeping is recorded',\n];\n\nexport default defineCommand<Args, Result>({\n name: 'preflight',\n description:\n 'Read-only pre-wrap sweep: the uncommitted trees, unpushed branches, and worktrees/branches/stashes present in git but missing from artifacts.yml, plus the checklist a wrap must answer. Writes nothing.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n cwd: {\n long: '--cwd',\n description: 'Directory to include in the swept repo set (default: current directory).',\n },\n },\n usage: 'active-work preflight <slug> [--cwd <dir>]',\n },\n async run(args, ctx) {\n const briefPath = path.join(ctx.activeRoot, args.slug, 'brief.md');\n try {\n await fs.access(briefPath);\n } catch {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n const cwd = args.cwd ?? ctx.cwd ?? process.cwd();\n const sweep = await sweepInitiative(args.slug, ctx.activeRoot, cwd);\n return { slug: args.slug, ...sweep, checklist: CHECKLIST };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport {\n ArtifactsSchema,\n type Artifacts,\n type BranchEntry,\n type StashEntry,\n type WorktreeEntry,\n} from '../schemas/artifacts.js';\nimport { registeredOf } from '../utils/registered-worktrees.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { expandTilde } from '../utils/paths.js';\nimport { resolveLocalRepoPath } from '../utils/git-gh.js';\nimport {\n discoverWorktrees,\n listStashes,\n readWorktreeState,\n type DiscoveredWorktree,\n type WorktreeState,\n} from '../utils/git-worktrees.js';\n\n/**\n * Pre-wrap sweep: the git state a session leaves behind that nobody recorded.\n *\n * The repo set is bounded and derived, never searched: the worktree paths in\n * `brief.md`, the `repo` values already in `artifacts.yml`, and the caller's\n * cwd. Everything else is read live through `getGitRunner()` (via\n * `src/utils/git-worktrees.ts`), so a repo that has moved contributes nothing\n * rather than aborting the sweep.\n */\n\nexport interface UnrecordedState {\n worktrees: WorktreeEntry[];\n branches: BranchEntry[];\n stashes: StashEntry[];\n}\n\nexport interface DirtyTree {\n path: string;\n repo: string;\n /** Null when git could not say — the tree is unknown, not clean. */\n files_changed: number | null;\n}\n\nexport interface UnpushedBranch {\n path: string;\n repo: string;\n branch: string;\n /** Commits that exist on no remote. */\n ahead: number;\n /**\n * True when the branch tracks nothing. Not a lesser case of `ahead > 0` but\n * the worse one: nothing about the branch exists anywhere but this disk.\n */\n no_upstream: boolean;\n}\n\nexport interface SweepResult {\n repos: string[];\n unrecorded: UnrecordedState;\n dirty: DirtyTree[];\n unpushed: UnpushedBranch[];\n}\n\ninterface LiveState {\n worktrees: WorktreeEntry[];\n branches: BranchEntry[];\n stashes: StashEntry[];\n dirty: DirtyTree[];\n unpushed: UnpushedBranch[];\n}\n\ninterface RepoSweep extends LiveState {\n /** The path we swept from — a repo root or any worktree attached to it. */\n sweptPath: string;\n /**\n * The repository this path belongs to, as git reports it (the main worktree\n * of the set). Two swept paths sharing a root are one repository.\n */\n root: string | null;\n}\n\nconst EMPTY_STATE = (): LiveState => ({\n worktrees: [],\n branches: [],\n stashes: [],\n dirty: [],\n unpushed: [],\n});\n\nconst emptySweep = (sweptPath: string): RepoSweep => ({\n ...EMPTY_STATE(),\n sweptPath,\n root: null,\n});\n\nfunction normalizePath(value: string): string {\n return path.resolve(expandTilde(value));\n}\n\n/** Stable identity for a `repo` field, which may be a path or `org/repo`. */\nfunction repoKey(repo: string): string {\n return resolveLocalRepoPath(repo) ?? repo;\n}\n\nfunction artifactsPath(initiativeDir: string): string {\n return path.join(initiativeDir, 'artifacts.yml');\n}\n\n/**\n * Missing `artifacts.yml` reads as empty; a malformed one still throws, so a\n * later append can never silently overwrite content it failed to parse.\n */\nasync function readArtifacts(initiativeDir: string): Promise<Artifacts> {\n const file = artifactsPath(initiativeDir);\n try {\n await fs.access(file);\n } catch {\n return { branches: [], stashes: [], worktrees: [] };\n }\n return readYaml(file, ArtifactsSchema);\n}\n\n/**\n * Registered worktree paths seed the repo set. Since v4 these live in\n * artifacts.yml alongside the swept ones (AW-67), so they arrive with the rest\n * of the artifacts read and need no separate file.\n */\nfunction registeredWorktreePaths(artifacts: Artifacts): string[] {\n return registeredOf(artifacts).map((entry) => entry.path);\n}\n\n/**\n * Absolute repo path -> the label to write into new artifact entries. Seeded\n * from `artifacts.yml` first so recorded spellings (`~/code/sample`) win over\n * the resolved absolute path.\n */\nfunction collectRepoLabels(\n artifacts: Artifacts,\n briefPaths: string[],\n cwd: string,\n): Map<string, string> {\n const labels = new Map<string, string>();\n const add = (value: string): void => {\n const abs = resolveLocalRepoPath(value);\n if (abs && !labels.has(abs)) labels.set(abs, value);\n };\n for (const branch of artifacts.branches) add(branch.repo);\n for (const stash of artifacts.stashes) add(stash.repo);\n for (const worktree of artifacts.worktrees) add(worktree.repo);\n for (const worktreePath of briefPaths) add(worktreePath);\n add(cwd);\n return labels;\n}\n\n/**\n * Collect one worktree's contribution to the sweep. Every live worktree is\n * recorded — its path and purpose are identity, and git cannot re-derive what\n * it is parked on — while branches, dirt, and unpushed commits are filtered.\n */\nfunction collectWorktree(\n discovered: DiscoveredWorktree,\n label: string,\n state: WorktreeState,\n into: RepoSweep,\n): void {\n const branch = state.branch ?? discovered.branch ?? undefined;\n // Never `?? 0`: a failed probe means unknown, and defaulting it to zero\n // reports the most dangerous branch — one that exists on no remote — as the\n // safest. Unknown counts as unpushed.\n // A failed `--not --remotes` probe falls back to `ahead`, and only then to 1\n // as \"unknown but non-zero\" — a tracked branch 3 ahead must not read as clean\n // just because the remote-wide count could not be taken.\n const stranded = state.unpushed ?? state.ahead ?? 1;\n const isUnpushed = stranded > 0;\n into.worktrees.push({\n path: discovered.path,\n repo: label,\n ...(branch ? { branch } : {}),\n });\n // `dirty: null` means git could not answer, which is reported rather than\n // skipped: treating an unreadable tree as clean hides exactly the\n // uncommitted work this sweep exists to surface.\n const dirtyUnknown = state.dirty === null;\n if (state.dirty || dirtyUnknown) {\n into.dirty.push({\n path: discovered.path,\n repo: label,\n files_changed: state.files_changed,\n });\n }\n if (!branch) return;\n if (isUnpushed) {\n into.unpushed.push({\n path: discovered.path,\n repo: label,\n branch,\n ahead: stranded,\n no_upstream: !state.has_upstream,\n });\n }\n // A checked-out branch is worth recording only when it carries work that\n // lives nowhere else — unpushed commits or an uncommitted tree. Recording\n // every branch git happens to have checked out would bury the ones that\n // matter.\n if (state.dirty !== false || isUnpushed) {\n into.branches.push({ repo: label, name: branch });\n }\n}\n\nasync function sweepRepo(repoPath: string, label: string): Promise<RepoSweep> {\n const [discovered, stashes] = await Promise.all([\n discoverWorktrees(repoPath),\n listStashes(repoPath),\n ]);\n const out = emptySweep(repoPath);\n // git lists the main worktree first; it identifies the repository the swept\n // path belongs to, whichever worktree of the set we were pointed at.\n out.root = discovered[0]?.path ?? null;\n for (const worktree of discovered) {\n if (worktree.bare) continue;\n const state = await readWorktreeState(worktree.path);\n if (!state.present) continue;\n collectWorktree(worktree, label, state, out);\n }\n out.stashes = stashes.map((stash) => ({\n repo: label,\n label: stash.label,\n sha: stash.sha,\n }));\n return out;\n}\n\n/** First occurrence wins, so the chosen `repo` label is stable across runs. */\nfunction dedupeBy<T>(items: T[], key: (item: T) => string): T[] {\n const seen = new Set<string>();\n return items.filter((item) => {\n const k = key(item);\n if (seen.has(k)) return false;\n seen.add(k);\n return true;\n });\n}\n\nconst worktreeKey = (entry: { path: string }): string => normalizePath(entry.path);\nconst branchKey = (entry: BranchEntry): string => `${repoKey(entry.repo)} ${entry.name}`;\nconst stashKey = (entry: StashEntry): string =>\n `${repoKey(entry.repo)} ${entry.sha ?? entry.label}`;\n\n/**\n * Which repository a sweep covered. Falls back to the swept path when git could\n * not say — a path that answers nothing cannot be merged with anything else.\n */\nconst repositoryOf = (sweep: RepoSweep): string => sweep.root ?? sweep.sweptPath;\n\n/**\n * `git worktree list` and `git stash list` are per-repository, and the repo set\n * can legitimately hold two paths belonging to one repo — a main checkout plus\n * a registered linked worktree. Sweeping both yields every worktree and stash\n * twice under different labels, so candidates must be deduped against each\n * other and not merely against what is already recorded.\n */\nfunction mergeSweeps(sweeps: RepoSweep[]): LiveState {\n const merged = EMPTY_STATE();\n for (const sweep of sweeps) {\n merged.worktrees.push(...sweep.worktrees);\n merged.branches.push(...sweep.branches);\n merged.stashes.push(...sweep.stashes);\n merged.dirty.push(...sweep.dirty);\n merged.unpushed.push(...sweep.unpushed);\n }\n return {\n worktrees: dedupeBy(merged.worktrees, worktreeKey),\n branches: dedupeBy(merged.branches, branchKey),\n stashes: dedupeBy(merged.stashes, stashKey),\n dirty: dedupeBy(merged.dirty, worktreeKey),\n unpushed: dedupeBy(merged.unpushed, worktreeKey),\n };\n}\n\nfunction unrecordedWorktrees(\n candidates: WorktreeEntry[],\n recorded: WorktreeEntry[],\n): WorktreeEntry[] {\n const seen = new Set(recorded.map((entry) => normalizePath(entry.path)));\n return candidates.filter((entry) => !seen.has(normalizePath(entry.path)));\n}\n\nfunction unrecordedBranches(candidates: BranchEntry[], recorded: BranchEntry[]): BranchEntry[] {\n const key = (repo: string, name: string): string => `${repoKey(repo)}\u0000${name}`;\n const seen = new Set(recorded.map((entry) => key(entry.repo, entry.name)));\n return candidates.filter((entry) => !seen.has(key(entry.repo, entry.name)));\n}\n\n/**\n * Stashes are matched on `repo` + `sha`, falling back to `label` for entries\n * recorded before a sha was known — a recorded stash with no sha is otherwise\n * invisible to the sweep and gets appended a second time on every wrap.\n */\nfunction unrecordedStashes(candidates: StashEntry[], recorded: StashEntry[]): StashEntry[] {\n const key = (repo: string, tail: string): string => `${repoKey(repo)}\u0000${tail}`;\n const shas = new Set<string>();\n const labels = new Set<string>();\n for (const entry of recorded) {\n if (entry.sha) shas.add(key(entry.repo, entry.sha));\n else labels.add(key(entry.repo, entry.label));\n }\n return candidates.filter(\n (entry) =>\n !(entry.sha && shas.has(key(entry.repo, entry.sha))) &&\n !labels.has(key(entry.repo, entry.label)),\n );\n}\n\n/** Read-only. Never writes. */\nexport async function sweepInitiative(\n slug: string,\n activeRoot: string,\n cwd: string,\n): Promise<SweepResult> {\n const initiativeDir = path.join(activeRoot, slug);\n const artifacts = await readArtifacts(initiativeDir);\n const labels = collectRepoLabels(artifacts, registeredWorktreePaths(artifacts), cwd);\n const swept = await Promise.all(\n [...labels].map(([repoPath, label]) => sweepRepo(repoPath, label)),\n );\n const distinct = dedupeBy(swept, repositoryOf);\n const live = mergeSweeps(distinct);\n return {\n repos: distinct.map(repositoryOf),\n unrecorded: {\n worktrees: unrecordedWorktrees(live.worktrees, artifacts.worktrees),\n branches: unrecordedBranches(live.branches, artifacts.branches),\n stashes: unrecordedStashes(live.stashes, artifacts.stashes),\n },\n dirty: live.dirty,\n unpushed: live.unpushed,\n };\n}\n\n/**\n * Appends `unrecorded` into artifacts.yml and returns how many of each were\n * added. CALLER MUST ALREADY HOLD THE INITIATIVE LOCK — this function must NOT\n * call withFileLock itself or it will deadlock inside wrap's existing lock.\n */\nexport async function recordUnrecorded(\n slug: string,\n activeRoot: string,\n unrecorded: UnrecordedState,\n): Promise<{ worktrees: number; branches: number; stashes: number }> {\n const initiativeDir = path.join(activeRoot, slug);\n const current = await readArtifacts(initiativeDir);\n const worktrees = unrecordedWorktrees(unrecorded.worktrees, current.worktrees);\n const branches = unrecordedBranches(unrecorded.branches, current.branches);\n const stashes = unrecordedStashes(unrecorded.stashes, current.stashes);\n const added = {\n worktrees: worktrees.length,\n branches: branches.length,\n stashes: stashes.length,\n };\n if (worktrees.length + branches.length + stashes.length === 0) return added;\n await writeYaml(\n artifactsPath(initiativeDir),\n {\n branches: [...current.branches, ...branches],\n stashes: [...current.stashes, ...stashes],\n worktrees: [...current.worktrees, ...worktrees],\n },\n ArtifactsSchema,\n );\n return added;\n}\n","import { getGitRunner } from './git-gh.js';\n\n/**\n * Live git worktree reads for `artifact.status`.\n *\n * Nothing here is persisted: `artifacts.yml` records only worktree identity\n * and purpose (see `src/schemas/artifacts.ts`), and everything volatile —\n * dirty flag, files changed, ahead/behind — is pulled at read time.\n *\n * Like `git-gh.ts`, every helper is failure-tolerant: a repo that has been\n * moved or deleted yields empty/null data rather than aborting the sweep.\n * All git calls go through `getGitRunner()` so tests can inject a fake.\n */\n\nexport interface DiscoveredWorktree {\n path: string;\n head: string | null;\n branch: string | null;\n detached: boolean;\n bare: boolean;\n}\n\nexport interface WorktreeState {\n /**\n * False when the path is gone or is no longer a git worktree. Without this a\n * deleted worktree reads exactly like a clean one — no dirt, no files, no\n * upstream — and silently drops out of the operator's attention.\n */\n present: boolean;\n /**\n * Null when `git status` could not answer. A failed probe is not a clean\n * tree: reporting it as clean is the same mistake `ahead` avoids below, and\n * it silences the one warning that says uncommitted work is about to be left\n * behind.\n */\n dirty: boolean | null;\n /** Null whenever `dirty` is null — an unknown tree has an unknown file count. */\n files_changed: number | null;\n branch: string | null;\n /** Null when there is no upstream — meaning unknown, never \"nothing to push\". */\n ahead: number | null;\n behind: number | null;\n /**\n * Whether the branch tracks a remote, probed directly. Deriving this from\n * `ahead !== null` conflated \"no upstream configured\" with \"the rev-list call\n * failed\", so a transient git failure reported a tracked branch as untracked.\n */\n has_upstream: boolean;\n /**\n * Commits reachable from HEAD that exist on no remote at all. This is the\n * honest \"what would be lost if this disk died\" number, and unlike `ahead`\n * it is defined for a branch that was never pushed anywhere.\n */\n unpushed: number | null;\n}\n\nexport interface StashRef {\n label: string;\n sha: string;\n}\n\nconst NO_UPSTREAM = { ahead: null, behind: null } as const;\n\nfunction shortBranch(ref: string): string {\n return ref.replace(/^refs\\/heads\\//, '');\n}\n\nfunction emptyWorktree(path: string): DiscoveredWorktree {\n return { path, head: null, branch: null, detached: false, bare: false };\n}\n\n/**\n * Parse `git worktree list --porcelain` output. Records are separated by\n * blank lines and always open with a `worktree <path>` line. Exported for\n * testing.\n */\nexport function parseWorktreePorcelain(stdout: string): DiscoveredWorktree[] {\n const out: DiscoveredWorktree[] = [];\n let current: DiscoveredWorktree | null = null;\n for (const rawLine of stdout.split('\\n')) {\n const line = rawLine.trimEnd();\n const [key, ...rest] = line.split(' ');\n const value = rest.join(' ');\n if (key === 'worktree') {\n current = emptyWorktree(value);\n out.push(current);\n } else if (!current) {\n continue;\n } else if (key === 'HEAD') {\n current.head = value || null;\n } else if (key === 'branch') {\n current.branch = shortBranch(value);\n } else if (key === 'detached') {\n current.detached = true;\n } else if (key === 'bare') {\n current.bare = true;\n }\n }\n return out;\n}\n\n/** Enumerate the worktrees attached to `repoPath`. Empty on failure. */\nexport async function discoverWorktrees(repoPath: string): Promise<DiscoveredWorktree[]> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', repoPath, 'worktree', 'list', '--porcelain']);\n if (res.code !== 0) return [];\n return parseWorktreePorcelain(res.stdout);\n } catch {\n return [];\n }\n}\n\nconst DIRT_UNKNOWN = { dirty: null, files_changed: null } as const;\n\nasync function readDirty(\n worktreePath: string,\n): Promise<{ dirty: boolean | null; files_changed: number | null }> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', worktreePath, 'status', '--porcelain']);\n if (res.code !== 0) return { ...DIRT_UNKNOWN };\n const lines = res.stdout.split('\\n').filter((line) => line.trim().length > 0);\n return { dirty: lines.length > 0, files_changed: lines.length };\n } catch {\n return { ...DIRT_UNKNOWN };\n }\n}\n\n/** Whether the current branch tracks a remote. Probed, never inferred. */\nasync function readHasUpstream(worktreePath: string): Promise<boolean> {\n const git = getGitRunner();\n try {\n const res = await git('git', [\n '-C',\n worktreePath,\n 'rev-parse',\n '--abbrev-ref',\n '--symbolic-full-name',\n '@{u}',\n ]);\n return res.code === 0 && res.stdout.trim().length > 0;\n } catch {\n return false;\n }\n}\n\n/** Current branch of a worktree, or null when HEAD is detached. */\nasync function readBranch(worktreePath: string): Promise<string | null> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', worktreePath, 'rev-parse', '--abbrev-ref', 'HEAD']);\n if (res.code !== 0) return null;\n const name = res.stdout.trim();\n return name && name !== 'HEAD' ? name : null;\n } catch {\n return null;\n }\n}\n\nasync function countRevs(\n worktreePath: string,\n range: string,\n extra: string[] = [],\n): Promise<number | null> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', worktreePath, 'rev-list', '--count', range, ...extra]);\n if (res.code !== 0) return null;\n const count = Number(res.stdout.trim());\n return Number.isFinite(count) ? count : null;\n } catch {\n return null;\n }\n}\n\n/** Ahead/behind versus the tracking branch; nulls when there is no upstream. */\nasync function readAheadBehind(\n worktreePath: string,\n): Promise<{ ahead: number | null; behind: number | null }> {\n const ahead = await countRevs(worktreePath, '@{u}..HEAD');\n if (ahead === null) return { ...NO_UPSTREAM };\n const behind = await countRevs(worktreePath, 'HEAD..@{u}');\n return { ahead, behind };\n}\n\n/** Whether `worktreePath` still resolves inside a git working tree. */\nexport async function isWorktreePresent(worktreePath: string): Promise<boolean> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', worktreePath, 'rev-parse', '--is-inside-work-tree']);\n return res.code === 0 && res.stdout.trim() === 'true';\n } catch {\n return false;\n }\n}\n\n// An absent worktree states `dirty: null` rather than `false` for the same\n// reason a failed probe does: there is no tree to be clean.\nconst ABSENT: WorktreeState = {\n present: false,\n dirty: null,\n files_changed: null,\n branch: null,\n ahead: null,\n behind: null,\n has_upstream: false,\n unpushed: null,\n};\n\n/** Commits on HEAD that no remote has. Defined even with no upstream set. */\nasync function readUnpushed(worktreePath: string): Promise<number | null> {\n return countRevs(worktreePath, 'HEAD', ['--not', '--remotes']);\n}\n\n/** Live, non-persisted state of a single worktree. */\nexport async function readWorktreeState(worktreePath: string): Promise<WorktreeState> {\n if (!(await isWorktreePresent(worktreePath))) return { ...ABSENT };\n const [{ dirty, files_changed }, branch, { ahead, behind }, unpushed, has_upstream] =\n await Promise.all([\n readDirty(worktreePath),\n readBranch(worktreePath),\n readAheadBehind(worktreePath),\n readUnpushed(worktreePath),\n readHasUpstream(worktreePath),\n ]);\n return {\n present: true,\n dirty,\n files_changed,\n branch,\n ahead,\n behind,\n has_upstream,\n unpushed,\n };\n}\n\n/** Stashes present in `repoPath`, newest first. Empty on failure. */\nexport async function listStashes(repoPath: string): Promise<StashRef[]> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', repoPath, 'stash', 'list', '--format=%H%x09%gs']);\n if (res.code !== 0) return [];\n return res.stdout\n .split('\\n')\n .map((line) => line.split('\\t'))\n .filter((parts): parts is [string, string] => Boolean(parts[0]?.trim() && parts[1]))\n .map(([sha, label]) => ({ sha: sha.trim(), label: label.trim() }));\n } catch {\n return [];\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport matter from 'gray-matter';\nimport { SessionFrontmatterSchema } from '../schemas/session.js';\nimport type { SessionFrontmatter } from '../schemas/session.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n limit: z.number().int().positive().optional(),\n});\n\nconst SessionEntrySchema = z.object({\n filename: z.string(),\n frontmatter: SessionFrontmatterSchema,\n first_line: z.string(),\n});\n\nconst ResultSchema = z.object({\n sessions: z.array(SessionEntrySchema),\n errors: z.array(z.object({ filename: z.string(), error: z.string() })),\n});\n\nconst DEFAULT_LIMIT = 100;\nconst MAX_FIRST_LINE = 120;\n\nfunction extractFirstLine(body: string): string {\n const lines = body.split(/\\r?\\n/);\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length === 0) continue;\n return trimmed.length > MAX_FIRST_LINE ? trimmed.slice(0, MAX_FIRST_LINE) : trimmed;\n }\n return '';\n}\n\ninterface ListEntry {\n filename: string;\n frontmatter: SessionFrontmatter;\n first_line: string;\n}\n\ninterface ListError {\n filename: string;\n error: string;\n}\n\nasync function listSessionFiles(dir: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(dir);\n return entries.filter((e) => e.endsWith('.md')).sort();\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n}\n\n/**\n * YAML parses unquoted ISO 8601 timestamps as `Date` instances. The session\n * schema expects ISO strings, so coerce known timestamp fields back to their\n * string form before validation.\n */\nfunction coerceTimestamps(raw: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = { ...raw };\n for (const field of ['started', 'ended'] as const) {\n const value = out[field];\n if (value instanceof Date) {\n out[field] = value.toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n }\n }\n return out;\n}\n\nasync function readSession(\n filePath: string,\n): Promise<{ frontmatter: SessionFrontmatter; body: string }> {\n const raw = await fs.readFile(filePath, 'utf8');\n const parsed = matter(raw);\n const coerced = coerceTimestamps(parsed.data as Record<string, unknown>);\n const result = SessionFrontmatterSchema.safeParse(coerced);\n if (!result.success) {\n throw new Error(`Frontmatter validation failed for ${filePath}: ${result.error.message}`);\n }\n return { frontmatter: result.data, body: parsed.content };\n}\n\nexport default defineCommand({\n name: 'session.list',\n description: 'List session summaries for an initiative, sorted by end time',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n limit: {\n long: '--limit',\n description: `Maximum sessions to return (default ${DEFAULT_LIMIT})`,\n },\n },\n usage: 'session.list <slug> [--limit N]',\n },\n async run(args) {\n const limit = args.limit ?? DEFAULT_LIMIT;\n const sessionsDir = path.join(getInitiativeDir(args.slug), 'sessions');\n const filenames = await listSessionFiles(sessionsDir);\n\n const entries: ListEntry[] = [];\n const errors: ListError[] = [];\n\n for (const filename of filenames) {\n const fullPath = path.join(sessionsDir, filename);\n try {\n const { frontmatter, body } = await readSession(fullPath);\n entries.push({\n filename,\n frontmatter,\n first_line: extractFirstLine(body),\n });\n } catch (err) {\n errors.push({\n filename,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n entries.sort((a, b) => {\n const aEnded = new Date(a.frontmatter.ended).getTime();\n const bEnded = new Date(b.frontmatter.ended).getTime();\n return bEnded - aEnded;\n });\n\n return { sessions: entries.slice(0, limit), errors };\n },\n});\n","import { promises as fs, createReadStream } from 'node:fs';\nimport type { Dirent } from 'node:fs';\nimport path from 'node:path';\nimport os from 'node:os';\nimport readline from 'node:readline';\nimport { z } from 'zod';\nimport { getActiveRoot, expandTilde } from '../utils/paths.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n limit: z.number().int().positive().optional(),\n include_active: z.boolean().optional(),\n});\n\nconst SessionEntrySchema = z.object({\n session_id: z.string(),\n cwd: z.string(),\n ended: z.string(),\n summary: z.string(),\n});\n\nconst ResultSchema = z.object({\n sessions: z.array(SessionEntrySchema),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\ntype SessionEntry = z.infer<typeof SessionEntrySchema>;\n\nconst DEFAULT_LIMIT = 50;\nconst SUMMARY_MAX = 150;\nconst CONTINUATION_MARKER = 'This session is being continued from a previous conversation';\n\nfunction claudeProjectsRoot(): string {\n const override = process.env.CLAUDE_PROJECTS_ROOT;\n if (override && override.length > 0) {\n return path.resolve(expandTilde(override));\n }\n return path.join(os.homedir(), '.claude', 'projects');\n}\n\ninterface ScannedSession {\n sessionId: string;\n cwd: string;\n mtimeMs: number;\n filePath: string;\n}\n\n/**\n * Walk the projects root looking for `*.jsonl` session files. Each\n * subdirectory under projects root holds sessions for one safe-encoded\n * working directory.\n */\nasync function listJsonlFiles(root: string): Promise<string[]> {\n let projectDirs: string[];\n try {\n projectDirs = await fs\n .readdir(root, { withFileTypes: true })\n .then((entries) =>\n entries.filter((e) => e.isDirectory()).map((e) => path.join(root, e.name)),\n );\n } catch {\n return [];\n }\n const all: string[] = [];\n for (const dir of projectDirs) {\n let files: string[];\n try {\n files = await fs.readdir(dir);\n } catch {\n continue;\n }\n for (const f of files) {\n if (f.endsWith('.jsonl')) {\n all.push(path.join(dir, f));\n }\n }\n }\n return all;\n}\n\n/**\n * Read the first line containing a `\"cwd\"` field without slurping the\n * whole file. Returns `null` when no such line is found.\n */\nasync function lightScanCwd(filePath: string): Promise<string | null> {\n const stream = createReadStream(filePath, { encoding: 'utf8' });\n const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });\n try {\n for await (const line of rl) {\n if (!line.includes('\"cwd\"')) continue;\n try {\n const parsed = JSON.parse(line) as Record<string, unknown>;\n const cwd = parsed.cwd;\n if (typeof cwd === 'string' && cwd.length > 0) {\n return cwd;\n }\n } catch {\n // ignore malformed line; keep scanning\n }\n }\n return null;\n } finally {\n rl.close();\n stream.destroy();\n }\n}\n\nasync function scanSession(filePath: string): Promise<ScannedSession | null> {\n const cwd = await lightScanCwd(filePath);\n if (!cwd) return null;\n const stat = await fs.stat(filePath);\n const sessionId = path.basename(filePath, '.jsonl');\n return { sessionId, cwd, mtimeMs: stat.mtimeMs, filePath };\n}\n\nasync function listActiveInitiativeRoots(): Promise<string[]> {\n const activeRoot = getActiveRoot();\n let entries: Dirent[];\n try {\n entries = await fs.readdir(activeRoot, { withFileTypes: true });\n } catch {\n return [];\n }\n return entries\n .filter((e) => e.isDirectory() && !e.name.startsWith('.'))\n .map((e) => path.join(activeRoot, e.name));\n}\n\nfunction isPathPrefix(parent: string, child: string): boolean {\n const p = path.resolve(parent);\n const c = path.resolve(child);\n if (p === c) return true;\n const withSep = p.endsWith(path.sep) ? p : p + path.sep;\n return c.startsWith(withSep);\n}\n\nfunction extractFirstUserText(line: string): string | null {\n try {\n const parsed = JSON.parse(line) as Record<string, unknown>;\n if (parsed.type !== 'user') return null;\n const message = parsed.message as Record<string, unknown> | undefined;\n if (!message) return null;\n const content = message.content;\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n for (const part of content) {\n if (\n part &&\n typeof part === 'object' &&\n 'text' in part &&\n typeof (part as { text: unknown }).text === 'string'\n ) {\n return (part as { text: string }).text;\n }\n }\n }\n return null;\n } catch {\n return null;\n }\n}\n\nfunction truncate(text: string, max: number): string {\n const trimmed = text.replace(/\\s+/g, ' ').trim();\n if (trimmed.length <= max) return trimmed;\n return trimmed.slice(0, max);\n}\n\n/**\n * Stream the jsonl file to extract a summary: prefer the most recent\n * compaction-continuation marker, otherwise fall back to the first\n * user message text.\n */\nasync function extractSummary(filePath: string): Promise<string> {\n const stream = createReadStream(filePath, { encoding: 'utf8' });\n const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });\n let latestContinuation: string | null = null;\n let firstUser: string | null = null;\n try {\n for await (const line of rl) {\n if (line.includes(CONTINUATION_MARKER)) {\n const text = extractFirstUserText(line);\n if (text) latestContinuation = text;\n } else if (firstUser === null) {\n const text = extractFirstUserText(line);\n if (text) firstUser = text;\n }\n }\n } finally {\n rl.close();\n stream.destroy();\n }\n const raw = latestContinuation ?? firstUser ?? '';\n return truncate(raw, SUMMARY_MAX);\n}\n\nexport async function runSessions(args: Args): Promise<Result> {\n const limit = args.limit ?? DEFAULT_LIMIT;\n const includeActive = args.include_active ?? false;\n\n const root = claudeProjectsRoot();\n const files = await listJsonlFiles(root);\n\n const scanned: ScannedSession[] = [];\n for (const f of files) {\n try {\n const entry = await scanSession(f);\n if (entry) scanned.push(entry);\n } catch {\n // ignore unreadable files\n }\n }\n\n let filtered = scanned;\n if (!includeActive) {\n const activeRoots = await listActiveInitiativeRoots();\n if (activeRoots.length > 0) {\n filtered = scanned.filter((s) => !activeRoots.some((root) => isPathPrefix(root, s.cwd)));\n }\n }\n\n filtered.sort((a, b) => b.mtimeMs - a.mtimeMs);\n const top = filtered.slice(0, limit);\n\n const sessions: SessionEntry[] = [];\n for (const entry of top) {\n const summary = await extractSummary(entry.filePath);\n sessions.push({\n session_id: entry.sessionId,\n cwd: entry.cwd,\n ended: new Date(entry.mtimeMs).toISOString(),\n summary,\n });\n }\n\n return { sessions };\n}\n\nconst sessions = defineCommand<Args, Result>({\n name: 'sessions',\n description: 'Browse recent Claude sessions discovered under ~/.claude/projects.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n limit: { long: '--limit', description: 'Max sessions to return (default 50).' },\n include_active: {\n long: '--include-active',\n description: 'Include sessions whose cwd lives under an active initiative.',\n },\n },\n usage: 'active-work sessions [--limit N] [--include-active]',\n },\n async run(args) {\n return runSessions(args);\n },\n});\n\nexport default sessions;\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema } from '../schemas/brief.js';\nimport { NoteKindSchema } from '../schemas/note.js';\nimport {\n NextStepSchema,\n SessionIdSchema,\n SessionResolveSchema,\n type NextStep,\n type SessionResolve,\n} from '../schemas/session.js';\nimport { writeSessionFile } from '../sessions/session-file.js';\nimport { findDanglingResolves, type DanglingKind } from '../sessions/open-loops.js';\nimport { writeNoteFile } from '../notes/note-file.js';\nimport { loadTasks } from '../lint/load-tasks.js';\nimport { recordUnrecorded, sweepInitiative, type SweepResult } from '../wrap/sweep.js';\nimport { getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readRawFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst NextStepsSchema = z.array(NextStepSchema);\nconst ResolvesSchema = z.array(SessionResolveSchema);\n\nconst NoteInputSchema = z.object({\n kind: NoteKindSchema,\n title: z.string().min(1),\n body: z.string().min(1),\n tags: z.array(z.string().min(1)).optional(),\n});\nconst NotesSchema = z.array(NoteInputSchema);\nconst TaskIdsSchema = z.array(z.string().min(1));\n\n// MCP callers pass structured arrays; the CLI passes a JSON string through a\n// single flag, since comma-splitting cannot express nested objects.\nconst nextStepsArg = z.union([z.string(), NextStepsSchema]);\nconst resolvesArg = z.union([z.string(), ResolvesSchema]);\nconst notesArg = z.union([z.string(), NotesSchema]);\nconst taskIdsArg = z.union([z.string(), TaskIdsSchema]);\n\nconst ArgsSchema = z\n .object({\n slug: z.string().min(1),\n session_id: SessionIdSchema,\n started: z.string().min(1),\n ended: z.string().min(1),\n track: z.enum(['canonical', 'sidecar', 'adhoc']).default('canonical'),\n parent_session_id: SessionIdSchema.optional(),\n body: z.string().optional(),\n body_file: z.string().optional(),\n next_steps: nextStepsArg.optional(),\n resolves: resolvesArg.optional(),\n no_loops: z.boolean().optional(),\n notes: notesArg.optional(),\n no_notes: z.boolean().optional(),\n tasks_filed: taskIdsArg.optional(),\n no_tasks: z.boolean().optional(),\n })\n .superRefine((value, ctx) => {\n const hasBody = value.body !== undefined;\n const hasFile = value.body_file !== undefined;\n if (!hasBody && !hasFile) {\n ctx.addIssue({\n code: 'custom',\n path: ['body'],\n message: 'Exactly one of --body or --body-file is required',\n });\n }\n if (hasBody && hasFile) {\n ctx.addIssue({\n code: 'custom',\n path: ['body'],\n message: '--body and --body-file are mutually exclusive',\n });\n }\n });\n\nconst RejectedResolveSchema = z.object({\n ref: z.string(),\n kind: z.enum(['missing', 'not-prior', 'self']),\n});\n\nconst FiledSchema = z.object({\n next_steps: z.number().int().nonnegative(),\n notes: z.number().int().nonnegative(),\n tasks: z.number().int().nonnegative(),\n worktrees: z.number().int().nonnegative(),\n branches: z.number().int().nonnegative(),\n stashes: z.number().int().nonnegative(),\n});\n\nconst ResultSchema = z.object({\n path: z.string(),\n filename: z.string(),\n /** False only when some `resolves` ref closed nothing and must be re-filed. */\n ready_to_end: z.boolean(),\n filed: FiledSchema,\n // Not `resolves`: the count of refs passed says nothing about how many closed\n // a loop, and the caller acts on the difference.\n closed: z.object({ resolves_applied: z.number().int().nonnegative() }),\n resolves_rejected: z.array(RejectedResolveSchema),\n /** The date stamped into `brief.updated`. */\n updated: z.string(),\n /** Files this wrap touched, relative to the initiative directory. */\n files_updated: z.array(z.string()),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\ntype RejectedResolve = z.infer<typeof RejectedResolveSchema>;\ntype NoteInput = z.infer<typeof NoteInputSchema>;\ntype Filed = z.infer<typeof FiledSchema>;\n\ninterface Ledger {\n next_steps: NextStep[];\n resolves: SessionResolve[];\n}\n\nfunction parseLedger<T>(raw: string | T[] | undefined, schema: z.ZodType<T[]>, field: string): T[] {\n if (raw === undefined) return [];\n if (Array.isArray(raw)) return schema.parse(raw);\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n throw new ValidationError(`--${field} must be a JSON array`);\n }\n const result = schema.safeParse(json);\n if (!result.success) {\n throw new ValidationError(`Invalid --${field}: ${result.error.message}`);\n }\n return result.data;\n}\n\n/**\n * Every category a session can leave behind needs an explicit answer, because\n * the alternative — silent omission — is the failure this command exists to\n * prevent. Each `empty` message deliberately does not name its own `--no-*`\n * escape hatch: an agent that reaches the error should be pointed at the work\n * of filing, not at the flag that silences the check. The flags are documented\n * in `--help` for the caller who genuinely has nothing to file.\n */\nconst GATES = {\n loops: {\n empty:\n 'Refusing to wrap with an empty ledger. Pass --next-steps with the loops this ' +\n 'session leaves open (anything a future session would need to pick up: ' +\n 'unfinished work, open PRs, unanswered questions) and/or --resolves with the ' +\n 'refs of prior loops it closed.',\n both: '--no-loops asserts an empty ledger; drop it to file --next-steps or --resolves.',\n },\n notes: {\n empty:\n 'Refusing to wrap without an answer for durable notes. Pass --notes with what ' +\n 'this session learned that no task would ever carry: process lessons, gotchas ' +\n 'that cost time, decisions and why they were made, FYIs about the state of the ' +\n 'worktree or the docs.',\n both: '--no-notes asserts this session produced no durable notes; drop it to file --notes.',\n },\n tasks: {\n empty:\n 'Refusing to wrap without an answer for tasks. Pass --tasks-filed with the ids of ' +\n 'the tasks created during this session — anything actionable that surfaced and ' +\n 'must outlive the session must be a task before wrap returns.',\n both: '--no-tasks asserts no tasks were filed this session; drop it to file --tasks-filed.',\n },\n} as const;\n\nfunction requireAnswer(\n filled: boolean,\n none: boolean,\n messages: { empty: string; both: string },\n): void {\n if (none) {\n if (filled) throw new ValidationError(messages.both);\n return;\n }\n if (!filled) throw new ValidationError(messages.empty);\n}\n\nfunction requireAnswers(args: Args, ledger: Ledger, notes: NoteInput[], taskIds: string[]): void {\n const hasLoops = ledger.next_steps.length > 0 || ledger.resolves.length > 0;\n requireAnswer(hasLoops, args.no_loops ?? false, GATES.loops);\n requireAnswer(notes.length > 0, args.no_notes ?? false, GATES.notes);\n requireAnswer(taskIds.length > 0, args.no_tasks ?? false, GATES.tasks);\n}\n\n/**\n * A fabricated id is worse than no id: it reads as filed work that does not\n * exist. Only existence is checkable here, and the message says so rather than\n * implying the ids were confirmed to be this session's.\n */\nasync function verifyTaskIds(initiativeDir: string, ids: string[]): Promise<void> {\n if (ids.length === 0) return;\n const known = new Set((await loadTasks(initiativeDir)).map((task) => task.id));\n const unknown = ids.filter((id) => !known.has(id));\n if (unknown.length === 0) return;\n throw new ValidationError(\n `--tasks-filed names ${unknown.length} id(s) with no task file in this initiative: ` +\n `${unknown.join(', ')}. File the task, then wrap. (Only existence is checked — ` +\n 'that a task was created during this session is not verifiable.)',\n );\n}\n\nasync function stampBriefUpdated(briefPath: string): Promise<string> {\n const updated = today();\n const { frontmatter, body } = await readRawFrontmatter(briefPath);\n frontmatter.updated = updated;\n await writeFrontmatter(briefPath, frontmatter, body, BriefFrontmatterSchema);\n return updated;\n}\n\n/**\n * Write the session file, then bump `brief.updated`. If the brief write fails\n * the session file is removed again, so a wrap is all-or-nothing rather than\n * merely discouraged from being partial.\n */\nasync function writeWrap(\n args: Args,\n briefPath: string,\n body: string,\n ledger: Ledger,\n): Promise<{ path: string; filename: string; updated: string }> {\n const session = await writeSessionFile({\n slug: args.slug,\n session_id: args.session_id,\n started: args.started,\n ended: args.ended,\n track: args.track,\n body,\n next_steps: ledger.next_steps,\n resolves: ledger.resolves,\n ...(args.no_loops === true ? { no_loops: true as const } : {}),\n ...(args.parent_session_id ? { parent_session_id: args.parent_session_id } : {}),\n });\n try {\n const updated = await stampBriefUpdated(briefPath);\n return { ...session, updated };\n } catch (err) {\n await fs.rm(session.path, { force: true });\n throw err;\n }\n}\n\n/** Note paths written, so a later failure can unwind them. */\nasync function fileNotes(\n initiativeDir: string,\n notes: NoteInput[],\n created: string,\n): Promise<string[]> {\n const written: string[] = [];\n for (const note of notes) {\n const result = await writeNoteFile(\n initiativeDir,\n {\n kind: note.kind,\n title: note.title,\n created,\n ...(note.tags === undefined ? {} : { tags: note.tags }),\n },\n note.body,\n );\n written.push(result.path);\n }\n return written;\n}\n\nconst NOTHING_RECORDED = { worktrees: 0, branches: 0, stashes: 0 };\n\n/**\n * Dirty trees and unpushed branches cannot be recorded anywhere — only the tree\n * itself knows. They are surfaced as warnings rather than gating the wrap.\n */\nfunction warnUnrecordable(sweep: SweepResult, warnings: string[]): void {\n for (const tree of sweep.dirty) {\n warnings.push(\n tree.files_changed === null\n ? `Could not read the working tree in ${tree.path} (${tree.repo}); it may hold uncommitted work. Check it before relying on this wrap.`\n : `Uncommitted work in ${tree.path} (${tree.repo}): ${tree.files_changed} file(s) changed.`,\n );\n }\n for (const branch of sweep.unpushed) {\n warnings.push(\n `${branch.branch} in ${branch.path} (${branch.repo}) is ${branch.ahead} commit(s) ahead of its remote.`,\n );\n }\n}\n\n/**\n * Record whatever git state the initiative has not written down. The operator\n * chose recording over refusing: a wrap never fails because a worktree was\n * untracked, only because writing the record itself failed.\n *\n * MUST run inside the initiative lock — `recordUnrecorded` takes none of its own.\n */\nasync function sweepAndRecord(\n slug: string,\n activeRoot: string,\n warnings: string[],\n): Promise<typeof NOTHING_RECORDED> {\n let sweep: SweepResult;\n try {\n sweep = await sweepInitiative(slug, activeRoot, process.cwd());\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n warnings.push(`Could not sweep git state for unrecorded artifacts: ${reason}`);\n return NOTHING_RECORDED;\n }\n warnUnrecordable(sweep, warnings);\n return recordUnrecorded(slug, activeRoot, sweep.unrecorded);\n}\n\n/**\n * Which `resolves` entries of the session just written closed nothing, and why.\n *\n * Derived by re-running the canonical derivation over the initiative rather\n * than re-implementing the rules: a second classifier that disagreed with\n * `deriveOpenLoops` would report a close that bootstrap still shows as open.\n */\nasync function rejectedResolves(\n initiativeDir: string,\n filename: string,\n): Promise<RejectedResolve[]> {\n const stem = filename.replace(/\\.md$/, '');\n const dangling = await findDanglingResolves(initiativeDir);\n return dangling\n .filter((entry) => entry.sessionFile === stem)\n .map(({ ref, kind }) => ({ ref, kind }));\n}\n\nconst REMEDY: Record<DanglingKind, string> = {\n missing: 'no loop carries that ref — check the session-file stem and the next_steps id',\n 'not-prior':\n 'the loop was opened by a session that did not end strictly before this one — re-file the resolve from a later session',\n self: 'a session cannot close a loop it opened — carry it as a next_step instead',\n};\n\n/**\n * The session is on disk by the time this runs and the message says so: an\n * agent that typo'd one ref should re-file that ref, not re-run the wrap and\n * duplicate the narrative.\n *\n * This rides `ctx.warnings` rather than a thrown error. Throwing discarded the\n * receipt — the one case `ready_to_end: false` and `resolves_rejected[]` exist\n * to describe was also the one case no caller could read them, leaving the\n * machine-readable half of the contract available only as prose to parse.\n */\nfunction rejectionReport(sessionPath: string, rejected: RejectedResolve[], total: number): string {\n const lines = rejected.map((r) => ` - ${r.ref} (${r.kind}): ${REMEDY[r.kind]}`);\n return (\n `Session written to ${sessionPath}, but ${rejected.length} of ${total} ` +\n `--resolves entries closed no loop:\\n${lines.join('\\n')}\\n` +\n 'The session file and brief.updated are committed, so ready_to_end is false: ' +\n 're-file only the rejected refs from a later session.'\n );\n}\n\nfunction filesUpdated(initiativeDir: string, notePaths: string[], recorded: Filed): string[] {\n const files = ['brief.md'];\n if (recorded.worktrees + recorded.branches + recorded.stashes > 0) {\n files.push('artifacts.yml');\n }\n return files.concat(notePaths.map((p) => path.relative(initiativeDir, p)));\n}\n\nexport default defineCommand<Args, Result>({\n name: 'wrap',\n description:\n 'The last thing a session does. Treat it as the moment the process exits: everything ' +\n 'not persisted before wrap returns is lost, so file it first and wrap last. Every ' +\n 'category the session can leave behind needs an explicit answer, and omitting one is ' +\n 'an error rather than a default — open loops (--next-steps / --resolves, or --no-loops), ' +\n 'durable notes (--notes or --no-notes), and tasks created this session (--tasks-filed or ' +\n '--no-tasks). Writes the session file and its ledger, files the notes under ' +\n 'sources/notes/, records any worktrees, branches and stashes the initiative had not ' +\n \"written down, stamps the brief's updated date, and returns a receipt of what was filed.\",\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n session_id: {\n long: '--session-id',\n description: 'Claude session identifier',\n required: true,\n },\n started: {\n long: '--started',\n description: 'ISO 8601 session start timestamp',\n required: true,\n },\n ended: {\n long: '--ended',\n description: 'ISO 8601 session end timestamp',\n required: true,\n },\n track: {\n long: '--track',\n description:\n \"'canonical' (mainline thread) | 'sidecar' (folded/derived) | 'adhoc' (parallel ad-hoc work) (default: canonical)\",\n },\n parent_session_id: {\n long: '--parent-session',\n description:\n 'Session id that spawned this one. Set by the agent-chat spawn hook for peers, whose parentage no transcript records.',\n },\n body: {\n long: '--body',\n description: 'Raw markdown body (session narrative)',\n },\n body_file: {\n long: '--body-file',\n description: 'Path to a file containing the markdown body',\n },\n next_steps: {\n long: '--next-steps',\n description:\n 'JSON array of loops this session opens: [{\"id\",\"text\",\"kind\":\"task|pr|prose\",\"ref\"?}]',\n },\n resolves: {\n long: '--resolves',\n description:\n 'JSON array of loops this session closes: [{\"ref\":\"<session-file-stem>#<id>\",\"outcome\":\"done|abandoned\",\"note\"?}]',\n },\n no_loops: {\n long: '--no-loops',\n description:\n 'Assert that this session leaves nothing hanging. Records no_loops: true so a deliberate empty ledger is distinguishable from an unfiled one. Mutually exclusive with --next-steps / --resolves.',\n },\n notes: {\n long: '--notes',\n description:\n 'JSON array of durable notes to file under sources/notes/: [{\"kind\":\"process|gotcha|fyi|decision\",\"title\",\"body\",\"tags\"?}]',\n },\n no_notes: {\n long: '--no-notes',\n description:\n 'Assert that this session produced no durable knowledge worth keeping. Mutually exclusive with --notes.',\n },\n tasks_filed: {\n long: '--tasks-filed',\n description:\n 'JSON array of task ids created during this session, e.g. [\"AW-66\",\"AW-67\"]. Each must already exist in the initiative.',\n },\n no_tasks: {\n long: '--no-tasks',\n description:\n 'Assert that this session filed no tasks. Mutually exclusive with --tasks-filed.',\n },\n },\n usage:\n 'active-work wrap <slug> --session-id <id> --started <iso> --ended <iso> [--track canonical|sidecar|adhoc] (--body <text> | --body-file <path>) (--next-steps <json> | --resolves <json> | --no-loops) (--notes <json> | --no-notes) (--tasks-filed <json> | --no-tasks)',\n },\n async run(args, ctx) {\n const initiativeDir = path.join(ctx.activeRoot, args.slug);\n const briefPath = path.join(initiativeDir, 'brief.md');\n try {\n await fs.access(briefPath);\n } catch {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n\n const ledger: Ledger = {\n next_steps: parseLedger(args.next_steps, NextStepsSchema, 'next-steps'),\n resolves: parseLedger(args.resolves, ResolvesSchema, 'resolves'),\n };\n const notes = parseLedger(args.notes, NotesSchema, 'notes');\n const taskIds = parseLedger(args.tasks_filed, TaskIdsSchema, 'tasks-filed');\n requireAnswers(args, ledger, notes, taskIds);\n const body = args.body ?? (await fs.readFile(args.body_file!, 'utf8'));\n\n return withFileLock(getLockPath(args.slug), async () => {\n await verifyTaskIds(initiativeDir, taskIds);\n const written = await writeWrap(args, briefPath, body, ledger);\n let notePaths: string[] = [];\n let recorded = NOTHING_RECORDED;\n try {\n notePaths = await fileNotes(initiativeDir, notes, written.updated);\n recorded = await sweepAndRecord(args.slug, ctx.activeRoot, ctx.warnings);\n } catch (err) {\n await Promise.all([...notePaths, written.path].map((p) => fs.rm(p, { force: true })));\n throw err;\n }\n\n const total = ledger.resolves.length;\n const rejected = await rejectedResolves(initiativeDir, written.filename);\n const filed: Filed = {\n next_steps: ledger.next_steps.length,\n notes: notePaths.length,\n tasks: taskIds.length,\n ...recorded,\n };\n const result: Result = {\n path: written.path,\n filename: written.filename,\n ready_to_end: rejected.length === 0,\n filed,\n closed: { resolves_applied: total - rejected.length },\n resolves_rejected: rejected,\n updated: written.updated,\n files_updated: filesUpdated(initiativeDir, notePaths, filed),\n };\n if (rejected.length > 0) {\n ctx.warnings.push(rejectionReport(written.path, rejected, total));\n }\n return result;\n });\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport {\n SessionFrontmatterSchema,\n type NextStep,\n type SessionResolve,\n} from '../schemas/session.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { ValidationError } from '../errors.js';\n\nexport interface SessionWriteInput {\n slug: string;\n session_id: string;\n started: string;\n ended: string;\n track: 'canonical' | 'sidecar' | 'adhoc';\n body: string;\n next_steps?: NextStep[];\n resolves?: SessionResolve[];\n no_loops?: true;\n /**\n * Override the resolved active root. Migrations are handed the root they\n * operate on as an argument and must not fall back to the process-wide\n * `getActiveRoot()`, which would write into the operator's live data.\n */\n activeRoot?: string;\n}\n\nexport interface SessionWriteResult {\n path: string;\n filename: string;\n}\n\nfunction formatStartedStamp(started: string): string {\n const parsed = new Date(started);\n if (Number.isNaN(parsed.getTime())) {\n throw new ValidationError(`Invalid started timestamp: ${started}`);\n }\n const yyyy = parsed.getUTCFullYear().toString().padStart(4, '0');\n const mm = (parsed.getUTCMonth() + 1).toString().padStart(2, '0');\n const dd = parsed.getUTCDate().toString().padStart(2, '0');\n const hh = parsed.getUTCHours().toString().padStart(2, '0');\n const min = parsed.getUTCMinutes().toString().padStart(2, '0');\n return `${yyyy}-${mm}-${dd}-${hh}${min}`;\n}\n\n/**\n * The filename stem a session gets from its `started` + `session_id`, minus\n * the `.md` extension and any de-duplication suffix. This is the first half\n * of a loop ref (`<stem>#<next_step id>`), so callers that need to predict a\n * session's path — the v2→v3 migration, which keys idempotence on the exact\n * target path — must derive it from here rather than reimplementing it.\n */\nexport function buildSessionStem(started: string, sessionId: string): string {\n return `${formatStartedStamp(started)}-${sessionId}`;\n}\n\n/** Absolute path a session with this stem would occupy on a first write. */\nexport function sessionFilePathForStem(slug: string, stem: string, activeRoot?: string): string {\n return path.join(resolveSessionsDir(slug, activeRoot), `${stem}.md`);\n}\n\nfunction resolveSessionsDir(slug: string, activeRoot?: string): string {\n const dir = activeRoot === undefined ? getInitiativeDir(slug) : path.join(activeRoot, slug);\n return path.join(dir, 'sessions');\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function pickAvailableFilename(\n dir: string,\n baseName: string,\n): Promise<{ filename: string; fullPath: string }> {\n const initial = `${baseName}.md`;\n const initialPath = path.join(dir, initial);\n if (!(await exists(initialPath))) {\n return { filename: initial, fullPath: initialPath };\n }\n for (let i = 1; i < 10_000; i++) {\n const candidate = `${baseName}-${i}.md`;\n const candidatePath = path.join(dir, candidate);\n if (!(await exists(candidatePath))) {\n return { filename: candidate, fullPath: candidatePath };\n }\n }\n throw new Error(`Could not find an available filename for ${baseName}`);\n}\n\n/**\n * Write `<slug>/sessions/<YYYY-MM-DD-HHMM>-<session_id>.md`, validating the\n * frontmatter first. `wrap` is the only command that writes sessions through\n * here; `fold` writes its derived sidecars directly.\n */\nexport async function writeSessionFile(input: SessionWriteInput): Promise<SessionWriteResult> {\n const sessionsDir = resolveSessionsDir(input.slug, input.activeRoot);\n await fs.mkdir(sessionsDir, { recursive: true });\n\n const baseName = buildSessionStem(input.started, input.session_id);\n const { filename, fullPath } = await pickAvailableFilename(sessionsDir, baseName);\n\n await writeFrontmatter(\n fullPath,\n {\n session_id: input.session_id,\n started: input.started,\n ended: input.ended,\n track: input.track,\n next_steps: input.next_steps ?? [],\n resolves: input.resolves ?? [],\n ...(input.no_loops === true ? { no_loops: true } : {}),\n },\n input.body,\n SessionFrontmatterSchema,\n );\n\n return { path: fullPath, filename };\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { NOTE_TITLE_MAX_LENGTH, NoteKindSchema } from '../schemas/note.js';\nimport { writeNoteFile } from '../notes/note-file.js';\nimport { getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z\n .object({\n slug: z.string().min(1),\n kind: NoteKindSchema,\n title: z\n .string()\n .min(1)\n .max(NOTE_TITLE_MAX_LENGTH, {\n message: `Title must be at most ${NOTE_TITLE_MAX_LENGTH} characters — it is slugified into the filename`,\n }),\n body: z.string().optional(),\n body_file: z.string().optional(),\n tags: z.array(z.string().min(1)).optional(),\n })\n .superRefine((value, ctx) => {\n const hasBody = value.body !== undefined;\n const hasFile = value.body_file !== undefined;\n if (!hasBody && !hasFile) {\n ctx.addIssue({\n code: 'custom',\n path: ['body'],\n message: 'Exactly one of --body or --body-file is required',\n });\n }\n if (hasBody && hasFile) {\n ctx.addIssue({\n code: 'custom',\n path: ['body'],\n message: '--body and --body-file are mutually exclusive',\n });\n }\n });\n\nconst ResultSchema = z.object({\n path: z.string(),\n filename: z.string(),\n kind: NoteKindSchema,\n title: z.string(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'note.add',\n description:\n 'File a durable note under <slug>/sources/notes/ — a process lesson, gotcha, decision, or FYI that a future session needs but that no task would carry. Actionable work belongs in `task add` instead.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n kind: {\n long: '--kind',\n description: 'process | gotcha | fyi | decision',\n required: true,\n },\n title: {\n long: '--title',\n description: `Short title, at most ${NOTE_TITLE_MAX_LENGTH} chars (slugified into the filename)`,\n required: true,\n },\n body: { long: '--body', description: 'Raw markdown body' },\n body_file: {\n long: '--body-file',\n description: 'Path to a file containing the markdown body',\n },\n tags: { long: '--tags', description: 'Comma-separated tags' },\n },\n usage:\n 'active-work note add <slug> --kind <process|gotcha|fyi|decision> --title <text> (--body <text> | --body-file <path>) [--tags a,b]',\n },\n async run(args) {\n const initiativeDir = getInitiativeDir(args.slug);\n try {\n await fs.access(path.join(initiativeDir, 'brief.md'));\n } catch {\n throw new NotFoundError(`Initiative not found: ${args.slug}`);\n }\n\n const body = args.body ?? (await fs.readFile(args.body_file!, 'utf8'));\n const frontmatter = {\n kind: args.kind,\n title: args.title,\n created: today(),\n ...(args.tags && args.tags.length > 0 ? { tags: args.tags } : {}),\n };\n\n return withFileLock(getLockPath(args.slug), async () => {\n const written = await writeNoteFile(initiativeDir, frontmatter, body);\n return { ...written, kind: args.kind, title: args.title };\n });\n },\n});\n","import { z } from 'zod';\nimport { NoteKindSchema } from '../schemas/note.js';\nimport { loadNotesFromDir } from '../notes/note-file.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n kind: NoteKindSchema.optional(),\n});\n\nconst NoteEntrySchema = z.object({\n filename: z.string(),\n path: z.string(),\n kind: NoteKindSchema,\n title: z.string(),\n created: z.string(),\n tags: z.array(z.string()).optional(),\n});\n\nconst ResultSchema = z.object({\n notes: z.array(NoteEntrySchema),\n // Unreadable files are reported, never dropped: a note that silently\n // disappears is exactly the knowledge loss notes exist to prevent.\n errors: z.array(z.object({ filename: z.string(), error: z.string() })),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'note.list',\n description: 'List durable notes for an initiative, newest first.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n kind: {\n long: '--kind',\n description: 'Only notes of this kind: process | gotcha | fyi | decision',\n },\n },\n usage: 'active-work note list <slug> [--kind process|gotcha|fyi|decision]',\n },\n async run(args) {\n const { notes, malformed } = await loadNotesFromDir(getInitiativeDir(args.slug));\n const selected = args.kind\n ? notes.filter((note) => note.frontmatter.kind === args.kind)\n : notes;\n return {\n notes: selected.map((note) => ({\n filename: note.filename,\n path: note.path,\n kind: note.frontmatter.kind,\n title: note.frontmatter.title,\n created: note.frontmatter.created,\n ...(note.frontmatter.tags ? { tags: note.frontmatter.tags } : {}),\n })),\n errors: malformed.map((entry) => ({\n filename: entry.file,\n error: entry.reason,\n })),\n };\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { ArtifactsSchema } from '../schemas/artifacts.js';\nimport { getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n repo: z.string().min(1),\n name: z.string().min(1),\n note: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n branch: z.object({\n repo: z.string(),\n name: z.string(),\n note: z.string().optional(),\n }),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'artifact.add-branch',\n description: 'Append or upsert a branch entry in artifacts.yml.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n repo: { long: '--repo', description: 'Repo path or org/repo', required: true },\n name: { long: '--name', description: 'Branch name', required: true },\n note: { long: '--note', description: 'Why this branch is worth tracking' },\n },\n },\n async run(args) {\n const artifactsPath = path.join(getInitiativeDir(args.slug), 'artifacts.yml');\n return withFileLock(getLockPath(args.slug), async () => {\n const current = await readYaml(artifactsPath, ArtifactsSchema);\n const entry = {\n repo: args.repo,\n name: args.name,\n ...(args.note ? { note: args.note } : {}),\n };\n const idx = current.branches.findIndex((b) => b.repo === args.repo && b.name === args.name);\n if (idx >= 0) {\n // Preserve the prior note unless the caller supplied a new one.\n const prior = current.branches[idx]!;\n current.branches[idx] = {\n repo: args.repo,\n name: args.name,\n ...(args.note !== undefined\n ? { note: args.note }\n : prior.note !== undefined\n ? { note: prior.note }\n : {}),\n };\n } else {\n current.branches.push(entry);\n }\n await writeYaml(artifactsPath, current, ArtifactsSchema);\n return {\n slug: args.slug,\n branch: current.branches[idx >= 0 ? idx : current.branches.length - 1]!,\n };\n });\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { ArtifactsSchema } from '../schemas/artifacts.js';\nimport { getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n repo: z.string().min(1),\n label: z.string().min(1),\n sha: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n stash: z.object({\n repo: z.string(),\n label: z.string(),\n sha: z.string().optional(),\n }),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'artifact.add-stash',\n description: 'Append a stash entry to artifacts.yml.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n repo: { long: '--repo', description: 'Repo path', required: true },\n label: { long: '--label', description: 'Stash label', required: true },\n sha: { long: '--sha', description: 'Stash SHA, if known' },\n },\n },\n async run(args) {\n const artifactsPath = path.join(getInitiativeDir(args.slug), 'artifacts.yml');\n return withFileLock(getLockPath(args.slug), async () => {\n const current = await readYaml(artifactsPath, ArtifactsSchema);\n const entry = {\n repo: args.repo,\n label: args.label,\n ...(args.sha ? { sha: args.sha } : {}),\n };\n current.stashes.push(entry);\n await writeYaml(artifactsPath, current, ArtifactsSchema);\n return { slug: args.slug, stash: entry };\n });\n },\n});\n","import { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { ArtifactsSchema, type Artifacts } from '../schemas/artifacts.js';\nimport { getActiveRoot, getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml } from '../utils/yaml-io.js';\nimport { UsageError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().optional(),\n all_initiatives: z.boolean().optional(),\n});\n\nconst ItemSchema = z.object({\n slug: z.string(),\n artifacts: ArtifactsSchema,\n});\n\nconst ResultSchema = z.object({\n items: z.array(ItemSchema),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nasync function readForSlug(slug: string): Promise<Artifacts> {\n const artifactsPath = path.join(getInitiativeDir(slug), 'artifacts.yml');\n return withFileLock(getLockPath(slug), () => readYaml(artifactsPath, ArtifactsSchema));\n}\n\nasync function listInitiativeSlugs(): Promise<string[]> {\n const root = getActiveRoot();\n let entries: Dirent[];\n try {\n entries = await fs.readdir(root, { withFileTypes: true });\n } catch {\n return [];\n }\n const slugs: string[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (entry.name.startsWith('.')) continue;\n const artifactsPath = path.join(root, entry.name, 'artifacts.yml');\n try {\n await fs.access(artifactsPath);\n slugs.push(entry.name);\n } catch {\n // skip dirs without artifacts.yml\n }\n }\n slugs.sort();\n return slugs;\n}\n\nexport default defineCommand<Args, Result>({\n name: 'artifact.list',\n description: 'List artifacts for a slug or across all initiatives.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n all_initiatives: {\n long: '--all-initiatives',\n description: 'Return artifacts for every initiative',\n },\n },\n },\n async run(args) {\n if (args.all_initiatives) {\n const slugs = await listInitiativeSlugs();\n const items: Array<{ slug: string; artifacts: Artifacts }> = [];\n for (const slug of slugs) {\n items.push({ slug, artifacts: await readForSlug(slug) });\n }\n return { items };\n }\n if (!args.slug) {\n throw new UsageError('artifact.list requires <slug> or --all-initiatives');\n }\n const artifacts = await readForSlug(args.slug);\n return { items: [{ slug: args.slug, artifacts }] };\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { ArtifactsSchema } from '../schemas/artifacts.js';\nimport { getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { UsageError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n repo: z.string().min(1),\n name: z.string().min(1),\n note: z.string().min(1),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n branch: z.object({\n repo: z.string(),\n name: z.string(),\n note: z.string(),\n }),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'artifact.note',\n description: 'Set or update the free-form note on a tracked branch.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n repo: { long: '--repo', description: 'Repo path or org/repo', required: true },\n name: { long: '--name', description: 'Branch name', required: true },\n note: { long: '--note', description: 'Note text', required: true },\n },\n },\n async run(args) {\n const artifactsPath = path.join(getInitiativeDir(args.slug), 'artifacts.yml');\n return withFileLock(getLockPath(args.slug), async () => {\n const current = await readYaml(artifactsPath, ArtifactsSchema);\n const idx = current.branches.findIndex((b) => b.repo === args.repo && b.name === args.name);\n if (idx < 0) {\n throw new UsageError(\n `No tracked branch '${args.name}' in repo '${args.repo}'. Add it first via 'artifact add-branch'.`,\n );\n }\n const updated = { repo: args.repo, name: args.name, note: args.note };\n current.branches[idx] = updated;\n await writeYaml(artifactsPath, current, ArtifactsSchema);\n return { slug: args.slug, branch: updated };\n });\n },\n});\n","import path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport { z } from 'zod';\nimport { ArtifactsSchema, type BranchEntry, type WorktreeEntry } from '../schemas/artifacts.js';\nimport { getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { defineCommand } from '../registry/index.js';\nimport { getGitRunner, resolveLocalRepoPath } from '../utils/git-gh.js';\nimport { isWorktreePresent } from '../utils/git-worktrees.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n apply: z.boolean().optional(),\n});\n\nconst PrunedSchema = z.object({\n kind: z.enum(['branch', 'worktree']),\n repo: z.string(),\n /** The branch name, or the worktree path. */\n name: z.string(),\n reason: z.string(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n applied: z.boolean(),\n pruned: z.array(PrunedSchema),\n kept_count: z.number().int().nonnegative(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\ntype Pruned = z.infer<typeof PrunedSchema>;\ntype Verdict = { keep: true } | { keep: false; reason: string };\n\nasync function branchExists(repoPath: string, name: string): Promise<boolean> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', repoPath, 'rev-parse', '--verify', `refs/heads/${name}`]);\n return res.code === 0;\n } catch {\n return false;\n }\n}\n\nasync function classifyBranch(branch: BranchEntry): Promise<Verdict> {\n const repoPath = resolveLocalRepoPath(branch.repo);\n if (!repoPath) {\n // `org/repo` style — we have no local clone to verify against, so\n // keep it: prune should never delete a tracked branch we can't see.\n return { keep: true };\n }\n const present = await branchExists(repoPath, branch.name);\n if (present) return { keep: true };\n return { keep: false, reason: 'branch missing in local repo' };\n}\n\nasync function dirExists(dir: string): Promise<boolean> {\n try {\n return (await fs.stat(dir)).isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * A worktree is only prunable when its repo is here to vouch for its absence.\n * artifacts.yml travels between machines; a repo that is not cloned on this\n * one says nothing about whether the worktree exists where it was registered.\n */\nasync function classifyWorktree(entry: WorktreeEntry): Promise<Verdict> {\n const repoPath = resolveLocalRepoPath(entry.repo);\n if (!repoPath || !(await dirExists(repoPath))) return { keep: true };\n if (await isWorktreePresent(entry.path)) return { keep: true };\n return { keep: false, reason: 'worktree path missing' };\n}\n\nasync function partition<T>(\n entries: T[],\n classify: (entry: T) => Promise<Verdict>,\n describe: (entry: T) => Omit<Pruned, 'reason'>,\n): Promise<{ keep: T[]; pruned: Pruned[] }> {\n const keep: T[] = [];\n const pruned: Pruned[] = [];\n for (const entry of entries) {\n const verdict = await classify(entry);\n if (verdict.keep) keep.push(entry);\n else pruned.push({ ...describe(entry), reason: verdict.reason });\n }\n return { keep, pruned };\n}\n\nconst artifactPrune = defineCommand<Args, Result>({\n name: 'artifact.prune',\n description:\n 'List (default) or remove (--apply) tracked branches and worktrees that no longer exist locally.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n apply: {\n long: '--apply',\n description: 'Write the pruned artifacts.yml. Without this, dry-run only.',\n },\n },\n },\n async run(args) {\n const artifactsPath = path.join(getInitiativeDir(args.slug), 'artifacts.yml');\n const apply = args.apply ?? false;\n return withFileLock(getLockPath(args.slug), async () => {\n const current = await readYaml(artifactsPath, ArtifactsSchema);\n const branches = await partition(current.branches, classifyBranch, (b) => ({\n kind: 'branch',\n repo: b.repo,\n name: b.name,\n }));\n const worktrees = await partition(current.worktrees, classifyWorktree, (w) => ({\n kind: 'worktree',\n repo: w.repo,\n name: w.path,\n }));\n const pruned = [...branches.pruned, ...worktrees.pruned];\n if (apply && pruned.length > 0) {\n current.branches = branches.keep;\n current.worktrees = worktrees.keep;\n await writeYaml(artifactsPath, current, ArtifactsSchema);\n }\n return {\n slug: args.slug,\n applied: apply && pruned.length > 0,\n pruned,\n kept_count: branches.keep.length + worktrees.keep.length,\n };\n });\n },\n});\n\nexport default artifactPrune;\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { ArtifactsSchema, type WorktreeEntry } from '../schemas/artifacts.js';\nimport { getInitiativeDir, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readYaml } from '../utils/yaml-io.js';\nimport { defineCommand } from '../registry/index.js';\nimport {\n getGhRunner,\n getGitRunner,\n resolveLocalRepoPath,\n resolveOrgRepo,\n} from '../utils/git-gh.js';\nimport { readWorktreeState } from '../utils/git-worktrees.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n});\n\nconst PrInfoSchema = z.object({\n number: z.number().int(),\n state: z.string(),\n title: z.string(),\n url: z.string(),\n checks: z.string().optional(),\n});\n\nconst BranchStatusSchema = z.object({\n repo: z.string(),\n name: z.string(),\n note: z.string().optional(),\n present: z.boolean(),\n last_commit_iso: z.string().nullable(),\n ahead: z.number().int().nullable(),\n behind: z.number().int().nullable(),\n pr: PrInfoSchema.nullable(),\n error: z.string().optional(),\n});\n\n/**\n * Persisted worktree identity plus live state read from git. The live half\n * is never written back to `artifacts.yml` — see `src/schemas/artifacts.ts`.\n */\nconst WorktreeStatusSchema = z.object({\n path: z.string(),\n repo: z.string(),\n branch: z.string().nullable(),\n holding: z.string().optional(),\n pr: z.number().int().optional(),\n note: z.string().optional(),\n present: z.boolean(),\n /** Null when git could not read the tree. Unknown is not clean. */\n dirty: z.boolean().nullable(),\n files_changed: z.number().int().nullable(),\n ahead: z.number().int().nullable(),\n behind: z.number().int().nullable(),\n has_upstream: z.boolean(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n branches: z.array(BranchStatusSchema),\n worktrees: z.array(WorktreeStatusSchema),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\ntype BranchStatus = z.infer<typeof BranchStatusSchema>;\ntype WorktreeStatus = z.infer<typeof WorktreeStatusSchema>;\ntype PrInfo = z.infer<typeof PrInfoSchema>;\n\ninterface BranchInput {\n repo: string;\n name: string;\n note?: string;\n}\n\nconst MAX_CONCURRENCY = 8;\n\nexport { setGitRunner, setGhRunner, resetRunners } from '../utils/git-gh.js';\n\n/**\n * Bounded-parallel map. Runs `worker(item)` for each item in `items`,\n * with at most `concurrency` in-flight at any time. Preserves order.\n */\nasync function mapConcurrent<I, O>(\n items: I[],\n concurrency: number,\n worker: (item: I, index: number) => Promise<O>,\n): Promise<O[]> {\n const results: O[] = new Array(items.length);\n let cursor = 0;\n async function pump(): Promise<void> {\n while (true) {\n const i = cursor++;\n if (i >= items.length) return;\n results[i] = await worker(items[i]!, i);\n }\n }\n const lanes = Array.from({ length: Math.min(concurrency, items.length) }, () => pump());\n await Promise.all(lanes);\n return results;\n}\n\nasync function checkBranchPresent(repoPath: string, name: string): Promise<boolean> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', repoPath, 'rev-parse', '--verify', `refs/heads/${name}`]);\n return res.code === 0;\n } catch {\n return false;\n }\n}\n\nasync function lastCommitIso(repoPath: string, name: string): Promise<string | null> {\n const git = getGitRunner();\n try {\n const res = await git('git', ['-C', repoPath, 'log', '-1', '--format=%cI', name]);\n if (res.code !== 0) return null;\n const stamp = res.stdout.trim();\n return stamp.length > 0 ? stamp : null;\n } catch {\n return null;\n }\n}\n\nasync function detectDefaultBase(repoPath: string): Promise<string | null> {\n const git = getGitRunner();\n for (const candidate of ['main', 'master']) {\n try {\n const res = await git('git', [\n '-C',\n repoPath,\n 'rev-parse',\n '--verify',\n `refs/remotes/origin/${candidate}`,\n ]);\n if (res.code === 0) return candidate;\n } catch {\n // continue\n }\n }\n return null;\n}\n\nasync function aheadBehind(\n repoPath: string,\n name: string,\n): Promise<{ ahead: number | null; behind: number | null }> {\n const base = await detectDefaultBase(repoPath);\n if (!base) return { ahead: null, behind: null };\n const git = getGitRunner();\n try {\n const res = await git('git', [\n '-C',\n repoPath,\n 'rev-list',\n '--left-right',\n '--count',\n `origin/${base}...${name}`,\n ]);\n if (res.code !== 0) return { ahead: null, behind: null };\n // Output is \"<behind>\\t<ahead>\" (left is base, right is branch).\n const parts = res.stdout.trim().split(/\\s+/);\n if (parts.length !== 2) return { ahead: null, behind: null };\n const behind = Number(parts[0]);\n const ahead = Number(parts[1]);\n if (!Number.isFinite(behind) || !Number.isFinite(ahead)) {\n return { ahead: null, behind: null };\n }\n return { ahead, behind };\n } catch {\n return { ahead: null, behind: null };\n }\n}\n\nasync function fetchPrInfo(orgRepo: string, name: string): Promise<PrInfo | null> {\n const gh = getGhRunner();\n try {\n const res = await gh('gh', [\n 'pr',\n 'list',\n '--head',\n name,\n '--repo',\n orgRepo,\n '--json',\n 'number,state,title,url,statusCheckRollup',\n '--limit',\n '1',\n ]);\n if (res.code !== 0) return null;\n const parsed = JSON.parse(res.stdout) as Array<{\n number?: number;\n state?: string;\n title?: string;\n url?: string;\n statusCheckRollup?: Array<{ conclusion?: string; state?: string }>;\n }>;\n if (!Array.isArray(parsed) || parsed.length === 0) return null;\n const first = parsed[0]!;\n if (\n typeof first.number !== 'number' ||\n typeof first.state !== 'string' ||\n typeof first.title !== 'string' ||\n typeof first.url !== 'string'\n ) {\n return null;\n }\n const checks = summarizeChecks(first.statusCheckRollup ?? []);\n return {\n number: first.number,\n state: first.state,\n title: first.title,\n url: first.url,\n ...(checks ? { checks } : {}),\n };\n } catch {\n return null;\n }\n}\n\nfunction summarizeChecks(\n rollup: Array<{ conclusion?: string; state?: string }>,\n): string | undefined {\n if (rollup.length === 0) return undefined;\n let pass = 0;\n let fail = 0;\n let pending = 0;\n for (const entry of rollup) {\n const tag = (entry.conclusion ?? entry.state ?? '').toUpperCase();\n if (tag === 'SUCCESS') pass++;\n else if (tag === 'FAILURE' || tag === 'CANCELLED' || tag === 'TIMED_OUT') fail++;\n else pending++;\n }\n if (fail > 0) return `fail (${fail}/${rollup.length})`;\n if (pending > 0) return `pending (${pending}/${rollup.length})`;\n return `pass (${pass}/${rollup.length})`;\n}\n\nasync function statusForBranch(branch: BranchInput): Promise<BranchStatus> {\n const out: BranchStatus = {\n repo: branch.repo,\n name: branch.name,\n ...(branch.note ? { note: branch.note } : {}),\n present: false,\n last_commit_iso: null,\n ahead: null,\n behind: null,\n pr: null,\n };\n\n const repoPath = resolveLocalRepoPath(branch.repo);\n\n try {\n if (repoPath) {\n out.present = await checkBranchPresent(repoPath, branch.name);\n if (out.present) {\n out.last_commit_iso = await lastCommitIso(repoPath, branch.name);\n const { ahead, behind } = await aheadBehind(repoPath, branch.name);\n out.ahead = ahead;\n out.behind = behind;\n }\n }\n\n const orgRepo = await resolveOrgRepo(branch.repo);\n if (orgRepo) {\n out.pr = await fetchPrInfo(orgRepo, branch.name);\n }\n } catch (err) {\n out.error = err instanceof Error ? err.message : String(err);\n }\n\n return out;\n}\n\nasync function statusForWorktree(entry: WorktreeEntry): Promise<WorktreeStatus> {\n const live = await readWorktreeState(entry.path);\n return {\n path: entry.path,\n repo: entry.repo,\n branch: live.branch ?? entry.branch ?? null,\n ...(entry.holding ? { holding: entry.holding } : {}),\n ...(entry.pr ? { pr: entry.pr } : {}),\n ...(entry.note ? { note: entry.note } : {}),\n present: live.present,\n dirty: live.dirty,\n files_changed: live.files_changed,\n ahead: live.ahead,\n behind: live.behind,\n has_upstream: live.has_upstream,\n };\n}\n\nconst artifactStatus = defineCommand<Args, Result>({\n name: 'artifact.status',\n description: 'Pull live PR and branch state for the initiative via `git` + `gh`. Read-only.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n },\n async run(args) {\n const artifactsPath = path.join(getInitiativeDir(args.slug), 'artifacts.yml');\n const current = await withFileLock(getLockPath(args.slug), () =>\n readYaml(artifactsPath, ArtifactsSchema),\n );\n const branches = await mapConcurrent(current.branches, MAX_CONCURRENCY, statusForBranch);\n const worktrees = await mapConcurrent(current.worktrees, MAX_CONCURRENCY, statusForWorktree);\n return { slug: args.slug, branches, worktrees };\n },\n});\n\nexport default artifactStatus;\n","import { z } from 'zod';\nimport { listSources } from '../sources/list.js';\nimport { lintSources } from '../lint/sources.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n type: z.enum(['pr', 'deepdive', 'session', 'pointer']).optional(),\n});\n\nconst SourceEntrySchema = z.object({\n filename: z.string(),\n path: z.string(),\n type: z.enum(['pr', 'deepdive', 'session', 'pointer']),\n title: z.string(),\n});\n\nconst ResultSchema = z.object({\n sources: z.array(SourceEntrySchema),\n // Drift between the directory and brief.md's hand-written references. Empty\n // when the brief keeps no reference list at all.\n drift: z.array(z.string()),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'source.list',\n description:\n \"List an initiative's sources, derived by reading sources/*.md — never a stored index.\",\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug'],\n options: {\n type: {\n long: '--type',\n description: 'Only sources of this type: pr | deepdive | session | pointer',\n },\n },\n usage: 'active-work source list <slug> [--type pr|deepdive|session|pointer]',\n },\n async run(args) {\n const initiativeDir = getInitiativeDir(args.slug);\n const sources = await listSources(initiativeDir);\n const selected = args.type ? sources.filter((entry) => entry.type === args.type) : sources;\n const findings = await lintSources(args.slug, initiativeDir);\n return {\n sources: selected,\n drift: findings.map((finding) => finding.message),\n };\n },\n});\n","/**\n * Sources are the external material an initiative accumulates: PR write-ups,\n * deep dives, session transcripts, pointers. They live as plain files under\n * `<initiative>/sources/`.\n *\n * There is deliberately no sidecar index and no `sources:` frontmatter field.\n * The listing is derived by reading the directory every time it is asked for,\n * so it cannot drift from what is actually on disk — a hand-maintained list\n * always eventually omits a file someone dropped in by hand (AW-80).\n */\n\nimport { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\n\n/** Naming conventions written by `source add`; see `deriveFilename` there. */\nexport type SourceType = 'pr' | 'deepdive' | 'session' | 'pointer';\n\nexport interface SourceEntry {\n /** Filename including `.md`. */\n filename: string;\n path: string;\n type: SourceType;\n /** First markdown heading, falling back to the filename stem. */\n title: string;\n}\n\n/** Resolve the sources directory for an initiative directory. */\nexport function getSourcesDir(initiativeDir: string): string {\n return path.join(initiativeDir, 'sources');\n}\n\nconst PR_FILENAME = /^pr-(\\d+)-/;\nconst DEEPDIVE_FILENAME = /^deepdive-/;\nconst SESSION_FILENAME = /^\\d{4}-\\d{2}-\\d{2}-/;\n\nfunction inferType(filename: string): SourceType {\n if (PR_FILENAME.test(filename)) return 'pr';\n if (DEEPDIVE_FILENAME.test(filename)) return 'deepdive';\n if (SESSION_FILENAME.test(filename)) return 'session';\n return 'pointer';\n}\n\nfunction firstHeading(contents: string): string | undefined {\n for (const line of contents.split('\\n', 200)) {\n const match = /^#{1,6}\\s+(.+?)\\s*$/.exec(line);\n if (match) return match[1];\n }\n return undefined;\n}\n\nasync function readTitle(filePath: string, filename: string): Promise<string> {\n const stem = filename.replace(/\\.md$/, '');\n try {\n const contents = await fs.readFile(filePath, 'utf8');\n return firstHeading(contents) ?? stem;\n } catch {\n return stem;\n }\n}\n\n/**\n * List an initiative's sources by reading `sources/*.md` at call time.\n *\n * Top-level files only: `sources/notes/` is the durable-notes store with its\n * own reader (`loadNotesFromDir`) and its own place in the bootstrap, so\n * folding it in here would double-report it. A missing `sources/` yields an\n * empty list rather than throwing — every caller treats \"no sources\" and \"no\n * directory yet\" the same way.\n */\nexport async function listSources(initiativeDir: string): Promise<SourceEntry[]> {\n const dir = getSourcesDir(initiativeDir);\n let entries: Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return [];\n }\n const filenames = entries\n .filter((e) => e.isFile() && e.name.endsWith('.md') && !e.name.startsWith('.'))\n .map((e) => e.name)\n .sort();\n\n return Promise.all(\n filenames.map(async (filename) => {\n const fullPath = path.join(dir, filename);\n return {\n filename,\n path: fullPath,\n type: inferType(filename),\n title: await readTitle(fullPath, filename),\n };\n }),\n );\n}\n\n/** Every `sources/...md` path mentioned in a chunk of markdown, deduped. */\nexport function extractSourceReferences(body: string): string[] {\n const matches = body.matchAll(/sources\\/([A-Za-z0-9._/-]+\\.md)/g);\n const seen = new Set<string>();\n for (const match of matches) {\n seen.add(match[1]);\n }\n return [...seen].sort();\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readRawFrontmatter } from '../utils/gray-matter-io.js';\nimport { extractSourceReferences, listSources } from '../sources/list.js';\nimport type { LintFinding } from './types.js';\n\nasync function fileExists(target: string): Promise<boolean> {\n try {\n await fs.access(target);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Flag drift between `sources/` on disk and the references hand-written in\n * `brief.md`.\n *\n * The listing itself is always derived from the directory (`source list`), so\n * this rule is about the prose: a brief that keeps a References section is\n * making a promise it has to keep. Two ways it breaks:\n *\n * - it links a `sources/...md` that no longer exists (rename, delete, typo);\n * - a file lands in `sources/` and never gets mentioned — the case that\n * actually bit us, where the References list silently under-reported what\n * the initiative knew.\n *\n * The unmentioned-file rule only fires once a brief references *some* source,\n * because that is the signal it maintains a list at all. Briefs that never\n * link into `sources/` are not silently broken and must not be nagged.\n */\nexport async function lintSources(slug: string, initiativeDir: string): Promise<LintFinding[]> {\n const briefPath = path.join(initiativeDir, 'brief.md');\n if (!(await fileExists(briefPath))) return [];\n\n const { body } = await readRawFrontmatter(briefPath);\n const referenced = extractSourceReferences(body);\n if (referenced.length === 0) return [];\n\n const findings: LintFinding[] = [];\n\n for (const ref of referenced) {\n const target = path.join(initiativeDir, 'sources', ref);\n if (!(await fileExists(target))) {\n findings.push({\n level: 'warn',\n slug,\n file: 'brief.md',\n message: `references sources/${ref}, which does not exist — fix the link or restore the file`,\n });\n }\n }\n\n const onDisk = await listSources(initiativeDir);\n const missing = onDisk\n .map((entry) => entry.filename)\n .filter((filename) => !referenced.includes(filename));\n\n if (missing.length > 0) {\n findings.push({\n level: 'warn',\n slug,\n file: 'brief.md',\n message:\n `references some sources but not ${missing.map((m) => `sources/${m}`).join(', ')} — ` +\n `the hand-written list drifted; \\`active-work source list ${slug}\\` derives it from the directory`,\n });\n }\n\n return findings;\n}\n","import path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport type { Dirent } from 'node:fs';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getActiveRoot, expandTilde } from '../utils/paths.js';\nimport { readRegisteredWorktrees, type RegisteredWorktree } from '../utils/registered-worktrees.js';\nimport { readFrontmatter } from '../utils/gray-matter-io.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst argsSchema = z.object({}).strict();\n\nconst initiativeSummarySchema = z.object({\n slug: z.string(),\n title: z.string(),\n state: z.enum(['focused', 'backburner', 'paused', 'done']),\n rank: z.number().int().positive().optional(),\n updated: z.string(),\n ship_target: z.string().optional(),\n});\n\nconst parseErrorSchema = z.object({\n slug: z.string(),\n error: z.string(),\n});\n\nconst conflictSchema = z.object({\n path: z.string(),\n slugs: z.array(z.string()),\n});\n\nconst resultSchema = z.object({\n initiatives: z.array(initiativeSummarySchema),\n parse_errors: z.array(parseErrorSchema),\n worktree_conflicts: z.array(conflictSchema),\n});\n\nconst STATE_ORDER: Record<BriefFrontmatter['state'], number> = {\n focused: 0,\n backburner: 1,\n paused: 2,\n done: 3,\n};\n\nexport interface ScanEntry {\n slug: string;\n frontmatter: BriefFrontmatter;\n /** Registered worktrees, which moved to artifacts.yml in v4 (AW-67). */\n worktrees: RegisteredWorktree[];\n}\n\nexport interface ScanError {\n slug: string;\n error: string;\n}\n\nexport interface ScanResult {\n entries: ScanEntry[];\n errors: ScanError[];\n}\n\nexport async function scanInitiatives(activeRoot: string): Promise<ScanResult> {\n let dirents: Dirent[];\n try {\n dirents = await fs.readdir(activeRoot, { withFileTypes: true });\n } catch {\n return { entries: [], errors: [] };\n }\n\n const entries: ScanEntry[] = [];\n const errors: ScanError[] = [];\n\n for (const dirent of dirents) {\n if (!dirent.isDirectory()) continue;\n if (dirent.name.startsWith('.')) continue;\n const slug = dirent.name;\n const briefPath = path.join(activeRoot, slug, 'brief.md');\n try {\n await fs.access(briefPath);\n } catch {\n continue;\n }\n try {\n const { frontmatter } = await readFrontmatter(briefPath, BriefFrontmatterSchema);\n const worktrees = await readRegisteredWorktrees(path.join(activeRoot, slug));\n entries.push({ slug, frontmatter, worktrees });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n errors.push({ slug, error: message });\n }\n }\n\n return { entries, errors };\n}\n\nfunction detectWorktreeConflicts(entries: ScanEntry[]): Array<{ path: string; slugs: string[] }> {\n const byPath = new Map<string, Set<string>>();\n for (const { slug, worktrees } of entries) {\n // Only registered worktrees conflict. Two initiatives whose sweeps both\n // observed the same directory have not laid claim to it.\n for (const entry of worktrees) {\n const resolved = path.resolve(expandTilde(entry.path));\n let bucket = byPath.get(resolved);\n if (!bucket) {\n bucket = new Set();\n byPath.set(resolved, bucket);\n }\n bucket.add(slug);\n }\n }\n const conflicts: Array<{ path: string; slugs: string[] }> = [];\n for (const [resolved, slugs] of byPath) {\n if (slugs.size > 1) {\n conflicts.push({ path: resolved, slugs: [...slugs].sort() });\n }\n }\n conflicts.sort((a, b) => a.path.localeCompare(b.path));\n return conflicts;\n}\n\nfunction compareInitiatives(a: ScanEntry, b: ScanEntry): number {\n const aRank = a.frontmatter.rank ?? Number.POSITIVE_INFINITY;\n const bRank = b.frontmatter.rank ?? Number.POSITIVE_INFINITY;\n if (aRank !== bRank) return aRank - bRank;\n const aState = STATE_ORDER[a.frontmatter.state];\n const bState = STATE_ORDER[b.frontmatter.state];\n if (aState !== bState) return aState - bState;\n return a.slug.localeCompare(b.slug);\n}\n\nexport default defineCommand({\n name: 'audit',\n description:\n 'Cross-initiative summary: lists every initiative, parse failures, and worktree path conflicts.',\n args: argsSchema,\n result: resultSchema,\n cli: {},\n async run() {\n const activeRoot = getActiveRoot();\n const { entries, errors } = await scanInitiatives(activeRoot);\n const initiatives = [...entries].sort(compareInitiatives).map(({ slug, frontmatter }) => ({\n slug,\n title: frontmatter.title,\n state: frontmatter.state,\n ...(frontmatter.rank !== undefined ? { rank: frontmatter.rank } : {}),\n updated: frontmatter.updated,\n ...(frontmatter.ship_target !== undefined ? { ship_target: frontmatter.ship_target } : {}),\n }));\n return {\n initiatives,\n parse_errors: errors,\n worktree_conflicts: detectWorktreeConflicts(entries),\n };\n },\n});\n","/**\n * Deterministic ID-join lookup across an active root (AW-85).\n *\n * The data model cross-references by ID — task ids (`AW-12`), loop refs\n * (`<session file stem>#<next_step id>`), and artifact branch/worktree names\n * that embed a task id. Tracing those links used to mean hand-rolled grep.\n *\n * This command is *exact-join only*: every match is a literal, token-bounded\n * occurrence of the queried id. Topic/paraphrase similarity (\"related sources\n * by topic\") is deliberately NOT here — it is a separate, fuzzy concern and\n * bundling it would make these results non-deterministic.\n */\nimport { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { TaskSchema } from '../schemas/task.js';\nimport { SessionFrontmatterSchema } from '../schemas/session.js';\nimport { ArtifactsSchema, type Artifacts } from '../schemas/artifacts.js';\nimport { getActiveRoot, getInitiativeDir } from '../utils/paths.js';\nimport { readYaml } from '../utils/yaml-io.js';\nimport { readFrontmatter } from '../utils/gray-matter-io.js';\n\nconst TASK_ID_REGEX = /^[A-Z][A-Z0-9]*-\\d+$/;\nconst MAX_SNIPPET = 160;\n\nconst ArgsSchema = z.object({\n id: z.string().min(1),\n slug: z.string().min(1).optional(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ReferenceSchema = z.object({\n slug: z.string(),\n source: z.enum(['task', 'session', 'artifacts']),\n /** Path relative to the initiative directory. */\n file: z.string(),\n /** Dotted/indexed path of the field that carried the match. */\n field: z.string(),\n text: z.string(),\n});\n\nconst SubjectSchema = z.object({\n kind: z.enum(['task', 'session', 'loop']),\n slug: z.string(),\n file: z.string(),\n title: z.string(),\n});\n\nconst ResultSchema = z.object({\n id: z.string(),\n kind: z.enum(['task', 'session', 'loop']),\n subject: SubjectSchema.nullable(),\n references: z.array(ReferenceSchema),\n initiatives_scanned: z.array(z.string()),\n errors: z.array(z.object({ file: z.string(), error: z.string() })),\n});\n\ntype Reference = z.infer<typeof ReferenceSchema>;\ntype Subject = z.infer<typeof SubjectSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\n/** Accumulates one initiative's worth of findings. */\ninterface Scan {\n references: Reference[];\n errors: { file: string; error: string }[];\n subject: Subject | null;\n}\n\n/**\n * Classify the query lexically. `#` is the loop-ref separator and is banned\n * from both halves of a ref, so its presence is unambiguous.\n */\nfunction classify(id: string): 'task' | 'loop' | 'session' {\n if (id.includes('#')) return 'loop';\n if (TASK_ID_REGEX.test(id)) return 'task';\n return 'session';\n}\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Token-bounded, case-insensitive matcher. Case-insensitive because task ids\n * appear lowercased inside branch names (`feat/aw-85-context-graph`); the\n * alphanumeric guards keep `AW-8` from matching `AW-85`.\n */\nfunction buildMatcher(id: string): RegExp {\n return new RegExp(`(?<![A-Za-z0-9])${escapeRegex(id)}(?![A-Za-z0-9])`, 'i');\n}\n\nfunction snippet(text: string): string {\n const trimmed = text.trim();\n return trimmed.length > MAX_SNIPPET ? `${trimmed.slice(0, MAX_SNIPPET)}…` : trimmed;\n}\n\nasync function listSlugs(): Promise<string[]> {\n let entries: Dirent[];\n try {\n entries = await fs.readdir(getActiveRoot(), { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n return entries\n .filter((e) => e.isDirectory() && !e.name.startsWith('.'))\n .map((e) => e.name)\n .sort();\n}\n\nasync function listFiles(dir: string, ext: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(dir);\n return entries.filter((e) => e.endsWith(ext)).sort();\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n}\n\n/** Emit a reference for every free-text field that literally contains the id. */\nfunction matchFields(\n match: RegExp,\n base: Omit<Reference, 'field' | 'text'>,\n fields: [field: string, value: string | undefined][],\n): Reference[] {\n const out: Reference[] = [];\n for (const [field, value] of fields) {\n if (value && match.test(value)) {\n out.push({ ...base, field, text: snippet(value) });\n }\n }\n return out;\n}\n\nasync function scanTasks(slug: string, id: string, match: RegExp, scan: Scan) {\n const dir = path.join(getInitiativeDir(slug), 'tasks');\n for (const file of await listFiles(dir, '.yml')) {\n const rel = path.join('tasks', file);\n try {\n const task = await readYaml(path.join(dir, file), TaskSchema);\n if (task.id === id) {\n scan.subject = { kind: 'task', slug, file: rel, title: task.title };\n continue;\n }\n const base = { slug, source: 'task' as const, file: rel };\n scan.references.push(\n ...matchFields(match, base, [\n ['title', task.title],\n ['done_when', task.done_when],\n ['notes', task.notes],\n ['tags', (task.tags ?? []).join(', ')],\n ]),\n );\n } catch (err) {\n scan.errors.push({ file: rel, error: errorText(err) });\n }\n }\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Body matches are reported per line so the caller gets a locatable hit. */\nfunction matchBody(\n match: RegExp,\n base: Omit<Reference, 'field' | 'text'>,\n body: string,\n): Reference[] {\n const out: Reference[] = [];\n body.split(/\\r?\\n/).forEach((line, index) => {\n if (match.test(line)) {\n out.push({ ...base, field: `body:L${index + 1}`, text: snippet(line) });\n }\n });\n return out;\n}\n\ninterface SessionScanInput {\n slug: string;\n stem: string;\n rel: string;\n id: string;\n match: RegExp;\n frontmatter: z.infer<typeof SessionFrontmatterSchema>;\n body: string;\n}\n\n/**\n * The loop a `<stem>#<step id>` query names is the *subject*, not a reference\n * to itself — everything else in the same file is still fair game.\n */\nfunction scanSessionFile(input: SessionScanInput, scan: Scan): void {\n const { slug, stem, rel, id, match, frontmatter, body } = input;\n const base = { slug, source: 'session' as const, file: rel };\n\n if (id === stem || id === frontmatter.session_id) {\n scan.subject = { kind: 'session', slug, file: rel, title: stem };\n }\n\n frontmatter.next_steps.forEach((step, i) => {\n if (`${stem}#${step.id}` === id) {\n scan.subject = { kind: 'loop', slug, file: rel, title: step.text };\n return;\n }\n scan.references.push(\n ...matchFields(match, base, [\n [`next_steps[${i}].ref`, step.ref],\n [`next_steps[${i}].text`, step.text],\n ]),\n );\n });\n\n frontmatter.resolves.forEach((entry, i) => {\n scan.references.push(\n ...matchFields(match, base, [\n [`resolves[${i}].ref`, entry.ref],\n [`resolves[${i}].note`, entry.note],\n ]),\n );\n });\n\n scan.references.push(...matchBody(match, base, body));\n}\n\nasync function scanSessions(slug: string, id: string, match: RegExp, scan: Scan) {\n const dir = path.join(getInitiativeDir(slug), 'sessions');\n for (const file of await listFiles(dir, '.md')) {\n const rel = path.join('sessions', file);\n try {\n const { frontmatter, body } = await readFrontmatter(\n path.join(dir, file),\n SessionFrontmatterSchema,\n );\n const stem = file.slice(0, -'.md'.length);\n scanSessionFile({ slug, stem, rel, id, match, frontmatter, body }, scan);\n } catch (err) {\n scan.errors.push({ file: rel, error: errorText(err) });\n }\n }\n}\n\nfunction artifactFields(artifacts: Artifacts): [field: string, value: string | undefined][] {\n const fields: [string, string | undefined][] = [];\n artifacts.branches.forEach((b, i) => {\n fields.push([`branches[${i}].name`, b.name], [`branches[${i}].note`, b.note]);\n });\n artifacts.stashes.forEach((s, i) => {\n fields.push([`stashes[${i}].label`, s.label]);\n });\n artifacts.worktrees.forEach((w, i) => {\n fields.push(\n [`worktrees[${i}].branch`, w.branch],\n [`worktrees[${i}].holding`, w.holding],\n [`worktrees[${i}].note`, w.note],\n );\n });\n return fields;\n}\n\nasync function scanArtifacts(slug: string, match: RegExp, scan: Scan) {\n const rel = 'artifacts.yml';\n const file = path.join(getInitiativeDir(slug), rel);\n try {\n await fs.access(file);\n } catch {\n return;\n }\n try {\n const artifacts = await readYaml(file, ArtifactsSchema);\n const base = { slug, source: 'artifacts' as const, file: rel };\n scan.references.push(...matchFields(match, base, artifactFields(artifacts)));\n } catch (err) {\n scan.errors.push({ file: rel, error: errorText(err) });\n }\n}\n\nexport default defineCommand<Args, Result>({\n name: 'context.graph',\n description:\n 'Trace every exact-ID reference to a task id, session, or loop ref across tasks, sessions, and artifacts',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['id'],\n options: {\n slug: {\n long: '--slug',\n description: 'Limit the scan to one initiative (default: every initiative)',\n },\n },\n usage: 'context graph <id> [--slug SLUG]',\n },\n async run(args) {\n const match = buildMatcher(args.id);\n const slugs = args.slug ? [args.slug] : await listSlugs();\n\n const scan: Scan = { references: [], errors: [], subject: null };\n for (const slug of slugs) {\n await scanTasks(slug, args.id, match, scan);\n await scanSessions(slug, args.id, match, scan);\n await scanArtifacts(slug, match, scan);\n }\n\n return {\n id: args.id,\n kind: classify(args.id),\n subject: scan.subject,\n references: scan.references,\n initiatives_scanned: slugs,\n errors: scan.errors,\n };\n },\n});\n","import { z } from 'zod';\nimport type { BriefFrontmatter } from '../schemas/brief.js';\nimport { getActiveRoot } from '../utils/paths.js';\nimport { scanInitiatives } from './audit.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst argsSchema = z.object({}).strict();\n\nconst itemSchema = z.object({\n slug: z.string(),\n title: z.string(),\n state: z.enum(['focused', 'backburner', 'paused', 'done']),\n rank: z.number().int().positive().optional(),\n ship_target: z.string().optional(),\n paused_since: z.string().optional(),\n updated: z.string(),\n});\n\nconst sectionSchema = z.object({\n heading: z.string(),\n items: z.array(itemSchema),\n});\n\nconst parseErrorSchema = z.object({\n slug: z.string(),\n error: z.string(),\n});\n\nconst resultSchema = z.object({\n sections: z.array(sectionSchema),\n parse_errors: z.array(parseErrorSchema),\n});\n\ninterface Item {\n slug: string;\n title: string;\n state: BriefFrontmatter['state'];\n rank?: number;\n ship_target?: string;\n paused_since?: string;\n updated: string;\n}\n\nfunction toItem(slug: string, fm: BriefFrontmatter): Item {\n return {\n slug,\n title: fm.title,\n state: fm.state,\n ...(fm.rank !== undefined ? { rank: fm.rank } : {}),\n ...(fm.ship_target !== undefined ? { ship_target: fm.ship_target } : {}),\n ...(fm.paused_since !== undefined ? { paused_since: fm.paused_since } : {}),\n updated: fm.updated,\n };\n}\n\nexport default defineCommand({\n name: 'list',\n description: 'List every initiative grouped by state. Replaces the legacy INDEX.md dump.',\n args: argsSchema,\n result: resultSchema,\n cli: {\n usage: 'list',\n },\n async run() {\n const activeRoot = getActiveRoot();\n const { entries, errors } = await scanInitiatives(activeRoot);\n\n const focused: Item[] = [];\n const backburner: Item[] = [];\n const paused: Item[] = [];\n const done: Item[] = [];\n\n for (const { slug, frontmatter } of entries) {\n const item = toItem(slug, frontmatter);\n switch (frontmatter.state) {\n case 'focused':\n focused.push(item);\n break;\n case 'backburner':\n backburner.push(item);\n break;\n case 'paused':\n paused.push(item);\n break;\n case 'done':\n done.push(item);\n break;\n }\n }\n\n focused.sort((a, b) => {\n const aRank = a.rank ?? Number.POSITIVE_INFINITY;\n const bRank = b.rank ?? Number.POSITIVE_INFINITY;\n if (aRank !== bRank) return aRank - bRank;\n return a.slug.localeCompare(b.slug);\n });\n backburner.sort((a, b) => a.slug.localeCompare(b.slug));\n paused.sort((a, b) => {\n const aPaused = a.paused_since ?? '';\n const bPaused = b.paused_since ?? '';\n if (aPaused !== bPaused) return aPaused.localeCompare(bPaused);\n return a.slug.localeCompare(b.slug);\n });\n done.sort((a, b) => {\n if (a.updated !== b.updated) return b.updated.localeCompare(a.updated);\n return a.slug.localeCompare(b.slug);\n });\n\n return {\n sections: [\n { heading: 'Focused', items: focused },\n { heading: 'Backburner', items: backburner },\n { heading: 'Paused', items: paused },\n { heading: 'Done', items: done },\n ],\n parse_errors: errors,\n };\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport type { WorktreeEntry } from '../schemas/artifacts.js';\nimport { getActiveRoot, getLockPath, expandTilde } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readArtifactsFile, writeArtifactsFile } from '../utils/registered-worktrees.js';\nimport { readFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst argsSchema = z.object({\n slug: z.string().min(1),\n path: z.string().min(1),\n label: z.string().min(1).optional(),\n default: z.boolean().optional(),\n});\n\nconst resultSchema = z.object({\n slug: z.string(),\n label: z.string(),\n path: z.string(),\n default: z.boolean(),\n /** True when this promoted a worktree `wrap` had already swept (AW-67). */\n promoted: z.boolean(),\n});\n\nconst DEFAULT_LABEL = 'main';\n\nconst samePath = (a: string, b: string): boolean =>\n path.resolve(expandTilde(a)) === path.resolve(expandTilde(b));\n\nexport default defineCommand({\n name: 'worktree.set',\n description:\n 'Add or update a registered worktree on an existing initiative. A lone worktree is made default automatically; use --default to promote an added one. Registered worktrees live in artifacts.yml alongside the ones wrap sweeps, and are what `aw` resolves a cwd against.',\n args: argsSchema,\n result: resultSchema,\n cli: {\n positional: ['slug', 'path'],\n options: {\n label: {\n long: '--label',\n description: `Worktree label (default: ${DEFAULT_LABEL}).`,\n },\n default: {\n long: '--default',\n description: 'Mark this worktree as the default, clearing default on others.',\n },\n },\n usage: 'active-work worktree.set <slug> <path> [--label <label>] [--default]',\n },\n async run(args) {\n const label = args.label ?? DEFAULT_LABEL;\n const initiativeDir = path.join(getActiveRoot(), args.slug);\n const briefPath = path.join(initiativeDir, 'brief.md');\n return withFileLock(getLockPath(args.slug), async () => {\n let frontmatter: BriefFrontmatter;\n let body: string;\n try {\n ({ frontmatter, body } = await readFrontmatter(briefPath, BriefFrontmatterSchema));\n } catch (err) {\n throw new ValidationError(err instanceof Error ? err.message : String(err));\n }\n\n const artifacts = await readArtifactsFile(initiativeDir);\n const byLabel = artifacts.worktrees.find((entry) => entry.name === label);\n // An unnamed entry at this path was swept by `wrap`. Naming it promotes it\n // in place rather than adding a second record of the same directory.\n const swept = artifacts.worktrees.find(\n (entry) => entry.name === undefined && samePath(entry.path, args.path),\n );\n const target = byLabel ?? swept;\n\n // Default when: explicitly requested, this is the only registered\n // worktree, or we're updating a label that was already the default (don't\n // silently demote it).\n const named = artifacts.worktrees.filter((e) => e.name !== undefined);\n const hadOthers = named.some((entry) => entry.name !== label);\n const makeDefault = args.default === true || !hadOthers || byLabel?.default === true;\n\n const updated: WorktreeEntry = {\n ...(target ?? {}),\n path: args.path,\n repo: target?.repo ?? args.path,\n name: label,\n ...(makeDefault ? { default: true } : {}),\n };\n if (!makeDefault) delete updated.default;\n\n const rest = artifacts.worktrees\n .filter((entry) => entry !== target)\n .map((entry) => {\n if (!makeDefault || entry.default !== true) return entry;\n // A new default clears the flag everywhere else.\n const cleared = { ...entry };\n delete cleared.default;\n return cleared;\n });\n\n await writeArtifactsFile(initiativeDir, {\n ...artifacts,\n worktrees: [...rest, updated],\n });\n await writeFrontmatter(\n briefPath,\n { ...frontmatter, updated: today() },\n body,\n BriefFrontmatterSchema,\n );\n return {\n slug: args.slug,\n label,\n path: args.path,\n default: makeDefault,\n promoted: byLabel === undefined && swept !== undefined,\n };\n });\n },\n});\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { getActiveRoot, getLockPath } from '../utils/paths.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readArtifactsFile, writeArtifactsFile } from '../utils/registered-worktrees.js';\nimport { readFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { today } from '../utils/today.js';\nimport { NotFoundError, ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\nconst argsSchema = z.object({\n slug: z.string().min(1),\n label: z.string().min(1),\n});\n\nconst resultSchema = z.object({\n slug: z.string(),\n default_label: z.string(),\n});\n\nexport default defineCommand({\n name: 'worktree.set-default',\n description:\n 'Mark the named worktree label as default for an initiative; clears default on other labels.',\n args: argsSchema,\n result: resultSchema,\n cli: {\n positional: ['slug', 'label'],\n },\n async run({ slug, label }) {\n const initiativeDir = path.join(getActiveRoot(), slug);\n const briefPath = path.join(initiativeDir, 'brief.md');\n return withFileLock(getLockPath(slug), async () => {\n let frontmatter: BriefFrontmatter;\n let body: string;\n try {\n ({ frontmatter, body } = await readFrontmatter(briefPath, BriefFrontmatterSchema));\n } catch (err) {\n throw new ValidationError(err instanceof Error ? err.message : String(err));\n }\n const artifacts = await readArtifactsFile(initiativeDir);\n if (!artifacts.worktrees.some((entry) => entry.name === label)) {\n throw new NotFoundError(`Worktree label \"${label}\" is not registered for \"${slug}\"`);\n }\n const worktrees = artifacts.worktrees.map((entry) => {\n const next = { ...entry };\n delete next.default;\n return entry.name === label ? { ...next, default: true } : next;\n });\n await writeArtifactsFile(initiativeDir, { ...artifacts, worktrees });\n await writeFrontmatter(\n briefPath,\n { ...frontmatter, updated: today() },\n body,\n BriefFrontmatterSchema,\n );\n return { slug, default_label: label };\n });\n },\n});\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { runDiscovery } from '../discover/index.js';\n\n/**\n * `active-work discover` — orchestrates every configured discovery source and emits\n * a flat list of hits. Always non-interactive; Claude is the primary\n * caller, and a human can pipe to a picker.\n */\n\nconst ArgsSchema = z.object({\n github_repos: z.array(z.string().min(1)).optional(),\n local_repos: z.array(z.string().min(1)).optional(),\n projects_root: z.string().optional(),\n});\n\nconst HitSchema = z.object({\n source: z.string(),\n ref: z.string(),\n detail: z.string(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n slug_match: z.string().optional(),\n untracked: z.boolean().optional(),\n});\n\nconst ResultSchema = z.object({\n hits: z.array(HitSchema),\n errors: z.array(z.object({ source: z.string(), error: z.string() })),\n});\n\nexport default defineCommand({\n name: 'discover',\n description:\n 'Scan configured sources (gh PRs, local git, projects root, Claude sessions) and emit unfiltered discovery hits.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n github_repos: {\n long: '--github-repos',\n description: 'Comma-separated owner/repo list for gh PR discovery',\n },\n local_repos: {\n long: '--local-repos',\n description: 'Comma-separated repo paths for local git discovery',\n },\n projects_root: {\n long: '--projects-root',\n description: 'Root directory whose subdirs are scanned as projects',\n },\n },\n },\n async run(args) {\n return runDiscovery({\n github_repos: args.github_repos,\n local_repos: args.local_repos,\n projects_root: args.projects_root,\n });\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { getActiveRoot } from '../utils/paths.js';\nimport type {\n DiscoveryConfig,\n DiscoveryHit,\n DiscoveryResult,\n DiscoverySourceError,\n} from './types.js';\nimport { discoverGitHub } from './github.js';\nimport { discoverGit } from './git.js';\nimport { discoverProjects } from './projects.js';\nimport { discoverClaudeSessions } from './claude.js';\n\n/**\n * Run every discovery source the config asks for, aggregate hits, then\n * cross-reference against the set of known initiative slugs sitting in\n * `<activeRoot>/*` and suppress anything already triaged via\n * `<activeRoot>/.triaged.log`.\n */\n\nexport async function runDiscovery(config: DiscoveryConfig): Promise<DiscoveryResult> {\n const allHits: DiscoveryHit[] = [];\n const allErrors: DiscoverySourceError[] = [];\n\n const githubRepos = config.github_repos ?? [];\n const localRepos = config.local_repos ?? [];\n const projectsRoot = config.projects_root ?? '';\n\n if (githubRepos.length > 0) {\n const r = await discoverGitHub(githubRepos);\n allHits.push(...r.hits);\n allErrors.push(...r.errors);\n }\n if (localRepos.length > 0) {\n const r = await discoverGit(localRepos);\n allHits.push(...r.hits);\n allErrors.push(...r.errors);\n }\n if (projectsRoot.length > 0) {\n const r = await discoverProjects(projectsRoot);\n allHits.push(...r.hits);\n allErrors.push(...r.errors);\n }\n // Claude session scanning is cheap and config-free, so always run it.\n const claude = await discoverClaudeSessions();\n allHits.push(...claude.hits);\n allErrors.push(...claude.errors);\n\n const activeRoot = getActiveRoot();\n const slugs = await loadSlugs(activeRoot);\n const suppressed = await loadTriagedRefs(activeRoot);\n\n const filtered: DiscoveryHit[] = [];\n for (const hit of allHits) {\n if (suppressed.has(hit.ref)) continue;\n const match = matchSlug(hit, slugs);\n if (match) {\n hit.slug_match = match;\n hit.untracked = false;\n } else {\n hit.untracked = true;\n }\n filtered.push(hit);\n }\n\n return { hits: filtered, errors: allErrors };\n}\n\nasync function loadSlugs(activeRoot: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(activeRoot, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory() && !e.name.startsWith('.')).map((e) => e.name);\n } catch {\n return [];\n }\n}\n\nasync function loadTriagedRefs(activeRoot: string): Promise<Set<string>> {\n const logPath = path.join(activeRoot, '.triaged.log');\n const refs = new Set<string>();\n try {\n const raw = await fs.readFile(logPath, 'utf8');\n for (const line of raw.split('\\n')) {\n if (!line.trim()) continue;\n const parts = line.split('\\t');\n // Format: <iso>\\t<action>\\t<ref>\\t<extra>\n const ref = parts[2];\n if (ref) refs.add(ref);\n }\n } catch {\n // No log yet — nothing to suppress.\n }\n return refs;\n}\n\nfunction matchSlug(hit: DiscoveryHit, slugs: string[]): string | undefined {\n const haystacks: string[] = [hit.ref.toLowerCase()];\n const cwd = hit.metadata?.cwd;\n if (typeof cwd === 'string') haystacks.push(cwd.toLowerCase());\n for (const slug of slugs) {\n const needle = slug.toLowerCase();\n if (haystacks.some((h) => h.includes(needle))) return slug;\n }\n return undefined;\n}\n\nexport type { DiscoveryConfig, DiscoveryHit, DiscoveryResult } from './types.js';\n","import { spawn } from 'node:child_process';\n\n/**\n * Minimal subprocess runner used by the discovery sources.\n *\n * Captures stdout/stderr separately. Resolves with the exit code so callers\n * can decide how to treat non-zero exits per-source.\n */\n\nexport interface CommandResult {\n code: number | null;\n stdout: string;\n stderr: string;\n}\n\nexport interface CommandOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n /** Max ms before the child is killed; defaults to 15s. */\n timeoutMs?: number;\n}\n\nexport type RunCommand = (\n bin: string,\n args: string[],\n opts?: CommandOptions,\n) => Promise<CommandResult>;\n\nconst DEFAULT_TIMEOUT_MS = 15_000;\n\nexport const runCommand: RunCommand = (bin, args, opts = {}) => {\n return new Promise<CommandResult>((resolve, reject) => {\n const child = spawn(bin, args, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n let settled = false;\n\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n child.kill('SIGKILL');\n reject(new Error(`${bin} timed out after ${opts.timeoutMs ?? DEFAULT_TIMEOUT_MS}ms`));\n }, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n\n child.stdout?.on('data', (chunk: Buffer) => stdoutChunks.push(chunk));\n child.stderr?.on('data', (chunk: Buffer) => stderrChunks.push(chunk));\n child.on('error', (err) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n reject(err);\n });\n child.on('close', (code) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve({\n code,\n stdout: Buffer.concat(stdoutChunks).toString('utf8'),\n stderr: Buffer.concat(stderrChunks).toString('utf8'),\n });\n });\n });\n};\n","import type { DiscoveryHit, DiscoverySourceError } from './types.js';\nimport { runCommand, type RunCommand } from './run-command.js';\n\n/**\n * Discover open PRs authored by the current user, per repo.\n *\n * Shells out to `gh pr list --author @me --state open` and converts each\n * PR to a `DiscoveryHit`. Failures (gh missing, auth, network) are\n * captured per-repo and never thrown.\n */\n\ninterface GhPullRequest {\n number: number;\n title: string;\n isDraft: boolean;\n headRefName: string;\n updatedAt: string;\n}\n\nexport interface DiscoverGitHubResult {\n hits: DiscoveryHit[];\n errors: DiscoverySourceError[];\n}\n\nexport async function discoverGitHub(\n repos: string[],\n run: RunCommand = runCommand,\n): Promise<DiscoverGitHubResult> {\n const hits: DiscoveryHit[] = [];\n const errors: DiscoverySourceError[] = [];\n\n for (const repo of repos) {\n const sourceId = `gh:${repo}`;\n try {\n const result = await run('gh', [\n 'pr',\n 'list',\n '--author',\n '@me',\n '--state',\n 'open',\n '--limit',\n '100',\n '--repo',\n repo,\n '--json',\n 'number,title,isDraft,headRefName,updatedAt',\n ]);\n if (result.code !== 0) {\n errors.push({\n source: sourceId,\n error: result.stderr.trim() || `gh exited with code ${result.code}`,\n });\n continue;\n }\n const parsed = JSON.parse(result.stdout) as GhPullRequest[];\n for (const pr of parsed) {\n hits.push({\n source: sourceId,\n ref: pr.headRefName,\n detail: `${pr.isDraft ? '[draft] ' : ''}#${pr.number} ${pr.title}`,\n metadata: {\n repo,\n number: pr.number,\n title: pr.title,\n isDraft: pr.isDraft,\n headRefName: pr.headRefName,\n updatedAt: pr.updatedAt,\n },\n });\n }\n } catch (err) {\n errors.push({\n source: sourceId,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n return { hits, errors };\n}\n","import path from 'node:path';\nimport type { DiscoveryHit, DiscoverySourceError } from './types.js';\nimport { runCommand, type RunCommand } from './run-command.js';\n\n/**\n * Discover local git activity (recent branches, worktrees, stashes) across\n * one or more repo paths. Each repo is queried independently so a failure\n * in one repo doesn't suppress hits from the others.\n */\n\nexport interface DiscoverGitResult {\n hits: DiscoveryHit[];\n errors: DiscoverySourceError[];\n}\n\nconst BRANCH_LIMIT = 20;\n\nexport async function discoverGit(\n repoPaths: string[],\n run: RunCommand = runCommand,\n): Promise<DiscoverGitResult> {\n const hits: DiscoveryHit[] = [];\n const errors: DiscoverySourceError[] = [];\n\n for (const repoPath of repoPaths) {\n const repoName = path.basename(repoPath);\n await collectBranches(repoPath, repoName, hits, errors, run);\n await collectWorktrees(repoPath, repoName, hits, errors, run);\n await collectStashes(repoPath, repoName, hits, errors, run);\n }\n\n return { hits, errors };\n}\n\nasync function collectBranches(\n repoPath: string,\n repoName: string,\n hits: DiscoveryHit[],\n errors: DiscoverySourceError[],\n run: RunCommand,\n): Promise<void> {\n const sourceId = `branch:${repoName}`;\n try {\n const result = await run('git', [\n '-C',\n repoPath,\n 'for-each-ref',\n '--sort=-committerdate',\n `--count=${BRANCH_LIMIT}`,\n '--format=%(refname:short)|%(committerdate:short)|%(subject)',\n 'refs/heads/',\n ]);\n if (result.code !== 0) {\n errors.push({ source: sourceId, error: errMsg(result.stderr, result.code) });\n return;\n }\n for (const line of splitLines(result.stdout)) {\n const [name, date, ...rest] = line.split('|');\n if (!name) continue;\n const subject = rest.join('|');\n hits.push({\n source: sourceId,\n ref: name,\n detail: `${name} @ ${date ?? ''} — ${subject}`,\n metadata: { repo: repoName, repoPath, name, date, subject },\n });\n }\n } catch (err) {\n errors.push({ source: sourceId, error: errStr(err) });\n }\n}\n\nasync function collectWorktrees(\n repoPath: string,\n repoName: string,\n hits: DiscoveryHit[],\n errors: DiscoverySourceError[],\n run: RunCommand,\n): Promise<void> {\n const sourceId = `worktree:${repoName}`;\n try {\n const result = await run('git', ['-C', repoPath, 'worktree', 'list', '--porcelain']);\n if (result.code !== 0) {\n errors.push({ source: sourceId, error: errMsg(result.stderr, result.code) });\n return;\n }\n for (const entry of parseWorktreePorcelain(result.stdout)) {\n // Skip the main worktree (== repoPath); only surface auxiliary ones.\n if (entry.path && entry.path !== repoPath && entry.branch) {\n hits.push({\n source: sourceId,\n ref: entry.branch,\n detail: `worktree ${entry.path} on ${entry.branch}`,\n metadata: { repo: repoName, repoPath, ...entry },\n });\n }\n }\n } catch (err) {\n errors.push({ source: sourceId, error: errStr(err) });\n }\n}\n\nasync function collectStashes(\n repoPath: string,\n repoName: string,\n hits: DiscoveryHit[],\n errors: DiscoverySourceError[],\n run: RunCommand,\n): Promise<void> {\n const sourceId = `stash:${repoName}`;\n try {\n const result = await run('git', ['-C', repoPath, 'stash', 'list']);\n if (result.code !== 0) {\n errors.push({ source: sourceId, error: errMsg(result.stderr, result.code) });\n return;\n }\n for (const line of splitLines(result.stdout)) {\n // Format: stash@{N}: WIP on <branch>: <hash> <subject>\n const refMatch = line.match(/^(stash@\\{\\d+\\}):\\s*(.*)$/);\n if (!refMatch) continue;\n const [, ref, message] = refMatch;\n hits.push({\n source: sourceId,\n ref: ref!,\n detail: message ?? line,\n metadata: { repo: repoName, repoPath, ref, message },\n });\n }\n } catch (err) {\n errors.push({ source: sourceId, error: errStr(err) });\n }\n}\n\ninterface WorktreeEntry {\n path?: string;\n head?: string;\n branch?: string;\n}\n\nfunction parseWorktreePorcelain(stdout: string): WorktreeEntry[] {\n const entries: WorktreeEntry[] = [];\n let current: WorktreeEntry = {};\n for (const rawLine of stdout.split('\\n')) {\n const line = rawLine.trimEnd();\n if (line === '') {\n if (Object.keys(current).length > 0) entries.push(current);\n current = {};\n continue;\n }\n if (line.startsWith('worktree ')) current.path = line.slice('worktree '.length);\n else if (line.startsWith('HEAD ')) current.head = line.slice('HEAD '.length);\n else if (line.startsWith('branch ')) {\n const ref = line.slice('branch '.length);\n current.branch = ref.replace(/^refs\\/heads\\//, '');\n }\n }\n if (Object.keys(current).length > 0) entries.push(current);\n return entries;\n}\n\nfunction splitLines(s: string): string[] {\n return s\n .split('\\n')\n .map((l) => l.trimEnd())\n .filter((l) => l.length > 0);\n}\n\nfunction errMsg(stderr: string, code: number | null): string {\n return stderr.trim() || `git exited with code ${code}`;\n}\n\nfunction errStr(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","import { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\nimport type { DiscoveryHit, DiscoverySourceError } from './types.js';\nimport { expandTilde } from '../utils/paths.js';\n\n/**\n * Scan a \"projects root\" directory (e.g. `~/code`) and surface each\n * top-level subdir as a potential work item. Skips dotfiles and the\n * conventional `active` worktree-staging dir.\n */\n\nexport interface DiscoverProjectsResult {\n hits: DiscoveryHit[];\n errors: DiscoverySourceError[];\n}\n\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\nconst RECENT_THRESHOLD_DAYS = 30;\n\nexport async function discoverProjects(projectsRoot: string): Promise<DiscoverProjectsResult> {\n const hits: DiscoveryHit[] = [];\n const errors: DiscoverySourceError[] = [];\n\n if (!projectsRoot) return { hits, errors };\n\n const resolved = path.resolve(expandTilde(projectsRoot));\n let entries: Dirent[];\n try {\n entries = await fs.readdir(resolved, { withFileTypes: true });\n } catch (err) {\n errors.push({\n source: 'projects',\n error: err instanceof Error ? err.message : String(err),\n });\n return { hits, errors };\n }\n\n const now = Date.now();\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (entry.name.startsWith('.')) continue;\n if (entry.name === 'active') continue;\n\n const fullPath = path.join(resolved, entry.name);\n let mtimeMs = 0;\n try {\n const stat = await fs.stat(fullPath);\n mtimeMs = stat.mtimeMs;\n } catch (err) {\n errors.push({\n source: `projects:${entry.name}`,\n error: err instanceof Error ? err.message : String(err),\n });\n continue;\n }\n const ageDays = (now - mtimeMs) / MS_PER_DAY;\n const recency =\n ageDays <= RECENT_THRESHOLD_DAYS ? `modified <${RECENT_THRESHOLD_DAYS}d ago` : 'older';\n hits.push({\n source: 'projects',\n ref: entry.name,\n detail: `${entry.name} (${recency})`,\n metadata: {\n name: entry.name,\n path: fullPath,\n mtime: new Date(mtimeMs).toISOString(),\n ageDays: Math.round(ageDays),\n recency,\n },\n });\n }\n\n return { hits, errors };\n}\n","import { promises as fs, type Dirent } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport type { DiscoveryHit, DiscoverySourceError } from './types.js';\n\n/**\n * Scan `~/.claude/projects/` for recent session JSONLs and surface one hit\n * per unique `cwd`. Honors `CLAUDE_PROJECTS_ROOT` for test injection.\n *\n * We do a light scan of each session file — just enough to extract `cwd`,\n * a subject (first user message or last compaction summary), and an mtime.\n * We do NOT filter against claimed slugs here; that's the orchestrator's\n * cross-reference step.\n */\n\nexport interface DiscoverClaudeResult {\n hits: DiscoveryHit[];\n errors: DiscoverySourceError[];\n}\n\ninterface CwdAggregate {\n cwd: string;\n sessionCount: number;\n lastMtimeMs: number;\n subject: string;\n lastSessionId: string;\n}\n\nconst MAX_SCAN_LINES = 200;\nconst COMPACTION_SUBJECT_PREFIX = '[compaction] ';\n\nexport async function discoverClaudeSessions(): Promise<DiscoverClaudeResult> {\n const root = process.env.CLAUDE_PROJECTS_ROOT ?? path.join(os.homedir(), '.claude', 'projects');\n const hits: DiscoveryHit[] = [];\n const errors: DiscoverySourceError[] = [];\n\n let projectDirs: Dirent[];\n try {\n projectDirs = await fs.readdir(root, { withFileTypes: true });\n } catch (err) {\n // No claude projects dir at all? That's not an error — return empty.\n const e = err as NodeJS.ErrnoException;\n if (e.code === 'ENOENT') return { hits, errors };\n errors.push({ source: 'claude-session', error: e.message ?? String(err) });\n return { hits, errors };\n }\n\n const byCwd = new Map<string, CwdAggregate>();\n\n for (const dir of projectDirs) {\n if (!dir.isDirectory()) continue;\n const dirPath = path.join(root, dir.name);\n let files: Dirent[];\n try {\n files = await fs.readdir(dirPath, { withFileTypes: true });\n } catch (err) {\n errors.push({\n source: `claude-session:${dir.name}`,\n error: err instanceof Error ? err.message : String(err),\n });\n continue;\n }\n for (const file of files) {\n if (!file.isFile() || !file.name.endsWith('.jsonl')) continue;\n const filePath = path.join(dirPath, file.name);\n try {\n await aggregateSession(filePath, byCwd);\n } catch (err) {\n errors.push({\n source: `claude-session:${file.name}`,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n }\n\n for (const agg of byCwd.values()) {\n hits.push({\n source: 'claude-session',\n ref: agg.cwd,\n detail: `${agg.sessionCount} session(s) at ${agg.cwd}${\n agg.subject ? ` — ${agg.subject}` : ''\n }`,\n metadata: {\n cwd: agg.cwd,\n sessionCount: agg.sessionCount,\n lastMtime: new Date(agg.lastMtimeMs).toISOString(),\n lastSessionId: agg.lastSessionId,\n subject: agg.subject,\n },\n });\n }\n\n return { hits, errors };\n}\n\nasync function aggregateSession(filePath: string, byCwd: Map<string, CwdAggregate>): Promise<void> {\n const stat = await fs.stat(filePath);\n // Read up to MAX_SCAN_LINES; this is a light scan, not a parser.\n const raw = await fs.readFile(filePath, 'utf8');\n const lines = raw.split('\\n').slice(0, MAX_SCAN_LINES);\n\n let cwd: string | undefined;\n let firstUserMessage: string | undefined;\n let lastCompactionSummary: string | undefined;\n\n for (const line of lines) {\n if (!line) continue;\n let record: unknown;\n try {\n record = JSON.parse(line);\n } catch {\n continue;\n }\n if (!record || typeof record !== 'object') continue;\n const rec = record as Record<string, unknown>;\n if (!cwd && typeof rec.cwd === 'string' && rec.cwd.length > 0) {\n cwd = rec.cwd;\n }\n if (!firstUserMessage) {\n const text = extractUserMessageText(rec);\n if (text) firstUserMessage = text;\n }\n const summary = extractCompactionSummary(rec);\n if (summary) lastCompactionSummary = summary;\n }\n\n if (!cwd) return;\n const subject = lastCompactionSummary\n ? `${COMPACTION_SUBJECT_PREFIX}${truncate(lastCompactionSummary, 120)}`\n : firstUserMessage\n ? truncate(firstUserMessage, 120)\n : '';\n const sessionId = path.basename(filePath, '.jsonl');\n\n const existing = byCwd.get(cwd);\n if (!existing) {\n byCwd.set(cwd, {\n cwd,\n sessionCount: 1,\n lastMtimeMs: stat.mtimeMs,\n subject,\n lastSessionId: sessionId,\n });\n return;\n }\n existing.sessionCount += 1;\n if (stat.mtimeMs > existing.lastMtimeMs) {\n existing.lastMtimeMs = stat.mtimeMs;\n existing.lastSessionId = sessionId;\n if (subject) existing.subject = subject;\n } else if (!existing.subject && subject) {\n existing.subject = subject;\n }\n}\n\nfunction extractUserMessageText(rec: Record<string, unknown>): string | undefined {\n if (rec.type !== 'user') return undefined;\n const message = rec.message;\n if (!message || typeof message !== 'object') return undefined;\n const content = (message as Record<string, unknown>).content;\n if (typeof content === 'string') return content.trim() || undefined;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (\n block &&\n typeof block === 'object' &&\n (block as Record<string, unknown>).type === 'text' &&\n typeof (block as Record<string, unknown>).text === 'string'\n ) {\n const text = ((block as Record<string, unknown>).text as string).trim();\n if (text) return text;\n }\n }\n }\n return undefined;\n}\n\nfunction extractCompactionSummary(rec: Record<string, unknown>): string | undefined {\n if (rec.type !== 'summary') return undefined;\n if (typeof rec.summary === 'string' && rec.summary.trim().length > 0) {\n return rec.summary.trim();\n }\n return undefined;\n}\n\nfunction truncate(s: string, max: number): string {\n const oneline = s.replace(/\\s+/g, ' ').trim();\n return oneline.length > max ? `${oneline.slice(0, max - 1)}…` : oneline;\n}\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { appendTriagedLog } from '../discover/triaged-log.js';\n\n/**\n * `active-work drop <ref>` — silently dismiss a discover hit. The orchestrator\n * reads `.triaged.log` and skips refs already marked dropped.\n */\n\nconst ArgsSchema = z.object({\n ref: z.string().min(1),\n reason: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n ref: z.string(),\n});\n\nexport default defineCommand({\n name: 'drop',\n description: 'Mark a discover hit as dropped so future discovers suppress it.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['ref'],\n options: {\n reason: {\n long: '--reason',\n description: 'Optional one-line reason recorded in the triage log',\n },\n },\n },\n async run(args) {\n await appendTriagedLog('drop', args.ref, args.reason ?? '-');\n return { ref: args.ref };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { atomicWrite } from '../utils/fs-atomic.js';\nimport { getActiveRoot } from '../utils/paths.js';\nimport { nowIso } from '../utils/today.js';\n\n/**\n * Append a single triage decision to `<activeRoot>/.triaged.log`.\n *\n * Format: `<nowIso()>\\t<action>\\t<ref>\\t<extra>` — one line per decision.\n * The orchestrator reads this file to suppress already-decided refs from\n * future discoveries.\n */\nexport async function appendTriagedLog(\n action: 'fold' | 'drop' | 'track',\n ref: string,\n extra: string,\n): Promise<void> {\n const root = getActiveRoot();\n await fs.mkdir(root, { recursive: true });\n const logPath = path.join(root, '.triaged.log');\n let existing = '';\n try {\n existing = await fs.readFile(logPath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n const line = `${nowIso()}\\t${action}\\t${ref}\\t${extra}\\n`;\n await atomicWrite(logPath, existing + line);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { SessionFrontmatterSchema } from '../schemas/session.js';\nimport { NotFoundError } from '../errors.js';\nimport { nowIso } from '../utils/today.js';\nimport { appendTriagedLog } from '../discover/triaged-log.js';\nimport { buildSessionStem, pickAvailableFilename } from '../sessions/session-file.js';\n\n/**\n * `active-work fold <ref> --into <slug>` — record that a discover hit has been\n * absorbed by an existing initiative.\n *\n * Side effects:\n * - writes a `sidecar`-track session file under the initiative's\n * `sessions/` so the fold is visible in the audit trail\n * - appends a `fold` line to `<activeRoot>/.triaged.log` so future\n * discovers suppress this ref\n */\n\nconst ArgsSchema = z.object({\n ref: z.string().min(1),\n into: z.string().min(1),\n note: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n ref: z.string(),\n into: z.string(),\n session_file: z.string(),\n});\n\nexport default defineCommand({\n name: 'fold',\n description: 'Mark a discover hit as folded into an existing initiative.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['ref'],\n options: {\n into: {\n long: '--into',\n description: 'Slug of the initiative this hit is folded into',\n required: true,\n },\n note: {\n long: '--note',\n description: 'Optional human note describing the fold',\n },\n },\n },\n async run(args) {\n const initiativeDir = getInitiativeDir(args.into);\n try {\n const stat = await fs.stat(initiativeDir);\n if (!stat.isDirectory()) {\n throw new NotFoundError(`Initiative not found: ${args.into}`);\n }\n } catch (err) {\n if (err instanceof NotFoundError) throw err;\n throw new NotFoundError(`Initiative not found: ${args.into}`);\n }\n\n const sessionsDir = path.join(initiativeDir, 'sessions');\n await fs.mkdir(sessionsDir, { recursive: true });\n\n const startedIso = nowIso();\n const stem = buildSessionStem(startedIso, `folded-${sanitizeRef(args.ref)}`);\n const { fullPath: sessionFile } = await pickAvailableFilename(sessionsDir, stem);\n\n const body = [\n `Folded hit \\`${args.ref}\\` into initiative \\`${args.into}\\`.`,\n '',\n args.note ? args.note : '_No note provided._',\n ].join('\\n');\n\n await writeFrontmatter(\n sessionFile,\n {\n session_id: `folded-${sanitizeRef(args.ref)}`,\n started: startedIso,\n ended: startedIso,\n track: 'sidecar' as const,\n next_steps: [],\n resolves: [],\n },\n body,\n SessionFrontmatterSchema,\n );\n\n await appendTriagedLog('fold', args.ref, `into:${args.into}`);\n\n return { ref: args.ref, into: args.into, session_file: sessionFile };\n },\n});\n\nfunction sanitizeRef(ref: string): string {\n return (\n ref\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40) || 'ref'\n );\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { BriefFrontmatterSchema } from '../schemas/brief.js';\nimport { ArtifactsSchema } from '../schemas/artifacts.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { atomicWrite } from '../utils/fs-atomic.js';\nimport { writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { derivePrefix, validateSlug } from '../utils/slug.js';\nimport { today } from '../utils/today.js';\nimport { UsageError, ValidationError } from '../errors.js';\nimport { stringify as yamlStringify } from 'yaml';\nimport { appendTriagedLog } from '../discover/triaged-log.js';\n\n/**\n * `active-work track <ref> --slug <slug>` — scaffold a fresh initiative from a\n * discover hit. The original `ref` is preserved in the brief body so\n * future readers can trace where the initiative came from.\n *\n * This deliberately re-implements directory scaffolding inline rather\n * than importing `active-work new`; the parallel-work split means `new` lives on a\n * branch this one can't reach.\n */\n\nconst ArgsSchema = z.object({\n ref: z.string().min(1),\n slug: z.string().min(1),\n title: z.string().optional(),\n ship_target: z.string().optional(),\n owner: z.string().optional(),\n worktree: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n dir: z.string(),\n ref: z.string(),\n});\n\nexport default defineCommand({\n name: 'track',\n description: 'Scaffold a new initiative from a discover hit.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['ref'],\n options: {\n slug: {\n long: '--slug',\n description: 'Kebab-case slug for the new initiative',\n required: true,\n },\n title: { long: '--title', description: 'Human-readable initiative title' },\n ship_target: { long: '--ship-target', description: 'Target ship window (e.g. 2026-Q3)' },\n owner: { long: '--owner', description: 'Initiative owner handle' },\n worktree: {\n long: '--worktree',\n description: 'Default worktree path to record on the brief',\n },\n },\n },\n async run(args) {\n const validation = validateSlug(args.slug);\n if (!validation.ok) {\n throw new ValidationError(validation.error);\n }\n const dir = getInitiativeDir(args.slug);\n\n if (await dirExists(dir)) {\n throw new UsageError(`Initiative already exists: ${args.slug}`);\n }\n await fs.mkdir(path.join(dir, 'tasks'), { recursive: true });\n await fs.mkdir(path.join(dir, 'sessions'), { recursive: true });\n await fs.mkdir(path.join(dir, 'sources'), { recursive: true });\n\n const title = args.title ?? deriveTitle(args.slug);\n const briefBody = buildBriefBody(title, args.ref);\n\n await writeFrontmatter(\n path.join(dir, 'brief.md'),\n {\n schema_version: 1,\n title,\n updated: today(),\n state: 'backburner' as const,\n ...(args.ship_target ? { ship_target: args.ship_target } : {}),\n ...(args.owner ? { owner: args.owner } : {}),\n task_prefix: derivePrefix(args.slug),\n },\n briefBody,\n BriefFrontmatterSchema,\n );\n\n // A worktree given at track time is registered, not merely observed (AW-67).\n const artifacts = ArtifactsSchema.parse({\n worktrees: args.worktree\n ? [{ path: args.worktree, repo: args.worktree, name: 'main', default: true }]\n : [],\n });\n await atomicWrite(path.join(dir, 'artifacts.yml'), yamlStringify(artifacts));\n await atomicWrite(path.join(dir, 'sources', '.gitkeep'), '');\n\n await appendTriagedLog('track', args.ref, `slug:${args.slug}`);\n\n return { slug: args.slug, dir, ref: args.ref };\n },\n});\n\nasync function dirExists(p: string): Promise<boolean> {\n try {\n const stat = await fs.stat(p);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction deriveTitle(slug: string): string {\n return slug\n .split('-')\n .filter(Boolean)\n .map((s) => s[0]!.toUpperCase() + s.slice(1))\n .join(' ');\n}\n\nfunction buildBriefBody(title: string, ref: string): string {\n return [\n `# ${title}`,\n '',\n `Source: ${ref}`,\n '',\n 'This initiative was scaffolded from a discover hit. Replace this',\n 'placeholder body with the actual brief before promoting from',\n 'backburner to focused.',\n '',\n ].join('\\n');\n}\n","import { z } from 'zod';\nimport { getActiveRoot } from '../utils/paths.js';\nimport { NotFoundError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\nimport { assembleBootstrap } from '../bootstrap/prompt.js';\nimport { resolveSlug, resolveSlugFromCwd } from './_open-helpers.js';\n\nconst ArgsSchema = z.object({\n slug: z.string().min(1).optional(),\n offline: z.boolean().optional(),\n // Directory to resolve the initiative from when no slug is given. Falls back\n // to the interactive-surface context cwd; unset for daemon/MCP callers.\n cwd: z.string().min(1).optional(),\n // Frame the prompt as ad-hoc work on the workstream rather than a\n // continuation of its handoff / top task.\n adhoc: z.boolean().optional(),\n // Skip the check for another session already live on this initiative.\n no_sibling_check: z.boolean().optional(),\n});\n\ntype PromptArgs = z.infer<typeof ArgsSchema>;\n\nconst promptCommand = defineCommand<PromptArgs, string>({\n name: 'prompt',\n description:\n \"Print the bootstrap prompt for an initiative — the same text `aw` feeds Claude at launch — without any side effects. Resolves the initiative from a slug or the caller's cwd. Use it to re-seed context in a running session.\",\n args: ArgsSchema,\n result: z.string(),\n cli: {\n positional: ['slug'],\n options: {\n offline: {\n long: '--offline',\n description: 'Skip the live `gh`/`git` artifact lookup; render artifacts statically.',\n },\n cwd: {\n long: '--cwd',\n description:\n 'Directory to resolve the initiative from when no slug is given (default: current directory).',\n },\n adhoc: {\n long: '--adhoc',\n description:\n 'Frame the prompt as ad-hoc work on the workstream, awaiting the user’s task, not a continuation of the handoff / top task.',\n },\n no_sibling_check: {\n long: '--no-sibling-check',\n description: 'Skip the check for another session already live on this initiative.',\n },\n },\n usage: 'active-work prompt [slug] [--offline] [--cwd <dir>] [--adhoc] [--no-sibling-check]',\n },\n async run(args, ctx) {\n const activeRoot = ctx.activeRoot ?? getActiveRoot();\n\n let slug: string;\n if (args.slug) {\n slug = await resolveSlug(activeRoot, args.slug);\n } else {\n const cwd = args.cwd ?? ctx.cwd;\n const matched = cwd ? await resolveSlugFromCwd(activeRoot, cwd) : null;\n if (!matched) {\n throw new NotFoundError(\n 'Could not determine an initiative from the current directory. ' +\n 'Pass a slug: `active-work prompt <slug>`.',\n );\n }\n slug = matched.slug;\n }\n\n // Deliberately no archiveStaleTasks, and deliberately no `acquireLease`:\n // `prompt` is a read-only view. It *detects* siblings — re-seeding context\n // mid-session is exactly when you want to know another session is live —\n // but recording a lease would make every re-seed look like a new session\n // to the next bootstrap.\n const { prompt } = await assembleBootstrap({\n activeRoot,\n slug,\n includeLiveStatus: !args.offline,\n adhoc: args.adhoc,\n detectSiblings: !args.no_sibling_check && !args.offline,\n ...(process.env.AW_LEASE_ID ? { ownLeaseId: process.env.AW_LEASE_ID } : {}),\n });\n return prompt;\n },\n});\n\nexport default promptCommand;\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { spawn } from 'node:child_process';\nimport type { ChildProcess, SpawnOptions } from 'node:child_process';\nimport { z } from 'zod';\nimport { BriefFrontmatterSchema } from '../schemas/brief.js';\nimport { getInitiativeDir } from '../utils/paths.js';\nimport { readFrontmatter } from '../utils/gray-matter-io.js';\nimport { NotFoundError, ValidationError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\n\n// `handoff` was the other target until v3 retired handoff.md. The enum is\n// kept (rather than dropped for a bare slug) so the CLI shape survives and a\n// stale `edit <slug> handoff` fails with a schema error naming the target.\nconst ArgsSchema = z.object({\n slug: z.string().min(1),\n target: z.enum(['brief']).default('brief'),\n});\n\nconst ResultSchema = z.object({\n slug: z.string(),\n target: z.enum(['brief']),\n file: z.string(),\n validated: z.boolean(),\n aborted: z.boolean().optional(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\ntype Result = z.infer<typeof ResultSchema>;\n\nexport interface EditorCommand {\n command: string;\n args: string[];\n}\n\nexport type EditorResolver = (filePath: string) => Promise<EditorCommand>;\n\nexport type EditorSpawner = (\n command: string,\n args: string[],\n options: SpawnOptions,\n) => Promise<number>;\n\n/**\n * Resolve which editor to launch using the cascading fallback:\n * 1. `$EDITOR` (invoked via `sh -c` so multi-token values like\n * `nvim --noplugin` split correctly).\n * 2. `code --wait` when the `code` binary resolves on PATH.\n * 3. `vi` as the universal last resort.\n */\nexport async function resolveEditor(filePath: string): Promise<EditorCommand> {\n const editorEnv = process.env.EDITOR;\n if (editorEnv && editorEnv.length > 0) {\n return { command: 'sh', args: ['-c', '$EDITOR \"$0\"', filePath] };\n }\n if (await commandExists('code')) {\n return { command: 'code', args: ['--wait', filePath] };\n }\n return { command: 'vi', args: [filePath] };\n}\n\nasync function commandExists(name: string): Promise<boolean> {\n return new Promise((resolve) => {\n const child = spawn('/bin/sh', ['-c', `command -v ${name}`], {\n stdio: 'ignore',\n });\n child.on('exit', (code) => resolve(code === 0));\n child.on('error', () => resolve(false));\n });\n}\n\n/**\n * Default child-process spawner. Inherits stdio so the editor takes\n * over the operator's TTY, and resolves with the exit code on close.\n */\nexport const defaultSpawner: EditorSpawner = (command, args, options) => {\n return new Promise((resolve, reject) => {\n let child: ChildProcess;\n try {\n child = spawn(command, args, options);\n } catch (err) {\n reject(err);\n return;\n }\n child.on('error', reject);\n child.on('exit', (code) => resolve(code ?? 1));\n });\n};\n\nexport interface RunEditDeps {\n resolveEditor: EditorResolver;\n spawner: EditorSpawner;\n}\n\nconst defaultDeps: RunEditDeps = {\n resolveEditor,\n spawner: defaultSpawner,\n};\n\nfunction targetFile(slug: string): string {\n return path.join(getInitiativeDir(slug), 'brief.md');\n}\n\nasync function fileExists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function runEdit(args: Args, deps: RunEditDeps = defaultDeps): Promise<Result> {\n const file = targetFile(args.slug);\n if (!(await fileExists(file))) {\n throw new NotFoundError(`brief.md not found for initiative \"${args.slug}\" (expected ${file})`);\n }\n\n const editor = await deps.resolveEditor(file);\n const exitCode = await deps.spawner(editor.command, editor.args, {\n stdio: 'inherit',\n });\n\n if (exitCode !== 0) {\n return {\n slug: args.slug,\n target: args.target,\n file,\n validated: false,\n aborted: true,\n };\n }\n\n try {\n await readFrontmatter(file, BriefFrontmatterSchema);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ValidationError(\n `Brief frontmatter is invalid after editing. Re-run \\`active-work edit ${args.slug}\\` to fix.\\n${message}`,\n { cause: err },\n );\n }\n\n return {\n slug: args.slug,\n target: args.target,\n file,\n validated: true,\n };\n}\n\nconst edit = defineCommand<Args, Result>({\n name: 'edit',\n description: \"Open the operator's editor on brief.md.\",\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n positional: ['slug', 'target'],\n usage: 'active-work edit <slug> [brief]',\n },\n async run(args) {\n return runEdit(args);\n },\n});\n\nexport default edit;\n","import { spawn } from 'node:child_process';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { runMcpStdio } from '../server/mcp.js';\nimport { runDaemon } from '../server/daemon.js';\n\n/**\n * `active-work mcp serve` — start the MCP server.\n *\n * - `--stdio`: speak JSON-RPC over stdio (for `claude mcp add`).\n * - `--detach`: fork a child running `active-work mcp serve` in the background.\n * - default: run the HTTP daemon in the foreground on `--port` (default 7400).\n */\n\nconst ArgsSchema = z.object({\n stdio: z.boolean().optional(),\n detach: z.boolean().optional(),\n port: z.number().int().positive().optional(),\n});\n\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n mode: z.enum(['stdio', 'http', 'detached']),\n pid: z.number().optional(),\n port: z.number().optional(),\n});\n\ntype Result = z.infer<typeof ResultSchema>;\n\nfunction detachedSpawn(port: number | undefined): { pid: number; port: number } {\n const entry = process.argv[1];\n if (!entry) {\n throw new Error('Cannot determine CLI entrypoint for detach');\n }\n const args = ['mcp', 'serve'];\n if (port !== undefined) {\n args.push('--port', String(port));\n }\n const child = spawn(process.execPath, [entry, ...args], {\n detached: true,\n stdio: 'ignore',\n env: process.env,\n });\n child.unref();\n return { pid: child.pid ?? -1, port: port ?? 7400 };\n}\n\nexport default defineCommand<Args, Result>({\n name: 'mcp.serve',\n description:\n 'Start the MCP server. --stdio for stdio mode; --detach to fork the HTTP daemon; otherwise runs the HTTP daemon in the foreground.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n stdio: {\n long: '--stdio',\n description: 'Run in stdio mode for Claude Code `claude mcp add`.',\n },\n detach: {\n long: '--detach',\n description: 'Spawn the HTTP daemon in the background and return.',\n },\n port: {\n long: '--port',\n description: 'TCP port for the HTTP daemon (default 7400).',\n },\n },\n },\n async run(args) {\n if (args.stdio) {\n await runMcpStdio();\n return { mode: 'stdio' };\n }\n if (args.detach) {\n const { pid, port } = detachedSpawn(args.port);\n return { mode: 'detached', pid, port };\n }\n await runDaemon({ port: args.port });\n return { mode: 'http', port: args.port };\n },\n});\n","/**\n * active-work's binding of `@titan-design/daemon`'s MCP surface (AW-a).\n *\n * The package parameterises every entry point on `McpServerOptions` so one\n * client can host several registries; active-work hosts exactly one, under the\n * `active__` prefix (`task.add` -> `active__task__add`). Those names are public\n * contract — they appear in consumers' configs and in `~/.claude.json` — so the\n * prefix and the handshake identity are pinned here and asserted by\n * `__tests__/server/mcp-tool-names.test.ts`.\n */\nimport type { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport {\n attachHandlers as pkgAttachHandlers,\n createMcpServer as pkgCreateMcpServer,\n invokeTool as pkgInvokeTool,\n listTools as pkgListTools,\n runMcpStdio as pkgRunMcpStdio,\n type McpServerOptions,\n type ToolCallOutcome,\n} from '@titan-design/daemon';\nimport {\n commandNameToToolName as pkgCommandNameToToolName,\n commandToTool as pkgCommandToTool,\n toolNameToCommandName as pkgToolNameToCommandName,\n type McpToolDescriptor,\n} from '@titan-design/registry';\nimport { registry, type AnyCommand, type CommandContext } from '../registry/index.js';\nimport '../commands/index.js'; // populates registry on import\nimport { formatError } from '../errors.js';\nimport { getActiveRoot } from '../utils/paths.js';\nimport { DAEMON_VERSION } from './health.js';\n\nconst TOOL_NAME_PREFIX = 'active__';\nconst NAMING = { prefix: TOOL_NAME_PREFIX } as const;\n\nexport type McpTool = McpToolDescriptor;\nexport type { ToolCallOutcome };\n\n/** The MCP identity and registry binding every entry point below shares. */\nexport function mcpOptions(): McpServerOptions<CommandContext> {\n return {\n registry,\n createContext: () => ({ activeRoot: getActiveRoot(), warnings: [], format: 'json' }),\n formatError,\n toolPrefix: TOOL_NAME_PREFIX,\n name: '@hjewkes/active-work',\n version: DAEMON_VERSION,\n };\n}\n\n/** Convert a command name (e.g. `task.add`) to a tool name (`active__task__add`). */\nexport function commandNameToToolName(commandName: string): string {\n return pkgCommandNameToToolName(commandName, NAMING);\n}\n\nexport function toolNameToCommandName(toolName: string): string | null {\n return pkgToolNameToCommandName(toolName, NAMING);\n}\n\nexport function commandToTool(cmd: AnyCommand): McpTool {\n return pkgCommandToTool(cmd, NAMING);\n}\n\nexport function listTools(): McpTool[] {\n return pkgListTools(mcpOptions());\n}\n\nexport async function invokeTool(toolName: string, rawArgs: unknown): Promise<ToolCallOutcome> {\n return pkgInvokeTool(mcpOptions(), toolName, rawArgs);\n}\n\n/** Wire MCP request handlers onto a server instance. Exposed for testing. */\nexport function attachHandlers(server: Server): void {\n pkgAttachHandlers(server, mcpOptions());\n}\n\nexport function createMcpServer(): Server {\n return pkgCreateMcpServer(mcpOptions());\n}\n\n/** Run the MCP server over stdio. Resolves when the transport closes. */\nexport async function runMcpStdio(): Promise<void> {\n await pkgRunMcpStdio(mcpOptions());\n}\n","/**\n * Health state active-work adds on top of `@titan-design/daemon`'s payload.\n *\n * The package builds `{ok, version, pid, uptime_ms, port}` and merges a\n * product extension into it; `index` below is that extension. `startedAt` is\n * captured at module load so uptime is measured from process start rather than\n * from when the app happened to be built.\n */\n\n// TODO: read version from package.json at build time; hardcoded for v0.\nexport const DAEMON_VERSION = '0.1.0';\n\nexport const startedAt = Date.now();\n\n/**\n * Session-index state, mirrored onto `/health` so `miner status` can report\n * what the daemon is doing without a second endpoint — and without the CLI\n * needing to reach into another process. `null` when this daemon is not\n * indexing.\n */\nexport interface HealthIndexState {\n indexing: boolean;\n pending: boolean;\n lastRunAt: string | null;\n lastDurationMs: number | null;\n consecutiveErrors: number;\n}\n","/**\n * Daemon entrypoint, composed over `@titan-design/daemon` (AW-a).\n *\n * The package owns binding the socket, splicing `/mcp`, watching the active\n * root, the pid file, and signal shutdown. What stays here is the one thing it\n * has no business knowing: the session-index watcher, which must start only\n * after `/health` is answerable and be closed — awaited — before the socket\n * does, because a refresh may be mid-transaction.\n */\nimport { DaemonAlreadyRunningError, startDaemon } from '@titan-design/daemon';\nimport type { Hono } from 'hono';\nimport { DaemonError } from '../errors.js';\nimport type { SchedulerStatus } from '../session-index/scheduler.js';\nimport { getActiveRoot, getStateRoot } from '../utils/paths.js';\nimport { handleDashboard } from './dashboard-routes.js';\nimport { DAEMON_VERSION, type HealthIndexState } from './health.js';\nimport { resolveDaemonPort } from './lifecycle.js';\nimport { getLogger } from './logger.js';\nimport { mcpOptions } from './mcp.js';\nimport { startSessionIndexWatch, type SessionIndexWatcher } from './session-index-watch.js';\n\nexport interface RunDaemonOptions {\n port?: number;\n}\n\nfunction resolvePort(options: RunDaemonOptions): number {\n if (typeof options.port === 'number' && Number.isFinite(options.port)) return options.port;\n return resolveDaemonPort();\n}\n\n/** Project the scheduler's snapshot onto the shape `/health` publishes. */\nfunction toHealthIndexState(status: SchedulerStatus | undefined): HealthIndexState | null {\n if (!status) return null;\n return {\n indexing: status.running,\n pending: status.pending,\n lastRunAt: status.last?.startedAt ?? null,\n lastDurationMs: status.last?.durationMs ?? null,\n consecutiveErrors: status.consecutiveErrors,\n };\n}\n\nexport async function runDaemon(options: RunDaemonOptions = {}): Promise<void> {\n const log = getLogger();\n // Read through a closure: the watcher only starts once the port is bound.\n let indexWatch: SessionIndexWatcher | null = null;\n\n const handle = await startDaemon({\n ...mcpOptions(),\n stateDir: getStateRoot(),\n port: resolvePort(options),\n watchRoot: getActiveRoot(),\n version: DAEMON_VERSION,\n logger: log,\n health: () => ({ index: toHealthIndexState(indexWatch?.status()) }),\n mountRoutes: (app: Hono) => {\n app.get('/ui', (c) => handleDashboard(c));\n app.get('/ui/*', (c) => handleDashboard(c));\n },\n }).catch((err: unknown) => {\n // The package's error carries the pid and port; active-work's callers\n // catch DaemonError, so translate rather than leak a second error type.\n if (err instanceof DaemonAlreadyRunningError) throw new DaemonError(err.message);\n throw err;\n });\n\n indexWatch = startSessionIndexWatch(log);\n\n await new Promise<void>((resolve) => {\n let shuttingDown = false;\n const shutdown = (signal: NodeJS.Signals): void => {\n if (shuttingDown) return;\n shuttingDown = true;\n log.info({ signal }, 'shutting down');\n void (async () => {\n try {\n // Awaited before the socket closes: a refresh may be mid-transaction\n // and must commit before the process exits.\n await indexWatch?.close();\n } catch (err) {\n log.error({ err }, 'error closing session index watcher');\n }\n try {\n await handle.close();\n } catch (err) {\n log.error({ err }, 'error closing daemon');\n }\n log.info('stopped');\n resolve();\n })();\n };\n\n process.once('SIGTERM', shutdown);\n process.once('SIGINT', shutdown);\n });\n}\n","/**\n * Dashboard static-asset handler.\n *\n * If `dist/dashboard/` exists (produced by a future `pnpm build:dashboard`),\n * we serve its contents under `/ui/*`. Otherwise we return a friendly\n * placeholder page so first-run users know what to do.\n */\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Context } from 'hono';\n\nconst PLACEHOLDER_HTML = `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>active-work dashboard</title>\n <style>\n body { font-family: system-ui, sans-serif; max-width: 36rem; margin: 4rem auto; padding: 0 1rem; color: #222; }\n code { background: #f4f4f5; padding: 0.1rem 0.3rem; border-radius: 4px; }\n </style>\n </head>\n <body>\n <h1>active-work</h1>\n <p>Dashboard not built yet — run <code>pnpm build:dashboard</code>.</p>\n <p>The daemon is running; use the CLI or MCP for now.</p>\n </body>\n</html>`;\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.htm': 'text/html; charset=utf-8',\n '.js': 'application/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n};\n\nfunction contentTypeFor(filename: string): string {\n const ext = path.extname(filename).toLowerCase();\n return CONTENT_TYPES[ext] ?? 'application/octet-stream';\n}\n\n/**\n * Candidate locations for the built dashboard bundle (`dist/dashboard/`).\n *\n * `tsup` bundles the daemon into `dist/cli.js`, so at runtime the compiled\n * file sits at `dist/` and the dashboard is a sibling (`here/dashboard`). In\n * dev (tsx) the source runs from `src/server/`, and the built dashboard lives\n * at `<repo>/dist/dashboard`. We probe both plus the legacy `dist/server`\n * layout and use the first that exists.\n */\nfunction dashboardDirCandidates(): string[] {\n const here = path.dirname(fileURLToPath(import.meta.url));\n return [\n path.resolve(here, 'dashboard'), // bundled: dist/cli.js -> dist/dashboard\n path.resolve(here, '..', 'dashboard'), // legacy: dist/server -> dist/dashboard\n path.resolve(here, '..', '..', 'dist', 'dashboard'), // dev: src/server -> dist/dashboard\n ];\n}\n\nasync function safeStat(p: string): Promise<{ exists: boolean; isFile: boolean }> {\n try {\n const stat = await fs.stat(p);\n return { exists: true, isFile: stat.isFile() };\n } catch {\n return { exists: false, isFile: false };\n }\n}\n\n/** First candidate directory that exists, or null if none is built yet. */\nasync function resolveDashboardDir(): Promise<string | null> {\n for (const dir of dashboardDirCandidates()) {\n if ((await safeStat(dir)).exists) return dir;\n }\n return null;\n}\n\nexport async function handleDashboard(c: Context): Promise<Response> {\n const root = await resolveDashboardDir();\n if (!root) {\n return c.html(PLACEHOLDER_HTML, 200);\n }\n\n // Strip the route prefix to get the asset-relative path.\n const url = new URL(c.req.url);\n const subpath = url.pathname.replace(/^\\/ui\\/?/, '');\n const relative = subpath === '' ? 'index.html' : subpath;\n\n // Guard against path traversal.\n const target = path.resolve(root, relative);\n if (!target.startsWith(root + path.sep) && target !== root) {\n return c.text('forbidden', 403);\n }\n\n const stat = await safeStat(target);\n if (!stat.exists || !stat.isFile) {\n // Fall back to index.html for SPA routing.\n const indexPath = path.join(root, 'index.html');\n const indexStat = await safeStat(indexPath);\n if (!indexStat.exists) {\n return c.html(PLACEHOLDER_HTML, 200);\n }\n const body = await fs.readFile(indexPath);\n return c.body(new Uint8Array(body), 200, {\n 'content-type': 'text/html; charset=utf-8',\n });\n }\n\n const body = await fs.readFile(target);\n return c.body(new Uint8Array(body), 200, {\n 'content-type': contentTypeFor(target),\n });\n}\n","/**\n * pino logger for the daemon.\n *\n * Logs to stderr (pretty when TTY, JSON otherwise) and additionally\n * appends a JSON record to `<state>/daemon.log`. Rotation is not yet\n * implemented; a future wave can layer pino-roll on top.\n */\nimport { mkdirSync, createWriteStream } from 'node:fs';\nimport path from 'node:path';\nimport pino, { type Logger, multistream, type StreamEntry } from 'pino';\nimport { getStateRoot } from '../utils/paths.js';\n\nlet cachedLogger: Logger | undefined;\n\nfunction buildLogger(): Logger {\n const stateRoot = getStateRoot();\n mkdirSync(stateRoot, { recursive: true });\n const logPath = path.join(stateRoot, 'daemon.log');\n\n const fileStream = createWriteStream(logPath, { flags: 'a' });\n\n const stderrIsTTY = process.stderr.isTTY === true;\n const stderrStream: NodeJS.WritableStream = stderrIsTTY\n ? (pino.transport({\n target: 'pino-pretty',\n options: { destination: 2, colorize: true },\n }) as unknown as NodeJS.WritableStream)\n : process.stderr;\n\n const streams: StreamEntry[] = [{ stream: stderrStream }, { stream: fileStream }];\n\n return pino({ level: process.env.AW_LOG_LEVEL ?? 'info' }, multistream(streams));\n}\n\nexport function getLogger(): Logger {\n cachedLogger ??= buildLogger();\n return cachedLogger;\n}\n\n/** Reset the cached logger. Used by tests that need a clean instance. */\nexport function resetLogger(): void {\n cachedLogger = undefined;\n}\n","/**\n * Daemon adapter that keeps the AW-23 session-signal index warm.\n *\n * Same posture as the live-reload watcher: indexing is a nicety, so every\n * failure path here degrades to `null` and a warning rather than aborting the\n * daemon. A failed migration, a better-sqlite3 ABI mismatch after a Node\n * upgrade, or an unreadable transcripts root must not stop `active-work mcp\n * serve` from serving.\n */\nimport { existsSync } from 'node:fs';\nimport { transcriptsRoot } from '@titan-design/session-read';\nimport { watchTree, type TreeWatcher } from '@titan-design/daemon';\nimport { openGraph, type SessionGraph } from '../session-index/graph.js';\nimport { runRefresh, withRefreshLock } from '../session-index/refresh.js';\nimport { RefreshScheduler, type SchedulerStatus } from '../session-index/scheduler.js';\n\nexport interface SessionIndexWatcher {\n status(): SchedulerStatus;\n close(): Promise<void>;\n}\n\ninterface WatchLogger {\n info(obj: object, msg: string): void;\n warn(obj: object, msg: string): void;\n}\n\n/**\n * Transcript writes arrive continuously during an active session, so the\n * debounce is an order of magnitude longer than the live-reload watcher's:\n * coalescing two seconds of appends into one pass is the difference between\n * indexing and thrashing.\n */\nconst DEFAULT_DEBOUNCE_MS = 2_000;\n\n/**\n * Fallback poll. `fs.watch` misses events on network filesystems and after a\n * watcher hits EMFILE, so the index converges on a timer even when no\n * notification ever arrives.\n */\nconst DEFAULT_POLL_MS = 60_000;\n\nfunction envInt(name: string, fallback: number): number {\n const raw = process.env[name];\n const value = raw === undefined ? NaN : Number(raw);\n return Number.isFinite(value) && value > 0 ? value : fallback;\n}\n\n/** Set `AW_INDEX_WATCH=0` to run the daemon with indexing switched off. */\nfunction disabled(): boolean {\n return process.env.AW_INDEX_WATCH === '0';\n}\n\nexport function startSessionIndexWatch(log: WatchLogger): SessionIndexWatcher | null {\n if (disabled()) {\n log.info({}, 'session index watch disabled by AW_INDEX_WATCH=0');\n return null;\n }\n\n let graph: SessionGraph;\n try {\n graph = openGraph();\n } catch (err) {\n log.warn({ err }, 'session index unavailable; transcript indexing disabled');\n return null;\n }\n\n const scheduler = new RefreshScheduler(() => withRefreshLock(() => runRefresh({ graph })), {\n onError: (err) => log.warn({ err }, 'session index refresh failed'),\n });\n\n const root = transcriptsRoot();\n let watcher: TreeWatcher | null = null;\n // A machine that has never run Claude Code has no transcripts root. That is\n // an ordinary state, not a fault: skip the watcher and let the poll pick the\n // directory up if it ever appears.\n if (existsSync(root)) {\n try {\n watcher = watchTree(root, () => scheduler.trigger(), {\n debounceMs: envInt('AW_INDEX_DEBOUNCE_MS', DEFAULT_DEBOUNCE_MS),\n onError: (err) => log.warn({ err }, 'session index watcher error'),\n });\n log.info({ root }, 'watching transcripts for session indexing');\n } catch (err) {\n log.warn({ err, root }, 'transcript watcher unavailable; falling back to polling');\n }\n } else {\n log.info({ root }, 'no transcripts root yet; session indexing will poll for one');\n }\n\n const poll = setInterval(() => scheduler.trigger(), envInt('AW_INDEX_POLL_MS', DEFAULT_POLL_MS));\n poll.unref();\n\n // Un-awaited: a cold corpus takes tens of seconds to index and the daemon\n // must be answering on its port long before that finishes.\n scheduler.trigger();\n\n return {\n status: () => scheduler.status(),\n async close(): Promise<void> {\n clearInterval(poll);\n watcher?.close();\n await scheduler.close();\n graph.db.close();\n },\n };\n}\n","import Database from 'better-sqlite3';\nimport { MIGRATIONS, openSessionGraph, type SessionGraph } from '@titan-design/session-graph';\nimport path from 'node:path';\nimport { getMinerRoot } from '../utils/paths.js';\n\n/**\n * active-work's binding of `@titan-design/session-graph`: where the graph file\n * lives, and how to open it read-only.\n *\n * The package owns the schema and its migration chain, so nothing here\n * describes tables. What active-work still decides is the path — under\n * `getMinerRoot()`, so `ACTIVE_ROOT` overrides and test isolation keep working.\n */\n\nexport type { SessionGraph };\n\n/**\n * The schema version the code expects, derived from the migration chain rather\n * than declared next to it (TP-35). `miner status` reports it.\n */\nexport const SCHEMA_VERSION = MIGRATIONS[MIGRATIONS.length - 1]?.version ?? 0;\n\n/**\n * The cross-initiative graph file.\n *\n * Deliberately not the `index.sqlite3` that `src/miner/` wrote: that file\n * carries the retired AW-23 schema under `PRAGMA user_version`, and the\n * package's migration runner tracks versions in its own table. Pointing the new\n * runner at the old file would leave two version records disagreeing about the\n * same database. A new name makes the cutover a rebuild, which is what it is.\n */\nexport function defaultGraphPath(): string {\n return path.join(getMinerRoot(), 'graph.sqlite3');\n}\n\n/** Open (creating if absent) the session graph, migrating it to `SCHEMA_VERSION`. */\nexport function openGraph(dbPath: string = defaultGraphPath()): SessionGraph {\n return openSessionGraph(dbPath);\n}\n\n/**\n * Open without migrating — for diagnostics, which must be able to *look at* a\n * graph without changing it.\n *\n * Opening is not a read: `openGraph` runs migrations, and a migration is free\n * to rewrite rows. That is intended for the indexer, which rebuilds\n * immediately afterwards. It is emphatically not intended for `miner status` or\n * `miner liveness`, where it turns \"tell me about the index\" into \"rewrite the\n * index\" with no prompt — as it did once, to a real 155 MB corpus, while this\n * very command was being written.\n */\nexport function openGraphReadOnly(dbPath: string = defaultGraphPath()): Database.Database {\n return new Database(dbPath, { readonly: true });\n}\n","import path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport lockfile from 'proper-lockfile';\nimport { discoverTranscripts, transcriptsRoot } from '@titan-design/session-read';\nimport { refreshCorpus, resetIndex } from '@titan-design/session-graph';\nimport { defaultGraphPath, openGraph, type SessionGraph } from './graph.js';\nimport { taskResolver } from './tasks.js';\n\n/**\n * One refresh pass over the transcript corpus: discover -> index each changed\n * transcript -> roll up -> reconcile -> enrich tasks from the active-work store.\n *\n * The pass itself is `@titan-design/session-graph`; what lives here is what the\n * package must not know — where the corpus is, where the graph file is, the\n * cross-process lock, and which store resolves a `task:` ref. This is the\n * single code path behind `tools/build-session-index.mjs`, the `miner refresh`\n * command and the daemon's watcher, so a bug can only be fixed (or introduced)\n * once.\n */\n\nexport interface RefreshOptions {\n /** Reuse an open graph (the daemon holds one); otherwise one is opened. */\n graph?: SessionGraph;\n dbPath?: string;\n /** Wipe every derived row and re-read every transcript from byte 0. */\n full?: boolean;\n /** Visit at most this many transcripts (debugging aid). */\n limit?: number;\n /** Stream a whole-file sha256 per transcript; defaults to `full`. */\n verifyHashes?: boolean;\n /** Transcript corpus root; overridable for tests. */\n root?: string;\n /** Active-work root the task resolver reads; defaults to `getActiveRoot()`. */\n taskRoot?: string;\n}\n\nexport interface RefreshSummary {\n startedAt: string;\n durationMs: number;\n /** Transcripts discovered in the corpus. */\n transcripts: number;\n /** Transcripts this pass actually visited (differs under `--limit`). */\n scanned: number;\n indexed: number;\n /** Transcripts re-read from byte 0 because the source was rewritten. */\n rewound: number;\n unchanged: number;\n quarantined: number;\n /** Visited transcripts that vanished mid-pass, between discovery and stat. */\n missing: number;\n /** Rows marked `missing` because their file was already gone (AW-105). */\n reconciledMissing: number;\n factsAdded: number;\n turnsRolledUp: number;\n /** Task ids handed to the resolver, and rows it wrote. */\n tasksRequested: number;\n tasksApplied: number;\n errors: string[];\n}\n\nexport const LOCK_STALE_MS = 60_000;\n\n/** `<minerRoot>/graph.sqlite3.lock` — the cross-process refresh mutex. */\nexport function refreshLockPath(): string {\n return `${defaultGraphPath()}.lock`;\n}\n\n/**\n * Run `fn` holding the refresh lock, *blocking* until the current holder\n * releases rather than failing fast: a user typing `miner refresh` while the\n * daemon happens to be mid-pass wants their refresh to happen, not an error.\n * A crashed holder's lock goes stale after `LOCK_STALE_MS`.\n */\nexport async function withRefreshLock<T>(fn: () => Promise<T>): Promise<T> {\n const target = refreshLockPath();\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.writeFile(target, '', { flag: 'a' });\n const release = await lockfile.lock(target, {\n realpath: false,\n stale: LOCK_STALE_MS,\n retries: { retries: 120, factor: 1.5, minTimeout: 200, maxTimeout: 2_000 },\n });\n try {\n return await fn();\n } finally {\n await release();\n }\n}\n\n/**\n * `verifyHashes` defaults to `full` on purpose, and drives both of the\n * package's hash options: `verifyHash` re-reads each transcript's consumed\n * prefix (detecting a rewrite that left the file the same length or longer),\n * `withContentHash` stores a whole-file sha256 for durability reporting. Both\n * are O(corpus), and making incremental passes sample them would make two runs\n * over identical inputs produce different `content_hash` state — which the\n * equivalence eval reads as a real divergence. Drift detection rides on\n * `--full`.\n *\n * The cost of that default: an ordinary incremental pass cannot see a rotation\n * that grew the file, so such a transcript reads from a stale offset, lands\n * mid-line and quarantines until the next `--full`. The pre-package extractor\n * hashed the prefix on every resume; `resumePoint` hashes *before* it decides\n * there is nothing to do, so making that unconditional would re-read the whole\n * corpus on every 60-second daemon poll.\n */\nexport async function runRefresh(options: RefreshOptions = {}): Promise<RefreshSummary> {\n const startedAt = new Date().toISOString();\n const started = Date.now();\n const graph = options.graph ?? openGraph(options.dbPath ?? defaultGraphPath());\n const owned = options.graph === undefined;\n\n try {\n if (options.full) resetIndex(graph);\n const discovered = await discoverTranscripts(options.root ?? transcriptsRoot());\n const visiting = discovered.slice(0, options.limit ?? discovered.length);\n const verify = options.verifyHashes ?? options.full ?? false;\n\n const summary = await refreshCorpus(graph, visiting, {\n full: options.full,\n verifyHash: verify,\n withContentHash: verify,\n resolveTasks: taskResolver(options.taskRoot),\n });\n\n return {\n startedAt,\n durationMs: Date.now() - started,\n transcripts: discovered.length,\n scanned: visiting.length,\n indexed: summary.indexed,\n rewound: summary.rewound,\n unchanged: summary.unchanged,\n quarantined: summary.quarantined,\n missing: summary.missing,\n reconciledMissing: summary.markedMissing,\n factsAdded: summary.facts,\n turnsRolledUp: summary.turnsRolledUp,\n tasksRequested: summary.tasks.requested,\n tasksApplied: summary.tasks.applied,\n errors: [\n ...(summary.tasks.failed ? [`tasks: ${summary.tasks.error ?? 'resolver failed'}`] : []),\n ...quarantineErrors(graph),\n ],\n };\n } finally {\n if (owned) graph.db.close();\n }\n}\n\n/**\n * Read the quarantine reasons back off the transcript rows rather than out of\n * the pass, because the package reports counts and stores the reasons. That\n * makes this the standing set of unreadable transcripts, not just the ones this\n * pass tripped over — which is the more useful answer for a command whose job\n * is \"is the index healthy\". Rows marked `missing` are excluded: a rotated\n * transcript is ordinary, and `reconciledMissing` already counts them.\n */\nfunction quarantineErrors(graph: SessionGraph): string[] {\n return graph.transcripts\n .list()\n .filter((row) => row.status === 'quarantined')\n .map((row) => `quarantined: ${row.sourceKey} — ${row.statusReason ?? 'no reason recorded'}`);\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport type { ResolvedTask, TaskResolution, TaskResolver } from '@titan-design/session-graph';\n\nimport { TaskSchema } from '../schemas/task.js';\nimport { getActiveRoot } from '../utils/paths.js';\nimport { readYaml } from '../utils/yaml-io.js';\n\n/**\n * Resolve `task:<id>` refs against the active-work task store (AW-101).\n *\n * This is the one thing the index reads that is not a transcript, and it is a\n * deliberate exception rather than drift. A transcript states only the id a\n * command acted on — `aw task done active-work AW-104` — so a task's present\n * title, initiative and status exist nowhere in the corpus. The alternative was\n * to drop the columns; the call was to fill them.\n *\n * `@titan-design/session-graph` takes this as its `TaskResolver` (TP-22) and\n * calls it once per refresh pass with every task id in the graph. Two\n * consequences follow and are designed for rather than hidden:\n *\n * - These columns are NOT a pure function of the JSONL, so a rebuild has to\n * re-read the store. That is why the resolver runs whole-table at the end of\n * every pass rather than at line-handling time.\n * - They go stale when a task changes. Recomputing each pass bounds that to one\n * refresh interval.\n */\n\n/**\n * A task id is unique per initiative, not globally, and one collision is real:\n * `health` and `herald` both mint `H-<n>`, so `H-1`..`H-7` name two different\n * tasks. An ambiguous id resolves to nothing rather than to a coin flip — a\n * wrong title is worse than a null one, and no ambiguous id is actually cited\n * by any command in the corpus.\n */\nconst AMBIGUOUS = null;\n\ntype TaskStore = Map<string, ResolvedTask | typeof AMBIGUOUS>;\n\nasync function initiativeSlugs(root: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(root, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory() && !e.name.startsWith('.')).map((e) => e.name);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n}\n\nasync function readInitiative(root: string, slug: string): Promise<[string, ResolvedTask][]> {\n const dir = path.join(root, slug, 'tasks');\n let files: string[];\n try {\n files = await fs.readdir(dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const found: [string, ResolvedTask][] = [];\n for (const file of files) {\n if (!file.endsWith('.yml')) continue;\n // A malformed task file must not fail the whole refresh: the index is a\n // read-only observer of this store and has no standing to reject it.\n try {\n const task = await readYaml(path.join(dir, file), TaskSchema);\n found.push([task.id, { initiative: slug, title: task.title, status: task.status }]);\n } catch {\n continue;\n }\n }\n return found;\n}\n\n/** Every task in the store, keyed by bare id; ambiguous ids map to null. */\nexport async function loadTaskStore(root: string = getActiveRoot()): Promise<TaskStore> {\n const store: TaskStore = new Map();\n for (const slug of await initiativeSlugs(root)) {\n for (const [id, task] of await readInitiative(root, slug)) {\n if (store.has(id)) store.set(id, AMBIGUOUS);\n else store.set(id, task);\n }\n }\n return store;\n}\n\n/**\n * Only the ids the graph asked about are answered, so the task table stays\n * \"tasks the corpus mentions\". The resolver contract allows returning ids no\n * transcript named, which would insert them; that would silently turn this\n * table into a mirror of the whole store, which is a different feature.\n */\nexport function taskResolver(root?: string): TaskResolver {\n return async (taskIds: readonly string[]): Promise<TaskResolution> => {\n const store = await loadTaskStore(root);\n const resolved = new Map<string, ResolvedTask | null>();\n for (const taskId of taskIds) {\n const task = store.get(taskId);\n if (task) resolved.set(taskId, task);\n }\n return resolved;\n };\n}\n","import type { RefreshSummary } from './refresh.js';\n\n/**\n * Collapses a burst of change notifications into a bounded number of refresh\n * runs, without ever running two concurrently.\n *\n * The daemon's file watcher fires on every write under the transcripts root —\n * which, during an active session, is continuous. Queueing one run per event\n * would put the indexer permanently behind; running them concurrently would\n * have two writers fighting over the same SQLite file. So: at most one run in\n * flight, and at most one more queued behind it.\n */\n\nexport interface SchedulerStatus {\n running: boolean;\n pending: boolean;\n last: RefreshSummary | null;\n lastError: string | null;\n consecutiveErrors: number;\n}\n\nexport interface SchedulerOptions {\n onError?: (err: unknown) => void;\n /** Injectable for tests; defaults to a real timer. */\n sleep?: (ms: number) => Promise<void>;\n baseBackoffMs?: number;\n maxBackoffMs?: number;\n}\n\nconst DEFAULT_BASE_BACKOFF_MS = 1_000;\nconst DEFAULT_MAX_BACKOFF_MS = 60_000;\n\nconst realSleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms).unref?.());\n\nexport class RefreshScheduler {\n private running = false;\n private pending = false;\n private closed = false;\n private inFlight: Promise<void> | null = null;\n private last: RefreshSummary | null = null;\n private lastError: string | null = null;\n private consecutiveErrors = 0;\n\n constructor(\n private readonly run: () => Promise<RefreshSummary>,\n private readonly options: SchedulerOptions = {},\n ) {}\n\n /**\n * Ask for a refresh. Fire-and-forget and never rejects — a watcher callback\n * has nowhere to put a rejection, and an unhandled one would take the daemon\n * down.\n */\n trigger(): void {\n if (this.closed) return;\n this.pending = true;\n if (this.running) return;\n this.running = true;\n this.inFlight = this.drain().finally(() => {\n this.running = false;\n this.inFlight = null;\n });\n }\n\n /**\n * `pending` is a boolean, not a counter: N triggers arriving mid-run must\n * collapse to exactly one extra run, not N. It is cleared at the *start* of\n * each iteration — clearing it after the run would swallow a trigger that\n * landed while that run was in progress, losing the change that caused it.\n */\n private async drain(): Promise<void> {\n do {\n this.pending = false;\n try {\n this.last = await this.run();\n this.lastError = null;\n this.consecutiveErrors = 0;\n } catch (err) {\n this.consecutiveErrors += 1;\n this.lastError = err instanceof Error ? err.message : String(err);\n this.options.onError?.(err);\n // Back off so a permanently broken corpus cannot spin the daemon.\n await (this.options.sleep ?? realSleep)(this.backoffMs());\n }\n } while (this.pending && !this.closed);\n }\n\n private backoffMs(): number {\n const base = this.options.baseBackoffMs ?? DEFAULT_BASE_BACKOFF_MS;\n const max = this.options.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;\n return Math.min(base * 2 ** (this.consecutiveErrors - 1), max);\n }\n\n status(): SchedulerStatus {\n return {\n running: this.running,\n pending: this.pending,\n last: this.last,\n lastError: this.lastError,\n consecutiveErrors: this.consecutiveErrors,\n };\n }\n\n /** Drop anything queued and wait for the in-flight run to commit. */\n async close(): Promise<void> {\n this.closed = true;\n this.pending = false;\n await this.inFlight;\n }\n}\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { isProcessAlive, readPidFile, removePidFile } from '../server/lifecycle.js';\n\n/**\n * `active-work mcp stop` — send SIGTERM to the daemon and wait for it to exit.\n *\n * Returns `{ stopped: false, reason: 'not running' }` when no PID file\n * exists or the recorded process has already died.\n */\n\nconst ArgsSchema = z.object({});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.union([\n z.object({ stopped: z.literal(true), pid: z.number() }),\n z.object({ stopped: z.literal(false), reason: z.string() }),\n]);\ntype Result = z.infer<typeof ResultSchema>;\n\nconst SHUTDOWN_TIMEOUT_MS = 3000;\nconst POLL_INTERVAL_MS = 100;\n\nasync function waitForExit(pid: number, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (!isProcessAlive(pid)) return true;\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n return !isProcessAlive(pid);\n}\n\nexport default defineCommand<Args, Result>({\n name: 'mcp.stop',\n description: 'Stop the running MCP HTTP daemon (sends SIGTERM, waits for exit).',\n args: ArgsSchema,\n result: ResultSchema,\n async run() {\n const pidEntry = await readPidFile();\n if (!pidEntry) {\n return { stopped: false, reason: 'not running' };\n }\n const { pid } = pidEntry;\n if (!isProcessAlive(pid)) {\n await removePidFile(pid);\n return { stopped: false, reason: 'not running' };\n }\n try {\n process.kill(pid, 'SIGTERM');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ESRCH') {\n await removePidFile(pid);\n return { stopped: false, reason: 'not running' };\n }\n throw err;\n }\n await waitForExit(pid, SHUTDOWN_TIMEOUT_MS);\n // Scoped to the pid we killed: a supervisor may have already replaced it.\n await removePidFile(pid);\n return { stopped: true, pid };\n },\n});\n","import { spawn } from 'node:child_process';\nimport { z } from 'zod';\nimport { DaemonError } from '../errors.js';\nimport { defineCommand } from '../registry/index.js';\nimport {\n DEFAULT_DAEMON_PORT,\n isProcessAlive,\n probeHealth,\n readPidFile,\n removePidFile,\n} from '../server/lifecycle.js';\n\n/**\n * `active-work mcp restart` — stop the running daemon (if any) then spawn a new\n * detached daemon. Honors the previously-bound port when not overridden.\n *\n * Both waits below are load-bearing (TP-36). A predecessor that has not exited\n * still owns the port, so a successor spawned too early fails to bind and dies\n * silently; the caller was then handed a pid that no longer existed and `mcp\n * status` reported nothing running at all.\n */\n\nconst ArgsSchema = z.object({\n port: z.number().int().positive().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n pid: z.number(),\n port: z.number(),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\n/** Shutdown awaits an in-flight index refresh, which runs for seconds on a large corpus. */\nconst SHUTDOWN_TIMEOUT_MS = 15_000;\n/** SIGKILL is immediate; this covers scheduler lag only. */\nconst KILL_TIMEOUT_MS = 3_000;\n/** Cold start rebuilds the registry and binds the socket before `/health` answers. */\nconst STARTUP_TIMEOUT_MS = 15_000;\nconst POLL_INTERVAL_MS = 100;\n\nasync function waitFor(\n ready: () => boolean | Promise<boolean>,\n timeoutMs: number,\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (await ready()) return true;\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n return ready();\n}\n\nfunction signal(pid: number, sig: NodeJS.Signals): void {\n try {\n process.kill(pid, sig);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ESRCH') throw err;\n }\n}\n\nasync function stopExisting(): Promise<number | undefined> {\n const entry = await readPidFile();\n if (!entry) return undefined;\n const { pid, meta } = entry;\n if (isProcessAlive(pid)) await terminate(pid);\n // Scoped to the pid we killed: a supervisor may have already replaced it.\n await removePidFile(pid);\n return meta.port;\n}\n\nasync function terminate(pid: number): Promise<void> {\n signal(pid, 'SIGTERM');\n if (await waitFor(() => !isProcessAlive(pid), SHUTDOWN_TIMEOUT_MS)) return;\n signal(pid, 'SIGKILL');\n if (await waitFor(() => !isProcessAlive(pid), KILL_TIMEOUT_MS)) return;\n throw new DaemonError(\n `Daemon pid ${pid} survived SIGTERM and SIGKILL; not starting a second one`,\n );\n}\n\nfunction detachedSpawn(port: number): { pid: number; port: number } {\n const entry = process.argv[1];\n if (!entry) {\n throw new Error('Cannot determine CLI entrypoint for restart');\n }\n const child = spawn(process.execPath, [entry, 'mcp', 'serve', '--port', String(port)], {\n detached: true,\n stdio: 'ignore',\n env: process.env,\n });\n child.unref();\n return { pid: child.pid ?? -1, port };\n}\n\n/**\n * A daemon that cannot bind exits within milliseconds and logs nothing, so the\n * death of the child is the fast signal; the timeout only covers a child that\n * lives but never becomes answerable.\n */\nasync function confirmStarted(pid: number, port: number): Promise<void> {\n const up = await waitFor(async () => {\n if (!isProcessAlive(pid)) {\n throw new DaemonError(\n `Spawned pid ${pid} exited immediately — port ${port} is likely still held. See \\`active-work mcp logs\\``,\n );\n }\n return (await probeHealth(port)) !== null;\n }, STARTUP_TIMEOUT_MS);\n if (up) return;\n throw new DaemonError(\n `Spawned pid ${pid} is running but nothing answered http://127.0.0.1:${port}/health within ${STARTUP_TIMEOUT_MS}ms`,\n );\n}\n\nexport default defineCommand<Args, Result>({\n name: 'mcp.restart',\n description: 'Restart the MCP HTTP daemon (stop, then spawn a fresh detached instance).',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n port: {\n long: '--port',\n description: 'Port for the restarted daemon (default: previous port or 7400).',\n },\n },\n },\n async run(args) {\n const prevPort = await stopExisting();\n const port = args.port ?? prevPort ?? DEFAULT_DAEMON_PORT;\n const spawned = detachedSpawn(port);\n await confirmStarted(spawned.pid, port);\n return spawned;\n },\n});\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport {\n isProcessAlive,\n probeHealth,\n readPidFile,\n resolveDaemonPort,\n} from '../server/lifecycle.js';\n\n/**\n * `active-work mcp status` — report whether the daemon is running, plus a\n * snapshot of `/health` if it answers.\n */\n\nconst ArgsSchema = z.object({});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n running: z.boolean(),\n pid: z.number().optional(),\n port: z.number().optional(),\n version: z.string().optional(),\n uptime_ms: z.number().optional(),\n healthy: z.boolean().optional(),\n /** Answering `/health` with no PID file naming it — see `removePidFile`. */\n orphaned: z.boolean().optional(),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\n/**\n * No usable PID file: probe the port anyway. Reporting \"not running\" purely\n * because the file is gone is how a live daemon disappeared from this command\n * while still serving requests (AW-76). `port` on a negative answer names what\n * we actually tried, since a daemon on a non-default `--port` with no file to\n * record it cannot be found from here.\n */\nasync function statusByPort(port: number): Promise<Result> {\n const health = await probeHealth(port);\n if (!health) return { running: false, port };\n return {\n running: true,\n healthy: true,\n orphaned: true,\n pid: health.pid,\n port: health.port,\n version: health.version,\n uptime_ms: health.uptime_ms,\n };\n}\n\nexport default defineCommand<Args, Result>({\n name: 'mcp.status',\n description: 'Report the MCP HTTP daemon status (pid, port, version, uptime).',\n args: ArgsSchema,\n result: ResultSchema,\n async run() {\n const entry = await readPidFile();\n if (!entry) {\n return statusByPort(resolveDaemonPort());\n }\n const { pid, meta } = entry;\n if (!isProcessAlive(pid)) {\n // A pre-meta pid file records port 0; fall back to where a daemon would be.\n return statusByPort(meta.port || resolveDaemonPort());\n }\n const health = await probeHealth(meta.port);\n if (health) {\n return {\n running: true,\n pid: health.pid,\n port: health.port,\n version: health.version,\n uptime_ms: health.uptime_ms,\n healthy: true,\n };\n }\n return {\n running: true,\n pid,\n port: meta.port,\n version: meta.version,\n healthy: false,\n };\n },\n});\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { getStateRoot } from '../utils/paths.js';\n\n/**\n * `active-work mcp logs` — return the tail of `daemon.log`.\n *\n * No `--follow` support in v0; callers that need streaming can `tail -f`\n * the file directly.\n */\n\nconst ArgsSchema = z.object({\n lines: z.number().int().positive().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n lines: z.array(z.string()),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nconst DEFAULT_LINES = 50;\n\nexport default defineCommand<Args, Result>({\n name: 'mcp.logs',\n description: 'Return the last N lines of the daemon log (default 50).',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n lines: {\n long: '--lines',\n description: 'Number of trailing lines to return (default 50).',\n },\n },\n },\n async run(args) {\n const n = args.lines ?? DEFAULT_LINES;\n const logPath = path.join(getStateRoot(), 'daemon.log');\n let content: string;\n try {\n content = await fs.readFile(logPath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return { lines: [] };\n }\n throw err;\n }\n const allLines = content.split(/\\r?\\n/);\n // Drop trailing empty line(s) from the final newline.\n while (allLines.length > 0 && allLines[allLines.length - 1] === '') {\n allLines.pop();\n }\n return { lines: allLines.slice(-n) };\n },\n});\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { runDrainIngest } from '../drain/transcript-reader.js';\n\n/**\n * `active-work miner drain-ingest` — cluster new tool-result and error blobs\n * from `~/.claude/projects` into the AW-28 Drain template store\n * (`<minerRoot>/templates.yml` + `occurrences.jsonl`).\n *\n * Registered alongside `miner refresh`/`miner status` (AW-90) so the miner CLI\n * surface stays one namespace, even though the two miners share no store:\n * `refresh` fills the session-signal SQLite index, this fills the template\n * store. `tools/mine-drain.mjs` is a thin wrapper over the same function, per\n * the `build-session-index.mjs` precedent.\n */\n\nconst ArgsSchema = z.object({\n full: z.boolean().optional(),\n limit: z.coerce.number().int().positive().optional(),\n verify_hashes: z.boolean().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n startedAt: z.string(),\n durationMs: z.number(),\n transcripts: z.number(),\n scanned: z.number(),\n unchanged: z.number(),\n rewound: z.number(),\n linesRead: z.number(),\n malformedLines: z.number(),\n blobs: z.number(),\n ingested: z.number(),\n newTemplates: z.number(),\n templates: z.number(),\n evicting: z.boolean(),\n curve: z.array(z.object({ blobs: z.number(), templates: z.number(), evicting: z.boolean() })),\n errors: z.array(z.string()),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'miner.drain-ingest',\n description:\n 'Cluster new tool-result/error blobs from Claude transcripts into the template store.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n full: {\n long: '--full',\n description: 'Ignore stored watermarks and re-read every transcript from byte 0.',\n },\n limit: {\n long: '--limit',\n description: 'Visit at most N transcripts.',\n },\n verify_hashes: {\n long: '--verify-hashes',\n description: 'Re-hash each read prefix to detect a rewritten transcript (slow).',\n },\n },\n },\n async run(args) {\n return runDrainIngest({\n full: args.full,\n limit: args.limit,\n verifyHashes: args.verify_hashes,\n });\n },\n});\n","import { nextOffset, prefixHash, readJsonLines, resumePoint } from '@titan-design/locator';\nimport { discoverTranscripts, transcriptsRoot } from '@titan-design/session-read';\nimport { MinerIngestor } from './ingestor.js';\nimport { collectToolUses, extractBlobs } from './blob-extract.js';\nimport {\n loadReaderState,\n saveReaderState,\n transcriptIndexFor,\n trimPendingToolNames,\n type ReaderState,\n type TranscriptState,\n} from './reader-state.js';\nimport { getMinerRoot } from '../utils/paths.js';\nimport type { Locator } from '../schemas/template.js';\n\n/**\n * AW-89: streams `~/.claude/projects/*<slash>*.jsonl` into\n * `MinerIngestor.ingestBlob`, the last build step deferred from AW-28/PR #81.\n *\n * Incremental by byte watermark per transcript (`reader-state.json`), over\n * `@titan-design/locator`'s line reader and resume point and\n * `@titan-design/session-read`'s discovery, so this and the session graph agree\n * on what a transcript is and where a line starts. What is deliberately *not*\n * shared is the extraction model: the graph indexes every line, this reads\n * whole tool-result blobs, because Drain clusters a blob's shape through one\n * signature line.\n *\n * Ingest runs buffered: one `templates.yml` write and one `occurrences.jsonl`\n * append per pass rather than per blob. Clustering is untouched by this — see\n * `MinerIngestorOptions.buffered`.\n */\n\nexport interface DrainIngestOptions {\n /** Miner store root; overridable for tests and eval sandboxes. */\n root?: string;\n /** Transcript corpus root. */\n corpusRoot?: string;\n /** Visit at most this many transcripts. */\n limit?: number;\n /** Ignore stored watermarks and re-read every transcript from byte 0. */\n full?: boolean;\n /**\n * Stop reading each transcript after this many new bytes, leaving the\n * watermark mid-file. Exists so the eval can force chunk boundaries that a\n * static corpus would never produce on its own.\n */\n chunkBytes?: number;\n /**\n * Re-hash each transcript's already-read prefix to detect a rewrite rather\n * than an append. Off by default because it is O(corpus) per pass; a file\n * that *shrank* below its watermark is always detected, hash or not.\n */\n verifyHashes?: boolean;\n /**\n * Record a `(blobs, templates)` sample every N blobs. Feeds the eval's\n * template-growth curve, which has to be sampled *within* one pass: slicing\n * the corpus by transcript instead makes slice size swing by two orders of\n * magnitude, and the resulting rates measure transcript size, not clustering.\n */\n sampleEvery?: number;\n}\n\n/** One `(blobs seen, templates known)` sample from the growth curve. */\nexport interface GrowthSample {\n blobs: number;\n templates: number;\n /** Whether any Drain partition was already evicting at this point. */\n evicting: boolean;\n}\n\nexport interface DrainIngestSummary {\n startedAt: string;\n durationMs: number;\n /** Transcripts discovered in the corpus. */\n transcripts: number;\n /** Transcripts this pass actually opened (the rest were at their watermark). */\n scanned: number;\n unchanged: number;\n /** Transcripts rewound to byte 0 because the source was rewritten. */\n rewound: number;\n linesRead: number;\n /** Lines that were not parseable JSON — counted, skipped, never fatal. */\n malformedLines: number;\n /** Candidate blobs found, before the AW-93 error-signal screen. */\n candidateBlobs: number;\n /** Candidates dropped by the screen: successful output with no failure shape. */\n screened: number;\n /** Eligible blobs found (`candidateBlobs - screened`). */\n blobs: number;\n /** Blobs that clustered successfully (`blobs - ingestErrors`). */\n ingested: number;\n newTemplates: number;\n /** Total templates in the store after this pass. */\n templates: number;\n /** Growth curve samples; empty unless `sampleEvery` was set. */\n curve: GrowthSample[];\n /** Any Drain partition is at its cluster cap — see `DrainTree.atCapacity`. */\n evicting: boolean;\n errors: string[];\n}\n\ninterface PassCounters {\n linesRead: number;\n malformedLines: number;\n candidateBlobs: number;\n screened: number;\n blobs: number;\n ingested: number;\n newTemplates: number;\n curve: GrowthSample[];\n errors: string[];\n}\n\nfunction emptyCounters(): PassCounters {\n return {\n linesRead: 0,\n malformedLines: 0,\n candidateBlobs: 0,\n screened: 0,\n blobs: 0,\n ingested: 0,\n newTemplates: 0,\n curve: [],\n errors: [],\n };\n}\n\n/** A watermark at byte 0, which is what `--full` resumes every transcript from. */\nconst BYTE_ZERO = { path: '', lastByteOffset: 0, prefixHash: null };\n\n/** Parse a line, counting (not throwing on) transcript corruption. */\nfunction parseLine(text: string, counters: PassCounters): Record<string, unknown> | null {\n try {\n const value: unknown = JSON.parse(text);\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;\n return value as Record<string, unknown>;\n } catch {\n counters.malformedLines++;\n return null;\n }\n}\n\ninterface TranscriptPass {\n transcriptIndex: number;\n absolutePath: string;\n start: number;\n entry: TranscriptState;\n}\n\n/**\n * Read one transcript from its watermark, ingesting every eligible blob.\n *\n * The watermark only ever advances to a *completed* line boundary\n * (`readJsonLines` withholds a trailing partial line), so a transcript being\n * appended to mid-pass resumes cleanly instead of splitting a record.\n */\nasync function readTranscript(\n pass: TranscriptPass,\n ingestor: MinerIngestor,\n counters: PassCounters,\n options: DrainIngestOptions,\n): Promise<void> {\n const toolNames = new Map(Object.entries(pass.entry.pendingToolNames));\n let offset = pass.start;\n\n for await (const line of readJsonLines(pass.absolutePath, pass.start)) {\n offset = nextOffset(line);\n counters.linesRead++;\n const parsed = parseLine(line.text, counters);\n if (parsed) {\n for (const [id, name] of collectToolUses(parsed)) toolNames.set(id, name);\n const locator: Locator = [pass.transcriptIndex, line.byteOffset, line.byteLength];\n await ingestLine(parsed, locator, toolNames, ingestor, counters, options.sampleEvery);\n }\n if (options.chunkBytes !== undefined && offset - pass.start >= options.chunkBytes) break;\n }\n\n pass.entry.lastByteOffset = offset;\n pass.entry.pendingToolNames = trimPendingToolNames(toolNames);\n pass.entry.prefixHash = options.verifyHashes ? await prefixHash(pass.absolutePath, offset) : null;\n}\n\nasync function ingestLine(\n parsed: Record<string, unknown>,\n locator: Locator,\n toolNames: Map<string, string>,\n ingestor: MinerIngestor,\n counters: PassCounters,\n sampleEvery: number | undefined,\n): Promise<void> {\n for (const blob of extractBlobs(parsed, toolNames)) {\n counters.candidateBlobs++;\n if (!blob.eligible) {\n counters.screened++;\n continue;\n }\n counters.blobs++;\n try {\n const result = await ingestor.ingestBlob({ ...blob, locator });\n counters.ingested++;\n if (result.isNewTemplate) counters.newTemplates++;\n if (sampleEvery !== undefined && counters.blobs % sampleEvery === 0) {\n counters.curve.push({\n blobs: counters.blobs,\n templates: ingestor.templateCount,\n evicting: ingestor.evicting,\n });\n }\n } catch (err) {\n counters.errors.push(\n `${locator[0]}:${locator[1]} ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n}\n\n/**\n * One full pass over the corpus. Idempotent in the sense that matters for a\n * template store: re-running it over unchanged transcripts reads nothing and\n * changes nothing, and a chunked sequence of passes converges to the same\n * template set as a single pass (asserted by `tools/eval-drain.mjs`).\n */\nexport async function runDrainIngest(\n options: DrainIngestOptions = {},\n): Promise<DrainIngestSummary> {\n const startedAt = new Date().toISOString();\n const started = process.hrtime.bigint();\n const root = options.root ?? getMinerRoot();\n const corpusRoot = options.corpusRoot ?? transcriptsRoot();\n\n const discovered = await discoverTranscripts(corpusRoot);\n const visiting = options.limit === undefined ? discovered : discovered.slice(0, options.limit);\n const state: ReaderState = options.full\n ? { version: 1, transcripts: [] }\n : await loadReaderState(root);\n const ingestor = await MinerIngestor.create(root, { buffered: true });\n\n const counters = emptyCounters();\n let scanned = 0;\n let unchanged = 0;\n let rewound = 0;\n\n for (const transcript of visiting) {\n const transcriptIndex = transcriptIndexFor(state, transcript.displayPath);\n const entry = state.transcripts[transcriptIndex];\n try {\n // `full` is expressed as a zeroed watermark rather than as a flag the\n // resume point knows about: the package's contract is \"given this entry,\n // where do I resume\", and re-reading from byte 0 is not a rewrite.\n const point = await resumePoint(options.full ? BYTE_ZERO : entry, transcript.absolutePath, {\n verifyHash: options.verifyHashes,\n });\n if (point.state === 'missing') {\n counters.errors.push(`${transcript.displayPath}: source file no longer exists`);\n continue;\n }\n if (point.state === 'rewritten') {\n rewound++;\n entry.pendingToolNames = {};\n }\n if (point.state === 'unchanged') {\n unchanged++;\n continue;\n }\n scanned++;\n await readTranscript(\n { transcriptIndex, absolutePath: transcript.absolutePath, start: point.start, entry },\n ingestor,\n counters,\n options,\n );\n } catch (err) {\n counters.errors.push(\n `${transcript.displayPath}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n await ingestor.flush();\n await saveReaderState(state, root);\n\n return {\n startedAt,\n durationMs: Number(process.hrtime.bigint() - started) / 1e6,\n transcripts: discovered.length,\n scanned,\n unchanged,\n rewound,\n templates: ingestor.templateCount,\n evicting: ingestor.evicting,\n ...counters,\n };\n}\n","import { Clusterer } from '@titan-design/cluster';\nimport { appendOccurrence, appendOccurrences, loadTemplates, saveTemplates } from './store.js';\nimport { loadTreeSnapshots, saveTreeSnapshots } from './tree-store.js';\nimport { getMinerRoot } from '../utils/paths.js';\nimport type { Locator, Occurrence, Template } from '../schemas/template.js';\n\nexport interface IngestBlobInput {\n toolType: string;\n rawText: string;\n locator: Locator;\n sessionId: string;\n timestamp: string;\n}\n\nexport interface IngestBlobResult {\n templateId: string;\n isNewTemplate: boolean;\n}\n\nexport interface MinerIngestorOptions {\n /**\n * Hold occurrence appends and `templates.yml` rewrites in memory until\n * `flush()`. Off by default, so a single-blob caller keeps the durable\n * write-per-blob semantics AW-28 shipped with.\n *\n * A corpus pass ingests tens of thousands of blobs, and rewriting the whole\n * `templates.yml` per blob is O(blobs x templates) file I/O — minutes of\n * fsync for a run whose actual clustering work is seconds. The clustering\n * itself is unaffected: buffering changes only *when* bytes hit disk, never\n * which template a blob routes to.\n */\n buffered?: boolean;\n}\n\n/**\n * Puts one blob through `@titan-design/cluster` and durably records what came\n * out: a `templates.yml` upsert and an `occurrences.jsonl` append.\n *\n * The clustering — signature extraction, masking, Drain, template id — is the\n * package's. What is active-work's is the store on either side of it, and the\n * fact that a template's occurrence count is a property of that store rather\n * than of the live clusterer.\n *\n * A warm start restores the Drain trees from `<minerRoot>/drain-trees.json`\n * (AW-89), so every cluster comes back with the wildcards it had learned and\n * with its original `clusterId -> templateId` binding. That is what makes a\n * chunked sequence of ingest passes converge on the same template set as one\n * all-at-once pass — `tools/eval-drain.mjs` gates on exactly that.\n */\nexport class MinerIngestor {\n private readonly clusterer: Clusterer;\n private readonly templates: Map<string, Template>;\n private readonly root: string;\n private readonly buffered: boolean;\n private readonly pending: Occurrence[] = [];\n\n private constructor(\n clusterer: Clusterer,\n templates: Template[],\n root: string,\n options: MinerIngestorOptions,\n ) {\n this.clusterer = clusterer;\n this.templates = new Map(templates.map((t) => [t.templateId, t]));\n this.root = root;\n this.buffered = options.buffered ?? false;\n }\n\n static async create(\n root: string = getMinerRoot(),\n options: MinerIngestorOptions = {},\n ): Promise<MinerIngestor> {\n const [templates, snapshot] = await Promise.all([loadTemplates(root), loadTreeSnapshots(root)]);\n return new MinerIngestor(Clusterer.fromSnapshot(snapshot), templates, root, options);\n }\n\n private async persistTemplates(): Promise<void> {\n await saveTemplates([...this.templates.values()], this.root);\n await saveTreeSnapshots(this.clusterer.snapshot(), this.root);\n }\n\n async ingestBlob(input: IngestBlobInput): Promise<IngestBlobResult> {\n const clustered = this.clusterer.cluster({ partition: input.toolType, text: input.rawText });\n const existing = this.templates.get(clustered.templateId);\n // The store decides what \"new\" means, not the clusterer: a template already\n // in `templates.yml` is not new just because this process minted its id for\n // the first time (a cold start with no snapshot does exactly that).\n const isNewTemplate = existing === undefined;\n\n const occurrence: Occurrence = {\n templateId: clustered.templateId,\n locator: input.locator,\n sessionId: input.sessionId,\n timestamp: input.timestamp,\n ...(Object.keys(clustered.extractedParams).length > 0\n ? { extractedParams: clustered.extractedParams }\n : {}),\n };\n if (this.buffered) this.pending.push(occurrence);\n else await appendOccurrence(occurrence, this.root);\n\n const updated: Template = existing\n ? { ...existing, occurrenceCount: existing.occurrenceCount + 1 }\n : {\n templateId: clustered.templateId,\n toolType: input.toolType,\n maskedSignature: clustered.maskedSignature,\n createdAt: input.timestamp,\n occurrenceCount: 1,\n exemplarLocator: input.locator,\n };\n this.templates.set(clustered.templateId, updated);\n if (!this.buffered) await this.persistTemplates();\n\n return { templateId: clustered.templateId, isNewTemplate };\n }\n\n /**\n * Write everything buffered since the last flush. A no-op in unbuffered\n * mode, so callers can flush unconditionally.\n */\n async flush(): Promise<void> {\n if (!this.buffered) return;\n await appendOccurrences(this.pending, this.root);\n this.pending.length = 0;\n await this.persistTemplates();\n }\n\n get templateCount(): number {\n return this.templates.size;\n }\n\n /** True once any Drain partition is at its cluster cap (see `DrainTree.atCapacity`). */\n get evicting(): boolean {\n return this.clusterer.evicting;\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readYaml, writeYaml } from '../utils/yaml-io.js';\nimport { atomicWrite, withFileLock } from '../utils/fs-atomic.js';\nimport { getMinerRoot } from '../utils/paths.js';\nimport {\n OccurrenceSchema,\n TemplatesFileSchema,\n type Occurrence,\n type Template,\n} from '../schemas/template.js';\n\n/**\n * Persistence for the AW-28 Drain miner store: `templates.yml` (bounded,\n * whole-file rewrite on change) and `occurrences.jsonl` (unbounded,\n * append-only). Both live under `getMinerRoot()` — cross-initiative, not\n * scoped to any single slug, since transcripts span every workstream.\n *\n * Drain-tree snapshots (`drain-tree.<toolType>.json`) are an explicitly\n * rebuildable cache per §C1 (\"safe to delete and regenerate from\n * `occurrences` + re-running Drain\") and are not implemented yet — the\n * canonical source of truth for this first slice is `occurrences.jsonl`\n * plus re-running `ingestBlob`, which is already idempotent.\n */\n\nfunction templatesPath(root: string): string {\n return path.join(root, 'templates.yml');\n}\n\nfunction occurrencesPath(root: string): string {\n return path.join(root, 'occurrences.jsonl');\n}\n\nexport async function loadTemplates(root: string = getMinerRoot()): Promise<Template[]> {\n try {\n const file = await readYaml(templatesPath(root), TemplatesFileSchema);\n return file.templates;\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT') return [];\n throw err;\n }\n}\n\nexport async function saveTemplates(\n templates: Template[],\n root: string = getMinerRoot(),\n): Promise<void> {\n await fs.mkdir(root, { recursive: true });\n await writeYaml(templatesPath(root), { templates }, TemplatesFileSchema);\n}\n\n/**\n * Append one occurrence to `occurrences.jsonl` under an advisory lock, so\n * concurrent writers never interleave partial lines.\n */\nexport async function appendOccurrence(\n occurrence: Occurrence,\n root: string = getMinerRoot(),\n): Promise<void> {\n const parsed = OccurrenceSchema.parse(occurrence);\n const target = occurrencesPath(root);\n await fs.mkdir(root, { recursive: true });\n await withFileLock(`${target}.lock`, async () => {\n await fs.appendFile(target, `${JSON.stringify(parsed)}\\n`, 'utf8');\n });\n}\n\n/**\n * Append many occurrences under a single lock acquisition and a single\n * `appendFile`. Semantically identical to calling `appendOccurrence` in a\n * loop, but a corpus pass ingests tens of thousands of blobs and paying a\n * lock round-trip per blob dominates the whole run.\n */\nexport async function appendOccurrences(\n occurrences: Occurrence[],\n root: string = getMinerRoot(),\n): Promise<void> {\n if (occurrences.length === 0) return;\n const parsed = occurrences.map((o) => OccurrenceSchema.parse(o));\n const target = occurrencesPath(root);\n await fs.mkdir(root, { recursive: true });\n const body = `${parsed.map((o) => JSON.stringify(o)).join('\\n')}\\n`;\n await withFileLock(`${target}.lock`, async () => {\n await fs.appendFile(target, body, 'utf8');\n });\n}\n\n/** Stream-read every occurrence, validating each line lazily. */\nexport async function* readOccurrences(root: string = getMinerRoot()): AsyncGenerator<Occurrence> {\n let raw: string;\n try {\n raw = await fs.readFile(occurrencesPath(root), 'utf8');\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT') return;\n throw err;\n }\n for (const line of raw.split('\\n')) {\n if (line.trim().length === 0) continue;\n yield OccurrenceSchema.parse(JSON.parse(line));\n }\n}\n\n/**\n * Atomically overwrite `occurrences.jsonl` with `occurrences`, in order —\n * used by callers that rebuild the log wholesale (e.g. eviction/compaction),\n * as opposed to `appendOccurrence`'s incremental append.\n */\nexport async function rewriteOccurrences(\n occurrences: Occurrence[],\n root: string = getMinerRoot(),\n): Promise<void> {\n const parsed = occurrences.map((o) => OccurrenceSchema.parse(o));\n await fs.mkdir(root, { recursive: true });\n const body = parsed.map((o) => JSON.stringify(o)).join('\\n');\n await atomicWrite(occurrencesPath(root), parsed.length > 0 ? `${body}\\n` : '');\n}\n","import { z } from 'zod';\n\n/**\n * AW-28: Drain-clustered tool-result / error templates.\n *\n * `Locator` is `[transcriptIndex, byteOffset, byteLength]` — a pointer back\n * into the source `.jsonl` transcript, never the blob text itself. Full\n * text is never copied into templates.yml or occurrences.jsonl (see\n * sources/deepdive-session-mining-build-specs.md §C1).\n */\nexport const LocatorSchema = z.tuple([\n z.number().int().nonnegative(),\n z.number().int().nonnegative(),\n z.number().int().positive(),\n]);\n\nexport const TemplateSchema = z.object({\n templateId: z.string().min(1),\n toolType: z.string().min(1),\n maskedSignature: z.string().min(1),\n createdAt: z.string().min(1),\n occurrenceCount: z.number().int().nonnegative(),\n exemplarLocator: LocatorSchema,\n});\n\nexport const OccurrenceSchema = z.object({\n templateId: z.string().min(1),\n locator: LocatorSchema,\n sessionId: z.string().min(1),\n timestamp: z.string().min(1),\n extractedParams: z.record(z.string(), z.string()).optional(),\n});\n\nexport const TemplatesFileSchema = z.object({\n templates: z.array(TemplateSchema).default([]),\n});\n\nexport type Locator = z.infer<typeof LocatorSchema>;\nexport type Template = z.infer<typeof TemplateSchema>;\nexport type Occurrence = z.infer<typeof OccurrenceSchema>;\nexport type TemplatesFile = z.infer<typeof TemplatesFileSchema>;\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport type { ClustererSnapshot } from '@titan-design/cluster';\nimport { atomicWrite } from '../utils/fs-atomic.js';\nimport { getMinerRoot } from '../utils/paths.js';\n\n/**\n * `<minerRoot>/drain-trees.json` — the Drain clustering state, persisted so a\n * warm start resumes from the tree it left off with.\n *\n * Still a *rebuildable cache* in the §C1 sense: deleting it costs clustering\n * fidelity across the restart, not data, since `occurrences.jsonl` plus a\n * re-run of `ingestBlob` reconstructs everything. What it buys is that a\n * chunked sequence of ingest passes produces the same templates as one\n * all-at-once pass. Before AW-89 a warm start re-inserted each template's\n * *first-seen* masked signature through `insert()`, losing every wildcard the\n * live tree had learned; `tools/eval-drain.mjs` measured that as a real ~6%\n * template-set divergence on the operator's corpus, which is why this exists.\n *\n * The schema mirrors `ClustererSnapshot` because that is what\n * `@titan-design/cluster` restores from. It is validated on the way in and out\n * anyway: the package promises a shape, this file is a place a human or a half\n * -written run can corrupt, and a bad snapshot must not take the ingest down.\n */\n\nconst PartitionSchema = z.object({\n partition: z.string().min(1),\n nextClusterId: z.number().int().positive(),\n clusters: z.array(\n z.object({\n clusterId: z.number().int().positive(),\n tokens: z.array(z.string()),\n size: z.number().int().nonnegative(),\n }),\n ),\n /** `clusterId -> templateId`, as pairs so the file has a stable order. */\n templateIds: z.array(z.tuple([z.number().int().positive(), z.string().min(1)])),\n});\n\nexport const TreeSnapshotFileSchema = z.object({\n version: z.literal(1).default(1),\n partitions: z.array(PartitionSchema).default([]),\n});\n\n/**\n * The pre-package file, which keyed each tree by `toolType` and called the list\n * `trees`. Read so an upgrade keeps the wildcards the live trees had learned:\n * discarding it instead would cost the ~6% template-set divergence AW-89 was\n * built to remove, once, on every existing store.\n */\nconst LegacySnapshotFileSchema = z.object({\n version: z.literal(1),\n trees: z.array(PartitionSchema.omit({ partition: true }).extend({ toolType: z.string().min(1) })),\n});\n\nfunction snapshotPath(root: string): string {\n return path.join(root, 'drain-trees.json');\n}\n\nfunction empty(): ClustererSnapshot {\n return { version: 1, partitions: [] };\n}\n\n/** A snapshot that will not parse is discarded rather than thrown: it is a cache. */\nexport async function loadTreeSnapshots(root: string = getMinerRoot()): Promise<ClustererSnapshot> {\n let raw: string;\n try {\n raw = await fs.readFile(snapshotPath(root), 'utf8');\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT') return empty();\n throw err;\n }\n const value: unknown = JSON.parse(raw);\n // Legacy first: zod strips unknown keys, so the current schema would read a\n // `trees` file as an empty snapshot and report success.\n const legacy = LegacySnapshotFileSchema.safeParse(value);\n if (legacy.success) {\n return {\n version: 1,\n partitions: legacy.data.trees.map(({ toolType, ...tree }) => ({\n partition: toolType,\n ...tree,\n })),\n };\n }\n const parsed = TreeSnapshotFileSchema.safeParse(value);\n return parsed.success ? parsed.data : empty();\n}\n\nexport async function saveTreeSnapshots(\n snapshot: ClustererSnapshot,\n root: string = getMinerRoot(),\n): Promise<void> {\n await fs.mkdir(root, { recursive: true });\n await atomicWrite(\n snapshotPath(root),\n `${JSON.stringify(TreeSnapshotFileSchema.parse(snapshot))}\\n`,\n );\n}\n","import { hasErrorSignal } from '@titan-design/cluster';\nimport { toolTypeFor } from './partition.js';\n\n/**\n * Projects one transcript JSONL line into the tool-result *blobs* the Drain\n * miner clusters (AW-89).\n *\n * Deliberately per-blob, not per-line: `ingestor.ts` clusters a whole\n * stdout/stderr blob through one extracted signature line, because feeding\n * Drain a stack trace line-by-line makes recursion depth — not failure shape —\n * the thing it clusters on.\n *\n * Every rule here is a pure function of the single line plus the\n * `tool_use_id -> tool name` map carried forward from earlier lines. That map\n * is the only cross-line state, and the transcript reader persists it with the\n * byte watermark, so resuming mid-transcript sees exactly what a full pass\n * would.\n */\n\ntype Json = Record<string, unknown>;\n\nexport interface ExtractedBlob {\n /** Drain-tree partition, via `toolTypeFor` on the originating tool name. */\n toolType: string;\n /** stdout+stderr, or the error text — never the surrounding JSON. */\n rawText: string;\n sessionId: string;\n timestamp: string;\n /**\n * Whether this blob is worth clustering (AW-93). A tool result flagged\n * `is_error` always is — the flag *is* the failure signal. Successful command\n * output only is when it carries a recognizable failure shape of its own; see\n * `hasErrorSignal`. Ineligible candidates are still reported, so narrowing is\n * a measured number in the eval scorecard rather than a silent drop.\n */\n eligible: boolean;\n}\n\nfunction asObject(value: unknown): Json | null {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Json)\n : null;\n}\n\nfunction str(source: Json | null, key: string): string | null {\n const value = source?.[key];\n return typeof value === 'string' && value.length > 0 ? value : null;\n}\n\nfunction blocks(line: Json): Json[] {\n const content = asObject(line.message)?.content;\n if (!Array.isArray(content)) return [];\n return content.map(asObject).filter((b): b is Json => b !== null);\n}\n\n/** A `tool_result` block's content is either a bare string or text blocks. */\nexport function toolResultText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return content\n .map((block) => str(asObject(block), 'text') ?? '')\n .filter(Boolean)\n .join('\\n');\n}\n\n/**\n * The `tool_use_id -> tool name` pairs this line declares. Recorded from\n * assistant lines so the *following* user line's `tool_result` can be routed\n * to the right Drain partition — the result block itself only carries the id.\n */\nexport function collectToolUses(line: Json): [string, string][] {\n const pairs: [string, string][] = [];\n for (const block of blocks(line)) {\n if (block.type !== 'tool_use') continue;\n const id = str(block, 'id');\n const name = str(block, 'name');\n if (id && name) pairs.push([id, name]);\n }\n return pairs;\n}\n\n/**\n * Bash-shaped results carry their output on the line's `toolUseResult`, not\n * inside the `tool_result` block (whose content is a rendered summary). Empty\n * output is not a blob: there is no shape to cluster.\n */\nfunction commandOutput(line: Json): string | null {\n const result = asObject(line.toolUseResult);\n if (!result) return null;\n const stdout = typeof result.stdout === 'string' ? result.stdout : '';\n const stderr = typeof result.stderr === 'string' ? result.stderr : '';\n const text = [stdout, stderr].filter((part) => part.trim().length > 0).join('\\n');\n return text.length > 0 ? text : null;\n}\n\n/**\n * Every candidate blob on one line: each `is_error` tool result, plus the\n * stdout+stderr of a successful command result. Each carries an `eligible`\n * flag; the caller decides what to do with the ineligible ones.\n *\n * A line yields at most one blob per `tool_result` block, and Claude Code\n * emits one result block per user line in practice; the loop is written for\n * the general case anyway so a batched line cannot silently drop blobs.\n */\nexport function extractBlobs(line: Json, toolNames: Map<string, string>): ExtractedBlob[] {\n const sessionId = str(line, 'sessionId');\n if (!sessionId) return [];\n const timestamp = str(line, 'timestamp');\n if (!timestamp) return [];\n\n const found: ExtractedBlob[] = [];\n for (const block of blocks(line)) {\n if (block.type !== 'tool_result') continue;\n const id = str(block, 'tool_use_id');\n const toolName = id ? toolNames.get(id) : undefined;\n if (id) toolNames.delete(id);\n\n const isError = block.is_error === true;\n const rawText = isError ? toolResultText(block.content) : commandOutput(line);\n if (!rawText || rawText.trim().length === 0) continue;\n\n const toolType = toolTypeFor(toolName ?? '');\n found.push({\n toolType,\n rawText,\n sessionId,\n timestamp,\n eligible: isError || hasErrorSignal(toolType, rawText),\n });\n }\n return found;\n}\n","/**\n * Which Drain partition a Claude Code tool result belongs to.\n *\n * `@titan-design/cluster` partitions by an opaque key and has no opinion about\n * what a partition means; this is active-work's mapping from a `tool_use` name\n * to one. Route before Drain sees a line, so a `tsc` failure and a `vitest`\n * failure never end up in the same cluster just because their token shapes\n * happen to overlap.\n */\n\nexport type ToolType = 'Bash' | 'Read' | 'Edit' | 'generic';\n\nconst KNOWN_TOOL_TYPES: Record<string, ToolType> = {\n Bash: 'Bash',\n Read: 'Read',\n Edit: 'Edit',\n MultiEdit: 'Edit',\n};\n\n/** Map a Claude Code tool_use name to its Drain-tree partition. */\nexport function toolTypeFor(toolName: string): ToolType {\n return KNOWN_TOOL_TYPES[toolName] ?? 'generic';\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { atomicWrite } from '../utils/fs-atomic.js';\nimport { getMinerRoot } from '../utils/paths.js';\n\n/**\n * The Drain transcript reader's resume state: `<minerRoot>/reader-state.json`.\n *\n * Two jobs, both forced by the `Locator` contract in\n * `src/schemas/template.ts` — `[transcriptIndex, byteOffset, byteLength]`:\n *\n * 1. It *is* the transcript table. `transcripts[i]` defines what\n * `transcriptIndex === i` means, so entries are only ever appended and\n * never reordered; a stored locator would otherwise start pointing at a\n * different file every time the corpus grew.\n * 2. It carries the per-transcript byte watermark, so a second pass reads\n * only the bytes appended since the first.\n *\n * `occurrences.jsonl` is NOT usable as the resume point even though it holds\n * locators: it records only the blobs that clustered, so the highest offset in\n * it is the last *eligible* line, not the last line read — resuming there\n * would re-scan (and re-count) every line after it. This mirrors\n * `session-index/watermark.ts`'s byte-watermark-per-transcript design, minus\n * SQLite, since this store is plain files.\n */\n\nconst TranscriptStateSchema = z.object({\n /** `~`-relative path, matching `session-index/discover.ts`'s display form. */\n path: z.string().min(1),\n lastByteOffset: z.number().int().nonnegative().default(0),\n /** sha256 of bytes `[0, lastByteOffset)`; detects rewrite vs. append. */\n prefixHash: z.string().nullable().default(null),\n /**\n * `tool_use_id -> tool name` pairs seen but not yet consumed by a result.\n * Persisted because a chunk boundary routinely falls between an assistant's\n * `tool_use` and the user line carrying its result.\n */\n pendingToolNames: z.record(z.string(), z.string()).default({}),\n});\n\nexport const ReaderStateSchema = z.object({\n version: z.literal(1).default(1),\n transcripts: z.array(TranscriptStateSchema).default([]),\n});\n\nexport type TranscriptState = z.infer<typeof TranscriptStateSchema>;\nexport type ReaderState = z.infer<typeof ReaderStateSchema>;\n\n/**\n * Cap on carried-forward `tool_use` ids per transcript. A tool call whose\n * result never arrives (interrupt, crash, compaction) would otherwise leak an\n * entry forever; the newest ids are the ones a result can still reference.\n */\nexport const MAX_PENDING_TOOL_NAMES = 256;\n\nexport function readerStatePath(root: string = getMinerRoot()): string {\n return path.join(root, 'reader-state.json');\n}\n\nexport async function loadReaderState(root: string = getMinerRoot()): Promise<ReaderState> {\n try {\n const raw = await fs.readFile(readerStatePath(root), 'utf8');\n return ReaderStateSchema.parse(JSON.parse(raw));\n } catch (err) {\n if (err instanceof Error && 'code' in err && err.code === 'ENOENT') {\n return { version: 1, transcripts: [] };\n }\n throw err;\n }\n}\n\nexport async function saveReaderState(\n state: ReaderState,\n root: string = getMinerRoot(),\n): Promise<void> {\n await fs.mkdir(root, { recursive: true });\n await atomicWrite(\n readerStatePath(root),\n `${JSON.stringify(ReaderStateSchema.parse(state), null, 2)}\\n`,\n );\n}\n\n/** Drop all but the newest `MAX_PENDING_TOOL_NAMES` insertions. */\nexport function trimPendingToolNames(names: Map<string, string>): Record<string, string> {\n const entries = [...names.entries()];\n return Object.fromEntries(entries.slice(-MAX_PENDING_TOOL_NAMES));\n}\n\n/**\n * Index of `displayPath` in the transcript table, appending it on first sight.\n * The returned index is the `transcriptIndex` every locator from this file\n * carries, so it must stay stable for the life of the store.\n */\nexport function transcriptIndexFor(state: ReaderState, displayPath: string): number {\n const existing = state.transcripts.findIndex((t) => t.path === displayPath);\n if (existing !== -1) return existing;\n state.transcripts.push({\n path: displayPath,\n lastByteOffset: 0,\n prefixHash: null,\n pendingToolNames: {},\n });\n return state.transcripts.length - 1;\n}\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { runRefresh, withRefreshLock } from '../session-index/refresh.js';\n\n/**\n * `active-work miner refresh` — bring the session-signal index up to date with\n * `~/.claude/projects`.\n *\n * Shares one code path with the daemon's watcher and\n * `tools/build-session-index.mjs`. The refresh lock is cross-process and this\n * command *blocks* on it: if the daemon is mid-pass, the user's refresh waits\n * and then runs, rather than failing or silently doing nothing. That is why\n * there is no HTTP endpoint here — the lock already serializes the two.\n */\n\nconst ArgsSchema = z.object({\n full: z.boolean().optional(),\n limit: z.coerce.number().int().positive().optional(),\n verify_hashes: z.boolean().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n startedAt: z.string(),\n durationMs: z.number(),\n transcripts: z.number(),\n scanned: z.number(),\n indexed: z.number(),\n rewound: z.number(),\n unchanged: z.number(),\n quarantined: z.number(),\n missing: z.number(),\n reconciledMissing: z.number(),\n factsAdded: z.number(),\n turnsRolledUp: z.number(),\n tasksRequested: z.number(),\n tasksApplied: z.number(),\n errors: z.array(z.string()),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'miner.refresh',\n description: 'Index new Claude session transcripts into the session-signal index.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n full: {\n long: '--full',\n description: 'Drop every derived row and re-read all transcripts from byte 0.',\n },\n limit: {\n long: '--limit',\n description: 'Visit at most N transcripts.',\n },\n verify_hashes: {\n long: '--verify-hashes',\n description: 'Re-hash every transcript to detect source drift (slow; implied by --full).',\n },\n },\n },\n async run(args) {\n return withRefreshLock(() =>\n runRefresh({ full: args.full, limit: args.limit, verifyHashes: args.verify_hashes }),\n );\n },\n});\n","import { existsSync } from 'node:fs';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { NotFoundError } from '../errors.js';\nimport { defaultGraphPath, openGraphReadOnly } from '../session-index/graph.js';\nimport { runLiveness } from '../session-index/liveness.js';\nimport { color } from '../utils/color.js';\n\n/**\n * `active-work miner liveness` — which declared structures does nothing write?\n *\n * The complement to `miner status`, which answers \"how much is in the index\".\n * This answers \"how much of what the schema promises is real\". Every AW-26\n * finding was a structure the design declared and no writer reached; the point\n * of a command is that the next one gets found on purpose.\n *\n * Advisory by construction: an empty column is a question, not a failure. Some\n * are legitimately awaiting a feature. The report says which, and a human\n * decides whether that is unfinished work or a thing to delete.\n */\n\nconst ArgsSchema = z.object({});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n emptyColumns: z.array(\n z.object({ table: z.string(), column: z.string(), rows: z.number(), nonNull: z.number() }),\n ),\n unusedRelations: z.array(z.string()),\n undeclaredRelations: z.array(z.string()),\n danglingNamespaces: z.array(\n z.object({ namespace: z.string(), edges: z.number(), dangling: z.number() }),\n ),\n unmappedNamespaces: z.array(z.string()),\n expectedEmptyColumns: z.array(\n z.object({ table: z.string(), column: z.string(), reason: z.string() }),\n ),\n staleTranscripts: z.number(),\n transcripts: z.number(),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nfunction report(result: Result): string {\n const lines: string[] = [color.bold('active-work miner liveness')];\n const bullet = (text: string): void => void lines.push(` ${text}`);\n\n lines.push('');\n lines.push(color.bold(' Columns nothing ever writes'));\n if (result.emptyColumns.length === 0) bullet(color.green('none — every column has a writer'));\n for (const column of result.emptyColumns) {\n bullet(`${color.yellow('EMPTY')} ${column.table}.${column.column} (0 of ${column.rows} rows)`);\n }\n\n if (result.expectedEmptyColumns.length > 0) {\n lines.push('');\n lines.push(color.bold(' Empty on purpose'));\n for (const column of result.expectedEmptyColumns) {\n bullet(color.dim(`${column.table}.${column.column} — ${column.reason}`));\n }\n }\n\n lines.push('');\n lines.push(color.bold(' Edge relations'));\n if (result.unusedRelations.length === 0 && result.undeclaredRelations.length === 0) {\n bullet(color.green('declared vocabulary matches what is written'));\n }\n for (const relation of result.unusedRelations) {\n bullet(`${color.yellow('UNUSED')} ${relation} — declared in RELATIONS, never written`);\n }\n for (const relation of result.undeclaredRelations) {\n bullet(`${color.red('UNDECLARED')} ${relation} — written, missing from RELATIONS`);\n }\n\n lines.push('');\n lines.push(color.bold(' Edge endpoints that resolve to nothing'));\n if (result.danglingNamespaces.length === 0) bullet(color.green('every endpoint resolves'));\n for (const namespace of result.danglingNamespaces) {\n bullet(\n `${color.yellow('DANGLING')} ${namespace.namespace}: ${namespace.dangling} of ${namespace.edges} endpoints`,\n );\n }\n for (const namespace of result.unmappedNamespaces) {\n bullet(`${color.yellow('UNMAPPED')} ${namespace}: — no entity table declared for this ref`);\n }\n\n if (result.staleTranscripts > 0) {\n lines.push('');\n lines.push(color.bold(' Transcripts'));\n bullet(\n `${color.yellow('STALE')} ${result.staleTranscripts} of ${result.transcripts} marked ok, but the file is gone`,\n );\n }\n return lines.join('\\n') + '\\n';\n}\n\nexport default defineCommand<Args, Result>({\n name: 'miner.liveness',\n description:\n 'Report which declared index structures nothing ever populates: empty columns, unused edge relations, dangling refs, stale transcripts.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: { usage: 'active-work miner liveness' },\n async run(_args, ctx) {\n const dbPath = defaultGraphPath();\n // An empty report would read as \"everything is healthy\", which is a\n // different claim from \"there is nothing to report on\".\n if (!existsSync(dbPath)) {\n throw new NotFoundError(`no session index at ${dbPath} — run \\`active-work miner refresh\\``);\n }\n const db = openGraphReadOnly(dbPath);\n try {\n const liveness = runLiveness(db);\n const result: Result = {\n emptyColumns: liveness.emptyColumns,\n expectedEmptyColumns: liveness.expectedEmptyColumns.map((column) => ({\n table: column.table,\n column: column.column,\n reason: column.reason,\n })),\n unusedRelations: liveness.relations\n .filter((relation) => relation.declared && relation.count === 0)\n .map((relation) => relation.relation),\n undeclaredRelations: liveness.relations\n .filter((relation) => !relation.declared)\n .map((relation) => relation.relation),\n danglingNamespaces: liveness.refNamespaces\n .filter((namespace) => (namespace.dangling ?? 0) > 0)\n .map((namespace) => ({\n namespace: namespace.namespace,\n edges: namespace.edges,\n dangling: namespace.dangling ?? 0,\n })),\n unmappedNamespaces: liveness.refNamespaces\n .filter((namespace) => namespace.dangling === null)\n .map((namespace) => namespace.namespace),\n staleTranscripts: liveness.staleTranscripts,\n transcripts: liveness.transcripts,\n };\n if (ctx.format !== 'json') process.stderr.write(report(result));\n return result;\n } finally {\n db.close();\n }\n },\n});\n","import { existsSync } from 'node:fs';\nimport type Database from 'better-sqlite3';\nimport { RELATIONS, toAbsolutePath } from '@titan-design/session-read';\n\n/**\n * \"Which declared structures does nothing ever populate?\"\n *\n * Every gap AW-26 turned up was an instance of one shape: a column, an enum\n * value, a relation or a directory level that the design declared and no\n * writer ever reached. Those stayed invisible for months because nothing\n * asked the question — and when someone finally noticed an empty column, the\n * natural reading was \"bad idea, delete it\" rather than \"unfinished, wire it\n * up\". Twice that reading was wrong.\n *\n * So this answers the question mechanically, and derives what to check from\n * the schema itself (`PRAGMA table_info`) and from the relation vocabulary\n * `@titan-design/session-read` declares. A hand-maintained checklist would rot\n * exactly the way the thing it is checking rotted — which is also why this\n * stayed in active-work when the graph moved into a package: it must read\n * whatever the schema currently is, including tables a later package version\n * adds without telling anyone.\n *\n * Read-only and cheap: one table scan per table, no transcript is opened.\n */\n\ntype Db = Database.Database;\n\nexport interface ColumnLiveness {\n table: string;\n column: string;\n rows: number;\n nonNull: number;\n}\n\nexport interface RelationLiveness {\n relation: string;\n count: number;\n /** False for a relation observed in the data but absent from `RELATIONS`. */\n declared: boolean;\n}\n\nexport interface RefNamespaceLiveness {\n /** The `<prefix>:` of an edge endpoint, e.g. `session`. */\n namespace: string;\n edges: number;\n /** Endpoints with no matching row in the entity table, or null if unmapped. */\n dangling: number | null;\n}\n\nexport interface LivenessReport {\n /** Columns nothing writes and nothing explains — the headline finding. */\n emptyColumns: ColumnLiveness[];\n /** Empty, but declared so in `EXPECTED_EMPTY`; reported, not flagged. */\n expectedEmptyColumns: (ColumnLiveness & { reason: string })[];\n columns: ColumnLiveness[];\n relations: RelationLiveness[];\n refNamespaces: RefNamespaceLiveness[];\n /** Transcripts recorded `ok` whose file is gone; `status` never says so. */\n staleTranscripts: number;\n transcripts: number;\n}\n\n/** Bookkeeping tables that have no product meaning, and the contentless FTS index. */\nconst SKIP_TABLES = /^(sqlite_|_migration$|search_fts)/;\n\n/**\n * Structures that are empty *on purpose*, with the reason.\n *\n * This is the difference between a diagnostic people act on and one they learn\n * to ignore. Some columns are legitimately never written, and reporting them\n * next to genuine unfinished work trains the reader to skim past both. An entry\n * here is a claim that emptiness is correct — so it carries its justification,\n * and `miner liveness` still prints it, just under a heading that says so.\n */\nexport const EXPECTED_EMPTY: Record<string, string> = {\n 'edge.t_invalid':\n 'NULL means current; the index is rebuilt from scratch, so no edge is ever superseded in place',\n 'edge.t_expired':\n 'NULL means current — idx_edge_current is defined WHERE t_expired IS NULL, so all-NULL is the designed steady state',\n 'edge.attrs': 'kit column; the session graph writes no per-edge attributes',\n};\n\n/**\n * Where an edge endpoint's `<prefix>:` resolves. Deliberately explicit and\n * colocated with nothing else: an unmapped namespace is *reported* rather\n * than skipped, so adding a ref type without extending this shows up as a\n * finding instead of silently passing.\n */\nconst REF_TABLES: Record<string, { table: string; column: string; bare?: boolean }> = {\n // `session` is the odd one out: it stores the bare id, every other entity\n // table stores the prefixed ref. Comparing without allowing for that reports\n // every session endpoint as dangling — a false alarm, which in a diagnostic\n // is worse than no check at all.\n session: { table: 'session', column: 'session_id', bare: true },\n agent: { table: 'subagent', column: 'agent_ref' },\n file: { table: 'file', column: 'file_ref' },\n branch: { table: 'branch', column: 'branch_ref' },\n task: { table: 'task', column: 'task_ref' },\n artifact: { table: 'artifact', column: 'artifact_ref' },\n // `pr` is keyed by `pr_ref` like every other entity table. It was left\n // unmapped on the belief that it was keyed by `(number, repo)` — that is\n // `pr_merge_observation`, a different table (AW-107).\n pr: { table: 'pr', column: 'pr_ref' },\n};\n\nfunction tableNames(db: Db): string[] {\n const rows = db\n .prepare(\"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name\")\n .all() as { name: string }[];\n return rows.map((row) => row.name).filter((name) => !SKIP_TABLES.test(name));\n}\n\nfunction columnNames(db: Db, table: string): string[] {\n const rows = db.prepare(`PRAGMA table_info(\"${table}\")`).all() as { name: string }[];\n return rows.map((row) => row.name);\n}\n\n/**\n * One scan per table, not one per column: `COUNT(col)` skips NULLs, so every\n * column's population is answered by a single aggregate row. On a 280k-row\n * `fact` table the difference is seconds versus a minute.\n */\nfunction scanTable(db: Db, table: string): ColumnLiveness[] {\n const columns = columnNames(db, table);\n if (columns.length === 0) return [];\n const selects = columns.map((column, index) => `COUNT(\"${column}\") AS c${index}`).join(', ');\n const row = db.prepare(`SELECT COUNT(*) AS total, ${selects} FROM \"${table}\"`).get() as Record<\n string,\n number\n >;\n return columns.map((column, index) => ({\n table,\n column,\n rows: row.total,\n nonNull: row[`c${index}`] ?? 0,\n }));\n}\n\nfunction relationLiveness(db: Db): RelationLiveness[] {\n const observed = new Map(\n (\n db.prepare('SELECT relation, COUNT(*) AS n FROM edge GROUP BY relation').all() as {\n relation: string;\n n: number;\n }[]\n ).map((row) => [row.relation, row.n]),\n );\n const declared = Object.values(RELATIONS) as string[];\n const report: RelationLiveness[] = declared.map((relation) => ({\n relation,\n count: observed.get(relation) ?? 0,\n declared: true,\n }));\n for (const [relation, count] of observed) {\n if (!declared.includes(relation)) report.push({ relation, count, declared: false });\n }\n return report.sort((a, b) => a.relation.localeCompare(b.relation));\n}\n\nfunction refNamespaces(db: Db): RefNamespaceLiveness[] {\n const rows = db\n .prepare(\n `SELECT namespace, COUNT(*) AS n FROM (\n SELECT substr(source_ref, 1, instr(source_ref, ':') - 1) AS namespace FROM edge\n UNION ALL\n SELECT substr(target_ref, 1, instr(target_ref, ':') - 1) FROM edge\n ) WHERE namespace <> '' GROUP BY namespace ORDER BY namespace`,\n )\n .all() as { namespace: string; n: number }[];\n\n return rows.map(({ namespace, n }) => {\n const target = REF_TABLES[namespace];\n if (!target) return { namespace, edges: n, dangling: null };\n const lhs = target.bare ? `substr(e.ref, ${namespace.length + 2})` : 'e.ref';\n const { c } = db\n .prepare(\n `SELECT COUNT(*) AS c FROM (\n SELECT source_ref AS ref FROM edge UNION ALL SELECT target_ref FROM edge\n ) e\n WHERE e.ref LIKE @prefix\n AND NOT EXISTS (SELECT 1 FROM \"${target.table}\" t WHERE t.\"${target.column}\" = ${lhs})`,\n )\n .get({ prefix: `${namespace}:%` }) as { c: number };\n return { namespace, edges: n, dangling: c };\n });\n}\n\n/**\n * Rows still claiming `ok` whose file is gone. `refreshCorpus` marks these at\n * the end of every pass, so a healthy index reports 0 here and a non-zero count\n * means the index is stale rather than that the status is unreachable — which\n * is what it meant when this check was written, and why it was written.\n */\nfunction staleTranscripts(db: Db): number {\n const rows = db.prepare(\"SELECT source_key FROM transcript WHERE status = 'ok'\").all() as {\n source_key: string;\n }[];\n return rows.filter((row) => !existsSync(toAbsolutePath(row.source_key))).length;\n}\n\nexport function runLiveness(db: Db): LivenessReport {\n const columns = tableNames(db).flatMap((table) => scanTable(db, table));\n // A column in an empty table says nothing, so those are not findings.\n const empty = columns.filter((column) => column.nonNull === 0 && column.rows > 0);\n const reasonFor = (column: ColumnLiveness): string | undefined =>\n EXPECTED_EMPTY[`${column.table}.${column.column}`];\n return {\n emptyColumns: empty.filter((column) => reasonFor(column) === undefined),\n expectedEmptyColumns: empty\n .filter((column) => reasonFor(column) !== undefined)\n .map((column) => ({ ...column, reason: reasonFor(column) as string })),\n columns,\n relations: relationLiveness(db),\n refNamespaces: refNamespaces(db),\n staleTranscripts: staleTranscripts(db),\n transcripts: (db.prepare('SELECT COUNT(*) AS n FROM transcript').get() as { n: number }).n,\n };\n}\n","import { existsSync, statSync } from 'node:fs';\nimport type Database from 'better-sqlite3';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { defaultGraphPath, openGraphReadOnly, SCHEMA_VERSION } from '../session-index/graph.js';\nimport { probeHealth, resolveDaemonPort } from '../server/lifecycle.js';\n\n/**\n * `active-work miner status` — a read-only picture of the session-signal\n * index.\n *\n * Everything here is answered from SQLite plus one optional `/health` probe:\n * no transcript is opened, so this stays instant on a multi-gigabyte corpus.\n * `behindBytes` is the honest \"how stale am I\" number — the bytes on disk past\n * each transcript's watermark, summed.\n */\n\nconst ArgsSchema = z.object({});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n dbPath: z.string(),\n schemaVersion: z.number(),\n sizeBytes: z.number(),\n counts: z.object({\n transcripts: z.number(),\n sessions: z.number(),\n facts: z.number(),\n turns: z.number(),\n edges: z.number(),\n spans: z.number(),\n }),\n transcripts: z.object({\n ok: z.number(),\n quarantined: z.number(),\n missing: z.number(),\n }),\n watermark: z.object({\n lastIndexedAt: z.string().nullable(),\n behindBytes: z.number(),\n }),\n fts: z.object({\n rows: z.number(),\n orphanRows: z.number(),\n needsFullRebuild: z.boolean(),\n }),\n daemon: z\n .object({\n indexing: z.boolean(),\n pending: z.boolean(),\n lastRunAt: z.string().nullable(),\n lastDurationMs: z.number().nullable(),\n consecutiveErrors: z.number(),\n })\n .nullable(),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\n/**\n * Purges and resets strand rows in the contentless `search_fts` (it cannot\n * delete a row without its original text). They are invisible to any query\n * that joins `search_span`, so this is a housekeeping signal, not a\n * correctness one — past this ratio the wasted index space is worth a\n * `refresh --full`.\n */\nconst ORPHAN_WARN_RATIO = 0.2;\n\nconst scalar = (db: Database.Database, sql: string): number =>\n (db.prepare<[], { n: number }>(sql).get() as { n: number } | undefined)?.n ?? 0;\n\nfunction sizeOf(dbPath: string): number {\n try {\n return statSync(dbPath).size;\n } catch {\n return 0;\n }\n}\n\nfunction ftsState(db: Database.Database): Result['fts'] {\n const rows = scalar(db, 'SELECT COUNT(*) AS n FROM search_fts');\n const orphanRows = scalar(\n db,\n `SELECT COUNT(*) AS n FROM search_fts f\n LEFT JOIN search_span s ON s.span_id = f.rowid\n WHERE s.span_id IS NULL`,\n );\n return { rows, orphanRows, needsFullRebuild: rows > 0 && orphanRows / rows > ORPHAN_WARN_RATIO };\n}\n\nasync function daemonState(): Promise<Result['daemon']> {\n const health = await probeHealth(resolveDaemonPort());\n return health?.index ?? null;\n}\n\n/**\n * \"Nothing indexed yet\" is a state, not a failure. A read-only open of a file\n * that does not exist throws `unable to open database file`, which is what a\n * user sees on a machine that has never run a refresh — including every machine\n * for the first pass after the graph moved to its own path.\n */\nasync function emptyStatus(dbPath: string): Promise<Result> {\n return {\n dbPath,\n schemaVersion: SCHEMA_VERSION,\n sizeBytes: 0,\n counts: { transcripts: 0, sessions: 0, facts: 0, turns: 0, edges: 0, spans: 0 },\n transcripts: { ok: 0, quarantined: 0, missing: 0 },\n watermark: { lastIndexedAt: null, behindBytes: 0 },\n fts: { rows: 0, orphanRows: 0, needsFullRebuild: false },\n daemon: await daemonState(),\n };\n}\n\nexport default defineCommand<Args, Result>({\n name: 'miner.status',\n description: 'Report session-signal index size, freshness, and daemon indexing state.',\n args: ArgsSchema,\n result: ResultSchema,\n async run() {\n const dbPath = defaultGraphPath();\n if (!existsSync(dbPath)) return emptyStatus(dbPath);\n const db = openGraphReadOnly(dbPath);\n try {\n const statusCount = (status: string): number =>\n (\n db\n .prepare<\n [string],\n { n: number }\n >('SELECT COUNT(*) AS n FROM transcript WHERE status = ?')\n .get(status) as { n: number }\n ).n;\n return {\n dbPath,\n schemaVersion: SCHEMA_VERSION,\n sizeBytes: sizeOf(dbPath),\n counts: {\n transcripts: scalar(db, 'SELECT COUNT(*) AS n FROM transcript'),\n sessions: scalar(db, 'SELECT COUNT(*) AS n FROM session'),\n facts: scalar(db, 'SELECT COUNT(*) AS n FROM fact'),\n turns: scalar(db, 'SELECT COUNT(*) AS n FROM turn'),\n edges: scalar(db, 'SELECT COUNT(*) AS n FROM edge'),\n spans: scalar(db, 'SELECT COUNT(*) AS n FROM search_span'),\n },\n transcripts: {\n ok: statusCount('ok'),\n quarantined: statusCount('quarantined'),\n missing: statusCount('missing'),\n },\n watermark: {\n lastIndexedAt:\n db\n .prepare<\n [],\n { at: string | null }\n >('SELECT MAX(last_indexed_at) AS at FROM transcript')\n .get()?.at ?? null,\n behindBytes: scalar(\n db,\n `SELECT COALESCE(SUM(MAX(file_size - last_offset, 0)), 0) AS n\n FROM transcript WHERE file_size IS NOT NULL`,\n ),\n },\n fts: ftsState(db),\n daemon: await daemonState(),\n };\n } finally {\n db.close();\n }\n },\n});\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { getActiveRoot } from '../utils/paths.js';\nimport { readStdinJson } from '../utils/read-stdin-json.js';\nimport { peekSpawnContext, stashSpawnContext } from '../utils/agent-chat-hook-state.js';\nimport { nowIso } from '../utils/today.js';\nimport { resolveSlugFromCwd } from './_open-helpers.js';\n\n/**\n * `active-work hooks agent-chat-spawn` (AW-99) — the `on_spawn` consumer\n * registered into agent-chat's generic lifecycle hooks (CC-71).\n *\n * Reads the on_spawn JSON payload from stdin\n * (`{agentId, name, session_id, cwd, parent, profile, briefing}`), resolves\n * which active-work initiative owns `cwd` via the same `resolveSlugFromCwd`\n * `open` uses, and stashes the spawn context so the matching\n * `hooks agent-chat-complete` call can record it. A cwd that resolves to no\n * initiative is a silent no-op — most agent-chat spawns are not spawned into\n * an active-work-tracked worktree, and that is not an error condition.\n *\n * Args intentionally empty: agent-chat pipes the payload as JSON on stdin,\n * not as CLI flags, so this command has no positionals/options of its own.\n */\nconst ArgsSchema = z.object({});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n matched: z.boolean(),\n slug: z.string().nullable(),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nfunction str(source: Record<string, unknown> | null, key: string): string | null {\n const value = source?.[key];\n return typeof value === 'string' && value.length > 0 ? value : null;\n}\n\n/** The on_spawn payload handler, separated from stdin-reading so it's unit-testable directly. */\nexport async function handleOnSpawn(\n payload: Record<string, unknown> | null,\n activeRoot: string,\n): Promise<Result> {\n const agentId = str(payload, 'agentId');\n const cwd = str(payload, 'cwd');\n const sessionId = str(payload, 'session_id');\n if (!agentId || !cwd || !sessionId) return { matched: false, slug: null };\n\n const match = await resolveSlugFromCwd(activeRoot, cwd);\n if (!match) return { matched: false, slug: null };\n\n const parentAgentId = str(payload, 'parent');\n const parent = parentAgentId ? await peekSpawnContext(parentAgentId) : null;\n\n await stashSpawnContext(agentId, {\n slug: match.slug,\n sessionId,\n name: str(payload, 'name') ?? agentId,\n started: nowIso(),\n parentSessionId: parent?.sessionId ?? null,\n profile: str(payload, 'profile'),\n briefing: str(payload, 'briefing'),\n });\n return { matched: true, slug: match.slug };\n}\n\nexport default defineCommand<Args, Result>({\n name: 'hooks.agent-chat-spawn',\n description:\n \"agent-chat on_spawn hook consumer (AW-99): stash a spawned peer's context, keyed by agentId, for the matching on_complete call.\",\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n usage: 'active-work hooks agent-chat-spawn (reads the on_spawn JSON payload from stdin)',\n },\n async run() {\n const payload = await readStdinJson();\n return handleOnSpawn(payload, getActiveRoot());\n },\n});\n","/**\n * AW-99: agent-chat's hooks (CC-71) pipe their event payload as JSON on\n * stdin. Injectable so tests can supply a payload without a real pipe.\n */\nexport async function readStdinJson(\n stream: NodeJS.ReadableStream = process.stdin,\n): Promise<Record<string, unknown> | null> {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n const raw = Buffer.concat(chunks).toString('utf8').trim();\n if (raw.length === 0) return null;\n try {\n const parsed: unknown = JSON.parse(raw);\n return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { atomicWrite } from './fs-atomic.js';\nimport { getStateRoot } from './paths.js';\n\n/**\n * AW-99: on_spawn (CC-71) knows the spawn context but not yet how the peer\n * exits; on_complete knows the exit but nothing else. This is the bridge\n * between them — one small JSON file per live agent, deleted on read.\n * Ephemeral by design: a peer that never completes (or whose on_spawn never\n * matched an initiative) just leaves an orphaned file here, not a growing\n * durable record.\n */\nconst SpawnContextSchema = z.object({\n slug: z.string().min(1),\n sessionId: z.string().min(1),\n name: z.string(),\n started: z.string(),\n /**\n * The spawning session, already resolved from the payload's `parent`\n * agentId to a session id. Resolved at spawn time on purpose: `parent` names\n * an agent, and the only thing that can map an agent to its session is\n * another live entry in this same directory — which is gone by the time\n * on_complete runs, because reading one deletes it.\n */\n parentSessionId: z.string().min(1).nullable().default(null),\n /** agent-chat profile and briefing slug, for the recorded session's prose. */\n profile: z.string().nullable().default(null),\n briefing: z.string().nullable().default(null),\n});\n\nexport type SpawnContext = z.infer<typeof SpawnContextSchema>;\n\nfunction stateDir(): string {\n return path.join(getStateRoot(), 'agent-chat-hooks');\n}\n\nfunction stateFile(agentId: string): string {\n return path.join(stateDir(), `${agentId}.json`);\n}\n\nexport async function stashSpawnContext(agentId: string, context: SpawnContext): Promise<void> {\n await fs.mkdir(stateDir(), { recursive: true });\n await atomicWrite(stateFile(agentId), JSON.stringify(context));\n}\n\nasync function readSpawnContext(agentId: string): Promise<SpawnContext | null> {\n let raw: string;\n try {\n raw = await fs.readFile(stateFile(agentId), 'utf8');\n } catch {\n return null;\n }\n const parsed = SpawnContextSchema.safeParse(JSON.parse(raw));\n return parsed.success ? parsed.data : null;\n}\n\n/** Reads and deletes the stashed context, or null if none was ever stashed. */\nexport async function takeSpawnContext(agentId: string): Promise<SpawnContext | null> {\n const context = await readSpawnContext(agentId);\n await fs.rm(stateFile(agentId), { force: true });\n return context;\n}\n\n/**\n * Reads without deleting — for resolving a *parent* agent, which is still\n * running and whose own on_complete has yet to claim its entry. A parent that\n * is not an agent-chat agent at all (the common case: a human-started session\n * spawning its first peer) simply has no entry, and that is not an error.\n */\nexport async function peekSpawnContext(agentId: string): Promise<SpawnContext | null> {\n return readSpawnContext(agentId);\n}\n","import { spawn } from 'node:child_process';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { readStdinJson } from '../utils/read-stdin-json.js';\nimport { takeSpawnContext, type SpawnContext } from '../utils/agent-chat-hook-state.js';\nimport { nowIso } from '../utils/today.js';\n\n/**\n * `active-work hooks agent-chat-complete` (AW-99) — the `on_complete`\n * consumer registered into agent-chat's generic lifecycle hooks (CC-71).\n *\n * Reads the on_complete JSON payload from stdin\n * (`{agentId, code, signal, inferred}`), looks up the context stashed by the\n * matching `hooks agent-chat-spawn` call, and — when one exists — records the\n * peer as a `track: adhoc` session via the real `wrap` command, exactly as a\n * human-run `active-work wrap --track adhoc` would. No new schema or storage:\n * bootstrap's existing \"Parallel sessions since then\" section picks this up\n * automatically. An agentId with no stashed context (its spawn never matched\n * an initiative, or on_spawn never fired) is a silent no-op.\n */\nconst ArgsSchema = z.object({});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n recorded: z.boolean(),\n slug: z.string().nullable(),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nfunction str(source: Record<string, unknown> | null, key: string): string | null {\n const value = source?.[key];\n return typeof value === 'string' ? value : null;\n}\n\n/** Injectable so tests never spawn a real `active-work wrap` subprocess. */\nexport type WrapRunner = (args: string[]) => Promise<{ code: number | null; stderr: string }>;\n\nconst defaultWrapRunner: WrapRunner = (args) =>\n new Promise((resolve, reject) => {\n const child = spawn('active-work', args, { stdio: ['ignore', 'ignore', 'pipe'] });\n const stderrChunks: Buffer[] = [];\n child.stderr?.on('data', (chunk: Buffer) => stderrChunks.push(chunk));\n child.on('error', reject);\n child.on('close', (code) =>\n resolve({ code, stderr: Buffer.concat(stderrChunks).toString('utf8') }),\n );\n });\n\nlet wrapRunner: WrapRunner = defaultWrapRunner;\nexport function setWrapRunner(next: WrapRunner): void {\n wrapRunner = next;\n}\nexport function resetWrapRunner(): void {\n wrapRunner = defaultWrapRunner;\n}\n\nfunction descriptor(context: SpawnContext): string {\n const parts = [\n context.profile ? `profile ${context.profile}` : null,\n context.briefing ? `briefed on ${context.briefing}` : null,\n ].filter((part): part is string => part !== null);\n return parts.length > 0 ? ` (${parts.join(', ')})` : '';\n}\n\nfunction summaryLine(payload: Record<string, unknown> | null, context: SpawnContext): string {\n const who = `Peer \"${context.name}\"${descriptor(context)} (spawned via agent-chat)`;\n if (str(payload, 'inferred') === 'true' || payload?.inferred === true) {\n return `${who} exit inferred; no exit code available.`;\n }\n const code = payload?.code;\n const signal = str(payload, 'signal');\n const codePart = typeof code === 'number' ? `code ${code}` : 'no exit code';\n const signalPart = signal ? `, signal ${signal}` : '';\n return `${who} exited with ${codePart}${signalPart}.`;\n}\n\n/** The on_complete payload handler, separated from stdin-reading so it's unit-testable directly. */\nexport async function handleOnComplete(payload: Record<string, unknown> | null): Promise<Result> {\n const agentId = str(payload, 'agentId');\n if (!agentId) return { recorded: false, slug: null };\n\n const context = await takeSpawnContext(agentId);\n if (!context) return { recorded: false, slug: null };\n\n const body = summaryLine(payload, context);\n const { code, stderr } = await wrapRunner([\n 'wrap',\n context.slug,\n '--session-id',\n context.sessionId,\n '--started',\n context.started,\n '--ended',\n nowIso(),\n '--track',\n 'adhoc',\n ...(context.parentSessionId ? ['--parent-session', context.parentSessionId] : []),\n '--body',\n body,\n '--no-loops',\n '--no-notes',\n '--no-tasks',\n ]);\n if (code !== 0) {\n throw new Error(`active-work wrap failed for agentId ${agentId} (exit ${code}): ${stderr}`);\n }\n return { recorded: true, slug: context.slug };\n}\n\nexport default defineCommand<Args, Result>({\n name: 'hooks.agent-chat-complete',\n description:\n \"agent-chat on_complete hook consumer (AW-99): record a spawned peer's run as a track:adhoc session via wrap.\",\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n usage:\n 'active-work hooks agent-chat-complete (reads the on_complete JSON payload from stdin)',\n },\n async run() {\n const payload = await readStdinJson();\n return handleOnComplete(payload);\n },\n});\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { runSetup } from '../setup/steps.js';\nimport { color } from '../utils/color.js';\n\n/**\n * `active-work setup` — interactive wizard that walks a fresh machine to a working state.\n *\n * Each step runs in sequence and short-circuits on the first hard failure.\n * `--yes` skips interactive prompts (assumes no for daemon start / ingestion).\n * `--update` re-runs idempotently and may overwrite the config stub.\n */\n\nconst ArgsSchema = z.object({\n update: z.boolean().optional(),\n yes: z.boolean().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst StepSchema = z.object({\n name: z.string(),\n ok: z.boolean(),\n done: z.boolean().optional(),\n message: z.string().optional(),\n error: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n banner: z.string(),\n steps: z.array(StepSchema),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nfunction printStep(step: Result['steps'][number]): void {\n if (step.ok) {\n const mark = color.green('OK');\n const msg = step.message ?? '';\n process.stderr.write(` ${mark} ${step.name}${msg ? ` — ${msg}` : ''}\\n`);\n } else {\n const mark = color.red('FAIL');\n process.stderr.write(` ${mark} ${step.name} — ${step.error ?? 'failed'}\\n`);\n }\n}\n\nexport default defineCommand<Args, Result>({\n name: 'setup',\n description:\n 'Interactive wizard: verifies Node, scaffolds directories, registers the MCP server, and optionally starts the daemon and walks through ingestion.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n update: {\n long: '--update',\n description: 'Re-run setup idempotently (may overwrite the config stub).',\n },\n yes: {\n long: '--yes',\n short: '-y',\n description: 'Skip all prompts; use defaults (no daemon, no ingestion).',\n },\n },\n },\n async run(args, ctx) {\n const banner = color.bold('active-work setup');\n if (ctx.format !== 'json') {\n process.stderr.write(banner + '\\n');\n }\n const report = await runSetup({\n yes: args.yes ?? false,\n update: args.update ?? false,\n });\n if (ctx.format !== 'json') {\n for (const step of report.steps) printStep(step);\n }\n const failed = report.steps.find((s) => !s.ok);\n if (failed) {\n throw new Error(`setup failed at step '${failed.name}': ${failed.error}`);\n }\n return report;\n },\n});\n","/**\n * Individual setup steps used by `active-work setup` and `active-work uninstall`.\n *\n * Each step is a small async function that accepts a `SetupDeps` bag\n * (filesystem, spawn, prompts, paths). Tests inject stubs; production\n * callers let everything default. Steps never throw on failure — they\n * return a tagged result so the orchestrator can short-circuit cleanly.\n */\nimport { promises as fsp, existsSync } from 'node:fs';\nimport nodePath from 'node:path';\nimport { spawn as nodeSpawn } from 'node:child_process';\nimport os from 'node:os';\nimport { fileURLToPath } from 'node:url';\nimport * as clackPrompts from '@clack/prompts';\nimport { ensureSchemaVersion } from '../schemas/state.js';\nimport { getActiveRoot, getStateRoot, getConfigRoot } from '../utils/paths.js';\nimport { STEP_SUPERVISION } from './supervision-systemd.js';\nimport { getSupervisor } from './supervision.js';\n\nfunction findRepoRoot(): string {\n let cursor = nodePath.dirname(fileURLToPath(import.meta.url));\n for (let depth = 0; depth < 6; depth++) {\n if (existsSync(nodePath.join(cursor, 'package.json'))) return cursor;\n const parent = nodePath.dirname(cursor);\n if (parent === cursor) break;\n cursor = parent;\n }\n // Fallback: two up from current file (covers source layout).\n return nodePath.resolve(nodePath.dirname(fileURLToPath(import.meta.url)), '..', '..');\n}\n\nexport interface StepPaths {\n activeRoot: string;\n stateRoot: string;\n configRoot: string;\n homeDir: string;\n}\n\nexport interface SetupDeps {\n fs?: typeof fsp;\n spawn?: typeof nodeSpawn;\n prompts?: typeof clackPrompts;\n paths?: StepPaths;\n /** When true, skip interactive prompts and assume yes. */\n yes?: boolean;\n /** When true, allow overwrite of existing user files. */\n update?: boolean;\n /** Optional override for repo root (where bundled skill lives). */\n repoRoot?: string;\n /** Optional override for the CLI entrypoint (for spawn calls). */\n cliEntry?: string;\n /**\n * Whether a supervisor already owns the daemon; null when the platform has\n * no integration. Defaults to probing launchctl/systemctl, so tests inject\n * it instead of reading the host's real supervision state.\n */\n supervisorActive?: () => Promise<{ kind: string; active: boolean } | null>;\n}\n\nexport interface StepOk {\n ok: true;\n name: string;\n done: boolean;\n message: string;\n}\n\nexport interface StepErr {\n ok: false;\n name: string;\n error: string;\n}\n\nexport type StepResult = StepOk | StepErr;\n\n/** Resolve every defaultable dep so each step has a complete bag. */\nfunction resolveDeps(deps: SetupDeps): Required<\n Omit<SetupDeps, 'yes' | 'update' | 'repoRoot' | 'cliEntry' | 'supervisorActive'>\n> & {\n yes: boolean;\n update: boolean;\n repoRoot: string;\n cliEntry: string;\n} {\n const fs = deps.fs ?? fsp;\n const spawn = deps.spawn ?? nodeSpawn;\n const prompts = deps.prompts ?? clackPrompts;\n const homeDir = deps.paths?.homeDir ?? os.homedir();\n const paths: StepPaths = deps.paths ?? {\n activeRoot: getActiveRoot(),\n stateRoot: getStateRoot(),\n configRoot: getConfigRoot(),\n homeDir,\n };\n // The bundled skill lives at `<repoRoot>/skill`. Find it by walking up\n // from this module until we hit a directory containing `package.json`\n // — works both for source (`src/setup/steps.ts`) and bundled\n // (`dist/cli.js`) layouts.\n const repoRoot = deps.repoRoot ?? findRepoRoot();\n const cliEntry = deps.cliEntry ?? process.argv[1] ?? 'active-work';\n return {\n fs,\n spawn,\n prompts,\n paths,\n yes: deps.yes ?? false,\n update: deps.update ?? false,\n repoRoot,\n cliEntry,\n };\n}\n\nconst STEP_CHECK_NODE = 'check-node';\nconst STEP_CREATE_ACTIVE = 'create-active-root';\nconst STEP_SCHEMA = 'write-schema-version';\nconst STEP_CONFIG = 'write-config-stub';\nconst STEP_SKILL = 'install-skill';\nconst STEP_COMMAND = 'install-command';\nconst STEP_MCP = 'register-mcp';\nconst STEP_AGENT_CHAT_HOOKS = 'register-agent-chat-hooks';\nconst STEP_DAEMON = 'start-daemon';\nconst STEP_INGEST = 'ingestion';\n\nexport const STEP_NAMES = {\n CHECK_NODE: STEP_CHECK_NODE,\n CREATE_ACTIVE: STEP_CREATE_ACTIVE,\n SCHEMA: STEP_SCHEMA,\n CONFIG: STEP_CONFIG,\n SKILL: STEP_SKILL,\n COMMAND: STEP_COMMAND,\n MCP: STEP_MCP,\n AGENT_CHAT_HOOKS: STEP_AGENT_CHAT_HOOKS,\n SUPERVISION: STEP_SUPERVISION,\n DAEMON: STEP_DAEMON,\n INGEST: STEP_INGEST,\n} as const;\n\nconst MIN_NODE_MAJOR = 22;\n\nfunction parseNodeMajor(version: string): number {\n const cleaned = version.startsWith('v') ? version.slice(1) : version;\n const major = Number(cleaned.split('.')[0]);\n return Number.isFinite(major) ? major : 0;\n}\n\nexport async function stepCheckNode(deps: SetupDeps = {}): Promise<StepResult> {\n void deps;\n const major = parseNodeMajor(process.versions.node);\n if (major < MIN_NODE_MAJOR) {\n return {\n ok: false,\n name: STEP_CHECK_NODE,\n error: `Node ${MIN_NODE_MAJOR}+ required, found v${process.versions.node}`,\n };\n }\n return {\n ok: true,\n name: STEP_CHECK_NODE,\n done: true,\n message: `Node v${process.versions.node} OK`,\n };\n}\n\nasync function ensureDir(fs: typeof fsp, dir: string): Promise<{ created: boolean }> {\n try {\n const stat = await fs.stat(dir);\n if (stat.isDirectory()) return { created: false };\n throw new Error(`${dir} exists but is not a directory`);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== 'ENOENT') throw err;\n }\n await fs.mkdir(dir, { recursive: true });\n return { created: true };\n}\n\nexport async function stepCreateActiveRoot(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, paths } = resolveDeps(deps);\n try {\n const created: string[] = [];\n for (const dir of [paths.activeRoot, paths.stateRoot, paths.configRoot]) {\n const { created: didCreate } = await ensureDir(fs, dir);\n if (didCreate) created.push(dir);\n }\n const message =\n created.length === 0\n ? `Active/state/config dirs already present`\n : `Created ${created.length} dir(s)`;\n return {\n ok: true,\n name: STEP_CREATE_ACTIVE,\n done: created.length > 0,\n message,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_CREATE_ACTIVE,\n error: (err as Error).message,\n };\n }\n}\n\nexport async function stepWriteSchemaVersion(deps: SetupDeps = {}): Promise<StepResult> {\n const { paths } = resolveDeps(deps);\n try {\n const result = await ensureSchemaVersion(paths.activeRoot);\n const message = result.migrated\n ? `Migrated v${result.before} -> v${result.after}`\n : `Schema at v${result.after}`;\n return {\n ok: true,\n name: STEP_SCHEMA,\n done: result.migrated,\n message,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_SCHEMA,\n error: (err as Error).message,\n };\n }\n}\n\nconst CONFIG_STUB = {\n discovery: {\n githubRepos: [] as string[],\n localRepos: [] as string[],\n projectsRoot: '~/Documents/projects',\n },\n // MCP push channels loaded on every `aw`/`open` launch, for every\n // initiative — see `utils/global-config.ts`. Edit or clear this list to\n // customize; an empty/missing array falls back to the agent-chat default.\n channels: ['plugin:agent-chat@agent-chat-local'] as string[],\n};\n\nexport async function stepWriteConfigStub(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, paths, update } = resolveDeps(deps);\n const configPath = nodePath.join(paths.configRoot, 'config.json');\n try {\n await ensureDir(fs, paths.configRoot);\n let exists = false;\n try {\n await fs.stat(configPath);\n exists = true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n if (exists && !update) {\n return {\n ok: true,\n name: STEP_CONFIG,\n done: false,\n message: `Config exists at ${configPath} (left untouched)`,\n };\n }\n await fs.writeFile(configPath, JSON.stringify(CONFIG_STUB, null, 2) + '\\n', 'utf8');\n return {\n ok: true,\n name: STEP_CONFIG,\n done: true,\n message: `Wrote config stub to ${configPath}`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_CONFIG,\n error: (err as Error).message,\n };\n }\n}\n\nasync function pathExists(fs: typeof fsp, p: string): Promise<boolean> {\n try {\n await fs.stat(p);\n return true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return false;\n throw err;\n }\n}\n\nasync function copyTree(fs: typeof fsp, src: string, dest: string): Promise<void> {\n // node:fs/promises has cp() in Node 22+.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const cp = (fs as any).cp as\n | undefined\n | ((from: string, to: string, opts: { recursive: boolean }) => Promise<void>);\n if (cp) {\n await cp(src, dest, { recursive: true });\n return;\n }\n // Fallback: shallow copy of files only (test envs may stub fs).\n await fs.mkdir(dest, { recursive: true });\n const entries = await fs.readdir(src, { withFileTypes: true });\n for (const entry of entries) {\n const from = nodePath.join(src, entry.name);\n const to = nodePath.join(dest, entry.name);\n if (entry.isDirectory()) {\n await copyTree(fs, from, to);\n } else {\n await fs.copyFile(from, to);\n }\n }\n}\n\nexport async function stepInstallSkill(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, paths, repoRoot } = resolveDeps(deps);\n const targetDir = nodePath.join(paths.homeDir, '.claude', 'skills', 'active-work');\n const targetMarker = nodePath.join(targetDir, 'SKILL.md');\n const sourceDir = nodePath.join(repoRoot, 'skill');\n try {\n if (await pathExists(fs, targetMarker)) {\n return {\n ok: true,\n name: STEP_SKILL,\n done: false,\n message: `Skill already installed at ${targetDir}`,\n };\n }\n if (!(await pathExists(fs, sourceDir))) {\n return {\n ok: true,\n name: STEP_SKILL,\n done: false,\n message: `Skill source not found at ${sourceDir}; skipping`,\n };\n }\n await fs.mkdir(nodePath.dirname(targetDir), { recursive: true });\n await copyTree(fs, sourceDir, targetDir);\n return {\n ok: true,\n name: STEP_SKILL,\n done: true,\n message: `Installed skill to ${targetDir}`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_SKILL,\n error: (err as Error).message,\n };\n }\n}\n\nexport async function stepInstallCommand(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, paths, repoRoot } = resolveDeps(deps);\n const targetDir = nodePath.join(paths.homeDir, '.claude', 'commands');\n const target = nodePath.join(targetDir, 'aw-prompt.md');\n const source = nodePath.join(repoRoot, 'claude-commands', 'aw-prompt.md');\n try {\n if (!(await pathExists(fs, source))) {\n return {\n ok: true,\n name: STEP_COMMAND,\n done: false,\n message: `Command source not found at ${source}; skipping`,\n };\n }\n await fs.mkdir(targetDir, { recursive: true });\n // Overwrite unconditionally (unlike the skill step, which skips if present):\n // the command is a single version-bundled file, so setup should refresh it.\n await fs.copyFile(source, target);\n return {\n ok: true,\n name: STEP_COMMAND,\n done: true,\n message: `Installed /aw-prompt command to ${target}`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_COMMAND,\n error: (err as Error).message,\n };\n }\n}\n\n/** Spawn a process and capture its exit code + stderr. */\nfunction runOnce(\n spawn: typeof nodeSpawn,\n cmd: string,\n args: string[],\n): Promise<{ code: number | null; stderr: string; spawnError?: Error }> {\n return new Promise((resolve) => {\n let stderr = '';\n let settled = false;\n try {\n const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });\n child.stderr?.on('data', (chunk: Buffer | string) => {\n stderr += chunk.toString();\n });\n child.on('error', (err) => {\n if (settled) return;\n settled = true;\n resolve({ code: null, stderr, spawnError: err });\n });\n child.on('close', (code) => {\n if (settled) return;\n settled = true;\n resolve({ code, stderr });\n });\n } catch (err) {\n if (settled) return;\n settled = true;\n resolve({ code: null, stderr, spawnError: err as Error });\n }\n });\n}\n\nconst MCP_FALLBACK_SNIPPET = `{\n \"active-work\": {\n \"command\": \"active-work\",\n \"args\": [\"mcp\", \"serve\", \"--stdio\"]\n }\n}`;\n\nexport async function stepRegisterMcp(deps: SetupDeps = {}): Promise<StepResult> {\n const { spawn } = resolveDeps(deps);\n const result = await runOnce(spawn, 'claude', [\n 'mcp',\n 'add',\n '--user',\n '@hjewkes/active-work',\n '--',\n 'active-work',\n 'mcp',\n 'serve',\n '--stdio',\n ]);\n if (result.spawnError && (result.spawnError as NodeJS.ErrnoException).code === 'ENOENT') {\n return {\n ok: true,\n name: STEP_MCP,\n done: false,\n message:\n '`claude` CLI not found. Add this to ~/.claude.json mcpServers section:\\n' +\n MCP_FALLBACK_SNIPPET,\n };\n }\n if (result.spawnError) {\n return {\n ok: true,\n name: STEP_MCP,\n done: false,\n message: `MCP registration skipped: ${result.spawnError.message}`,\n };\n }\n if (result.code === 0) {\n return {\n ok: true,\n name: STEP_MCP,\n done: true,\n message: 'Registered MCP server with Claude Code',\n };\n }\n return {\n ok: true,\n name: STEP_MCP,\n done: false,\n message:\n `claude mcp add exited with code ${result.code ?? 'null'}. ` +\n 'If already registered, this is safe. Otherwise add manually:\\n' +\n MCP_FALLBACK_SNIPPET,\n };\n}\n\n/** The two commands this build registers into agent-chat's on_spawn/on_complete hooks (AW-99/AW-100). */\nconst AGENT_CHAT_HOOK_COMMANDS: Record<'on_spawn' | 'on_complete', string> = {\n on_spawn: 'active-work hooks agent-chat-spawn',\n on_complete: 'active-work hooks agent-chat-complete',\n};\n\ninterface AgentChatHooksConfig {\n on_spawn?: string[];\n on_complete?: string[];\n}\n\n/**\n * `~/.agent-chat/hooks.json` (honoring `AGENT_CHAT_HOME`, matching agent-chat's\n * own `home()` in `src/paths.ts`) — outside this build's control, so an\n * override or a missing home directory both have to degrade gracefully.\n */\nfunction agentChatHooksPath(paths: StepPaths): string {\n const home = process.env.AGENT_CHAT_HOME ?? nodePath.join(paths.homeDir, '.agent-chat');\n return nodePath.join(home, 'hooks.json');\n}\n\n/**\n * Merges this build's on_spawn/on_complete commands into agent-chat's generic\n * lifecycle hooks (CC-71) — additive only. An existing `hooks.json` keeps\n * every entry another tool registered; re-running this step is a no-op once\n * both commands are present, since it checks membership rather than\n * appending unconditionally. No `~/.agent-chat` directory at all means\n * agent-chat isn't installed on this machine, which is a normal skip, not an\n * error — this build must not be what creates agent-chat's home directory.\n */\nexport async function stepRegisterAgentChatHooks(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, paths } = resolveDeps(deps);\n const hooksPath = agentChatHooksPath(paths);\n const agentChatHome = nodePath.dirname(hooksPath);\n\n try {\n await fs.stat(agentChatHome);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return {\n ok: true,\n name: STEP_AGENT_CHAT_HOOKS,\n done: false,\n message: `agent-chat not found at ${agentChatHome} — skipped`,\n };\n }\n return { ok: false, name: STEP_AGENT_CHAT_HOOKS, error: (err as Error).message };\n }\n\n try {\n let config: AgentChatHooksConfig = {};\n try {\n const raw = await fs.readFile(hooksPath, 'utf8');\n const parsed: unknown = JSON.parse(raw);\n if (typeof parsed === 'object' && parsed !== null) config = parsed as AgentChatHooksConfig;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {\n return {\n ok: false,\n name: STEP_AGENT_CHAT_HOOKS,\n error: `${hooksPath} exists but is not valid JSON: ${(err as Error).message}`,\n };\n }\n }\n\n let changed = false;\n for (const event of ['on_spawn', 'on_complete'] as const) {\n const command = AGENT_CHAT_HOOK_COMMANDS[event];\n const existing = config[event] ?? [];\n if (!existing.includes(command)) {\n config[event] = [...existing, command];\n changed = true;\n }\n }\n\n if (!changed) {\n return {\n ok: true,\n name: STEP_AGENT_CHAT_HOOKS,\n done: false,\n message: `Already registered in ${hooksPath}`,\n };\n }\n\n await fs.writeFile(hooksPath, JSON.stringify(config, null, 2) + '\\n', 'utf8');\n return {\n ok: true,\n name: STEP_AGENT_CHAT_HOOKS,\n done: true,\n message: `Registered on_spawn/on_complete hooks in ${hooksPath}`,\n };\n } catch (err) {\n return { ok: false, name: STEP_AGENT_CHAT_HOOKS, error: (err as Error).message };\n }\n}\n\n/**\n * Offer to install a user-level supervisor (systemd on Linux, launchd on\n * macOS) that keeps the daemon running across logins. No-op on platforms\n * without an integration.\n */\nexport async function stepSupervision(deps: SetupDeps = {}): Promise<StepResult> {\n const { prompts, yes } = resolveDeps(deps);\n const supervisor = getSupervisor();\n if (!supervisor) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Skipped: no daemon supervisor is integrated for ${process.platform}`,\n };\n }\n if (!yes) {\n const answer = await prompts.confirm({\n message: supervisor.installPrompt,\n initialValue: true,\n });\n if (prompts.isCancel(answer) || answer !== true) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: 'Supervision install skipped',\n };\n }\n }\n // Supervision is an optional enhancement, not a prerequisite. Like\n // `stepStartDaemon`, a runtime failure (no user session, container, CI) must\n // not abort the whole setup — the unit/plist is still written, so downgrade\n // an install failure to a non-fatal warning that tells the user how to finish\n // enabling it by hand.\n const result = await supervisor.install(deps);\n if (!result.ok) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Daemon supervision not enabled (${result.error}); run \\`${supervisor.enableHint}\\` once a user session is available`,\n };\n }\n return result;\n}\n\n/** Probe the platform supervisor; null when the platform has no integration. */\nasync function probeSupervisor(deps: SetupDeps): Promise<{ kind: string; active: boolean } | null> {\n const supervisor = getSupervisor();\n if (!supervisor) return null;\n return { kind: supervisor.kind, active: await supervisor.isActive(deps) };\n}\n\n/** Spawn `active-work mcp serve --detach` (best-effort). */\nexport async function stepStartDaemon(deps: SetupDeps = {}): Promise<StepResult> {\n const { spawn, prompts, yes, cliEntry } = resolveDeps(deps);\n // If a supervisor already owns the daemon, skip the manual spawn — restarting\n // it is the supervisor's job (e.g. `systemctl --user restart` / `launchctl\n // kickstart`).\n const probe = deps.supervisorActive ?? (() => probeSupervisor(deps));\n const supervisor = await probe();\n if (supervisor?.active) {\n return {\n ok: true,\n name: STEP_DAEMON,\n done: false,\n message: `Daemon already supervised by ${supervisor.kind}; manual start skipped`,\n };\n }\n if (!yes) {\n const answer = await prompts.confirm({\n message: 'Start the HTTP daemon now? (background process)',\n initialValue: true,\n });\n if (prompts.isCancel(answer) || answer !== true) {\n return {\n ok: true,\n name: STEP_DAEMON,\n done: false,\n message: 'Daemon start skipped',\n };\n }\n } else {\n return {\n ok: true,\n name: STEP_DAEMON,\n done: false,\n message: 'Daemon start skipped (--yes)',\n };\n }\n try {\n const child = spawn(process.execPath, [cliEntry, 'mcp', 'serve', '--detach'], {\n detached: true,\n stdio: 'ignore',\n });\n child.unref?.();\n return {\n ok: true,\n name: STEP_DAEMON,\n done: true,\n message: `Daemon launched (pid=${child.pid ?? 'unknown'})`,\n };\n } catch (err) {\n return {\n ok: true,\n name: STEP_DAEMON,\n done: false,\n message: `Daemon launch skipped: ${(err as Error).message}`,\n };\n }\n}\n\nexport async function stepIngestion(deps: SetupDeps = {}): Promise<StepResult> {\n const { prompts, yes, paths } = resolveDeps(deps);\n if (yes) {\n return {\n ok: true,\n name: STEP_INGEST,\n done: false,\n message:\n `Skipped ingestion walkthrough. Run \\`claude\\` in ${paths.activeRoot} ` +\n 'and ask it to run `active-work discover` followed by `active-work fold` / `active-work drop` / `active-work track`.',\n };\n }\n const answer = await prompts.confirm({\n message: 'Walk through existing work with Claude now?',\n initialValue: false,\n });\n if (prompts.isCancel(answer) || answer !== true) {\n return {\n ok: true,\n name: STEP_INGEST,\n done: false,\n message:\n `Ingestion skipped. Later: run \\`claude\\` in ${paths.activeRoot} and ask it to ` +\n 'invoke `active-work discover` to scan your work.',\n };\n }\n return {\n ok: true,\n name: STEP_INGEST,\n done: true,\n message:\n `Run \\`claude\\` in ${paths.activeRoot} and paste this prompt: ` +\n '\"Please run `active-work discover`, then walk me through `active-work fold` / `active-work drop` / `active-work track` for each hit.\"',\n };\n}\n\nexport interface SetupReport {\n banner: string;\n steps: Array<{\n name: string;\n ok: boolean;\n done?: boolean;\n message?: string;\n error?: string;\n }>;\n}\n\n/** Run every setup step in order, short-circuiting on the first failure. */\nexport async function runSetup(deps: SetupDeps = {}): Promise<SetupReport> {\n const banner = 'active-work setup';\n const steps: SetupReport['steps'] = [];\n const ordered = [\n stepCheckNode,\n stepCreateActiveRoot,\n stepWriteSchemaVersion,\n stepWriteConfigStub,\n stepInstallSkill,\n stepInstallCommand,\n stepRegisterMcp,\n stepRegisterAgentChatHooks,\n stepSupervision,\n stepStartDaemon,\n stepIngestion,\n ];\n for (const step of ordered) {\n const result = await step(deps);\n if (result.ok) {\n steps.push({\n name: result.name,\n ok: true,\n done: result.done,\n message: result.message,\n });\n } else {\n steps.push({ name: result.name, ok: false, error: result.error });\n break;\n }\n }\n return { banner, steps };\n}\n\n// ----- Uninstall ----------------------------------------------------------\n\nexport interface UninstallReport {\n steps: Array<{ name: string; done: boolean; message?: string; error?: string }>;\n activeRootPreservedAt: string;\n}\n\nasync function confirmStep(\n prompts: typeof clackPrompts,\n yes: boolean,\n message: string,\n initial = true,\n): Promise<boolean> {\n if (yes) return true;\n const answer = await prompts.confirm({ message, initialValue: initial });\n if (prompts.isCancel(answer)) return false;\n return answer === true;\n}\n\nexport async function uninstallSkill(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, paths } = resolveDeps(deps);\n const target = nodePath.join(paths.homeDir, '.claude', 'skills', 'active-work');\n try {\n if (!(await pathExists(fs, target))) {\n return {\n ok: true,\n name: STEP_SKILL,\n done: false,\n message: `Skill not present at ${target}`,\n };\n }\n await fs.rm(target, { recursive: true, force: true });\n return {\n ok: true,\n name: STEP_SKILL,\n done: true,\n message: `Removed skill from ${target}`,\n };\n } catch (err) {\n return { ok: false, name: STEP_SKILL, error: (err as Error).message };\n }\n}\n\nexport async function uninstallCommand(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, paths } = resolveDeps(deps);\n const target = nodePath.join(paths.homeDir, '.claude', 'commands', 'aw-prompt.md');\n try {\n if (!(await pathExists(fs, target))) {\n return {\n ok: true,\n name: STEP_COMMAND,\n done: false,\n message: `Command not present at ${target}`,\n };\n }\n await fs.rm(target, { force: true });\n return {\n ok: true,\n name: STEP_COMMAND,\n done: true,\n message: `Removed /aw-prompt command from ${target}`,\n };\n } catch (err) {\n return { ok: false, name: STEP_COMMAND, error: (err as Error).message };\n }\n}\n\nexport async function uninstallStopDaemon(deps: SetupDeps = {}): Promise<StepResult> {\n const { spawn, cliEntry } = resolveDeps(deps);\n const result = await runOnce(spawn, process.execPath, [cliEntry, 'mcp', 'stop']);\n if (result.spawnError) {\n return {\n ok: true,\n name: STEP_DAEMON,\n done: false,\n message: `Daemon stop skipped: ${result.spawnError.message}`,\n };\n }\n return {\n ok: true,\n name: STEP_DAEMON,\n done: result.code === 0,\n message: result.code === 0 ? 'Daemon stopped' : `Daemon stop exited ${result.code ?? 'null'}`,\n };\n}\n\nexport async function uninstallMcp(deps: SetupDeps = {}): Promise<StepResult> {\n const { spawn } = resolveDeps(deps);\n const result = await runOnce(spawn, 'claude', [\n 'mcp',\n 'remove',\n '--user',\n '@hjewkes/active-work',\n ]);\n if (result.spawnError && (result.spawnError as NodeJS.ErrnoException).code === 'ENOENT') {\n return {\n ok: true,\n name: STEP_MCP,\n done: false,\n message: '`claude` CLI not found. Remove the entry manually from ~/.claude.json',\n };\n }\n if (result.spawnError) {\n return {\n ok: true,\n name: STEP_MCP,\n done: false,\n message: `MCP unregister skipped: ${result.spawnError.message}`,\n };\n }\n return {\n ok: true,\n name: STEP_MCP,\n done: result.code === 0,\n message:\n result.code === 0\n ? 'Unregistered MCP server from Claude Code'\n : `claude mcp remove exited with code ${result.code ?? 'null'}`,\n };\n}\n\nexport async function runUninstall(deps: SetupDeps = {}): Promise<UninstallReport> {\n const resolved = resolveDeps(deps);\n const steps: UninstallReport['steps'] = [];\n\n const wantSkill = await confirmStep(\n resolved.prompts,\n resolved.yes,\n 'Remove the active-work skill from ~/.claude/skills/?',\n );\n if (wantSkill) {\n const r = await uninstallSkill(deps);\n steps.push({\n name: r.name,\n done: r.ok ? r.done : false,\n ...(r.ok ? { message: r.message } : { error: r.error }),\n });\n } else {\n steps.push({ name: STEP_SKILL, done: false, message: 'Skipped' });\n }\n\n const wantCommand = await confirmStep(\n resolved.prompts,\n resolved.yes,\n 'Remove the /aw-prompt command from ~/.claude/commands/?',\n );\n if (wantCommand) {\n const r = await uninstallCommand(deps);\n steps.push({\n name: r.name,\n done: r.ok ? r.done : false,\n ...(r.ok ? { message: r.message } : { error: r.error }),\n });\n } else {\n steps.push({ name: STEP_COMMAND, done: false, message: 'Skipped' });\n }\n\n const supervisor = getSupervisor();\n if (supervisor) {\n const wantSupervision = await confirmStep(\n resolved.prompts,\n resolved.yes,\n supervisor.uninstallPrompt,\n );\n if (wantSupervision) {\n const r = await supervisor.uninstall(deps);\n steps.push({\n name: r.name,\n done: r.ok ? r.done : false,\n ...(r.ok ? { message: r.message } : { error: r.error }),\n });\n } else {\n steps.push({ name: STEP_SUPERVISION, done: false, message: 'Skipped' });\n }\n }\n\n const wantDaemon = await confirmStep(resolved.prompts, resolved.yes, 'Stop the daemon?');\n if (wantDaemon) {\n const r = await uninstallStopDaemon(deps);\n steps.push({\n name: r.name,\n done: r.ok ? r.done : false,\n ...(r.ok ? { message: r.message } : { error: r.error }),\n });\n } else {\n steps.push({ name: STEP_DAEMON, done: false, message: 'Skipped' });\n }\n\n const wantMcp = await confirmStep(\n resolved.prompts,\n resolved.yes,\n 'Unregister MCP from Claude Code?',\n );\n if (wantMcp) {\n const r = await uninstallMcp(deps);\n steps.push({\n name: r.name,\n done: r.ok ? r.done : false,\n ...(r.ok ? { message: r.message } : { error: r.error }),\n });\n } else {\n steps.push({ name: STEP_MCP, done: false, message: 'Skipped' });\n }\n\n return {\n steps,\n activeRootPreservedAt: resolved.paths.activeRoot,\n };\n}\n","import { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport { CURRENT_VERSION, runMigrations } from '../migrations/index.js';\n\nconst SCHEMA_VERSION_FILENAME = '.schema-version';\n\nconst schemaVersionPath = (activeRoot: string): string => join(activeRoot, SCHEMA_VERSION_FILENAME);\n\nconst isNodeErrnoException = (err: unknown): err is NodeJS.ErrnoException =>\n typeof err === 'object' && err !== null && 'code' in err;\n\nexport async function readSchemaVersion(activeRoot: string): Promise<number> {\n const path = schemaVersionPath(activeRoot);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (isNodeErrnoException(err) && err.code === 'ENOENT') {\n return 0;\n }\n throw err;\n }\n\n const trimmed = raw.trim();\n if (trimmed === '' || !/^\\d+$/.test(trimmed)) {\n throw new Error(\n `Invalid schema version in ${path}: expected a positive integer, got ${JSON.stringify(raw)}`,\n );\n }\n\n const parsed = Number(trimmed);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(\n `Invalid schema version in ${path}: expected a positive integer, got ${JSON.stringify(raw)}`,\n );\n }\n return parsed;\n}\n\nexport async function writeSchemaVersion(activeRoot: string, version: number): Promise<void> {\n if (!Number.isInteger(version) || version <= 0) {\n throw new Error(`Schema version must be a positive integer, got ${version}`);\n }\n await writeFile(schemaVersionPath(activeRoot), `${version}\\n`, 'utf8');\n}\n\nasync function readRawSchemaVersion(\n activeRoot: string,\n): Promise<{ present: false } | { present: true; version: number }> {\n const path = schemaVersionPath(activeRoot);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (isNodeErrnoException(err) && err.code === 'ENOENT') {\n return { present: false };\n }\n throw err;\n }\n\n const trimmed = raw.trim();\n if (trimmed === '' || !/^\\d+$/.test(trimmed)) {\n throw new Error(\n `Invalid schema version in ${path}: expected a non-negative integer, got ${JSON.stringify(raw)}`,\n );\n }\n\n const parsed = Number(trimmed);\n if (!Number.isInteger(parsed) || parsed < 0) {\n throw new Error(\n `Invalid schema version in ${path}: expected a non-negative integer, got ${JSON.stringify(raw)}`,\n );\n }\n return { present: true, version: parsed };\n}\n\n/**\n * Ensures the schema version file is present and up to date.\n *\n * - If the file is missing: writes `CURRENT_VERSION` (fresh install).\n * - If the file equals `CURRENT_VERSION`: no-op.\n * - If the file is older than `CURRENT_VERSION`: runs migrations in\n * order, then writes the new version.\n * - If the file is newer than `CURRENT_VERSION`: throws (downgrade not\n * supported).\n *\n * The summary is shaped for CLI/MCP startup logs.\n */\nexport async function ensureSchemaVersion(activeRoot: string): Promise<{\n before: number;\n after: number;\n migrated: boolean;\n ran: Array<{ from: number; to: number; description: string }>;\n}> {\n const raw = await readRawSchemaVersion(activeRoot);\n\n if (!raw.present) {\n await writeSchemaVersion(activeRoot, CURRENT_VERSION);\n return {\n before: CURRENT_VERSION,\n after: CURRENT_VERSION,\n migrated: false,\n ran: [],\n };\n }\n\n const before = raw.version;\n\n if (before === CURRENT_VERSION) {\n return { before, after: before, migrated: false, ran: [] };\n }\n\n const { ran } = await runMigrations(activeRoot, before);\n await writeSchemaVersion(activeRoot, CURRENT_VERSION);\n\n return {\n before,\n after: CURRENT_VERSION,\n migrated: ran.length > 0,\n ran: ran.map((m) => ({ from: m.from, to: m.to, description: m.description })),\n };\n}\n","import { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\nimport YAML from 'yaml';\nimport { ArtifactsSchema } from '../schemas/artifacts.js';\nimport { writeYaml } from '../utils/yaml-io.js';\nimport type { Migration } from './types.js';\n\n/**\n * v1 → v2 (AW-15): collapse `artifacts.yml` to a branches+stashes-only\n * schema and surface dropped PR entries via a migration log.\n *\n * Per-file transforms:\n * - `prs:` is dropped entirely. Each entry is logged at WARN to\n * `<activeRoot>/.migrations.log` so the user can reconcile manually.\n * - `branches[].last_commit` is dropped.\n * - `stashes[].message` → `stashes[].label`; `created` is dropped; `sha`\n * is preserved if present.\n *\n * The walk covers active-root initiatives and (best-effort) archived ones\n * under `<archiveRoot>/<domain>/archive/<slug>/artifacts.yml`, where\n * `archiveRoot` is the parent directory of the active root.\n *\n * Idempotent: re-running on already-v2 files leaves them unchanged\n * (extraneous keys like `prs:` simply aren't present in the v2 input).\n */\n\ninterface V1Pr {\n number?: number;\n repo?: string;\n title?: string;\n status?: string;\n}\n\ninterface V1Branch {\n repo?: string;\n name?: string;\n last_commit?: string;\n note?: string;\n}\n\ninterface V1Stash {\n repo?: string;\n message?: string;\n label?: string;\n created?: string;\n sha?: string;\n}\n\ninterface RawArtifacts {\n prs?: V1Pr[];\n branches?: V1Branch[];\n stashes?: V1Stash[];\n [key: string]: unknown;\n}\n\nfunction asArray<T>(value: unknown): T[] {\n return Array.isArray(value) ? (value as T[]) : [];\n}\n\nfunction normaliseBranch(b: V1Branch): { repo: string; name: string; note?: string } | null {\n if (typeof b.repo !== 'string' || typeof b.name !== 'string') return null;\n if (b.repo.length === 0 || b.name.length === 0) return null;\n const out: { repo: string; name: string; note?: string } = {\n repo: b.repo,\n name: b.name,\n };\n if (typeof b.note === 'string' && b.note.length > 0) out.note = b.note;\n return out;\n}\n\nfunction normaliseStash(s: V1Stash): { repo: string; label: string; sha?: string } | null {\n if (typeof s.repo !== 'string' || s.repo.length === 0) return null;\n // v1 used `message`; v2 uses `label`. Prefer label if both present.\n const label =\n typeof s.label === 'string' && s.label.length > 0\n ? s.label\n : typeof s.message === 'string'\n ? s.message\n : '';\n if (label.length === 0) return null;\n const out: { repo: string; label: string; sha?: string } = { repo: s.repo, label };\n if (typeof s.sha === 'string' && s.sha.length > 0) out.sha = s.sha;\n return out;\n}\n\ninterface MigrateOneResult {\n changed: boolean;\n droppedPrs: V1Pr[];\n}\n\nasync function migrateOne(filePath: string): Promise<MigrateOneResult> {\n let raw: string;\n try {\n raw = await fs.readFile(filePath, 'utf8');\n } catch {\n return { changed: false, droppedPrs: [] };\n }\n\n let parsed: RawArtifacts;\n try {\n parsed = (YAML.parse(raw) ?? {}) as RawArtifacts;\n } catch {\n // Malformed YAML — leave it; user will see it on next read.\n return { changed: false, droppedPrs: [] };\n }\n\n const droppedPrs = asArray<V1Pr>(parsed.prs);\n const branches = asArray<V1Branch>(parsed.branches)\n .map(normaliseBranch)\n .filter((b): b is { repo: string; name: string; note?: string } => b !== null);\n const stashes = asArray<V1Stash>(parsed.stashes)\n .map(normaliseStash)\n .filter((s): s is { repo: string; label: string; sha?: string } => s !== null);\n\n // Detect a no-op: prs absent, no last_commit on branches, no message-only stashes.\n const branchHadLegacy = asArray<V1Branch>(parsed.branches).some(\n (b) => typeof b.last_commit === 'string',\n );\n const stashHadLegacy = asArray<V1Stash>(parsed.stashes).some(\n (s) => typeof s.message === 'string' || typeof s.created === 'string',\n );\n const hadPrs = droppedPrs.length > 0 || parsed.prs !== undefined;\n if (!branchHadLegacy && !stashHadLegacy && !hadPrs) {\n return { changed: false, droppedPrs: [] };\n }\n\n const next = ArtifactsSchema.parse({ branches, stashes });\n await writeYaml(filePath, next, ArtifactsSchema);\n return { changed: true, droppedPrs };\n}\n\nasync function walkArtifactsFiles(activeRoot: string): Promise<string[]> {\n const out: string[] = [];\n\n // Active initiatives: <activeRoot>/<slug>/artifacts.yml\n try {\n const entries = await fs.readdir(activeRoot, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (entry.name.startsWith('.')) continue;\n const candidate = path.join(activeRoot, entry.name, 'artifacts.yml');\n try {\n await fs.access(candidate);\n out.push(candidate);\n } catch {\n // skip\n }\n }\n } catch {\n // active root may not exist; nothing to migrate.\n }\n\n // Archived initiatives: <archiveRoot>/<domain>/archive/<slug-YYYY-MM>/artifacts.yml\n const archiveRoot = path.resolve(activeRoot, '..');\n try {\n const domains = await fs.readdir(archiveRoot, { withFileTypes: true });\n for (const domain of domains) {\n if (!domain.isDirectory()) continue;\n if (domain.name.startsWith('.')) continue;\n // Skip the active root itself when scanning its parent.\n if (path.join(archiveRoot, domain.name) === path.resolve(activeRoot)) continue;\n const archiveDir = path.join(archiveRoot, domain.name, 'archive');\n let archived: Dirent[];\n try {\n archived = await fs.readdir(archiveDir, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const entry of archived) {\n if (!entry.isDirectory()) continue;\n const candidate = path.join(archiveDir, entry.name, 'artifacts.yml');\n try {\n await fs.access(candidate);\n out.push(candidate);\n } catch {\n // skip\n }\n }\n }\n } catch {\n // best-effort\n }\n\n return out;\n}\n\nasync function appendMigrationLog(activeRoot: string, lines: string[]): Promise<void> {\n if (lines.length === 0) return;\n const logPath = path.join(activeRoot, '.migrations.log');\n const stamp = new Date().toISOString();\n const body = lines.map((l) => `${stamp}\\tv1->v2\\t${l}\\n`).join('');\n try {\n await fs.mkdir(activeRoot, { recursive: true });\n } catch {\n // ignore\n }\n await fs.appendFile(logPath, body, 'utf8');\n}\n\nexport const v1ToV2Artifacts: Migration = {\n from: 1,\n to: 2,\n description: 'Drop prs[] / last_commit / stash.message from artifacts.yml',\n async run(activeRoot: string): Promise<void> {\n const files = await walkArtifactsFiles(activeRoot);\n const logEntries: string[] = [];\n for (const file of files) {\n const { droppedPrs } = await migrateOne(file);\n for (const pr of droppedPrs) {\n const num = typeof pr.number === 'number' ? `#${pr.number}` : '#?';\n const repo = pr.repo ?? '(unknown repo)';\n const title = pr.title ?? '(no title)';\n logEntries.push(`${file}\\t${num} (${repo}) ${title}`);\n }\n }\n await appendMigrationLog(activeRoot, logEntries);\n },\n};\n\nexport default v1ToV2Artifacts;\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { ValidationError } from '../errors.js';\nimport { BriefFrontmatterSchema, type BriefFrontmatter } from '../schemas/brief.js';\nimport { SessionFrontmatterSchema, type SessionFrontmatter } from '../schemas/session.js';\nimport {\n buildSessionStem,\n sessionFilePathForStem,\n writeSessionFile,\n} from '../sessions/session-file.js';\nimport { withFileLock } from '../utils/fs-atomic.js';\nimport { readRawFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\nimport { loadProposal, type Proposal, type ProposalInitiative } from './v3-proposal.js';\nimport {\n KNOWN_REPAIRS,\n applyRepair,\n planRepairs,\n repairBriefFrontmatter,\n type RepairPlan,\n} from './v3-repairs.js';\nimport type { Migration } from './types.js';\n\n/**\n * v2 → v3 (AW-38): retire `handoff.md` in favour of the session open-loops\n * ledger.\n *\n * Per initiative, driven entirely by the hand-authored proposal data file:\n * - write a back-dated `track: sidecar` session carrying the handoff's\n * next-actions as `next_steps`, so they enter the ledger and start aging\n * from their real last-touch;\n * - where the proposal marks a loop `abandoned`, write a *second* sidecar\n * session, stamped later, whose `resolves` closes it (see below);\n * - repair known-broken brief fields, then backfill `task_seq`;\n * - copy `handoff.md` to `sources/handoff-archive.md`, then delete it;\n * - repair the two known-malformed session files (see `v3-repairs.ts`).\n *\n * **This module writes sessions via `writeSessionFile` directly rather than\n * through `wrap`, which `SKILL.md` otherwise names as the only session\n * writer.** `wrap` stamps `brief.updated = today()`. Running it 17 times would\n * mark every initiative touched today and destroy the exact staleness signal\n * the back-dating exists to preserve. This is the sanctioned exception; no\n * other caller should copy it.\n *\n * **Why abandonment takes a second session.** A loop that was already dead\n * when the handoff was written must still be *opened* — the ledger's job is to\n * show that it existed — and then closed by a decision that is itself dated.\n * Migrating it as live would leave a loop whose own text reads \"do not chase\"\n * aging in the ledger forever and tripping the 30-day warning. Since only a\n * strictly later session may resolve an earlier one's loops, the closing\n * session is stamped with the proposal's `abandoned_at` — a fixed value, not\n * the clock, because the filename derives from it and idempotence keys on the\n * exact path.\n *\n * Two-phase by construction: `planV2ToV3` builds and schema-validates every\n * initiative in memory and throws on the first problem; nothing is written\n * until the whole batch passes. A rejected `session_id` therefore fails before\n * anything lands rather than half way through, which matters because a\n * half-run leaves `.schema-version` un-bumped and the next CLI invocation\n * re-runs from the top.\n *\n * Idempotent by exact target path: every synthetic session has a deterministic\n * `started` + `session_id`, so its filename is reproducible and an existing\n * file is a skip — checked per session, so an interrupted run that wrote the\n * opening session but not the abandonment one completes correctly.\n * `writeSessionFile`'s own de-duplication (which appends `-1`) is deliberately\n * never allowed to fire; it would duplicate every migrated loop under fresh\n * refs on a re-run.\n *\n * Synthetic sessions never set `no_loops`. An empty ledger here means \"the\n * handoff had nothing extractable\", not \"the operator confirmed nothing is\n * hanging\", and the migration is not entitled to make the second claim.\n */\n\nconst HANDOFF_FILE = 'handoff.md';\nconst HANDOFF_ARCHIVE = path.join('sources', 'handoff-archive.md');\n\n/** Distinguishes the back-dated opening session from the later closing one. */\nexport type SessionKind = 'open' | 'abandon';\n\nexport type HandoffDisposition = 'archive-and-remove' | 'archive-exists' | 'absent';\n\nexport interface SessionPlan {\n kind: SessionKind;\n stem: string;\n path: string;\n frontmatter: SessionFrontmatter;\n body: string;\n exists: boolean;\n}\n\n/** A single validated brief write carrying both repairs and the backfill. */\nexport interface BriefWrite {\n frontmatter: BriefFrontmatter;\n body: string;\n /** Value written, or `null` when only field repairs applied. */\n taskSeq: number | null;\n repairs: string[];\n}\n\nexport interface InitiativePlan {\n slug: string;\n /** Empty when uncovered; one session normally; two when loops are abandoned. */\n sessions: SessionPlan[];\n /** Set when no proposal entry covers this initiative; no session is written. */\n uncoveredReason?: string;\n brief: BriefWrite | null;\n /** Set when the brief cannot be rewritten; skipped, not fatal. */\n briefBlocked?: string;\n handoff: HandoffDisposition;\n}\n\nexport interface MigrationPlan {\n proposalOrigin: string;\n initiatives: InitiativePlan[];\n repairs: RepairPlan[];\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function listInitiativeSlugs(activeRoot: string): Promise<string[]> {\n let entries;\n try {\n entries = await fs.readdir(activeRoot, { withFileTypes: true });\n } catch {\n return [];\n }\n const slugs: string[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith('.')) continue;\n if (await pathExists(path.join(activeRoot, entry.name, 'brief.md'))) {\n slugs.push(entry.name);\n }\n }\n return slugs.sort();\n}\n\n/**\n * Highest task number ever visible on disk, including `tasks/archive/`.\n * `task add` only scans `tasks/`, so archiving the highest-numbered task\n * currently lowers its allocation floor; seeding the high-water mark from\n * both directories closes that hole at the same instant as the reuse window.\n */\nasync function maxOnDiskTaskNumber(initiativeDir: string, prefix: string): Promise<number> {\n const re = new RegExp(`^${prefix}-(\\\\d+)\\\\.yml$`);\n const tasksDir = path.join(initiativeDir, 'tasks');\n let max = 0;\n for (const dir of [tasksDir, path.join(tasksDir, 'archive')]) {\n let names: string[];\n try {\n names = await fs.readdir(dir);\n } catch {\n continue;\n }\n for (const name of names) {\n const m = re.exec(name);\n if (m) max = Math.max(max, Number.parseInt(m[1]!, 10));\n }\n }\n return max;\n}\n\nasync function nextTaskSeq(\n initiativeDir: string,\n frontmatter: Record<string, unknown>,\n): Promise<number | null> {\n if (frontmatter.task_seq !== undefined) return null;\n const prefix = frontmatter.task_prefix;\n if (typeof prefix !== 'string' || prefix.length === 0) return null;\n const max = await maxOnDiskTaskNumber(initiativeDir, prefix);\n return max > 0 ? max : null;\n}\n\n/**\n * The brief to write, or `null` when nothing changes. Field repairs run first\n * so an initiative whose brief is currently invalid — `health`, which carries\n * an out-of-enum `state` — stops being skipped by the backfill.\n *\n * Spread-then-set preserves every other field, `updated` included: neither a\n * repair nor a backfill is a touch of the work.\n */\nasync function planBrief(\n initiativeDir: string,\n slug: string,\n): Promise<{ write: BriefWrite | null; blocked?: string }> {\n const raw = await readRawFrontmatter(path.join(initiativeDir, 'brief.md'));\n const repaired = repairBriefFrontmatter(slug, raw.frontmatter);\n const taskSeq = await nextTaskSeq(initiativeDir, repaired.frontmatter);\n if (taskSeq === null && repaired.applied.length === 0) return { write: null };\n\n const merged = {\n ...repaired.frontmatter,\n ...(taskSeq === null ? {} : { task_seq: taskSeq }),\n };\n // A brief still invalid for some *other* reason is reported and skipped: one\n // malformed brief must not block the other sixteen initiatives.\n const parsed = BriefFrontmatterSchema.safeParse(merged);\n if (!parsed.success) {\n return { write: null, blocked: `brief.md is invalid: ${parsed.error.message}` };\n }\n return {\n write: { frontmatter: parsed.data, body: raw.body, taskSeq, repairs: repaired.applied },\n };\n}\n\nasync function planHandoff(initiativeDir: string): Promise<HandoffDisposition> {\n if (!(await pathExists(path.join(initiativeDir, HANDOFF_FILE)))) return 'absent';\n // An archive already sitting next to a live handoff means a previous run\n // stopped mid-initiative, or the operator has begun the manual split. Either\n // way the archive is not ours to overwrite, and deleting the handoff without\n // archiving it would destroy the only copy.\n if (await pathExists(path.join(initiativeDir, HANDOFF_ARCHIVE))) return 'archive-exists';\n return 'archive-and-remove';\n}\n\nfunction buildOpenSession(entry: ProposalInitiative): Omit<SessionPlan, 'path' | 'exists'> {\n const frontmatter = SessionFrontmatterSchema.parse({\n session_id: entry.session_id,\n // A synthetic session is an instant, not an interval: it stands for a\n // state read off the handoff, so `started === ended`.\n started: entry.ended,\n ended: entry.ended,\n track: 'sidecar',\n // `abandoned` is proposal-only bookkeeping and must not reach the file.\n next_steps: entry.next_steps.map(({ abandoned: _abandoned, ...step }) => step),\n resolves: [],\n });\n const stem = buildSessionStem(entry.ended, entry.session_id);\n return { kind: 'open', stem, frontmatter, body: buildOpenBody(entry, stem) };\n}\n\nfunction buildAbandonSession(\n entry: ProposalInitiative,\n openStem: string,\n abandonedAt: string,\n): Omit<SessionPlan, 'path' | 'exists'> {\n const sessionId = `${entry.session_id}-abandonment`;\n const frontmatter = SessionFrontmatterSchema.parse({\n session_id: sessionId,\n started: abandonedAt,\n ended: abandonedAt,\n track: 'sidecar',\n next_steps: [],\n resolves: entry.next_steps\n .filter((step) => step.abandoned !== undefined)\n .map((step) => ({\n ref: `${openStem}#${step.id}`,\n outcome: 'abandoned' as const,\n note: step.abandoned!.note,\n })),\n });\n const stem = buildSessionStem(abandonedAt, sessionId);\n return {\n kind: 'abandon',\n stem,\n frontmatter,\n body: buildAbandonBody(entry, openStem, stem),\n };\n}\n\nconst PERMANENCE_NOTE = (stem: string): string =>\n `_This file is permanent. Deleting it frees the stem \\`${stem}\\` for reuse by` +\n ` any later session sharing its minute and \\`session_id\\`, silently` +\n ` retargeting every ref filed against it._`;\n\nfunction buildOpenBody(entry: ProposalInitiative, stem: string): string {\n return [\n entry.body.trimEnd(),\n '',\n '---',\n '',\n `_Synthetic session written by the v2→v3 open-loops migration from this` +\n ` initiative's \\`handoff.md\\` (archived at \\`sources/handoff-archive.md\\`)._`,\n PERMANENCE_NOTE(stem),\n '',\n ].join('\\n');\n}\n\nfunction buildAbandonBody(entry: ProposalInitiative, openStem: string, stem: string): string {\n const dead = entry.next_steps.filter((s) => s.abandoned !== undefined);\n return [\n '# Abandoned on arrival',\n '',\n `The v2→v3 open-loops migration opened ${entry.slug}'s loops in \\`${openStem}\\`,`,\n 'back-dated to its real last-touch. The items below were already dead when that',\n 'handoff was written — the window each depended on had closed — so this session',\n 'closes them immediately rather than leaving loops in the ledger that their own',\n 'text tells a future session not to chase.',\n '',\n ...dead.flatMap((step) => [`- \\`${openStem}#${step.id}\\` — ${step.abandoned!.note}`, '']),\n '---',\n '',\n PERMANENCE_NOTE(stem),\n '',\n ].join('\\n');\n}\n\nasync function locateSessions(\n activeRoot: string,\n slug: string,\n drafts: Array<Omit<SessionPlan, 'path' | 'exists'>>,\n): Promise<SessionPlan[]> {\n const located: SessionPlan[] = [];\n for (const draft of drafts) {\n const full = sessionFilePathForStem(slug, draft.stem, activeRoot);\n located.push({ ...draft, path: full, exists: await pathExists(full) });\n }\n return located;\n}\n\nfunction draftSessions(\n entry: ProposalInitiative,\n abandonedAt: string | undefined,\n): Array<Omit<SessionPlan, 'path' | 'exists'>> {\n const open = buildOpenSession(entry);\n const hasAbandoned = entry.next_steps.some((s) => s.abandoned !== undefined);\n if (!hasAbandoned) return [open];\n // Guaranteed by ProposalSchema's refinement; re-asserted so a future caller\n // constructing a Proposal by hand cannot skip the ordering guarantee.\n if (abandonedAt === undefined) {\n throw new ValidationError(\n `${entry.slug} marks a next_step abandoned but the proposal has no abandoned_at`,\n );\n }\n return [open, buildAbandonSession(entry, open.stem, abandonedAt)];\n}\n\nasync function planInitiative(\n activeRoot: string,\n slug: string,\n entry: ProposalInitiative | undefined,\n abandonedAt: string | undefined,\n): Promise<InitiativePlan> {\n const initiativeDir = path.join(activeRoot, slug);\n const brief = await planBrief(initiativeDir, slug);\n const base = {\n slug,\n brief: brief.write,\n ...(brief.blocked === undefined ? {} : { briefBlocked: brief.blocked }),\n handoff: await planHandoff(initiativeDir),\n };\n if (entry === undefined) {\n return { ...base, sessions: [], uncoveredReason: 'no entry in the migration proposal' };\n }\n return {\n ...base,\n sessions: await locateSessions(activeRoot, slug, draftSessions(entry, abandonedAt)),\n };\n}\n\nfunction assertProposalSlugsExist(proposal: Proposal, known: string[]): void {\n const set = new Set(known);\n const missing = proposal.initiatives.filter((i) => !set.has(i.slug)).map((i) => i.slug);\n if (missing.length > 0) {\n throw new ValidationError(\n `v2→v3 migration proposal names initiatives that do not exist: ${missing.join(', ')}`,\n );\n }\n}\n\n/**\n * Phase one. Reads everything, validates everything, writes nothing. Throws\n * on the first invalid entry so a bad proposal is a pre-run error.\n */\nexport async function planV2ToV3(activeRoot: string): Promise<MigrationPlan> {\n const { proposal, origin } = await loadProposal();\n const slugs = await listInitiativeSlugs(activeRoot);\n assertProposalSlugsExist(proposal, slugs);\n\n const byslug = new Map(proposal.initiatives.map((i) => [i.slug, i]));\n const initiatives: InitiativePlan[] = [];\n for (const slug of slugs) {\n initiatives.push(\n await planInitiative(activeRoot, slug, byslug.get(slug), proposal.abandoned_at),\n );\n }\n return { proposalOrigin: origin, initiatives, repairs: await planRepairs(activeRoot) };\n}\n\nasync function archiveHandoff(initiativeDir: string): Promise<void> {\n const source = path.join(initiativeDir, HANDOFF_FILE);\n const target = path.join(initiativeDir, HANDOFF_ARCHIVE);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.copyFile(source, target);\n await fs.rm(source);\n}\n\nasync function writePlannedSession(\n activeRoot: string,\n slug: string,\n session: SessionPlan,\n): Promise<void> {\n const fm = session.frontmatter;\n await writeSessionFile({\n slug,\n activeRoot,\n session_id: fm.session_id,\n started: fm.started,\n ended: fm.ended,\n track: fm.track,\n next_steps: fm.next_steps,\n resolves: fm.resolves,\n body: session.body,\n });\n}\n\nasync function applyInitiative(activeRoot: string, plan: InitiativePlan): Promise<void> {\n const initiativeDir = path.join(activeRoot, plan.slug);\n await withFileLock(path.join(initiativeDir, '.lock'), async () => {\n // Ordered: the opening session must exist before the one that resolves it.\n for (const session of plan.sessions) {\n if (session.exists) continue;\n await writePlannedSession(activeRoot, plan.slug, session);\n }\n if (plan.brief !== null) {\n await writeFrontmatter(\n path.join(initiativeDir, 'brief.md'),\n plan.brief.frontmatter,\n plan.brief.body,\n BriefFrontmatterSchema,\n );\n }\n if (plan.handoff === 'archive-and-remove') {\n await archiveHandoff(initiativeDir);\n }\n });\n}\n\n/** Phase two. Writes only what phase one already validated. */\nexport async function applyV2ToV3(activeRoot: string, plan: MigrationPlan): Promise<void> {\n for (const initiative of plan.initiatives) {\n await applyInitiative(activeRoot, initiative);\n }\n for (const repair of plan.repairs) {\n await applyRepair(activeRoot, repair);\n }\n}\n\nexport const v2ToV3OpenLoops: Migration = {\n from: 2,\n to: 3,\n description: 'Retire handoff.md into synthetic back-dated open-loop sessions',\n async run(activeRoot: string): Promise<void> {\n const plan = await planV2ToV3(activeRoot);\n await applyV2ToV3(activeRoot, plan);\n },\n};\n\nexport { KNOWN_REPAIRS };\nexport default v2ToV3OpenLoops;\n","import { promises as fs } from 'node:fs';\nimport { z } from 'zod';\nimport { ValidationError } from '../errors.js';\nimport { NextStepSchema, SessionIdSchema } from '../schemas/session.js';\nimport { V3_OPEN_LOOPS_PROPOSAL } from './data/v3-open-loops-proposal.js';\n\n/**\n * The data file the v2→v3 migration consumes.\n *\n * The migration is deliberately mechanical: it does not read handoff prose,\n * does not infer back-dates, and does not decide what a loop is. Those are\n * per-initiative judgement calls made ahead of time and recorded here, so the\n * code that touches the operator's data has no discretion left in it.\n */\n\n// A synthetic `session_id` also becomes part of the filename and the first\n// half of every ref the session mints. The schema-level rule only bans\n// `#`, whitespace and `/`; kebab-case is narrower on purpose, because a\n// hand-authored proposal naturally reaches for spaces and slashes and the\n// resulting failure would otherwise land mid-run.\nconst KEBAB_SESSION_ID = SessionIdSchema.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, {\n message: 'session_id must be kebab-case ([a-z0-9-], no leading/trailing dash)',\n});\n\nconst ISO_INSTANT = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/;\n\n/**\n * A loop that is dead on arrival — the handoff recorded it, but the window it\n * depended on has since closed. It is still *opened* by the back-dated session\n * (the ledger should show it existed) and then closed by a second, later\n * session carrying this note. Recording it as live would leave a loop whose\n * own text says \"do not chase\" sitting in the ledger forever.\n */\nconst AbandonedSchema = z.object({ note: z.string().min(1) });\n\nconst ProposalNextStepSchema = NextStepSchema.extend({\n abandoned: AbandonedSchema.optional(),\n});\n\nconst ProposalInitiativeSchema = z.object({\n slug: z.string().min(1),\n /**\n * Real last-touch of the initiative, hand-supplied. Never `Date.now()` and\n * never file mtime — several initiatives have mtimes months adrift from\n * their true last-touch, and the whole point of back-dating is to preserve\n * the staleness signal.\n */\n ended: z.string().regex(ISO_INSTANT, {\n message: 'ended must be an ISO 8601 instant with timezone',\n }),\n session_id: KEBAB_SESSION_ID,\n body: z.string().min(1),\n next_steps: z.array(ProposalNextStepSchema).default([]),\n});\n\nexport const ProposalSchema = z\n .object({\n /**\n * When the abandonment decision was made. Hand-supplied rather than read\n * from the clock: the second session's filename derives from it, and the\n * migration keys idempotence on exact paths, so `Date.now()` would mint a\n * fresh path — and a duplicate abandonment session — on every re-run.\n */\n abandoned_at: z\n .string()\n .regex(ISO_INSTANT, {\n message: 'abandoned_at must be an ISO 8601 instant with timezone',\n })\n .optional(),\n initiatives: z.array(ProposalInitiativeSchema),\n })\n .superRefine((value, ctx) => {\n const withAbandoned = value.initiatives.filter((i) =>\n i.next_steps.some((n) => n.abandoned !== undefined),\n );\n if (withAbandoned.length === 0) return;\n if (value.abandoned_at === undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['abandoned_at'],\n message: 'abandoned_at is required when any next_step is marked abandoned',\n });\n return;\n }\n // Only a strictly later session may resolve an earlier one's loops.\n const at = new Date(value.abandoned_at).getTime();\n for (const initiative of withAbandoned) {\n if (at <= new Date(initiative.ended).getTime()) {\n ctx.addIssue({\n code: 'custom',\n path: ['abandoned_at'],\n message:\n `abandoned_at (${value.abandoned_at}) must be strictly after ` +\n `${initiative.slug}'s ended (${initiative.ended}), or the abandonment ` +\n 'session cannot resolve the loops it opens',\n });\n }\n }\n });\n\nexport type ProposalInitiative = z.infer<typeof ProposalSchema>['initiatives'][number];\nexport type ProposalNextStep = z.infer<typeof ProposalNextStepSchema>;\nexport type Proposal = z.infer<typeof ProposalSchema>;\n\n/** Env var pointing at a JSON proposal, overriding the bundled default. */\nexport const PROPOSAL_PATH_ENV = 'AW_V3_PROPOSAL';\n\nfunction parseProposal(input: unknown, origin: string): Proposal {\n const result = ProposalSchema.safeParse(input);\n if (!result.success) {\n throw new ValidationError(\n `Invalid v2→v3 migration proposal (${origin}): ${result.error.message}`,\n );\n }\n const seen = new Set<string>();\n for (const initiative of result.data.initiatives) {\n if (seen.has(initiative.slug)) {\n throw new ValidationError(\n `Invalid v2→v3 migration proposal (${origin}): duplicate slug ${initiative.slug}`,\n );\n }\n seen.add(initiative.slug);\n }\n return result.data;\n}\n\n/**\n * Load and validate the proposal. Prefers `$AW_V3_PROPOSAL` (a JSON file) so\n * the operator can stage and dry-run a revised proposal without a rebuild;\n * otherwise uses the copy bundled with this release.\n */\nexport async function loadProposal(): Promise<{ proposal: Proposal; origin: string }> {\n const override = process.env[PROPOSAL_PATH_ENV];\n if (override !== undefined && override.length > 0) {\n let raw: string;\n try {\n raw = await fs.readFile(override, 'utf8');\n } catch {\n throw new ValidationError(`${PROPOSAL_PATH_ENV} points at an unreadable file: ${override}`);\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw new ValidationError(\n `${PROPOSAL_PATH_ENV} is not valid JSON (${override}): ${(err as Error).message}`,\n );\n }\n return { proposal: parseProposal(json, override), origin: override };\n }\n return {\n proposal: parseProposal(V3_OPEN_LOOPS_PROPOSAL, 'bundled'),\n origin: 'bundled',\n };\n}\n","/**\n * Per-initiative input to the v2→v3 open-loops migration.\n *\n * Authored by hand (one pass per initiative, reviewing its `handoff.md`), not\n * generated at run time. Typed `unknown` so it can only be used after passing\n * `ProposalSchema` — the migration validates the whole batch before it writes\n * anything, and a data file that typechecks is not thereby trusted.\n *\n * Shape: see `ProposalSchema` in `../v3-proposal.ts`.\n *\n * `ended` is each initiative's real last-touch, and never the clock. It is\n * normally read off the handoff's own content; where that is silent it is\n * taken from the covering session's recorded `ended`, and only as a last\n * resort from file mtime (many mtimes are months adrift from the true\n * last-touch, which is exactly what back-dating exists to preserve). The\n * loops below are therefore born already aged, and the eight initiatives last\n * touched in May trip the 30-day stale-loop warning on day one. That is the\n * intended outcome, not a defect.\n *\n * A `next_step` carrying `abandoned` is opened by the back-dated session and\n * then closed by a second session stamped `abandoned_at`, so the ledger shows\n * the loop existed and shows who killed it.\n *\n * An initiative absent from this list is SKIPPED: its `handoff.md` is still\n * archived to `sources/handoff-archive.md`, but no synthetic session is\n * written and its next-actions do not enter the ledger. The migration reports\n * every such skip loudly rather than guessing at content.\n *\n * ## Refreshed 2026-07-29 (AW-65)\n *\n * This file was authored 2026-07-28 12:28, *mid-session* for several\n * initiatives, and four of them then kept working and rewrote the handoff it\n * had just been derived from: `relay`, `active-work`, `claude-channels` and\n * `voltras-workspace`. Those four entries were re-derived against the handoffs\n * as they then stood; the other 13 predate 12:28 and are untouched. Each\n * changed entry carries a comment saying what moved and why.\n *\n * **It then had to happen a SECOND time the same day.** Between the refresh and\n * the apply window, further sessions rewrote `relay` (19:27Z) and\n * `voltras-workspace` (19:09Z) again, closed `R-24` and `CC-31`, and merged\n * `VMCP-01.72` part (a). A hand-authored proposal cannot stay current for an\n * initiative that is being actively worked: **re-validate immediately before\n * applying, in a window where nothing else is running, and treat any gap\n * between refresh and apply as invalidating.** The mechanical checks below are\n * the cheap part; the content drift is not.\n *\n * Four rules these passes established, worth keeping if this is ever redone:\n *\n * - **A loop for finished work cannot be expressed here.** The only resolve\n * this file can emit is `abandoned` (`v2-to-v3-open-loops.ts`), so a loop\n * whose work *completed* must be DROPPED, never marked abandoned — that\n * would invert the distinction AW-59 added.\n * - **`kind: pr` never auto-resolves.** Bootstrap leaves `mergedPrs`\n * unsupplied on purpose to stay offline (`bootstrap/prompt.ts`), so a PR\n * loop hangs forever regardless of merge state. Prefer prose.\n * - **Never point a loop at a `done` task whose work is not done.** It\n * auto-resolves on arrival and deletes the item from the ledger silently.\n * `claude-channels` teleport is the live example: CC-20 covered the design\n * and is closed, but the implementation — second on that board — has no\n * open task, so it is carried as prose.\n * - **Re-check every `kind: task` ref against task STATUS at apply time, not\n * just existence.** `relay` n9 pointed at R-24, which closed hours after the\n * first refresh; the loop would have vanished on arrival and taken the\n * recurring obligation with it (it is prose now). Where a task closes and the\n * work genuinely is finished, DROP the loop instead — filing one that\n * auto-resolves is noise, which is why `claude-channels` n1 is gone.\n */\nexport const V3_OPEN_LOOPS_PROPOSAL: unknown = {\n abandoned_at: '2026-07-28T18:00:00Z',\n initiatives: [\n {\n slug: 'active-work',\n // DELIBERATELY NOT the handoff's last-touch (2026-07-28T18:52Z), unlike\n // every other entry refreshed on 2026-07-29. The 2026-07-28 session\n // rewrote this handoff end to end, and the rewrite silently dropped the\n // miner/release thread below — AW-23, AW-28 and AW-34 are all still\n // `status: open` and appear nowhere in the current file. 2026-07-15 is\n // their real hang date; `tasks/` records no such thing. Stamping this\n // session 07-28 would reset that age to zero and defeat the back-dating.\n //\n // The current handoff's own next-actions (AW-65, AW-38, inbox) are NOT\n // migrated here: the 2026-07-28 and 2026-07-29 wraps already filed them\n // as live loops, and re-filing would double-count them — the specific\n // hazard AW-65 was raised to catch.\n ended: '2026-07-15T00:00:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-07-15\\n\\nSession-mining tooling now lives in active-work, its proper home, and the miner roadmap is moving. active-work is published to npm as `@titan-design/active-work@0.1.0`; `main` is clean.\\n\\nTwo PRs are open, neither merged: **active-work#56** (`feat/session-miner-tooling` — the byte-identical miner port into `tools/`, plus AW-24 cost rollups and AW-27 the eval harness, both done) and **titan-design#110** (the design-repo copy, reduced to dashboard specimens). The eval immediately caught a real miner bug — junk branch names `/` and `HEAD:main` — filed as AW-34.\\n\\nThe v0.1 publish shipped under the org scope, not the planned `@hjewkes` scope, and releasing is now tag-triggered OIDC trusted publishing (#54) with changesets removed (#55). The first tagged run has never been exercised end to end.\\n\\nOne pre-existing flake: `__tests__/server/file-watch.test.ts` (timing/debounce, matches AW-12), passes on re-run.\\n\\n_This state is 13 days behind the initiative's newest real session (2026-07-28)._\\n\\n_Refreshed 2026-07-29 (AW-65): the 2026-07-28 handoff rewrite dropped this thread without closing it, so it is carried here from the 07-15 state and ages from there. PR #56 merged 2026-07-29 and its loop was removed rather than migrated._\",\n next_steps: [\n {\n id: 'n1',\n text: 'AW-28 Drain error-atlas sourcing (est 8) is the next miner build and the first piece to land in src/ as real TypeScript — native Drain port, do not shell to Python. Recipe in sources/deepdive-session-mining-build-specs.md §C1.',\n kind: 'task',\n ref: 'AW-28',\n },\n {\n id: 'n2',\n text: 'AW-34 is the quick one (est 2) — fix the junk branch names the eval caught, then regression-check with `pnpm eval:miner`.',\n kind: 'task',\n ref: 'AW-34',\n },\n {\n id: 'n3',\n text: \"AW-23 production session-signal index (est 8) is now unblocked by AW-27's eval gate and unlocks the Phase-3 backlog AW-29 through AW-33.\",\n kind: 'task',\n ref: 'AW-23',\n },\n // n4 (merge active-work#56) is deliberately absent. The PR merged\n // 2026-07-29T03:46:53Z, so the loop is dead on arrival — but it\n // *completed*, and this file can only express `abandoned`\n // (v2-to-v3-open-loops.ts:261). Recording a merged PR as abandoned\n // would invert the very distinction AW-59 added. Nor can it be left\n // live: bootstrap leaves `mergedPrs` unsupplied on purpose so\n // derivation stays offline (bootstrap/prompt.ts:743), so a `kind: pr`\n // loop never auto-resolves and this one would hang forever. Dropped.\n {\n id: 'n5',\n text: 'Merge titan-design#110 — the design-repo copy with miner tools removed; the lab/active-work-dashboard branch is pushed as a full-history archive. Verified still open 2026-07-29 (active-work#56, its former companion, has since merged).',\n kind: 'prose',\n },\n {\n id: 'n6',\n text: 'Eyeball the first tagged release run: it is the first real end-to-end exercise of the OIDC trusted-publisher config, and nothing has pushed a vX.Y.Z tag yet.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'ai-investing-workflow',\n ended: '2026-05-26T23:59:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-05-26\\n\\nResearch phase complete. Three async agents (institutional ceiling, retail toolkit, empirical edge) reported and were synthesized into a unified position. The prior hypothesis — \\\"retail can't compete with institutional AI\\\" — was confirmed half-right and refined: the right benchmark is the median active fund (which most institutions also lose to) and one's own un-AI'd behaviour, not Citadel.\\n\\nNext phase is execution: pick sources to subscribe to, decide tooling spend, build 2–3 concrete LLM workflows (10-K diff, earnings-call execution-credibility, pre-mortem) and establish behavioural guardrails before any of it touches real capital decisions.\\n\\nCore allocation stays passive/indexed regardless. This work is about being a more literate observer of macro, and possibly supporting a small active sleeve in small/mid-cap names where AI-assisted research can plausibly close information gaps.\\n\\nNothing has moved since. Eight AIW-* tasks are filed and all are open.\",\n next_steps: [\n {\n id: 'n1',\n text: 'Decide: pay for FT now, or trial the free Overshoot + Slok weekly deck first. This gates AIW-1 and is the only thing standing between research and execution.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Answer whether an active sleeve exists today or the small-active-sleeve idea is still entirely hypothetical — everything downstream is sized by this.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Confirm whether direct indexing is already in place in the tax-advantaged accounts before evaluating Wealthfront/Betterment (the measured after-tax uplift is ~1.8%).',\n kind: 'task',\n ref: 'AIW-6',\n },\n ],\n },\n {\n slug: 'audiobook',\n ended: '2026-07-26T00:00:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-07-26\\n\\nThe autopull pipeline (main track) runs fully unattended and is healthy. Book 7 is complete, 12/12 chapters exported. No open engineering blockers on either track.\\n\\nA separate `feat/tts-quality` branch (local, unpushed, HEAD `6680bee`, 153 tests passing) carries TTS-quality work: chunker boundary-hallucination fix, currency/decimal/punctuation normalization, stats-table roster rephrasing, self-heal of hallucinated takes wired into the worker (~68% babble reduction), and a new MP3→m4b packaging tool. The Book 7 Ch 16 appendix was re-rendered clean and replaced in the R2 feed on 2026-07-23 (stable GUID — delete+refresh in Overcast to re-pull).\\n\\nThe m4b tool delivered Soccer Supremo Book 1 as two m4bs in `~/Downloads/Soccer Supremo 1/`, awaiting an Apple Books playback check.\\n\\nPRs #4, #5 and #6 are merged to main with green CI: the pipeline event store + FastMCP server, the book-discovery gap plus lock cleanup, and the cheap precheck gate at a 15-minute cadence.',\n next_steps: [\n {\n id: 'n1',\n text: 'Close the partial-generation recovery gap: a chapter downloaded + normalized + chunked but interrupted mid-TTS (has normalized.txt, no audio.wav) is not re-picked by the precheck or find_new_chapters — both key off raw-without-normalized.',\n kind: 'task',\n ref: 'A-2',\n },\n {\n id: 'n2',\n text: '/api/scraper/preview returns 422 — fiction_id is declared a Path param but is absent from the route path. Latent; unused by autopull.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: \"Decide the fate of parked code: PR #1's cloud infra (Docker/k8s/Terraform/S3/SQS/Postgres) contradicts the single-user filesystem-only design and sits under parked/ — keep as reference or delete. The dialogue/speaker module is parked too; revive only if wanted.\",\n kind: 'prose',\n },\n {\n id: 'n4',\n text: \"Check Soccer Supremo Book 1's two m4bs actually play in Apple Books — the AAC-vs-MP3-remux split exists precisely because Apple Books plays MP3-in-m4b silent, and this was never confirmed.\",\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'brain',\n ended: '2026-05-12T00:00:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-05-12\\n\\nHEAD is on `spike/2026-05-platform`, pointing at the same SHA as `main` (`6da9d96`, 2026-05-02). Two active tracks.\\n\\n**Platform redesign spike** — Spike 1 critical-subset checkboxes pass. Restate + Claude Agent SDK + a custom YAML compiler validated end to end across 10 packages, ~3,500 LOC, 42 unit tests, 3 e2e smokes (cancellation reaches the Claude Code child in 201ms; the planning workflow walks 4 nodes in 22ms). `07-spike-1-decision-memo.md` recommends adopting Path 1.\\n\\n**Main-line autonomy/PM work** — the last 30 commits on main are VNM-56 worktree/merge-lifecycle (#215–#221) and VNM-48 dispatch/file-ownership. Phase 1 stabilization is done; Phase 2 (parallel dispatch on real workstreams) is unblocked.\\n\\nThe working tree is dirty in a non-trivial way: ~80+ untracked files under `docs/plans/` and `docs/pm-module/diagnostic/v*`, plus a top-level `platform-redesign-2026-05.zip` (358K) and a mirror directory duplicating content already in the repo.\\n\\n⚠️ Contested since: titan-platform\\'s 2026-07-13 round-2 research concluded the spike is a **design, not a built or adopted platform**, and that the \"decision memo\" framing was wrong.',\n next_steps: [\n {\n id: 'n1',\n text: 'Read docs/architecture/2026-05-platform-redesign/07-handoff-spike-1-continuation.md and 07-spike-1-decision-memo.md first — they are the freshest authoritative state — then spike-1-notes.md for per-checkbox status.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: \"THE gating decision: adopt Path 1 and scope a migration of src/modules/workflow/ (and consumers) onto the spike's Step contract + Restate; or defer and keep investing in the homegrown runtime; or abandon the spike. Deferred items are enumerated in the decision memo § 'What's deferred to migration'. Weigh this against titan-platform's later finding that the spike was never actually adopted.\",\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'If continuing the spike: (3) HITL awakeable wiring is the highest-value remaining critical-subset coverage; (4) real leaves and (5) parallel-spawn fan-out make the artifact stronger. The side-by-side and decision memo are already written.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'If executing the migration: scope which existing modules (pm, agents, sessions, workflow, codebase) become leaves on the Step contract vs stay outside it. Side-by-side §5 enumerates the surfaces.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'Housekeeping on the dirty tree: classify docs/plans/* (commit canonical, gitignore ephemeral — pattern set by #210 691fcf1), then decide whether platform-redesign-2026-05.zip and its mirror dir are a discardable backup or content to commit.',\n kind: 'prose',\n },\n {\n id: 'n6',\n text: 'Root-cause the embedding dimension mismatch (Expected 384 dimensions but received 768) that intermittently breaks PM-via-MCP — likely DB-init vs embedder-config drift. Not blocking via CLI but it degrades autonomy.',\n kind: 'prose',\n },\n {\n id: 'n7',\n text: 'Reconcile PM state: three tasks from the 2026-04-27 parallel test still show in-progress/stuck despite merged PRs. Verify #218 (VNM-56.71) actually cleared the backlog, or file a follow-up.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'claude-channels',\n // Refreshed 2026-07-29 (AW-65). Was 2026-07-28T16:29:00Z — authored\n // mid-session, ~2.7h before the covering session's own recorded\n // `ended: 2026-07-28T19:10:00Z`, and before CC-30 closed, CC-31 was\n // filed and teleport was designed. Anchored to the session's end.\n ended: '2026-07-28T19:10:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-07-28\\n\\n**Agent teams work.** CC-17 closed: a spawned agent is a durable, addressable peer that outlives its spawner, launchable headless or in a terminal under normal permissions — and spawned agents have now done real work (one found a lifecycle race, three found a security gap, two live defects, a false test). **CC-30 closed** too: ordinary sessions now have durable identity.\\n\\n`feat/plugin-packaging` pushed at `a12c1fc`, clean tree, 323 tests green, tsc and prettier clean. The broker runs properly detached in its own process group, so it survives the session that started it. **CC-24 closed** — the headless hang is gone, and the fix was not A8's stream.jsonl: the streams are discarded, because Claude Code already writes a full structured transcript per session and we assign the session id ourselves. §9 and A8 in agent-teams.md are marked superseded.\\n\\n**CC-28 has since closed**, so confinement is real and the planned wave items stand on their own. Confinement turned out to be schema-level: a denied tool is ABSENT from the model's schema rather than refused, so there is **no denial frame at all** for a toolset-confined agent — whereas settings-level denials ARE observable (`is_error: true` plus a `toolDenialKind` marker). Any feature here must say which of the two it covers.\\n\\n**CC-31 is the most important new finding of the session:** severing a session's bus produces no noticeable dead bus — Claude Code restarts the MCP server and the session ends up silently absent from a *working* bus, unable to tell.\\n\\nTeleport (CC-20) is now fully designed, with all five decisions recorded in the task, but **not implemented**.\\n\\nThe title is legacy: the subject is general agent orchestration, and the logic will eventually fold into relay. Keep the orchestration logic separable from the local broker / event log / registry.\\n\\n_Refreshed 2026-07-29 (AW-65) against the handoff as it stood at session close._\",\n next_steps: [\n // The original n1 (build the live-spawn harness) duplicated n4's CC-27\n // content and was dropped. The first 2026-07-29 pass replaced it with\n // CC-31, the handoff's \"Top of the board\" item — and CC-31 then CLOSED\n // later the same day: re-measured, the `CLAUDE_CODE_SESSION_ID` gate\n // answered, and the two failure states it had conflated separated.\n // Leaving it as a task ref would file a loop that auto-resolves on\n // arrival and never surfaces, so the slot is simply empty. Nothing is\n // lost: this initiative's 14:32 session filed four live loops through\n // `wrap`, so its current work is already in the ledger.\n {\n id: 'n2',\n text: 'CC-25 — the spawn-rate budget §11.3 promises and that does not exist. Named as a §11 defence that turned out to be prose.',\n kind: 'task',\n ref: 'CC-25',\n },\n {\n id: 'n3',\n text: 'CC-26 — agent_ready + spawnedBy. Design is fully worked out in the task and the subscription machinery shipped in bd31bad, so this is one protocol selector plus a default.',\n kind: 'task',\n ref: 'CC-26',\n },\n {\n id: 'n4',\n text: 'CC-27 — the opt-in iTerm placement test EXISTS (83271dd) but has never had a clean verified end-to-end run; it was stopped partway, on purpose. Run it cleanly and unattended. It stays gated behind an env var so it never fires on CI or by default — that gating is load-bearing, since an ungated iterm-pane test once opened real windows on the laptop (fixed in aa08d86). Do not hand this to an agent: it takes focus (see the ~20-run incident).',\n kind: 'task',\n ref: 'CC-27',\n },\n {\n id: 'n5',\n text: 'CC-29 needs a DECISION, not more probing — its empirical half is closed (two live probes settled it 2026-07-28). Pairing option (2) `agent logs`, settings-level only, with option (4) surface deny lists at spawn time covers both failure kinds; either alone covers only one.',\n kind: 'task',\n ref: 'CC-29',\n },\n {\n id: 'n6',\n // Deliberately `prose`, NOT `kind: task, ref: CC-20`. CC-20 is\n // `status: done` — it covered the DESIGN — but teleport is not\n // implemented: the handoff ranks it second on the board and its\n // branch `feat/teleport-identity` is 6 commits UNPUSHED. A task ref\n // here would auto-resolve on migration and delete the #2 item from\n // the ledger without anyone deciding to. No open task represents\n // the implementation; this loop is the only thing carrying it.\n text: \"Implement teleport — second on the board behind CC-31. It is fully DESIGNED (CC-20, now closed; all five decisions recorded there), but NOT built: branch `feat/teleport-identity` is 6 commits and UNPUSHED, main untouched on purpose. No open task covers the implementation. Related: CC-23 (headless↔terminal switching) rides the same substrate and is partly gated on CC-29, since 'notice an agent is stuck and surface it into a terminal' presupposes noticing.\",\n kind: 'prose',\n },\n // Old n7 (Service Steps 3/4 parallelism) dropped: \"Service Steps\",\n // \"CLI restructure\" and \"HTTP reads\" appear nowhere in the current\n // 93-line handoff, and nothing else corroborates them. Migrating an\n // unverifiable loop would put a permanently unanswerable item in the\n // ledger; the text survives in sources/handoff-archive.md if needed.\n ],\n },\n {\n slug: 'codewatch',\n ended: '2026-07-06T23:49:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-07-06 (session 30 wrap)\\n\\nShipped the C-88 gate(a) query-time capability surface the session-29 gates authorized — PR #121, self-merged once CI went green under standing authorization.\\n\\n`packages/graph/src/embeddings.ts` + migration v5 add an `embedding` table content-addressed by (model, text_hash), deliberately not snapshot-scoped: vectors are found by rebuilding text→hash at read time, so incremental reuse is free (843/843 reused, zero ollama calls), vectors never duplicate across snapshots, and the indexer is untouched. New `graph embed`, `graph index --embed`, and `graph similar <intent>` returning top-K candidates-not-verdicts. Read API 1.1.0→1.2.0 plus MCP `find_similar`. 1276 tests green, typecheck clean, fitness gate 0-new.\\n\\nAn owner-directed injection eval ran the same session (sources/c88-injection-eval.md). Verdict: the duplication-prevention delta is SMALL on the documented surface — A0 already reuses 9/12. The real measured value is −28% cost ($8.82→$6.31) and 19.5→16.1 avg turns as the search phase collapses, plus A1 consolidating tRPC\\'s real getQueryKeyInternal twin-duplication onto one shared impl.\\n\\nThe file below this block was ~1,750 lines of reverse-chronological session diary back to 2026-07-04; every \"NEXT\" in it was acted on by the following session.',\n next_steps: [\n {\n id: 'n1',\n text: \"C-88 gate(b), cost-gated: coarse hierarchical Leiden on the resolved file graph → LLM community summaries at capability altitude → a 'how does this repo do X' convention surface, reusable for the C-90 bundle. Gate on a cost budget — summarize the coarse level only, or lazily.\",\n kind: 'task',\n ref: 'C-88',\n },\n {\n id: 'n2',\n text: 'C-92 codewatch plugin (injection delivery), now evidence-framed by the injection eval: a SessionStart/plan-time hook injecting find_similar + context. Frame the value as cost/latency/reliability and consolidation, NOT duplication prevention.',\n kind: 'task',\n ref: 'C-92',\n },\n {\n id: 'n3',\n text: 'C-90 compact context-bundle (p7) — ranked file-line citations, and it can now include similar-capability candidates.',\n kind: 'task',\n ref: 'C-90',\n },\n {\n id: 'n4',\n text: 'These three were an explicit pick-ONE, not a queue. Conditional: the duplication-prevention claim needs the undocumented surface (where sig-only retrieval is also weaker) — only build that stratified eval if C-92 ships.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'OPERATOR-ONLY, orphaned: the npm publish is still not done. C-6 shipped a publish-READY distribution (all 7 packages, verified end-to-end via local verdaccio) but the actual publish needs the @codewatch npm org/scope created plus auth, then `pnpm release` or the Release action with dry_run=false and an NPM_TOKEN secret. C-6 is closed, so this lives in no task.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'computer-organization',\n ended: '2026-05-12T00:00:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-05-12\\n\\nInitiative scaffolded from the `aw discover` triage pass. 22 per-directory triage tasks filed (CO-1..CO-22), all open, severity low, priority matching the CO number. Nothing decided yet — every legacy directory is still sitting in ~/Documents/projects/ untouched.\\n\\nState is `backburner`: this drains opportunistically, not on a deadline. All work happens on the filesystem; no repo, no CI, no tests.\\n\\nThe one thing that exists here and nowhere else is the first-pass triage judgment — which specific directories are obvious deletes, which are obvious archives, and which need investigation before anything is touched. The CO-*.yml tasks are all still generically titled \"archive, integrate, or delete\" with no disposition recorded, so the calls below are the only record of that work.',\n next_steps: [\n {\n id: 'n1',\n text: 'Pick ONE canonical archive destination (e.g. ~/Documents/projects/.archive/ vs an external cold-storage path) and record it before moving anything, or the triage fragments across destinations.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Fast-DELETE candidates from the first pass, pending spot-check: `test` (CO-16), `bookmarks-demo` (CO-2), `webfetch` (CO-21).',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Fast-ARCHIVE candidates from the first pass: `experimentation_docs` (CO-5), `rp-university-transcripts` (CO-14), `kaizen-analysis` (CO-10).',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'Investigate the three name-collision dirs — `titan-design` (CO-18), `voltras` (CO-19), `workflow-improvement` (CO-22) — by reading README and git log to establish their relationship to the live counterparts, then decide confirm-then-merge vs treat-as-stale-and-delete.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'Decide the home-infra consolidation question: promote `home` (CO-7), `home_server` (CO-8) and `homeassistant_samba` (CO-9) into one initiative and close all three with pointers, or triage each in isolation.',\n kind: 'prose',\n },\n {\n id: 'n6',\n text: 'Decide whether the container dirs `nd projects` (CO-12), `personal_projects` (CO-13) and `split_projects` (CO-15) need their own sub-triage or can be classified wholesale.',\n kind: 'prose',\n },\n {\n id: 'n7',\n text: 'Then work the remaining CO tasks individually, recording the chosen disposition in each YAML before any destructive operation, and re-run `aw discover` after each batch to confirm dirs have dropped off the untracked list.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'denver-rezzy',\n ended: '2026-05-12T00:00:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-05-12\\n\\nPhase 1 skeleton complete and exercised end to end on **synthetic data**. The MCP server boots, all three tools (search_restaurants, get_restaurant, auth_status) work over stdio, and orchestrator + caching + ranking + tool plumbing are real. The vitest MCP-handshake smoke test passes.\\n\\nResy and OpenTable probes still return stub data behind REZZY_USE_STUB_RESY / REZZY_USE_STUB_OPENTABLE. The Tock probe deliberately errors as \"Phase 3, not implemented\".\\n\\nMost recent source-tree activity ran Apr 30 → May 2: src/commands/seed.ts, scripts/discover-resy.mjs and scripts/verify-opentable-rids.mjs modified May 2; src/probes/resy/ folder mtime May 2 05:31; src/core/search.ts updated May 2 06:21. It reads as mid-Task-4 (platform-listings backfill) with early Resy probe scaffolding underway.\\n\\n**There is no .git/ directory.** Nothing is committed anywhere; the work lives only on disk, so Task 4\\'s actual completion state can only be established by querying the database. This handoff was the sole record of the remaining Phase 1 plan — tasks/ was empty.',\n next_steps: [\n {\n id: 'n1',\n text: 'Before writing any code, inventory what already exists — no git means the DB is the only evidence. Run `npm run dev auth-status`, `SELECT count(*) FROM platform_listings` (target >= 40), and diff src/probes/resy/index.ts against the stub to see how much of Task 2 is already there.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Decide on git initialization, recommended before any further change, and what the initial commit should encompass. Without it there is no rollback, no diff and no branch isolation for the Resy / OpenTable implementations.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Auth is not captured: `rezzy auth-status` will be empty for resy and opentable until `rezzy auth-capture <platform>` is run, and that is required before Tasks 2/3 can produce real data.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'Phase 1 remainder, in order: real Resy probe (ref lgrees/resy-cli) → real OpenTable probe (mobile-api.opentable.com/api/v3/restaurant/availability, ref jonluca/OpenTable-Reservation-Maker) → backfill platform_listings for the 29 seed restaurants using the existing discover/verify scripts, flagging likely Tock-only venues (Beckon, Bruto, Margot, Kizaki) → flip both stub toggles to false and run the end-to-end real-data smoke test in Claude Desktop. Proposed as DR-1..DR-7.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: \"Run `npm run typecheck` before declaring any task done, per the repo's CLAUDE.md.\",\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'health',\n ended: '2026-07-27T22:59:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-07-27\\n\\nScope decided and the first two builds shipped. `/Users/hjewkes/Documents/health` is live: TypeScript, 35 tests passing, typecheck and production build clean, three commits on branch `feat/macro-calculator` — unmerged, nothing pushed, there is no remote.\\n\\n**Macro planner** (src/core/) — a pure calculation chain ported from the weight-loss spreadsheet: composition → Katch-McArdle BMR → TDEE → deficit → macro split → projection, composed by buildPlan(). A golden test reproduces the spreadsheet's figures exactly. The projection bug is fixed: the sheet extrapolated a fixed daily loss, but the target is a percentage of current bodyweight, so the curve is exponential — the estimate moves from 110 days (Nov 14) to 117 days (Nov 21), and both are shown in the minimal web UI in src/ui/.\\n\\n**Instacart ingest** (src/ingest/instacart/) — parses order receipts out of Gmail into structured orders, plus a merge step repairing email-truncated item lists from the web receipt. 33 orders parsed; the last 20 Costco orders at full coverage (287 items, 2025-05 → 2026-07, $5,243).\\n\\nNext session was to be meal planning.\",\n next_steps: [\n {\n id: 'n1',\n text: 'Meal planning: build plans against the macro targets from buildPlan() using the real Costco basket in data/instacart-orders.json rather than invented recipes, and emit a shopping list. No task exists for this — H-4 only covers turning a list into an Instacart cart.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Consider cost-per-gram-of-protein, now that both price and purchase data exist in the same place.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Merge feat/macro-calculator once the user has reviewed it — three commits, nothing pushed, no remote exists.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: \"Unresolved and cosmetic: the spreadsheet's BMI cell (33.57) disagrees with its own Ideal BMI Weight cell (223.1 lb, which pins height at 83.5 in and implies BMI 32.52). No calorie or macro target uses height, so nothing is blocked, but the true height is still unconfirmed.\",\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'herald',\n ended: '2026-05-29T05:59:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-05-28 (superseded — recorded for the record)\\n\\nDesign phase complete, build started. S1 done (H-1): src restructured into core/drivers/transports, 186 tests green, committed on `feat/harness-pivot` @ 896d3bb. Working tree clean, nothing pushed. The plan at the time was S2 (H-2) quarantine the backlog, then S3 (H-3) the Plugin/BrainDriver/Transport contract, then S4/M0 the Slack echo round-trip on the phone.\\n\\n**Almost all of this is now stale.** H-2 and H-3 both closed in the 2026-05-29 and 2026-06-02 sessions. Nothing has happened in this initiative since 2026-06-02, roughly eight weeks.\\n\\nThe one item that survived — and the reason this record exists — is a blocker containing a time-sensitive deadline that has silently expired. It is recorded below as ABANDONED rather than migrated as live work, so a future session does not chase it.\\n\\nDecisions remain locked in the brief: library-first TS harness; service-owns-loop with a swappable BrainDriver; ChannelDriver as the v0 default with SdkDriver for isolated/triage workloads; Slack v0 behind a transport adapter; diet coach as the first vertical.',\n next_steps: [\n {\n id: 'n1',\n text: 'The \"~June 8 Agent SDK credit (June 15 billing change)\" window lapsed. The credit is gone; any cost assumption predating the June 15 billing change needs rechecking before the SdkDriver metered path is priced.',\n kind: 'prose',\n abandoned: {\n note: 'The Agent SDK credit claim window (~June 8, ahead of the June 15 billing change) lapsed roughly seven weeks before the migration; the credit is gone. Recorded as abandoned rather than migrated live so no future session chases it. The surviving follow-up — rechecking cost assumptions that predate the June 15 billing change before pricing the SdkDriver metered path — belongs to the brief, not the ledger.',\n },\n },\n ],\n },\n {\n slug: 'home-assistant',\n ended: '2026-05-13T00:00:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-05-13\\n\\n`main` last commit `7758913` (\"fix: remove dead src.core.config_utils import breaking all MCP tools\"). Working tree dirty: three ha_config/ files modified (automations_dir/automations.yaml, configuration.yaml, scenes_lighting.yaml) plus untracked .brain/, .claude/settings.local.json, ha_config/custom_templates/, ha_config/dashboards/home_overview.yaml and tools/screenshot.py.\\n\\nThe initiative is on the back burner — no active coding push — but the brain PM `HOME` instance has 31 pending tasks across 8 workstreams (21 done), so there is plenty queued when attention returns. The most recent work landed the MCP server, SSH config-sync tooling, legacy src/ cleanup, and a Jinja2/stale-entity sweep.\\n\\n⚠️ That dirty-tree file list is now roughly 2.5 months old and this is a live home-automation system, so treat it as a hint, not a fact. The handoff\\'s own guard applies: run `make config-status` and `make config-diff` before deciding anything — live /config/ is authoritative.\\n\\nNote: HOME-* ids below live in the external brain PM instance, not in this initiative\\'s tasks/, which is empty.',\n next_steps: [\n {\n id: 'n1',\n text: 'Reconcile the uncommitted ha_config/ edits: run `make config-status`, decide the pull-or-push direction, then commit the local-side delta. Never push or pull blindly — live /config/ is authoritative.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Decide the fate of src/ (brain PM HOME-07.17): only config.py and exceptions.py remain. This gates the tools/ test work so the tests target the right layer, and HOME-07.14 / HOME-07.15 are duplicates — close one.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Triage the HOME-08 design backlog — pick one or two of climate (08.05), presence/away (08.06), goodnight/morning (08.07) as the next active design thread.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'Two small unblockers worth knocking out together: HOME-03.05 add-on updates and HOME-04.01 DHCP reservation for the PowerView hub.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'HOME-03.01 Roborock re-auth is blocked on a UI action — it must be done from Settings → Devices & Services and cannot be scripted.',\n kind: 'prose',\n },\n {\n id: 'n6',\n text: 'Opportunistic: HOME-09.03, archive the three stale debug dashboards next time dashboards are open.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'logan',\n ended: '2026-07-17T17:59:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-07-17\\n\\nA full session took the backyard treehouse / play structure from open question to a ready-to-submit HOA packet. It settled as an open-sided children\\'s play structure (not an enclosed playhouse) in the south side yard, which keeps it a Greenwood Village 5 ft-setback, permit-exempt \"playground equipment\" (Lot 28 = R-1.0 PUD, per Ordinance 03/2021). Analysis lives in docs/treehouse-*; the assembled packet is in property-records/hoa/\"ACC Submission - Play Structure/\". Only the neighbour signature is left before it goes to the new ACC members. The owner is not pulling a city building permit, and is building to code regardless. The project folder moved to ~/projects/logan, out of the TCC-blocked ~/Documents.\\n\\nFrom a tooling standpoint this initiative is on the back burner: the folder is maintained by hand, not by any pipeline. Active construction is real — the kitchen contract is signed at $93,346.85, trenching began 2026-04-22, junipers were scheduled the same day. The docs/ knowledge base was last edited 2026-04-18 and is behind reality.\\n\\nSeveral vendor decisions are sitting undecided in bids/ with no record of a call either way.',\n next_steps: [\n {\n id: 'n1',\n text: \"Submit the treehouse ACC packet: print property-records/hoa/'ACC Submission - Play Structure/', get Deb/Nolan Pratt (5185 S Logan) to sign line 1, then send to ACC members Caitlin Tesoriero and Kathy Martinez. Everything else in the packet is ready.\",\n kind: 'task',\n ref: 'L-1',\n },\n {\n id: 'n2',\n text: \"Chase Wiley/DBS for the electrician's heater breakout (DBS #8635.2) — ceiling-mount vs recessed is a ~$18K swing and the make/model is still unspecified. If it is still missing, request a second bid.\",\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Plumbing quotes QU0543 / QU0545 for the steam shower are still unsigned — sign or decline.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'Finish selections still open: concrete countertop colour (samples were due 2026-04-22) against Sapphire cabinets and the existing brick; the $5,556 countertop allowance — confirm L-shape coverage, cutouts and overage handling; and brick sourcing for the backsplash, where an exact match is not guaranteed and samples need viewing.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'Decide the remaining un-contracted vendors — painting, flooring, Hall Marble stone, all sitting in bids/ with no decision recorded — or explicitly defer them in docs/open-questions.md.',\n kind: 'prose',\n },\n {\n id: 'n6',\n text: 'Refresh docs/open-questions.md against reality post-2026-04-22 (trenching, tree-placement walkthrough, sample reviews). It was last edited 2026-04-18.',\n kind: 'prose',\n },\n {\n id: 'n7',\n text: 'File the 4-29 DBS L3 drawing and the CO #3 bid (synthetic turf, additional trees, steps, timber walls) into docs/bid-analysis.md — check the 2026-07-20 DBS scope/payments sessions first, they may have covered part of this.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'relay',\n // Refreshed TWICE on 2026-07-29 (AW-65). First pass moved this off\n // 16:19:00Z, which predated even its covering session's own `ended`. A\n // further session then ran and rewrote the handoff again at 19:27Z —\n // later than either of that day's session ends — to record the\n // R-3-step-2 branch state, R-49/R-50 being filed and R-24 closing. The\n // loops below were not all true until that edit, so `ended` follows it.\n ended: '2026-07-29T19:27:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-07-29\\n\\n**R-3 step 2 is built and fully verified, and it is sitting on an unmerged branch.** Dispatch exists in the schema and the storage seam: an item is handed to an agent by setting its GTD context to `agent`, and a runner claims it by appending to one append-only `events` log. No daemon exists yet, nothing executes, nothing is deployed. 386 tests across 17 files, `tsc` clean, `make check` exit 0, and the compatibility suite at 66/66 local AND hosted — local/hosted divergence still measures zero, now across 66 constructs.\\n\\n**Production is untouched by this work:** 24 objects, no `events` table, migration 0008 applied to LOCAL D1 only. Production still holds the 111 imported items plus the two test captures (ids 113, 114).\\n\\nEarlier context that still holds: R-33 is decided and R-38 shipped it — type-specific attributes live in a registry-validated `meta` column enforced by database triggers that both writer doors inherit. Both MCP surfaces are deployed; production is Worker version `119a7987`.\\n\\nThe model in four lines: a narrow typed core with type-specific facets in one meta JSON column; `type_schemas` is a TABLE, so registering a kind or attribute is an INSERT; BEFORE INSERT/UPDATE triggers enforce registered keys and allowed values, so both doors and a hand-run `wrangler d1 execute` all obey; hot attributes promote to generated columns, derived so they cannot drift.\\n\\nThe session that produced this handoff left R-23 Part B half-answered — OAuth completed but the six admin verbs never attached. R-23, R-27 and R-36 all closed later the same day, so the headline NEXT ACTION and the first two operator-only items are no longer live and are excluded below.\\n\\n**READ THIS BEFORE TRUSTING ANY CLOSED SECURITY TICKET. R-20 closed by RE-SCOPE, not by resolving the risk.** The mascot-madness token still reaches relay's D1 and Worker; the blast radius is unchanged. **R-44 (account separation) is the real precondition**, and the handoff names it as the one thing an operator might want to do first, because the cost grows with every new surface pointed at the hostname.\\n\\n_Refreshed twice on 2026-07-29 (AW-65); this reflects the handoff as rewritten at 19:27Z, after R-3 step 2 was verified, R-49/R-50 were filed and R-24 closed._\",\n next_steps: [\n {\n id: 'n1',\n text: '`disabledMcpServers: [\"claude.ai Relay\"]` is currently SET for this project in ~/.claude.json, left over from probe 4. Claude Code sessions have no relay tools until it is removed.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'R-32 is the highest-leverage thing available: the 1-bit sign sketch takes recall@10 from 55.8% to 96.6% with no schema change, is orthogonal to everything else, and is the candidate generator R-40 needs. Do it first.',\n kind: 'task',\n ref: 'R-32',\n },\n {\n id: 'n3',\n text: \"R-40 second — reference content as the second real kind. `note` exists but is a task in disguise (0005 gave it the identical six attributes), so R-33's central ~0-shared-attributes claim is still untested. 'Look up' is a capability relay does not have at all: list_items filters, it does not search.\",\n kind: 'task',\n ref: 'R-40',\n },\n {\n id: 'n4',\n text: \"R-39 third — registry-driven MCP tools, the fast-follow that R-40 exercises. This is also what makes R-33's no-deploy property real rather than half-real.\",\n kind: 'task',\n ref: 'R-39',\n },\n {\n id: 'n5',\n text: 'R-35 (entities) is deliberately sequenced AFTER R-40 by the operator — do not pull it forward.',\n kind: 'task',\n ref: 'R-35',\n },\n {\n id: 'n6',\n text: 'R-37 is about an hour and now covers TWO detectors sequenced together — the index-drift check plus the new R-41 schema-drift check. It is the deciding evidence for the one genuine unfixable-on-D1 defect, and index drift has never been observed or ruled out. Take it any time.',\n kind: 'task',\n ref: 'R-37',\n },\n {\n id: 'n7',\n text: 'R-34 (R2 blob tier) is gated on R-36 (logan data-handling), which has closed — so it is unblocked. It also inherits the hard preconditions C1/C2 from docs/logan-corpus-decision.md §5; check those before starting. (It was never gated on R-20, despite an earlier note conflating the two.)',\n kind: 'task',\n ref: 'R-34',\n },\n {\n id: 'n8',\n text: \"R-28 is operator-only and cannot be delegated: capture 'Fix list_items paging' from the phone and listen to whether the readback says 'list underscore items', 'list items' or 'listitems'. The three mean different things — record which.\",\n kind: 'task',\n ref: 'R-28',\n },\n // Was `kind: task, ref: R-24`. R-24 closed 2026-07-29 (66/66 hosted),\n // so the ref would have auto-resolved this loop the moment the\n // migration ran and deleted it before anyone read it. What survives\n // R-24's closure is the RECURRING obligation, which no task carries —\n // hence prose.\n {\n id: 'n9',\n text: 'Recurring, and owned by nobody: `make check-compat-remote` is operator-only (it refuses a non-TTY by design) and must be re-run after ANY change to the SQL constructs relay depends on. The one-off run closed as R-24 on 2026-07-29 at 66/66 hosted, with local/hosted divergence still measuring zero — but the obligation did not close with it.',\n kind: 'prose',\n },\n {\n id: 'n10',\n text: 'Voice `list_items` and `complete_item` have still never run from a phone — only capture has. No task covers this verification gap.',\n kind: 'prose',\n },\n // Was standalone prose reading \"delete 113/114 when convenient\". The\n // handoff records that this was pulled into task R-47 precisely\n // because \"when convenient\" survived two handoffs unactioned, and\n // R-47 also covers closing/annotating the already-built #104/#106.\n {\n id: 'n11',\n text: 'R-47 housekeeping, filed because \"delete when convenient\" survived two handoffs unactioned: delete production test captures ids 113 and 114, AND close/annotate items #104 and #106, which are already built.',\n kind: 'task',\n ref: 'R-47',\n },\n {\n id: 'n12',\n text: \"R-44 (account separation) is the one thing an operator might want to do FIRST. R-20 closed by re-scope rather than by resolving the risk — the mascot-madness token still reaches relay's D1 and Worker — and R-44 is the real precondition, now also gating step 6 specifically. Cost grows with every new surface pointed at the hostname, so deferring it gets more expensive, not less.\",\n kind: 'task',\n ref: 'R-44',\n },\n // n13-n15 added in the second 2026-07-29 refresh pass. A further\n // session rewrote this handoff at 19:27Z, and the headline it left —\n // an entire built-and-verified feature waiting on a merge decision —\n // was covered by none of the twelve loops above.\n //\n // Prose, not `kind: pr`: there is no PR, only an unpushed branch, and\n // a `kind: pr` loop could never auto-resolve anyway.\n {\n id: 'n13',\n text: 'DECIDE WHETHER R-3 STEP 2 LANDS. `feat/agent-dispatch-events` holds four commits, NOT merged and NOT pushed: agent as a GTD context (not a kind or assignee), an append-only `events` log with an atomic claim, both design docs corrected, and the claim verified on hosted D1 at 66/66. Nothing is mid-flight and nothing needs a restart — the branch is green and self-consistent, so the only open question is merge/push/deploy. Migration 0008 is applied to LOCAL D1 only; production is untouched. One live consequence to weigh: voice cannot set context=agent until R-49 lands.',\n kind: 'prose',\n },\n {\n id: 'n14',\n text: 'R-49 — a dedicated voice `dispatch_to_agent` tool, sequenced to land with R-3 step 3. This is what restores the ability to hand an item to an agent by voice once step 2 makes `agent` a context.',\n kind: 'task',\n ref: 'R-49',\n },\n {\n id: 'n15',\n text: 'R-50 — scope note on R-39: the registry drives ATTRIBUTES, never the verb set. Worth reading before starting R-39 so the no-deploy property does not get overstated.',\n kind: 'task',\n ref: 'R-50',\n },\n ],\n },\n {\n slug: 'taxes',\n ended: '2026-05-12T00:00:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-05-12\\n\\nThe 2025 return is on extension. The bulk of documents were uploaded to SafeSend in early April 2026 ahead of Carolynn's Apr 10 cutoff; extension paperwork came back from her on Apr 15 (in 2025/extension-from-carolynn/) and the federal, CO and AZ extension payments have been made.\\n\\nAwaiting CPA work-up. Nothing was required from the owner at the time unless a still-needed document surfaced.\\n\\nThe extended filing deadline is Oct 2026, so the actions below are still live — but this record is about 2.5 months old and Carolynn may have moved the draft along since. Confirm status with her before re-doing any of it.\\n\\nThe open-items list (Walmart 1099-DIV, missed 2025 quarterlies, Colorado 1099-G, the underpayment-penalty estimate, the CP503 notice and the E-Trade cost-basis flag) is already restated near-verbatim in the brief's Open questions / risks section and is not duplicated here.\",\n next_steps: [\n {\n id: 'n1',\n text: 'Log into Computershare and pull the Walmart 1099-DIV, or screenshot account-no-activity if the shares were already divested, then tell Carolynn to estimate.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Pull IRS / CO / OR payment-history screenshots showing 2025 calendar-year activity into 2025/estimated-payments/, and confirm Carolynn has them. No 2025 quarterlies were made (federal $14K/qtr, CO $460/qtr); what the portals do show is the small nanny-payroll federal payments plus the April extension payments already saved.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Resolve the IRS CP503 notice (2024 balance, $19,499) sitting in 2025/estimated-payments/ — call the IRS or check the transcript — and file the confirmation.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'When Carolynn returns the draft return, review it against 2025/CHECKLIST.md totals before signing, and verify the final return uses the E-Trade Stock Plan Supplement basis rather than the 1099-B noncovered figures.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'After filing, mirror the final return PDF into 2025/ and update INDEX.md with the filing date and delivery method.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'titan-platform',\n ended: '2026-07-13T23:16:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-07-13\\n\\nAudit complete, round-2 research complete, architecture not yet started. No code written, nothing extracted — this initiative is audit + design only so far.\\n\\nRound 1 audited all sibling agentic projects via parallel agents, producing six cited docs in sources/ plus the extraction map in sources/00-index.md. The conclusion: the platform is mostly an EXTRACTION problem. Nearly every tier already exists somewhere — registry/daemon from active-work; embed, agent, retrieval, sessions, memory and pm from brain; store and code-graph from codewatch; dashboard-kit from titan-design, already shared. `cluster` and `locator` are the only genuinely-new tier-0 pieces, and codewatch is the monorepo template to copy.\\n\\nRound 2 closed the pre-architecture gaps and all six results are persisted as sources/research-*.md. Its most consequential correction: the brain spike is a DESIGN, not a built or adopted platform — only agent-submission was built, it is untracked, Restate was never integrated, and there was no adoption decision. The earlier \"decision memo\" claim was wrong and is now corrected everywhere.\\n\\nTP-1..TP-15 have since been filed, so the handoff\\'s \"create TP-* tasks\" action is already done. The session-miner build (active-work AW-23/27/28) proceeds in parallel and is the first likely consumer of the extracted store / session-read / registry packages.',\n next_steps: [\n {\n id: 'n1',\n text: 'The architecture phase is awaiting owner go-ahead. With the full picture in hand, draft the concrete @titan-design/* package DAG plus extraction sequencing before starting any TP-* build.',\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Decide monorepo vs multirepo, and settle the npm-scope inconsistency (@codewatch/* vs @titan-design/*). Both are open and recorded nowhere else.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: \"Settle the workflow-runtime approach: a light scheduler for the miner (herald patterns) now, defer the durable engine to tier-2/product, and when choosing prefer MIT/Apache (DBOS, Hatchet, Trigger) over Restate's BUSL. The SDK is a leaf, not a substrate.\",\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'Optional before starting architecture: pull the final agent-sdk report.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'TP-10 carries two unresolved decisions worth naming: @titan-design/react-ui is real and published but has a single stale consumer (codewatch@0.2.7) and brain never adopted it — it needs a generic-vs-Voltras split AND an RN-Web platform decision.',\n kind: 'task',\n ref: 'TP-10',\n },\n ],\n },\n {\n slug: 'voltras-workspace',\n // Refreshed TWICE on 2026-07-29 (AW-65). The first pass moved this off\n // 17:29:00Z, which matched only a session-close doc while an\n // undocumented session had run afterwards. A second large session then\n // ran the same day — nine PRs across three repos, three npm releases,\n // VW-101 and VW-106 closed, VMCP-01.72 part (a) merged — so this now\n // follows that session's recorded end.\n ended: '2026-07-29T19:15:00Z',\n session_id: 'handoff-migration',\n body: \"# Handoff state as of 2026-07-29 (second session)\\n\\nSix agents, **nine PRs merged across three repos, plus three npm releases**. `voltra-playground` main `e4a5bd1`, `voltras-mcp` main `1f010d9`, `voltra-node-sdk` main `a53804e` with tags v0.12.1/2/3 and npm at `@voltras/node-sdk@0.12.3`. Every repo clean, nothing unpushed, no worktrees left behind — but agents leave an UNTRACKED `.agent-notes/` in `voltras-mcp` that is not gitignored, so their reports do not survive a clean.\\n\\n**`VW-101` is fully closed, and it took THREE releases — that is the lesson.** 0.12.1 made `voltra-manager.ts`'s requires opaque to Metro; gates were green and Metro's own `collectDependencies` was clean over that file, **and it still did not work**, because `index.ts` value-exports `createBLEAdapter` from the adapters BARREL, which statically re-exports `NobleHost` — a second door nobody looked for. Two instrument lessons worth keeping: the 90-second check that would have caught it first try is bundling the real app with the workaround REMOVED (now the acceptance test: iOS bundles, 2125 modules, `@stoprocent/noble` 0); and read the sourcemap `sources` array, never grep the Hermes `.hbc`, which returned 0 both for the forbidden strings and for strings that had to be there — a blind instrument that reads as a pass.\\n\\n**`VMCP-01.72` part (a) is merged** (`1f010d9`, #220): the eight per-exercise read paths now scope by the set's own `exercise_id`. Part (b) is `VW-114`.\\n\\nEarlier the same day: `LiveFatiguePanel` wiring landed, and `VW-106` is done: `coordination/` is deleted, its 472 files reorganized into this initiative's `sources/` tree, and every path reference across six repos, brain, the skills and these docs rewritten. Snapshot at `~/projects/_archive/voltras-coordination-snapshot-2026-07-29.tar.gz`. **handoff.md is now the session surface — dated `HANDOFF-*.md` / `NEXT-SESSION-*.md` docs are retired and must not be recreated.**\\n\\nThe five-branch stack and `VW-105` have since landed. Earlier context that still holds: @titan-design/react-ui@0.12.0 is live on npm and voltras-mcp main is on it (7094aa1, PR #213); VW-99 passed all four rows on the wall. The diverging dual stage is built and merged (VMCP-04.05, voltras-mcp #214, main 3382496) — tempo and the exertion alert are shared rather than per-limb, and sets/reps/load stays on the page-level ExerciseHeader. The SPA works end to end on real hardware single-arm; the dual-arm view is still behind `?variant=live-dual`.\\n\\nThe 07-27 postmortem is why this file was rewritten: handoff.md was 12 days stale and the brief's in-flight efforts 22 days stale, bootstrap's priority ordering pointed at VW-68 (since demoted to p30), and the file titled \\\"start here\\\" was never opened. That cost a full session.\\n\\n_Refreshed twice on 2026-07-29 (AW-65). Only headline next actions are migrated as loops; the rest of the open ticket table stays in `tasks/` by decision, to keep the ledger readable._\",\n next_steps: [\n // n1 has now been re-pointed twice. Originally \"wire LiveFatiguePanel\"\n // (ref VW-76), which was already done while VW-76.yml still read\n // `status: open` — so it would NOT have auto-resolved and would have\n // migrated live. The first refresh replaced it with VMCP-01.72 as\n // prose, because VMCP-* tickets live in voltras-mcp and a ref would\n // have dangled. Part (a) has since merged (1f010d9, #220), and the\n // remainder now HAS a local task — VW-114, priority 1, open — so this\n // is finally a real task ref.\n {\n id: 'n1',\n // Text must not restate its own ref — the bootstrap label already\n // supplies it, and restating renders it twice (AW-71).\n text: \"FIRST — VMCP-01.72 part (b): implement `session.set_exercise` so one workout can hold multiple exercises without fragmenting across session rows. Part (a) is merged (1f010d9, #220): the eight per-exercise read paths now scope by the set's own `exercise_id`. Both user decisions on shape are recorded on the ticket. The original defect: a session's exercise was write-once at session.start and set.start took no exercise argument, so advancing exercises required session.end → session.start.\",\n kind: 'task',\n ref: 'VW-114',\n },\n // Added in the second 2026-07-29 pass. Prose because VMCP-* tickets\n // are tracked in voltras-mcp, not this initiative's `tasks/`.\n // Admitted past the narrow-entry policy because it is a fresh\n // high-severity regression caused BY the merges that just landed —\n // exactly what a headline-only ledger should surface.\n {\n id: 'n2b',\n text: \"REGRESSION from today's merges: VMCP-04.15 (high) — the dual REST stage renders COMPLETELY BLANK, body empty at 0:02 and 0:05. Dual telemetry is now the DEFAULT view for any bilateral rig, so every real two-limb session hits this.\",\n kind: 'prose',\n },\n // Old n3 (decide the fate of mapStoreToDualModel) dropped: the handoff\n // records \"RESOLVED 2026-07-28 — mapStoreToDualModel is DELETED with\n // its tests\", along with five downstream functions.\n {\n id: 'n2',\n text: \"The 07-27 postmortem's standing guard — 'read the newest coordination/NEXT-SESSION-*.md before trusting bootstrap's priority ordering' — is INVALIDATED and needs a replacement. VW-106 deleted coordination/ and retired dated session-close docs; handoff.md is the session surface now. The underlying failure the guard existed for is unfixed: priority ordering is stale by default, and two things the operator cared about had no VW-level task at all. Decide what enforces that now.\",\n kind: 'prose',\n },\n {\n id: 'n4',\n text: \"VW-95 demo video is no longer blocked — the titan publish was the gate and the SPA is now on 0.12.0, so a camera sees the current UI. What remains is content, not plumbing: no script and no shot list exist. Before filming with cues on, decide VMCP-05.01 (critical, safety): the mic is deaf during TTS/cues, including the 'stop' phrase.\",\n kind: 'task',\n ref: 'VW-95',\n },\n {\n id: 'n5',\n text: 'VW-92 experience_tier is still the cross-cutting blocker. The SCHEMA half is done — training_profile with a declared_tier column shipped in the v9 wave (sqlite-store.ts:369-371) — but the derivation logic and any reader or writer are missing: empty DDL, zero call sites. The design exists in coordination/tier-signal-design.md with no code written. B05/B06/B07/B14/B25/B31 all branch on tier.',\n kind: 'task',\n ref: 'VW-92',\n },\n {\n id: 'n6',\n text: 'VW-96 storage Wave 3 is not started, deliberately: training_profile and exercise_baselines are empty DDL with zero call sites. The WA audit rates baselines the single highest-leverage addition (14 downstream items), and it is a prerequisite for the RP tier work.',\n kind: 'task',\n ref: 'VW-96',\n },\n {\n id: 'n7',\n text: 'RP build order, starting with this one: B15 drift guard is the foundation → B56/B57 baselines → VW-91 (B04 two-session underperformance/MRV detector, rated highest value: high impact, small effort, buildable now, zero new instrumentation) → B16 → B09/B14. Also real and stalled: VMCP-02.25, plan_suggest_progression is VBT-blind and recommends +5 lb after near-failure sets.',\n kind: 'task',\n ref: 'VW-90',\n },\n {\n id: 'n8',\n text: \"Unowned and will fall through the cracks: VMCP-05.19 position→metres conversion — hard serialization, nobody bumps WA to 2.0.0 before this is written or position_units starts lying. Also unowned: the WA 2.0.0 consumer migration, drift-tolerance fit (needs no hardware), and 'what is a setup?' (setup_id / exercise_setups exist on main and are empty).\",\n kind: 'prose',\n },\n {\n id: 'n9',\n text: \"The bench sitting is the common unblocker. Run all FOUR checklists — they do NOT supersede each other, and two were written the same evening without referencing each other, so 'newest wins' silently drops a gate: validation-runbooks/BENCH-2026-07-26-consolidated.md, the two BENCH-ADDENDUM sweeps, and validation-runbooks/2026-07-27-vw68-write-lease-hardware-bench.md (added 07-27). Order: Q1 chains direction (frees the stuck WA 2.0.0 publish) → isometric calibration VMCP-02.82 (5 min) → voice/deaf-window → v9 capture run → rep-count and peak-power → guided-load wedge LAST, it may need a power cycle. The titan visual gate is done (VW-85, VW-99) — do not re-run it.\",\n kind: 'prose',\n },\n {\n id: 'n10',\n text: '⚠️ The live DB is at v8 and code on main is v9; the next MCP restart migrates it. Back up first — it is a one-way door and a v8 build cannot reopen a v9 file.',\n kind: 'prose',\n },\n ],\n },\n {\n slug: 'youtube',\n ended: '2026-07-27T00:00:00Z',\n session_id: 'handoff-migration',\n body: '# Handoff state as of 2026-07-27\\n\\nThe extractor is stable and did its job — 84 RP University lectures (~267K words) plus 22 others under sources/out/. Tool-level tasks Y-1/Y-2/Y-3 are unchanged and low priority. The active work is now downstream of the transcripts, not in the tool.\\n\\nThe last working session (2026-07-26, ~3h, 20 agents, 6 waves) started as \"mine the RP transcripts into brain\" and became a full foundation audit that redesigned the Voltras data layer. Design complete, zero code written — deliberately, because each audit kept finding the wanted features sat on a foundation that could not support them correctly. That ratio should now flip to building.\\n\\nDone and durable: the knowledge base is LIVE (386 notes in the voltras-workspace brain instance, all 84 lectures, 2,298 graph edges, 7 retrieval probes passing, entry point rp-cross-cutting-synthesis); a 60-item scored backlog; and ten design/audit docs.\\n\\nThe MVS has since shipped — voltras-mcp main is at SCHEMA_VERSION = 9 and the putSet INSERT OR REPLACE landmine is defused, so the v5-collision and unrecoverable-data warnings that used to sit here are both resolved. Six backlog items were filed as VW-89..VW-94 in voltras-workspace; the remaining ~50 stay in the backlog doc rather than becoming tickets nobody can start.',\n next_steps: [\n {\n id: 'n1',\n text: \"NEXT is hardware, not code: not one capture field has been seen populating from real hardware — everything was verified against mock adapters and DB copies. Run coordination/BENCH-CHECKLIST-v7-capture-and-open-questions.md alongside validation-runbooks/BENCH-2026-07-26-consolidated.md; NEITHER supersedes the other, and 'newest wins' silently drops the titan release gate and the voice deaf-window safety measurement. Back up the DB first — v9 is a one-way door.\",\n kind: 'prose',\n },\n {\n id: 'n2',\n text: 'Four decisions are blocked on measurements only the wall can give, one of which (Q1 chains direction) is holding a workout-analytics 2.0.0 npm publish.',\n kind: 'prose',\n },\n {\n id: 'n3',\n text: 'Plan Y-10, Y-11 and Y-12 as ONE schema-and-capture wave — they keep landing on the same tables from different directions.',\n kind: 'prose',\n },\n {\n id: 'n4',\n text: 'Operator decision: the weight_lbs = 0 backfill. Recommendation is NULLIF, with the reasoning in the build handoff; six more decisions sit in migration plan §7.',\n kind: 'prose',\n },\n {\n id: 'n5',\n text: 'Operator decisions still open after the 07-26 pass: the diet-phase tag, the B42 legal review, and ratifying performance-gated deloads. (Settled and not open: advisory-only for stop-set/deload, multi-user now, experiment waits for capture, validate the higher sample rate.)',\n kind: 'prose',\n },\n {\n id: 'n6',\n text: 'The program-level phase plan — sizing phases 1–4 the way phase 0 was sized — was offered but never started. It is what makes the milestone-timing question answerable.',\n kind: 'prose',\n },\n ],\n },\n ],\n};\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { SessionFrontmatterSchema, type SessionFrontmatter } from '../schemas/session.js';\nimport { readRawFrontmatter, writeFrontmatter } from '../utils/gray-matter-io.js';\n\n/**\n * Two session files in the live data predate the schema and fail it. v3 turns\n * unreadable session files into a standing `doctor` warning, so unless these\n * are repaired in the same pass the new integrity check starts life crying\n * wolf — and a permanent false positive masks the real reports it exists for.\n *\n * They are addressed by exact path rather than by a general rule: \"any session\n * with an out-of-enum `track` becomes adhoc\" would silently rewrite files the\n * operator has not looked at. Each repair re-checks its precondition, so a\n * file already fixed by hand is left alone and a re-run is a no-op.\n */\n\nexport type RepairAction = 'retrack' | 'relocate' | 'skip';\n\nexport interface RepairPlan {\n action: RepairAction;\n /** Path relative to the active root. */\n file: string;\n target?: string;\n detail: string;\n /** Validated replacement content, populated by `retrack` plans only. */\n repaired?: { frontmatter: SessionFrontmatter; body: string };\n}\n\ninterface KnownRepair {\n file: string;\n kind: 'retrack' | 'relocate';\n target?: string;\n why: string;\n}\n\nexport const KNOWN_REPAIRS: KnownRepair[] = [\n {\n file: path.join('audiobook', 'sessions', '2026-07-23-0549-2026-07-26-book1-m4b-packaging.md'),\n kind: 'retrack',\n why: \"track is a branch name ('feat/tts-quality'), not one of canonical|sidecar|adhoc\",\n },\n {\n file: path.join('voltras-workspace', 'sessions', 'ARCHIVED-handoff-through-2026-07-15.md'),\n kind: 'relocate',\n target: path.join('voltras-workspace', 'sources', 'ARCHIVED-handoff-through-2026-07-15.md'),\n why: 'not a session file — a hand-archived handoff parked in sessions/',\n },\n];\n\nconst TRACKS = new Set(['canonical', 'sidecar', 'adhoc']);\n\n/**\n * Brief-level repairs, applied before the `task_seq` backfill so a brief that\n * currently fails validation can still be rewritten.\n *\n * `health` carries `state: active`, which has never been in the enum, so every\n * validating writer refuses it — `active-work touch health` errors today. The\n * operator's chosen resolution is `focused` at rank 11 (1–10 are taken).\n * Guarded by the exact broken value, so a hand-fix beforehand wins.\n */\nconst BRIEF_REPAIRS: Record<\n string,\n (fm: Record<string, unknown>) => { patch: Record<string, unknown>; detail: string } | null\n> = {\n health(fm) {\n if (fm.state !== 'active') return null;\n return {\n patch: { state: 'focused', ...(fm.rank === undefined ? { rank: 11 } : {}) },\n detail: \"state 'active' (not in the enum) -> 'focused', rank 11\",\n };\n },\n};\n\n/**\n * Apply any known repair for `slug` to raw brief frontmatter. Returns the\n * frontmatter unchanged (and an empty `applied`) when nothing matches.\n */\nexport function repairBriefFrontmatter(\n slug: string,\n frontmatter: Record<string, unknown>,\n): { frontmatter: Record<string, unknown>; applied: string[] } {\n const repair = BRIEF_REPAIRS[slug]?.(frontmatter);\n if (repair == null) return { frontmatter, applied: [] };\n return {\n frontmatter: { ...frontmatter, ...repair.patch },\n applied: [repair.detail],\n };\n}\n\n/**\n * An out-of-enum `track` is the only thing this repair is allowed to fix, so\n * the repaired frontmatter is validated here, in phase one. A file that is\n * still invalid for some *other* reason is reported and left alone rather\n * than throwing half way through the write phase.\n */\nasync function planRetrack(fullPath: string, repair: KnownRepair): Promise<RepairPlan> {\n let raw: { frontmatter: Record<string, unknown>; body: string };\n try {\n raw = await readRawFrontmatter(fullPath);\n } catch {\n return { action: 'skip', file: repair.file, detail: 'unreadable; left for the operator' };\n }\n const track = raw.frontmatter.track;\n if (typeof track === 'string' && TRACKS.has(track)) {\n return { action: 'skip', file: repair.file, detail: `track already ${track}` };\n }\n const parsed = SessionFrontmatterSchema.safeParse({ ...raw.frontmatter, track: 'adhoc' });\n if (!parsed.success) {\n return {\n action: 'skip',\n file: repair.file,\n detail: `still invalid after retrack; left for the operator: ${parsed.error.message}`,\n };\n }\n return {\n action: 'retrack',\n file: repair.file,\n detail: `track ${JSON.stringify(track)} -> \"adhoc\" (${repair.why})`,\n repaired: { frontmatter: parsed.data, body: raw.body },\n };\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function planRepairs(activeRoot: string): Promise<RepairPlan[]> {\n const plans: RepairPlan[] = [];\n for (const repair of KNOWN_REPAIRS) {\n const fullPath = path.join(activeRoot, repair.file);\n if (!(await exists(fullPath))) {\n plans.push({ action: 'skip', file: repair.file, detail: 'already absent' });\n continue;\n }\n if (repair.kind === 'retrack') {\n plans.push(await planRetrack(fullPath, repair));\n continue;\n }\n const target = repair.target!;\n if (await exists(path.join(activeRoot, target))) {\n plans.push({\n action: 'skip',\n file: repair.file,\n target,\n detail: 'target already occupied; left for the operator',\n });\n continue;\n }\n plans.push({ action: 'relocate', file: repair.file, target, detail: repair.why });\n }\n return plans;\n}\n\nexport async function applyRepair(activeRoot: string, plan: RepairPlan): Promise<void> {\n const fullPath = path.join(activeRoot, plan.file);\n if (plan.action === 'retrack' && plan.repaired !== undefined) {\n await writeFrontmatter(\n fullPath,\n plan.repaired.frontmatter,\n plan.repaired.body,\n SessionFrontmatterSchema,\n );\n return;\n }\n if (plan.action === 'relocate') {\n const target = path.join(activeRoot, plan.target!);\n await fs.mkdir(path.dirname(target), { recursive: true });\n await fs.rename(fullPath, target);\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport matter from 'gray-matter';\nimport YAML from 'yaml';\nimport { ArtifactsSchema, type WorktreeEntry } from '../schemas/artifacts.js';\nimport { writeYaml } from '../utils/yaml-io.js';\nimport { atomicWrite } from '../utils/fs-atomic.js';\nimport type { Migration } from './types.js';\n\n/**\n * v3 → v4 (AW-67): move `brief.worktrees` into `artifacts.yml`.\n *\n * A worktree had two homes: a curated map in the brief keyed by label, and the\n * list `wrap` sweeps from git. They now share one list, with `name` marking the\n * entries an operator registered — see `src/schemas/artifacts.ts`.\n *\n * Per initiative:\n * - each `brief.worktrees[label]` becomes an `artifacts.worktrees[]` entry with\n * `name: label` and its `default` flag preserved\n * - a swept entry already at that path is *promoted* in place rather than\n * duplicated, so the pairing survives a wrap that ran before the migration\n * - `repo` is required by the schema and the brief never carried one, so a\n * promoted entry keeps the repo the sweep found and a fresh entry falls back\n * to its own path\n * - `worktrees` is removed from the brief frontmatter\n *\n * Idempotent: a brief with no `worktrees` key is left untouched, and a second\n * run finds nothing to move. Only the frontmatter is rewritten; brief prose is\n * preserved byte-for-byte.\n */\n\ninterface RawBriefWorktree {\n path?: unknown;\n default?: unknown;\n}\n\n/** Same-path comparison without tilde expansion surprises. */\nfunction normalize(value: string): string {\n const expanded = value.startsWith('~')\n ? path.join(process.env.HOME ?? '', value.slice(1))\n : value;\n return path.resolve(expanded);\n}\n\nfunction toEntries(raw: unknown): Array<{ name: string; path: string; default: boolean }> {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return [];\n const out: Array<{ name: string; path: string; default: boolean }> = [];\n for (const [name, value] of Object.entries(raw as Record<string, RawBriefWorktree>)) {\n const wtPath = value?.path;\n if (typeof wtPath !== 'string' || wtPath.length === 0) continue;\n out.push({ name, path: wtPath, default: value?.default === true });\n }\n return out;\n}\n\n/**\n * Merge migrated entries into whatever the sweep already recorded. At most one\n * `default` survives: the brief could only express one, but a promoted entry\n * plus a stale flag elsewhere could otherwise produce two and fail validation.\n */\nfunction mergeWorktrees(\n existing: WorktreeEntry[],\n incoming: Array<{ name: string; path: string; default: boolean }>,\n): WorktreeEntry[] {\n const out = existing.map((entry) => ({ ...entry }));\n for (const wt of incoming) {\n const match = out.find(\n (entry) => entry.name === undefined && normalize(entry.path) === normalize(wt.path),\n );\n const target = match ?? { path: wt.path, repo: wt.path };\n target.name = wt.name;\n if (wt.default) target.default = true;\n else delete target.default;\n if (!match) out.push(target);\n }\n if (out.filter((entry) => entry.default === true).length > 1) {\n let kept = false;\n for (const entry of out) {\n if (entry.default !== true) continue;\n if (kept) delete entry.default;\n kept = true;\n }\n }\n return out;\n}\n\nasync function readArtifacts(file: string): Promise<{\n branches: unknown[];\n stashes: unknown[];\n worktrees: WorktreeEntry[];\n}> {\n try {\n const raw = YAML.parse(await fs.readFile(file, 'utf8')) as Record<string, unknown>;\n return {\n branches: Array.isArray(raw?.branches) ? raw.branches : [],\n stashes: Array.isArray(raw?.stashes) ? raw.stashes : [],\n worktrees: Array.isArray(raw?.worktrees) ? (raw.worktrees as WorktreeEntry[]) : [],\n };\n } catch {\n return { branches: [], stashes: [], worktrees: [] };\n }\n}\n\n/** Returns how many worktrees moved out of this brief. */\nasync function migrateOne(initiativeDir: string): Promise<number> {\n const briefPath = path.join(initiativeDir, 'brief.md');\n let raw: string;\n try {\n raw = await fs.readFile(briefPath, 'utf8');\n } catch {\n return 0;\n }\n const parsed = matter(raw);\n const data = parsed.data as Record<string, unknown>;\n if (!('worktrees' in data)) return 0;\n\n const incoming = toEntries(data.worktrees);\n delete data.worktrees;\n\n if (incoming.length > 0) {\n const artifactsPath = path.join(initiativeDir, 'artifacts.yml');\n const current = await readArtifacts(artifactsPath);\n await writeYaml(\n artifactsPath,\n ArtifactsSchema.parse({\n branches: current.branches,\n stashes: current.stashes,\n worktrees: mergeWorktrees(current.worktrees, incoming),\n }),\n ArtifactsSchema,\n );\n }\n\n // Rewrite the brief frontmatter only; `matter.stringify` preserves the body.\n await atomicWrite(briefPath, matter.stringify(parsed.content, data));\n return incoming.length;\n}\n\nasync function initiativeDirs(activeRoot: string): Promise<string[]> {\n const out: string[] = [];\n let entries;\n try {\n entries = await fs.readdir(activeRoot, { withFileTypes: true });\n } catch {\n return out;\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith('.')) continue;\n const dir = path.join(activeRoot, entry.name);\n try {\n await fs.access(path.join(dir, 'brief.md'));\n out.push(dir);\n } catch {\n // not an initiative\n }\n }\n return out;\n}\n\nexport const v3ToV4Worktrees: Migration = {\n from: 3,\n to: 4,\n description: 'Move brief.worktrees into artifacts.yml as named worktree entries',\n async run(activeRoot: string): Promise<void> {\n const moved: string[] = [];\n for (const dir of await initiativeDirs(activeRoot)) {\n const count = await migrateOne(dir);\n if (count > 0) moved.push(`${path.basename(dir)}\\t${count} worktree(s)`);\n }\n if (moved.length === 0) return;\n const stamp = new Date().toISOString();\n await fs.appendFile(\n path.join(activeRoot, '.migrations.log'),\n moved.map((line) => `${stamp}\\tv3->v4\\t${line}\\n`).join(''),\n 'utf8',\n );\n },\n};\n\nexport default v3ToV4Worktrees;\n","import { ConfigError } from '../errors.js';\nimport type { Migration } from './types.js';\nimport { v1ToV2Artifacts } from './v1-to-v2-artifacts.js';\nimport { v2ToV3OpenLoops } from './v2-to-v3-open-loops.js';\nimport { v3ToV4Worktrees } from './v3-to-v4-worktrees.js';\n\nexport type { Migration } from './types.js';\n\n/**\n * The oldest version this build migrates from.\n *\n * v1 is the baseline. There is intentionally no v0 -> v1 migrator: the\n * plan's fresh-start policy says v0 data is not auto-migrated. Setup\n * stamps {@link CURRENT_VERSION} on first run; an existing\n * `.schema-version` file containing `0` is treated as an error so the\n * user notices.\n */\nexport const BASE_VERSION = 1;\n\n/**\n * Migrations registry. Add an entry when the on-disk layout changes.\n * Keep entries sorted by `from` ascending.\n */\nexport const MIGRATIONS: readonly Migration[] = [v1ToV2Artifacts, v2ToV3OpenLoops, v3ToV4Worktrees];\n\n/**\n * The schema version this build expects, derived from the chain rather\n * than hand-maintained (TP-35): adding a migrator is the only way to\n * move it, so the constant and the list cannot disagree.\n */\nexport const CURRENT_VERSION = targetVersion(MIGRATIONS);\n\nfunction targetVersion(migrations: readonly Migration[]): number {\n return migrations.reduce((highest, m) => Math.max(highest, m.to), BASE_VERSION);\n}\n\n/**\n * Everything wrong with a migration chain, as readable lines; empty means\n * it walks {@link BASE_VERSION} to its target in single steps with no\n * duplicate or missing version. Exported so a test can assert the shipped\n * chain, which is what stops a bad merge resolution reaching a release.\n */\nexport function chainProblems(migrations: readonly Migration[] = MIGRATIONS): string[] {\n const problems: string[] = [];\n const byFrom = new Map<number, Migration[]>();\n for (const m of migrations) {\n if (m.to <= m.from) {\n problems.push(`${m.description} does not advance the version (from=${m.from}, to=${m.to})`);\n }\n byFrom.set(m.from, [...(byFrom.get(m.from) ?? []), m]);\n }\n for (const [from, group] of byFrom) {\n if (group.length > 1) {\n const names = group.map((m) => m.description).join(', ');\n problems.push(`v${from} has ${group.length} migrations, expected one: ${names}`);\n }\n }\n problems.push(...gaps(byFrom, targetVersion(migrations)));\n return problems;\n}\n\nfunction gaps(byFrom: Map<number, Migration[]>, target: number): string[] {\n let cursor = BASE_VERSION;\n while (cursor < target) {\n const next = byFrom.get(cursor)?.[0];\n if (!next) return [`no migration from v${cursor}; the chain stops short of v${target}`];\n // Guards the walk as well as the chain: a non-advancing step would loop here.\n if (next.to <= cursor) return [`${next.description} cannot advance past v${cursor}`];\n cursor = next.to;\n }\n return [];\n}\n\n/**\n * Runs every migrator needed to bring `activeRoot` from `fromVersion`\n * to {@link CURRENT_VERSION}. Throws {@link ConfigError} if no\n * contiguous chain exists, or if `fromVersion` is newer than what this\n * build understands.\n *\n * The `migrations` parameter exists for dependency injection in tests;\n * production callers should rely on the default.\n */\nexport async function runMigrations(\n activeRoot: string,\n fromVersion: number,\n migrations: readonly Migration[] = MIGRATIONS,\n): Promise<{ ran: Migration[] }> {\n if (fromVersion === CURRENT_VERSION) {\n return { ran: [] };\n }\n\n if (fromVersion > CURRENT_VERSION) {\n throw new ConfigError(\n `Schema version ${fromVersion} is newer than this build (${CURRENT_VERSION}); ` +\n `downgrade not supported. Upgrade the active-work CLI to match.`,\n );\n }\n\n const ran: Migration[] = [];\n let cursor = fromVersion;\n\n while (cursor < CURRENT_VERSION) {\n const next = migrations.find((m) => m.from === cursor);\n if (!next) {\n throw new ConfigError(\n `No migration registered from schema version ${cursor} to ${CURRENT_VERSION}. ` +\n `Gap at v${cursor} -> v${cursor + 1}.`,\n );\n }\n if (next.to <= next.from) {\n throw new ConfigError(\n `Invalid migration: ${next.description} (from=${next.from}, to=${next.to}) does not advance the version.`,\n );\n }\n await next.run(activeRoot);\n ran.push(next);\n cursor = next.to;\n }\n\n if (cursor !== CURRENT_VERSION) {\n throw new ConfigError(`Migration chain ended at v${cursor}, expected v${CURRENT_VERSION}.`);\n }\n\n return { ran };\n}\n","/**\n * Linux user-level systemd supervision for the active-work daemon.\n *\n * Installs a `~/.config/systemd/user/active-work.service` unit that runs\n * `active-work mcp serve` in the foreground; systemd handles restart on\n * crash. Also enables lingering (`loginctl enable-linger`) so the daemon\n * survives logout and starts at boot. On non-Linux platforms every step here\n * is a no-op.\n */\nimport { promises as fsp } from 'node:fs';\nimport nodePath from 'node:path';\nimport { spawn as nodeSpawn } from 'node:child_process';\nimport os from 'node:os';\nimport type { SetupDeps, StepPaths, StepResult } from './steps.js';\n\nexport const UNIT_NAME = 'active-work.service';\nexport const STEP_SUPERVISION = 'install-supervision';\n\nfunction isLinux(platform: NodeJS.Platform = process.platform): boolean {\n return platform === 'linux';\n}\n\nfunction resolveLocalDeps(deps: SetupDeps): {\n fs: typeof fsp;\n spawn: typeof nodeSpawn;\n paths: StepPaths;\n cliEntry: string;\n platform: NodeJS.Platform;\n} {\n const fs = deps.fs ?? fsp;\n const spawn = deps.spawn ?? nodeSpawn;\n const homeDir = deps.paths?.homeDir ?? os.homedir();\n const paths: StepPaths =\n deps.paths ??\n ({\n activeRoot: '',\n stateRoot: '',\n configRoot: '',\n homeDir,\n } as StepPaths);\n const cliEntry = deps.cliEntry ?? process.argv[1] ?? 'active-work';\n return { fs, spawn, paths, cliEntry, platform: process.platform };\n}\n\nexport function getUnitDir(homeDir: string): string {\n return nodePath.join(homeDir, '.config', 'systemd', 'user');\n}\n\nexport function getUnitPath(homeDir: string): string {\n return nodePath.join(getUnitDir(homeDir), UNIT_NAME);\n}\n\nexport interface UnitOptions {\n cliEntry: string;\n port?: number;\n nodeBin?: string;\n}\n\n/** Render the systemd unit file content. */\nexport function renderUnit(opts: UnitOptions): string {\n const node = opts.nodeBin ?? process.execPath;\n const args = ['mcp', 'serve'];\n if (opts.port !== undefined) {\n args.push('--port', String(opts.port));\n }\n // ExecStart must use absolute paths. Quote the node binary and entrypoint\n // in case they contain spaces (common on macOS dev paths, less so on Linux,\n // but cheap insurance).\n const execStart = [quoteIfNeeded(node), quoteIfNeeded(opts.cliEntry), ...args].join(' ');\n return [\n '[Unit]',\n 'Description=active-work HTTP daemon (MCP + REST + dashboard)',\n 'After=network.target',\n '',\n '[Service]',\n 'Type=simple',\n `ExecStart=${execStart}`,\n 'Restart=on-failure',\n 'RestartSec=5',\n 'Environment=NODE_ENV=production',\n '',\n '[Install]',\n 'WantedBy=default.target',\n '',\n ].join('\\n');\n}\n\nfunction quoteIfNeeded(value: string): string {\n if (!/\\s/.test(value)) return value;\n // systemd unit files support double-quoted argv elements; escape any embedded\n // double quotes and backslashes.\n const escaped = value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n return `\"${escaped}\"`;\n}\n\n/** Spawn a process and capture its exit code + stderr. */\nfunction runOnce(\n spawn: typeof nodeSpawn,\n cmd: string,\n args: string[],\n): Promise<{ code: number | null; stderr: string; spawnError?: Error }> {\n return new Promise((resolve) => {\n let stderr = '';\n let settled = false;\n try {\n const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });\n child.stderr?.on('data', (chunk: Buffer | string) => {\n stderr += chunk.toString();\n });\n child.on('error', (err) => {\n if (settled) return;\n settled = true;\n resolve({ code: null, stderr, spawnError: err });\n });\n child.on('close', (code) => {\n if (settled) return;\n settled = true;\n resolve({ code, stderr });\n });\n } catch (err) {\n if (settled) return;\n settled = true;\n resolve({ code: null, stderr, spawnError: err as Error });\n }\n });\n}\n\n/**\n * Probe whether the user-level systemd unit is currently active.\n * Returns false (without error) on non-Linux or when `systemctl` is missing.\n */\nexport async function isUnitActive(deps: SetupDeps = {}): Promise<boolean> {\n const { spawn, platform } = resolveLocalDeps(deps);\n if (!isLinux(platform)) return false;\n const result = await runOnce(spawn, 'systemctl', ['--user', 'is-active', '--quiet', UNIT_NAME]);\n if (result.spawnError) return false;\n return result.code === 0;\n}\n\nexport interface InstallSupervisionOptions {\n /** Override the port baked into the unit's ExecStart. */\n port?: number;\n}\n\n/**\n * Install (or refresh) the user-level systemd unit and enable+start it.\n *\n * No-op on non-Linux. On Linux it writes the unit, reloads the daemon,\n * and runs `enable --now`. Idempotent: if the unit is already active and\n * its content matches, returns done:false.\n */\nexport async function stepInstallSupervision(\n deps: SetupDeps = {},\n opts: InstallSupervisionOptions = {},\n): Promise<StepResult> {\n const { fs, spawn, paths, cliEntry, platform } = resolveLocalDeps(deps);\n if (!isLinux(platform)) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Skipped: systemd supervision only applies on Linux (this host is ${platform})`,\n };\n }\n const unitDir = getUnitDir(paths.homeDir);\n const unitPath = getUnitPath(paths.homeDir);\n const desired = renderUnit({ cliEntry, port: opts.port });\n\n try {\n await fs.mkdir(unitDir, { recursive: true });\n let existing: string | null = null;\n try {\n existing = await fs.readFile(unitPath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n const unchanged = existing === desired;\n if (!unchanged) {\n await fs.writeFile(unitPath, desired, 'utf8');\n }\n\n const reload = await runOnce(spawn, 'systemctl', ['--user', 'daemon-reload']);\n if (reload.spawnError) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Wrote ${unitPath} but \\`systemctl\\` is unavailable (${reload.spawnError.message}). Run \\`systemctl --user daemon-reload && systemctl --user enable --now ${UNIT_NAME}\\` manually.`,\n };\n }\n if (reload.code !== 0) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: `systemctl --user daemon-reload exited ${reload.code ?? 'null'}: ${reload.stderr.trim()}`,\n };\n }\n\n // Enable lingering so the user manager — and thus the daemon — persists\n // across logout and starts at boot. Without it a `--user` unit is torn down\n // when the user's last session ends, so the daemon would not survive logout.\n //\n // Pass the username explicitly: the bare `loginctl enable-linger` form needs\n // an active login session to resolve \"self\" (it errors \"No such device\" when\n // run outside one), whereas the explicit form still routes through polkit's\n // `set-self-linger` action when the target is the caller. Best-effort:\n // enabling linger can require privileges, so a failure degrades to a note\n // rather than failing the install.\n let lingerUser: string | undefined;\n try {\n lingerUser = os.userInfo().username;\n } catch {\n lingerUser = undefined;\n }\n const linger = await runOnce(spawn, 'loginctl', [\n 'enable-linger',\n ...(lingerUser ? [lingerUser] : []),\n ]);\n const lingerEnabled = !linger.spawnError && linger.code === 0;\n\n const enable = await runOnce(spawn, 'systemctl', ['--user', 'enable', '--now', UNIT_NAME]);\n if (enable.spawnError) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: `systemctl --user enable --now ${UNIT_NAME} failed to spawn: ${enable.spawnError.message}`,\n };\n }\n if (enable.code !== 0) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: `systemctl --user enable --now ${UNIT_NAME} exited ${enable.code ?? 'null'}: ${enable.stderr.trim()}`,\n };\n }\n\n const action = unchanged ? 'refreshed' : 'installed';\n const lingerCmd = `loginctl enable-linger${lingerUser ? ` ${lingerUser}` : ''}`;\n const lingerNote = lingerEnabled\n ? ' Lingering enabled — survives logout and starts at boot.'\n : ` NOTE: could not enable lingering; run \\`sudo ${lingerCmd}\\` so the daemon survives logout and starts at boot (without it, it stops when your session ends).`;\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: !unchanged,\n message: `Systemd unit ${action} at ${unitPath} and enabled.${lingerNote}`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: (err as Error).message,\n };\n }\n}\n\n/**\n * Disable the user-level unit and remove the file.\n * No-op on non-Linux or when the unit is absent.\n */\nexport async function uninstallSupervision(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, spawn, paths, platform } = resolveLocalDeps(deps);\n if (!isLinux(platform)) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Skipped: systemd supervision only applies on Linux (this host is ${platform})`,\n };\n }\n const unitPath = getUnitPath(paths.homeDir);\n try {\n let present = true;\n try {\n await fs.stat(unitPath);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') present = false;\n else throw err;\n }\n if (!present) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `No systemd unit at ${unitPath}`,\n };\n }\n const disable = await runOnce(spawn, 'systemctl', ['--user', 'disable', '--now', UNIT_NAME]);\n if (disable.spawnError) {\n // systemctl missing — still try to remove the file so re-install is clean.\n await fs.rm(unitPath, { force: true });\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: true,\n message: `Removed ${unitPath} (systemctl unavailable: ${disable.spawnError.message})`,\n };\n }\n // Non-zero exit from `disable` is non-fatal (unit may already be inactive).\n await fs.rm(unitPath, { force: true });\n const reload = await runOnce(spawn, 'systemctl', ['--user', 'daemon-reload']);\n if (reload.code !== 0 && !reload.spawnError) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: true,\n message: `Removed ${unitPath}; daemon-reload exited ${reload.code ?? 'null'}`,\n };\n }\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: true,\n message: `Disabled and removed ${unitPath}`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: (err as Error).message,\n };\n }\n}\n","/**\n * macOS user-level launchd supervision for the active-work daemon (AW-2).\n *\n * Installs a `~/Library/LaunchAgents/dev.hjewkes.active-work.plist` LaunchAgent\n * that runs `active-work mcp serve`; launchd handles restart on crash and\n * relaunch at login. On non-macOS platforms every step here is a no-op — the\n * Linux equivalent lives in `supervision-systemd.ts`.\n */\nimport { promises as fsp } from 'node:fs';\nimport nodePath from 'node:path';\nimport { spawn as nodeSpawn } from 'node:child_process';\nimport os from 'node:os';\nimport { STEP_SUPERVISION } from './supervision-systemd.js';\nimport type { SetupDeps, StepPaths, StepResult } from './steps.js';\n\nexport const PLIST_LABEL = 'dev.hjewkes.active-work';\nexport const PLIST_NAME = `${PLIST_LABEL}.plist`;\n\nfunction isDarwin(platform: NodeJS.Platform = process.platform): boolean {\n return platform === 'darwin';\n}\n\nfunction resolveLocalDeps(deps: SetupDeps): {\n fs: typeof fsp;\n spawn: typeof nodeSpawn;\n paths: StepPaths;\n cliEntry: string;\n uid: number;\n platform: NodeJS.Platform;\n} {\n const fs = deps.fs ?? fsp;\n const spawn = deps.spawn ?? nodeSpawn;\n const homeDir = deps.paths?.homeDir ?? os.homedir();\n const paths: StepPaths =\n deps.paths ??\n ({\n activeRoot: '',\n stateRoot: '',\n configRoot: '',\n homeDir,\n } as StepPaths);\n const cliEntry = deps.cliEntry ?? process.argv[1] ?? 'active-work';\n const uid = process.getuid?.() ?? 0;\n return { fs, spawn, paths, cliEntry, uid, platform: process.platform };\n}\n\nexport function getAgentDir(homeDir: string): string {\n return nodePath.join(homeDir, 'Library', 'LaunchAgents');\n}\n\nexport function getPlistPath(homeDir: string): string {\n return nodePath.join(getAgentDir(homeDir), PLIST_NAME);\n}\n\nfunction getLogDir(homeDir: string): string {\n return nodePath.join(homeDir, 'Library', 'Logs', 'active-work');\n}\n\n/** The `gui/<uid>/<label>` service target used by `launchctl`. */\nfunction serviceTarget(uid: number): string {\n return `gui/${uid}/${PLIST_LABEL}`;\n}\n\nfunction escapeXml(value: string): string {\n return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n}\n\nexport interface PlistOptions {\n cliEntry: string;\n homeDir: string;\n port?: number;\n nodeBin?: string;\n}\n\n/** Render the launchd plist for the daemon. */\nexport function renderPlist(opts: PlistOptions): string {\n const node = opts.nodeBin ?? process.execPath;\n const argv = [node, opts.cliEntry, 'mcp', 'serve'];\n if (opts.port !== undefined) argv.push('--port', String(opts.port));\n const logDir = getLogDir(opts.homeDir);\n const programArgs = argv.map((a) => ` <string>${escapeXml(a)}</string>`).join('\\n');\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">',\n '<plist version=\"1.0\">',\n '<dict>',\n ' <key>Label</key>',\n ` <string>${PLIST_LABEL}</string>`,\n ' <key>ProgramArguments</key>',\n ' <array>',\n programArgs,\n ' </array>',\n ' <key>RunAtLoad</key>',\n ' <true/>',\n ' <key>KeepAlive</key>',\n ' <true/>',\n ' <key>ProcessType</key>',\n ' <string>Background</string>',\n ' <key>EnvironmentVariables</key>',\n ' <dict>',\n ' <key>NODE_ENV</key>',\n ' <string>production</string>',\n ' </dict>',\n ' <key>StandardOutPath</key>',\n ` <string>${escapeXml(nodePath.join(logDir, 'daemon.out.log'))}</string>`,\n ' <key>StandardErrorPath</key>',\n ` <string>${escapeXml(nodePath.join(logDir, 'daemon.err.log'))}</string>`,\n '</dict>',\n '</plist>',\n '',\n ].join('\\n');\n}\n\n/** Spawn a process and capture its exit code + stderr. */\nfunction runOnce(\n spawn: typeof nodeSpawn,\n cmd: string,\n args: string[],\n): Promise<{ code: number | null; stderr: string; spawnError?: Error }> {\n return new Promise((resolve) => {\n let stderr = '';\n let settled = false;\n try {\n const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });\n child.stderr?.on('data', (chunk: Buffer | string) => {\n stderr += chunk.toString();\n });\n child.on('error', (err) => {\n if (settled) return;\n settled = true;\n resolve({ code: null, stderr, spawnError: err });\n });\n child.on('close', (code) => {\n if (settled) return;\n settled = true;\n resolve({ code, stderr });\n });\n } catch (err) {\n if (settled) return;\n settled = true;\n resolve({ code: null, stderr, spawnError: err as Error });\n }\n });\n}\n\n/**\n * Probe whether the launchd agent is currently loaded.\n * Returns false (without error) on non-macOS or when `launchctl` is missing.\n */\nexport async function isAgentLoaded(deps: SetupDeps = {}): Promise<boolean> {\n const { spawn, uid, platform } = resolveLocalDeps(deps);\n if (!isDarwin(platform)) return false;\n const result = await runOnce(spawn, 'launchctl', ['print', serviceTarget(uid)]);\n if (result.spawnError) return false;\n return result.code === 0;\n}\n\nexport interface InstallLaunchAgentOptions {\n /** Override the port baked into the plist's ProgramArguments. */\n port?: number;\n}\n\n/**\n * Install (or refresh) the user LaunchAgent and load it.\n *\n * No-op on non-macOS. On macOS it writes the plist, boots out any stale copy,\n * and bootstraps it into the `gui/<uid>` domain. Idempotent: if the plist is\n * unchanged and already loaded, returns done:false.\n */\nexport async function installLaunchAgent(\n deps: SetupDeps = {},\n opts: InstallLaunchAgentOptions = {},\n): Promise<StepResult> {\n const { fs, spawn, paths, cliEntry, uid, platform } = resolveLocalDeps(deps);\n if (!isDarwin(platform)) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Skipped: launchd supervision only applies on macOS (this host is ${platform})`,\n };\n }\n const plistPath = getPlistPath(paths.homeDir);\n const desired = renderPlist({ cliEntry, homeDir: paths.homeDir, port: opts.port });\n\n try {\n await fs.mkdir(getAgentDir(paths.homeDir), { recursive: true });\n await fs.mkdir(getLogDir(paths.homeDir), { recursive: true });\n\n let existing: string | null = null;\n try {\n existing = await fs.readFile(plistPath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n const unchanged = existing === desired;\n if (unchanged && (await isAgentLoaded(deps))) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `launchd agent already loaded from ${plistPath}`,\n };\n }\n if (!unchanged) {\n await fs.writeFile(plistPath, desired, 'utf8');\n }\n\n // Boot out any stale instance first so bootstrap is idempotent. A missing\n // service exits non-zero (\"No such process\") — that is expected, not fatal.\n const bootout = await runOnce(spawn, 'launchctl', ['bootout', serviceTarget(uid)]);\n if (bootout.spawnError) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Wrote ${plistPath} but \\`launchctl\\` is unavailable (${bootout.spawnError.message}). Load it manually with \\`launchctl bootstrap gui/${uid} ${plistPath}\\`.`,\n };\n }\n\n const bootstrap = await runOnce(spawn, 'launchctl', ['bootstrap', `gui/${uid}`, plistPath]);\n if (bootstrap.spawnError) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: `launchctl bootstrap failed to spawn: ${bootstrap.spawnError.message}`,\n };\n }\n if (bootstrap.code !== 0) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: `launchctl bootstrap gui/${uid} exited ${bootstrap.code ?? 'null'}: ${bootstrap.stderr.trim()}`,\n };\n }\n\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: true,\n message: `launchd agent installed at ${plistPath} and loaded`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: (err as Error).message,\n };\n }\n}\n\n/**\n * Boot out the LaunchAgent and remove the plist.\n * No-op on non-macOS or when the plist is absent.\n */\nexport async function uninstallLaunchAgent(deps: SetupDeps = {}): Promise<StepResult> {\n const { fs, spawn, paths, uid, platform } = resolveLocalDeps(deps);\n if (!isDarwin(platform)) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `Skipped: launchd supervision only applies on macOS (this host is ${platform})`,\n };\n }\n const plistPath = getPlistPath(paths.homeDir);\n try {\n let present = true;\n try {\n await fs.stat(plistPath);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') present = false;\n else throw err;\n }\n if (!present) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: false,\n message: `No launchd agent at ${plistPath}`,\n };\n }\n // Best-effort bootout; a not-loaded agent exits non-zero, which is fine.\n const bootout = await runOnce(spawn, 'launchctl', ['bootout', serviceTarget(uid)]);\n await fs.rm(plistPath, { force: true });\n if (bootout.spawnError) {\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: true,\n message: `Removed ${plistPath} (launchctl unavailable: ${bootout.spawnError.message})`,\n };\n }\n return {\n ok: true,\n name: STEP_SUPERVISION,\n done: true,\n message: `Booted out and removed ${plistPath}`,\n };\n } catch (err) {\n return {\n ok: false,\n name: STEP_SUPERVISION,\n error: (err as Error).message,\n };\n }\n}\n","/**\n * Platform dispatcher for daemon supervision.\n *\n * `setup`/`uninstall` should not care whether a host uses systemd or launchd —\n * they ask `getSupervisor()` for the local implementation and drive it through\n * this common interface. Linux → systemd (`supervision-systemd.ts`),\n * macOS → launchd (`supervision-launchd.ts`), everything else → no supervisor.\n */\nimport {\n UNIT_NAME,\n stepInstallSupervision,\n uninstallSupervision,\n isUnitActive,\n} from './supervision-systemd.js';\nimport {\n PLIST_LABEL,\n installLaunchAgent,\n uninstallLaunchAgent,\n isAgentLoaded,\n} from './supervision-launchd.js';\nimport type { SetupDeps, StepResult } from './steps.js';\n\nexport interface Supervisor {\n readonly kind: 'systemd' | 'launchd';\n /** One-line prompt shown when offering to install supervision. */\n readonly installPrompt: string;\n /** One-line prompt shown when offering to remove supervision. */\n readonly uninstallPrompt: string;\n /** Manual command that finishes enabling if the runtime step fails. */\n readonly enableHint: string;\n install(deps: SetupDeps, opts?: { port?: number }): Promise<StepResult>;\n uninstall(deps: SetupDeps): Promise<StepResult>;\n /** True when the daemon is already supervised (so manual start is skipped). */\n isActive(deps: SetupDeps): Promise<boolean>;\n}\n\nconst systemdSupervisor: Supervisor = {\n kind: 'systemd',\n installPrompt: 'Install user systemd unit to keep the daemon running across logins?',\n uninstallPrompt: 'Disable and remove the systemd user unit (active-work.service)?',\n enableHint: `systemctl --user enable --now ${UNIT_NAME}`,\n install: (deps, opts) => stepInstallSupervision(deps, opts),\n uninstall: (deps) => uninstallSupervision(deps),\n isActive: (deps) => isUnitActive(deps),\n};\n\nconst launchdSupervisor: Supervisor = {\n kind: 'launchd',\n installPrompt: 'Install a launchd agent to keep the daemon running across logins?',\n uninstallPrompt: `Boot out and remove the launchd agent (${PLIST_LABEL})?`,\n enableHint: `launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/${PLIST_LABEL}.plist`,\n install: (deps, opts) => installLaunchAgent(deps, opts),\n uninstall: (deps) => uninstallLaunchAgent(deps),\n isActive: (deps) => isAgentLoaded(deps),\n};\n\n/** Return the supervisor for `platform`, or null when none is integrated. */\nexport function getSupervisor(platform: NodeJS.Platform = process.platform): Supervisor | null {\n if (platform === 'linux') return systemdSupervisor;\n if (platform === 'darwin') return launchdSupervisor;\n return null;\n}\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { runUninstall } from '../setup/steps.js';\nimport { color } from '../utils/color.js';\n\n/**\n * `active-work uninstall` — reverse what setup did. Asks for confirmation before each\n * destructive action (or --yes to skip prompts). Does NOT touch the active\n * root: that's operator data, and removing it should be a deliberate act.\n */\n\nconst ArgsSchema = z.object({\n yes: z.boolean().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst StepSchema = z.object({\n name: z.string(),\n done: z.boolean(),\n message: z.string().optional(),\n error: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n steps: z.array(StepSchema),\n activeRootPreservedAt: z.string(),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nexport default defineCommand<Args, Result>({\n name: 'uninstall',\n description:\n 'Reverse what setup did: remove the skill, stop the daemon, unregister MCP. Preserves the active root.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n yes: {\n long: '--yes',\n short: '-y',\n description: 'Skip all prompts; assume yes.',\n },\n },\n },\n async run(args, ctx) {\n const report = await runUninstall({ yes: args.yes ?? false });\n if (ctx.format !== 'json') {\n for (const step of report.steps) {\n const mark = step.error ? color.red('FAIL') : color.green('OK');\n const trailing = step.error ?? step.message ?? '';\n process.stderr.write(` ${mark} ${step.name}${trailing ? ` — ${trailing}` : ''}\\n`);\n }\n process.stderr.write(\n '\\n' +\n color.dim(\n `Your active root at ${report.activeRootPreservedAt} is preserved. ` +\n 'Remove manually if you want.',\n ) +\n '\\n',\n );\n }\n return report;\n },\n});\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { runDoctor, type CheckStatus } from '../doctor.js';\nimport { color } from '../utils/color.js';\n\n/**\n * `active-work doctor` — health-check the local install.\n *\n * Returns a structured report (exit 0; scripts read the `ok` field) and, in\n * human mode, prints a readable table to stderr like `active-work setup`.\n */\n\nconst ArgsSchema = z.object({});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst CheckSchema = z.object({\n name: z.string(),\n status: z.enum(['ok', 'warn', 'fail']),\n detail: z.string(),\n});\n\nconst ResultSchema = z.object({\n ok: z.boolean(),\n checks: z.array(CheckSchema),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nfunction badge(status: CheckStatus): string {\n if (status === 'ok') return color.green('OK ');\n if (status === 'warn') return color.yellow('WARN');\n return color.red('FAIL');\n}\n\nexport default defineCommand<Args, Result>({\n name: 'doctor',\n description:\n 'Health-check the install: Node, active root, daemon, MCP registration, skill, and supervision.',\n args: ArgsSchema,\n result: ResultSchema,\n async run(_args, ctx) {\n const report = await runDoctor();\n if (ctx.format !== 'json') {\n process.stderr.write(color.bold('active-work doctor') + '\\n');\n for (const check of report.checks) {\n process.stderr.write(` ${badge(check.status)} ${check.name} — ${check.detail}\\n`);\n }\n const summary = report.ok\n ? color.green('All checks passed (warnings are advisory).')\n : color.red('One or more checks failed.');\n process.stderr.write(summary + '\\n');\n }\n return report;\n },\n});\n","/**\n * `active-work doctor` — aggregate health checks for a local install (AW-4).\n *\n * Verifies the pieces `active-work setup` wires up: Node version, the active\n * root + schema version, the MCP daemon, Claude Code MCP registration, the\n * installed skill, and (if the platform supports it) daemon supervision.\n *\n * Every probe is injectable so the checks are unit-testable without a real\n * daemon, filesystem layout, or service manager.\n */\nimport { promises as fsp } from 'node:fs';\nimport nodePath from 'node:path';\nimport os from 'node:os';\nimport { getActiveRoot } from './utils/paths.js';\nimport { isProcessAlive, probeHealth, readPidFile, resolveDaemonPort } from './server/lifecycle.js';\nimport { getSupervisor } from './setup/supervision.js';\nimport { lintHashes, listInitiativeSlugs } from './lint/index.js';\nimport { loadTasks } from './lint/load-tasks.js';\nimport { loadNotesFromDir } from './notes/note-file.js';\nimport { NOTE_TITLE_MAX_LENGTH } from './schemas/note.js';\nimport { sweepAllLeases, type LeaseSweepResult } from './sessions/lease.js';\nimport {\n deriveOpenLoops,\n findSessionIssues,\n type DanglingKind,\n type DanglingResolve,\n type MalformedSession,\n} from './sessions/open-loops.js';\n\nexport type CheckStatus = 'ok' | 'warn' | 'fail';\n\nexport interface DoctorCheck {\n name: string;\n status: CheckStatus;\n detail: string;\n}\n\nexport interface DoctorReport {\n ok: boolean;\n checks: DoctorCheck[];\n}\n\nexport interface DaemonProbe {\n running: boolean;\n healthy: boolean;\n port?: number;\n version?: string;\n pid?: number;\n /** True when `/health` answered but no PID file names the daemon. */\n orphaned?: boolean;\n}\n\nexport interface DoctorDeps {\n fs?: typeof fsp;\n activeRoot?: string;\n homeDir?: string;\n /** Node version string like `process.version` (`v22.4.0`). */\n nodeVersion?: string;\n /** Minimum supported Node major (defaults to 22). */\n minNodeMajor?: number;\n /** Probe the daemon; defaults to reading the pid file + `/health`. */\n probeDaemon?: () => Promise<DaemonProbe>;\n /** Whether a supervisor already owns the daemon; null when unsupported. */\n supervisorActive?: () => Promise<{ kind: string; active: boolean } | null>;\n /** Sweep session leases; defaults to the real `.sessions/` walk. */\n sweepLeases?: (activeRoot: string) => Promise<LeaseSweepResult>;\n}\n\n/**\n * Probe by port alone, for when the PID file is absent or names a dead\n * process. A missing file used to read as \"not running\" outright, which is how\n * a live daemon whose file its predecessor clobbered became indistinguishable\n * from no daemon at all (AW-76). Something answering `/health` outranks the\n * bookkeeping, so adopt the pid/port/version it reports.\n */\nasync function probeByPort(port: number): Promise<DaemonProbe> {\n const health = await probeHealth(port);\n if (!health) return { running: false, healthy: false, port };\n return {\n running: true,\n healthy: true,\n orphaned: true,\n pid: health.pid,\n port: health.port,\n version: health.version,\n };\n}\n\nasync function defaultProbeDaemon(): Promise<DaemonProbe> {\n const entry = await readPidFile();\n if (!entry) return probeByPort(resolveDaemonPort());\n if (!isProcessAlive(entry.pid)) {\n // A pre-meta pid file records port 0; fall back to where a daemon would be.\n return probeByPort(entry.meta.port || resolveDaemonPort());\n }\n const health = await probeHealth(entry.meta.port);\n if (health) {\n return {\n running: true,\n healthy: true,\n pid: health.pid,\n port: health.port,\n version: health.version,\n };\n }\n return {\n running: true,\n healthy: false,\n pid: entry.pid,\n port: entry.meta.port,\n version: entry.meta.version,\n };\n}\n\nasync function defaultSupervisorActive(): Promise<{\n kind: string;\n active: boolean;\n} | null> {\n const supervisor = getSupervisor();\n if (!supervisor) return null;\n return { kind: supervisor.kind, active: await supervisor.isActive({}) };\n}\n\nfunction parseMajor(version: string): number {\n const match = /^v?(\\d+)\\./.exec(version);\n return match ? Number(match[1]) : 0;\n}\n\nasync function fileExists(fs: typeof fsp, target: string): Promise<boolean> {\n try {\n await fs.access(target);\n return true;\n } catch {\n return false;\n }\n}\n\n// `setup` registers the server as `@hjewkes/active-work` (stdio), but users\n// commonly wire it as `active-work` (http, pointed at the daemon). Accept\n// either name.\nconst MCP_SERVER_NAMES = ['@hjewkes/active-work', 'active-work'];\n\nasync function readMcpRegistered(fs: typeof fsp, homeDir: string): Promise<boolean> {\n const configPath = nodePath.join(homeDir, '.claude.json');\n try {\n const raw = await fs.readFile(configPath, 'utf8');\n const parsed = JSON.parse(raw) as {\n mcpServers?: Record<string, unknown>;\n };\n const servers = parsed.mcpServers ?? {};\n return MCP_SERVER_NAMES.some((name) => Boolean(servers[name]));\n } catch {\n return false;\n }\n}\n\nasync function checkNode(deps: DoctorDeps): Promise<DoctorCheck> {\n const version = deps.nodeVersion ?? process.version;\n const min = deps.minNodeMajor ?? 22;\n const major = parseMajor(version);\n if (major >= min) {\n return { name: 'node', status: 'ok', detail: `${version} (>= ${min})` };\n }\n return {\n name: 'node',\n status: 'fail',\n detail: `${version} is older than the required Node ${min}`,\n };\n}\n\nasync function checkActiveRoot(deps: DoctorDeps): Promise<DoctorCheck> {\n const fs = deps.fs ?? fsp;\n const activeRoot = deps.activeRoot ?? getActiveRoot();\n if (!(await fileExists(fs, activeRoot))) {\n return {\n name: 'active-root',\n status: 'fail',\n detail: `${activeRoot} does not exist — run \\`active-work setup\\``,\n };\n }\n const schemaFile = nodePath.join(activeRoot, '.schema-version');\n if (!(await fileExists(fs, schemaFile))) {\n return {\n name: 'active-root',\n status: 'warn',\n detail: `${activeRoot} exists but has no .schema-version`,\n };\n }\n return { name: 'active-root', status: 'ok', detail: activeRoot };\n}\n\nasync function checkDaemon(deps: DoctorDeps): Promise<DoctorCheck> {\n const probe = await (deps.probeDaemon ?? defaultProbeDaemon)();\n const where = `pid ${probe.pid ?? '?'}, port ${probe.port ?? '?'}, v${probe.version ?? '?'}`;\n if (probe.running && probe.healthy && probe.orphaned === true) {\n // Answering but unfiled: `mcp stop`/`mcp restart` key off the PID file and\n // will not find it, so this needs saying even though the daemon is fine.\n return {\n name: 'daemon',\n status: 'warn',\n detail:\n `running (${where}) but no pid file — \\`mcp stop\\`/\\`mcp restart\\` ` +\n 'cannot see it; restart it through your supervisor to re-file it',\n };\n }\n if (probe.running && probe.healthy) {\n return { name: 'daemon', status: 'ok', detail: `running (${where})` };\n }\n if (probe.running && !probe.healthy) {\n return {\n name: 'daemon',\n status: 'warn',\n detail: `pid ${probe.pid ?? '?'} is alive but /health did not answer`,\n };\n }\n // Name the port we probed: a daemon started on a non-default `--port` with\n // no pid file to record it is invisible here, and that beats implying none.\n const probed = probe.port === undefined ? '' : ` (nothing answered port ${probe.port})`;\n return {\n name: 'daemon',\n status: 'warn',\n detail: `not running${probed} — start it with \\`active-work mcp serve --detach\\``,\n };\n}\n\nasync function checkMcp(deps: DoctorDeps): Promise<DoctorCheck> {\n const fs = deps.fs ?? fsp;\n const homeDir = deps.homeDir ?? os.homedir();\n if (await readMcpRegistered(fs, homeDir)) {\n return { name: 'mcp-registration', status: 'ok', detail: 'registered in ~/.claude.json' };\n }\n return {\n name: 'mcp-registration',\n status: 'warn',\n detail: 'not registered with Claude Code — run `active-work setup`',\n };\n}\n\nasync function checkSkill(deps: DoctorDeps): Promise<DoctorCheck> {\n const fs = deps.fs ?? fsp;\n const homeDir = deps.homeDir ?? os.homedir();\n const skill = nodePath.join(homeDir, '.claude', 'skills', 'active-work', 'SKILL.md');\n if (await fileExists(fs, skill)) {\n return { name: 'skill', status: 'ok', detail: skill };\n }\n return {\n name: 'skill',\n status: 'warn',\n detail: 'skill not installed in ~/.claude/skills — run `active-work setup`',\n };\n}\n\nasync function checkSupervisor(deps: DoctorDeps): Promise<DoctorCheck> {\n const result = await (deps.supervisorActive ?? defaultSupervisorActive)();\n if (!result) {\n return {\n name: 'supervision',\n status: 'ok',\n detail: `no supervisor integration for ${process.platform} (optional)`,\n };\n }\n if (result.active) {\n return { name: 'supervision', status: 'ok', detail: `${result.kind} agent is loaded` };\n }\n return {\n name: 'supervision',\n status: 'warn',\n detail: `${result.kind} supervisor not active — re-run \\`active-work setup\\` to enable`,\n };\n}\n\n/** Each rejection kind has a different remedy, so each gets its own sentence. */\nconst DANGLING_REMEDY: Record<DanglingKind, string> = {\n missing: 'no such next_step — fix or drop the ref',\n 'not-prior':\n 'target session ended at or after the resolver, so the close was rejected — re-file the resolve from a later session',\n self: 'a session cannot resolve its own loop — resolve it from a later session',\n};\n\nfunction describeDangling(kind: DanglingKind, entries: string[]): string {\n return `${DANGLING_REMEDY[kind]}: ${entries.join(', ')}`;\n}\n\nfunction openLoopsCheck(byKind: Map<DanglingKind, string[]>): DoctorCheck {\n if (byKind.size === 0) {\n return { name: 'open-loops', status: 'ok', detail: 'no dangling resolves' };\n }\n const parts = [...byKind.entries()].map(([kind, refs]) => describeDangling(kind, refs));\n return { name: 'open-loops', status: 'warn', detail: parts.join('; ') };\n}\n\nfunction taskRefsCheck(entries: string[]): DoctorCheck {\n if (entries.length === 0) {\n return { name: 'task-refs', status: 'ok', detail: 'every next_steps task ref resolves' };\n }\n return {\n name: 'task-refs',\n status: 'warn',\n // Mirrors dangling resolves, but for the other half of the ledger: unlike\n // a bad `resolves` ref, a bad `next_steps` ref is never rejected — the\n // loop just stays open and silent forever.\n detail: `next_steps reference a task that does not exist: ${entries.join('; ')}`,\n };\n}\n\n/** `kind: 'task'` open loops whose `ref` names no task in this initiative. */\nasync function collectBadTaskRefs(\n slug: string,\n initiativeDir: string,\n now: Date,\n): Promise<string[]> {\n const tasks = await loadTasks(initiativeDir);\n const taskIds = new Set(tasks.map((t) => t.id));\n const loops = await deriveOpenLoops(initiativeDir, { now, tasks });\n return loops\n .filter((loop) => loop.kind === 'task' && loop.targetRef !== undefined)\n .filter((loop) => !taskIds.has(loop.targetRef as string))\n .map(\n (loop) =>\n `${slug}/sessions/${loop.sessionFile}.md ${loop.ref} -> ${loop.targetRef} (no such task)`,\n );\n}\n\nfunction sessionFilesCheck(malformed: string[]): DoctorCheck {\n if (malformed.length === 0) {\n return { name: 'session-files', status: 'ok', detail: 'every session file parses' };\n }\n return {\n name: 'session-files',\n status: 'warn',\n // These files are invisible in the ledger: their loops vanish and the loops\n // they closed come back. Only this check can surface them.\n detail: `${malformed.length} session file(s) unreadable — their loops are missing from the ledger: ${malformed.join('; ')}`,\n };\n}\n\n/**\n * Walk every initiative once and report both integrity signals derivation\n * cannot express in the ledger: rejected `resolves` and unparseable sessions.\n */\nasync function checkSessions(deps: DoctorDeps): Promise<DoctorCheck[]> {\n const activeRoot = deps.activeRoot ?? getActiveRoot();\n const slugs = await listInitiativeSlugs(activeRoot);\n const byKind = new Map<DanglingKind, string[]>();\n const malformed: string[] = [];\n const badTaskRefs: string[] = [];\n const now = new Date();\n for (const slug of slugs) {\n const initiativeDir = nodePath.join(activeRoot, slug);\n const issues = await findSessionIssues(initiativeDir);\n for (const entry of issues.dangling) collectDangling(byKind, slug, entry);\n for (const entry of issues.malformed) malformed.push(describeMalformed(slug, entry));\n badTaskRefs.push(...(await collectBadTaskRefs(slug, initiativeDir, now)));\n }\n return [openLoopsCheck(byKind), sessionFilesCheck(malformed), taskRefsCheck(badTaskRefs)];\n}\n\nfunction collectDangling(\n byKind: Map<DanglingKind, string[]>,\n slug: string,\n entry: DanglingResolve,\n): void {\n const line = `${slug}/sessions/${entry.sessionFile}.md resolves ${entry.ref}`;\n const existing = byKind.get(entry.kind);\n if (existing) existing.push(line);\n else byKind.set(entry.kind, [line]);\n}\n\nfunction describeMalformed(slug: string, entry: MalformedSession): string {\n return `${slug}/sessions/${entry.file} (${entry.reason})`;\n}\n\nfunction noteTitlesCheck(entries: string[]): DoctorCheck {\n if (entries.length === 0) {\n return {\n name: 'note-titles',\n status: 'ok',\n detail: `every note title is at most ${NOTE_TITLE_MAX_LENGTH} characters`,\n };\n }\n return {\n name: 'note-titles',\n status: 'warn',\n // `note.add` rejects these now, so anything here predates the bound: the\n // read path stays permissive on purpose, and this is the only place those\n // notes get named.\n detail:\n `note title longer than ${NOTE_TITLE_MAX_LENGTH} characters ` +\n `(rename the title in the file's frontmatter): ${entries.join('; ')}`,\n };\n}\n\n/** Notes whose stored title exceeds the write-time bound. */\nasync function checkNoteTitles(deps: DoctorDeps): Promise<DoctorCheck> {\n const activeRoot = deps.activeRoot ?? getActiveRoot();\n const slugs = await listInitiativeSlugs(activeRoot);\n const overlong: string[] = [];\n for (const slug of slugs) {\n const { notes } = await loadNotesFromDir(nodePath.join(activeRoot, slug));\n for (const note of notes) {\n if (note.frontmatter.title.length <= NOTE_TITLE_MAX_LENGTH) continue;\n overlong.push(\n `${slug}/sources/notes/${note.filename} (${note.frontmatter.title.length} chars)`,\n );\n }\n }\n return noteTitlesCheck(overlong);\n}\n\n/**\n * Session leases under `<activeRoot>/.sessions/` (CC-9).\n *\n * Dead leases are swept by whoever next bootstraps the initiative, so this is\n * mostly a visibility check — but a directory that cannot be pruned means the\n * sibling warning would eventually fire on every launch forever, and that is\n * worth naming before the operator starts ignoring the warning. Never `fail`:\n * leases are advisory, and an install is not broken because one is stuck.\n */\nasync function checkLeases(deps: DoctorDeps): Promise<DoctorCheck> {\n const activeRoot = deps.activeRoot ?? getActiveRoot();\n const result = await (deps.sweepLeases ?? sweepAllLeases)(activeRoot);\n const counts = `${result.live} live, ${result.pruned} pruned`;\n if (result.error) {\n return {\n name: 'session-leases',\n status: 'warn',\n detail: `could not sweep ${nodePath.join(activeRoot, '.sessions')} (${result.error}) — stale leases will keep warning every bootstrap`,\n };\n }\n return { name: 'session-leases', status: 'ok', detail: counts };\n}\n\nfunction artifactHashesCheck(drifted: string[]): DoctorCheck {\n if (drifted.length === 0) {\n return {\n name: 'artifact-hashes',\n status: 'ok',\n detail: 'no hand-edits detected in tracked structured artifacts',\n };\n }\n return {\n name: 'artifact-hashes',\n status: 'warn',\n detail: `hand-edited outside active-work: ${drifted.join('; ')}`,\n };\n}\n\n/** Structured artifacts (tasks/*.yml, artifacts.yml, brief.md) whose content no longer matches the last CLI write (AW-66). */\nasync function checkArtifactHashes(deps: DoctorDeps): Promise<DoctorCheck> {\n const activeRoot = deps.activeRoot ?? getActiveRoot();\n const slugs = await listInitiativeSlugs(activeRoot);\n const drifted: string[] = [];\n for (const slug of slugs) {\n const findings = await lintHashes(slug, nodePath.join(activeRoot, slug));\n drifted.push(...findings.map((f) => `${slug}/${f.file}`));\n }\n return artifactHashesCheck(drifted);\n}\n\n/** Run all health checks and return a report. `ok` is false iff any check failed. */\nexport async function runDoctor(deps: DoctorDeps = {}): Promise<DoctorReport> {\n const [installChecks, sessionChecks, noteTitles, artifactHashes, leases] = await Promise.all([\n Promise.all([\n checkNode(deps),\n checkActiveRoot(deps),\n checkDaemon(deps),\n checkMcp(deps),\n checkSkill(deps),\n checkSupervisor(deps),\n ]),\n checkSessions(deps),\n checkNoteTitles(deps),\n checkArtifactHashes(deps),\n checkLeases(deps),\n ]);\n const checks = [...installChecks, ...sessionChecks, noteTitles, artifactHashes, leases];\n return { ok: checks.every((c) => c.status !== 'fail'), checks };\n}\n","import { promises as fs, type Dirent } from 'node:fs';\nimport path from 'node:path';\nimport { getActiveRoot } from '../utils/paths.js';\nimport { lintBrief } from './brief.js';\nimport { lintHashes } from './hashes.js';\nimport { lintOpenLoops } from './open-loops.js';\nimport { lintSources } from './sources.js';\nimport { lintTasks } from './task.js';\nimport { lintZeroLoops } from './zero-loops.js';\nimport { DEFAULT_LIMITS, type LintFinding, type LintLimits } from './types.js';\n\nexport type { LintFinding, LintLevel, LintLimits } from './types.js';\nexport { DEFAULT_LIMITS } from './types.js';\nexport { lintBrief } from './brief.js';\nexport { lintTasks } from './task.js';\nexport { lintOpenLoops } from './open-loops.js';\nexport { lintZeroLoops } from './zero-loops.js';\nexport { lintSources } from './sources.js';\nexport { lintHashes } from './hashes.js';\n\ninterface LintOptions {\n activeRoot?: string;\n limits?: LintLimits;\n /** Injected for determinism; defaults to `new Date()`. */\n now?: Date;\n}\n\n/**\n * Run every lint against a single initiative and concatenate the findings.\n *\n * Per-lint errors propagate; missing artifacts (handled inside each lint)\n * simply yield no findings.\n */\nexport async function lintSlug(slug: string, options: LintOptions = {}): Promise<LintFinding[]> {\n const activeRoot = options.activeRoot ?? getActiveRoot();\n const limits = options.limits ?? DEFAULT_LIMITS;\n const now = options.now ?? new Date();\n const initiativeDir = path.join(activeRoot, slug);\n const [brief, tasks, openLoops, zeroLoops, sources, hashes] = await Promise.all([\n lintBrief(slug, initiativeDir, limits),\n lintTasks(slug, initiativeDir, limits),\n lintOpenLoops(slug, initiativeDir, limits, now),\n lintZeroLoops(slug, initiativeDir),\n lintSources(slug, initiativeDir),\n lintHashes(slug, initiativeDir),\n ]);\n return [...brief, ...tasks, ...openLoops, ...zeroLoops, ...sources, ...hashes];\n}\n\nexport async function listInitiativeSlugs(activeRoot: string): Promise<string[]> {\n let entries: Dirent[];\n try {\n entries = await fs.readdir(activeRoot, { withFileTypes: true });\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') return [];\n throw err;\n }\n return entries\n .filter((e) => e.isDirectory() && !e.name.startsWith('.'))\n .map((e) => e.name)\n .sort();\n}\n\n/**\n * Lint every initiative under `activeRoot` and return the aggregated\n * findings ordered by slug.\n */\nexport async function lintAll(options: LintOptions = {}): Promise<LintFinding[]> {\n const activeRoot = options.activeRoot ?? getActiveRoot();\n const slugs = await listInitiativeSlugs(activeRoot);\n const findings: LintFinding[] = [];\n for (const slug of slugs) {\n const slugFindings = await lintSlug(slug, {\n activeRoot,\n limits: options.limits,\n now: options.now,\n });\n findings.push(...slugFindings);\n }\n return findings;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readRawFrontmatter } from '../utils/gray-matter-io.js';\nimport { DEFAULT_LIMITS, type LintFinding, type LintLimits } from './types.js';\n\nfunction countBodyLines(body: string): number {\n const lines = body.split('\\n');\n while (lines.length > 0 && lines[lines.length - 1].trim() === '') {\n lines.pop();\n }\n return lines.length;\n}\n\n/**\n * Read `brief.md` and emit warnings about its prose body.\n *\n * Parses with `readRawFrontmatter` so schema-invalid briefs still get linted\n * — fixing schema issues is the writer's job; lint stays advisory.\n */\nexport async function lintBrief(\n slug: string,\n initiativeDir: string,\n limits: LintLimits = DEFAULT_LIMITS,\n): Promise<LintFinding[]> {\n const filePath = path.join(initiativeDir, 'brief.md');\n try {\n await fs.access(filePath);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') return [];\n throw err;\n }\n\n const { body } = await readRawFrontmatter(filePath);\n const bodyLines = countBodyLines(body);\n if (bodyLines <= limits.briefMaxBodyLines) return [];\n\n return [\n {\n level: 'warn',\n slug,\n file: 'brief.md',\n message: `body is ${bodyLines} lines (> ${limits.briefMaxBodyLines}). Move resolved/archival content to a purpose-named file under sources/ and trim the brief.`,\n },\n ];\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { hashContent, readArtifactHashes } from '../utils/artifact-hash.js';\nimport type { LintFinding } from './types.js';\n\n/**\n * Compare each tracked structured artifact's on-disk content against the\n * hash recorded at its last CLI write. Files with no manifest entry (never\n * CLI-written, or predating AW-66) are silently skipped rather than flagged\n * — an empty manifest must never read as \"everything drifted\".\n *\n * A manifest entry whose file has since been deleted (e.g. `task delete`,\n * which does not route through `writeYaml`) is also skipped: absence is not\n * drift.\n */\nexport async function lintHashes(slug: string, initiativeDir: string): Promise<LintFinding[]> {\n const manifest = await readArtifactHashes(initiativeDir);\n const findings: LintFinding[] = [];\n\n for (const [relPath, storedHash] of Object.entries(manifest)) {\n let content: string;\n try {\n content = await fs.readFile(path.join(initiativeDir, relPath), 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') continue;\n throw err;\n }\n if (hashContent(content) === storedHash) continue;\n findings.push({\n level: 'warn',\n slug,\n file: relPath,\n message: `${relPath} was hand-edited outside active-work (content no longer matches the last CLI write) — re-apply the change through the CLI/MCP tools instead of editing the file directly`,\n });\n }\n\n return findings;\n}\n","import path from 'node:path';\nimport { deriveOpenLoops } from '../sessions/open-loops.js';\nimport { loadTasks } from './load-tasks.js';\nimport { DEFAULT_LIMITS, type LintFinding, type LintLimits } from './types.js';\n\n/**\n * A `kind: 'task'` loop closes itself when its task is marked done, because\n * derivation is handed the task list. A `kind: 'pr'` loop has no such luck:\n * `isAutoResolved` can close one, but only when given `mergedPrs`, and\n * bootstrap deliberately withholds that to stay offline on every launch. So a\n * PR loop never closes on its own however long ago its PR merged — it just\n * ages until it trips the cap below, where the generic advice (\"resolve with\n * outcome: abandoned\") is exactly wrong for work that in fact shipped (AW-74).\n */\nfunction staleLoopAdvice(kind: string): string {\n if (kind === 'pr') {\n return (\n 'work it or resolve it explicitly — note that a pr loop can never ' +\n 'close itself (loop derivation stays offline and never checks merge ' +\n 'state), so if the PR has already merged, resolve it with outcome: ' +\n 'done rather than abandoned'\n );\n }\n return 'work it or resolve it with outcome: abandoned';\n}\n\n/**\n * Warn about open loops that have aged past the cap.\n *\n * Derivation is best-effort by construction (malformed sessions are skipped\n * inside `deriveOpenLoops`), so this rule never throws on a broken initiative\n * — it just reports whatever loops it could derive.\n */\nexport async function lintOpenLoops(\n slug: string,\n initiativeDir: string,\n limits: LintLimits = DEFAULT_LIMITS,\n now: Date = new Date(),\n): Promise<LintFinding[]> {\n const tasks = await loadTasks(initiativeDir);\n const loops = await deriveOpenLoops(initiativeDir, { now, tasks });\n\n return loops\n .filter((loop) => loop.ageDays > limits.openLoopMaxAgeDays)\n .map((loop) => ({\n level: 'warn',\n slug,\n file: path.posix.join('sessions', `${loop.sessionFile}.md`),\n message: `open loop ${loop.ref} (\"${loop.text}\") is ${loop.ageDays} days old (> ${limits.openLoopMaxAgeDays}) — ${staleLoopAdvice(loop.kind)}`,\n }));\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport YAML from 'yaml';\nimport { DEFAULT_LIMITS, type LintFinding, type LintLimits } from './types.js';\n\nfunction countNotesLines(notes: string): number {\n const lines = notes.split('\\n');\n while (lines.length > 0 && lines[lines.length - 1].trim() === '') {\n lines.pop();\n }\n return lines.length;\n}\n\nasync function listTaskFiles(tasksDir: string): Promise<string[]> {\n try {\n const entries = await fs.readdir(tasksDir);\n return entries.filter((n) => n.endsWith('.yml')).sort();\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') return [];\n throw err;\n }\n}\n\n/**\n * Walk `tasks/*.yml` and warn when a task's `notes` field exceeds the limit.\n *\n * Files that fail to parse are silently skipped — those are hard failures\n * surfaced by reader-side schema validation elsewhere; lint is warn-only.\n */\nexport async function lintTasks(\n slug: string,\n initiativeDir: string,\n limits: LintLimits = DEFAULT_LIMITS,\n): Promise<LintFinding[]> {\n const tasksDir = path.join(initiativeDir, 'tasks');\n const files = await listTaskFiles(tasksDir);\n const findings: LintFinding[] = [];\n\n for (const filename of files) {\n const filePath = path.join(tasksDir, filename);\n let raw: string;\n try {\n raw = await fs.readFile(filePath, 'utf8');\n } catch {\n continue;\n }\n\n let parsed: unknown;\n try {\n parsed = YAML.parse(raw);\n } catch {\n continue;\n }\n\n if (!parsed || typeof parsed !== 'object') continue;\n const record = parsed as Record<string, unknown>;\n const notes = record.notes;\n if (typeof notes !== 'string' || notes.length === 0) continue;\n\n const lineCount = countNotesLines(notes);\n if (lineCount <= limits.taskNotesMaxLines) continue;\n\n const id = typeof record.id === 'string' ? record.id : filename.replace(/\\.yml$/, '');\n findings.push({\n level: 'warn',\n slug,\n file: path.posix.join('tasks', filename),\n message: `task ${id} notes are ${lineCount} lines — consider summarizing into done_when or a sources/ file`,\n });\n }\n\n return findings;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport YAML from 'yaml';\nimport { SessionFrontmatterSchema, type SessionFrontmatter } from '../schemas/session.js';\nimport type { LintFinding } from './types.js';\n\nconst FRONTMATTER_DELIM = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/;\n\nasync function readSessionFrontmatter(filePath: string): Promise<SessionFrontmatter | null> {\n let raw: string;\n try {\n raw = await fs.readFile(filePath, 'utf8');\n } catch {\n return null;\n }\n const match = FRONTMATTER_DELIM.exec(raw);\n if (!match) return null;\n let parsed: unknown;\n try {\n parsed = YAML.parse(match[1] ?? '');\n } catch {\n return null;\n }\n const result = SessionFrontmatterSchema.safeParse(parsed);\n return result.success ? result.data : null;\n}\n\n/**\n * Warn when a session records an empty ledger — no `next_steps`, no\n * `resolves` — without the `no_loops` marker.\n *\n * An unmarked empty ledger is indistinguishable from a wrap that simply\n * forgot to file anything; `no_loops: true` (written by `wrap --no-loops`) is\n * the only way to say \"deliberately clear\" instead. `track: 'sidecar'` is\n * exempt: `fold` writes sidecar sessions to import already-discovered work,\n * not to record a wrap-up, so every one of them has an empty ledger with no\n * marker by construction — warning on those would be permanent, unactionable\n * noise.\n *\n * Malformed session files are skipped: this rule is warn-only and must never\n * throw on a broken initiative.\n */\nexport async function lintZeroLoops(slug: string, initiativeDir: string): Promise<LintFinding[]> {\n const sessionsDir = path.join(initiativeDir, 'sessions');\n let entries: string[];\n try {\n entries = await fs.readdir(sessionsDir);\n } catch {\n return [];\n }\n\n const findings: LintFinding[] = [];\n for (const filename of entries.filter((n) => n.endsWith('.md')).sort()) {\n const frontmatter = await readSessionFrontmatter(path.join(sessionsDir, filename));\n if (!frontmatter || frontmatter.track === 'sidecar' || frontmatter.no_loops === true) {\n continue;\n }\n if (frontmatter.next_steps.length > 0 || frontmatter.resolves.length > 0) continue;\n\n findings.push({\n level: 'warn',\n slug,\n file: path.posix.join('sessions', filename),\n message:\n 'session recorded an empty ledger (no next_steps, no resolves) without no_loops: true — ' +\n 're-wrap with --no-loops if that was deliberate, or file the loops that were missed',\n });\n }\n return findings;\n}\n","import { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { UsageError } from '../errors.js';\nimport { CURRENT_VERSION } from '../migrations/index.js';\nimport { applyV2ToV3, planV2ToV3 } from '../migrations/v2-to-v3-open-loops.js';\nimport { readSchemaVersion, writeSchemaVersion } from '../schemas/state.js';\nimport { color } from '../utils/color.js';\n\n/**\n * `active-work migrate --dry-run` — report exactly what the pending v2→v3\n * open-loops migration would change, per initiative, writing nothing.\n *\n * The migration otherwise runs unattended under `active-work setup`, which is\n * the only command that migrates — no ordinary command does. This surface\n * exists because v3 rewrites session history: it is reviewed before it runs,\n * and a dry run is the review artifact. Applying is opt-in (`--apply`) so the\n * command cannot mutate data by being run bare.\n */\n\nconst ArgsSchema = z.object({\n dry_run: z.boolean().optional(),\n apply: z.boolean().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst SessionSchema = z.object({\n kind: z.enum(['open', 'abandon']),\n action: z.enum(['write', 'exists']),\n file: z.string(),\n ended: z.string(),\n loops: z.number().int().nonnegative(),\n resolves: z.number().int().nonnegative(),\n});\n\nconst InitiativeSchema = z.object({\n slug: z.string(),\n sessions: z.array(SessionSchema),\n task_seq_backfill: z.number().int().positive().nullable(),\n brief_repairs: z.array(z.string()),\n brief_blocked: z.string().optional(),\n handoff: z.enum(['archive-and-remove', 'archive-exists', 'absent']),\n note: z.string().optional(),\n});\n\nconst ResultSchema = z.object({\n applied: z.boolean(),\n proposal: z.string(),\n initiatives: z.array(InitiativeSchema),\n repairs: z.array(z.object({ action: z.string(), file: z.string(), detail: z.string() })),\n uncovered: z.array(z.string()),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\ntype Initiative = z.infer<typeof InitiativeSchema>;\n\nfunction describe(plan: Awaited<ReturnType<typeof planV2ToV3>>, applied: boolean): Result {\n const initiatives: Initiative[] = plan.initiatives.map((i) => ({\n slug: i.slug,\n sessions: i.sessions.map((s) => ({\n kind: s.kind,\n action: s.exists ? ('exists' as const) : ('write' as const),\n file: s.path,\n ended: s.frontmatter.ended,\n loops: s.frontmatter.next_steps.length,\n resolves: s.frontmatter.resolves.length,\n })),\n task_seq_backfill: i.brief?.taskSeq ?? null,\n brief_repairs: i.brief?.repairs ?? [],\n ...(i.briefBlocked === undefined ? {} : { brief_blocked: i.briefBlocked }),\n handoff: i.handoff,\n ...(i.uncoveredReason === undefined ? {} : { note: i.uncoveredReason }),\n }));\n return {\n applied,\n proposal: plan.proposalOrigin,\n initiatives,\n repairs: plan.repairs.map((r) => ({\n action: r.action,\n file: r.file,\n detail: r.detail,\n })),\n uncovered: initiatives.filter((i) => i.sessions.length === 0).map((i) => i.slug),\n };\n}\n\nfunction renderSession(s: Initiative['sessions'][number]): string {\n const what = s.kind === 'open' ? `opens ${s.loops} loop(s)` : `abandons ${s.resolves} loop(s)`;\n const verb = s.action === 'exists' ? 'already present — skip' : 'write';\n return `session (${s.kind}) ${verb}: ${s.file} — ${what}, ended ${s.ended}`;\n}\n\nfunction renderInitiative(i: Initiative): string {\n const parts: string[] = i.sessions.map(renderSession);\n if (i.sessions.length === 0) {\n parts.push(color.yellow(`NO SYNTHETIC SESSION — ${i.note}`));\n }\n for (const repair of i.brief_repairs) parts.push(`brief repair: ${repair}`);\n if (i.task_seq_backfill !== null) parts.push(`task_seq -> ${i.task_seq_backfill}`);\n if (i.brief_blocked !== undefined) {\n parts.push(color.yellow(`brief NOT rewritten — ${i.brief_blocked}`));\n }\n if (i.handoff === 'archive-and-remove') {\n parts.push('handoff.md -> sources/handoff-archive.md, then delete');\n }\n if (i.handoff === 'archive-exists') {\n parts.push(color.yellow('handoff.md kept — sources/handoff-archive.md already exists'));\n }\n if (parts.length === 0) parts.push('nothing to do');\n return ` ${color.bold(i.slug)}\\n${parts.map((p) => ` - ${p}`).join('\\n')}`;\n}\n\nfunction render(result: Result): string {\n const lines = [\n color.bold(result.applied ? 'active-work migrate (applied)' : 'active-work migrate --dry-run'),\n ` proposal: ${result.proposal}`,\n ...result.initiatives.map(renderInitiative),\n color.bold(' repairs'),\n ...result.repairs.map((r) => ` - ${r.action}: ${r.file} — ${r.detail}`),\n ];\n if (result.uncovered.length > 0) {\n lines.push(\n color.yellow(\n ` ${result.uncovered.length} initiative(s) have no proposal entry and will keep ` +\n `their next-actions only in sources/handoff-archive.md: ${result.uncovered.join(', ')}`,\n ),\n );\n }\n return lines.join('\\n') + '\\n';\n}\n\nexport default defineCommand<Args, Result>({\n name: 'migrate',\n description: 'Preview (or apply) the pending v2→v3 open-loops migration.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n dry_run: { long: '--dry-run', description: 'Report what would change; write nothing' },\n apply: { long: '--apply', description: 'Actually run the migration' },\n },\n usage: 'active-work migrate --dry-run | --apply',\n },\n async run(args, ctx) {\n if (args.apply !== true) {\n const plan = await planV2ToV3(ctx.activeRoot);\n const result = describe(plan, false);\n if (ctx.format !== 'json') process.stderr.write(render(result));\n return result;\n }\n if (args.dry_run === true) {\n throw new UsageError('--dry-run and --apply are mutually exclusive');\n }\n // This command runs one step of the chain. Stamping v3 over data that has\n // not been through v1→v2 would strand the artifacts migration forever.\n const before = await readSchemaVersion(ctx.activeRoot);\n if (before !== CURRENT_VERSION - 1) {\n throw new UsageError(\n `--apply runs only the v2→v3 step, but this root is at schema v${before}. ` +\n 'Run `active-work setup` to work through the pending chain first — it is ' +\n 'the only command that migrates; ordinary commands (`list`, `open`, …) ' +\n 'do not.',\n );\n }\n const plan = await planV2ToV3(ctx.activeRoot);\n await applyV2ToV3(ctx.activeRoot, plan);\n await writeSchemaVersion(ctx.activeRoot, CURRENT_VERSION);\n const result = describe(plan, true);\n if (ctx.format !== 'json') process.stderr.write(render(result));\n return result;\n },\n});\n","import os from 'node:os';\nimport { z } from 'zod';\nimport { defineCommand } from '../registry/index.js';\nimport { ActiveWorkError, UsageError } from '../errors.js';\nimport { getGitRunner, type CommandResult } from '../utils/git-gh.js';\nimport { color } from '../utils/color.js';\n\n/**\n * `active-work sync` — multi-machine git sync for the active root (AW-5).\n *\n * Runs `git pull --rebase && git push` from inside the active root so a\n * git-backed workspace stays in step across machines. Uncommitted local edits\n * are auto-committed first (this is the normal state — you just touched a\n * task), and rebase conflicts are surfaced clearly and left in place for the\n * user to resolve rather than silently aborted.\n */\n\nconst ArgsSchema = z.object({\n message: z.string().min(1).optional(),\n require_clean: z.boolean().optional(),\n});\ntype Args = z.infer<typeof ArgsSchema>;\n\nconst ResultSchema = z.object({\n branch: z.string(),\n committed: z.boolean(),\n committed_files: z.number().int(),\n rebased: z.boolean(),\n pushed: z.boolean(),\n summary: z.string(),\n});\ntype Result = z.infer<typeof ResultSchema>;\n\nexport { setGitRunner, resetRunners } from '../utils/git-gh.js';\n\n/** Run git in the active root; timeouts/spawn failures become clear errors. */\nasync function git(root: string, args: string[]): Promise<CommandResult> {\n return getGitRunner()('git', ['-C', root, ...args]);\n}\n\nasync function assertGitRepo(root: string): Promise<void> {\n let res: CommandResult;\n try {\n res = await git(root, ['rev-parse', '--is-inside-work-tree']);\n } catch (err) {\n throw new ActiveWorkError(\n `could not run git in ${root}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (res.code !== 0 || res.stdout.trim() !== 'true') {\n throw new UsageError(\n `active root is not a git repository: ${root}\\n` +\n 'Initialize it and add a remote, then retry:\\n' +\n ` git -C \"${root}\" init && git -C \"${root}\" remote add origin <url>`,\n );\n }\n}\n\nasync function currentBranch(root: string): Promise<string> {\n const res = await git(root, ['rev-parse', '--abbrev-ref', 'HEAD']);\n const branch = res.stdout.trim();\n if (res.code !== 0 || !branch || branch === 'HEAD') {\n throw new UsageError(\n 'could not determine the current branch (detached HEAD?). ' +\n 'Check out a branch before syncing.',\n );\n }\n return branch;\n}\n\nasync function assertUpstream(root: string, branch: string): Promise<void> {\n const res = await git(root, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);\n if (res.code !== 0) {\n throw new UsageError(\n `branch \"${branch}\" has no upstream configured.\\n` +\n `Set one, then retry:\\n` +\n ` git -C \"${root}\" push -u origin ${branch}`,\n );\n }\n}\n\n/** True when the working tree (tracked or untracked) has changes to commit. */\nasync function isDirty(root: string): Promise<boolean> {\n const res = await git(root, ['status', '--porcelain']);\n return res.stdout.trim().length > 0;\n}\n\nfunction defaultMessage(): string {\n return `aw sync: ${new Date().toISOString()} (${os.hostname()})`;\n}\n\n/** Stage and commit everything. Returns the number of files committed. */\nasync function commitAll(root: string, message: string): Promise<number> {\n const add = await git(root, ['add', '-A']);\n if (add.code !== 0) {\n throw new ActiveWorkError(`git add failed: ${add.stderr.trim() || 'unknown error'}`);\n }\n // Nothing actually staged (e.g. only ignored files touched) — skip commit.\n const staged = await git(root, ['diff', '--cached', '--name-only']);\n const files = staged.stdout.trim().split('\\n').filter(Boolean);\n if (files.length === 0) return 0;\n\n const commit = await git(root, ['commit', '-m', message]);\n if (commit.code !== 0) {\n throw new ActiveWorkError(`git commit failed: ${commit.stderr.trim() || 'unknown error'}`);\n }\n return files.length;\n}\n\n/** Names of files with unresolved merge conflicts. */\nasync function conflictedFiles(root: string): Promise<string[]> {\n const res = await git(root, ['diff', '--name-only', '--diff-filter=U']);\n return res.stdout.trim().split('\\n').filter(Boolean);\n}\n\nasync function headSha(root: string): Promise<string> {\n return (await git(root, ['rev-parse', 'HEAD'])).stdout.trim();\n}\n\nasync function pullRebase(root: string): Promise<{ rebased: boolean }> {\n // Compare HEAD before/after rather than scraping git's (version-dependent)\n // \"up to date\" wording: HEAD moves iff upstream actually had new commits.\n const before = await headSha(root);\n const res = await git(root, ['pull', '--rebase']);\n if (res.code === 0) {\n return { rebased: (await headSha(root)) !== before };\n }\n\n const conflicts = await conflictedFiles(root);\n if (conflicts.length > 0) {\n throw new ActiveWorkError(\n 'sync stopped on a rebase conflict — your local changes are committed and safe.\\n' +\n `Conflicted files:\\n${conflicts.map((f) => ` - ${f}`).join('\\n')}\\n` +\n 'Resolve them, then either continue or undo:\\n' +\n ` git -C \"${root}\" add <files> && git -C \"${root}\" rebase --continue && aw sync\\n` +\n ` git -C \"${root}\" rebase --abort # to undo the pull`,\n );\n }\n throw new ActiveWorkError(\n `git pull --rebase failed: ${res.stderr.trim() || res.stdout.trim() || 'unknown error'}`,\n );\n}\n\nasync function push(root: string): Promise<void> {\n const res = await git(root, ['push']);\n if (res.code !== 0) {\n throw new ActiveWorkError(\n `git push failed: ${res.stderr.trim() || res.stdout.trim() || 'unknown error'}`,\n );\n }\n}\n\nexport default defineCommand<Args, Result>({\n name: 'sync',\n description: 'Sync the active root over git: auto-commit local edits, pull --rebase, then push.',\n args: ArgsSchema,\n result: ResultSchema,\n cli: {\n options: {\n message: {\n long: '--message',\n short: '-m',\n description: 'Commit message for the auto-commit (default: timestamp + host)',\n },\n require_clean: {\n long: '--require-clean',\n description: 'Fail instead of auto-committing when the tree is dirty',\n },\n },\n },\n async run(args, ctx) {\n const root = ctx.activeRoot;\n await assertGitRepo(root);\n const branch = await currentBranch(root);\n await assertUpstream(root, branch);\n\n let committed = false;\n let committedFiles = 0;\n if (await isDirty(root)) {\n if (args.require_clean) {\n throw new UsageError(\n 'active root has uncommitted changes and --require-clean was given.\\n' +\n 'Commit or stash them, or drop --require-clean to auto-commit.',\n );\n }\n committedFiles = await commitAll(root, args.message ?? defaultMessage());\n committed = committedFiles > 0;\n }\n\n const { rebased } = await pullRebase(root);\n await push(root);\n\n const summary =\n `${committed ? `committed ${committedFiles} file(s), ` : ''}` +\n `${rebased ? 'rebased onto upstream, ' : 'already up to date, '}` +\n 'pushed';\n const result: Result = {\n branch,\n committed,\n committed_files: committedFiles,\n rebased,\n pushed: true,\n summary,\n };\n\n if (ctx.format !== 'json') {\n process.stderr.write(color.green(`✓ sync (${branch}): ${summary}`) + '\\n');\n }\n return result;\n },\n});\n","/**\n * Imports every command module and registers its default export with the\n * shared registry. The CLI dispatcher (Wave 3.1) and MCP server (Wave 3.2)\n * import this module first so the registry is populated.\n *\n * Order doesn't affect runtime behavior (the registry is a Map keyed by\n * command name), but is kept alphabetical for readability.\n */\nimport { register, type AnyCommand } from '../registry/index.js';\n\n// Lifecycle\nimport archive from './archive.js';\nimport cmdNew from './new.js';\nimport paths from './paths.js';\nimport rename from './rename.js';\nimport set from './set.js';\nimport touch from './touch.js';\n\n// Focus / pause\nimport focus from './focus.js';\nimport pause from './pause.js';\nimport unfocus from './unfocus.js';\nimport unpause from './unpause.js';\n\n// Tasks\nimport taskAdd from './task-add.js';\nimport taskDelete from './task-delete.js';\nimport taskDone from './task-done.js';\nimport taskEdit from './task-edit.js';\nimport taskList from './task-list.js';\nimport taskReorder from './task-reorder.js';\n\n// Sessions\nimport loops from './loops.js';\nimport preflight from './preflight.js';\nimport resume from './resume.js';\nimport sessionList from './session-list.js';\nimport sessionsBrowser from './sessions-browser.js';\nimport wrap from './wrap.js';\n\n// Notes\nimport noteAdd from './note-add.js';\nimport noteList from './note-list.js';\n\n// Sources / artifacts\nimport artifactAddBranch from './artifact-add-branch.js';\nimport artifactAddStash from './artifact-add-stash.js';\nimport artifactList from './artifact-list.js';\nimport artifactNote from './artifact-note.js';\nimport artifactPrune from './artifact-prune.js';\nimport artifactStatus from './artifact-status.js';\nimport sourceAdd from './source-add.js';\nimport sourceList from './source-list.js';\n\n// Worktree / cross-initiative reads\nimport audit from './audit.js';\nimport contextGraph from './context-graph.js';\nimport list from './list.js';\nimport worktreeSet from './worktree-set.js';\nimport worktreeSetDefault from './worktree-set-default.js';\n\n// Discover / triage\nimport discover from './discover.js';\nimport drop from './drop.js';\nimport fold from './fold.js';\nimport track from './track.js';\n\n// Bootstrap / picker\nimport open from './open.js';\nimport prompt from './prompt.js';\n\n// Editor\nimport edit from './edit.js';\n\n// MCP server\nimport mcpServe from './mcp-serve.js';\nimport mcpStop from './mcp-stop.js';\nimport mcpRestart from './mcp-restart.js';\nimport mcpStatus from './mcp-status.js';\nimport mcpLogs from './mcp-logs.js';\n\n// Session-signal index / Drain miner\nimport minerDrainIngest from './miner-drain-ingest.js';\nimport minerRefresh from './miner-refresh.js';\nimport minerLiveness from './miner-liveness.js';\nimport minerStatus from './miner-status.js';\n\n// agent-chat lifecycle hooks (AW-99)\nimport hooksAgentChatSpawn from './hooks-agent-chat-spawn.js';\nimport hooksAgentChatComplete from './hooks-agent-chat-complete.js';\n\n// Setup / uninstall\nimport setup from './setup.js';\nimport uninstall from './uninstall.js';\nimport doctor from './doctor.js';\nimport migrate from './migrate.js';\nimport sync from './sync.js';\n\nconst ALL_COMMANDS: AnyCommand[] = [\n // lifecycle\n cmdNew,\n set,\n touch,\n paths,\n rename,\n archive,\n // focus / pause\n focus,\n unfocus,\n pause,\n unpause,\n // tasks\n taskAdd,\n taskDone,\n taskList,\n taskEdit,\n taskReorder,\n taskDelete,\n // sessions\n sessionList,\n sessionsBrowser,\n loops,\n preflight,\n resume,\n wrap,\n // notes\n noteAdd,\n noteList,\n // sources / artifacts\n sourceAdd,\n sourceList,\n artifactAddBranch,\n artifactAddStash,\n artifactList,\n artifactStatus,\n artifactPrune,\n artifactNote,\n // worktree / cross-initiative\n worktreeSet,\n worktreeSetDefault,\n audit,\n list,\n contextGraph,\n // discover / triage\n discover,\n fold,\n drop,\n track,\n // bootstrap\n open,\n prompt,\n // editor\n edit,\n // mcp server\n mcpServe,\n mcpStop,\n mcpRestart,\n mcpStatus,\n mcpLogs,\n // session-signal index / drain miner\n minerDrainIngest,\n minerRefresh,\n minerLiveness,\n minerStatus,\n // agent-chat lifecycle hooks (AW-99)\n hooksAgentChatSpawn,\n hooksAgentChatComplete,\n // setup / uninstall\n setup,\n uninstall,\n doctor,\n migrate,\n sync,\n];\n\nfor (const cmd of ALL_COMMANDS) {\n register(cmd);\n}\n\nexport { ALL_COMMANDS };\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { getStateRoot } from './paths.js';\n\n/**\n * Single line in `$XDG_STATE_HOME/active-work/usage.jsonl`.\n *\n * The log is fire-and-forget telemetry written by the CLI dispatcher for\n * later self-reflection. Failures to write must never break the user's\n * command, so `appendUsage` swallows all errors.\n */\nexport interface UsageRecord {\n ts: string; // ISO 8601\n command: string; // registry name\n args?: Record<string, unknown>;\n duration_ms?: number;\n success: boolean;\n exit_code: number;\n}\n\n/** Resolve the on-disk path of the usage log. */\nexport function usageLogPath(): string {\n return path.join(getStateRoot(), 'usage.jsonl');\n}\n\n/**\n * Append a single JSON-encoded record + newline to the usage log.\n *\n * Silent on any error: telemetry must never fail a user-facing command.\n */\nexport async function appendUsage(rec: UsageRecord): Promise<void> {\n try {\n const file = usageLogPath();\n await fs.mkdir(path.dirname(file), { recursive: true });\n await fs.appendFile(file, JSON.stringify(rec) + '\\n', 'utf8');\n } catch {\n // Intentionally silent.\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,SAAS,sBAAsB;;;ACDxC,SAAS,YAAY,UAAU;AAC/B,OAAO,UAAU;AACjB,SAAS,SAAS;AAIlB,IAAM,aAAa,EAAE,OAAO;AAAA,EAC1B,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACtB,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC;AAC1B,CAAC;AAED,IAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,MAAM,EAAE,OAAO;AAAA,EACf,IAAI,EAAE,OAAO;AACf,CAAC;AAED,eAAe,UAAU,GAA6B;AACpD,MAAI;AACF,UAAM,OAAO,MAAM,GAAG,KAAK,CAAC;AAC5B,WAAO,KAAK,YAAY;AAAA,EAC1B,QAAQ;AACN,WAAO;AAAA,EACT;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CAA+C,EAChE;AAAA,IACC;AAAA,IACA;AAAA,EAEF;AAGF,QAAM,OAAO,SAAS,KAAK;AAC3B,aAAW,OAAO,MAAM;AACtB,kBAAc,SAAS,GAAG;AAAA,EAC5B;AAEA,SAAO;AACT;AAOA,eAAsB,KAAK,MAA+B;AACxD,QAAM,UAAU,aAAa;AAC7B,MAAI;AACF,UAAM,QAAQ,WAAW,IAAI;AAAA,EAC/B,SAAS,KAAK;AACZ,QAAI,eAAe,gBAAgB;AAEjC,UAAI,IAAI,SAAS,6BAA6B,IAAI,SAAS,qBAAqB;AAC9E,gBAAQ,KAAK,CAAC;AAAA,MAChB;AACA,cAAQ,KAAK,KAAK,KAAK;AAAA,IACzB;AACA,UAAM,EAAE,SAAS,KAAK,IAAI,YAAY,GAAG;AACzC,cAAU,SAAS,MAAM,OAAO;AAChC,YAAQ,KAAK,IAAI;AAAA,EACnB;AACF;AAEA,KAAK,KAAK,QAAQ,IAAI;","names":["fs","path","z","ArgsSchema","z","ResultSchema","dirExists","fs","path","fs","path","z","ArgsSchema","z","ResultSchema","path","fs","fs","path","z","ArgsSchema","z","ResultSchema","dirExists","fs","path","fs","path","z","ArgsSchema","z","ResultSchema","path","fs","fs","path","z","ArgsSchema","z","ResultSchema","path","fs","z","fs","path","fs","path","ArgsSchema","z","ResultSchema","z","z","ArgsSchema","ResultSchema","applyLocked","z","ArgsSchema","z","ResultSchema","applyLocked","z","ArgsSchema","z","ResultSchema","fs","path","z","fs","path","path","fs","ArgsSchema","z","path","fs","fs","path","z","ArgsSchema","z","ResultSchema","path","fs","path","z","ArgsSchema","z","path","path","z","ArgsSchema","z","path","fs","path","z","z","ArgsSchema","ResultSchema","fs","path","fs","path","z","ArgsSchema","z","ResultSchema","path","fs","path","z","fs","path","path","fs","ArgsSchema","z","ResultSchema","path","fs","path","z","fs","path","path","git","path","fs","ArgsSchema","z","ResultSchema","path","fs","fs","path","z","matter","ArgsSchema","z","ResultSchema","fs","matter","path","fs","path","z","ArgsSchema","z","SessionEntrySchema","ResultSchema","DEFAULT_LIMIT","path","fs","root","sessions","fs","path","z","fs","path","path","fs","z","ArgsSchema","ResultSchema","fs","path","fs","path","z","ArgsSchema","z","ResultSchema","fs","path","z","ArgsSchema","z","ResultSchema","path","z","ArgsSchema","z","ResultSchema","artifactsPath","path","path","z","ArgsSchema","z","ResultSchema","artifactsPath","path","fs","path","z","ArgsSchema","z","ResultSchema","artifactsPath","path","fs","path","z","ArgsSchema","z","ResultSchema","artifactsPath","path","path","fs","z","ArgsSchema","z","ResultSchema","git","dirExists","fs","classify","describe","artifactsPath","path","path","z","ArgsSchema","z","ResultSchema","git","artifactsPath","path","z","fs","path","fs","path","fs","path","ArgsSchema","z","ResultSchema","path","fs","z","z","fs","path","fs","path","z","ArgsSchema","z","ResultSchema","listSlugs","fs","path","z","argsSchema","z","parseErrorSchema","resultSchema","path","z","argsSchema","z","resultSchema","path","path","z","argsSchema","z","resultSchema","path","z","fs","path","path","path","parseWorktreePorcelain","fs","path","path","fs","fs","os","path","truncate","fs","path","ArgsSchema","z","ResultSchema","z","fs","path","fs","path","ArgsSchema","z","ResultSchema","fs","path","z","ArgsSchema","z","ResultSchema","fs","path","fs","path","z","ArgsSchema","z","ResultSchema","dirExists","fs","path","z","ArgsSchema","z","fs","path","spawn","z","ArgsSchema","z","ResultSchema","spawn","path","fileExists","fs","spawn","z","fs","path","body","path","path","transcriptsRoot","path","path","path","fs","fs","path","fs","path","fs","path","startedAt","transcriptsRoot","signal","ArgsSchema","z","ResultSchema","spawn","z","ArgsSchema","z","ResultSchema","spawn","z","ArgsSchema","z","ResultSchema","SHUTDOWN_TIMEOUT_MS","POLL_INTERVAL_MS","detachedSpawn","spawn","z","ArgsSchema","z","ResultSchema","fs","path","z","ArgsSchema","z","ResultSchema","path","fs","z","discoverTranscripts","transcriptsRoot","fs","path","z","path","fs","fs","path","z","z","path","fs","fs","path","z","z","path","fs","startedAt","transcriptsRoot","discoverTranscripts","ArgsSchema","z","ResultSchema","z","ArgsSchema","z","ResultSchema","existsSync","z","existsSync","report","empty","ArgsSchema","z","ResultSchema","existsSync","existsSync","z","ArgsSchema","z","ResultSchema","existsSync","z","fs","path","z","z","path","fs","ArgsSchema","z","ResultSchema","str","spawn","z","ArgsSchema","z","ResultSchema","str","spawn","str","signal","ArgsSchema","ResultSchema","z","fsp","existsSync","nodePath","nodeSpawn","os","fileURLToPath","fs","path","fs","path","fs","path","fs","z","z","fs","fs","path","path","exists","fs","path","fs","listInitiativeSlugs","maxOnDiskTaskNumber","fs","path","matter","YAML","path","readArtifacts","YAML","fs","migrateOne","matter","artifactsPath","MIGRATIONS","MIGRATIONS","path","os","fs","spawn","fsp","nodePath","nodeSpawn","os","resolveLocalDeps","fs","fsp","spawn","nodeSpawn","os","nodePath","runOnce","nodePath","fileURLToPath","existsSync","fs","fsp","spawn","nodeSpawn","os","fs","nodePath","exists","pathExists","runOnce","spawn","ArgsSchema","z","ResultSchema","report","z","ArgsSchema","z","StepSchema","ResultSchema","report","z","fsp","nodePath","os","fs","path","fs","path","fs","path","fs","path","path","fs","path","YAML","fs","path","YAML","listInitiativeSlugs","fs","fileExists","fs","nodePath","fsp","os","listInitiativeSlugs","ArgsSchema","z","ResultSchema","report","z","ArgsSchema","z","ResultSchema","plan","result","os","z","ArgsSchema","z","ResultSchema","os","fs","path","path","fs"]}
|