paseo-room 0.7.0 → 0.8.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.
Files changed (34) hide show
  1. package/README.md +31 -10
  2. package/dist/index.js +34 -15
  3. package/dist/index.js.map +1 -1
  4. package/dist/prompts/contract/lead.md +22 -2
  5. package/dist/runtime-plugin/client/data.ts +2 -1
  6. package/dist/runtime-plugin/client/effort-settings.tsx +89 -0
  7. package/dist/runtime-plugin/client/model.ts +5 -0
  8. package/dist/runtime-plugin/client/pills.ts +8 -2
  9. package/dist/runtime-plugin/client/record.tsx +8 -0
  10. package/dist/runtime-plugin/client/room.tsx +2 -2
  11. package/dist/runtime-plugin/client/views.tsx +2 -0
  12. package/dist/runtime-plugin/index.server.ts +17 -0
  13. package/dist/runtime-plugin/server/attention/delivery.ts +29 -4
  14. package/dist/runtime-plugin/server/attention/engine.ts +62 -28
  15. package/dist/runtime-plugin/server/attention/mask.ts +6 -0
  16. package/dist/runtime-plugin/server/attention/observer.ts +25 -15
  17. package/dist/runtime-plugin/server/attention/signals.ts +25 -15
  18. package/dist/runtime-plugin/server/attention/triage.ts +41 -2
  19. package/dist/runtime-plugin/server/brief.ts +38 -0
  20. package/dist/runtime-plugin/server/context.ts +22 -2
  21. package/dist/runtime-plugin/server/contracts/actions.ts +4 -0
  22. package/dist/runtime-plugin/server/controller.ts +78 -15
  23. package/dist/runtime-plugin/server/domain/state.ts +20 -2
  24. package/dist/runtime-plugin/server/domain/views.ts +22 -4
  25. package/dist/runtime-plugin/server/events/schema.ts +5 -1
  26. package/dist/runtime-plugin/server/handlers/actions.ts +26 -12
  27. package/dist/runtime-plugin/server/handlers/peer.ts +5 -3
  28. package/dist/runtime-plugin/server/handlers/turns.ts +4 -3
  29. package/dist/runtime-plugin/server/paseo-port.ts +23 -0
  30. package/dist/runtime-plugin/server/rpc.ts +25 -1
  31. package/dist/runtime-plugin/server/tools.ts +30 -8
  32. package/dist/runtime-plugin/shared/effort.ts +27 -0
  33. package/dist/runtime-plugin/shared/rpc-contracts.ts +20 -1
  34. package/package.json +1 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../package.json","../src/result.ts","../src/credentials.ts","../src/layout.ts","../src/fsops.ts","../src/roles.ts","../src/room.ts","../src/which.ts","../src/auth.ts","../src/room/prompts.ts","../src/room/instructions.ts","../src/agents/mcp.ts","../src/agents/resources.ts","../src/room/skills.ts","../src/agents/claude.ts","../src/agents/codex.ts","../src/agents/pi.ts","../src/paseo.ts","../src/plugin.ts","../src/runtime-plugin/shared/policy.ts","../src/runtime-plugin/shared/manifest.ts","../src/runtime-plugin/shared/identity.ts","../src/runtime.ts","../src/runtime-plugin/shared/limits.ts","../src/runtime-plugin/server/domain/scope.ts","../src/runtime-plugin/server/domain/state.ts","../src/runtime-plugin/server/domain/receipts.ts","../src/runtime-plugin/server/domain/views.ts","../src/runtime-plugin/server/contracts/assignment.ts","../src/runtime-plugin/server/contracts/actions.ts","../src/runtime-plugin/server/contracts/peer.ts","../src/runtime-plugin/server/events/schema.ts","../src/runtime-plugin/server/store/publish.ts","../src/runtime-plugin/server/store/project.ts","../src/runtime-state.ts","../src/commands.ts","../src/wizard.ts","../src/cli.ts","../src/export.ts","../src/render.ts","../src/index.ts"],"sourcesContent":["{\n \"name\": \"paseo-room\",\n \"version\": \"0.7.0\",\n \"description\": \"One CLI that configures Codex, Claude Code, and Pi role homes in $HOME and registers them with your local Paseo daemon.\",\n \"keywords\": [\n \"paseo\",\n \"codex\",\n \"claude-code\",\n \"pi-coding-agent\",\n \"agent\",\n \"orchestration\",\n \"cli\"\n ],\n \"homepage\": \"https://github.com/cuongntr/paseo-room#readme\",\n \"bugs\": \"https://github.com/cuongntr/paseo-room/issues\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/cuongntr/paseo-room.git\"\n },\n \"license\": \"MIT\",\n \"author\": \"Invoker <cuongnt1987@gmail.com>\",\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"bin\": {\n \"paseo-room\": \"dist/index.js\"\n },\n \"files\": [\n \"dist/\"\n ],\n \"scripts\": {\n \"typecheck\": \"tsc --noEmit && tsc -p src/runtime-plugin\",\n \"lint\": \"eslint . --max-warnings 0\",\n \"test\": \"vitest run\",\n \"test:package\": \"vitest run --config vitest.package.config.ts\",\n \"build\": \"tsup && node --input-type=module -e \\\"import { cpSync, rmSync } from 'node:fs'; for (const [source, target] of [['src/room/prompts', 'dist/prompts'], ['src/room/skills', 'dist/skills'], ['src/plugin-assets', 'dist/plugin-assets'], ['src/runtime-plugin', 'dist/runtime-plugin']]) { rmSync(target, { recursive: true, force: true }); cpSync(source, target, { recursive: true }); }\\\"\",\n \"prepack\": \"npm run build\",\n \"verify\": \"npm run typecheck && npm run lint && npm test && npm run build && npm run test:package\",\n \"attention:eval\": \"node --experimental-transform-types --no-warnings --import ./scripts/ts-resolve.mjs scripts/attention-eval.ts\"\n },\n \"dependencies\": {\n \"@clack/prompts\": \"^1.8.0\",\n \"@getpaseo/client\": \"0.9.1\",\n \"commander\": \"^14.0.3\",\n \"semver\": \"^7.8.5\",\n \"smol-toml\": \"^1.8.0\",\n \"zod\": \"^4.5.4\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^10.0.1\",\n \"@getpaseo/plugin\": \"0.9.1\",\n \"@getpaseo/protocol\": \"0.9.1\",\n \"@types/node\": \"^22.0.0\",\n \"@types/react\": \"19.2.2\",\n \"@types/semver\": \"^7.7.0\",\n \"eslint\": \"^10.10.0\",\n \"react\": \"19.1.0\",\n \"react-native\": \"0.81.5\",\n \"tsup\": \"^8.5.1\",\n \"typescript\": \"~5.9.3\",\n \"typescript-eslint\": \"^8.70.0\",\n \"vitest\": \"^4.1.11\"\n }\n}\n","export type Status = 'pass' | 'warn' | 'fail';\nexport interface Check {\n readonly id: string;\n readonly status: Status;\n readonly message: string;\n readonly fix?: string;\n}\nexport interface Operation {\n readonly action: 'create' | 'update' | 'remove' | 'noop';\n readonly kind: 'dir' | 'file' | 'link' | 'provider' | 'profile' | 'plugin';\n readonly target: string;\n}\nexport type Outcome = 'ok' | 'changes-planned' | 'failed';\nexport interface Result {\n readonly command: string;\n readonly outcome: Outcome;\n readonly changed: boolean;\n readonly checks: readonly Check[];\n readonly operations: readonly Operation[];\n}\n\nexport function pass(id: string, message: string): Check {\n return { id, status: 'pass', message };\n}\nexport function warn(id: string, message: string, fix?: string): Check {\n return { id, status: 'warn', message, ...(fix === undefined ? {} : { fix }) };\n}\nexport function fail(id: string, message: string, fix: string): Check {\n return { id, status: 'fail', message, fix };\n}\nexport function failed(command: string, checks: readonly Check[]): Result {\n return { command, outcome: 'failed', changed: false, checks, operations: [] };\n}\nexport function hasFailure(checks: readonly Check[]): boolean {\n return checks.some(check => check.status === 'fail');\n}\nexport function exitCode(result: Result): number {\n return result.outcome === 'failed' || hasFailure(result.checks) ? 1 : 0;\n}\n","import { lstat, readlink } from 'node:fs/promises';\nimport { warn, type Check } from './result.js';\n\nexport type CredentialPathState =\n | { readonly kind: 'missing' }\n | { readonly kind: 'file' }\n | { readonly kind: 'symlink'; readonly target: string }\n | { readonly kind: 'unsafe'; readonly fileType: string };\n\nexport interface CredentialDiagnostic {\n /** Credential paths are diagnostic-only and must never become managed entries. */\n readonly path: string;\n readonly checks: readonly Check[];\n}\n\nfunction fileType(stat: Awaited<ReturnType<typeof lstat>>): string {\n if (stat.isDirectory()) return 'directory';\n if (stat.isSocket()) return 'socket';\n if (stat.isFIFO()) return 'FIFO';\n if (stat.isCharacterDevice()) return 'character device';\n if (stat.isBlockDevice()) return 'block device';\n return 'unsupported file type';\n}\n\n/** Inspect only path metadata. Credential contents and link targets are never followed. */\nexport async function inspectCredentialPath(path: string): Promise<CredentialPathState> {\n let stat;\n try {\n stat = await lstat(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { kind: 'missing' };\n return { kind: 'unsafe', fileType: 'uninspectable path' };\n }\n if (stat.isFile()) return { kind: 'file' };\n if (!stat.isSymbolicLink()) return { kind: 'unsafe', fileType: fileType(stat) };\n try {\n return { kind: 'symlink', target: await readlink(path) };\n } catch {\n return { kind: 'unsafe', fileType: 'unreadable symbolic link' };\n }\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nexport function roleCommand(\n environment: Readonly<Record<string, string>>,\n executable: string,\n args: readonly string[] = [],\n): string {\n const variables = Object.entries(environment).map(([name, value]) => `${name}=${shellQuote(value)}`);\n return [...variables, ...[executable, ...args].map(shellQuote)].join(' ');\n}\n\nexport interface PreservedCredentialInput {\n readonly id: string;\n readonly agent: string;\n readonly role: string;\n readonly path: string;\n readonly state: Exclude<CredentialPathState, { readonly kind: 'missing' }>;\n readonly login: string;\n readonly status?: string;\n}\n\n/** Produce migration diagnostics for an existing path without claiming authentication. */\nexport function preservedCredentialCheck(input: PreservedCredentialInput): Check {\n const status = input.status ? ` Check status with: ${input.status}.` : '';\n if (input.state.kind === 'file') {\n return warn(`${input.id}.diverged-file-preserve`,\n `${input.agent} ${input.role} auth: configured structurally (diverged-file-preserve); a role-owned credential file exists at ${input.path} and is preserved. Token validity and freshness were not checked.`,\n `If authentication fails, close that role and authenticate it again with: ${input.login}.${status}`);\n }\n if (input.state.kind === 'symlink') {\n return warn(`${input.id}.legacy-shared-risk`,\n `${input.agent} ${input.role} auth: legacy-shared-risk; a credential symlink at ${input.path} -> ${input.state.target} is preserved. Its target was not inspected, followed, or changed.`,\n `Close that role. Remove only the legacy link with: rm -- ${shellQuote(input.path)}. Then create role-owned credentials with: ${input.login}.${status}`);\n }\n return warn(`${input.id}.manual-recovery`,\n `${input.agent} ${input.role} auth: diverged-file-preserve/manual-recovery; ${input.path} is a ${input.state.fileType}, not a credential file. It is preserved without inspection.`,\n `Close that role and inspect the path metadata yourself. Move or remove it manually only when safe, then authenticate with: ${input.login}.${status}`);\n}\n\nexport function presentNames(names: ReadonlySet<string>, supported: readonly string[]): string[] {\n return supported.filter(name => names.has(name));\n}\n\nexport function ambientNamesCheck(id: string, agent: string, role: string, names: readonly string[]): Check {\n return warn(`${id}.ambient-auth-unverifiable`,\n `${agent} ${role} auth: ambient auth unverifiable; ${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} present by name in the setup process. paseo-room does not copy credential values into providers, so availability to the Paseo-launched role, token validity, and freshness were not checked.`);\n}\n","import { homedir } from 'node:os';\nimport { join, resolve, sep } from 'node:path';\nimport { fail, type Check } from './result.js';\nimport type { AgentId, Role } from './roles.js';\n\nexport interface Options {\n readonly roomHome?: string;\n readonly codexHome?: string;\n readonly claudeHome?: string;\n readonly piHome?: string;\n readonly codexBin?: string;\n readonly claudeBin?: string;\n readonly piBin?: string;\n readonly paseoBin?: string;\n}\nexport interface Layout {\n readonly home: string;\n readonly roomHome: string;\n readonly paseoHome: string;\n readonly agentHome: Record<AgentId, string>;\n /** Claude keeps legacy default state beside ~/.claude, but custom config state inside it. */\n readonly claudeState: string;\n readonly bin: Record<AgentId | 'paseo', string>;\n /** The PATH executables are looked up on. Resolved here so nothing reaches for process.env. */\n readonly searchPath: string;\n /** Environment names only, for structural auth diagnostics without retaining values. */\n readonly envNames: ReadonlySet<string>;\n}\n\nfunction pick(...candidates: readonly (string | undefined)[]): string {\n for (const candidate of candidates) if (candidate?.trim()) return candidate.trim();\n throw new Error('Could not determine HOME; pass explicit --room-home and --codex-home/--claude-home paths.');\n}\n\n/** Everything is derived from HOME; flags and environment only override defaults. */\nexport function resolveLayout(options: Options = {}, env: NodeJS.ProcessEnv = process.env): Layout {\n const home = pick(env.HOME, homedir());\n const claudeOverride = options.claudeHome?.trim() || env.CLAUDE_CONFIG_DIR?.trim() || undefined;\n const claudeHome = resolve(pick(claudeOverride, join(home, '.claude')));\n // Relative overrides resolve against the working directory, as a CLI flag should.\n return {\n home,\n roomHome: resolve(pick(options.roomHome, env.PASEO_ROOM_HOME, join(home, '.paseo-room'))),\n paseoHome: resolve(pick(env.PASEO_HOME, join(home, '.paseo'))),\n agentHome: {\n codex: resolve(pick(options.codexHome, env.CODEX_HOME, join(home, '.codex'))),\n claude: claudeHome,\n pi: resolve(pick(options.piHome, env.PI_CODING_AGENT_DIR, join(home, '.pi', 'agent'))),\n },\n claudeState: claudeOverride?.trim() ? join(claudeHome, '.claude.json') : join(home, '.claude.json'),\n bin: {\n codex: pick(options.codexBin, env.CODEX_BIN, 'codex'),\n claude: pick(options.claudeBin, env.CLAUDE_BIN, 'claude'),\n pi: pick(options.piBin, env.PI_BIN, 'pi'),\n paseo: pick(options.paseoBin, env.PASEO_BIN, 'paseo'),\n },\n searchPath: env.PATH ?? '',\n envNames: new Set(Object.keys(env)),\n };\n}\n\n/** True when `path` is the root itself or sits underneath it. */\nexport function contains(root: string, path: string): boolean {\n return path === root || path.startsWith(root.endsWith(sep) ? root : root + sep);\n}\n\n/** The room home must own its directory: no overlap with $HOME or a source agent home. */\nexport function layoutChecks(layout: Layout, agents: readonly AgentId[]): Check[] {\n const checks: Check[] = [];\n if (contains(layout.roomHome, layout.home)) {\n checks.push(fail('room.home', `Refusing to use ${layout.roomHome} as the room home: it contains your home directory.`,\n 'Point --room-home at a dedicated directory, by default ~/.paseo-room.'));\n }\n for (const id of agents) {\n const home = layout.agentHome[id];\n if (contains(layout.roomHome, home) || contains(home, layout.roomHome)) {\n checks.push(fail(`${id}.home`, `The ${id} home ${home} overlaps the room home ${layout.roomHome}.`,\n `Pass --${id}-home pointing at your own ${id} configuration (this happens when setup runs inside a room seat).`));\n }\n }\n return checks;\n}\n\nexport function roleHome(layout: Layout, agent: AgentId, role: Role): string {\n return join(layout.roomHome, 'roles', agent, role);\n}\nexport function sharedRoom(layout: Layout): string {\n return join(layout.roomHome, 'room');\n}\n","import { randomBytes } from 'node:crypto';\nimport { chmod, lstat, mkdir, readdir, readFile, readlink, rename, rm, symlink, unlink, writeFile } from 'node:fs/promises';\nimport type { Stats } from 'node:fs';\nimport { basename, dirname, join } from 'node:path';\nimport type { Operation } from './result.js';\n\n/** A directory the room creates but whose children it does not own. */\nexport interface DirEntry { readonly kind: 'dir'; readonly path: string }\n/** `once` writes the file only when absent: runtime state the agent owns after setup. */\nexport interface FileEntry { readonly kind: 'file'; readonly path: string; readonly content: string; readonly once?: true }\nexport interface LinkEntry { readonly kind: 'link'; readonly path: string; readonly target: string }\n/**\n * A managed path this room declares must not exist, so suppressing generated content\n * removes the stale file instead of leaving an older generation behind. Like every other\n * managed entry it only ever replaces the shape it writes: a regular file. Anything else\n * is refused rather than deleted.\n */\nexport interface AbsentEntry { readonly kind: 'absent'; readonly path: string }\n/**\n * A directory whose whole child inventory the room owns: names outside `children`\n * are removed so a generated projection cannot go stale. Ownership is declared here\n * and never inferred from an ordinary `dir`, so it stays limited to generated\n * projections such as Peer `skills` — never role homes or credential-bearing paths.\n */\nexport interface ManagedDirEntry {\n readonly kind: 'managed-dir';\n readonly path: string;\n readonly children: readonly string[];\n /** The single legacy shape this path may be migrated from: a symlink to this target. */\n readonly legacyLink?: string;\n /**\n * Names inside this directory the room neither writes nor reconciles, because the agent's\n * own runtime owns them. Without this, exact ownership would treat the agent's state as a\n * stale child and try to delete what it did not generate.\n */\n readonly reserved?: readonly string[];\n}\nexport type Entry = DirEntry | FileEntry | LinkEntry | ManagedDirEntry | AbsentEntry;\n\nconst DIR_MODE = 0o700;\nconst FILE_MODE = 0o600;\n\n/**\n * An existing path is not the shape the room manages, so replacing it would destroy\n * something this CLI does not own. Raised before any deletion.\n */\nexport class ManagedPathError extends Error {\n readonly path: string;\n readonly fix: string;\n constructor(path: string, message: string, fix: string) {\n super(message);\n this.name = 'ManagedPathError';\n this.path = path;\n this.fix = fix;\n }\n}\n\nconst MOVE_ASIDE = 'Check that path for role-owned credentials, move it aside manually, then run setup again.';\n\nfunction shape(stat: Stats): string {\n if (stat.isSymbolicLink()) return 'a symbolic link';\n if (stat.isDirectory()) return 'a directory';\n if (stat.isFile()) return 'a regular file';\n return 'a special file';\n}\n\nfunction refuse(path: string, expected: string, stat: Stats): never {\n throw new ManagedPathError(path, `Refusing to replace ${path}: expected ${expected} but found ${shape(stat)}.`, MOVE_ASIDE);\n}\n\nfunction isMissing(error: unknown): boolean {\n return error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT';\n}\n\nasync function lstatOrAbsent(path: string): Promise<Stats | undefined> {\n try { return await lstat(path); } catch (error) {\n if (isMissing(error)) return undefined;\n throw error;\n }\n}\n\n/** Names present under a managed directory that its declaration does not claim. */\nasync function staleChildren(entry: ManagedDirEntry): Promise<string[]> {\n const declared = new Set([...entry.children, ...entry.reserved ?? []]);\n let names: string[];\n try { names = await readdir(entry.path); } catch (error) {\n if (isMissing(error)) return [];\n throw error;\n }\n return names.filter(name => !declared.has(name));\n}\n\nasync function current(entry: Entry): Promise<'absent' | 'same' | 'different'> {\n const stat = await lstatOrAbsent(entry.path);\n // A declared-absent path is already correct when nothing is there.\n if (entry.kind === 'absent') return stat ? 'different' : 'same';\n if (!stat) return 'absent';\n if (entry.kind === 'dir') return stat.isDirectory() ? 'same' : 'different';\n if (entry.kind === 'managed-dir') {\n if (!stat.isDirectory()) return 'different';\n return (await staleChildren(entry)).length === 0 ? 'same' : 'different';\n }\n if (entry.kind === 'link') {\n if (!stat.isSymbolicLink()) return 'different';\n return await readlink(entry.path) === entry.target ? 'same' : 'different';\n }\n if (!stat.isFile()) return 'different';\n if (entry.once) return 'same';\n return await readFile(entry.path, 'utf8') === entry.content ? 'same' : 'different';\n}\n\n/** Everything lives under the room home, which this CLI owns outright. */\nexport async function planEntries(entries: readonly Entry[]): Promise<Operation[]> {\n const operations: Operation[] = [];\n for (const entry of entries) {\n const state = await current(entry);\n operations.push({\n action: state === 'same' ? 'noop' : entry.kind === 'absent' ? 'remove' : state === 'absent' ? 'create' : 'update',\n // A managed directory is still a directory to everything that reports operations.\n kind: entry.kind === 'managed-dir' ? 'dir' : entry.kind === 'absent' ? 'file' : entry.kind,\n target: entry.path,\n });\n }\n return operations;\n}\n\n/** Unique so two runs, or a leftover from a failed one, can never collide. */\nfunction tempSibling(path: string): string {\n return join(dirname(path), `.${basename(path)}.paseo-room-${randomBytes(8).toString('hex')}`);\n}\n\n/** A managed file or link may replace only an absent path or the same shape. */\nasync function assertReplaceable(entry: FileEntry | LinkEntry): Promise<void> {\n const stat = await lstatOrAbsent(entry.path);\n if (!stat) return;\n if (entry.kind === 'link') {\n if (!stat.isSymbolicLink()) refuse(entry.path, 'a symbolic link', stat);\n return;\n }\n if (!stat.isFile()) refuse(entry.path, 'a regular file', stat);\n}\n\n/** Build beside the target and rename, so a reader never sees a half-written path. */\nasync function replaceAtomically(entry: FileEntry | LinkEntry): Promise<void> {\n const temp = tempSibling(entry.path);\n try {\n if (entry.kind === 'link') await symlink(entry.target, temp);\n else {\n await writeFile(temp, entry.content, { mode: FILE_MODE });\n await chmod(temp, FILE_MODE);\n }\n await rename(temp, entry.path);\n } catch (error) {\n await rm(temp, { force: true });\n throw error;\n }\n}\n\nasync function applyDirectory(path: string): Promise<void> {\n const stat = await lstatOrAbsent(path);\n if (stat && !stat.isDirectory()) refuse(path, 'a directory', stat);\n await mkdir(path, { recursive: true, mode: DIR_MODE });\n}\n\n/**\n * Creates the projection, migrating the one declared legacy symlink by unlinking the\n * link alone, and removes only undeclared children that are links or files. An\n * unrecognized shape — including a real child directory — fails instead of being\n * deleted recursively.\n */\nasync function applyManagedDirectory(entry: ManagedDirEntry): Promise<void> {\n const stat = await lstatOrAbsent(entry.path);\n if (stat?.isSymbolicLink() === true) {\n const target = await readlink(entry.path);\n if (entry.legacyLink === undefined || target !== entry.legacyLink) {\n throw new ManagedPathError(entry.path,\n `Refusing to replace ${entry.path}: this room owns that directory, but it is a symbolic link to ${target}.`,\n MOVE_ASIDE);\n }\n // Unlink the alias only; the operator directory it pointed at is never touched.\n await unlink(entry.path);\n await mkdir(entry.path, { recursive: true, mode: DIR_MODE });\n return;\n }\n if (stat && !stat.isDirectory()) refuse(entry.path, 'a directory this room owns', stat);\n await mkdir(entry.path, { recursive: true, mode: DIR_MODE });\n if (!stat) return;\n for (const name of await staleChildren(entry)) {\n const child = join(entry.path, name);\n const childStat = await lstatOrAbsent(child);\n if (!childStat) continue;\n if (!childStat.isFile() && !childStat.isSymbolicLink()) {\n throw new ManagedPathError(child,\n `Refusing to remove ${child}: this room manages ${entry.path} by name, but that stale child is ${shape(childStat)} rather than a generated file or link.`,\n MOVE_ASIDE);\n }\n await rm(child, { force: true });\n }\n}\n\n/**\n * Removes a suppressed managed file. Only a regular file is ever deleted: a directory,\n * link or special file at that path belongs to something this room does not own.\n */\nasync function removeManagedFile(path: string): Promise<void> {\n const stat = await lstatOrAbsent(path);\n if (!stat) return;\n if (!stat.isFile()) refuse(path, 'a regular file this room generated', stat);\n await rm(path, { force: true });\n}\n\n/** Rewrites only what differs, so a repeat run costs stats rather than writes. */\nexport async function applyEntries(entries: readonly Entry[]): Promise<void> {\n for (const entry of entries) {\n if (await current(entry) === 'same') continue;\n if (entry.kind === 'dir') {\n await applyDirectory(entry.path);\n continue;\n }\n if (entry.kind === 'managed-dir') {\n await applyManagedDirectory(entry);\n continue;\n }\n if (entry.kind === 'absent') {\n await removeManagedFile(entry.path);\n continue;\n }\n await mkdir(dirname(entry.path), { recursive: true, mode: DIR_MODE });\n await assertReplaceable(entry);\n await replaceAtomically(entry);\n }\n}\n\nexport async function exists(path: string): Promise<boolean> {\n try { await lstat(path); return true; } catch { return false; }\n}\n\n/** Which of `names` exist under `home`, probed once for all roles that share them. */\nexport async function existingPaths(home: string, names: readonly string[]): Promise<string[]> {\n const paths = names.map(name => join(home, name));\n const present = await Promise.all(paths.map(exists));\n return paths.filter((_, index) => present[index] === true);\n}\n\nexport async function readIfPresent(path: string): Promise<string | undefined> {\n try { return await readFile(path, 'utf8'); } catch { return undefined; }\n}\n","export const ROLES = ['supervisor', 'lead', 'peer'] as const;\nexport type Role = (typeof ROLES)[number];\n\nexport const AGENT_IDS = ['codex', 'claude', 'pi'] as const;\nexport type AgentId = (typeof AGENT_IDS)[number];\n\n/** Supervisor and Lead orchestrate; Peer executes one brief and gets no room tools. */\nexport const ROLE_PASEO_TOOLS: Record<Role, boolean> = { supervisor: true, lead: true, peer: false };\n\n/**\n * Whether a role may be given the opt-in runtime coordinator's assignment-scoped reporting\n * pair, `ask` and `handoff`. This is deliberately not `ROLE_PASEO_TOOLS`: that field is Paseo's\n * native room-tool policy and stays off for Peer, because reporting one's own assignment is not\n * room access. Supervisor and Lead already report through room tools, so only Peer needs it.\n *\n * The flag authorizes nothing by itself. The CLI never writes a reporting server, and no\n * generated provider changes shape from this constant; an installed runtime plugin is the only\n * thing that can act on it, and only for the exact provider it manages. Keeping the two\n * policies separate is the point: a reader can see that granting a report did not grant a\n * control plane, and `verify` still fails if Peer's `paseoTools.enabled` ever flips.\n */\nexport const ROLE_PEER_REPORTING: Record<Role, boolean> = { supervisor: false, lead: false, peer: true };\n\n/**\n * Reasoning effort a seat starts at: Supervisor routes, Lead judges, Peer implements.\n * Deliberately short of the top option on either agent — `ultra` and `ultracode`\n * advertise automatic task delegation, which is a second control plane.\n */\nexport const ROLE_THINKING: Record<Role, string> = { supervisor: 'low', lead: 'high', peer: 'high' };\n\n/**\n * The top option on either agent, which Paseo advertises as maximum reasoning with automatic\n * task delegation. Whether it can still delegate once the room has closed the native\n * multi-agent paths is unverified, so selecting one is reported and never rejected.\n */\nexport const DELEGATING_THINKING = ['ultra', 'ultracode'] as const;\n\n/** Paseo profile appearance encodes the room role, independent of agent runtime. */\nexport const ROLE_ICON: Record<Role, string> = { supervisor: 'eye', lead: 'compass', peer: 'code' };\nexport const ROLE_COLOR: Record<Role, string> = { supervisor: 'violet', lead: 'blue', peer: 'emerald' };\n\n/** Paseo shows these to orchestrating agents, so each one says who may open the seat. */\nexport const ROLE_NOTES: Record<Role, string> = {\n supervisor: 'Human-facing routing seat. Opened by Human, never by another agent; cwd, title and provider label do not prove room membership.',\n lead: 'Sole project technical owner. When opening, copy every present profile launch field. Otherwise reuse only with exact current room Lead provider/mode/workspace evidence plus corroborated ownership. Cwd, title and provider label are not membership. Creates Peer seats only.',\n peer: 'One fresh Lead brief. Open by copying every present profile launch field; require exact current room Peer provider/mode/workspace and paseo.parent-agent-id for its Lead. Cwd, title and provider label are not membership; no orchestration.',\n};\n\nexport function providerId(agent: AgentId, role: Role): string {\n return `${agent}-${role}`;\n}\n/** Distinct from the provider id: a host may already have a profile by that name. */\nexport function profileId(agent: AgentId, role: Role): string {\n return `room-${agent}-${role}`;\n}\nexport function providerLabel(agent: AgentId, role: Role): string {\n const title = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);\n return `${title(agent)} ${title(role)}`;\n}\n","import { join } from 'node:path';\nimport { z } from 'zod';\nimport { readIfPresent } from './fsops.js';\nimport type { Layout } from './layout.js';\nimport { AGENT_IDS, ROLES, type AgentId, type Role } from './roles.js';\n\nexport const MARKER = 'room.json';\n\nconst markerSchema = z.object({\n version: z.string(),\n agents: z.array(z.enum(AGENT_IDS)).min(1),\n roles: z.array(z.enum(ROLES)).min(1),\n /**\n * The rendered contract generation this room was installed from. Optional because a room\n * written before contract provenance existed has no digest, and such a marker must still\n * parse rather than look like a foreign file.\n */\n contract: z.string().min(1).optional(),\n /**\n * False when this room deliberately suppressed the role contract in Claude's `CLAUDE.md`,\n * leaving the plugin as its only Claude carrier. Optional and defaulted to true so a room\n * written before the option existed keeps parsing and keeps its current behaviour.\n */\n claudeMemoryContract: z.boolean().optional(),\n /**\n * Present only when this room opted in to runtime coordination. Missing means disabled, so a\n * marker written before runtime existed keeps parsing and keeps its behaviour.\n */\n runtime: z.strictObject({ enabled: z.literal(true), generation: z.string().min(1), schema: z.literal(1) }).optional(),\n});\nexport type Marker = z.infer<typeof markerSchema>;\nexport type RuntimeMarker = NonNullable<Marker['runtime']>;\n\n/** Deterministic on purpose: re-running setup must not show a phantom change. */\nexport function renderMarker(\n version: string,\n agents: readonly AgentId[],\n roles: readonly Role[],\n contract?: string,\n claudeMemoryContract?: boolean,\n runtime?: RuntimeMarker,\n): string {\n return JSON.stringify({\n version, agents: [...agents], roles: [...roles],\n ...(contract === undefined ? {} : { contract }),\n // Written only when it differs from the default, so an unchanged room's marker is unchanged.\n ...(claudeMemoryContract === false ? { claudeMemoryContract: false } : {}),\n ...(runtime === undefined ? {} : { runtime }),\n } satisfies Marker, null, 2) + '\\n';\n}\n\n/** Records what setup created, so verify and remove touch nothing else. */\nexport async function readMarker(layout: Layout): Promise<Marker | undefined> {\n const source = await readIfPresent(join(layout.roomHome, MARKER));\n if (source === undefined) return undefined;\n try { return markerSchema.parse(JSON.parse(source)); } catch { return undefined; }\n}\n","import { execFile } from 'node:child_process';\nimport { access, constants } from 'node:fs/promises';\nimport { delimiter, isAbsolute, join, resolve } from 'node:path';\nimport { promisify } from 'node:util';\n\nconst run = promisify(execFile);\n\n/**\n * Resolve a command to an absolute executable path on `searchPath`.\n *\n * Deliberately not canonicalised. Version managers point a stable name at a\n * versioned file — `~/.local/bin/claude` at `versions/2.1.267`, mise's\n * `node/latest` at `node/24.15.0` — and the resolved target is deleted by the\n * next upgrade. Providers store this path, so following the link would pin every\n * seat to a binary that stops existing.\n */\nexport async function which(command: string, searchPath: string): Promise<string | undefined> {\n const candidates = isAbsolute(command) || command.includes('/')\n ? [resolve(command)]\n : searchPath.split(delimiter).filter(Boolean).map(entry => join(entry, command));\n for (const candidate of candidates) {\n try {\n await access(candidate, constants.X_OK);\n return candidate;\n } catch { /* try the next PATH entry */ }\n }\n return undefined;\n}\n\nexport interface CommandOutput {\n readonly ok: boolean;\n readonly stdout: string;\n}\n/** Bounded, shell-free probe. Failures are reported, never thrown. */\nexport async function probe(executable: string, args: readonly string[], env: NodeJS.ProcessEnv): Promise<CommandOutput> {\n try {\n const { stdout } = await run(executable, [...args], { env, timeout: 20_000, maxBuffer: 16 * 1024 * 1024, encoding: 'utf8' });\n return { ok: true, stdout };\n } catch {\n return { ok: false, stdout: '' };\n }\n}\n","import { spawn } from 'node:child_process';\nimport { constants } from 'node:os';\nimport { join } from 'node:path';\nimport { lstat } from 'node:fs/promises';\nimport { roleCommand } from './credentials.js';\nimport { resolveLayout, roleHome, type Options } from './layout.js';\nimport { MARKER, readMarker } from './room.js';\nimport { AGENT_IDS, ROLES, type AgentId, type Role } from './roles.js';\nimport { which } from './which.js';\n\nexport const AUTHENTICATION_GUIDE = 'AUTHENTICATION.md';\n/** A truthy empty override suppresses Pi's role-home APPEND_SYSTEM.md discovery. */\nexport const PI_AUTH_ARGV = ['--no-extensions', '--no-approve', '--append-system-prompt', ''] as const;\n\n/** A copy-paste-safe Pi login command that cannot inherit the caller repository cwd. */\nexport function piLoginCommand(rolePath: string, binary: string): string {\n const command = roleCommand({ PI_CODING_AGENT_DIR: rolePath }, binary, PI_AUTH_ARGV);\n return `cd ${roleCommand({}, rolePath)} && ${command}`;\n}\n\nexport interface LoginOutput {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport interface LoginSpawnOptions {\n readonly env: NodeJS.ProcessEnv;\n readonly cwd?: string;\n readonly shell: false;\n readonly stdio: 'inherit';\n}\n\nexport interface LoginChild {\n once(event: 'error', listener: (error: Error) => void): this;\n once(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;\n}\n\nexport type LoginSpawner = (executable: string, argv: readonly string[], options: LoginSpawnOptions) => LoginChild;\n\nconst spawnLogin: LoginSpawner = (executable, argv, options) => spawn(executable, [...argv], options);\n\nfunction title(value: string): string {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\n\nfunction loginInvocation(agent: AgentId, rolePath: string, binary: string): {\n readonly env: Readonly<Record<string, string>>;\n readonly argv: readonly string[];\n readonly cwd?: string;\n readonly command: string;\n} {\n if (agent === 'codex') {\n const env = { CODEX_HOME: rolePath };\n const argv = ['login'] as const;\n return { env, argv, command: roleCommand(env, binary, argv) };\n }\n if (agent === 'claude') {\n const env = { CLAUDE_CONFIG_DIR: rolePath, CLAUDE_SECURESTORAGE_CONFIG_DIR: rolePath };\n const argv = ['auth', 'login'] as const;\n return { env, argv, command: roleCommand(env, binary, argv) };\n }\n const env = { PI_CODING_AGENT_DIR: rolePath };\n const argv = PI_AUTH_ARGV;\n return { env, argv, cwd: rolePath, command: piLoginCommand(rolePath, binary) };\n}\n\n/** Deterministic, secret-free instructions using setup's resolved executables. */\nexport function renderAuthenticationGuide(\n roomHome: string,\n binaries: Readonly<Partial<Record<AgentId, string>>>,\n agents: readonly AgentId[],\n roles: readonly Role[],\n): string {\n const lines = [\n '# Role authentication',\n '',\n 'Setup and verify do not validate authentication, inspect credential contents, query keyrings,',\n 'or test token freshness. Run the command for each role you want to authenticate.',\n '',\n ];\n for (const agent of agents) {\n const binary = binaries[agent];\n if (!binary) throw new Error(`Cannot render authentication guidance without the resolved ${agent} executable.`);\n lines.push(`## ${agent === 'claude' ? 'Claude Code' : title(agent)}`, '');\n for (const role of roles) {\n const invocation = loginInvocation(agent, join(roomHome, 'roles', agent, role), binary);\n lines.push(`### ${title(role)}`, '', '```sh', invocation.command, '```', '');\n if (agent === 'pi') {\n lines.push('Run `/login`, then exit Pi when authentication completes. This minimal interactive',\n 'login session starts in the role home, not the caller repository, disables extension discovery and',\n 'approval files, and suppresses role-home APPEND_SYSTEM.md discovery;',\n 'it is not equivalent to launching the room seat through Paseo.', '');\n }\n }\n }\n return `${lines.join('\\n').trimEnd()}\\n`;\n}\n\nasync function realDirectory(path: string): Promise<'directory' | 'missing' | 'unsafe'> {\n try {\n return (await lstat(path)).isDirectory() ? 'directory' : 'unsafe';\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'ENOENT' ? 'missing' : 'unsafe';\n }\n}\n\nfunction usageError(output: LoginOutput, detail: string): number {\n output.stderr(`paseo-room auth login: ${detail}\\n`);\n return 2;\n}\n\nexport interface LoginOptions extends Options {\n readonly env?: NodeJS.ProcessEnv;\n readonly isTTY: boolean;\n readonly spawn?: LoginSpawner;\n}\n\n/** Launch one vendor's normal interactive login without touching credential stores itself. */\nexport async function loginRole(\n agentValue: string,\n roleValue: string,\n options: LoginOptions,\n output: LoginOutput,\n): Promise<number> {\n const agent = AGENT_IDS.find(value => value === agentValue);\n if (!agent) return usageError(output, `unknown agent \"${agentValue}\"; expected codex, claude, or pi.`);\n const role = ROLES.find(value => value === roleValue);\n if (!role) return usageError(output, `unknown role \"${roleValue}\"; expected supervisor, lead, or peer.`);\n if (!options.isTTY) {\n output.stderr('paseo-room auth login requires interactive stdin, stdout, and stderr terminals.\\n');\n return 1;\n }\n\n const env = options.env ?? process.env;\n const layout = resolveLayout(options, env);\n if (await realDirectory(layout.roomHome) !== 'directory') {\n output.stderr(`No room found at ${layout.roomHome}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n try {\n if (!(await lstat(join(layout.roomHome, MARKER))).isFile()) throw new Error('not a regular marker');\n } catch {\n output.stderr(`No valid room marker found at ${join(layout.roomHome, MARKER)}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n const marker = await readMarker(layout);\n if (!marker) {\n output.stderr(`No valid room marker found at ${join(layout.roomHome, MARKER)}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n if (!marker.agents.includes(agent)) {\n output.stderr(`${title(agent)} is not selected in this room. Re-run setup with --agent ${agent} --apply.\\n`);\n return 1;\n }\n if (!marker.roles.includes(role)) {\n output.stderr(`${title(role)} is not installed for ${agent} in this room. Re-run setup --apply.\\n`);\n return 1;\n }\n const rolePath = roleHome(layout, agent, role);\n for (const path of [join(layout.roomHome, 'roles'), join(layout.roomHome, 'roles', agent), rolePath]) {\n if (await realDirectory(path) !== 'directory') {\n output.stderr(`The selected ${agent} ${role} role is not safely installed at ${rolePath}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n }\n\n const binary = await which(layout.bin[agent], layout.searchPath);\n if (!binary) {\n output.stderr(`${title(agent)} executable not found. Install it, or pass --${agent}-bin /path/to/${agent}.\\n`);\n return 1;\n }\n const invocation = loginInvocation(agent, rolePath, binary);\n if (agent === 'pi') {\n output.stdout(`Starting a minimal interactive Pi login session for ${role} in its role home. Run /login, then exit Pi when authentication completes.\\n`);\n output.stdout('Extensions and approval files are disabled, and role APPEND_SYSTEM.md discovery is suppressed.\\n');\n output.stdout('This is not a room-equivalent Paseo launch.\\n');\n } else {\n output.stdout(`Starting ${agent === 'claude' ? 'Claude Code' : 'Codex'} login for ${role}.\\n`);\n }\n\n const childEnv = { ...env, ...invocation.env };\n const launch = options.spawn ?? spawnLogin;\n return new Promise(resolve => {\n let settled = false;\n const finish = (code: number): void => {\n if (settled) return;\n settled = true;\n resolve(code);\n };\n let child: LoginChild;\n try {\n child = launch(binary, invocation.argv, {\n env: childEnv,\n ...(invocation.cwd === undefined ? {} : { cwd: invocation.cwd }),\n shell: false,\n stdio: 'inherit',\n });\n } catch (error) {\n const detail = error instanceof Error ? error.message : 'unknown error';\n output.stderr(`Could not start ${agent} login: ${detail}\\n`);\n finish(1);\n return;\n }\n child.once('error', error => {\n output.stderr(`Could not start ${agent} login: ${error.message}\\n`);\n finish(1);\n });\n child.once('close', (code, signal) => {\n if (code !== null) {\n finish(code);\n return;\n }\n if (signal) {\n const signalNumber = constants.signals[signal];\n const mapped = typeof signalNumber === 'number' ? 128 + signalNumber : 1;\n output.stderr(`${title(agent)} login ended from signal ${signal}; returning ${String(mapped)}.\\n`);\n finish(mapped);\n return;\n }\n output.stderr(`${title(agent)} login ended without an exit code or signal.\\n`);\n finish(1);\n });\n });\n}\n","import { readFileSync } from 'node:fs';\n\nexport const PROMPT_ASSETS = {\n documents: {\n supervisor: { path: 'documents/supervisor.md', kind: 'head' },\n lead: { path: 'documents/lead.md', kind: 'head' },\n peer: { path: 'documents/peer.md', kind: 'head' },\n },\n contract: {\n sharedAuthority: { path: 'contract/shared-authority.md', kind: 'body' },\n sharedSeatIdentity: { path: 'contract/shared-seat-identity.md', kind: 'section' },\n challengeSignals: { path: 'contract/challenge-signals.md', kind: 'section' },\n supervisor: { path: 'contract/supervisor.md', kind: 'body' },\n lead: { path: 'contract/lead.md', kind: 'body' },\n peer: { path: 'contract/peer.md', kind: 'body' },\n },\n pi: {\n communicationStyle: { path: 'pi/communication-style.md', kind: 'capsule' },\n runtime: { path: 'pi/runtime.md', kind: 'capsule' },\n },\n} as const;\n\nexport type PromptAssetGroup = keyof typeof PROMPT_ASSETS;\nexport type PromptAssetKey<Group extends PromptAssetGroup> = keyof (typeof PROMPT_ASSETS)[Group];\nexport type ContractKey = PromptAssetKey<'contract'>;\nexport type DocumentKey = PromptAssetKey<'documents'>;\nexport type PiPromptKey = PromptAssetKey<'pi'>;\n\ntype PromptAssetKind = 'head' | 'section' | 'body' | 'capsule';\ninterface PromptAssetDefinition {\n readonly path: string;\n readonly kind: PromptAssetKind;\n}\n\nexport class PromptAssetError extends Error {\n readonly logicalAsset: string;\n readonly assetUrl: URL;\n\n constructor(logicalAsset: string, assetUrl: URL, detail: string, options?: ErrorOptions) {\n super(`Prompt asset ${logicalAsset} at ${assetUrl.pathname} ${detail} Reinstall paseo-room and try again.`, options);\n this.name = 'PromptAssetError';\n this.logicalAsset = logicalAsset;\n this.assetUrl = assetUrl;\n }\n}\n\nconst cache = new Map<string, string>();\n\nfunction definition<Group extends PromptAssetGroup>(\n group: Group,\n key: PromptAssetKey<Group>,\n): PromptAssetDefinition {\n const assets = PROMPT_ASSETS[group] as Readonly<Record<string, PromptAssetDefinition>>;\n const asset = assets[String(key)];\n if (asset === undefined) throw new Error(`Unknown prompt asset ${group}.${String(key)}.`);\n return asset;\n}\n\nfunction headingCount(source: string, level: 1 | 2): number {\n const prefix = level === 1 ? '# ' : '## ';\n return source.split('\\n').filter(line => line.startsWith(prefix)).length;\n}\n\nfunction validateHeadOrCapsule(source: string, kind: 'head' | 'capsule'): string {\n const trimmed = source.trimEnd();\n if (!trimmed.trim()) throw new Error('is empty.');\n const firstLine = trimmed.split('\\n', 1)[0] ?? '';\n if (!/^# \\S.*$/.test(firstLine) || headingCount(trimmed, 1) !== 1) {\n throw new Error(`${kind === 'head' ? 'document head' : 'Pi capsule'} must begin with exactly one H1 heading.`);\n }\n return trimmed;\n}\n\n/**\n * Renders one H2 section: the heading verbatim, then each blank-line-delimited statement\n * collapsed onto a single bullet, so authoring line wrapping never reaches a model.\n */\nfunction renderSection(heading: string, bodyLines: readonly string[]): string {\n if (bodyLines.some(line => /^#{1,6}\\s/.test(line))) {\n throw new Error('section must not contain additional Markdown headings.');\n }\n const body = bodyLines.join('\\n').trim();\n if (!body) throw new Error('section must contain at least one non-empty statement.');\n const statements = body.split(/\\n\\s*\\n/).map(statement =>\n statement.split('\\n').map(line => line.trim()).join(' '),\n );\n if (statements.some(statement => !statement)) {\n throw new Error('section must contain only non-empty statements.');\n }\n return `${heading}\\n${statements.map(statement => `- ${statement}`).join('\\n')}`;\n}\n\nfunction validateSection(source: string): string {\n const trimmed = source.trimEnd();\n if (!trimmed.trim()) throw new Error('is empty.');\n const lines = trimmed.split('\\n');\n const heading = lines.shift() ?? '';\n if (!/^## \\S.*$/.test(heading) || headingCount(trimmed, 2) !== 1) {\n throw new Error('section must begin with exactly one H2 heading.');\n }\n return renderSection(heading, lines);\n}\n\ninterface SplitSections {\n readonly preface: readonly string[];\n readonly sections: readonly { readonly heading: string; readonly lines: readonly string[] }[];\n}\n\n/** Splits a multi-section asset at its H2 headings, keeping anything before the first one. */\nfunction splitSections(lines: readonly string[]): SplitSections {\n const preface: string[] = [];\n const sections: { heading: string; lines: string[] }[] = [];\n for (const line of lines) {\n if (/^## \\S.*$/.test(line)) {\n sections.push({ heading: line, lines: [] });\n continue;\n }\n const current = sections.at(-1);\n if (current === undefined) preface.push(line);\n else current.lines.push(line);\n }\n return { preface, sections };\n}\n\n/** A role body: one or more H2 sections and nothing above the first of them. */\nfunction validateBody(source: string): string {\n const trimmed = source.trimEnd();\n if (!trimmed.trim()) throw new Error('is empty.');\n const { preface, sections } = splitSections(trimmed.split('\\n'));\n if (sections.length === 0) throw new Error('role body must contain at least one H2 section.');\n if (preface.some(line => line.trim())) {\n throw new Error('role body must not contain content above its first H2 heading.');\n }\n return sections.map(section => renderSection(section.heading, section.lines)).join('\\n\\n');\n}\n\nexport function loadPromptAsset<Group extends PromptAssetGroup>(\n group: Group,\n key: PromptAssetKey<Group>,\n): string {\n const logicalAsset = `${group}.${String(key)}`;\n const cached = cache.get(logicalAsset);\n if (cached !== undefined) return cached;\n\n const asset = definition(group, key);\n const assetUrl = new URL(`./prompts/${asset.path}`, import.meta.url);\n try {\n const source = readFileSync(assetUrl, 'utf8');\n if (source.includes('\\uFFFD')) throw new Error('is not valid UTF-8 text.');\n const validated = validate(source, asset.kind);\n cache.set(logicalAsset, validated);\n return validated;\n } catch (error) {\n if (error instanceof PromptAssetError) throw error;\n const detail = error instanceof Error ? error.message : 'could not be read.';\n throw new PromptAssetError(logicalAsset, assetUrl, detail, { cause: error });\n }\n}\n\nfunction validate(source: string, kind: PromptAssetKind): string {\n switch (kind) {\n case 'section': return validateSection(source);\n case 'body': return validateBody(source);\n default: return validateHeadOrCapsule(source, kind);\n }\n}\n","import { createHash } from 'node:crypto';\nimport { ROLES, type Role } from '../roles.js';\nimport { loadPromptAsset, type ContractKey } from './prompts.js';\n\nexport type InstructionKind = Role;\n\n// Every role carries the same authority floor. The layers above it reach only the seats they\n// belong to: room-seat identity evidence reaches the two seats that open seats, and the\n// challenge vocabulary reaches the two seats that use it. Broadcasting either one is the\n// attention cost the model exists to avoid.\nconst SHARED_KEYS = {\n supervisor: ['sharedAuthority', 'sharedSeatIdentity'],\n lead: ['sharedAuthority', 'sharedSeatIdentity', 'challengeSignals'],\n peer: ['sharedAuthority', 'challengeSignals'],\n} as const satisfies Record<Role, readonly ContractKey[]>;\n\n// Exactly one role body per role: the body is the review unit, so the composition cannot\n// silently drop or duplicate a role's own obligations.\nconst ROLE_KEYS = {\n supervisor: 'supervisor',\n lead: 'lead',\n peer: 'peer',\n} as const satisfies Record<Role, ContractKey>;\n\nexport function instructionKeys(role: Role): readonly ContractKey[] {\n return [...SHARED_KEYS[role], ROLE_KEYS[role]];\n}\n\n/**\n * The room composes role documents only. Repository workflow policy is a repository's own\n * optional root `WORKSPACE_PROTOCOL.md`: the room ships no default copy of it, so nothing\n * here can inject a second, hidden workflow document into a seat.\n */\nexport function renderInstructions(kind: InstructionKind): string {\n return [\n loadPromptAsset('documents', kind),\n ...instructionKeys(kind).map(key => loadPromptAsset('contract', key)),\n ].join('\\n\\n') + '\\n';\n}\n\n/** Every document the room composes, in one fixed order, so a digest over them is stable. */\nexport const INSTRUCTION_KINDS = [...ROLES] as const satisfies readonly InstructionKind[];\n\n/**\n * Identifies the rendered contract generation a room was installed from.\n *\n * Derived from the composed documents rather than the package version: two packages that\n * render identical contracts are the same generation, and editing one prompt asset without a\n * release still changes the digest. Truncated because this is provenance an operator compares\n * by eye, not a security claim.\n */\nexport function contractDigest(): string {\n const hash = createHash('sha256');\n for (const kind of INSTRUCTION_KINDS) hash.update(`${kind}\\u0000${renderInstructions(kind)}\\u0000`);\n return `sha256:${hash.digest('hex').slice(0, 16)}`;\n}\n","import { fail, type Check } from '../result.js';\n\n/**\n * The bounded heuristic: `paseo` as a whole identifier or path token, including a\n * lower-to-upper camel-case boundary. It is not embedded in a larger word, so `paseo`,\n * `paseo-mcp`, `/opt/paseo/bin/serve` and `paseoRoom` match while `grapaseo`,\n * `paseonaut` and `PASEONAUT` do not.\n *\n * This recognizes an obvious configuration collision and says why it matched. It is not a\n * scanner for a hostile or obfuscated endpoint, and matching nothing proves nothing.\n */\nconst PASEO_TOKEN = /(?<![\\p{L}\\p{N}])[Pp][Aa][Ss][Ee][Oo](?=$|[^\\p{L}\\p{N}]|\\p{Lu}\\p{Ll})/u;\n\n/** Declaration fields that name what a server runs or connects to. */\nconst VALUE_FIELDS = ['command', 'url', 'serverUrl', 'httpUrl', 'endpoint'] as const;\n/** Declaration fields that carry a list of such values. */\nconst LIST_FIELDS = ['args'] as const;\n\n/** One recognizable declaration, kept so the diagnostic can state its own evidence. */\nexport interface McpMatch {\n readonly server: string;\n /** `name`, or the declaration field that carried the token. */\n readonly field: 'name' | (typeof VALUE_FIELDS)[number] | (typeof LIST_FIELDS)[number];\n readonly value: string;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** An MCP declaration map exactly as an already-parsed config carries it. */\nexport function serverTable(value: unknown): Record<string, unknown> {\n return asRecord(value) ?? {};\n}\n\n/** Names one side declares and the other does not, in both directions. */\nexport interface NameDivergence {\n /** Declared for the operator but absent from the compared side. */\n readonly missing: readonly string[];\n /** Declared by the compared side but no longer by the operator. */\n readonly extra: readonly string[];\n}\n\n/**\n * Compare two declaration maps by server name alone. Used for seed-once runtime state the\n * room must not synchronize: a name difference is reportable, and nothing about what those\n * servers run is compared, copied, or written back.\n */\nexport function serverNameDivergence(\n operator: Readonly<Record<string, unknown>>,\n compared: Readonly<Record<string, unknown>>,\n): NameDivergence | undefined {\n const operatorNames = new Set(Object.keys(operator));\n const comparedNames = new Set(Object.keys(compared));\n const missing = [...operatorNames].filter(name => !comparedNames.has(name)).sort();\n const extra = [...comparedNames].filter(name => !operatorNames.has(name)).sort();\n return missing.length === 0 && extra.length === 0 ? undefined : { missing, extra };\n}\n\n/**\n * The declaration maps inside a JSON configuration file, read through the named keys only:\n * nothing else in the document — history, credentials, runtime state — is inspected.\n *\n * Every named key is merged, in the order given, because an agent that accepts more than one\n * key loads all of them: stopping at the first table would let a benign one hide a Paseo\n * declaration under a later key. A name declared twice keeps the earlier key's entry at its\n * own name and the later one under a key-qualified name, so no declaration is lost. Invalid\n * JSON, a non-object root, or a named declaration value that is not an object is rejected:\n * an unparseable source cannot truthfully be reported as inspected and clean.\n */\nexport function jsonServerTable(source: string | undefined, keys: readonly string[]): Record<string, unknown> {\n if (source === undefined) return {};\n const root = asRecord(JSON.parse(source));\n if (!root) throw new TypeError('MCP configuration must be a JSON object.');\n const merged: Record<string, unknown> = {};\n for (const key of keys) {\n const value = root[key];\n if (value === undefined) continue;\n const table = asRecord(value);\n if (!table) throw new TypeError(`${key} must be a JSON object.`);\n for (const [server, declaration] of Object.entries(table)) {\n merged[server in merged ? `${server} (${key})` : server] = declaration;\n }\n }\n return merged;\n}\n\n/** Every recognizably Paseo-related declaration, with the evidence that recognized it. */\nexport function detectPaseoServers(servers: Readonly<Record<string, unknown>>): McpMatch[] {\n const matches: McpMatch[] = [];\n for (const [server, declaration] of Object.entries(servers)) {\n if (PASEO_TOKEN.test(server)) matches.push({ server, field: 'name', value: server });\n const fields = asRecord(declaration);\n if (!fields) continue;\n for (const field of VALUE_FIELDS) {\n const value = fields[field];\n if (typeof value === 'string' && PASEO_TOKEN.test(value)) matches.push({ server, field, value });\n }\n for (const field of LIST_FIELDS) {\n const list = fields[field];\n if (!Array.isArray(list)) continue;\n for (const item of list) {\n if (typeof item === 'string' && PASEO_TOKEN.test(item)) matches.push({ server, field, value: item });\n }\n }\n }\n return matches;\n}\n\nfunction evidence(match: McpMatch): string {\n return match.field === 'name' ? `${match.server} (server name)` : `${match.server} (${match.field}: ${match.value})`;\n}\n\n/**\n * Paseo is the room's only control plane, so a Peer-visible MCP server that looks like a\n * second one fails before anything is applied. The room never edits operator configuration:\n * the fix names the source file and leaves the decision with the operator.\n */\nexport function paseoMcpCheck(id: string, path: string, servers: Readonly<Record<string, unknown>>): Check | undefined {\n const matches = detectPaseoServers(servers);\n if (matches.length === 0) return undefined;\n return fail(id,\n `${path} declares MCP servers that are recognizably Paseo-related: ${matches.map(evidence).join('; ')}.`,\n `Remove or rename those servers in ${path} so no room seat reaches Paseo outside its own seat, then run setup again. paseo-room never edits your MCP configuration, and this name check is a bounded heuristic rather than a sandbox.`);\n}\n","import { readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { Entry } from '../fsops.js';\nimport type { Role } from '../roles.js';\n\n/** The one operator resource the room projects child by child rather than aliasing. */\nexport const SKILLS = 'skills';\n\n/** An orchestration skill: advertised to seats that orchestrate, never to Peer. */\nfunction isPaseoSkill(name: string): boolean {\n return name.toLowerCase().startsWith('paseo');\n}\n\n/**\n * Peer has no room tools, so the room also stops loading orchestration surfaces into it.\n * This closes known configuration paths — Peer still has a shell, so it is not containment.\n */\nfunction receivesExecutableResources(role: Role): boolean {\n return role !== 'peer';\n}\n\n/**\n * The room-owned skill reaches the one seat that owns a repository's workflow policy. Peer\n * reads one brief, and Supervisor holds no standing protocol mandate, so neither receives it.\n */\nfunction receivesRoomSkill(role: Role): boolean {\n return role === 'lead';\n}\n\n/** Names under the operator skills directory; a missing directory is an empty projection. */\nasync function skillNames(\n path: string,\n reserved: ReadonlySet<string>,\n keep: (name: string) => boolean,\n): Promise<string[]> {\n try {\n return (await readdir(path)).filter(name => keep(name) && !reserved.has(name.toLowerCase())).sort();\n } catch (error) {\n if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return [];\n throw error;\n }\n}\n\nexport interface RoomSkill {\n /** The child name inside the projected `skills` directory. */\n readonly name: string;\n /** The shared room-owned source each Lead aggregate links to; declared once. */\n readonly source: string;\n}\n\nexport interface RoleResourceInput {\n readonly role: Role;\n /** The role home every generated alias is created inside. */\n readonly target: string;\n /** The operator agent home the shared resources are read from. */\n readonly home: string;\n /** Shared resource basenames in the adapter's declared order, present or not. */\n readonly names: readonly string[];\n /** Absolute operator paths that exist, probed once for every role. */\n readonly shared: readonly string[];\n /** Basenames whose contents can run code, withheld from Peer. */\n readonly executable: readonly string[];\n /**\n * Names inside the projected `skills` directory that the agent's own runtime writes and\n * owns. A case-insensitive operator-name match is not linked, and the declared runtime name is\n * not reconciled: the agent creates its own copy inside the role home, so projecting one would\n * alias runtime state and reconciling one would delete it.\n */\n readonly reservedSkills?: readonly string[];\n /** The room-owned skill; required so an adapter cannot silently leave Lead without it. */\n readonly roomSkill: RoomSkill;\n /** Lead's room-owned aggregate; required even for calls whose current role does not consume it. */\n readonly leadSkillProjection: string;\n}\n\n/**\n * The projected `skills` directory for a role the room owns by exact child inventory, or\n * `undefined` for a role that keeps the whole-directory alias.\n *\n * Peer receives the non-`paseo*` operator skills and no room-owned skill. Lead receives every\n * operator skill plus the room-owned one; a name that collides with it case-insensitively is not\n * linked, because the room-owned copy owns that name inside the Lead aggregate while the\n * operator's own skill stays where it is, untouched. Case-insensitive comparison keeps the\n * projection valid on the default macOS filesystem as well as on case-sensitive filesystems.\n *\n * The projection is declared even when the operator deleted the whole skills directory: an\n * empty managed directory is what lets a later run remove yesterday's child links. Peer's\n * role-home directory also migrates the legacy whole-directory symlink. Lead instead keeps a\n * symlink at that legacy path and projects children into a room-owned aggregate, so an older\n * package can replace the same symlink shape during rollback.\n */\nasync function skillsProjection(\n input: RoleResourceInput,\n path: string,\n alias: string,\n present: ReadonlySet<string>,\n reserved: ReadonlySet<string>,\n): Promise<Entry[] | undefined> {\n const roomSkill = receivesRoomSkill(input.role) ? input.roomSkill : undefined;\n const projectsChildren = !receivesExecutableResources(input.role) || roomSkill !== undefined;\n if (!projectsChildren) return undefined;\n const reservedNames = new Set([...reserved].map(name => name.toLowerCase()));\n const keep = roomSkill === undefined\n ? (name: string): boolean => !isPaseoSkill(name)\n : (name: string): boolean => name.toLowerCase() !== roomSkill.name.toLowerCase();\n const operator = present.has(path) ? await skillNames(path, reservedNames, keep) : [];\n const children = roomSkill === undefined ? operator : [...operator, roomSkill.name];\n const projection = input.role === 'lead' ? input.leadSkillProjection : alias;\n return [\n {\n kind: 'managed-dir', path: projection, children,\n ...(input.role === 'peer' ? { legacyLink: path } : {}),\n ...(reserved.size === 0 ? {} : { reserved: [...reserved] }),\n },\n ...operator.map(child => ({ kind: 'link' as const, path: join(projection, child), target: join(path, child) })),\n ...(roomSkill === undefined\n ? []\n : [{ kind: 'link' as const, path: join(projection, roomSkill.name), target: roomSkill.source }]),\n ...(input.role === 'lead' ? [{ kind: 'link' as const, path: alias, target: projection }] : []),\n ];\n}\n\n/**\n * Supervisor keeps one alias per shared operator resource that exists, so it never gains a\n * broken link. Lead keeps those aliases too, except its `skills` alias points to an exact\n * room-owned aggregate so the room skill can join the operator's own without writing into the\n * operator home. Peer receives no executable resource, and its `skills` is an exact projection\n * of the non-`paseo*` operator skills.\n *\n * A name the agent's own runtime owns inside a projected directory is reserved rather than\n * projected: the room neither aliases it nor counts it stale, so the agent's state survives.\n */\nexport async function roleResourceEntries(input: RoleResourceInput): Promise<Entry[]> {\n const present = new Set(input.shared);\n const executable = new Set(input.executable);\n const reserved = new Set(input.reservedSkills ?? []);\n const entries: Entry[] = [];\n for (const name of input.names) {\n const path = join(input.home, name);\n const alias = join(input.target, name);\n if (name === SKILLS) {\n const projection = await skillsProjection(input, path, alias, present, reserved);\n if (projection !== undefined) {\n entries.push(...projection);\n continue;\n }\n }\n if (!receivesExecutableResources(input.role) && executable.has(name)) continue;\n if (!present.has(path)) continue;\n entries.push({ kind: 'link', path: alias, target: path });\n }\n return entries;\n}\n","import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Entry } from '../fsops.js';\nimport type { Layout } from '../layout.js';\nimport { sharedRoom } from '../layout.js';\nimport type { AgentId } from '../roles.js';\n\n/**\n * The one room-owned Agent Skill. The name is also the child name inside a Lead role home, so\n * an operator skill of the same name is not linked there: the room-owned copy owns that name\n * inside the room, and the operator's own directory is never touched.\n */\nexport const ROOM_SKILL_NAME = 'paseo-project-onboarding';\n\n/**\n * The skill's exact shape: directories the room creates and files it writes, and nothing else.\n * Ownership is declared here rather than inferred from a recursive copy, so a stray file in the\n * package cannot become a managed path.\n */\nconst SKILL_DIRECTORIES = ['references'] as const;\nconst SKILL_FILES = ['SKILL.md', 'references/workspace-protocol-template.md'] as const;\n\nexport class SkillAssetError extends Error {\n readonly logicalAsset: string;\n readonly assetUrl: URL;\n\n constructor(logicalAsset: string, assetUrl: URL, detail: string, options?: ErrorOptions) {\n super(`Skill asset ${logicalAsset} at ${assetUrl.pathname} ${detail} Reinstall paseo-room and try again.`, options);\n this.name = 'SkillAssetError';\n this.logicalAsset = logicalAsset;\n this.assetUrl = assetUrl;\n }\n}\n\nconst cache = new Map<string, string>();\n\nfunction validateSkillAsset(path: string, source: string): string {\n if (source.includes('\\uFFFD')) throw new Error('is not valid UTF-8 text.');\n if (!source.trim()) throw new Error('is empty.');\n if (path === 'SKILL.md') {\n const frontmatter = /^---\\n([\\s\\S]*?)\\n---\\n/.exec(source)?.[1];\n if (frontmatter === undefined) throw new Error('must begin with YAML frontmatter.');\n const declaredName = /^name: (.+)$/m.exec(frontmatter)?.[1];\n if (declaredName !== ROOM_SKILL_NAME) {\n throw new Error(`frontmatter name must be ${ROOM_SKILL_NAME}.`);\n }\n if (!/^description: \\S.+$/m.test(frontmatter)) {\n throw new Error('frontmatter must contain a non-empty single-line description.');\n }\n }\n if (path === 'references/workspace-protocol-template.md'\n && !source.startsWith('# Workspace protocol template (scaffold)\\n')) {\n throw new Error('must begin with the workspace protocol scaffold heading.');\n }\n return source;\n}\n\nfunction loadSkillAsset(path: string): string {\n const cached = cache.get(path);\n if (cached !== undefined) return cached;\n const logicalAsset = `${ROOM_SKILL_NAME}/${path}`;\n const assetUrl = new URL(`./skills/${ROOM_SKILL_NAME}/${path}`, import.meta.url);\n try {\n const validated = validateSkillAsset(path, readFileSync(assetUrl, 'utf8'));\n cache.set(path, validated);\n return validated;\n } catch (error) {\n if (error instanceof SkillAssetError) throw error;\n const detail = error instanceof Error ? error.message : 'could not be read.';\n throw new SkillAssetError(logicalAsset, assetUrl, detail, { cause: error });\n }\n}\n\n/** Where every Lead projection's room-owned skill link points: one shared source copy. */\nexport function roomSkillSource(layout: Layout): string {\n return join(sharedRoom(layout), 'skills', ROOM_SKILL_NAME);\n}\n\n/** Parent of every per-agent room-owned skill projection. */\nexport function skillProjectionRoot(layout: Layout): string {\n return join(sharedRoom(layout), 'skill-projections');\n}\n\n/** Parent of one agent's room-owned skill projections. */\nexport function agentSkillProjectionRoot(layout: Layout, agent: AgentId): string {\n return join(skillProjectionRoot(layout), agent);\n}\n\n/** A room-owned aggregate that lets the role path remain a rollback-compatible symlink. */\nexport function leadSkillProjection(layout: Layout, agent: AgentId): string {\n return join(agentSkillProjectionRoot(layout, agent), 'lead');\n}\n\n/**\n * The shared skill source, by exact file and directory shape. Added once from the command that\n * builds the desired state rather than per adapter, so three seated agents do not declare the\n * same managed paths three times.\n */\nexport function roomSkillEntries(layout: Layout, agents: readonly AgentId[]): Entry[] {\n const root = roomSkillSource(layout);\n return [\n { kind: 'dir', path: join(sharedRoom(layout), 'skills') },\n { kind: 'dir', path: skillProjectionRoot(layout) },\n ...agents.map(agent => ({ kind: 'dir' as const, path: agentSkillProjectionRoot(layout, agent) })),\n { kind: 'managed-dir', path: root, children: ['SKILL.md', ...SKILL_DIRECTORIES] },\n {\n kind: 'managed-dir', path: join(root, 'references'),\n children: SKILL_FILES.filter(path => path.startsWith('references/')).map(path => path.slice('references/'.length)),\n },\n ...SKILL_FILES.map(path => ({\n kind: 'file' as const, path: join(root, path), content: loadSkillAsset(path),\n })),\n ];\n}\n","import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport {\n ambientNamesCheck, inspectCredentialPath, presentNames, preservedCredentialCheck,\n roleCommand, type CredentialDiagnostic,\n} from '../credentials.js';\nimport type { Layout } from '../layout.js';\nimport { roleHome } from '../layout.js';\nimport type { Entry } from '../fsops.js';\nimport { existingPaths, exists, readIfPresent } from '../fsops.js';\nimport { fail, pass, warn, type Check } from '../result.js';\nimport type { Role } from '../roles.js';\nimport { renderInstructions } from '../room/instructions.js';\nimport { which } from '../which.js';\nimport { jsonServerTable, paseoMcpCheck, serverNameDivergence, type NameDivergence } from './mcp.js';\nimport { roleResourceEntries } from './resources.js';\nimport { leadSkillProjection, ROOM_SKILL_NAME, roomSkillSource } from '../room/skills.js';\nimport type { Agent, AgentPlan, BuildOptions } from './types.js';\n\n/** Operator-authored resources shared by reference; native agent definitions stay out. */\nconst SHARED = [\n 'skills', 'plugins', 'commands', 'hooks', 'rules',\n 'output-styles', 'keybindings.json', 'themes',\n] as const;\n/** These carry executable prompts, plugin code, and hook programs: never shared with Peer. */\nconst EXECUTABLE = ['plugins', 'commands', 'hooks'] as const;\n/**\n * Claude's own runtime writes its downloaded skill bucket here, inside whichever home it runs\n * with. It is agent state rather than an operator-authored skill, so the room leaves the name\n * alone in both directions: it is never projected and never reconciled as stale.\n */\nconst RUNTIME_SKILLS = ['synced'] as const;\n/** Claude keeps personal MCP declarations under this one key of its runtime state. */\nconst MCP_KEY = 'mcpServers';\nconst AUTH_ENV = [\n 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN',\n 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY',\n] as const;\nconst CONTROL_PLANE_ENV = {\n CLAUDE_CODE_DISABLE_AGENT_VIEW: '1',\n CLAUDE_CODE_DISABLE_WORKFLOWS: '1',\n} as const;\n/** One native-orchestration deny list, emitted into both Claude and Paseo enforcement surfaces. */\nconst DISALLOWED_TOOLS = [\n 'Task', 'Agent', 'Workflow', 'ListAgents', 'SendMessage', 'TeamCreate', 'TeamDelete',\n 'TaskCreate', 'TaskGet', 'TaskList', 'TaskUpdate',\n 'CronCreate', 'CronDelete', 'CronList',\n] as const;\nconst SECURE_STORAGE_ENV = 'CLAUDE_SECURESTORAGE_CONFIG_DIR';\n/** Copied once so a fresh role home does not re-run interactive onboarding. */\nconst SEEDED_KEYS = ['hasCompletedOnboarding', 'theme', 'installMethod', 'userID', MCP_KEY] as const;\n\nfunction asObject(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};\n}\n\n/** Any unreadable or non-object source is simply an empty starting point. */\nfunction readObject(source: string | undefined): Record<string, unknown> {\n try { return asObject(source === undefined ? {} : JSON.parse(source)); } catch { return {}; }\n}\n\n/** Read optional runtime state, but do not turn an inspection failure into \"no servers\". */\nasync function readStateIfPresent(path: string): Promise<string | undefined> {\n try { return await readFile(path, 'utf8'); } catch (error) {\n if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return undefined;\n throw error;\n }\n}\n\n/** Render only room-owned policy; operator settings are intentionally not imported. */\nexport function renderRoleSettings(role: Role, secureStorageDir?: string): string {\n const settings = {\n // Claude applies settings.env after the launch environment, so repeat provider closures here.\n env: {\n ...CONTROL_PLANE_ENV,\n PASEO_ROOM_ROLE: role,\n ...(secureStorageDir === undefined ? {} : { [SECURE_STORAGE_ENV]: secureStorageDir }),\n },\n // Provider disallowedTools is not sufficient alone; the isolated home carries the same list.\n permissions: { deny: DISALLOWED_TOOLS },\n // These restrictive settings cannot be weakened by another settings scope.\n disableAgentView: true,\n disableWorkflows: true,\n crossSessionInbound: 'refuse',\n };\n return JSON.stringify(settings, null, 2) + '\\n';\n}\n\nexport function renderRoleState(source: string | undefined): string {\n const root = readObject(source);\n const state: Record<string, unknown> = { hasCompletedOnboarding: true };\n for (const key of SEEDED_KEYS) if (key in root) state[key] = root[key];\n return JSON.stringify(state, null, 2) + '\\n';\n}\n\n/**\n * Preserve the operator's global memory, then add the stronger room role contract.\n *\n * With the contract suppressed, the file carries the operator's memory alone: the plugin is\n * then the room's only Claude contract carrier. Returning `undefined` for an operator with no\n * global memory keeps the room from writing a file whose whole content it just removed.\n */\nexport function renderRoleMemory(source: string | undefined, role: Role, contract = true): string | undefined {\n const operator = source?.trim();\n if (!contract) return operator ? `${operator}\\n` : undefined;\n return operator ? `${operator}\\n\\n${renderInstructions(role)}` : renderInstructions(role);\n}\n\nexport async function claudeCredentialDiagnostic(\n layout: Layout,\n role: Role,\n platform: NodeJS.Platform = process.platform,\n binary = 'claude',\n): Promise<CredentialDiagnostic> {\n const home = roleHome(layout, 'claude', role);\n const path = join(home, '.credentials.json');\n const roleEnvironment = { CLAUDE_CONFIG_DIR: home, [SECURE_STORAGE_ENV]: home };\n const login = roleCommand(roleEnvironment, binary, ['auth', 'login']);\n const status = roleCommand(roleEnvironment, binary, ['auth', 'status']);\n const state = await inspectCredentialPath(path);\n const id = `claude.auth.${role}`;\n if (state.kind !== 'missing') {\n return { path, checks: [preservedCredentialCheck({ id, agent: 'Claude', role, path, state, login, status })] };\n }\n const ambient = presentNames(layout.envNames, AUTH_ENV);\n if (ambient.length > 0) return { path, checks: [ambientNamesCheck(id, 'Claude', role, ambient)] };\n if (platform === 'darwin') {\n return { path, checks: [{\n id: `${id}.native-keyring-unverifiable`, status: 'warn',\n message: `Claude ${role} auth: native-keyring unverifiable; the current runtime's secure-storage location is pinned to this role home, but no Keychain entry was queried and older runtime behavior was not assumed. Token validity and freshness were not checked.`,\n fix: `Authenticate this role with: ${login}. If that subcommand is unavailable, launch ${roleCommand(roleEnvironment, binary)} and run /login. Check status with: ${status}.`,\n }] };\n }\n return { path, checks: [{\n id: `${id}.login-required`, status: 'warn',\n message: `Claude ${role} auth: login-required; no role-owned .credentials.json or supported ambient auth environment name was detected. Authentication was not attempted.`,\n fix: `Authenticate this role with: ${login}. If that subcommand is unavailable, launch ${roleCommand(roleEnvironment, binary)} and run /login. Check status with: ${status}.`,\n }] };\n}\n\n/**\n * `.claude.json` is seeded once and runtime-owned afterwards, so a later change to the\n * operator's own MCP inventory never reaches a role home. That is reported rather than\n * repaired: rewriting the file would discard whatever the runtime has since stored in it.\n * Only declared names are compared — no command, URL, argument, credential or history value\n * is read for this check.\n */\nfunction mcpDriftCheck(role: Role, home: string, path: string, divergence: NameDivergence): Check {\n const parts = [\n ...(divergence.missing.length === 0 ? [] : [`not declared for this role: ${divergence.missing.join(', ')}`]),\n ...(divergence.extra.length === 0 ? [] : [`declared only for this role: ${divergence.extra.join(', ')}`]),\n ];\n return warn(`claude.mcp.drift.${role}`,\n `Claude ${role} MCP server names differ from your own Claude MCP servers (${parts.join('; ')}). ${path} is seeded once and owned by Claude afterwards, so paseo-room did not change it; only server names were compared.`,\n `If this role should have the same servers, add them with: CLAUDE_CONFIG_DIR=${home} claude mcp add ... — or delete ${path} and run setup --apply to reseed it from your current Claude state, which discards that role's other runtime state.`);\n}\n\nexport const claudeAgent: Agent = {\n id: 'claude',\n label: 'Claude Code',\n homeEnv: 'CLAUDE_CONFIG_DIR',\n // Agent View and dynamic workflows have entry points beyond model tool calls.\n providerEnv: CONTROL_PLANE_ENV,\n defaultModeId: 'bypassPermissions',\n // Keep the legacy Task name and block current native orchestration,\n // shared task/cron coordination, and cross-session paths. Paseo alone owns\n // agent lifecycle and coordination.\n pins: { disallowedTools: DISALLOWED_TOOLS },\n async build(layout: Layout, roles: readonly Role[], options: BuildOptions = {}): Promise<AgentPlan> {\n const home = layout.agentHome.claude;\n const binary = await which(layout.bin.claude, layout.searchPath);\n if (!binary) {\n return { entries: [], checks: [fail('claude.bin', 'Claude Code executable not found.', 'Install Claude Code, or pass --claude-bin /path/to/claude.')] };\n }\n if (!(await exists(home))) {\n return { entries: [], checks: [fail('claude.home', `No Claude config directory at ${home}.`, 'Run claude once to initialise it, or pass --claude-home.')] };\n }\n const checks: Check[] = [pass('claude.home', `Claude Code found at ${binary} using ${home}.`)];\n\n const memorySource = await readIfPresent(join(home, 'CLAUDE.md'));\n let stateSource: string | undefined;\n let operatorServers: Record<string, unknown>;\n try {\n stateSource = await readStateIfPresent(layout.claudeState);\n // `.claude.json` is runtime-owned after the seed write, so only this one key is interpreted.\n operatorServers = jsonServerTable(stateSource, [MCP_KEY]);\n } catch {\n return { entries: [], checks: [...checks, fail('claude.mcp',\n `Could not read ${layout.claudeState} as a JSON object, so its MCP declarations could not be inspected.`,\n 'Make your Claude state file readable and fix its JSON structure, then run setup again.')] };\n }\n const stateConflict = paseoMcpCheck('claude.mcp', layout.claudeState, operatorServers);\n if (stateConflict) return { entries: [], checks: [...checks, stateConflict] };\n const shared = await existingPaths(home, SHARED);\n const entries: Entry[] = [];\n const credentials: CredentialDiagnostic[] = [];\n const providerEnv: Partial<Record<Role, Readonly<Record<string, string>>>> = {};\n // Held back so a hard conflict found in a later role is never preceded by advice.\n const drift: Check[] = [];\n const roomSkill = { name: ROOM_SKILL_NAME, source: roomSkillSource(layout) };\n for (const role of roles) {\n const target = roleHome(layout, 'claude', role);\n const statePath = join(target, '.claude.json');\n // A seeded role home keeps its own copy, so its declarations are checked as well.\n let roleStateSource: string | undefined;\n let roleServers: Record<string, unknown>;\n try {\n roleStateSource = await readStateIfPresent(statePath);\n roleServers = jsonServerTable(roleStateSource, [MCP_KEY]);\n } catch {\n return { entries: [], checks: [...checks, fail(`claude.mcp.${role}`,\n `Could not read ${statePath} as a JSON object, so its MCP declarations could not be inspected.`,\n 'Make that role-owned Claude state file readable and fix its JSON structure, then run setup again.')] };\n }\n const roleConflict = paseoMcpCheck(`claude.mcp.${role}`, statePath, roleServers);\n if (roleConflict) return { entries: [], checks: [...checks, roleConflict] };\n // Only an already-seeded role home can have drifted: an absent one is about to be\n // seeded from the same operator state this run just read.\n if (roleStateSource !== undefined) {\n const divergence = serverNameDivergence(operatorServers, roleServers);\n if (divergence) drift.push(mcpDriftCheck(role, target, statePath, divergence));\n }\n entries.push({ kind: 'dir', path: target });\n const memoryPath = join(target, 'CLAUDE.md');\n const memory = renderRoleMemory(memorySource, role, options.memoryContract ?? true);\n // Suppressed with no operator memory to carry: remove any file an earlier run wrote,\n // so a stale contract generation cannot outlive the option that turned it off.\n entries.push(memory === undefined\n ? { kind: 'absent', path: memoryPath }\n : { kind: 'file', path: memoryPath, content: memory });\n entries.push({ kind: 'file', path: join(target, 'settings.json'), content: renderRoleSettings(role, target) });\n entries.push({ kind: 'file', path: statePath, content: renderRoleState(stateSource), once: true });\n entries.push(...await roleResourceEntries({\n role, target, home, names: SHARED, shared, executable: EXECUTABLE,\n reservedSkills: RUNTIME_SKILLS, roomSkill,\n leadSkillProjection: leadSkillProjection(layout, 'claude'),\n }));\n credentials.push(await claudeCredentialDiagnostic(layout, role, process.platform, binary));\n providerEnv[role] = { [SECURE_STORAGE_ENV]: target };\n }\n return { entries, credentials, checks: [...checks, ...drift], binary, providerEnv };\n },\n};\n","import { join } from 'node:path';\nimport { parse, stringify, type TomlTable } from 'smol-toml';\nimport { inspectCredentialPath, preservedCredentialCheck, roleCommand, type CredentialDiagnostic } from '../credentials.js';\nimport type { Layout } from '../layout.js';\nimport { roleHome } from '../layout.js';\nimport type { Entry } from '../fsops.js';\nimport { existingPaths, readIfPresent } from '../fsops.js';\nimport { fail, pass, type Check } from '../result.js';\nimport type { Role } from '../roles.js';\nimport { renderInstructions } from '../room/instructions.js';\nimport { probe, which } from '../which.js';\nimport { paseoMcpCheck, serverTable } from './mcp.js';\nimport { roleResourceEntries } from './resources.js';\nimport { leadSkillProjection, ROOM_SKILL_NAME, roomSkillSource } from '../room/skills.js';\nimport type { Agent, AgentPlan } from './types.js';\n\n/** Read-only operator resources every role shares by reference, never by copy. */\nconst SHARED = ['AGENTS.md', 'skills', 'plugins', 'hooks.json'] as const;\n/** Plugins and hooks run operator code, so Peer — which has no room tools — never loads them. */\nconst EXECUTABLE = ['plugins', 'hooks.json'] as const;\nconst CATALOG = 'model-catalog.json';\nexport type CodexCredentialStore = 'file' | 'ephemeral' | 'auto' | 'keyring' | 'unknown';\n\nfunction table(parent: TomlTable, key: string): TomlTable {\n const value = parent[key];\n if (value === undefined || typeof value !== 'object' || Array.isArray(value) || value instanceof Date) {\n return (parent[key] = {});\n }\n return value;\n}\n\n/**\n * Close Codex's native multi-agent features inside one scope: the top-level table, or an\n * active profile, which outranks it.\n */\nfunction pinMultiAgentFeatures(scope: TomlTable): void {\n const features = table(scope, 'features');\n features.multi_agent = false;\n // Newer configs represent v2 as a table; keep that shape rather than writing a\n // boolean at the same key, which would be a TOML conflict.\n if (typeof features.multi_agent_v2 === 'boolean' || features.multi_agent_v2 === undefined) features.multi_agent_v2 = false;\n else table(features, 'multi_agent_v2').enabled = false;\n}\n\nexport interface RoleConfigInput {\n readonly roleDocument: string;\n readonly catalogPath?: string;\n}\n/**\n * Copy the operator's config, then override only the keys the room owns.\n *\n * `model_instructions_file` is deliberately untouched: it *replaces* Codex's base\n * prompt, so writing it would mean vendoring and maintaining a full copy of that\n * prompt. The room contract is additive and belongs in `developer_instructions`.\n */\nexport function renderRoleConfig(source: TomlTable, input: RoleConfigInput): string {\n const config = structuredClone(source);\n config.sandbox_mode = 'danger-full-access';\n config.approval_policy = 'never';\n config.developer_instructions = input.roleDocument;\n if (input.catalogPath) config.model_catalog_json = input.catalogPath;\n // Codex's own multi-agent mode would compete with the room's role contract.\n // `[agents]` stays top-level only: Codex profiles have no such key.\n table(config, 'agents').enabled = false;\n pinMultiAgentFeatures(config);\n // An active profile outranks the top-level keys, so every room-owned key a profile can\n // also carry — sandbox, approval, catalog, features — has to land there too.\n if (typeof config.profile === 'string') {\n const profile = table(table(config, 'profiles'), config.profile);\n profile.sandbox_mode = 'danger-full-access';\n profile.approval_policy = 'never';\n if (input.catalogPath) profile.model_catalog_json = input.catalogPath;\n pinMultiAgentFeatures(profile);\n }\n return stringify(config) + '\\n';\n}\n\nexport function renderCatalog(catalog: unknown): string {\n return JSON.stringify(catalog, (key, value: unknown) => (key === 'multi_agent_version' ? null : value), 2) + '\\n';\n}\n\n/** Facts the captured catalog itself carries. Nothing is inferred beyond them. */\nexport interface CatalogEvidence {\n /** Codex reads the catalog as a JSON object, so any other top-level shape is not one. */\n readonly object: boolean;\n /** How many `multi_agent_version` fields the capture carried, and the copy therefore nulls. */\n readonly markers: number;\n}\n\nexport function catalogEvidence(catalog: unknown): CatalogEvidence {\n let markers = 0;\n const walk = (value: unknown): void => {\n if (Array.isArray(value)) { for (const item of value) walk(item); return; }\n if (value === null || typeof value !== 'object') return;\n for (const [key, nested] of Object.entries(value)) {\n if (key === 'multi_agent_version') markers += 1;\n else walk(nested);\n }\n };\n walk(catalog);\n return { object: catalog !== null && typeof catalog === 'object' && !Array.isArray(catalog), markers };\n}\n\n/** Read only the generated config's non-secret store selector. */\nexport function codexCredentialStore(config: TomlTable): CodexCredentialStore {\n const value = config.cli_auth_credentials_store;\n return value === 'file' || value === 'ephemeral' || value === 'auto' || value === 'keyring'\n ? value\n : 'unknown';\n}\n\nasync function credentialDiagnostic(\n layout: Layout,\n role: Role,\n store: CodexCredentialStore,\n binary: string,\n): Promise<CredentialDiagnostic> {\n const home = roleHome(layout, 'codex', role);\n const path = join(home, 'auth.json');\n const login = roleCommand({ CODEX_HOME: home }, binary, ['login']);\n const status = roleCommand({ CODEX_HOME: home }, binary, ['login', 'status']);\n const state = await inspectCredentialPath(path);\n const id = `codex.auth.${role}`;\n const checks: Check[] = [];\n if (state.kind !== 'missing') {\n checks.push(preservedCredentialCheck({ id, agent: 'Codex', role, path, state, login, status }));\n } else {\n if (store === 'keyring' || store === 'auto') {\n checks.push({\n id: `${id}.native-keyring-unverifiable`, status: 'warn',\n message: `Codex ${role} auth: native-keyring unverifiable; cli_auth_credentials_store is ${store}, and no keyring was queried. Token validity and freshness were not checked.`,\n fix: `Authenticate this role with: ${login}. Check status with: ${status}.`,\n });\n } else {\n const apiKey = layout.envNames.has('OPENAI_API_KEY')\n ? ' OPENAI_API_KEY is present only in the setup process; Codex has not stored it for this role and paseo-room does not copy it into the provider.'\n : '';\n const detail = store === 'ephemeral'\n ? 'cli_auth_credentials_store is ephemeral, so no persistent credential file is expected'\n : `no role-owned auth.json exists${store === 'file' ? ' for the configured file store' : ''}`;\n checks.push({\n id: `${id}.login-required`, status: 'warn',\n message: `Codex ${role} auth: login-required; ${detail}.${apiKey} Authentication was not attempted.`,\n fix: `Authenticate this role with: ${login}. Check status with: ${status}.`,\n });\n }\n }\n if (state.kind !== 'missing' && (store === 'keyring' || store === 'auto')) {\n checks.push({\n id: `${id}.native-keyring-unverifiable`, status: 'warn',\n message: `Codex ${role} auth: native-keyring unverifiable; cli_auth_credentials_store is ${store}, and the preserved auth.json does not prove what the runtime will use. No keyring was queried.`,\n fix: `Check status without exposing credentials: ${status}.`,\n });\n }\n return { path, checks };\n}\n\nexport const codexAgent: Agent = {\n id: 'codex',\n label: 'Codex',\n homeEnv: 'CODEX_HOME',\n defaultModeId: 'full-access',\n // Without these, Paseo's own mode preset (default auto-review) is sent to the\n // app-server and outranks the sandbox/approval keys in the generated config.\n pins: { params: { sandbox_mode: 'danger-full-access', approval_policy: 'never' } },\n async build(layout: Layout, roles: readonly Role[]): Promise<AgentPlan> {\n const checks: Check[] = [];\n const home = layout.agentHome.codex;\n const binary = await which(layout.bin.codex, layout.searchPath);\n if (!binary) {\n return { entries: [], checks: [fail('codex.bin', 'Codex executable not found.', 'Install Codex, or pass --codex-bin /path/to/codex.')] };\n }\n const configPath = join(home, 'config.toml');\n const raw = await readIfPresent(configPath);\n if (raw === undefined) {\n return { entries: [], checks: [fail('codex.home', `No config.toml in ${home}.`, 'Run codex once to initialise it, or pass --codex-home.')] };\n }\n let source: TomlTable;\n try { source = parse(raw); } catch {\n return { entries: [], checks: [fail('codex.config', `Could not read ${configPath} as TOML.`, 'Fix the syntax in your Codex config, then run setup again.')] };\n }\n checks.push(pass('codex.home', `Codex found at ${binary} using ${home}.`));\n // Paseo is the room's only control plane, so a Paseo-looking MCP server fails here,\n // before any managed path is written, rather than being filtered out of the copy.\n const conflict = paseoMcpCheck('codex.mcp', configPath, serverTable(source.mcp_servers));\n if (conflict) return { entries: [], checks: [...checks, conflict] };\n const store = codexCredentialStore(source);\n\n const entries: Entry[] = [];\n const credentials: CredentialDiagnostic[] = [];\n\n // The scrubbed catalog is one of the room's three native multi-agent closures, so a\n // catalog it cannot capture is a build failure, not a silent fall back to the\n // built-in catalog and its collaboration metadata.\n const capture = roleCommand({ CODEX_HOME: home }, binary, ['debug', 'models']);\n const models = await probe(binary, ['debug', 'models'], { HOME: layout.home, CODEX_HOME: home, PATH: layout.searchPath });\n if (!models.ok) {\n return { entries: [], checks: [...checks, fail('codex.catalog',\n 'Codex model catalog unavailable, so native multi-agent metadata cannot be removed.',\n `Run ${capture} to see why it failed, upgrade Codex to a version that prints the JSON catalog, then run setup again.`)] };\n }\n let catalogSource: string;\n let evidence: CatalogEvidence;\n try {\n const parsed: unknown = JSON.parse(models.stdout);\n evidence = catalogEvidence(parsed);\n catalogSource = renderCatalog(parsed);\n } catch {\n return { entries: [], checks: [...checks, fail('codex.catalog',\n 'Codex model catalog was not valid JSON, so native multi-agent metadata cannot be removed.',\n `Check the output of ${capture}, upgrade Codex if it does not print a JSON catalog, then run setup again.`)] };\n }\n // A JSON scalar or array parses but is not a catalog: writing it would point every role\n // at a file Codex cannot load, which is the same closure failure as no catalog at all.\n if (!evidence.object) {\n return { entries: [], checks: [...checks, fail('codex.catalog',\n 'Codex printed valid JSON that is not a model catalog object, so native multi-agent metadata cannot be removed.',\n `Check the output of ${capture}, upgrade Codex to a version that prints the JSON catalog object, then run setup again.`)] };\n }\n checks.push(pass('codex.catalog', evidence.markers === 0\n ? `Codex model catalog captured from ${capture}; it declared no multi_agent_version field, and each role home gets that generated copy instead of Codex's built-in catalog.`\n : `Codex model catalog captured from ${capture}; ${String(evidence.markers)} multi_agent_version field(s) are nulled in the generated copy in each role home.`));\n\n const shared = await existingPaths(home, SHARED);\n const roomSkill = { name: ROOM_SKILL_NAME, source: roomSkillSource(layout) };\n for (const role of roles) {\n const target = roleHome(layout, 'codex', role);\n const catalogPath = join(target, CATALOG);\n const roleDocument = renderInstructions(role);\n entries.push({ kind: 'dir', path: target });\n // Codex reads the brief from developer_instructions; this copy is for the operator.\n entries.push({ kind: 'file', path: join(target, 'role-instructions.md'), content: roleDocument });\n entries.push({\n kind: 'file',\n path: join(target, 'config.toml'),\n content: renderRoleConfig(source, { roleDocument, catalogPath }),\n });\n entries.push({ kind: 'file', path: catalogPath, content: catalogSource });\n entries.push(...await roleResourceEntries({\n role, target, home, names: SHARED, shared, executable: EXECUTABLE, roomSkill,\n leadSkillProjection: leadSkillProjection(layout, 'codex'),\n }));\n credentials.push(await credentialDiagnostic(layout, role, store, binary));\n }\n return { entries, credentials, checks, binary };\n },\n};\n","import { spawn } from 'node:child_process';\nimport { mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { isAbsolute, join, resolve } from 'node:path';\nimport {\n ambientNamesCheck, inspectCredentialPath, presentNames, preservedCredentialCheck,\n type CredentialDiagnostic,\n} from '../credentials.js';\nimport { piLoginCommand } from '../auth.js';\nimport type { Entry } from '../fsops.js';\nimport { existingPaths } from '../fsops.js';\nimport type { Layout } from '../layout.js';\nimport { contains, roleHome } from '../layout.js';\nimport { fail, pass, type Check } from '../result.js';\nimport type { Role } from '../roles.js';\nimport { renderInstructions } from '../room/instructions.js';\nimport { loadPromptAsset } from '../room/prompts.js';\nimport { which } from '../which.js';\nimport { jsonServerTable, paseoMcpCheck } from './mcp.js';\nimport { roleResourceEntries } from './resources.js';\nimport { leadSkillProjection, ROOM_SKILL_NAME, roomSkillSource } from '../room/skills.js';\nimport type { Agent, AgentPlan } from './types.js';\n\nconst PACKAGE_NAME = 'pi-mcp-adapter';\nconst PROBE_ID = 'paseo-room-pi-mcp-probe';\nconst PROBE_TIMEOUT_MS = 10_000;\nconst PROBE_OUTPUT_LIMIT = 1024 * 1024;\nconst SHARED = ['models.json', 'AGENTS.md', 'skills', 'prompts', 'themes', 'keybindings.json', 'mcp.json'] as const;\n/** Pi prompts are its slash commands, so they execute; Peer receives no such resource. */\nconst EXECUTABLE = ['prompts'] as const;\nconst MCP_FILE = 'mcp.json';\n/** Pi accepts either key for its declaration map, so both are read and neither is rewritten. */\nconst MCP_KEYS = ['mcpServers', 'servers'] as const;\n/** Built-in provider key names only; ambient cloud credential files are deliberately not probed. */\nconst AUTH_ENV = [\n 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY',\n 'OPENAI_API_KEY', 'AZURE_OPENAI_API_KEY', 'GEMINI_API_KEY', 'GOOGLE_CLOUD_API_KEY',\n 'MISTRAL_API_KEY', 'GROQ_API_KEY', 'CEREBRAS_API_KEY', 'XAI_API_KEY',\n 'DEEPSEEK_API_KEY', 'OPENROUTER_API_KEY', 'AI_GATEWAY_API_KEY', 'FIREWORKS_API_KEY',\n 'ZAI_API_KEY', 'MINIMAX_API_KEY', 'OPENCODE_API_KEY', 'KIMI_API_KEY',\n 'COPILOT_GITHUB_TOKEN',\n] as const;\n\nfunction asObject(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? { ...value } : undefined;\n}\n\n/** Copy operator preferences but remove every declaration that can install or load packages. */\nexport function renderPiSettings(source: string | undefined): string {\n const parsed: unknown = source === undefined ? {} : JSON.parse(source);\n const settings = asObject(parsed);\n if (!settings) throw new Error('Pi settings must be a JSON object.');\n delete settings.packages;\n delete settings.extensions;\n return JSON.stringify(settings, null, 2) + '\\n';\n}\n\n/** Preserve the operator append first; room-specific guidance is additive and stronger. */\nexport function renderPiAppend(source: string | undefined, role: Role): string {\n return [\n source?.trim(),\n loadPromptAsset('pi', 'communicationStyle'),\n loadPromptAsset('pi', 'runtime'),\n renderInstructions(role),\n ].filter((part): part is string => Boolean(part)).join('\\n\\n');\n}\n\ninterface ResolvedAdapter {\n readonly entry: string;\n readonly version: string;\n}\n\nfunction adapterFailure(home: string, detail: string): Check {\n return fail('pi.adapter', detail,\n `Install ${PACKAGE_NAME} in ${join(home, 'npm')} with Pi yourself, then run setup again.`);\n}\n\n/** Resolve only Pi's intended global package and its single declared extension entry. */\nexport async function resolvePiAdapter(home: string): Promise<{ readonly adapter?: ResolvedAdapter; readonly check: Check }> {\n const packageRoot = join(home, 'npm', 'node_modules', PACKAGE_NAME);\n const manifestPath = join(packageRoot, 'package.json');\n try {\n const [canonicalRoot, manifestStat, raw] = await Promise.all([\n realpath(packageRoot), stat(manifestPath), readFile(manifestPath, 'utf8'),\n ]);\n if (!manifestStat.isFile()) return { check: adapterFailure(home, `${manifestPath} is not a regular file.`) };\n const manifest = asObject(JSON.parse(raw));\n if (!manifest || manifest.name !== PACKAGE_NAME) {\n return { check: adapterFailure(home, `${manifestPath} does not identify ${PACKAGE_NAME}.`) };\n }\n const pi = asObject(manifest.pi);\n const declared = pi?.extensions;\n if (!Array.isArray(declared) || declared.length !== 1 || typeof declared[0] !== 'string' || !declared[0].trim()) {\n return { check: adapterFailure(home, `${manifestPath} must declare one Pi extension entry.`) };\n }\n const declaration = declared[0];\n if (isAbsolute(declaration)) {\n return { check: adapterFailure(home, `${manifestPath} declares an unsafe absolute extension path.`) };\n }\n const candidate = resolve(packageRoot, declaration);\n const [canonicalEntry, entryStat] = await Promise.all([realpath(candidate), stat(candidate)]);\n if (!contains(canonicalRoot, canonicalEntry) || canonicalEntry === canonicalRoot || !entryStat.isFile()) {\n return { check: adapterFailure(home, `The declared ${PACKAGE_NAME} extension escapes its package or is not a regular file.`) };\n }\n const version = typeof manifest.version === 'string' && manifest.version.trim() ? manifest.version.trim() : 'unknown';\n return {\n adapter: { entry: canonicalEntry, version },\n check: pass('pi.adapter', `${PACKAGE_NAME} ${version} resolved to ${canonicalEntry}.`),\n };\n } catch {\n return { check: adapterFailure(home, `Could not safely resolve ${PACKAGE_NAME} from ${manifestPath}.`) };\n }\n}\n\nexport interface PiProbeOptions {\n readonly timeoutMs?: number;\n readonly outputLimit?: number;\n}\ninterface ProcessResult {\n readonly ok: boolean;\n readonly stdout: string;\n readonly reason?: 'failure' | 'timeout' | 'overflow';\n}\n\nfunction terminateProbe(child: ReturnType<typeof spawn>): void {\n if (child.pid !== undefined) {\n try { process.kill(-child.pid, 'SIGKILL'); } catch { /* the process group may already be gone */ }\n }\n try { child.kill('SIGKILL'); } catch { /* the direct child may already be gone */ }\n child.stdin?.destroy();\n child.stdout?.destroy();\n child.stderr?.destroy();\n}\n\n/** One bounded JSONL request in its own process group and isolated working directory. */\nfunction runProbeProcess(\n executable: string,\n adapterEntry: string,\n env: NodeJS.ProcessEnv,\n options: PiProbeOptions,\n cwd: string,\n): Promise<ProcessResult> {\n const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;\n const outputLimit = options.outputLimit ?? PROBE_OUTPUT_LIMIT;\n const args = ['--mode', 'rpc', '--no-session', '--no-extensions', '--extension', adapterEntry, '--no-approve'];\n return new Promise(resolveResult => {\n const child = spawn(executable, args, { cwd, detached: true, env, stdio: ['pipe', 'pipe', 'pipe'] });\n const stdout: Buffer[] = [];\n let bytes = 0;\n let settled = false;\n const finish = (result: ProcessResult): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolveResult(result);\n };\n const abort = (reason: NonNullable<ProcessResult['reason']>): void => {\n if (settled) return;\n terminateProbe(child);\n finish({ ok: false, stdout: Buffer.concat(stdout).toString('utf8'), reason });\n };\n const capture = (chunk: Buffer, keep: boolean): void => {\n if (settled) return;\n bytes += chunk.length;\n if (bytes > outputLimit) {\n abort('overflow');\n return;\n }\n if (keep) stdout.push(chunk);\n };\n const timer = setTimeout(() => { abort('timeout'); }, timeoutMs);\n child.stdout.on('data', (chunk: Buffer) => { capture(chunk, true); });\n child.stderr.on('data', (chunk: Buffer) => { capture(chunk, false); });\n child.stdout.on('error', () => { abort('failure'); });\n child.stderr.on('error', () => { abort('failure'); });\n child.on('error', () => { abort('failure'); });\n child.on('close', code => {\n const output = Buffer.concat(stdout).toString('utf8');\n finish(code === 0 ? { ok: true, stdout: output } : { ok: false, stdout: output, reason: 'failure' });\n });\n child.stdin.on('error', () => { /* a failed child is reported by close/error */ });\n child.stdin.end(`${JSON.stringify({ id: PROBE_ID, type: 'get_commands' })}\\n`);\n });\n}\n\n/** Pi runs migrations against cwd before RPC, so never probe in the caller's project. */\nasync function runProbe(\n executable: string,\n adapterEntry: string,\n env: NodeJS.ProcessEnv,\n options: PiProbeOptions,\n): Promise<ProcessResult> {\n const createdCwd = await mkdtemp(join(tmpdir(), 'paseo-room-pi-probe-'));\n const cwd = await realpath(createdCwd);\n try {\n return await runProbeProcess(executable, adapterEntry, {\n ...env,\n HOME: cwd,\n PI_CODING_AGENT_DIR: '/dev/null',\n PI_MCP_CONFIG_MODE: 'exclusive',\n PI_OFFLINE: '1',\n }, options, cwd);\n } finally {\n await rm(createdCwd, { force: true, recursive: true });\n }\n}\n\nfunction probeFailure(message: string): Check {\n return fail('pi.capability', message,\n 'Use a Pi and pi-mcp-adapter installation that exposes /mcp through the declared adapter entry.');\n}\n\n/** Authenticate the exact adapter path through Pi's correlated get_commands response. */\nexport async function probePiMcp(\n executable: string,\n adapterEntry: string,\n env: NodeJS.ProcessEnv,\n options: PiProbeOptions = {},\n): Promise<Check> {\n let result: ProcessResult;\n try {\n result = await runProbe(executable, adapterEntry, env, options);\n } catch {\n return probeFailure('Pi capability probe could not create or clean its isolated working directory.');\n }\n if (!result.ok) {\n if (result.reason === 'timeout') return probeFailure('Pi capability probe timed out.');\n if (result.reason === 'overflow') return probeFailure('Pi capability probe exceeded its output limit.');\n return probeFailure('Pi capability probe failed.');\n }\n const correlated: Record<string, unknown>[] = [];\n for (const line of result.stdout.split(/\\r?\\n/).filter(Boolean)) {\n let parsed: unknown;\n try { parsed = JSON.parse(line); } catch { return probeFailure('Pi capability probe returned malformed JSONL.'); }\n const event = asObject(parsed);\n if (!event) return probeFailure('Pi capability probe returned malformed JSONL.');\n if (event.type === 'response' && event.id === PROBE_ID) correlated.push(event);\n }\n if (correlated.length !== 1) return probeFailure('Pi capability probe did not return one correlated get_commands response.');\n const response = correlated[0];\n if (response?.command !== 'get_commands' || response.success !== true) {\n return probeFailure('Pi rejected the get_commands capability probe.');\n }\n const data = asObject(response.data);\n const commands = data?.commands;\n if (!Array.isArray(commands)) return probeFailure('Pi get_commands response was malformed.');\n const matches = commands.map(asObject).filter((command): command is Record<string, unknown> => command?.name === 'mcp');\n if (matches.length !== 1) return probeFailure('Pi did not expose exactly one /mcp command.');\n const command = matches[0];\n if (command?.source !== 'extension') return probeFailure('Pi exposed /mcp from the wrong source.');\n const sourceInfo = asObject(command.sourceInfo);\n if (typeof sourceInfo?.path !== 'string') return probeFailure('Pi did not report the /mcp extension path.');\n try {\n const sourcePath = await realpath(sourceInfo.path);\n if (sourcePath !== adapterEntry) return probeFailure('Pi loaded /mcp from a different extension path.');\n } catch {\n return probeFailure('Pi reported an unresolvable /mcp extension path.');\n }\n return pass('pi.capability', `Pi exposed /mcp from ${adapterEntry}.`);\n}\n\nasync function readPiOptional(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw error;\n }\n}\n\nexport async function piCredentialDiagnostic(layout: Layout, role: Role, binary = 'pi'): Promise<CredentialDiagnostic> {\n const home = roleHome(layout, 'pi', role);\n const path = join(home, 'auth.json');\n const launch = piLoginCommand(home, binary);\n const state = await inspectCredentialPath(path);\n const id = `pi.auth.${role}`;\n if (state.kind !== 'missing') {\n return {\n path,\n checks: [preservedCredentialCheck({\n id, agent: 'Pi', role, path, state,\n login: `${launch}; this starts a minimal, non-room-equivalent interactive login session. Run /login, then exit Pi`,\n })],\n };\n }\n const configured = presentNames(layout.envNames, AUTH_ENV);\n if (configured.length > 0) return { path, checks: [ambientNamesCheck(id, 'Pi', role, configured)] };\n return { path, checks: [{\n id: `${id}.login-required`, status: 'warn',\n message: `Pi ${role} auth: login-required; no role-owned auth.json or known provider environment name was detected. Ambient provider auth may exist, but it was not inspected or validated.`,\n fix: `Start a minimal, non-room-equivalent interactive login session with: ${launch}. Run /login, then exit Pi.`,\n }] };\n}\n\nexport const piAgent: Agent = {\n id: 'pi',\n label: 'Pi',\n homeEnv: 'PI_CODING_AGENT_DIR',\n providerEnv: { PI_MCP_CONFIG_MODE: 'exclusive' },\n pins: {},\n async build(layout: Layout, roles: readonly Role[]): Promise<AgentPlan> {\n const home = layout.agentHome.pi;\n const binary = await which(layout.bin.pi, layout.searchPath);\n if (!binary) {\n return { entries: [], checks: [fail('pi.bin', 'Pi executable not found.', 'Install Pi yourself, or pass --pi-bin /path/to/pi.')] };\n }\n try {\n if (!(await stat(home)).isDirectory()) throw new Error('not a directory');\n } catch {\n return { entries: [], checks: [fail('pi.home', `No Pi config directory at ${home}.`, 'Run Pi once to initialise it, or pass --pi-home.')] };\n }\n const resolved = await resolvePiAdapter(home);\n if (!resolved.adapter) return { entries: [], checks: [resolved.check] };\n const capability = await probePiMcp(binary, resolved.adapter.entry, {\n HOME: layout.home,\n PATH: layout.searchPath,\n PI_CODING_AGENT_DIR: '/dev/null',\n PI_OFFLINE: '1',\n });\n if (capability.status === 'fail') return { entries: [], checks: [resolved.check, capability] };\n\n const settingsPath = join(home, 'settings.json');\n let settings: string;\n try { settings = renderPiSettings(await readPiOptional(settingsPath)); } catch {\n return {\n entries: [], checks: [resolved.check, capability,\n fail('pi.settings', `Could not read ${settingsPath} as a JSON object.`,\n 'Make your Pi settings readable and fix any JSON syntax, then run setup again.')],\n };\n }\n const operatorAppendPath = join(home, 'APPEND_SYSTEM.md');\n let operatorAppend: string | undefined;\n try {\n operatorAppend = await readPiOptional(operatorAppendPath);\n } catch {\n return {\n entries: [], checks: [resolved.check, capability,\n fail('pi.append', `Could not read ${operatorAppendPath}.`,\n 'Make your Pi APPEND_SYSTEM.md readable, then run setup again.')],\n };\n }\n const shared = await existingPaths(home, SHARED);\n // The adapter reads this file as its only config source, so a Paseo-looking server here\n // would be a second control plane. Fail before apply; never edit the operator's file.\n const mcpPath = join(home, MCP_FILE);\n let servers: Record<string, unknown>;\n try {\n servers = jsonServerTable(await readPiOptional(mcpPath), MCP_KEYS);\n } catch {\n return {\n entries: [], checks: [resolved.check, capability,\n fail('pi.mcp', `Could not read ${mcpPath} as a JSON object, so its MCP declarations could not be inspected.`,\n 'Make your Pi mcp.json readable and fix its JSON structure, then run setup again.')],\n };\n }\n const conflict = paseoMcpCheck('pi.mcp', mcpPath, servers);\n if (conflict) return { entries: [], checks: [resolved.check, capability, conflict] };\n const entries: Entry[] = [];\n const credentials: CredentialDiagnostic[] = [];\n const argv: Partial<Record<Role, readonly string[]>> = {};\n const roomSkill = { name: ROOM_SKILL_NAME, source: roomSkillSource(layout) };\n for (const role of roles) {\n const target = roleHome(layout, 'pi', role);\n const appendPath = join(target, 'APPEND_SYSTEM.md');\n entries.push({ kind: 'dir', path: target });\n entries.push({ kind: 'file', path: join(target, 'settings.json'), content: settings });\n entries.push({ kind: 'file', path: appendPath, content: renderPiAppend(operatorAppend, role) });\n entries.push(...await roleResourceEntries({\n role, target, home, names: SHARED, shared, executable: EXECUTABLE, roomSkill,\n leadSkillProjection: leadSkillProjection(layout, 'pi'),\n }));\n credentials.push(await piCredentialDiagnostic(layout, role, binary));\n argv[role] = ['--no-extensions', '--extension', resolved.adapter.entry, '--no-approve', '--append-system-prompt', appendPath];\n }\n return {\n entries,\n credentials,\n checks: [pass('pi.home', `Pi found at ${binary} using ${home}.`), resolved.check, capability],\n binary,\n argv,\n };\n },\n};\n","import type { PaseoClient, PaseoClientConfig } from '@getpaseo/client';\nimport { gte, valid } from 'semver';\nimport { z } from 'zod';\nimport type { Layout } from './layout.js';\nimport { fail, pass, type Check } from './result.js';\nimport type { Profile, Provider } from './agents/types.js';\nimport type { AgentId } from './roles.js';\nimport { probe, which } from './which.js';\n\nexport const MINIMUM_VERSION = '0.8.0-beta.1';\nexport const PI_MINIMUM_VERSION = '0.8.0';\n\n/** Claude and Pi need `0.8.0`; so does the runtime plugin, whose range the caller also checks. */\nexport function minimumPaseoVersion(agents: readonly AgentId[], runtime = false): string {\n return runtime || agents.includes('pi') || agents.includes('claude') ? PI_MINIMUM_VERSION : MINIMUM_VERSION;\n}\n\n/**\n * Read `daemon status --json` for only the four facts compatibility turns on, and read them\n * loosely: this is a CLI's human-facing output, not a versioned protocol type, and it has already\n * changed shape once. `0.8.x` reported `cliVersion`; `0.9.x` dropped it and gained a supervisor\n * `pid` separate from `workerPid`, so the caller supplies the CLI version instead. `localDaemon`\n * is a plain string because its state names are Paseo's to extend — `0.9.x` added `not_ready` —\n * and every name but `running` means the same thing to this tool.\n */\nconst statusSchema = z.object({\n listen: z.string().min(1),\n localDaemon: z.string().min(1),\n cliVersion: z.string().optional(),\n daemonVersion: z.string().nullish(),\n});\n\nexport interface Daemon {\n readonly url: string;\n readonly version: string;\n}\nexport interface DaemonResult {\n readonly checks: readonly Check[];\n readonly daemon?: Daemon;\n}\n\nexport function normalizeUrl(listen: string): string | undefined {\n const match = /^(?:ws:\\/\\/)?([^:/]+|\\[[^\\]]+\\]):(\\d+)$/.exec(listen.trim());\n if (!match) return undefined;\n const [, host = '', port = ''] = match;\n const local = ['localhost', '127.0.0.1', '0.0.0.0', '[::1]', '[::]'].includes(host) ? '127.0.0.1' : host;\n return `ws://${local}:${port}`;\n}\n\n/**\n * The whole compatibility story: is Paseo running, and is it new enough? `cliVersion` is the\n * executable's own version, used only when the status output no longer carries one; comparing it\n * to the daemon is what catches an upgraded CLI whose daemon was never restarted.\n */\nexport function assessStatus(raw: unknown, minimumVersion = MINIMUM_VERSION, cliVersion?: string): DaemonResult {\n const parsed = statusSchema.safeParse(raw);\n if (!parsed.success) {\n return { checks: [fail('paseo.status', 'Paseo status output was not understood.', 'Upgrade Paseo, then run: paseo daemon status --json')] };\n }\n const status = parsed.data;\n if (status.localDaemon !== 'running') {\n return { checks: [fail('paseo.daemon', `Paseo daemon is ${status.localDaemon}.`, 'Start it with: paseo daemon start')] };\n }\n const cli = valid(status.cliVersion ?? cliVersion);\n const daemon = status.daemonVersion == null ? null : valid(status.daemonVersion);\n if (!cli || !daemon) {\n return { checks: [fail('paseo.version', 'Paseo did not report a usable version.', 'Upgrade Paseo to a release that reports semver versions.')] };\n }\n if (cli !== daemon) {\n return { checks: [fail('paseo.version', `Paseo CLI is ${cli} but the running daemon is ${daemon}.`, 'Restart the daemon with: paseo daemon restart')] };\n }\n if (!gte(daemon, minimumVersion)) {\n return { checks: [fail('paseo.version', `Paseo ${daemon} is older than the required ${minimumVersion}.`, 'Upgrade Paseo, then run setup again.')] };\n }\n const url = normalizeUrl(status.listen);\n if (!url) {\n return { checks: [fail('paseo.listen', `Paseo listen address ${status.listen} was not understood.`, 'Use a host:port listen address in the Paseo config.')] };\n }\n return { checks: [pass('paseo.version', `Paseo ${daemon} is running on ${url} (compatible, needs >= ${minimumVersion}).`)], daemon: { url, version: daemon } };\n}\n\nexport async function checkDaemon(layout: Layout, env: NodeJS.ProcessEnv = process.env, minimumVersion = MINIMUM_VERSION): Promise<DaemonResult> {\n const binary = await which(layout.bin.paseo, layout.searchPath);\n if (!binary) {\n return { checks: [fail('paseo.bin', 'Paseo executable not found.', 'Install Paseo, or pass --paseo-bin /path/to/paseo.')] };\n }\n const output = await probe(binary, ['daemon', 'status', '--json'], {\n HOME: layout.home, PASEO_HOME: layout.paseoHome, PATH: layout.searchPath,\n ...(env.PASEO_PASSWORD === undefined ? {} : { PASEO_PASSWORD: env.PASEO_PASSWORD }),\n });\n if (!output.ok) {\n return { checks: [fail('paseo.status', 'Could not read Paseo daemon status.', 'Run: paseo daemon status --json')] };\n }\n let status: unknown;\n try { status = JSON.parse(output.stdout); }\n catch { return assessStatus(undefined, minimumVersion); }\n // Paseo 0.9 stopped reporting the CLI version in status, so ask the same executable we just\n // ran. Only then: a status that still carries one needs no second process.\n const reported = (status as { cliVersion?: unknown } | null)?.cliVersion;\n if (typeof reported === 'string') return assessStatus(status, minimumVersion);\n const version = await probe(binary, ['--version'], { HOME: layout.home, PATH: layout.searchPath });\n return assessStatus(status, minimumVersion, version.ok ? version.stdout.trim() : undefined);\n}\n\nconst configSchema = z.object({\n config: z.object({\n providers: z.record(z.string(), z.unknown()).optional(),\n // Read loosely: entries carry operator fields the room neither knows nor touches.\n agentProfiles: z.array(z.record(z.string(), z.unknown())).optional(),\n pluginsEnabled: z.boolean().optional(),\n }),\n});\nexport type LiveProfile = Record<string, unknown>;\nexport interface LivePlugin {\n readonly id: string;\n readonly path: string;\n readonly enabled: boolean;\n readonly status: string;\n readonly error?: string | undefined;\n}\n\nexport interface Session {\n readProviders(): Promise<Record<string, unknown>>;\n writeProviders(providers: Readonly<Record<string, Provider>>): Promise<void>;\n removeProviders(ids: readonly string[]): Promise<void>;\n readProfiles(): Promise<readonly LiveProfile[]>;\n /** Paseo has no remove-one call for profiles, so this replaces the whole array. */\n writeProfiles(profiles: readonly LiveProfile[]): Promise<void>;\n pluginsEnabled(): Promise<boolean>;\n listPlugins(): Promise<readonly LivePlugin[]>;\n installPlugin(path: string, id: string): Promise<LivePlugin>;\n reloadPlugin(id: string): Promise<LivePlugin>;\n enablePlugin(id: string): Promise<LivePlugin>;\n removePlugin(id: string): Promise<void>;\n refresh(ids: readonly string[]): Promise<void>;\n}\nexport interface RoomClient extends PaseoClient {\n listPlugins(): Promise<LivePlugin[]>;\n installDirectoryPlugin(path: string, id?: string): Promise<LivePlugin>;\n reloadPlugin(id: string): Promise<LivePlugin>;\n enablePlugin(id: string): Promise<LivePlugin>;\n removePlugin(id: string): Promise<void>;\n}\nexport type ClientFactory = (config: PaseoClientConfig) => RoomClient;\n\n/** One connection per command. No retries, no reconnects, no background state. */\nexport async function withSession<T>(\n daemon: Daemon,\n run: (session: Session) => Promise<T>,\n options: { readonly password?: string; readonly factory?: ClientFactory } = {},\n): Promise<T> {\n const quiet = { debug() { /* silent */ }, info() { /* silent */ }, warn() { /* silent */ }, error() { /* silent */ } };\n // Loaded here so the \"Paseo is not running\" path never pays for the SDK.\n const clientConfig: PaseoClientConfig = {\n url: `${daemon.url}/ws`,\n ...(options.password === undefined ? {} : { password: options.password }),\n appVersion: MINIMUM_VERSION,\n connectTimeoutMs: 10_000,\n reconnect: { enabled: false },\n logger: quiet,\n };\n let client: RoomClient;\n if (options.factory !== undefined) {\n client = options.factory(clientConfig);\n } else {\n const [{ createPaseoApi }, { DaemonClient }] = await Promise.all([\n import('@getpaseo/client'), import('@getpaseo/client/internal/daemon-client'),\n ]);\n // The public config types `capabilities` as possibly undefined while DaemonClient's does not,\n // so forward it only when present rather than spreading an explicit undefined.\n const { capabilities, ...config } = clientConfig;\n const raw = new DaemonClient({\n ...config, ...(capabilities === undefined ? {} : { capabilities }),\n clientId: `paseo-room-${String(process.pid)}`, clientType: 'cli',\n });\n client = {\n ...createPaseoApi(raw),\n connect: () => raw.connect(), close: () => raw.close(),\n ensureConnected: () => { raw.ensureConnected(); }, getConnectionState: () => raw.getConnectionState(),\n listPlugins: () => raw.listPlugins(),\n installDirectoryPlugin: (path, id) => raw.installDirectoryPlugin(path, id),\n reloadPlugin: id => raw.reloadPlugin(id), enablePlugin: id => raw.enablePlugin(id),\n removePlugin: id => raw.removePlugin(id),\n };\n }\n try {\n await client.connect();\n return await run({\n async readProviders() {\n const response = configSchema.parse(await client.config.get());\n return response.config.providers ?? {};\n },\n async writeProviders(providers) {\n await client.config.patch({ providers } as unknown as Parameters<PaseoClient['config']['patch']>[0]);\n },\n async removeProviders(ids) {\n await client.config.patch({ removeProviders: [...ids] });\n },\n async readProfiles() {\n const response = configSchema.parse(await client.config.get());\n return response.config.agentProfiles ?? [];\n },\n async writeProfiles(profiles) {\n await client.config.patch({ agentProfiles: [...profiles] } as unknown as Parameters<PaseoClient['config']['patch']>[0]);\n },\n async pluginsEnabled() {\n const response = configSchema.parse(await client.config.get());\n return response.config.pluginsEnabled === true;\n },\n async listPlugins() {\n return await client.listPlugins();\n },\n async installPlugin(path, id) {\n return await client.installDirectoryPlugin(path, id);\n },\n async reloadPlugin(id) {\n return await client.reloadPlugin(id);\n },\n async enablePlugin(id) {\n return await client.enablePlugin(id);\n },\n async removePlugin(id) {\n await client.removePlugin(id);\n },\n async refresh(ids) {\n await client.providers.refresh({ providers: [...ids] });\n },\n });\n } finally {\n await client.close();\n }\n}\n\n/**\n * The provider environment is written whole by the room, so it is compared whole: an\n * added key can enable exactly what the pins close, and a subset test would call that a\n * match. Unrelated *top-level* provider fields remain the operator's.\n */\nfunction envMatches(live: unknown, desired: Readonly<Record<string, string>>): boolean {\n if (live === null || typeof live !== 'object' || Array.isArray(live)) return false;\n const entries = Object.entries(live as Record<string, unknown>);\n return entries.length === Object.keys(desired).length &&\n entries.every(([key, value]) => Object.hasOwn(desired, key) && value === desired[key]);\n}\n\n/** Compare only the keys the room owns; unrelated fields stay the operator's. */\nexport function providerMatches(desired: Provider, live: unknown): boolean {\n if (live === null || typeof live !== 'object') return false;\n const entry = live as Record<string, unknown>;\n const tools = entry.paseoTools;\n const same = (left: unknown, right: unknown): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);\n return entry.extends === desired.extends &&\n same(entry.command, desired.command) &&\n envMatches(entry.env, desired.env) &&\n tools !== null && typeof tools === 'object' &&\n (tools as { enabled?: unknown }).enabled === desired.paseoTools.enabled &&\n // Pins are the room's guarantee: drifting them silently re-enables what they block.\n same(entry.params, desired.params) &&\n same(entry.disallowedTools, desired.disallowedTools);\n}\n\n/** Compare only the fields the room writes on an update; the rest are the operator's. */\nexport function profileMatches(desired: Profile, live: unknown): boolean {\n if (live === null || typeof live !== 'object') return false;\n const entry = live as Record<string, unknown>;\n return entry.name === desired.name && entry.icon === desired.icon && entry.color === desired.color &&\n entry.provider === desired.provider && entry.modeId === desired.modeId && entry.notes === desired.notes;\n}\n\n/**\n * Paseo stores every profile in one host-wide array, so the room rewrites that array\n * rather than patching an entry. Operator profiles pass through untouched, and so does\n * every field of a room profile that the room does not own.\n */\nexport function mergeProfiles(\n live: readonly LiveProfile[],\n desired: readonly Profile[],\n drop: readonly string[],\n): LiveProfile[] {\n const dropped = new Set(drop);\n const wanted = new Map(desired.map(profile => [profile.id, profile]));\n const seen = new Set<string>();\n const kept = live\n .filter(entry => !dropped.has(String(entry.id)))\n .map(entry => {\n const profile = wanted.get(String(entry.id));\n if (!profile) return entry;\n seen.add(profile.id);\n // Model and thinkingOptionId remain operator choices; the room owns the\n // role's visual identity and its no-prompt launch mode.\n const updated: LiveProfile = {\n ...entry, name: profile.name, icon: profile.icon, color: profile.color,\n provider: profile.provider, notes: profile.notes,\n };\n if (profile.modeId === undefined) delete updated.modeId;\n else updated.modeId = profile.modeId;\n return updated;\n });\n return [...kept, ...desired.filter(profile => !seen.has(profile.id)).map(profile => ({ ...profile }))];\n}\n","import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Entry } from './fsops.js';\nimport type { Layout } from './layout.js';\nimport { providerId, type Role } from './roles.js';\nimport { contractDigest, renderInstructions } from './room/instructions.js';\n\nexport const CLAUDE_CARRIER_PLUGIN_ID = 'paseo-room-claude-carrier';\n/** Kept in step with `RUNTIME_PASEO_RANGE`: both bind the same unchanged plugin host contract. */\nexport const CLAUDE_CARRIER_PASEO_RANGE = '>=0.8.0 <0.10.0';\n\nconst STATIC_ASSETS = [\n 'paseo-plugin.json',\n 'package.json',\n 'tsconfig.json',\n 'index.server.ts',\n 'server/carrier.ts',\n] as const;\n\nfunction loadAsset(path: string): string {\n return readFileSync(new URL(`./plugin-assets/${path}`, import.meta.url), 'utf8');\n}\n\nexport function claudeCarrierPluginDir(layout: Layout): string {\n return join(layout.roomHome, 'plugin');\n}\n\n/** A readable TypeScript string literal that preserves the rendered Markdown byte-for-byte. */\nexport function typescriptTemplateLiteral(value: string): string {\n const escaped = value\n .replaceAll('\\\\', '\\\\\\\\')\n .replaceAll('`', '\\\\`')\n .replaceAll('${', '\\\\${');\n return `\\`${escaped}\\``;\n}\n\nexport function renderClaudeCarrierContract(roles: readonly Role[]): string {\n const entries = roles.map(role => {\n const id = JSON.stringify(providerId('claude', role));\n return ` ${id}: ${typescriptTemplateLiteral(renderInstructions(role))},`;\n });\n return [\n '/** Generated by paseo-room. The Markdown prompt assets remain authoritative. */',\n `export const GENERATION = ${JSON.stringify(contractDigest())};`,\n 'export const CONTRACT: Readonly<Record<string, string>> = {',\n ...entries,\n '};',\n '',\n ].join('\\n');\n}\n\nexport function claudeCarrierEntries(layout: Layout, roles: readonly Role[]): Entry[] {\n const root = claudeCarrierPluginDir(layout);\n return [\n { kind: 'dir', path: root },\n { kind: 'dir', path: join(root, 'server') },\n ...STATIC_ASSETS.map(path => ({ kind: 'file' as const, path: join(root, path), content: loadAsset(path) })),\n { kind: 'file', path: join(root, 'server', 'contract.ts'), content: renderClaudeCarrierContract(roles) },\n ];\n}\n","/**\n * The runtime role-policy projection: which runtime operations each room role may invoke.\n *\n * This is the single source for both the CLI, which writes it into the generated room manifest,\n * and the plugin's authorization. It is deliberately not `ROLE_PASEO_TOOLS`: Paseo's built-in\n * room tools stay off for Peer, and the only runtime surface a Peer can ever hold is the\n * assignment-scoped reporting pair (docs/design/runtime-coordination.md D4, §3.4).\n */\n\nexport const RUNTIME_ROLES = ['supervisor', 'lead', 'peer'] as const;\nexport type RuntimeRole = (typeof RUNTIME_ROLES)[number];\n\nexport const RUNTIME_AGENTS = ['codex', 'claude', 'pi'] as const;\nexport type RuntimeAgent = (typeof RUNTIME_AGENTS)[number];\n\nexport const SUPERVISOR_OPERATIONS = ['room_status', 'runtime_findings', 'message_lead', 'attention_feedback'] as const;\nexport const LEAD_OPERATIONS = [\n 'assignment_create', 'assignment_dispatch', 'assignment_answer', 'assignment_rework',\n 'assignment_accept', 'assignment_reject', 'assignment_abandon', 'assignment_close',\n 'assignment_status', 'gate_run', 'workspace_close', 'lease_reclaim',\n] as const;\n/** A closed tuple. Adding a Peer operation is an authority and protocol revision, not a patch. */\nexport const PEER_REPORTING_TOOLS = ['ask', 'handoff'] as const;\n\nexport type SupervisorOperation = (typeof SUPERVISOR_OPERATIONS)[number];\nexport type LeadOperation = (typeof LEAD_OPERATIONS)[number];\nexport type PeerReportingTool = (typeof PEER_REPORTING_TOOLS)[number];\nexport type RuntimeCapability = SupervisorOperation | LeadOperation | PeerReportingTool;\n\nexport const RUNTIME_CAPABILITIES: readonly RuntimeCapability[] = [\n ...SUPERVISOR_OPERATIONS, ...LEAD_OPERATIONS, ...PEER_REPORTING_TOOLS,\n];\n\nexport interface PeerReportingDeclaration {\n readonly protocol: 1;\n readonly tools: readonly ['ask', 'handoff'];\n readonly qualifiedVia: 'exact-room-provider';\n}\n\nexport interface RuntimeRolePolicy {\n readonly capabilities: readonly RuntimeCapability[];\n readonly peerReporting?: PeerReportingDeclaration;\n}\n\nexport const PEER_REPORTING_DECLARATION: PeerReportingDeclaration = {\n protocol: 1,\n tools: ['ask', 'handoff'],\n qualifiedVia: 'exact-room-provider',\n};\n\n/**\n * Projects one role's runtime capabilities. `peerReportingEligible` comes from the canonical\n * `ROLE_PEER_REPORTING` policy; a Peer that is not eligible holds no runtime operation at all.\n */\nexport function runtimeRolePolicy(role: RuntimeRole, peerReportingEligible: boolean): RuntimeRolePolicy {\n if (role === 'supervisor') return { capabilities: [...SUPERVISOR_OPERATIONS] };\n if (role === 'lead') return { capabilities: [...LEAD_OPERATIONS] };\n return peerReportingEligible\n ? { capabilities: [...PEER_REPORTING_TOOLS], peerReporting: PEER_REPORTING_DECLARATION }\n : { capabilities: [] };\n}\n","/**\n * The generated room manifest (docs/design/runtime-coordination.md §3.2): the only bridge from\n * provisioning evidence to runtime recognition. Setup is its only writer; the plugin refuses\n * anything missing, broader than the policy projection, or keyed by a non-exact provider id.\n */\nimport { z } from 'zod';\nimport {\n PEER_REPORTING_TOOLS, RUNTIME_AGENTS, RUNTIME_CAPABILITIES, RUNTIME_ROLES, runtimeRolePolicy,\n} from './policy.js';\n\nexport const MANIFEST_FILE = 'generated/room-manifest.json';\n\nconst generation = z.string().min(1).max(256);\n\nconst peerReportingSchema = z.strictObject({\n protocol: z.literal(1),\n tools: z.tuple([z.literal(PEER_REPORTING_TOOLS[0]), z.literal(PEER_REPORTING_TOOLS[1])]),\n qualifiedVia: z.literal('exact-room-provider'),\n});\n\nconst providerSchema = z.strictObject({\n agent: z.enum(RUNTIME_AGENTS),\n role: z.enum(RUNTIME_ROLES),\n capabilities: z.array(z.enum(RUNTIME_CAPABILITIES as [string, ...string[]])),\n peerReporting: peerReportingSchema.optional(),\n}).superRefine((entry, context) => {\n // A declaration is valid only when it is exactly the projection for its role: never broader,\n // never a Peer operation outside the closed tuple, never reporting on a non-Peer seat.\n const eligible = entry.role === 'peer' && entry.peerReporting !== undefined;\n const expected = runtimeRolePolicy(entry.role, eligible);\n if (JSON.stringify(entry.capabilities) !== JSON.stringify(expected.capabilities)) {\n context.addIssue({ code: 'custom', message: `capabilities do not match the ${entry.role} runtime policy` });\n }\n if (entry.peerReporting !== undefined && entry.role !== 'peer') {\n context.addIssue({ code: 'custom', message: 'peerReporting is only valid on a Peer entry' });\n }\n});\n\n/** Exact provider ids only: a runtime never matches by prefix, label, title or cwd. */\nconst providerId = z.string().regex(/^[a-z0-9][a-z0-9-]*$/).max(128);\n\nexport const runtimeRoomManifestSchema = z.strictObject({\n schema: z.literal(1),\n roomGeneration: generation,\n contractGeneration: generation,\n reportingPolicyGeneration: generation,\n providers: z.record(providerId, providerSchema),\n});\n\nexport type RuntimeRoomManifestV1 = z.infer<typeof runtimeRoomManifestSchema>;\nexport type RuntimeManifestProvider = RuntimeRoomManifestV1['providers'][string];\n","/**\n * Identity of the opt-in runtime coordination plugin. Shared by the server and client entries,\n * and by the CLI that provisions it, so the id and the supported Paseo range have one source.\n *\n * Separate from `paseo-room-claude-carrier` on purpose: a runtime fault must never remove or\n * rewrite the Claude contract carrier (docs/design/runtime-coordination.md D1).\n */\nexport const RUNTIME_PLUGIN_ID = 'paseo-room-runtime';\n\n/**\n * `0.8.0` and `0.9.1` are the live-qualified points. `0.9.x` carries a byte-identical plugin\n * compiler, unchanged lifecycle hooks and an unchanged provider/profile config schema, so the\n * host contract this plugin depends on is the same one `0.8.0` was qualified against. `0.10.0`\n * is unqualified, so the bound stays exclusive.\n */\nexport const RUNTIME_PASEO_RANGE = '>=0.8.0 <0.10.0';\n\n/**\n * Daemon versions on which worktree dispatch passed live qualification\n * (docs/design/runtime-coordination-phase2.md §9). Any other version — or one the plugin cannot\n * read — refuses `isolation: 'worktree'` with `worktree_unqualified`; it is a runtime check, not a\n * change of the plugin's range. `0.9.1`: delta §9.2, 2026-09-23.\n */\nexport const QUALIFIED_WORKTREE_DAEMONS: readonly string[] = ['0.9.1'];\n","import { createHash } from 'node:crypto';\nimport { readdirSync, readFileSync } from 'node:fs';\nimport { join, relative, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Entry } from './fsops.js';\nimport type { Layout } from './layout.js';\nimport { providerId, ROLE_PEER_REPORTING, type AgentId, type Role } from './roles.js';\nimport { contractDigest } from './room/instructions.js';\nimport { MANIFEST_FILE, runtimeRoomManifestSchema, type RuntimeRoomManifestV1 } from './runtime-plugin/shared/manifest.js';\nimport { RUNTIME_PASEO_RANGE, RUNTIME_PLUGIN_ID } from './runtime-plugin/shared/identity.js';\nimport { runtimeRolePolicy } from './runtime-plugin/shared/policy.js';\n\nexport { RUNTIME_PASEO_RANGE, RUNTIME_PLUGIN_ID };\n\n/** The bundled plugin tree: `src/runtime-plugin` in a checkout, `dist/runtime-plugin` when packed. */\nconst BUNDLE = fileURLToPath(new URL('./runtime-plugin/', import.meta.url));\n\nexport function runtimePluginDir(layout: Layout): string {\n return join(layout.roomHome, 'runtime-plugin');\n}\n\nfunction digest(value: unknown): string {\n return `sha256:${createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 16)}`;\n}\n\n/** Every role's runtime policy, as the canonical reporting policy decides it. */\nfunction reportingPolicy(): Record<Role, ReturnType<typeof runtimeRolePolicy>> {\n return {\n supervisor: runtimeRolePolicy('supervisor', ROLE_PEER_REPORTING.supervisor),\n lead: runtimeRolePolicy('lead', ROLE_PEER_REPORTING.lead),\n peer: runtimeRolePolicy('peer', ROLE_PEER_REPORTING.peer),\n };\n}\n\n/** Changes exactly when the approved reporting policy changes, so a stale plugin can refuse it. */\nexport function reportingPolicyGeneration(): string {\n return digest(reportingPolicy());\n}\n\n/**\n * The generated room manifest: exact provider ids mapped to role capabilities, with\n * `peerReporting` only where `ROLE_PEER_REPORTING` allows it. Deterministic, so rerunning setup\n * shows no phantom change, and validated against the plugin's own strict schema before use.\n */\nexport function renderRuntimeManifest(agents: readonly AgentId[], roles: readonly Role[]): RuntimeRoomManifestV1 {\n const policy = reportingPolicy();\n const providers: RuntimeRoomManifestV1['providers'] = {};\n for (const agent of agents) {\n for (const role of roles) {\n const { capabilities, peerReporting } = policy[role];\n providers[providerId(agent, role)] = {\n agent, role, capabilities: [...capabilities],\n ...(peerReporting === undefined ? {} : { peerReporting: { ...peerReporting, tools: ['ask', 'handoff'] } }),\n };\n }\n }\n const contractGeneration = contractDigest();\n return runtimeRoomManifestSchema.parse({\n schema: 1,\n roomGeneration: digest({ agents: [...agents], roles: [...roles], contractGeneration }),\n contractGeneration,\n reportingPolicyGeneration: reportingPolicyGeneration(),\n providers,\n });\n}\n\nexport function renderRuntimeManifestFile(agents: readonly AgentId[], roles: readonly Role[]): string {\n return `${JSON.stringify(renderRuntimeManifest(agents, roles), null, 2)}\\n`;\n}\n\nexport const LOCATION_MODULE = 'server/generated/location.ts';\n\n/** The per-room locator the plugin reads, since Paseo evaluates it without a file path of its own. */\nexport function renderRuntimeLocation(layout: Layout): string {\n const location = { pluginDirectory: runtimePluginDir(layout), runtimeRoot: join(layout.roomHome, 'runtime', 'v1') };\n return [\n '/** Generated by paseo-room setup for this room. */',\n 'export interface RoomLocation {',\n ' readonly pluginDirectory: string;',\n ' readonly runtimeRoot: string;',\n '}',\n '',\n `export const ROOM_LOCATION: RoomLocation | undefined = ${JSON.stringify(location)};`,\n '',\n ].join('\\n');\n}\n\n/** Relative paths of the bundled plugin tree, directories first so they are planned before files. */\nfunction bundleInventory(): { readonly dirs: string[]; readonly files: string[] } {\n const entries = readdirSync(BUNDLE, { recursive: true, withFileTypes: true });\n const toRelative = (entry: (typeof entries)[number]): string =>\n relative(BUNDLE, join(entry.parentPath, entry.name)).split(sep).join('/');\n return {\n dirs: entries.filter(entry => entry.isDirectory()).map(toRelative).sort(),\n files: entries.filter(entry => entry.isFile()).map(toRelative).sort(),\n };\n}\n\n/**\n * The runtime plugin as ordinary managed entries under `~/.paseo-room/runtime-plugin`. The\n * plugin-owned `~/.paseo-room/runtime` state tree is deliberately absent: setup never plans,\n * compares, replaces or deletes it.\n */\nexport function runtimePluginEntries(layout: Layout, agents: readonly AgentId[], roles: readonly Role[]): Entry[] {\n const root = runtimePluginDir(layout);\n const { dirs, files } = bundleInventory();\n const generatedDir = MANIFEST_FILE.split('/').slice(0, -1).join('/');\n return [\n { kind: 'dir', path: root },\n ...[...new Set([...dirs, generatedDir])].sort().map(path => ({ kind: 'dir' as const, path: join(root, path) })),\n ...files.map(path => ({\n kind: 'file' as const, path: join(root, path),\n content: path === LOCATION_MODULE ? renderRuntimeLocation(layout) : readFileSync(join(BUNDLE, path), 'utf8'),\n })),\n { kind: 'file', path: join(root, MANIFEST_FILE), content: renderRuntimeManifestFile(agents, roles) },\n ];\n}\n","/**\n * Size bounds for every strict runtime input (docs/design/runtime-coordination.md §3.4, D6).\n * Measured in UTF-8 bytes, not UTF-16 code units, so a limit means the same on every side.\n */\nimport { z } from 'zod';\n\nexport const MAX_AGGREGATE_BYTES = 64 * 1024;\nexport const MAX_ARRAY_ITEMS = 64;\nexport const MAX_STRING_BYTES = 8 * 1024;\nexport const MAX_COMMAND_BYTES = 16 * 1024;\nexport const MAX_GATE_TIMEOUT_SECONDS = 3_600;\n\nconst encoder = new TextEncoder();\n\nexport function utf8Bytes(value: string): number {\n return encoder.encode(value).length;\n}\n\n/** A string of 1 byte up to `max` UTF-8 bytes. */\nexport function boundedString(max = MAX_STRING_BYTES): z.ZodString {\n return z.string().refine(value => {\n const bytes = utf8Bytes(value);\n return bytes >= 1 && bytes <= max;\n }, { message: `must be 1 byte to ${String(max)} bytes of UTF-8` });\n}\n\nexport function boundedArray<T extends z.ZodType>(item: T): z.ZodArray<T> {\n return z.array(item).max(MAX_ARRAY_ITEMS);\n}\n\n/** True when the JSON form of `value` fits the aggregate bound; non-serialisable input does not. */\nexport function withinAggregateLimit(value: unknown): boolean {\n try {\n // Typed as string, but undefined and functions serialise to undefined at run time.\n const json = JSON.stringify(value) as string | undefined;\n return json !== undefined && utf8Bytes(json) <= MAX_AGGREGATE_BYTES;\n } catch {\n return false;\n }\n}\n\n/**\n * Concurrent worktree writer leases per project (docs/design/runtime-coordination-phase2.md\n * P2-D1). Fixed: raising it is a design change, not configuration.\n */\nexport const MAX_WORKTREE_LEASES = 3;\n","/**\n * Canonical write-scope grammar and the conservative collision checks behind worktree dispatch\n * (docs/design/runtime-coordination-phase2.md §5).\n *\n * This decides scheduling, not access. Every approximation errs toward \"overlapping\": a false\n * overlap costs Lead one narrower brief, a false \"disjoint\" lets two writers meet on one path.\n * No dependency: glob libraries match a path against a pattern, and this needs the intersection\n * of two patterns (§5.5).\n */\nimport { MAX_STRING_BYTES, utf8Bytes } from '../../shared/limits.js';\n\n/** One normalised scope entry. `segments` always ends in `**`: an entry owns everything below it. */\nexport interface ScopeEntry {\n readonly text: string;\n readonly segments: readonly string[];\n}\n\nexport type ScopeParse =\n | { readonly ok: true; readonly entry: ScopeEntry }\n | { readonly ok: false; readonly item: string; readonly reason: string };\n\nexport type ScopesParse =\n | { readonly ok: true; readonly entries: readonly ScopeEntry[] }\n | { readonly ok: false; readonly item: string; readonly reason: string };\n\nconst GLOBSTAR = '**';\nconst WHOLE_REPOSITORY: ScopeEntry = { text: GLOBSTAR, segments: [GLOBSTAR] };\n\n/** NFC, repeated `/` collapsed, trailing `/` stripped. Refusals are `parseScope`'s job. */\nexport function normalizeScope(raw: string): string {\n return raw.normalize('NFC').replace(/\\/{2,}/g, '/').replace(/\\/+$/, '');\n}\n\nfunction refusal(raw: string, text: string): string | undefined {\n if (utf8Bytes(raw) > MAX_STRING_BYTES) return `longer than ${String(MAX_STRING_BYTES)} bytes`;\n if (text === '') return 'empty';\n if (text.includes('\\\\')) return 'contains a backslash';\n if (text.startsWith('/')) return 'is absolute';\n if (text.startsWith('!')) return 'is a negation';\n if (/[{}]/.test(text)) return 'uses brace expansion';\n if (/[[\\]]/.test(text)) return 'uses a character class';\n if (text.split('/').some(segment => segment === '.' || segment === '..')) return 'has a . or .. segment';\n return undefined;\n}\n\n/** Parse one entry under the §5.1 grammar. A refusal names the entry as written. */\nexport function parseScope(raw: string): ScopeParse {\n const text = normalizeScope(raw);\n const reason = refusal(raw, text);\n if (reason !== undefined) return { ok: false, item: raw, reason };\n // A run of `*` inside a segment means the same as one; a whole-segment run is the globstar.\n const segments = text.split('/').map(segment => (/^\\*+$/.test(segment) && segment.length > 1 ? GLOBSTAR : segment.replace(/\\*{2,}/g, '*')));\n if (segments.at(-1) !== GLOBSTAR) segments.push(GLOBSTAR);\n return { ok: true, entry: { text, segments } };\n}\n\n/** Parse a scope list; an empty list is the whole repository. */\nexport function parseScopes(raws: readonly string[]): ScopesParse {\n if (raws.length === 0) return { ok: true, entries: [WHOLE_REPOSITORY] };\n const entries: ScopeEntry[] = [];\n for (const raw of raws) {\n const parsed = parseScope(raw);\n if (!parsed.ok) return parsed;\n entries.push(parsed.entry);\n }\n return { ok: true, entries };\n}\n\n/** Code points, not UTF-16 units: a `?` stands for one character, as it does for Git. */\nconst codePoints = (value: string): string[] => Array.from(value);\n\n/**\n * Lower-case one code point at a time, keeping any code point whose lower case is longer, so a\n * `?` still counts the same characters on both sides of a comparison.\n */\nfunction fold(value: string): string[] {\n return codePoints(value).map(point => {\n const lower = point.toLowerCase();\n return codePoints(lower).length === 1 ? lower : point;\n });\n}\n\nconst isPattern = (segment: string): boolean => segment.includes('*') || segment.includes('?');\n\n/** Whether a `*`/`?` segment pattern matches a literal segment, both already split into code points. */\nfunction segmentMatches(pattern: readonly string[], literal: readonly string[]): boolean {\n let row = new Array<boolean>(literal.length + 1).fill(false);\n row[literal.length] = true;\n for (let i = pattern.length - 1; i >= 0; i--) {\n const next = new Array<boolean>(literal.length + 1).fill(false);\n for (let j = literal.length; j >= 0; j--) {\n const token = pattern[i];\n if (token === '*') next[j] = (row[j] ?? false) || (j < literal.length && (next[j + 1] ?? false));\n else next[j] = j < literal.length && (token === '?' || token === literal[j]) && (row[j + 1] ?? false);\n }\n row = next;\n }\n return row[0] ?? false;\n}\n\n/** The fixed code points before the first and after the last wildcard. */\nfunction fixedEnds(pattern: readonly string[]): { prefix: string[]; suffix: string[] } {\n const wildcards = pattern.flatMap((point, index) => (point === '*' || point === '?' ? [index] : []));\n return { prefix: pattern.slice(0, wildcards[0]), suffix: pattern.slice((wildcards.at(-1) ?? pattern.length) + 1) };\n}\n\nconst agree = (a: readonly string[], b: readonly string[]): boolean => a.every((point, index) => index >= b.length || point === b[index]);\n\n/** Whether two non-globstar segments could both match one path segment, case-folded. */\nfunction segmentsIntersect(a: string, b: string): boolean {\n const left = fold(a);\n const right = fold(b);\n const leftPattern = isPattern(a);\n const rightPattern = isPattern(b);\n if (!leftPattern && !rightPattern) return left.join('') === right.join('');\n if (!rightPattern) return segmentMatches(left, right);\n if (!leftPattern) return segmentMatches(right, left);\n // Two patterns: disjoint only when a fixed prefix or a fixed suffix provably differs.\n const l = fixedEnds(left);\n const r = fixedEnds(right);\n const suffixesAgree = agree([...l.suffix].reverse(), [...r.suffix].reverse());\n return agree(l.prefix, r.prefix) && suffixesAgree;\n}\n\n/** Could some path match both segment lists? `**` consumes zero or more segments of the other side. */\nfunction sequencesIntersect(a: readonly string[], b: readonly string[]): boolean {\n const width = b.length + 1;\n const table = new Uint8Array((a.length + 1) * width);\n const at = (i: number, j: number): boolean => table[i * width + j] === 1;\n for (let i = a.length; i >= 0; i--) {\n for (let j = b.length; j >= 0; j--) {\n let value: boolean;\n if (i === a.length && j === b.length) value = true;\n else if (i === a.length) value = b[j] === GLOBSTAR && at(i, j + 1);\n else if (j === b.length) value = a[i] === GLOBSTAR && at(i + 1, j);\n else if (a[i] === GLOBSTAR || b[j] === GLOBSTAR) value = at(i + 1, j) || at(i, j + 1);\n else value = segmentsIntersect(a[i] ?? '', b[j] ?? '') && at(i + 1, j + 1);\n table[i * width + j] = value ? 1 : 0;\n }\n }\n return at(0, 0);\n}\n\n/**\n * True when some path could belong to both entries. Case-folded, so a case-insensitive checkout\n * cannot hide an overlap.\n */\nexport function overlaps(a: ScopeEntry, b: ScopeEntry): boolean {\n return sequencesIntersect(a.segments, b.segments);\n}\n\n/** The first overlapping pair across two scope lists, for a refusal that names both entries. */\nexport function firstOverlap(as: readonly ScopeEntry[], bs: readonly ScopeEntry[]): readonly [ScopeEntry, ScopeEntry] | undefined {\n for (const a of as) for (const b of bs) if (overlaps(a, b)) return [a, b];\n return undefined;\n}\n\n/**\n * True when `scope` may write anything under the serial-only path. A serial path owns its whole\n * subtree like any entry, so this is overlap with it.\n */\nexport function reaches(scope: ScopeEntry, serialPath: ScopeEntry): boolean {\n return overlaps(scope, serialPath);\n}\n\n/** Whether a scope's segments match a literal path; the path side is never read as a pattern. */\nfunction pathMatches(scope: readonly string[], path: readonly string[]): boolean {\n let row = new Array<boolean>(path.length + 1).fill(false);\n row[path.length] = true;\n for (let i = scope.length - 1; i >= 0; i--) {\n const segment = scope[i] ?? '';\n const next = new Array<boolean>(path.length + 1).fill(false);\n for (let j = path.length; j >= 0; j--) {\n if (segment === GLOBSTAR) next[j] = (row[j] ?? false) || (j < path.length && (next[j + 1] ?? false));\n else next[j] = j < path.length && segmentMatches(codePoints(segment), codePoints(path[j] ?? '')) && (row[j + 1] ?? false);\n }\n row = next;\n }\n return row[0] ?? false;\n}\n\n/**\n * The changed paths no scope entry covers, in input order. Matched exactly (after NFC), not\n * case-folded: a path that differs only in case is reported, which errs toward evidence.\n */\nexport function conforms(changedPaths: readonly string[], scopes: readonly ScopeEntry[]): string[] {\n return changedPaths.filter(path => {\n const segments = path.normalize('NFC').split('/').filter(segment => segment !== '');\n return !scopes.some(scope => pathMatches(scope.segments, segments));\n });\n}\n","/**\n * Runtime state projection (docs/design/runtime-coordination.md §4.3, §4.4, §5.1, §5.3).\n *\n * Replay folds immutable events into this projection. `checkEvent` decides whether an event is\n * a legal next step without mutating anything; the controller calls it before appending, and\n * replay calls it before applying, so an illegal transition in a ledger pauses the project\n * instead of being silently absorbed. Writer ownership is its own projection: no technical\n * decision about an assignment releases it — only proven archive does.\n *\n * Phase 2 (docs/design/runtime-coordination-phase2.md §4, §5.3) extends a writable reservation\n * with a writer lease on its own worktree. Leases may coexist only with each other, within the\n * fixed cap and with provably disjoint scopes; a writer in Lead's workspace still excludes every\n * other writer. Replay re-checks those rules, so a ledger can never hold two colliding writers.\n */\nimport { MAX_WORKTREE_LEASES } from '../../shared/limits.js';\nimport type { AssignmentCreateInputV1, CandidateRefV1 } from '../contracts/assignment.js';\nimport type { PeerReportReceiptV1 } from '../contracts/peer.js';\nimport type { GateResultV1, RuntimeEventOf, RuntimeEventV1 } from '../events/schema.js';\nimport { firstOverlap, parseScopes, reaches, type ScopeEntry } from './scope.js';\n\nexport type AssignmentState =\n | 'draft' | 'dispatching' | 'active' | 'questioned' | 'blocked' | 'handed-back' | 'rework'\n | 'awaiting-permission' | 'accepted' | 'rejected' | 'abandoned' | 'uncertain';\nexport type ReportingState = 'closed' | 'open' | 'consumed' | 'uncertain';\nexport type Closure = 'open' | 'closing' | 'closed' | 'uncertain';\nexport type OwnershipState = 'reserved' | 'held' | 'releasing' | 'released' | 'uncertain';\n\nexport const TERMINAL_STATES: readonly AssignmentState[] = ['accepted', 'rejected', 'abandoned'];\n\nexport interface AcceptedReport {\n readonly generation: number;\n readonly tool: 'ask' | 'handoff';\n readonly requestId: string;\n readonly fingerprint: string;\n readonly receipt: PeerReportReceiptV1;\n readonly report: Readonly<Record<string, unknown>>;\n readonly eventId: string;\n}\n\nexport interface GateRun {\n readonly gateRunId: string;\n readonly candidate: CandidateRefV1;\n readonly command: string;\n readonly status: 'running' | 'finished' | 'uncertain';\n readonly result?: GateResultV1;\n}\n\n/**\n * A writer lease on a runtime-created worktree. Its state is the ownership state it extends:\n * reserved → held → releasing → released, or uncertain.\n */\nexport interface WriterLease {\n readonly workspaceId: string;\n /** The requested branch until the worktree exists, then the branch Paseo resolved. */\n readonly branch: string;\n readonly baseCommit: string;\n readonly scopes: readonly string[];\n readonly serialOnly: readonly string[];\n readonly epoch: number;\n readonly worktreePath?: string;\n /** Peers this lease was reclaimed from; none of them may report again. */\n readonly priorAgentIds: readonly string[];\n}\n\nexport interface WriterOwnership {\n readonly assignmentId: string;\n readonly workspaceId: string;\n readonly baseCommit: string;\n readonly agentId?: string;\n readonly state: OwnershipState;\n readonly lease?: WriterLease;\n}\n\nexport type WorkspaceCreateState = 'requested' | 'succeeded' | 'failed' | 'uncertain' | 'refused';\nexport type WorkspaceCloseState = 'open' | 'requested' | 'succeeded' | 'failed' | 'uncertain';\n\n/** A runtime-requested Paseo worktree workspace, one per worktree assignment. */\nexport interface WorkspaceRecord {\n readonly assignmentId: string;\n readonly workspaceId: string;\n readonly idempotencyKey: string;\n readonly baseCommit: string;\n readonly branchName: string;\n readonly worktreeSlug: string;\n readonly create: WorkspaceCreateState;\n readonly createIntentId: string;\n readonly worktreePath?: string;\n readonly branch?: string;\n readonly headCommit?: string;\n readonly close: WorkspaceCloseState;\n readonly closeIntentId?: string;\n readonly discardUncommitted?: boolean;\n readonly archivedAt?: string;\n /** False is cleanup evidence: Paseo archived the record but the directory is still there. */\n readonly directoryRemoved?: boolean;\n readonly eventIds: readonly string[];\n}\n\nexport interface AssignmentView {\n readonly id: string;\n readonly input: AssignmentCreateInputV1;\n readonly leadAgentId: string;\n readonly leadProviderId: string;\n readonly state: AssignmentState;\n readonly closure: Closure;\n readonly reportingGeneration: number;\n readonly reportingState: ReportingState;\n /** The generation whose single `run()` has been requested; one run per generation. */\n readonly runGeneration: number;\n readonly peerProviderId?: string;\n readonly workspaceId?: string;\n readonly peerAgentId?: string;\n readonly observedProviderId?: string;\n readonly observedModel?: string;\n readonly candidate?: CandidateRefV1;\n readonly inspectedCommit?: string;\n readonly reports: readonly AcceptedReport[];\n readonly gates: readonly GateRun[];\n readonly awaitingPermissionId?: string;\n /** Intents without a terminal result, keyed by intent id. Recovery works from these. */\n readonly openIntents: Readonly<Record<string, RuntimeEventV1['type']>>;\n readonly decision?: { readonly type: 'accepted' | 'rejected' | 'abandoned'; readonly eventId: string };\n /** Changed paths of the current candidate outside its lease's scopes: evidence, not containment. */\n readonly scopeExceeded?: { readonly candidateCommit: string; readonly paths: readonly string[]; readonly eventId: string };\n readonly eventIds: readonly string[];\n}\n\nexport interface NoticeView {\n readonly noticeId: string;\n readonly assignmentId?: string;\n readonly kind: string;\n readonly class: 'record' | 'owner' | 'operator' | 'page';\n readonly state: 'pending' | 'sent' | 'failed' | 'uncertain';\n readonly eventId: string;\n}\n\nexport interface ProjectState {\n readonly projectId: string;\n binding?: { readonly canonicalRoot: string; readonly gitCommonDir: string };\n ownershipConflict?: { readonly leadAgentIds: readonly string[]; readonly eventId: string };\n readonly assignments: Map<string, AssignmentView>;\n readonly ownership: Map<string, WriterOwnership>;\n /** Runtime-requested worktree workspaces, keyed by assignment id. */\n readonly workspaces: Map<string, WorkspaceRecord>;\n readonly notices: Map<string, NoticeView>;\n lastSequence: number;\n}\n\nexport interface Violation {\n readonly eventId: string;\n readonly type: string;\n readonly message: string;\n}\n\nexport function emptyProjectState(projectId: string): ProjectState {\n return { projectId, assignments: new Map(), ownership: new Map(), workspaces: new Map(), notices: new Map(), lastSequence: 0 };\n}\n\n/** Any writer ownership in the project other than released, optionally ignoring one assignment. */\nexport function activeWriter(state: ProjectState, except?: string): WriterOwnership | undefined {\n for (const owner of state.ownership.values()) if (owner.state !== 'released' && owner.assignmentId !== except) return owner;\n return undefined;\n}\n\n/** A writer in Lead's own workspace that is not released: it excludes every other writer. */\nexport function leadWorkspaceWriter(state: ProjectState, except?: string): WriterOwnership | undefined {\n for (const owner of state.ownership.values()) {\n if (owner.state !== 'released' && owner.lease === undefined && owner.assignmentId !== except) return owner;\n }\n return undefined;\n}\n\n/** Worktree leases that are not released. */\nexport function activeLeases(state: ProjectState, except?: string): (WriterOwnership & { readonly lease: WriterLease })[] {\n return [...state.ownership.values()].filter((owner): owner is WriterOwnership & { readonly lease: WriterLease } =>\n owner.lease !== undefined && owner.state !== 'released' && owner.assignmentId !== except);\n}\n\nexport type LeaseCollision =\n | { readonly code: 'writer_exclusive'; readonly message: string }\n | { readonly code: 'writer_uncertain'; readonly message: string }\n | { readonly code: 'lease_cap'; readonly message: string }\n | { readonly code: 'scope_not_canonical'; readonly message: string }\n | { readonly code: 'scope_overlap'; readonly message: string }\n | { readonly code: 'serial_path'; readonly message: string };\n\nfunction parsed(raws: readonly string[], empty: 'whole' | 'none'): readonly ScopeEntry[] | string {\n if (raws.length === 0 && empty === 'none') return [];\n const result = parseScopes(raws);\n return result.ok ? result.entries : `${result.item} ${result.reason}`;\n}\n\n/**\n * The §5.3 collision rules for a new worktree lease, decided on one projection. The controller\n * runs them before recording anything; replay runs them again on `lease.reserved`.\n */\nexport function leaseCollision(state: ProjectState, assignmentId: string, request: { readonly scopes: readonly string[]; readonly serialOnly: readonly string[] }): LeaseCollision | undefined {\n const exclusive = leadWorkspaceWriter(state, assignmentId);\n if (exclusive !== undefined) return { code: 'writer_exclusive', message: `Assignment ${exclusive.assignmentId} writes in Lead's workspace (${exclusive.state}); it excludes every other writer.` };\n const leases = activeLeases(state, assignmentId);\n const uncertain = leases.find(lease => lease.state === 'uncertain');\n if (uncertain !== undefined) return { code: 'writer_uncertain', message: `The writer of ${uncertain.assignmentId} is uncertain; no new writer starts until it is proven stopped.` };\n if (leases.length >= MAX_WORKTREE_LEASES) return { code: 'lease_cap', message: `${String(MAX_WORKTREE_LEASES)} worktree leases are already held in this project.` };\n const mine = parsed(request.scopes, 'whole');\n if (typeof mine === 'string') return { code: 'scope_not_canonical', message: `writeScope item ${mine}.` };\n const serial = parsed(request.serialOnly, 'none');\n if (typeof serial === 'string') return { code: 'scope_not_canonical', message: `serialOnly item ${serial}.` };\n const others = leases.map(lease => ({ lease, scopes: parsed(lease.lease.scopes, 'whole'), serial: parsed(lease.lease.serialOnly, 'none') }));\n for (const other of others) {\n // A recorded lease that no longer parses cannot be proven disjoint.\n if (typeof other.scopes === 'string' || typeof other.serial === 'string') {\n return { code: 'scope_overlap', message: `The scopes of ${other.lease.assignmentId} cannot be compared.` };\n }\n const overlap = firstOverlap(mine, other.scopes);\n if (overlap !== undefined) return { code: 'scope_overlap', message: `${overlap[0].text} overlaps ${overlap[1].text} held by ${other.lease.assignmentId}.` };\n }\n const union = [...serial, ...others.flatMap(other => (typeof other.serial === 'string' ? [] : other.serial))];\n for (const path of union) {\n if (!mine.some(scope => reaches(scope, path))) continue;\n const holder = others.find(other => typeof other.scopes !== 'string' && other.scopes.some(scope => reaches(scope, path)));\n if (holder !== undefined) return { code: 'serial_path', message: `${path.text} is serial-only and ${holder.lease.assignmentId} already writes under it.` };\n }\n return undefined;\n}\n\ntype Check = string | undefined;\n\nfunction need(condition: boolean, message: string): Check {\n return condition ? undefined : message;\n}\n\nfunction assignmentOf(state: ProjectState, event: RuntimeEventV1): AssignmentView | undefined {\n return event.assignmentId === undefined ? undefined : state.assignments.get(event.assignmentId);\n}\n\nfunction inState(assignment: AssignmentView, allowed: readonly AssignmentState[], action: string): Check {\n return need(allowed.includes(assignment.state), `Cannot ${action} while the assignment is ${assignment.state}.`);\n}\n\n/** Why `event` may not follow `state`, or undefined when it is a legal next step. */\nexport function checkEvent(state: ProjectState, event: RuntimeEventV1): Check {\n if (event.projectId !== state.projectId) return 'Event belongs to another project.';\n switch (event.type) {\n case 'project.bound': return need(state.binding === undefined, 'The project is already bound.');\n case 'project.rebound': return need(state.binding !== undefined, 'Only a bound project can be rebound.');\n case 'project.ownership-conflict': return undefined;\n case 'project.ownership-resolved': return need(state.ownershipConflict !== undefined, 'There is no ownership conflict to resolve.');\n case 'notice.pending': return need(!state.notices.has(event.data.noticeId), `Notice ${event.data.noticeId} already exists.`);\n case 'notice.sent': case 'notice.failed': case 'notice.uncertain':\n return need(state.notices.has(event.data.noticeId), `Unknown notice ${event.data.noticeId}.`);\n default: break;\n }\n if (event.type === 'assignment.created') {\n if (event.assignmentId === undefined) return 'An assignment event needs an assignment id.';\n return need(!state.assignments.has(event.assignmentId), `Assignment ${event.assignmentId} already exists.`);\n }\n const assignment = assignmentOf(state, event);\n if (assignment === undefined) return `Event ${event.type} names no known assignment.`;\n const owner = state.ownership.get(assignment.id);\n const writable = assignment.input.mode === 'writable';\n switch (event.type) {\n case 'assignment.dispatch-requested':\n return inState(assignment, ['draft'], 'dispatch')\n ?? need(state.ownershipConflict === undefined, 'Dispatch is paused by a Lead ownership conflict.')\n // The dispatch mode is not known yet: a writer in Lead's workspace excludes both modes,\n // and `agent.create-requested` decides the rest once the mode is recorded.\n ?? need(!writable || leadWorkspaceWriter(state) === undefined, 'Another writer still owns this project.');\n case 'ownership.reserved':\n return need(writable, 'A read-only assignment reserves no writer ownership.')\n ?? inState(assignment, ['dispatching'], 'reserve ownership')\n ?? need(leadWorkspaceWriter(state) === undefined, 'Another writer still owns this project.');\n case 'agent.create-requested': {\n const lease = owner?.lease;\n return inState(assignment, ['dispatching'], 'create the Peer')\n ?? need(!writable || owner?.state === 'reserved', 'A writable Peer is created only after ownership is reserved.')\n ?? need(assignment.peerAgentId === undefined, 'This assignment already has a Peer.')\n // A writer in Lead's workspace excludes every other writer, leased or not.\n ?? need(!writable || lease !== undefined || activeWriter(state, assignment.id) === undefined, 'Another writer still owns this project.')\n ?? need(lease === undefined || (state.workspaces.get(assignment.id)?.create === 'succeeded' && event.data.workspaceId === lease.workspaceId), 'A leased Peer is created only in its proven worktree.');\n }\n case 'agent.create-succeeded': case 'agent.create-failed': case 'agent.create-uncertain':\n return need(assignment.openIntents[event.data.intentId] === 'agent.create-requested'\n || (assignment.state === 'uncertain' && event.type !== 'agent.create-uncertain'), 'No unresolved create intent matches.');\n case 'binding.refused':\n return inState(assignment, ['dispatching'], 'refuse the Peer binding')\n ?? need(assignment.peerAgentId === event.data.agentId, 'The refusal names a different agent than the one created.');\n case 'binding.published':\n return inState(assignment, ['dispatching'], 'bind the Peer')\n ?? need(assignment.peerAgentId === event.data.agentId, 'The binding names a different agent than the one created.');\n case 'ownership.held':\n return need(owner?.state === 'reserved', 'Only reserved ownership becomes held.')\n ?? need(assignment.peerAgentId === event.data.agentId && assignment.observedProviderId !== undefined, 'Ownership is held only by the bound Peer.');\n case 'reporting.generation-opened': {\n const from: Record<typeof event.data.turn, readonly AssignmentState[]> = {\n initial: ['dispatching'], answer: ['questioned'], 'follow-up': ['blocked'], rework: ['rework'],\n };\n return inState(assignment, from[event.data.turn], `open a ${event.data.turn} reporting generation`)\n ?? need(event.data.generation === assignment.reportingGeneration + 1, 'Reporting generations increase by exactly one.')\n ?? need(assignment.reportingState === 'closed' || assignment.reportingState === 'consumed', 'The previous reporting generation is not terminal.')\n ?? need(assignment.observedProviderId !== undefined, 'No proven Peer binding exists.')\n ?? need(!writable || owner?.state === 'held', 'A writable Peer needs held ownership before any turn.');\n }\n case 'run.requested':\n return need(event.data.generation === assignment.reportingGeneration && assignment.reportingState === 'open', 'A run must use the open reporting generation.')\n ?? need(assignment.runGeneration < event.data.generation, 'This reporting generation already has its run.')\n ?? need(!Object.values(assignment.openIntents).includes('run.requested'), 'Another run is still unresolved.');\n case 'run.succeeded': case 'run.failed': case 'run.uncertain':\n return need(assignment.openIntents[event.data.intentId] === 'run.requested'\n || (assignment.state === 'uncertain' && event.type !== 'run.uncertain'), 'No unresolved run intent matches.');\n case 'report.accepted':\n return need(event.data.generation === assignment.reportingGeneration, 'The report names a stale generation.')\n ?? need(assignment.reportingState === 'open' || assignment.reportingState === 'uncertain', 'The reporting generation is not open.')\n ?? inState(assignment, ['active', 'awaiting-permission', 'uncertain'], 'accept a report');\n case 'report.refused': return undefined;\n case 'report.missing':\n return need(event.data.generation === assignment.reportingGeneration, 'Missing report names a stale generation.')\n ?? need(assignment.reportingState === 'open' || assignment.reportingState === 'uncertain', 'The reporting generation is not open.')\n ?? inState(assignment, ['active', 'awaiting-permission', 'uncertain'], 'record a missing report');\n case 'report.uncertain':\n return need(event.data.generation === assignment.reportingGeneration, 'Uncertain report names a stale generation.');\n case 'permission.awaiting':\n return inState(assignment, ['active'], 'await a reporting permission')\n ?? need(event.data.generation === assignment.reportingGeneration && assignment.reportingState === 'open', 'Permission applies only to the open generation.');\n case 'permission.resolved':\n return inState(assignment, ['awaiting-permission'], 'resolve a permission')\n ?? need(assignment.awaitingPermissionId === event.data.permissionRequestId, 'A different permission request is outstanding.');\n case 'assignment.answered': return inState(assignment, ['questioned', 'blocked'], 'answer');\n case 'assignment.rework-requested': return inState(assignment, ['handed-back'], 'request rework');\n case 'assignment.accepted': return inState(assignment, ['handed-back'], 'accept');\n case 'assignment.rejected': return inState(assignment, ['handed-back'], 'reject');\n case 'assignment.abandoned':\n if (assignment.state === 'uncertain') {\n return need(assignment.reportingState !== 'open' && assignment.reportingState !== 'uncertain', 'Abandon an uncertain assignment only after its generation is terminal.')\n ?? need(assignment.closure === 'closing' || assignment.closure === 'uncertain', 'Abandon an uncertain assignment only after archive is requested.');\n }\n return inState(assignment, ['draft', 'questioned', 'blocked', 'handed-back', 'rework'], 'abandon');\n case 'assignment.close-requested':\n return need(TERMINAL_STATES.includes(assignment.state) || assignment.state === 'uncertain', 'Close an assignment only after a technical decision or while it is uncertain.')\n ?? need(assignment.closure === 'open' || assignment.closure === 'uncertain', 'The assignment is already closing or closed.');\n case 'archive.requested':\n return need(assignment.closure === 'closing' || assignment.closure === 'uncertain', 'Archive follows a close request.')\n ?? need(assignment.peerAgentId === event.data.agentId, 'Archive names a different agent.')\n ?? need(!Object.values(assignment.openIntents).includes('archive.requested'), 'Another archive is still unresolved.');\n case 'archive.succeeded': case 'archive.failed': case 'archive.uncertain':\n return need(assignment.openIntents[event.data.intentId] === 'archive.requested'\n || (assignment.closure === 'uncertain' && event.type !== 'archive.uncertain'), 'No unresolved archive intent matches.');\n case 'ownership.releasing':\n return need(owner?.state === 'held', 'Only held ownership starts releasing.')\n ?? need(assignment.closure === 'closing', 'Release starts only after a close request.');\n case 'ownership.released':\n return need(owner?.state === 'releasing' || owner?.state === 'uncertain', 'Only releasing or uncertain ownership is released.')\n ?? need(assignment.closure === 'closed', 'Ownership is released only after archive is proven.');\n case 'ownership.uncertain':\n return need(owner !== undefined && owner.state !== 'released', 'No unreleased ownership to mark uncertain.');\n case 'lease.reserved': {\n const collision = leaseCollision(state, assignment.id, event.data);\n return need(writable, 'A read-only assignment holds no lease.')\n ?? inState(assignment, ['dispatching'], 'reserve a lease')\n ?? need(owner?.state === 'reserved' && owner.lease === undefined && owner.agentId === undefined, 'A lease extends a fresh reservation.')\n ?? need(owner?.workspaceId === event.data.workspaceId && owner.baseCommit === event.data.baseCommit, 'The lease names a different workspace or base than the reservation.')\n ?? (collision === undefined ? undefined : `${collision.code}: ${collision.message}`);\n }\n case 'workspace.create-requested':\n return inState(assignment, ['dispatching'], 'request a worktree')\n ?? need(owner?.state === 'reserved' && owner.lease?.workspaceId === event.data.workspaceId && owner.lease.baseCommit === event.data.baseCommit, 'A worktree is requested only for its reserved lease.')\n ?? need(!state.workspaces.has(assignment.id), 'This assignment already requested its worktree.');\n case 'workspace.create-succeeded': case 'workspace.create-failed': case 'workspace.create-uncertain': case 'workspace.create-refused': {\n const record = state.workspaces.get(assignment.id);\n const from = event.type === 'workspace.create-uncertain' ? ['requested'] : ['requested', 'uncertain'];\n return need(record !== undefined && record.createIntentId === event.data.intentId && from.includes(record.create), 'No unresolved worktree create matches.')\n ?? need(!('workspaceId' in event.data) || event.data.workspaceId === record?.workspaceId, 'The result names a different workspace.');\n }\n case 'lease.reclaimed': {\n const check = reclaimCheck(state, assignment.id);\n if (!check.ok) return check.message;\n return need(event.data.fromEpoch === check.value.lease.epoch && event.data.toEpoch === event.data.fromEpoch + 1, 'A reclaim moves the lease to exactly the next epoch.')\n ?? need(event.data.priorAgentId === check.value.prior, 'The reclaim names a different writer than the lease holder.');\n }\n case 'scope.exceeded':\n return need(owner?.lease !== undefined, 'Only a leased candidate has scopes to exceed.')\n ?? need(assignment.candidate?.commit === event.data.candidateCommit, 'The evidence names a different candidate.');\n case 'workspace.close-requested': {\n const record = state.workspaces.get(assignment.id);\n return need(record?.workspaceId === event.data.workspaceId && (record.create === 'succeeded' || record.create === 'refused'), 'Only a created worktree is closed.')\n ?? need(record?.close === 'open' || record?.close === 'failed', 'The worktree is already closing or closed.')\n ?? need(owner?.state === 'released', 'A worktree closes only after its writer is proven released.')\n ?? need(!event.data.discardUncommitted || event.data.reason !== undefined, 'Discarding uncommitted work needs a reason.');\n }\n case 'workspace.close-succeeded': case 'workspace.close-failed': case 'workspace.close-uncertain': {\n const record = state.workspaces.get(assignment.id);\n const from = event.type === 'workspace.close-uncertain' ? ['requested'] : ['requested', 'uncertain'];\n return need(record !== undefined && record.closeIntentId === event.data.intentId && from.includes(record.close) && record.workspaceId === event.data.workspaceId, 'No unresolved worktree close matches.');\n }\n case 'gate.requested':\n return inState(assignment, ['handed-back'], 'run a gate')\n ?? need(assignment.candidate !== undefined && assignment.candidate.commit === event.data.candidate.commit, 'A gate runs only against the projected candidate.')\n ?? need(!assignment.gates.some(gate => gate.status === 'running'), 'Another gate is still running.');\n case 'gate.finished':\n // A late sidecar may still settle a gate recorded as uncertain after a restart.\n return need(assignment.gates.some(gate => gate.gateRunId === event.data.result.id && gate.status !== 'finished'), 'No unsettled gate matches.');\n case 'gate.uncertain':\n return need(assignment.gates.some(gate => gate.gateRunId === event.data.gateRunId && gate.status === 'running'), 'No running gate matches.');\n default: {\n const exhaustive: never = event;\n return `Unhandled event ${(exhaustive as RuntimeEventV1).type}.`;\n }\n }\n}\n\nfunction update(state: ProjectState, id: string, change: Partial<AssignmentView>, event: RuntimeEventV1): void {\n const current = state.assignments.get(id);\n if (current === undefined) return;\n state.assignments.set(id, { ...current, ...change, eventIds: [...current.eventIds, event.id] });\n}\n\nfunction withIntent(view: AssignmentView, intentId: string, type: RuntimeEventV1['type'] | undefined): Record<string, RuntimeEventV1['type']> {\n const next = { ...view.openIntents };\n if (type === undefined) Reflect.deleteProperty(next, intentId);\n else next[intentId] = type;\n return next;\n}\n\nfunction withoutPermission(view: AssignmentView): AssignmentView {\n const copy: { -readonly [K in keyof AssignmentView]?: AssignmentView[K] } = { ...view };\n delete copy.awaitingPermissionId;\n return copy as AssignmentView;\n}\n\nfunction setOwner(state: ProjectState, id: string, change: Partial<WriterOwnership>): void {\n const current = state.ownership.get(id);\n if (current !== undefined) state.ownership.set(id, { ...current, ...change });\n}\n\nfunction setLease(state: ProjectState, id: string, change: Partial<WriterLease>): void {\n const current = state.ownership.get(id);\n if (current?.lease !== undefined) state.ownership.set(id, { ...current, lease: { ...current.lease, ...change } });\n}\n\nfunction setWorkspace(state: ProjectState, id: string, change: Partial<WorkspaceRecord>, event: RuntimeEventV1): void {\n const current = state.workspaces.get(id);\n if (current !== undefined) state.workspaces.set(id, { ...current, ...change, eventIds: [...current.eventIds, event.id] });\n}\n\n/** A reclaim ends the prior Peer's binding: the assignment dispatches again inside its lease. */\nfunction reclaimed(view: AssignmentView, event: RuntimeEventV1): AssignmentView {\n const copy: { -readonly [K in keyof AssignmentView]?: AssignmentView[K] } = { ...withoutPermission(view) };\n delete copy.peerAgentId;\n delete copy.observedProviderId;\n delete copy.observedModel;\n return { ...(copy as AssignmentView), state: 'dispatching', reportingState: 'consumed', eventIds: [...view.eventIds, event.id] };\n}\n\nfunction applyReport(state: ProjectState, view: AssignmentView, event: RuntimeEventOf<'report.accepted'>): void {\n const report: AcceptedReport = {\n generation: event.data.generation, tool: event.data.tool, requestId: event.data.requestId,\n fingerprint: event.data.fingerprint, receipt: event.data.receipt, report: event.data.report, eventId: event.id,\n };\n update(state, view.id, {\n state: event.data.receipt.assignmentState,\n reportingState: 'consumed',\n reports: [...view.reports, report],\n ...(event.data.candidate === undefined ? {} : { candidate: event.data.candidate }),\n ...(event.data.inspectedCommit === undefined ? {} : { inspectedCommit: event.data.inspectedCommit }),\n }, event);\n // Scope evidence belongs to one candidate; a new candidate replaces it (or not, if in scope).\n const next = state.assignments.get(view.id);\n if (next?.scopeExceeded !== undefined && event.data.candidate !== undefined && event.data.candidate.commit !== next.scopeExceeded.candidateCommit) {\n const copy: { -readonly [K in keyof AssignmentView]?: AssignmentView[K] } = { ...next };\n delete copy.scopeExceeded;\n state.assignments.set(view.id, copy as AssignmentView);\n }\n}\n\n/** Folds one already-checked event into the projection. */\nexport function applyEvent(state: ProjectState, event: RuntimeEventV1): void {\n state.lastSequence = Math.max(state.lastSequence, event.sequence);\n switch (event.type) {\n case 'project.bound': case 'project.rebound':\n state.binding = { canonicalRoot: event.data.canonicalRoot, gitCommonDir: event.data.gitCommonDir };\n return;\n case 'project.ownership-conflict':\n state.ownershipConflict = { leadAgentIds: event.data.leadAgentIds, eventId: event.id };\n return;\n case 'project.ownership-resolved':\n delete state.ownershipConflict;\n return;\n case 'notice.pending':\n state.notices.set(event.data.noticeId, {\n noticeId: event.data.noticeId, kind: event.data.kind, class: event.data.class, state: 'pending', eventId: event.id,\n ...(event.assignmentId === undefined ? {} : { assignmentId: event.assignmentId }),\n });\n return;\n case 'notice.sent': case 'notice.failed': case 'notice.uncertain': {\n const notice = state.notices.get(event.data.noticeId);\n if (notice !== undefined) state.notices.set(notice.noticeId, { ...notice, state: event.type === 'notice.sent' ? 'sent' : event.type === 'notice.failed' ? 'failed' : 'uncertain' });\n return;\n }\n case 'assignment.created':\n if (event.assignmentId === undefined) return;\n state.assignments.set(event.assignmentId, {\n id: event.assignmentId, input: event.data.input, leadAgentId: event.data.leadAgentId, leadProviderId: event.data.leadProviderId,\n state: 'draft', closure: 'open', reportingGeneration: 0, reportingState: 'closed', runGeneration: 0, reports: [], gates: [],\n openIntents: {}, eventIds: [event.id],\n });\n return;\n default: break;\n }\n const view = assignmentOf(state, event);\n if (view === undefined) return;\n const id = view.id;\n switch (event.type) {\n case 'assignment.dispatch-requested':\n update(state, id, { state: 'dispatching', peerProviderId: event.data.peerProviderId, workspaceId: event.data.workspaceId }, event); return;\n case 'ownership.reserved':\n state.ownership.set(id, { assignmentId: id, workspaceId: event.data.workspaceId, baseCommit: event.data.baseCommit, state: 'reserved' });\n update(state, id, {}, event); return;\n case 'agent.create-requested':\n update(state, id, { openIntents: withIntent(view, event.data.intentId, event.type) }, event); return;\n case 'agent.create-succeeded':\n update(state, id, { peerAgentId: event.data.agentId, openIntents: withIntent(view, event.data.intentId, undefined), ...(view.state === 'uncertain' ? { state: 'dispatching' } : {}) }, event); return;\n case 'agent.create-failed': {\n // Proven: no agent exists, so a reservation without an agent cannot still be writing.\n const owner = state.ownership.get(id);\n if (owner?.state === 'reserved' || (owner?.state === 'uncertain' && owner.agentId === undefined)) setOwner(state, id, { state: 'released' });\n update(state, id, { state: 'blocked', openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n }\n case 'agent.create-uncertain':\n setOwner(state, id, { state: 'uncertain' });\n update(state, id, { state: 'uncertain' }, event); return;\n case 'binding.refused':\n setOwner(state, id, { state: 'uncertain', agentId: event.data.agentId });\n update(state, id, { state: 'uncertain' }, event); return;\n case 'binding.published':\n update(state, id, { observedProviderId: event.data.providerId, observedModel: event.data.model, workspaceId: event.data.workspaceId }, event); return;\n case 'ownership.held':\n setOwner(state, id, { state: 'held', agentId: event.data.agentId });\n update(state, id, {}, event); return;\n case 'reporting.generation-opened':\n update(state, id, { reportingGeneration: event.data.generation, reportingState: 'open' }, event); return;\n case 'run.requested':\n // Active is published with the run intent, before the external call, so a first tool call\n // can never race an internal dispatching, questioned, blocked or rework state.\n update(state, id, { state: 'active', runGeneration: event.data.generation, openIntents: withIntent(view, event.data.intentId, event.type) }, event); return;\n case 'run.succeeded':\n update(state, id, { openIntents: withIntent(view, event.data.intentId, undefined), ...(view.state === 'uncertain' ? { state: 'active', reportingState: 'open' } : {}) }, event); return;\n case 'run.failed':\n update(state, id, { state: 'blocked', reportingState: 'consumed', openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n case 'run.uncertain':\n update(state, id, { state: 'uncertain', reportingState: 'uncertain' }, event); return;\n case 'report.accepted': applyReport(state, view, event); return;\n case 'report.refused': update(state, id, {}, event); return;\n case 'report.missing':\n state.assignments.set(id, { ...withoutPermission(view), state: 'blocked', reportingState: 'consumed', eventIds: [...view.eventIds, event.id] });\n return;\n case 'report.uncertain':\n update(state, id, { state: 'uncertain', reportingState: 'uncertain' }, event); return;\n case 'permission.awaiting':\n update(state, id, { state: 'awaiting-permission', awaitingPermissionId: event.data.permissionRequestId }, event); return;\n case 'permission.resolved':\n state.assignments.set(id, { ...withoutPermission(view), state: 'active', eventIds: [...view.eventIds, event.id] });\n return;\n case 'assignment.answered': update(state, id, {}, event); return;\n case 'assignment.rework-requested': update(state, id, { state: 'rework' }, event); return;\n case 'assignment.accepted': case 'assignment.rejected': case 'assignment.abandoned': {\n const type = event.type === 'assignment.accepted' ? 'accepted' : event.type === 'assignment.rejected' ? 'rejected' : 'abandoned';\n update(state, id, { state: type, decision: { type, eventId: event.id } }, event); return;\n }\n case 'assignment.close-requested': update(state, id, { closure: 'closing' }, event); return;\n case 'archive.requested': update(state, id, { openIntents: withIntent(view, event.data.intentId, event.type) }, event); return;\n case 'archive.succeeded': update(state, id, { closure: 'closed', openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n case 'archive.failed': update(state, id, { closure: 'uncertain', openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n case 'archive.uncertain': update(state, id, { closure: 'uncertain' }, event); return;\n case 'ownership.releasing': setOwner(state, id, { state: 'releasing' }); update(state, id, {}, event); return;\n case 'ownership.released': setOwner(state, id, { state: 'released' }); update(state, id, {}, event); return;\n case 'ownership.uncertain': setOwner(state, id, { state: 'uncertain' }); update(state, id, {}, event); return;\n case 'lease.reserved':\n setOwner(state, id, {\n lease: {\n workspaceId: event.data.workspaceId, branch: event.data.branch, baseCommit: event.data.baseCommit, scopes: event.data.scopes,\n serialOnly: event.data.serialOnly, epoch: event.data.epoch, priorAgentIds: [],\n },\n });\n update(state, id, {}, event); return;\n case 'workspace.create-requested':\n state.workspaces.set(id, {\n assignmentId: id, workspaceId: event.data.workspaceId, idempotencyKey: event.data.idempotencyKey, baseCommit: event.data.baseCommit,\n branchName: event.data.branchName, worktreeSlug: event.data.worktreeSlug, create: 'requested', createIntentId: event.data.intentId,\n close: 'open', eventIds: [event.id],\n });\n update(state, id, { openIntents: withIntent(view, event.data.intentId, event.type) }, event); return;\n case 'workspace.create-succeeded':\n setWorkspace(state, id, { create: 'succeeded', worktreePath: event.data.worktreePath, branch: event.data.branch, headCommit: event.data.headCommit }, event);\n setLease(state, id, { worktreePath: event.data.worktreePath, branch: event.data.branch });\n update(state, id, { openIntents: withIntent(view, event.data.intentId, undefined), ...(view.state === 'uncertain' ? { state: 'dispatching' } : {}) }, event); return;\n case 'workspace.create-failed': case 'workspace.create-refused':\n // No Peer was ever placed in the worktree, so the lease cannot still be writing.\n setWorkspace(state, id, { create: event.type === 'workspace.create-failed' ? 'failed' : 'refused' }, event);\n setOwner(state, id, { state: 'released' });\n update(state, id, { state: 'blocked', openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n case 'workspace.create-uncertain':\n setWorkspace(state, id, { create: 'uncertain' }, event);\n setOwner(state, id, { state: 'uncertain' });\n update(state, id, { state: 'uncertain' }, event); return;\n case 'lease.reclaimed': {\n const owner = state.ownership.get(id);\n const lease = owner?.lease;\n if (owner === undefined || lease === undefined) return;\n const next: { -readonly [K in keyof WriterOwnership]?: WriterOwnership[K] } = { ...owner, state: 'reserved', lease: { ...lease, epoch: event.data.toEpoch, priorAgentIds: [...lease.priorAgentIds, event.data.priorAgentId] } };\n delete next.agentId;\n state.ownership.set(id, next as WriterOwnership);\n state.assignments.set(id, reclaimed(view, event));\n return;\n }\n case 'scope.exceeded':\n update(state, id, { scopeExceeded: { candidateCommit: event.data.candidateCommit, paths: event.data.paths, eventId: event.id } }, event); return;\n case 'workspace.close-requested':\n setWorkspace(state, id, { close: 'requested', closeIntentId: event.data.intentId, discardUncommitted: event.data.discardUncommitted }, event);\n update(state, id, { openIntents: withIntent(view, event.data.intentId, event.type) }, event); return;\n case 'workspace.close-succeeded':\n setWorkspace(state, id, { close: 'succeeded', archivedAt: event.data.archivedAt, directoryRemoved: event.data.directoryRemoved }, event);\n update(state, id, { openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n case 'workspace.close-failed':\n setWorkspace(state, id, { close: 'failed' }, event);\n update(state, id, { openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n case 'workspace.close-uncertain':\n setWorkspace(state, id, { close: 'uncertain' }, event);\n update(state, id, {}, event); return;\n case 'gate.requested':\n update(state, id, { gates: [...view.gates, { gateRunId: event.data.gateRunId, candidate: event.data.candidate, command: event.data.command, status: 'running' }] }, event); return;\n case 'gate.finished':\n update(state, id, { gates: view.gates.map(gate => gate.gateRunId === event.data.result.id ? { ...gate, status: 'finished', result: event.data.result } : gate) }, event); return;\n case 'gate.uncertain':\n update(state, id, { gates: view.gates.map(gate => gate.gateRunId === event.data.gateRunId ? { ...gate, status: 'uncertain' } : gate) }, event); return;\n default: return;\n }\n}\n\nexport interface Projection {\n readonly state: ProjectState;\n readonly violations: readonly Violation[];\n}\n\n/** Replays a ledger. The first illegal transition stops folding: state after it is unknown. */\nexport function project(projectId: string, events: readonly RuntimeEventV1[]): Projection {\n const state = emptyProjectState(projectId);\n for (const event of events) {\n const problem = checkEvent(state, event);\n if (problem !== undefined) return { state, violations: [{ eventId: event.id, type: event.type, message: problem }] };\n applyEvent(state, event);\n }\n return { state, violations: [] };\n}\n\nexport interface ReclaimableLease {\n readonly view: AssignmentView;\n readonly lease: WriterLease;\n readonly worktreePath: string;\n readonly prior: string;\n readonly provider: string;\n}\n\nexport type ReclaimCheck =\n | { readonly ok: true; readonly value: ReclaimableLease }\n | { readonly ok: false; readonly code: string; readonly message: string };\n\n/**\n * The one projection rule for a lease reclaim, shared by replay (`lease.reclaimed`), the controller\n * and the panel. What remains after it passes is live proof that the prior Peer stopped.\n */\nexport function reclaimCheck(state: ProjectState, assignmentId: string): ReclaimCheck {\n const refused = (code: string, message: string): ReclaimCheck => ({ ok: false, code, message });\n const view = state.assignments.get(assignmentId);\n const owner = state.ownership.get(assignmentId);\n const lease = owner?.lease;\n const record = state.workspaces.get(assignmentId);\n if (view === undefined || owner === undefined || lease === undefined || record === undefined) return refused('lease_missing', `Assignment ${assignmentId} holds no worktree lease.`);\n if (owner.state === 'released' || owner.state === 'reserved') return refused('lease_state', 'Only a held or uncertain lease is reclaimed.');\n const prior = owner.agentId;\n if (prior === undefined || view.peerAgentId !== prior) return refused('lease_state', 'The reclaim names a different writer than the lease holder.');\n if (TERMINAL_STATES.includes(view.state) || view.state === 'draft' || view.state === 'dispatching') return refused('assignment_state', `Cannot reclaim while the assignment is ${view.state}.`);\n if (view.closure !== 'open') return refused('assignment_state', 'A closing assignment is not reclaimed.');\n if (Object.keys(view.openIntents).length > 0) return refused('effect_unresolved', 'Settle every unresolved effect before a reclaim.');\n if (record.create !== 'succeeded' || record.close !== 'open' || record.worktreePath === undefined) return refused('worktree_unavailable', 'The lease\\'s worktree is not open.');\n if (view.peerProviderId === undefined) return refused('lease_state', 'The assignment names no Peer provider.');\n return { ok: true, value: { view, lease, worktreePath: record.worktreePath, prior, provider: view.peerProviderId } };\n}\n","/**\n * Durable report receipts (docs/design/runtime-coordination.md §3.4).\n *\n * An action fingerprint is the reporting generation, the tool and the canonical validated\n * payload. A retry of an accepted action — same request id, or the same fingerprint under a\n * new id — returns the original receipt and repeats no transition. Everything else aimed at a\n * consumed or foreign generation is refused without consuming anything.\n */\nimport { createHash } from 'node:crypto';\nimport type { PeerReportErrorCodeV1, PeerReportReceiptV1 } from '../contracts/peer.js';\nimport type { AssignmentView } from './state.js';\n\n/** JSON with object keys sorted at every depth, so equal values always hash equally. */\nexport function canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, item]) => item !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(',')}}`;\n }\n return JSON.stringify(value);\n}\n\nexport function sha256(text: string): string {\n return `sha256:${createHash('sha256').update(text).digest('hex')}`;\n}\n\nexport function actionFingerprint(generation: number, tool: 'ask' | 'handoff', payload: unknown): string {\n return sha256(canonicalJson({ generation, tool, payload }));\n}\n\nexport interface CapturedAction {\n /** The generation the bridge captured when it enqueued the call — never re-attributed. */\n readonly generation: number;\n readonly requestId: string;\n readonly fingerprint: string;\n}\n\nexport type ReceiptResolution =\n | { readonly kind: 'replay'; readonly receipt: PeerReportReceiptV1 }\n | { readonly kind: 'refuse'; readonly code: PeerReportErrorCodeV1; readonly message: string }\n | { readonly kind: 'proceed' };\n\n/**\n * Steps 4 and 5 of the §3.4 validation order: the durable-receipt lookup for this binding's\n * captured generation, then the current-generation check. Payload, binding and authorization\n * checks run before this; live and invariant checks run only after `proceed`.\n */\nexport function resolveReceipt(view: AssignmentView, action: CapturedAction): ReceiptResolution {\n const accepted = view.reports.filter(report => report.generation === action.generation);\n const sameRequest = accepted.find(report => report.requestId === action.requestId);\n if (sameRequest !== undefined) {\n return sameRequest.fingerprint === action.fingerprint\n ? { kind: 'replay', receipt: sameRequest.receipt }\n : { kind: 'refuse', code: 'report_conflict', message: 'This request id was already used for a different report.' };\n }\n const sameAction = accepted.find(report => report.fingerprint === action.fingerprint);\n if (sameAction !== undefined) return { kind: 'replay', receipt: sameAction.receipt };\n if (accepted.length > 0) {\n return { kind: 'refuse', code: 'report_stale', message: 'This turn already has an accepted report; a different report is not accepted.' };\n }\n if (action.generation !== view.reportingGeneration) {\n return { kind: 'refuse', code: 'report_stale', message: 'This report belongs to an earlier turn.' };\n }\n if (view.reportingState === 'uncertain') {\n return { kind: 'refuse', code: 'report_uncertain', message: 'An earlier report for this turn is still being confirmed. Retry shortly.' };\n }\n if (view.reportingState !== 'open') {\n return { kind: 'refuse', code: 'report_stale', message: 'No report is expected for this turn.' };\n }\n return { kind: 'proceed' };\n}\n","/**\n * Role-filtered status views (docs/design/runtime-coordination.md D8, D9, §8.1, §8.2).\n *\n * Every claim carries its evidence class. \"Healthy\" means no known enforced or detected failure;\n * it never means a model obeyed its prompt or that the operating system contained anything.\n * Every degraded or pending item names one bounded recovery action. Peer receives no view.\n */\nimport type { RuntimeEventV1 } from '../events/schema.js';\nimport { canonicalJson, sha256 } from './receipts.js';\nimport {\n activeLeases, leadWorkspaceWriter, reclaimCheck, TERMINAL_STATES, type AssignmentView, type ProjectState, type Violation, type WorkspaceRecord,\n} from './state.js';\n\nexport type EvidenceClass = 'enforced' | 'detected' | 'procedural' | 'unverifiable';\nexport type ViewerRole = 'operator' | 'supervisor' | 'lead';\n\nexport interface Claim<T> {\n readonly value: T;\n readonly evidence: EvidenceClass;\n}\n\nexport type FindingKind =\n | 'project-paused' | 'ownership-conflict' | 'uncertain-effect' | 'report-missing' | 'report-uncertain'\n | 'awaiting-permission' | 'notice-failed' | 'worktree-retained' | 'worktree-cleanup' | 'scope-exceeded';\n\nexport interface Finding {\n readonly kind: FindingKind;\n readonly evidence: EvidenceClass;\n readonly message: string;\n readonly recoveryAction: string;\n readonly sourceEventIds: readonly string[];\n readonly assignmentId?: string;\n}\n\nexport interface ReplayHealth {\n readonly status: 'ok' | 'paused';\n readonly problems: readonly { readonly file: string; readonly reason: string; readonly detail: string }[];\n}\n\nexport interface StatusInput {\n readonly projectId: string;\n readonly canonicalRoot: string;\n readonly replay: ReplayHealth;\n readonly violations: readonly Violation[];\n readonly state: ProjectState;\n readonly events: readonly RuntimeEventV1[];\n /** False while Paseo is unreachable: live facts are then labelled stale, never fresh. */\n readonly liveAvailable: boolean;\n /**\n * Whether a directory still exists, for worktrees Paseo archived but left behind. Callers with\n * a filesystem pass it; without it a left-behind directory is assumed still there.\n */\n readonly present?: (path: string) => boolean;\n}\n\nexport interface AssignmentSummary {\n readonly id: string;\n readonly mode: string;\n readonly kind: string;\n readonly outcome: string;\n readonly state: Claim<string>;\n readonly closure: Claim<string>;\n readonly peerProviderId?: string;\n readonly candidate?: Claim<string>;\n}\n\n/** A worktree writer lease (Phase 2). Scopes are scheduling evidence, never containment. */\nexport interface LeaseView {\n readonly assignmentId: string;\n readonly state: Claim<string>;\n readonly epoch: number;\n readonly scopes: readonly string[];\n readonly serialOnly: readonly string[];\n readonly workspaceId: string;\n readonly branch: string;\n readonly worktreePath?: string;\n readonly agentId?: string;\n /** The projection allows a reclaim; the prior Peer must still be proven stopped live. */\n readonly reclaimable: boolean;\n}\n\n/** A runtime-requested worktree, while it may still exist on disk. */\nexport interface WorktreeView {\n readonly assignmentId: string;\n readonly workspaceId: string;\n readonly path?: string;\n readonly branch: string;\n readonly create: Claim<string>;\n readonly close: Claim<string>;\n readonly disposition: WorktreeDisposition;\n}\n\nexport interface ProjectStatusView {\n readonly projectId: string;\n readonly canonicalRoot: string;\n readonly health: Claim<'healthy' | 'attention' | 'paused'>;\n readonly liveFacts: 'fresh' | 'stale';\n readonly writer?: { readonly assignmentId: string; readonly state: Claim<string> };\n readonly leases: readonly LeaseView[];\n readonly worktrees: readonly WorktreeView[];\n /** Said wherever scopes are shown (PRD REQ-011). */\n readonly scopeStatement: string;\n readonly assignments: readonly AssignmentSummary[];\n readonly findings: readonly Finding[];\n}\n\nexport const SCOPE_STATEMENT = 'Write scopes decide which isolated writers may run at the same time. They prevent collisions; they do not contain a Peer, which can still write anywhere its user can.';\n\nexport interface AssignmentDetailView extends AssignmentSummary {\n readonly brief: AssignmentView['input'];\n readonly leadAgentId: string;\n readonly peerAgentId?: string;\n readonly observedModel?: string;\n readonly reportingGeneration: number;\n readonly peerVerification: readonly Claim<{ readonly command: string; readonly outcome: string }>[];\n readonly runtimeGates: readonly Claim<{ readonly gateRunId: string; readonly status: string; readonly exitCode?: number }>[];\n readonly ownership?: Claim<string>;\n readonly lease?: LeaseView;\n readonly worktree?: WorktreeView;\n readonly scopeExceeded?: Claim<{ readonly candidateCommit: string; readonly paths: readonly string[] }>;\n readonly history: readonly string[];\n}\n\nconst RECOVERY = {\n paused: 'Export the project, inspect the named event file, and quarantine it only if it is confirmed corrupt; the runtime never repairs it.',\n conflict: 'Supervisor or Human confirms the one Lead that owns this project; dispatch stays paused until then.',\n uncertain: 'Inspect the agent in Paseo; when its state is known, let recovery settle it or abandon after archive is requested.',\n missing: 'Lead answers with a follow-up turn or abandons the assignment; prose in the transcript is not a report.',\n reportUncertain: 'Wait for recovery to confirm whether the report was recorded; no later turn starts meanwhile.',\n permission: 'An operator approves or denies the reporting tool permission in Paseo; the runtime never answers it.',\n notice: 'Check the Lead seat is reachable; the notice is retried with the same id.',\n retained: 'Inspect the worktree, then Lead calls workspace_close — or a Human closes it here — with discardUncommitted and a reason to discard its work.',\n cleanup: 'Paseo archived the workspace but left its directory; remove it by hand once nothing in it is needed. The branch is kept.',\n exceeded: 'Review the named paths; accepting this candidate needs an override reason and a residual-risk acknowledgement, or ask for rework.',\n} as const;\n\nfunction leaseView(state: ProjectState, assignmentId: string): LeaseView | undefined {\n const owner = state.ownership.get(assignmentId);\n const lease = owner?.lease;\n if (owner === undefined || lease === undefined) return undefined;\n return {\n assignmentId, state: { value: owner.state, evidence: owner.state === 'uncertain' ? 'unverifiable' : 'enforced' },\n epoch: lease.epoch, scopes: lease.scopes, serialOnly: lease.serialOnly, workspaceId: lease.workspaceId, branch: lease.branch,\n ...(lease.worktreePath === undefined ? {} : { worktreePath: lease.worktreePath }),\n ...(owner.agentId === undefined ? {} : { agentId: owner.agentId }),\n reclaimable: reclaimCheck(state, assignmentId).ok,\n };\n}\n\n/**\n * What a runtime worktree record means on disk — the one rule every view, count and blocker uses.\n * `unresolved`: a create or close is unconfirmed. `active`: its writer is not released.\n * `retained`: writer released, worktree open, waiting for an explicit close. `leftover`: archived\n * by Paseo but its directory is still there. `gone`: never created, or closed and removed.\n */\nexport type WorktreeDisposition = 'unresolved' | 'active' | 'retained' | 'leftover' | 'gone';\n\nexport function worktreeDisposition(state: ProjectState, record: WorkspaceRecord, present: (path: string) => boolean = () => true): WorktreeDisposition {\n if (record.create === 'requested' || record.create === 'uncertain' || record.close === 'requested' || record.close === 'uncertain') return 'unresolved';\n if (record.create === 'failed') return 'gone';\n if (record.close === 'succeeded') {\n return record.directoryRemoved === false && (record.worktreePath === undefined || present(record.worktreePath)) ? 'leftover' : 'gone';\n }\n return state.ownership.get(record.assignmentId)?.state === 'released' ? 'retained' : 'active';\n}\n\nfunction worktreeView(record: WorkspaceRecord, disposition: WorktreeDisposition): WorktreeView {\n const claim = (value: string): Claim<string> => ({ value, evidence: value === 'uncertain' ? 'unverifiable' : 'detected' });\n return {\n assignmentId: record.assignmentId, workspaceId: record.workspaceId, branch: record.branch ?? record.branchName,\n ...(record.worktreePath === undefined ? {} : { path: record.worktreePath }),\n create: claim(record.create), close: claim(record.close), disposition,\n };\n}\n\n/** Every record's disposition, worked out once per view (each may check the disk). */\nfunction dispositions(state: ProjectState, present?: (path: string) => boolean): Map<WorkspaceRecord, WorktreeDisposition> {\n return new Map([...state.workspaces.values()].map(record => [record, worktreeDisposition(state, record, present)]));\n}\n\nfunction eventIdsOf(events: readonly RuntimeEventV1[], assignmentId: string, type: RuntimeEventV1['type']): string[] {\n return events.filter(event => event.assignmentId === assignmentId && event.type === type).map(event => event.id);\n}\n\nexport function findings(input: StatusInput): Finding[] {\n const found: Finding[] = [];\n if (input.replay.status === 'paused' || input.violations.length > 0) {\n found.push({\n kind: 'project-paused', evidence: 'detected',\n message: [...input.replay.problems.map(problem => `${problem.file}: ${problem.reason}`), ...input.violations.map(violation => `${violation.eventId}: ${violation.message}`)].join('; '),\n recoveryAction: RECOVERY.paused, sourceEventIds: input.violations.map(violation => violation.eventId),\n });\n }\n const conflict = input.state.ownershipConflict;\n if (conflict !== undefined) {\n found.push({ kind: 'ownership-conflict', evidence: 'detected', message: `Leads ${conflict.leadAgentIds.join(', ')} both claim this project.`, recoveryAction: RECOVERY.conflict, sourceEventIds: [conflict.eventId] });\n }\n const flagged = new Set<string>();\n for (const view of input.state.assignments.values()) {\n const owner = input.state.ownership.get(view.id);\n if (view.state === 'uncertain' || view.closure === 'uncertain' || owner?.state === 'uncertain' || view.gates.some(gate => gate.status === 'uncertain')) {\n flagged.add(view.id);\n found.push({\n kind: view.reportingState === 'uncertain' ? 'report-uncertain' : 'uncertain-effect', evidence: 'unverifiable', assignmentId: view.id,\n message: `Assignment ${view.id} has an effect whose outcome is not known.`,\n recoveryAction: view.reportingState === 'uncertain' ? RECOVERY.reportUncertain : RECOVERY.uncertain,\n sourceEventIds: view.eventIds.slice(-1),\n });\n }\n if (view.state === 'blocked') {\n const missing = eventIdsOf(input.events, view.id, 'report.missing');\n const last = view.eventIds.at(-1);\n if (last !== undefined && missing.includes(last)) {\n found.push({ kind: 'report-missing', evidence: 'detected', assignmentId: view.id, message: `The Peer turn for ${view.id} ended without an accepted report.`, recoveryAction: RECOVERY.missing, sourceEventIds: [last] });\n }\n }\n if (view.state === 'awaiting-permission') {\n found.push({ kind: 'awaiting-permission', evidence: 'detected', assignmentId: view.id, message: `The Peer for ${view.id} is waiting for permission to call its reporting tool.`, recoveryAction: RECOVERY.permission, sourceEventIds: eventIdsOf(input.events, view.id, 'permission.awaiting').slice(-1) });\n }\n }\n for (const [record, disposition] of dispositions(input.state, input.present)) {\n const ids = record.eventIds.slice(-1);\n if (record.create === 'uncertain' || record.close === 'uncertain') {\n if (!flagged.has(record.assignmentId)) {\n found.push({ kind: 'uncertain-effect', evidence: 'unverifiable', assignmentId: record.assignmentId, message: `The worktree ${record.create === 'uncertain' ? 'create' : 'close'} of ${record.assignmentId} is unconfirmed.`, recoveryAction: RECOVERY.uncertain, sourceEventIds: ids });\n }\n } else if (disposition === 'retained') {\n found.push({ kind: 'worktree-retained', evidence: 'detected', assignmentId: record.assignmentId, message: `The worktree of ${record.assignmentId} (${record.worktreePath ?? record.workspaceId}) was ${record.create === 'refused' ? 'refused and not closed' : 'retained after its writer was released'}.`, recoveryAction: RECOVERY.retained, sourceEventIds: ids });\n } else if (disposition === 'leftover') {\n found.push({ kind: 'worktree-cleanup', evidence: 'detected', assignmentId: record.assignmentId, message: `The worktree of ${record.assignmentId} is closed but ${record.worktreePath ?? 'its directory'} remains.`, recoveryAction: RECOVERY.cleanup, sourceEventIds: ids });\n }\n }\n for (const view of input.state.assignments.values()) {\n const exceeded = view.scopeExceeded;\n if (exceeded !== undefined && !TERMINAL_STATES.includes(view.state)) {\n found.push({ kind: 'scope-exceeded', evidence: 'detected', assignmentId: view.id, message: `The candidate of ${view.id} changes ${exceeded.paths.join(', ')} outside its write scope.`, recoveryAction: RECOVERY.exceeded, sourceEventIds: [exceeded.eventId] });\n }\n }\n for (const notice of input.state.notices.values()) {\n if (notice.state === 'failed' || notice.state === 'uncertain') {\n found.push({ kind: 'notice-failed', evidence: notice.state === 'failed' ? 'detected' : 'unverifiable', message: `Notice ${notice.noticeId} (${notice.kind}) was not confirmed delivered.`, recoveryAction: RECOVERY.notice, sourceEventIds: [notice.eventId], ...(notice.assignmentId === undefined ? {} : { assignmentId: notice.assignmentId }) });\n }\n }\n return found;\n}\n\nfunction stateClaim(view: AssignmentView): Claim<string> {\n return { value: view.state, evidence: view.state === 'uncertain' ? 'unverifiable' : 'enforced' };\n}\n\nfunction summary(view: AssignmentView): AssignmentSummary {\n return {\n id: view.id, mode: view.input.mode, kind: view.input.kind, outcome: view.input.outcome,\n state: stateClaim(view),\n closure: { value: view.closure, evidence: view.closure === 'uncertain' ? 'unverifiable' : view.closure === 'closed' ? 'detected' : 'enforced' },\n ...(view.peerProviderId === undefined ? {} : { peerProviderId: view.peerProviderId }),\n ...(view.candidate === undefined ? {} : { candidate: { value: view.candidate.commit, evidence: 'detected' as const } }),\n };\n}\n\n/**\n * Project status is the same for every viewer that may see it — Supervisor, Lead and the\n * operator. `ViewerRole` has no Peer member, so a Peer cannot be handed a view at all.\n */\nexport function projectStatusView(input: StatusInput): ProjectStatusView {\n const found = findings(input);\n const paused = found.some(finding => finding.kind === 'project-paused' || finding.kind === 'ownership-conflict');\n // The one writer in Lead's workspace; isolated writers are listed under `leases`.\n const writer = leadWorkspaceWriter(input.state);\n return {\n projectId: input.projectId,\n canonicalRoot: input.canonicalRoot,\n health: { value: paused ? 'paused' : found.length > 0 ? 'attention' : 'healthy', evidence: 'detected' },\n liveFacts: input.liveAvailable ? 'fresh' : 'stale',\n ...(writer === undefined ? {} : { writer: { assignmentId: writer.assignmentId, state: { value: writer.state, evidence: writer.state === 'uncertain' ? 'unverifiable' : 'enforced' } } }),\n leases: activeLeases(input.state).flatMap(owner => leaseView(input.state, owner.assignmentId) ?? []),\n worktrees: [...dispositions(input.state, input.present)].filter(([, disposition]) => disposition !== 'gone').map(([record, disposition]) => worktreeView(record, disposition)),\n scopeStatement: SCOPE_STATEMENT,\n assignments: [...input.state.assignments.values()].map(summary),\n findings: found,\n };\n}\n\n/** Full assignment detail is for Lead and the operator; Supervisor observes summaries only. */\nexport function assignmentDetailView(state: ProjectState, assignmentId: string, role: ViewerRole, present?: (path: string) => boolean): AssignmentDetailView | undefined {\n if (role === 'supervisor') return undefined;\n const view = state.assignments.get(assignmentId);\n if (view === undefined) return undefined;\n const owner = state.ownership.get(view.id);\n const lease = leaseView(state, view.id);\n const record = state.workspaces.get(view.id);\n const handoff = [...view.reports].reverse().find(report => report.tool === 'handoff');\n const verification = Array.isArray(handoff?.report.verification) ? handoff.report.verification as readonly { command?: unknown; outcome?: unknown }[] : [];\n return {\n ...summary(view),\n brief: view.input,\n leadAgentId: view.leadAgentId,\n ...(view.peerAgentId === undefined ? {} : { peerAgentId: view.peerAgentId }),\n ...(view.observedModel === undefined ? {} : { observedModel: view.observedModel }),\n reportingGeneration: view.reportingGeneration,\n // The Peer's own gate report is a procedural claim: the runtime cannot prove it ran.\n peerVerification: verification.map(entry => ({ value: { command: String(entry.command), outcome: String(entry.outcome) }, evidence: 'procedural' as const })),\n runtimeGates: view.gates.map(gate => ({\n value: { gateRunId: gate.gateRunId, status: gate.status, ...(gate.result?.exitCode === undefined ? {} : { exitCode: gate.result.exitCode }) },\n evidence: gate.status === 'uncertain' ? 'unverifiable' as const : 'enforced' as const,\n })),\n ...(owner === undefined ? {} : { ownership: { value: owner.state, evidence: owner.state === 'uncertain' ? 'unverifiable' as const : 'enforced' as const } }),\n ...(lease === undefined ? {} : { lease }),\n ...(record === undefined ? {} : { worktree: worktreeView(record, worktreeDisposition(state, record, present)) }),\n ...(view.scopeExceeded === undefined ? {} : { scopeExceeded: { value: { candidateCommit: view.scopeExceeded.candidateCommit, paths: view.scopeExceeded.paths }, evidence: 'detected' as const } }),\n history: view.eventIds,\n };\n}\n\n/** A stable content revision: unchanged views keep the same revision. */\nexport function revision(view: unknown): string {\n return sha256(canonicalJson(view)).slice('sha256:'.length, 'sha256:'.length + 24);\n}\n\nexport interface QuiescenceBlocker {\n readonly kind: 'assignment' | 'ownership' | 'lease' | 'worktree' | 'archive' | 'gate' | 'delivery' | 'intent';\n readonly id: string;\n readonly detail: string;\n}\n\n/**\n * True when nothing the runtime started is still active or uncertain, so deselection cannot\n * strand a writer, a managed Peer, a gate or a delivery (docs/design/runtime-coordination.md §10),\n * a worktree lease or an unresolved worktree create or close (Phase 2 delta §8). A retained\n * worktree whose writer is released does not block: it is Paseo's, and stays for a decision.\n */\nexport function quiescence(state: ProjectState): { readonly quiescent: boolean; readonly blockers: readonly QuiescenceBlocker[] } {\n const blockers: QuiescenceBlocker[] = [];\n for (const view of state.assignments.values()) {\n if (view.state !== 'draft' && !TERMINAL_STATES.includes(view.state)) blockers.push({ kind: 'assignment', id: view.id, detail: `is ${view.state}` });\n if (view.peerAgentId !== undefined && view.closure !== 'closed') blockers.push({ kind: 'archive', id: view.id, detail: `managed Peer ${view.peerAgentId} is not archived (${view.closure})` });\n for (const gate of view.gates) {\n // A running gate always blocks. An uncertain one blocks until its Peer is proven archived:\n // after that nothing can act on it, and nothing could ever settle it further.\n if (gate.status === 'running' || (gate.status === 'uncertain' && view.closure !== 'closed')) {\n blockers.push({ kind: 'gate', id: gate.gateRunId, detail: `gate is ${gate.status}` });\n }\n }\n for (const [intent, type] of Object.entries(view.openIntents)) blockers.push({ kind: 'intent', id: intent, detail: `${type} has no result` });\n }\n for (const owner of state.ownership.values()) {\n if (owner.state === 'released') continue;\n blockers.push(owner.lease === undefined\n ? { kind: 'ownership', id: owner.assignmentId, detail: `writer ownership is ${owner.state}` }\n : { kind: 'lease', id: owner.assignmentId, detail: `worktree lease (epoch ${String(owner.lease.epoch)}) is ${owner.state}` });\n }\n for (const record of state.workspaces.values()) {\n if (worktreeDisposition(state, record) === 'unresolved') {\n blockers.push({ kind: 'worktree', id: record.workspaceId, detail: `worktree of ${record.assignmentId} is unresolved (create ${record.create}, close ${record.close})` });\n }\n }\n for (const notice of state.notices.values()) {\n if (notice.state === 'pending' || notice.state === 'uncertain') blockers.push({ kind: 'delivery', id: notice.noticeId, detail: `notice is ${notice.state}` });\n }\n return { quiescent: blockers.length === 0, blockers };\n}\n\n/** Runtime worktrees that may still be on disk: retained ones Paseo still lists, and leftover directories. */\nexport function worktreesOnDisk(state: ProjectState, present?: (path: string) => boolean): { readonly retained: number; readonly leftover: number } {\n const values = [...dispositions(state, present).values()];\n return { retained: values.filter(value => value === 'retained').length, leftover: values.filter(value => value === 'leftover').length };\n}\n","/**\n * Assignment input and evidence shapes (docs/design/runtime-coordination.md §4.3, §4.4).\n * Structural only: semantic rules such as mode/kind compatibility or a writable gate belong to\n * the domain validator, so every refusal there carries an actionable reason.\n */\nimport { z } from 'zod';\nimport { boundedArray, boundedString, MAX_COMMAND_BYTES, MAX_GATE_TIMEOUT_SECONDS } from '../../shared/limits.js';\n\nexport const ASSIGNMENT_MODES = ['writable', 'read-only'] as const;\nexport const ASSIGNMENT_KINDS = ['engineer', 'architect', 'reviewer', 'scout'] as const;\nexport type AssignmentMode = (typeof ASSIGNMENT_MODES)[number];\nexport type AssignmentKind = (typeof ASSIGNMENT_KINDS)[number];\n\n/** A full Git object id: SHA-1 or SHA-256. Abbreviations are refused, never resolved. */\nexport const commitSchema = z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/);\n\nexport const gateSpecSchema = z.strictObject({\n command: boundedString(MAX_COMMAND_BYTES),\n timeoutSeconds: z.number().int().min(1).max(MAX_GATE_TIMEOUT_SECONDS),\n runtimeRerun: z.enum(['none', 'optional', 'required']),\n processContractVersion: z.literal(1),\n});\nexport type GateSpecV1 = z.infer<typeof gateSpecSchema>;\n\nconst items = boundedArray(boundedString());\n\nexport const assignmentCreateSchema = z.strictObject({\n mode: z.enum(ASSIGNMENT_MODES),\n kind: z.enum(ASSIGNMENT_KINDS),\n outcome: boundedString(),\n prerequisites: items,\n writeScope: items,\n exclusions: items,\n invariants: items,\n acceptanceEvidence: items,\n gate: gateSpecSchema.optional(),\n expectedHandoff: items,\n reopenConditions: items,\n baseCommit: commitSchema,\n});\nexport type AssignmentCreateInputV1 = z.infer<typeof assignmentCreateSchema>;\n\nexport const candidateRefSchema = z.strictObject({\n kind: z.literal('git-commit'),\n commit: commitSchema,\n baseCommit: commitSchema,\n changedPaths: z.array(z.string().min(1)),\n workspaceId: z.string().min(1),\n branch: z.string().min(1).optional(),\n});\nexport type CandidateRefV1 = z.infer<typeof candidateRefSchema>;\n","/**\n * Inputs of the Supervisor and Lead action tools (docs/design/runtime-coordination.md §3.4, D4).\n * Operation names come from the shared role-policy projection; this module only types payloads.\n */\nimport { z } from 'zod';\nimport { boundedArray, boundedString } from '../../shared/limits.js';\nimport type { LeadOperation, SupervisorOperation } from '../../shared/policy.js';\nimport { assignmentCreateSchema } from './assignment.js';\n\n/** Runtime-minted assignment ids; never a Paseo agent id or a path. */\nexport const assignmentIdSchema = z.string().regex(/^asg_[A-Za-z0-9_-]{8,64}$/);\nconst reason = boundedString();\nconst assignment = { assignmentId: assignmentIdSchema };\n\nexport const SUPERVISOR_ACTION_SCHEMAS = {\n room_status: z.strictObject({}),\n runtime_findings: z.strictObject({}),\n // `project` names a project in the caller's portfolio: a runtime project id, the project key or\n // the repository's name. Omitted, it is the caller's own working project, or its only project.\n message_lead: z.strictObject({ message: boundedString(), project: z.string().min(1).max(4_096).optional() }),\n attention_feedback: z.strictObject({ id: z.string().regex(/^att_[A-Za-z0-9_-]{8,32}$/), verdict: z.enum(['useful', 'noise', 'unknown']) }),\n} as const satisfies Record<SupervisorOperation, z.ZodType>;\n\nexport const LEAD_ACTION_SCHEMAS = {\n assignment_create: assignmentCreateSchema,\n // An eligible exact Peer provider id from the room manifest; the model is never selectable.\n // `worktree` asks the runtime for an isolated worktree; the default is Phase 1's shared\n // workspace. `serialOnly` names paths that admit one writer at a time, quoted from the\n // repository's own protocol (docs/design/runtime-coordination-phase2.md P2-D1, §5.3).\n assignment_dispatch: z.strictObject({\n ...assignment,\n peerProvider: z.string().min(1).max(128),\n isolation: z.enum(['lead-workspace', 'worktree']).optional(),\n serialOnly: boundedArray(boundedString()).optional(),\n }),\n assignment_answer: z.strictObject({ ...assignment, answer: boundedString() }),\n assignment_rework: z.strictObject({ ...assignment, instructions: boundedString() }),\n assignment_accept: z.strictObject({\n ...assignment,\n reason,\n // Required by the domain when the Peer gate or a required rerun is red; never a waiver of\n // a missing gate.\n override: z.strictObject({ reason, residualRiskAcknowledged: z.literal(true) }).optional(),\n }),\n assignment_reject: z.strictObject({ ...assignment, reason }),\n assignment_abandon: z.strictObject({ ...assignment, reason }),\n assignment_close: z.strictObject(assignment),\n assignment_status: z.strictObject({ assignmentId: assignmentIdSchema.optional() }),\n gate_run: z.strictObject(assignment),\n // Discarding a retained worktree's uncommitted work is Lead's explicit decision, with a reason.\n workspace_close: z.strictObject({ ...assignment, discardUncommitted: z.literal(true).optional(), reason: reason.optional() })\n .refine(input => input.discardUncommitted !== true || input.reason !== undefined, { message: 'discardUncommitted needs a reason', path: ['reason'] }),\n lease_reclaim: z.strictObject({ ...assignment, reason }),\n} as const satisfies Record<LeadOperation, z.ZodType>;\n","/**\n * The Peer reporting tools, `ask` and `handoff` (docs/design/runtime-coordination.md §3.4).\n *\n * No schema here accepts a room, project, assignment, agent, parent, provider, model,\n * recipient, candidate or lifecycle identifier: the server derives every identity from its own\n * binding. The one `handoff` detail variant a Peer may use is chosen by the server from the\n * bound assignment's work kind; a Peer can neither choose nor change it.\n */\nimport { z } from 'zod';\nimport { boundedArray, boundedString, MAX_COMMAND_BYTES, withinAggregateLimit } from '../../shared/limits.js';\nimport type { PeerReportingTool } from '../../shared/policy.js';\nimport type { AssignmentKind } from './assignment.js';\n\nconst text = boundedString();\nconst texts = boundedArray(text);\n\nexport const verificationReportSchema = z.strictObject({\n command: boundedString(MAX_COMMAND_BYTES),\n outcome: z.enum(['passed', 'failed', 'not-run']),\n note: text.optional(),\n});\nexport type VerificationReportV1 = z.infer<typeof verificationReportSchema>;\n\nexport const askInputSchema = z.strictObject({\n question: text,\n blockingContext: text,\n evidence: texts,\n});\nexport type AskInputV1 = z.infer<typeof askInputSchema>;\n\nexport const HANDOFF_DETAILS = {\n engineer: z.strictObject({ kind: z.literal('engineer') }),\n architect: z.strictObject({\n kind: z.literal('architect'),\n alternatives: texts,\n strongestCounterargument: text,\n reversalConditions: texts,\n evidence: texts,\n }),\n reviewer: z.strictObject({\n kind: z.literal('reviewer'),\n findings: boundedArray(z.strictObject({ claim: text, evidence: texts })),\n }),\n scout: z.strictObject({\n kind: z.literal('scout'),\n evidence: texts,\n remainingUnknowns: texts,\n confidence: z.enum(['low', 'medium', 'high']),\n }),\n} as const satisfies Record<AssignmentKind, z.ZodType>;\n\nconst handoffBase = {\n summary: text,\n deliverables: texts,\n verification: boundedArray(verificationReportSchema),\n residualRisks: texts,\n evidence: texts,\n};\n\n/** The strict `handoff` input for exactly one bound work kind. */\nexport function handoffInputSchema<K extends AssignmentKind>(kind: K) {\n return z.discriminatedUnion('completion', [\n z.strictObject({ ...handoffBase, completion: z.literal('blocked'), blocker: text }),\n z.strictObject({ ...handoffBase, completion: z.literal('partial'), blocker: text }),\n z.strictObject({ ...handoffBase, completion: z.literal('complete'), details: HANDOFF_DETAILS[kind] }),\n ]);\n}\nexport type HandoffInputV1 = z.infer<ReturnType<typeof handoffInputSchema>>;\n\nexport const PEER_REPORT_ERROR_CODES = [\n 'report_malformed', 'report_unauthorized', 'report_stale', 'report_conflict',\n 'report_state', 'report_precondition', 'report_uncertain',\n] as const;\nexport type PeerReportErrorCodeV1 = (typeof PEER_REPORT_ERROR_CODES)[number];\n\nexport const peerReportReceiptSchema = z.strictObject({\n schema: z.literal(1),\n receipt: z.string().min(1).max(128),\n tool: z.enum(['ask', 'handoff']),\n status: z.literal('accepted'),\n assignmentState: z.enum(['questioned', 'blocked', 'handed-back']),\n});\nexport type PeerReportReceiptV1 = z.infer<typeof peerReportReceiptSchema>;\n\nexport const peerReportErrorSchema = z.strictObject({\n schema: z.literal(1),\n error: z.strictObject({\n code: z.enum(PEER_REPORT_ERROR_CODES),\n message: boundedString(1024),\n retryable: z.boolean(),\n }),\n});\nexport type PeerReportErrorV1 = z.infer<typeof peerReportErrorSchema>;\n\nexport type PeerToolParse =\n | { readonly ok: true; readonly tool: 'ask'; readonly input: AskInputV1 }\n | { readonly ok: true; readonly tool: 'handoff'; readonly input: HandoffInputV1 }\n | { readonly ok: false; readonly message: string };\n\n/**\n * Parses raw Peer tool input for the bound work kind. The aggregate bound is checked on the raw\n * value first, so an oversize payload is refused before any field is interpreted.\n */\nexport function parsePeerToolInput(tool: PeerReportingTool, kind: AssignmentKind, raw: unknown): PeerToolParse {\n if (!withinAggregateLimit(raw)) return { ok: false, message: 'Report exceeds the 64 KiB aggregate limit.' };\n if (tool === 'ask') {\n const parsed = askInputSchema.safeParse(raw);\n return parsed.success ? { ok: true, tool, input: parsed.data } : { ok: false, message: z.prettifyError(parsed.error) };\n }\n const parsed = handoffInputSchema(kind).safeParse(raw);\n return parsed.success ? { ok: true, tool, input: parsed.data } : { ok: false, message: z.prettifyError(parsed.error) };\n}\n","/**\n * The closed runtime event union (docs/design/runtime-coordination.md §4.2).\n *\n * Writers can emit only a declared `type` at its declared `payloadVersion`, with a strict\n * payload. Readers keep strict envelopes but ignore unknown additive fields at the top level of\n * a supported payload, and refuse an unknown type or an unsupported payload version — which\n * pauses that project rather than reading it as empty. A breaking payload change adds a new\n * payload version beside the old reader; it never edits a v1 shape in place.\n */\nimport { z } from 'zod';\nimport { boundedString, MAX_COMMAND_BYTES } from '../../shared/limits.js';\nimport { PEER_REPORTING_TOOLS, RUNTIME_ROLES } from '../../shared/policy.js';\nimport { assignmentIdSchema } from '../contracts/actions.js';\nimport { assignmentCreateSchema, candidateRefSchema, commitSchema, gateSpecSchema } from '../contracts/assignment.js';\nimport { PEER_REPORT_ERROR_CODES, peerReportReceiptSchema } from '../contracts/peer.js';\n\nexport const EVENT_SCHEMA = 'paseo-room.runtime-event';\n\nconst id = z.string().min(1).max(128);\nconst text = boundedString();\nconst reason = boundedString(1024);\nconst generation = z.number().int().min(1);\nconst digest = z.string().regex(/^sha256:[0-9a-f]{64}$/);\nconst timestamp = z.iso.datetime({ offset: true });\n/** A Paseo workspace id the runtime chose before asking for it (delta P2-D3). */\nexport const workspaceIdSchema = z.string().regex(/^wks_[a-f0-9]{16}$/);\nconst branch = z.string().min(1).max(256);\nconst epoch = z.number().int().min(1);\nconst scopes = z.array(boundedString()).max(64);\n\nexport const gateResultSchema = z.strictObject({\n id,\n assignmentId: assignmentIdSchema,\n candidate: candidateRefSchema,\n command: boundedString(MAX_COMMAND_BYTES),\n startedAt: timestamp,\n finishedAt: timestamp.optional(),\n exitCode: z.number().int().optional(),\n signal: z.string().min(1).max(32).optional(),\n timedOut: z.boolean(),\n termination: z.enum(['exited', 'signaled', 'killed', 'uncertain']),\n processContractVersion: z.literal(1),\n environmentPolicyVersion: z.literal(1),\n outputDigest: digest,\n outputTailAttachment: z.string().min(1).max(256).optional(),\n workspaceMoved: z.boolean(),\n});\nexport type GateResultV1 = z.infer<typeof gateResultSchema>;\n\nexport const NOTICE_DISPOSITIONS = ['record', 'panel', 'lead-now', 'supervisor-digest', 'supervisor-now', 'operator-now', 'human-required'] as const;\nexport const NOTICE_CLASSES = ['record', 'owner', 'operator', 'page'] as const;\n\n/**\n * Every payload, as a raw shape. Intent/result pairs share one `intentId` so replay can\n * find an intent that never reached a terminal result.\n */\nexport const EVENT_PAYLOADS = {\n // Project binding and Lead ownership (§4.1, §5.2).\n 'project.bound': { canonicalRoot: z.string().min(1), gitCommonDir: z.string().min(1) },\n 'project.rebound': { canonicalRoot: z.string().min(1), gitCommonDir: z.string().min(1), previousRoot: z.string().min(1) },\n 'project.ownership-conflict': { leadAgentIds: z.array(id).min(2), leadProviderIds: z.array(id).min(1) },\n 'project.ownership-resolved': { keptLeadAgentId: id, decidedBy: z.enum(['evidence', 'human']) },\n\n // Assignment lifecycle decided by Lead or Human (§5.1).\n 'assignment.created': { input: assignmentCreateSchema, leadAgentId: id, leadProviderId: id },\n 'assignment.dispatch-requested': { peerProviderId: id, workspaceId: id },\n 'assignment.answered': { answer: text },\n 'assignment.rework-requested': { instructions: text },\n 'assignment.accepted': {\n candidate: candidateRefSchema.optional(),\n inspectedCommit: commitSchema.optional(),\n reason,\n override: z.strictObject({ reason, residualRiskAcknowledged: z.literal(true) }).optional(),\n gateResultId: id.optional(),\n },\n 'assignment.rejected': { reason },\n 'assignment.abandoned': { reason },\n 'assignment.close-requested': {},\n\n // Writer ownership, independent of assignment state (§5.3).\n 'ownership.reserved': { workspaceId: id, baseCommit: commitSchema },\n 'ownership.held': { agentId: id },\n 'ownership.releasing': { agentId: id },\n 'ownership.released': { agentId: id, archivedAt: timestamp },\n 'ownership.uncertain': { reason },\n\n // External effects: agent creation, turn delivery and archive (§6).\n // `agentId` and `idempotencyKey` are chosen before the call, so recovery reissues the identical\n // request (Phase 2 delta P2-D3). Optional and additive: a Phase 1 reader ignores them.\n 'agent.create-requested': {\n intentId: id, peerProviderId: id, workspaceId: id, parentAgentId: id, label: id,\n agentId: z.uuid().optional(), idempotencyKey: z.string().min(1).max(512).optional(),\n },\n 'agent.create-succeeded': { intentId: id, agentId: id },\n 'agent.create-failed': { intentId: id, reason },\n 'agent.create-uncertain': { intentId: id, reason },\n // A created Peer whose fresh snapshot did not prove provider, parent, workspace, idleness\n // and no prior prompt. It is archived, never adopted or prompted (§3.3, §5.3).\n 'binding.refused': { agentId: id, reason },\n 'binding.published': {\n agentId: id, providerId: id, model: z.string().min(1).max(256), parentAgentId: id, workspaceId: id, roomGeneration: id,\n },\n 'reporting.generation-opened': { generation, capabilityHash: digest, turn: z.enum(['initial', 'answer', 'rework', 'follow-up']) },\n 'run.requested': { intentId: id, generation, promptDigest: digest },\n 'run.succeeded': { intentId: id, generation },\n 'run.failed': { intentId: id, generation, reason },\n 'run.uncertain': { intentId: id, generation, reason },\n 'archive.requested': { intentId: id, agentId: id },\n 'archive.succeeded': { intentId: id, agentId: id, archivedAt: timestamp, liveStatus: z.literal('closed') },\n 'archive.failed': { intentId: id, agentId: id, reason },\n 'archive.uncertain': { intentId: id, agentId: id, reason },\n\n // Peer reporting (§3.4). Report content is evidence; identity and candidate are derived.\n 'report.accepted': {\n generation,\n tool: z.enum(PEER_REPORTING_TOOLS),\n requestId: id,\n fingerprint: digest,\n receipt: peerReportReceiptSchema,\n report: z.record(z.string(), z.unknown()),\n candidate: candidateRefSchema.optional(),\n inspectedCommit: commitSchema.optional(),\n },\n 'report.refused': { generation: generation.optional(), tool: z.string().min(1).max(64), requestId: id, code: z.enum(PEER_REPORT_ERROR_CODES), reason },\n 'report.missing': { generation },\n 'report.uncertain': { generation, requestId: id.optional(), reason },\n 'permission.awaiting': { generation, permissionRequestId: id, tool: z.enum(PEER_REPORTING_TOOLS) },\n 'permission.resolved': { generation, permissionRequestId: id, outcome: z.enum(['allowed', 'denied', 'other']) },\n\n // Independent runtime gate (D6).\n 'gate.requested': {\n gateRunId: id, candidate: candidateRefSchema, command: boundedString(MAX_COMMAND_BYTES),\n timeoutSeconds: gateSpecSchema.shape.timeoutSeconds,\n processContractVersion: z.literal(1), environmentPolicyVersion: z.literal(1),\n },\n 'gate.finished': { result: gateResultSchema },\n 'gate.uncertain': { gateRunId: id, reason },\n\n // Phase 2 worktree concurrency (docs/design/runtime-coordination-phase2.md §4). A writer lease\n // extends the assignment's ownership with its own worktree, scopes and epoch.\n 'lease.reserved': { workspaceId: workspaceIdSchema, branch, baseCommit: commitSchema, scopes, serialOnly: scopes, epoch: z.literal(1) },\n 'workspace.create-requested': {\n intentId: id, workspaceId: workspaceIdSchema, idempotencyKey: z.string().min(1).max(512), baseCommit: commitSchema,\n branchName: branch, worktreeSlug: z.string().min(1).max(128),\n },\n // Written only after the Git proof (P2-D4); `branch` is the name Paseo resolved.\n 'workspace.create-succeeded': { intentId: id, workspaceId: workspaceIdSchema, worktreePath: z.string().min(1).max(4096), branch, headCommit: commitSchema },\n 'workspace.create-failed': { intentId: id, reason },\n 'workspace.create-uncertain': { intentId: id, reason },\n // Created but failed its proof: no Peer is ever placed there, and a close follows.\n 'workspace.create-refused': { intentId: id, workspaceId: workspaceIdSchema, reason },\n 'lease.reclaimed': { fromEpoch: epoch, toEpoch: epoch, priorAgentId: id, decidedBy: z.enum(['lead', 'human']), reason },\n // Handoff evidence, not containment (§5.4).\n 'scope.exceeded': { candidateCommit: commitSchema, paths: z.array(z.string().min(1)).min(1) },\n 'workspace.close-requested': { intentId: id, workspaceId: workspaceIdSchema, discardUncommitted: z.boolean(), reason: reason.optional() },\n 'workspace.close-succeeded': { intentId: id, workspaceId: workspaceIdSchema, archivedAt: timestamp, directoryRemoved: z.boolean() },\n 'workspace.close-failed': { intentId: id, workspaceId: workspaceIdSchema, reason },\n 'workspace.close-uncertain': { intentId: id, workspaceId: workspaceIdSchema, reason },\n\n // Deterministic notices (D9). Delivery is at least once with a stable id.\n 'notice.pending': {\n noticeId: id, kind: z.string().min(1).max(64), class: z.enum(NOTICE_CLASSES), disposition: z.enum(NOTICE_DISPOSITIONS),\n recipientAgentId: id.optional(), recipientRole: z.enum(RUNTIME_ROLES).exclude(['peer']).optional(), text,\n },\n 'notice.sent': { noticeId: id },\n 'notice.failed': { noticeId: id, reason },\n 'notice.uncertain': { noticeId: id, reason },\n} as const satisfies Record<string, z.ZodRawShape>;\n\nexport type EventType = keyof typeof EVENT_PAYLOADS;\nexport const EVENT_TYPES = Object.keys(EVENT_PAYLOADS) as EventType[];\n/**\n * Payload versions this runtime can read. Phase 1 emits and reads only version 1 of every type;\n * a later breaking payload adds its version here beside the retained v1 reader.\n */\nexport const SUPPORTED_PAYLOAD_VERSIONS: Readonly<Record<EventType, readonly number[]>> = Object.fromEntries(\n EVENT_TYPES.map(type => [type, [1]] as const),\n) as unknown as Record<EventType, readonly number[]>;\n\nconst actorSchema = z.strictObject({\n source: z.enum(['human', 'plugin', 'seat', 'paseo']),\n role: z.enum(RUNTIME_ROLES).optional(),\n agentId: id.optional(),\n providerId: id.optional(),\n});\n\nconst envelope = {\n schema: z.literal(EVENT_SCHEMA),\n version: z.literal(1),\n id: z.string().regex(/^evt_[A-Za-z0-9_-]{8,64}$/),\n sequence: z.number().int().min(1),\n projectId: z.uuid(),\n assignmentId: assignmentIdSchema.optional(),\n actor: actorSchema,\n causationId: id.optional(),\n idempotencyKey: id.optional(),\n occurredAt: timestamp,\n};\n\ntype Shapes = typeof EVENT_PAYLOADS;\ntype EnvelopeFields = z.infer<z.ZodObject<typeof envelope>>;\nexport type RuntimeEventV1 = {\n [K in EventType]: EnvelopeFields & { readonly type: K; readonly payloadVersion: 1; readonly data: z.infer<z.ZodObject<Shapes[K]>> }\n}[EventType];\nexport type RuntimeEventOf<K extends EventType> = Extract<RuntimeEventV1, { type: K }>;\n\nfunction variants(strict: boolean) {\n return EVENT_TYPES.map(type => z.strictObject({\n ...envelope,\n type: z.literal(type),\n payloadVersion: z.literal(1),\n data: strict ? z.strictObject(EVENT_PAYLOADS[type]) : z.object(EVENT_PAYLOADS[type]),\n }));\n}\n\nconst [firstWriter, ...restWriters] = variants(true);\nconst [firstReader, ...restReaders] = variants(false);\nif (firstWriter === undefined || firstReader === undefined) throw new Error('The runtime event union is empty.');\nconst writerSchema = z.discriminatedUnion('type', [firstWriter, ...restWriters]);\nconst readerSchema = z.discriminatedUnion('type', [firstReader, ...restReaders]);\n\n/** Strict validation before persistence; a writer never publishes anything else. */\nexport function validateForWrite(event: unknown): RuntimeEventV1 {\n return writerSchema.parse(event) as RuntimeEventV1;\n}\n\nexport type EventReadResult =\n | { readonly ok: true; readonly event: RuntimeEventV1 }\n | { readonly ok: false; readonly reason: 'unknown-type' | 'unsupported-version' | 'invalid'; readonly detail: string };\n\n/** Forward-tolerant within a supported payload version; fail-closed everywhere else. */\nexport function readEvent(value: unknown): EventReadResult {\n if (typeof value !== 'object' || value === null) return { ok: false, reason: 'invalid', detail: 'Event is not an object.' };\n const { type, payloadVersion } = value as { type?: unknown; payloadVersion?: unknown };\n if (typeof type !== 'string' || !Object.hasOwn(EVENT_PAYLOADS, type)) {\n return { ok: false, reason: 'unknown-type', detail: `Unknown event type ${typeof type === 'string' ? type : typeof type}.` };\n }\n if (typeof payloadVersion !== 'number' || !SUPPORTED_PAYLOAD_VERSIONS[type as EventType].includes(payloadVersion)) {\n return { ok: false, reason: 'unsupported-version', detail: `Unsupported payload version ${String(payloadVersion)} for ${type}.` };\n }\n const parsed = readerSchema.safeParse(value);\n return parsed.success\n ? { ok: true, event: parsed.data as RuntimeEventV1 }\n : { ok: false, reason: 'invalid', detail: z.prettifyError(parsed.error) };\n}\n","/**\n * No-clobber atomic publication for runtime state (docs/design/runtime-coordination.md §4.2).\n *\n * A file is written whole to a unique sibling temporary, fsynced, and published with `link()` to\n * a name that did not exist. `link()` fails with EEXIST instead of replacing, so a published\n * file can never be overwritten — not by an overlapping plugin reload and not by a retry. A\n * filesystem that cannot hard-link fails closed; there is deliberately no rename fallback,\n * because rename silently replaces an existing target.\n */\nimport { randomBytes } from 'node:crypto';\nimport { chmod, link, lstat, mkdir, open, readdir, unlink } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nexport const TEMPORARY_PREFIX = '.tmp-';\nexport const PRIVATE_DIR_MODE = 0o700;\nexport const PRIVATE_FILE_MODE = 0o600;\n\n/** Where a crash-boundary test may interrupt a publication. Production passes no hook. */\nexport type PublishStep = 'temporary-written' | 'temporary-synced' | 'linked' | 'temporary-removed';\nexport type PublishHook = (step: PublishStep) => void;\n\nexport class PublishUnsupportedError extends Error {\n constructor(directory: string, cause: unknown) {\n super(`The filesystem at ${directory} cannot publish runtime state without the risk of overwriting it (hard links unavailable).`, { cause });\n this.name = 'PublishUnsupportedError';\n }\n}\n\nexport class AlreadyPublishedError extends Error {\n constructor(readonly path: string) {\n super(`${path} is already published and is never replaced.`);\n this.name = 'AlreadyPublishedError';\n }\n}\n\nfunction code(error: unknown): string | undefined {\n return typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : undefined;\n}\n\nconst UNSUPPORTED = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EXDEV', 'EMLINK']);\n\n/** Creates a room-owned runtime directory as 0700. Existing directories are tightened, never loosened. */\nexport async function ensurePrivateDirectory(path: string): Promise<void> {\n await mkdir(path, { recursive: true, mode: PRIVATE_DIR_MODE });\n const stat = await lstat(path);\n if (!stat.isDirectory()) throw new Error(`${path} is not a directory.`);\n if ((stat.mode & 0o777) !== PRIVATE_DIR_MODE) await chmod(path, PRIVATE_DIR_MODE);\n}\n\nasync function writeTemporary(directory: string, content: string | Uint8Array, hook?: PublishHook): Promise<string> {\n const temporary = join(directory, `${TEMPORARY_PREFIX}${String(process.pid)}-${randomBytes(8).toString('hex')}`);\n const handle = await open(temporary, 'wx', PRIVATE_FILE_MODE);\n try {\n await handle.writeFile(content);\n hook?.('temporary-written');\n await handle.sync();\n hook?.('temporary-synced');\n } finally {\n await handle.close();\n }\n return temporary;\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n // Directory fsync makes the new name durable. Some platforms refuse it; the file itself is\n // already synced, so that refusal is tolerated rather than failing the publication.\n let handle;\n try {\n handle = await open(directory, 'r');\n await handle.sync();\n } catch (error) {\n if (!['EISDIR', 'EINVAL', 'EPERM', 'EBADF', 'ENOTSUP'].includes(code(error) ?? '')) throw error;\n } finally {\n await handle?.close();\n }\n}\n\nasync function publishWith(\n directory: string,\n content: string | Uint8Array,\n allocate: (attempt: number) => string | undefined,\n hook?: PublishHook,\n): Promise<string> {\n const temporary = await writeTemporary(directory, content, hook);\n let published: string | undefined;\n try {\n for (let attempt = 0; ; attempt += 1) {\n const name = allocate(attempt);\n if (name === undefined) break;\n const target = join(directory, name);\n try {\n await link(temporary, target);\n published = target;\n break;\n } catch (error) {\n const reason = code(error);\n if (reason === 'EEXIST') continue;\n if (reason !== undefined && UNSUPPORTED.has(reason)) throw new PublishUnsupportedError(directory, error);\n throw error;\n }\n }\n if (published !== undefined) hook?.('linked');\n } finally {\n await unlink(temporary).catch(() => undefined);\n }\n if (published === undefined) return '';\n hook?.('temporary-removed');\n await syncDirectory(directory);\n return published;\n}\n\n/**\n * Publishes `content` under exactly `name`. An existing file is never replaced: the call throws\n * `AlreadyPublishedError` and leaves both the existing file and nothing else behind.\n */\nexport async function publishOnce(directory: string, name: string, content: string | Uint8Array, hook?: PublishHook): Promise<string> {\n const path = await publishWith(directory, content, attempt => (attempt === 0 ? name : undefined), hook);\n if (path === '') throw new AlreadyPublishedError(join(directory, name));\n return path;\n}\n\n/**\n * Publishes `content` under the first free name `allocate` offers. EEXIST moves to the next\n * attempt, so two concurrent writers both succeed under distinct names and neither overwrites.\n */\nexport async function publishAllocating(\n directory: string,\n content: string | Uint8Array,\n allocate: (attempt: number) => string,\n options: { readonly maxAttempts?: number; readonly hook?: PublishHook } = {},\n): Promise<string> {\n const maxAttempts = options.maxAttempts ?? 64;\n const path = await publishWith(directory, content, attempt => (attempt < maxAttempts ? allocate(attempt) : undefined), options.hook);\n if (path === '') throw new Error(`Could not allocate a free name in ${directory} after ${String(maxAttempts)} attempts.`);\n return path;\n}\n\n/** Temporary files a crash left behind. They are never read as state; callers report them. */\nexport async function staleTemporaries(directory: string): Promise<string[]> {\n const names = await readdir(directory);\n return names.filter(name => name.startsWith(TEMPORARY_PREFIX)).sort();\n}\n","/**\n * Per-project runtime store (docs/design/runtime-coordination.md §4.1, §4.2).\n *\n * Immutable `meta.json` and immutable event files are the only authority. Everything under\n * `cache/` is disposable and rebuilt from replay. A project whose events cannot be read in full\n * is paused with its evidence preserved — never read as an empty ledger, never auto-repaired.\n */\nimport { randomBytes, randomUUID } from 'node:crypto';\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, join } from 'node:path';\nimport { z } from 'zod';\nimport { EVENT_SCHEMA, readEvent, validateForWrite, type RuntimeEventV1 } from '../events/schema.js';\nimport {\n AlreadyPublishedError, ensurePrivateDirectory, PRIVATE_FILE_MODE, publishOnce, staleTemporaries,\n} from './publish.js';\n\nexport const RUNTIME_LAYOUT_VERSION = 'v1';\nconst EVENT_FILE = /^(\\d{12})\\.json$/;\nconst MAX_SEQUENCE_ATTEMPTS = 64;\n\nexport function runtimeRoot(roomHome: string): string {\n return join(roomHome, 'runtime', RUNTIME_LAYOUT_VERSION);\n}\n\nconst metaSchema = z.strictObject({\n schema: z.literal(1),\n projectId: z.uuid(),\n createdAt: z.iso.datetime({ offset: true }),\n canonicalRoot: z.string().min(1),\n gitCommonDir: z.string().min(1),\n});\nexport type ProjectMeta = z.infer<typeof metaSchema>;\n\nexport interface ReplayProblem {\n readonly file: string;\n readonly reason: 'unknown-type' | 'unsupported-version' | 'invalid' | 'unreadable' | 'sequence-mismatch' | 'duplicate-id' | 'foreign-project' | 'unexpected-file';\n readonly detail: string;\n}\n\nexport interface ReplayResult {\n /** `paused` means the ledger is not fully readable; callers must refuse every mutation. */\n readonly status: 'ok' | 'paused';\n readonly events: readonly RuntimeEventV1[];\n readonly problems: readonly ReplayProblem[];\n /** Sequence numbers absent between 1 and the last event. Allowed and reported. */\n readonly gaps: readonly number[];\n readonly staleTemporaries: readonly string[];\n}\n\n/** An event as a writer supplies it; the store assigns envelope identity and order. */\nexport type NewEvent = Omit<RuntimeEventV1, 'schema' | 'version' | 'id' | 'sequence' | 'projectId' | 'occurredAt'>;\n\nfunction eventName(sequence: number): string {\n return `${String(sequence).padStart(12, '0')}.json`;\n}\n\nfunction slug(root: string): string {\n const name = basename(root).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32);\n return name === '' ? 'project' : name;\n}\n\nexport class ProjectStore {\n private lastSequence = 0;\n\n private constructor(readonly directory: string, readonly meta: ProjectMeta, private readonly now: () => Date) {}\n\n get eventsDirectory(): string { return join(this.directory, 'events'); }\n get cacheDirectory(): string { return join(this.directory, 'cache'); }\n get gatesDirectory(): string { return join(this.directory, 'gates'); }\n get quarantineDirectory(): string { return join(this.directory, 'quarantine'); }\n\n /** Opens an existing project directory; refuses one whose `meta.json` is not exactly v1. */\n static async open(directory: string, now: () => Date = () => new Date()): Promise<ProjectStore> {\n const meta = metaSchema.parse(JSON.parse(await readFile(join(directory, 'meta.json'), 'utf8')));\n return new ProjectStore(directory, meta, now);\n }\n\n /**\n * Binds a new project to its canonical Git common directory. Identity is a minted UUID, never\n * a hash of a movable path; a moved repository is rebound only by an explicit operator action.\n */\n static async create(\n root: string,\n binding: { readonly canonicalRoot: string; readonly gitCommonDir: string },\n now: () => Date = () => new Date(),\n ): Promise<ProjectStore> {\n const projects = join(root, 'projects');\n await ensurePrivateDirectory(projects);\n const projectId = randomUUID();\n const directory = join(projects, `${slug(binding.canonicalRoot)}-${projectId}`);\n await ensurePrivateDirectory(directory);\n for (const child of ['events', 'cache', 'gates', 'quarantine']) await ensurePrivateDirectory(join(directory, child));\n const meta: ProjectMeta = { schema: 1, projectId, createdAt: now().toISOString(), ...binding };\n await publishOnce(directory, 'meta.json', `${JSON.stringify(meta, null, 2)}\\n`);\n const store = new ProjectStore(directory, meta, now);\n await store.append({ type: 'project.bound', payloadVersion: 1, actor: { source: 'plugin' }, data: { ...binding } });\n return store;\n }\n\n /** Finds the project bound to this Git common directory. Never matches by name, remote or cwd. */\n static async find(root: string, gitCommonDir: string, now?: () => Date): Promise<ProjectStore | undefined> {\n for (const store of await ProjectStore.list(root, now)) {\n if (store.meta.gitCommonDir === gitCommonDir) return store;\n }\n return undefined;\n }\n\n static async list(root: string, now?: () => Date): Promise<ProjectStore[]> {\n const projects = join(root, 'projects');\n let names: string[];\n try { names = await readdir(projects); } catch { return []; }\n const stores: ProjectStore[] = [];\n for (const name of names.sort()) {\n try { stores.push(await ProjectStore.open(join(projects, name), now)); } catch { /* reported by diagnostics, never adopted */ }\n }\n return stores;\n }\n\n /** Reads every event strictly. Any unreadable file pauses the project; nothing is moved. */\n async replay(): Promise<ReplayResult> {\n const names = (await readdir(this.eventsDirectory)).sort();\n const problems: ReplayProblem[] = [];\n const events: RuntimeEventV1[] = [];\n const ids = new Map<string, string>();\n for (const name of names) {\n if (name.startsWith('.tmp-')) continue;\n const match = EVENT_FILE.exec(name);\n if (!match) { problems.push({ file: name, reason: 'unexpected-file', detail: 'Not a runtime event file name.' }); continue; }\n let raw: string;\n let value: unknown;\n try {\n raw = await readFile(join(this.eventsDirectory, name), 'utf8');\n value = JSON.parse(raw);\n } catch (error) {\n problems.push({ file: name, reason: 'unreadable', detail: error instanceof Error ? error.message : String(error) });\n continue;\n }\n const read = readEvent(value);\n if (!read.ok) { problems.push({ file: name, reason: read.reason, detail: read.detail }); continue; }\n const event = read.event;\n if (event.sequence !== Number(match[1])) {\n problems.push({ file: name, reason: 'sequence-mismatch', detail: `File name does not match sequence ${String(event.sequence)}.` });\n continue;\n }\n if (event.projectId !== this.meta.projectId) {\n problems.push({ file: name, reason: 'foreign-project', detail: `Event belongs to project ${event.projectId}.` });\n continue;\n }\n const previous = ids.get(event.id);\n if (previous !== undefined) {\n problems.push({ file: name, reason: 'duplicate-id', detail: `Event id ${event.id} is also used by ${previous}.` });\n continue;\n }\n ids.set(event.id, name);\n events.push(event);\n }\n const gaps: number[] = [];\n let expected = 1;\n for (const event of events) {\n for (; expected < event.sequence; expected += 1) gaps.push(expected);\n expected = event.sequence + 1;\n }\n const highest = names.map(name => EVENT_FILE.exec(name)?.[1]).filter((value): value is string => value !== undefined).map(Number);\n this.lastSequence = Math.max(this.lastSequence, 0, ...highest);\n return {\n status: problems.length === 0 ? 'ok' : 'paused',\n events,\n problems,\n gaps,\n staleTemporaries: await staleTemporaries(this.eventsDirectory),\n };\n }\n\n /**\n * Validates and publishes one event at the next free sequence. A concurrent writer that took\n * that sequence causes reallocation, never replacement.\n */\n async append(event: NewEvent): Promise<RuntimeEventV1> {\n if (this.lastSequence === 0) await this.replay();\n // Fixed per call, so concurrent appends probe successive free sequences instead of skipping.\n const base = this.lastSequence;\n for (let attempt = 0; attempt < MAX_SEQUENCE_ATTEMPTS; attempt += 1) {\n const sequence = base + 1 + attempt;\n const full = validateForWrite({\n ...event,\n schema: EVENT_SCHEMA,\n version: 1,\n id: `evt_${randomBytes(12).toString('hex')}`,\n sequence,\n projectId: this.meta.projectId,\n occurredAt: this.now().toISOString(),\n });\n try {\n await publishOnce(this.eventsDirectory, eventName(sequence), `${JSON.stringify(full)}\\n`);\n this.lastSequence = Math.max(this.lastSequence, sequence);\n return full;\n } catch (error) {\n if (!(error instanceof AlreadyPublishedError)) throw error;\n }\n }\n throw new Error(`Could not allocate an event sequence in ${this.eventsDirectory}.`);\n }\n\n /** Writes one disposable derived view. Cache files may be replaced; they are never authority. */\n async writeCache(name: string, content: string): Promise<void> {\n await mkdir(this.cacheDirectory, { recursive: true, mode: 0o700 });\n const temporary = join(this.cacheDirectory, `.tmp-${String(process.pid)}-${randomBytes(6).toString('hex')}`);\n await writeFile(temporary, content, { mode: PRIVATE_FILE_MODE });\n await rename(temporary, join(this.cacheDirectory, name));\n }\n\n async readCache(name: string): Promise<string | undefined> {\n try { return await readFile(join(this.cacheDirectory, name), 'utf8'); } catch { return undefined; }\n }\n\n /** Deletes every cached view; the next replay rebuilds them. */\n async clearCache(): Promise<void> {\n await rm(this.cacheDirectory, { recursive: true, force: true });\n await ensurePrivateDirectory(this.cacheDirectory);\n }\n\n /** Moves one named event file aside. Only an explicit operator action calls this. */\n async quarantine(file: string): Promise<void> {\n if (!EVENT_FILE.test(file) && !file.startsWith('.tmp-')) throw new Error(`${file} is not a runtime event file.`);\n await ensurePrivateDirectory(this.quarantineDirectory);\n await rename(join(this.eventsDirectory, file), join(this.quarantineDirectory, file));\n }\n}\n","import { existsSync } from 'node:fs';\nimport { readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { project } from './runtime-plugin/server/domain/state.js';\nimport { quiescence, worktreesOnDisk, type QuiescenceBlocker } from './runtime-plugin/server/domain/views.js';\nimport { ProjectStore, runtimeRoot } from './runtime-plugin/server/store/project.js';\n\n/**\n * A read-only look at the runtime state a room recorded, using the plugin's own replay and\n * projection. The CLI never writes, repairs or quarantines anything under `runtime/`.\n */\nexport interface RuntimeStateSummary {\n readonly root: string;\n readonly projects: number;\n /** Everything still active or uncertain; a paused ledger counts, since it cannot be proven quiet. */\n readonly blockers: readonly (QuiescenceBlocker & { readonly project: string })[];\n /** Runtime worktrees Paseo still lists, awaiting a close. They are Paseo's; the CLI never closes them. */\n readonly retainedWorktrees: number;\n /** Directories Paseo archived but left behind. The CLI never deletes them either. */\n readonly leftoverDirectories: number;\n}\n\nexport async function inspectRuntimeState(roomHome: string): Promise<RuntimeStateSummary> {\n const root = runtimeRoot(roomHome);\n const names = await readdir(join(root, 'projects')).catch(() => [] as string[]);\n const blockers: (QuiescenceBlocker & { project: string })[] = [];\n const stores: ProjectStore[] = [];\n let retained = 0;\n let leftover = 0;\n for (const name of names.sort()) {\n try {\n stores.push(await ProjectStore.open(join(root, 'projects', name)));\n } catch {\n // Unreadable metadata is unknown state, never an empty project.\n blockers.push({ project: name, kind: 'assignment', id: name, detail: 'has unreadable project metadata' });\n }\n }\n for (const store of stores) {\n const replay = await store.replay();\n const projection = project(store.meta.projectId, replay.events);\n if (replay.status !== 'ok' || projection.violations.length > 0) {\n blockers.push({ project: store.meta.canonicalRoot, kind: 'assignment', id: store.meta.projectId, detail: 'the project ledger is paused and cannot be proven quiet' });\n continue;\n }\n for (const blocker of quiescence(projection.state).blockers) blockers.push({ ...blocker, project: store.meta.canonicalRoot });\n const onDisk = worktreesOnDisk(projection.state, existsSync);\n retained += onDisk.retained;\n leftover += onDisk.leftover;\n }\n return { root, projects: names.length, blockers, retainedWorktrees: retained, leftoverDirectories: leftover };\n}\n\nexport function describeBlockers(summary: RuntimeStateSummary, limit = 5): string {\n const shown = summary.blockers.slice(0, limit).map(blocker => `${blocker.project}: ${blocker.kind} ${blocker.id} ${blocker.detail}`);\n const more = summary.blockers.length > limit ? `; and ${String(summary.blockers.length - limit)} more` : '';\n return `${shown.join('; ')}${more}`;\n}\n","import { join, sep } from 'node:path';\nimport { lstat, rm } from 'node:fs/promises';\nimport { satisfies } from 'semver';\nimport metadata from '../package.json' with { type: 'json' };\nimport { claudeAgent } from './agents/claude.js';\nimport { codexAgent } from './agents/codex.js';\nimport { piAgent } from './agents/pi.js';\nimport type { Agent, AgentPlan, BuildOptions, Profile, Provider } from './agents/types.js';\nimport { AUTHENTICATION_GUIDE, renderAuthenticationGuide } from './auth.js';\nimport { applyEntries, exists, planEntries, type Entry } from './fsops.js';\nimport { layoutChecks, resolveLayout, roleHome, sharedRoom, type Layout, type Options } from './layout.js';\nimport { checkDaemon, mergeProfiles, minimumPaseoVersion, profileMatches, providerMatches, withSession, type ClientFactory, type LivePlugin, type LiveProfile, type Session } from './paseo.js';\nimport { CLAUDE_CARRIER_PASEO_RANGE, CLAUDE_CARRIER_PLUGIN_ID, claudeCarrierEntries, claudeCarrierPluginDir } from './plugin.js';\nimport { fail, failed, hasFailure, pass, warn, type Check, type Operation, type Result } from './result.js';\nimport { contractDigest } from './room/instructions.js';\nimport {\n agentSkillProjectionRoot, leadSkillProjection, roomSkillEntries, roomSkillSource, skillProjectionRoot,\n} from './room/skills.js';\nimport { MARKER, readMarker, renderMarker, type Marker, type RuntimeMarker } from './room.js';\nimport {\n renderRuntimeManifest, RUNTIME_PASEO_RANGE, RUNTIME_PLUGIN_ID, runtimePluginDir, runtimePluginEntries,\n} from './runtime.js';\nimport { describeBlockers, inspectRuntimeState, type RuntimeStateSummary } from './runtime-state.js';\nimport { DELEGATING_THINKING, profileId, providerId, providerLabel, ROLES, ROLE_COLOR, ROLE_ICON, ROLE_NOTES, ROLE_PASEO_TOOLS, ROLE_THINKING, type AgentId, type Role } from './roles.js';\n\nexport const AGENTS: Record<AgentId, Agent> = { codex: codexAgent, claude: claudeAgent, pi: piAgent };\n\nexport interface RunOptions extends Options {\n readonly agents?: readonly AgentId[];\n readonly apply?: boolean;\n /**\n * Write the role contract into Claude's `CLAUDE.md` as well as the plugin. Defaults to true:\n * the plugin is the strong carrier, but whether a resumed session re-enters its creation hook\n * is unproven, so the file fallback is only dropped when asked for.\n */\n readonly claudeMemoryContract?: boolean;\n /** Opt in to runtime coordination (preview). A per-run setup choice, recorded in the marker. */\n readonly runtime?: boolean;\n readonly env?: NodeJS.ProcessEnv;\n readonly factory?: ClientFactory;\n}\n\nfunction sessionOptions(options: RunOptions): { password?: string; factory?: ClientFactory } {\n const password = (options.env ?? process.env).PASEO_PASSWORD;\n return { ...(password === undefined ? {} : { password }), ...(options.factory ? { factory: options.factory } : {}) };\n}\n\n/** The only per-agent differences are the home variable and the provider pins. */\nfunction roleProviders(\n layout: Layout,\n agent: Agent,\n plan: { readonly binary: string; readonly argv?: AgentPlan['argv']; readonly providerEnv?: AgentPlan['providerEnv'] },\n roles: readonly Role[],\n): Record<string, Provider> {\n return Object.fromEntries(roles.map(role => [providerId(agent.id, role), {\n extends: agent.id,\n label: providerLabel(agent.id, role),\n command: [plan.binary, ...(plan.argv?.[role] ?? [])],\n env: { ...agent.providerEnv, ...plan.providerEnv?.[role], [agent.homeEnv]: roleHome(layout, agent.id, role) },\n paseoTools: { enabled: ROLE_PASEO_TOOLS[role] },\n ...agent.pins,\n }]));\n}\n\n/** The picker preset that points at a provider, so a seat is one click rather than four. */\nfunction roleProfiles(agent: Agent, roles: readonly Role[]): Profile[] {\n return roles.map(role => ({\n id: profileId(agent.id, role),\n name: providerLabel(agent.id, role),\n icon: ROLE_ICON[role],\n color: ROLE_COLOR[role],\n provider: providerId(agent.id, role),\n ...(agent.defaultModeId === undefined ? {} : { modeId: agent.defaultModeId }),\n thinkingOptionId: ROLE_THINKING[role],\n notes: ROLE_NOTES[role],\n }));\n}\n\n/**\n * A trusted Paseo plugin the room owns. The Claude carrier and the runtime are separate\n * plugins with separate ids, paths and diagnostics, so a fault in one never names or touches the\n * other (docs/design/runtime-coordination.md D1).\n */\ninterface PluginSpec {\n readonly id: string;\n readonly path: string;\n /** Check id prefix: `<prefix>.enabled`, `<prefix>.path`, `<prefix>.runtime`. */\n readonly check: string;\n readonly running: string;\n readonly enabledPass: string;\n readonly enabledFail: string;\n /**\n * The manifest's `requirements.paseo`. Paseo refuses to install a plugin outside it, so the\n * room states the same bound as its own check rather than letting `--apply` surface the\n * daemon's error. Its id is explicit because the two plugins were named independently.\n */\n readonly paseoRange: string;\n readonly rangeCheck: string;\n readonly rangeRemedy: string;\n}\n\nfunction carrierSpec(layout: Layout): PluginSpec {\n return {\n id: CLAUDE_CARRIER_PLUGIN_ID, path: claudeCarrierPluginDir(layout), check: 'claude.plugin',\n running: 'Claude contract carrier plugin',\n enabledPass: 'Paseo plugins are enabled for the required Claude contract carrier.',\n enabledFail: 'Claude rooms require the paseo-room trusted server plugin, but Paseo plugins are disabled. Plugins are trusted, unsandboxed code with access to the daemon machine.',\n paseoRange: CLAUDE_CARRIER_PASEO_RANGE, rangeCheck: 'claude.paseo-range',\n rangeRemedy: 'Use a Paseo release inside that range, or upgrade paseo-room, then run setup again.',\n };\n}\n\nfunction runtimeSpec(layout: Layout): PluginSpec {\n return {\n id: RUNTIME_PLUGIN_ID, path: runtimePluginDir(layout), check: 'runtime.plugin',\n running: 'Runtime coordination plugin (preview)',\n enabledPass: 'Paseo plugins are enabled for the runtime coordination plugin.',\n enabledFail: 'Runtime coordination is a trusted server plugin, but Paseo plugins are disabled. Plugins are trusted, unsandboxed code with access to the daemon machine.',\n paseoRange: RUNTIME_PASEO_RANGE, rangeCheck: 'runtime.paseo-range',\n rangeRemedy: 'Use a Paseo release inside that range, or run setup without --runtime.',\n };\n}\n\ninterface Desired {\n readonly entries: readonly Entry[];\n readonly providers: Readonly<Record<string, Provider>>;\n readonly profiles: readonly Profile[];\n readonly checks: readonly Check[];\n /** Room plugins this selection requires, carrier first. */\n readonly plugins: readonly PluginSpec[];\n readonly runtime?: RuntimeMarker;\n}\nasync function buildDesired(\n layout: Layout,\n agents: readonly AgentId[],\n roles: readonly Role[],\n build: BuildOptions & { readonly runtime?: boolean } = {},\n): Promise<Desired> {\n // The room-owned skill source is composed once here rather than per adapter, so three\n // seated agents cannot declare the same managed paths three times.\n const entries: Entry[] = [\n { kind: 'dir', path: layout.roomHome },\n { kind: 'dir', path: sharedRoom(layout) },\n // Earlier versions generated a default workspace protocol template here. The room ships no\n // default protocol now, so the old generated regular file is declared absent and removed.\n { kind: 'absent', path: join(sharedRoom(layout), 'WORKSPACE_PROTOCOL.md') },\n ...roomSkillEntries(layout, agents),\n ];\n const providers: Record<string, Provider> = {};\n const profiles: Profile[] = [];\n const checks: Check[] = [];\n const binaries: Partial<Record<AgentId, string>> = {};\n for (const id of agents) {\n const agent = AGENTS[id];\n const plan = await agent.build(layout, roles, build);\n entries.push(...plan.entries);\n checks.push(...plan.checks);\n const credentials = plan.credentials ?? [];\n checks.push(...credentials.flatMap(credential => credential.checks));\n const credentialPaths = new Set(credentials.map(credential => credential.path));\n const collisions = plan.entries.filter(entry => credentialPaths.has(entry.path));\n if (collisions.length > 0) {\n checks.push(fail(`${id}.credentials`,\n `${agent.label} produced managed entries for preserve-only credential paths: ${collisions.map(entry => entry.path).join(', ')}.`,\n 'This is an adapter defect; do not apply the plan.'));\n }\n if (plan.binary === undefined) continue;\n binaries[id] = plan.binary;\n Object.assign(providers, roleProviders(layout, agent, {\n binary: plan.binary,\n ...(plan.argv ? { argv: plan.argv } : {}),\n ...(plan.providerEnv ? { providerEnv: plan.providerEnv } : {}),\n }, roles));\n profiles.push(...roleProfiles(agent, roles));\n }\n if (agents.every(id => binaries[id] !== undefined)) {\n entries.push({\n kind: 'file',\n path: join(layout.roomHome, AUTHENTICATION_GUIDE),\n content: renderAuthenticationGuide(layout.roomHome, binaries, agents, roles),\n });\n checks.push(warn('room.authentication-not-validated',\n `Role authentication was not validated. Login instructions are managed at ${join(layout.roomHome, AUTHENTICATION_GUIDE)}.`,\n 'After setup --apply, follow that guide or run: paseo-room auth login <agent> <role>'));\n }\n const plugins: PluginSpec[] = [];\n if (agents.includes('claude')) {\n plugins.push(carrierSpec(layout));\n entries.push(...claudeCarrierEntries(layout, roles));\n }\n let runtime: RuntimeMarker | undefined;\n if (build.runtime === true) {\n plugins.push(runtimeSpec(layout));\n entries.push(...runtimePluginEntries(layout, agents, roles));\n runtime = { enabled: true, generation: renderRuntimeManifest(agents, roles).roomGeneration, schema: 1 };\n }\n entries.push({ kind: 'file', path: join(layout.roomHome, MARKER), content: renderMarker(metadata.version, agents, roles, contractDigest(), markerMemoryContract(agents, build.memoryContract ?? true), runtime) });\n return { entries, providers, profiles, checks, plugins, ...(runtime === undefined ? {} : { runtime }) };\n}\n\n/**\n * The marker records which rendered contract generation installed this room, so an operator\n * who upgrades the package can see that the seats now hold older text. A room installed\n * before provenance existed has no digest, which is reported the same way rather than\n * treated as a broken marker.\n */\nfunction contractProvenance(previous: Marker | undefined): Check[] {\n const digest = contractDigest();\n if (!previous) return [];\n if (previous.contract === digest) {\n return [pass('room.contract', `Role contract generation ${digest} matches this package.`)];\n }\n const held = previous.contract === undefined\n ? `was installed before the room recorded its contract generation (package ${previous.version})`\n : `holds contract generation ${previous.contract}`;\n return [warn('room.contract',\n `This room ${held}; this package renders ${digest}. Managed role documents are rewritten by setup, and a running seat keeps the text it started with.`,\n 'Run: paseo-room setup --apply, then restart the affected seats.')];\n}\n\n/**\n * `thinkingOptionId` is seeded once and the operator's afterwards, so a risky selection is\n * reported rather than corrected. Nothing here changes provider selection, profile writes, or\n * exit status.\n */\nfunction thinkingDiagnostics(live: readonly LiveProfile[], desired: readonly Profile[]): Check[] {\n const owned = new Set(desired.map(profile => profile.id));\n const selected = live\n .filter(entry => owned.has(String(entry.id)))\n .filter(entry => DELEGATING_THINKING.some(option => option === entry.thinkingOptionId))\n .map(entry => `${String(entry.id)} (${String(entry.thinkingOptionId)})`)\n .sort();\n if (selected.length === 0) return [];\n return [warn('room.thinking',\n `${String(selected.length)} room seats are set to a top reasoning option that Paseo describes as including automatic task delegation: ${selected.join(', ')}. Whether that option can actually delegate once the room has closed the native multi-agent paths is unverified: paseo-room has not verified whether those closures prevent that option from delegating, and left your selection in place.`,\n `Choose a lower reasoning option for those seats in Paseo if you want the room's own defaults (${ROLE_THINKING.supervisor} for Supervisor, ${ROLE_THINKING.lead} for Lead and Peer).`)];\n}\n\n/**\n * Names what kind of drift was found. A path the room suppressed needs deleting rather than\n * rewriting, so reporting every difference as \"missing or outdated\" would name the wrong fix.\n */\nfunction fileDriftSummary(drifted: readonly Operation[]): string {\n const removals = drifted.filter(operation => operation.action === 'remove').length;\n const count = String(drifted.length);\n const subject = drifted.length === 1 ? 'managed role file is' : 'managed role files are';\n if (removals === 0) return `${count} ${subject} missing or outdated.`;\n if (removals === drifted.length) return `${count} ${subject} present but suppressed by this room.`;\n return `${count} ${subject} missing or outdated, and ${String(removals)} of them are present but suppressed by this room.`;\n}\n\n/** Catalog copies are one of the room's three native multi-agent closures, so their drift is named. */\nfunction fileDriftDetail(targets: readonly string[]): string {\n const catalogs = targets.filter(target => target.endsWith(`${sep}model-catalog.json`));\n if (catalogs.length === 0) return '';\n const count = catalogs.length === 1 ? 'One of them is a generated Codex model catalog' : `${String(catalogs.length)} of them are generated Codex model catalogs`;\n return ` ${count}, so those seats currently lack the scrubbed catalog closure rather than only older contract text.`;\n}\n\ninterface Stale {\n readonly providerIds: readonly string[];\n readonly profileIds: readonly string[];\n /** Room plugins a previous selection registered that this one does not. */\n readonly removePlugins: readonly PluginSpec[];\n /** Role homes are retained during setup because runtime-owned credentials may be inside. */\n readonly retainedDirectories: readonly string[];\n}\nconst NOTHING_STALE: Stale = { providerIds: [], profileIds: [], removePlugins: [], retainedDirectories: [] };\n\nasync function safeDirectory(path: string, checks: Check[]): Promise<boolean> {\n try {\n const stat = await lstat(path);\n if (stat.isDirectory()) return true;\n checks.push(fail('room.path-safety',\n `Refusing to traverse ${path}: every existing room directory ancestor must be a real directory, not a symbolic link or another file type.`,\n 'Move the path aside manually after checking it for role-owned credentials, then run the command again.'));\n return false;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;\n checks.push(fail('room.path-safety', `Could not inspect room directory ${path} without following links.`,\n 'Fix its parent permissions or move the path manually, then run the command again.'));\n return false;\n }\n}\n\n/** Refuse managed writes through any existing room-relative directory alias. */\nasync function roomPathSafety(layout: Layout, agents: readonly AgentId[], roles: readonly Role[]): Promise<Check[]> {\n const checks: Check[] = [];\n if (!await safeDirectory(layout.roomHome, checks)) return checks;\n\n const room = sharedRoom(layout);\n const roomIsSafe = await safeDirectory(room, checks);\n // Calls with no agents are root-only checks used before marker discovery and by explicit remove.\n // Recursive removal unlinks nested symlinks without following them, so it must remain able to\n // delete a broken room; setup and verify make a later full pass with the affected agents.\n if (roomIsSafe && agents.length > 0) {\n const skills = join(room, 'skills');\n if (await safeDirectory(skills, checks)) {\n const source = roomSkillSource(layout);\n if (await safeDirectory(source, checks)) await safeDirectory(join(source, 'references'), checks);\n }\n const projections = skillProjectionRoot(layout);\n if (await safeDirectory(projections, checks)) {\n for (const agent of agents) {\n const agentRoot = agentSkillProjectionRoot(layout, agent);\n if (await safeDirectory(agentRoot, checks)) await safeDirectory(leadSkillProjection(layout, agent), checks);\n }\n }\n }\n\n const rolesHome = join(layout.roomHome, 'roles');\n if (!await safeDirectory(rolesHome, checks)) return checks;\n for (const agent of agents) {\n const agentHome = join(rolesHome, agent);\n if (!await safeDirectory(agentHome, checks)) continue;\n for (const role of roles) await safeDirectory(roleHome(layout, agent, role), checks);\n }\n return checks;\n}\n\n/** A previous setup may have seated agents or roles this one does not: drop those. */\nasync function staleFrom(\n layout: Layout, previous: Marker | undefined, agents: readonly AgentId[], roles: readonly Role[], runtime: boolean,\n): Promise<Stale> {\n if (!previous) return NOTHING_STALE;\n const kept = new Set(agents.flatMap(agent => roles.map(role => providerId(agent, role))));\n const providerIds: string[] = [];\n const profileIds: string[] = [];\n const retainedDirectories: string[] = [];\n for (const agent of previous.agents) {\n for (const role of previous.roles) {\n if (kept.has(providerId(agent, role))) continue;\n providerIds.push(providerId(agent, role));\n profileIds.push(profileId(agent, role));\n const path = roleHome(layout, agent, role);\n if (await exists(path)) retainedDirectories.push(path);\n }\n }\n return {\n providerIds,\n profileIds,\n removePlugins: [\n ...(previous.agents.includes('claude') && !agents.includes('claude') ? [carrierSpec(layout)] : []),\n ...(previous.runtime?.enabled === true && !runtime ? [runtimeSpec(layout)] : []),\n ],\n retainedDirectories,\n };\n}\n\ninterface Plan {\n readonly operations: readonly Operation[];\n /** Carried out of the plan so apply rewrites the array it actually compared against. */\n readonly liveProfiles: readonly LiveProfile[];\n readonly livePlugins: ReadonlyMap<string, LivePlugin>;\n readonly pluginChecks: readonly Check[];\n}\n\nfunction pluginPlan(spec: PluginSpec, wanted: boolean, plugins: readonly LivePlugin[]): {\n operation?: Operation; livePlugin?: LivePlugin; checks: Check[];\n} {\n const livePlugin = plugins.find(plugin => plugin.id === spec.id);\n if (livePlugin !== undefined && livePlugin.path !== spec.path) {\n return {\n livePlugin,\n checks: [fail(`${spec.check}.path`,\n `Plugin ${spec.id} is registered from ${livePlugin.path}, not the room-owned path ${spec.path}.`,\n 'Move or remove that conflicting plugin registration manually, then run setup again.')],\n };\n }\n if (wanted) {\n const healthy = livePlugin?.enabled === true && livePlugin.status === 'running' && livePlugin.error === undefined;\n return {\n ...(livePlugin === undefined ? {} : { livePlugin }),\n operation: { action: livePlugin === undefined ? 'create' : healthy ? 'noop' : 'update', kind: 'plugin', target: spec.id },\n checks: [],\n };\n }\n return {\n ...(livePlugin === undefined ? {} : { livePlugin }),\n operation: { action: livePlugin === undefined ? 'noop' : 'remove', kind: 'plugin', target: spec.id },\n checks: [],\n };\n}\n\n/** One definition of drift, shared by the command that fixes it and the one that reports it. */\nasync function planRoom(session: Session, desired: Desired, stale: Stale): Promise<Plan> {\n const inspectPlugins = desired.plugins.length > 0 || stale.removePlugins.length > 0;\n const [live, liveProfiles, plugins] = await Promise.all([\n session.readProviders(), session.readProfiles(), inspectPlugins ? session.listPlugins() : Promise.resolve([]),\n ]);\n const byId = new Map(liveProfiles.map(entry => [String(entry.id), entry]));\n const planned = [\n ...desired.plugins.map(spec => pluginPlan(spec, true, plugins)),\n ...stale.removePlugins.map(spec => pluginPlan(spec, false, plugins)),\n ];\n const livePlugins = new Map<string, LivePlugin>();\n for (const plugin of planned) if (plugin.livePlugin !== undefined) livePlugins.set(plugin.livePlugin.id, plugin.livePlugin);\n return {\n liveProfiles,\n livePlugins,\n pluginChecks: planned.flatMap(plugin => plugin.checks),\n operations: [\n ...await planEntries(desired.entries),\n ...Object.entries(desired.providers).map(([id, provider]) => ({\n action: !(id in live) ? 'create' : providerMatches(provider, live[id]) ? 'noop' : 'update',\n kind: 'provider',\n target: id,\n }) satisfies Operation),\n ...desired.profiles.map(profile => ({\n action: !byId.has(profile.id) ? 'create' : profileMatches(profile, byId.get(profile.id)) ? 'noop' : 'update',\n kind: 'profile',\n target: profile.id,\n }) satisfies Operation),\n ...stale.providerIds.filter(id => id in live).map(id => ({ action: 'remove', kind: 'provider', target: id }) satisfies Operation),\n ...stale.profileIds.filter(id => byId.has(id)).map(id => ({ action: 'remove', kind: 'profile', target: id }) satisfies Operation),\n ...planned.flatMap(plugin => (plugin.operation === undefined ? [] : [plugin.operation])),\n ],\n };\n}\n\nfunction pluginsEnabledCheck(spec: PluginSpec, enabled: boolean): Check {\n return enabled\n ? pass(`${spec.check}.enabled`, spec.enabledPass)\n : fail(`${spec.check}.enabled`, spec.enabledFail,\n 'Review that trust boundary, enable plugins in Paseo Settings, reload Paseo, then run setup again.');\n}\n\nfunction pluginRuntimeCheck(spec: PluginSpec, plugin: LivePlugin | undefined): Check {\n if (plugin === undefined) {\n return fail(`${spec.check}.runtime`, `Plugin ${spec.id} is not registered.`, 'Run: paseo-room setup --apply');\n }\n if (plugin.path !== spec.path) {\n return fail(`${spec.check}.runtime`, `Plugin ${spec.id} is registered from ${plugin.path}, not ${spec.path}.`,\n 'Move or remove that conflicting plugin registration manually, then run setup again.');\n }\n if (!plugin.enabled || plugin.status !== 'running' || plugin.error !== undefined) {\n const detail = plugin.error === undefined ? `status ${plugin.status}` : `${plugin.status}: ${plugin.error}`;\n return fail(`${spec.check}.runtime`, `Plugin ${spec.id} is not running (${detail}).`, 'Run: paseo-room setup --apply');\n }\n return pass(`${spec.check}.runtime`, `${spec.running} is running from ${spec.path}.`);\n}\n\nasync function reconcilePlugins(session: Session, desired: Desired, stale: Stale, plan: Plan, pending: readonly Operation[]): Promise<Check[]> {\n for (const spec of stale.removePlugins) {\n if (plan.livePlugins.has(spec.id)) await session.removePlugin(spec.id);\n }\n const checks: Check[] = [];\n for (const spec of desired.plugins) {\n let plugin = plan.livePlugins.get(spec.id);\n if (plugin === undefined) {\n plugin = await session.installPlugin(spec.path, spec.id);\n } else {\n if (!plugin.enabled) plugin = await session.enablePlugin(spec.id);\n const filesChanged = pending.some(operation =>\n (operation.kind === 'file' || operation.kind === 'dir') && operation.target.startsWith(`${spec.path}${sep}`),\n );\n const needsReload = filesChanged || plugin.status !== 'running' || plugin.error !== undefined;\n if (needsReload) plugin = await session.reloadPlugin(spec.id);\n }\n checks.push(pluginRuntimeCheck(spec, plugin));\n }\n return checks;\n}\n\n/**\n * A room plugin's range is exact on both ends: `0.8.0` and `0.9.1` are live-qualified and\n * `0.10.0` is unqualified. Selecting the plugin accepts that bound; not selecting it never\n * raises the baseline, which stays the floor `minimumPaseoVersion` reports.\n */\nfunction pluginRangeCheck(spec: PluginSpec, version: string): Check {\n return satisfies(version, spec.paseoRange)\n ? pass(spec.rangeCheck, `Paseo ${version} is inside the ${spec.running} range ${spec.paseoRange}.`)\n : fail(spec.rangeCheck, `${spec.running} supports Paseo ${spec.paseoRange}; the running daemon is ${version}.`, spec.rangeRemedy);\n}\n\n/**\n * Deselecting runtime must not strand work it recorded: it is refused while any assignment,\n * writer ownership, managed Peer archive, gate or delivery is active or uncertain. Once quiet,\n * the plugin is unregistered and the recorded state is kept for export or a later re-enable.\n */\nasync function runtimeDeselectionCheck(layout: Layout): Promise<Check[]> {\n const summary = await inspectRuntimeState(layout.roomHome);\n if (summary.projects === 0) return [];\n if (summary.blockers.length > 0) {\n return [fail('runtime.deselect',\n `Runtime coordination still has active or uncertain work: ${describeBlockers(summary)}.`,\n 'Keep --runtime and finish, close or abandon that work first; the runtime state is preserved either way.')];\n }\n return [warn('runtime.state-retained',\n `Runtime coordination is quiet; its recorded state for ${String(summary.projects)} project(s) stays at ${summary.root}.${worktreeNote(summary, 'gone')}`,\n 'Export it with: paseo-room export --out <dir>, or keep it for a later --runtime.')];\n}\n\n/**\n * Retained runtime worktrees and left-behind directories belong to Paseo and the operator: named,\n * counted, never deleted by the CLI. The remedy depends on whether the runtime panel still exists.\n */\nfunction worktreeNote(summary: RuntimeStateSummary, panel: 'available' | 'gone'): string {\n const parts: string[] = [];\n if (summary.retainedWorktrees > 0) {\n parts.push(` ${String(summary.retainedWorktrees)} runtime worktree(s) remain open in Paseo; the CLI does not close them — ${panel === 'available'\n ? 'close them from the runtime panel first'\n : 'archive them in Paseo, or re-enable --runtime and close them from the runtime panel'}.`);\n }\n if (summary.leftoverDirectories > 0) {\n parts.push(` ${String(summary.leftoverDirectories)} closed worktree director(ies) were left on disk by a failed teardown; remove them by hand once nothing in them is needed.`);\n }\n return parts.join('');\n}\n\n/** Whole-room removal keeps its destructive meaning, but says what runtime history it deletes. */\nasync function runtimeRemovalWarning(layout: Layout): Promise<Check[]> {\n const summary = await inspectRuntimeState(layout.roomHome).catch(() => undefined);\n if (summary === undefined || summary.projects === 0) return [];\n const active = summary.blockers.length > 0 ? ` It still has active or uncertain work: ${describeBlockers(summary)}.` : '';\n return [warn('room.remove.runtime-state',\n `Deleting ${layout.roomHome} also deletes runtime coordination history for ${String(summary.projects)} project(s).${active}${worktreeNote(summary, 'available')}`,\n 'Export it first with: paseo-room export --out <dir>')];\n}\n\n/**\n * The marker value for the Claude memory-contract choice. A room with no Claude seat records\n * nothing: the choice only describes Claude's `CLAUDE.md`, and storing it anyway would leave\n * state in the marker that nothing generated and nothing reads.\n */\nfunction markerMemoryContract(agents: readonly AgentId[], memoryContract: boolean): boolean | undefined {\n return agents.includes('claude') ? memoryContract : undefined;\n}\n\n/**\n * With the file carrier suppressed, the plugin is the room's only Claude carrier. The plugin\n * is verified, so this is not a silent risk — but whether a resumed session re-enters the\n * creation hook is unproven, so the operator is told what they gave up rather than reassured.\n */\nfunction memoryContractDiagnostic(agents: readonly AgentId[], memoryContract: boolean): Check[] {\n if (memoryContract || !agents.includes('claude')) return [];\n return [warn('claude.memory-contract',\n 'Claude role CLAUDE.md files carry your global memory only: the role contract was not written to them, so the trusted server plugin is this room\\'s only Claude carrier. Only a newly created agent passes through its creation hook, and whether a resumed session re-enters that hook is unproven.',\n 'Drop --no-claude-memory-contract and run setup --apply to restore the file fallback.')];\n}\n\n/** The whole product: write the role homes, then register them with Paseo. */\nexport async function setup(options: RunOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const agents = options.agents ?? ['codex'];\n const memoryContract = options.claudeMemoryContract ?? true;\n const invalid = layoutChecks(layout, agents);\n if (invalid.length > 0) return failed('setup', invalid);\n const rootSafety = await roomPathSafety(layout, [], []);\n if (hasFailure(rootSafety)) return failed('setup', rootSafety);\n const previous = await readMarker(layout);\n const safetyAgents = [...new Set([...agents, ...(previous?.agents ?? [])])];\n const pathSafety = await roomPathSafety(layout, safetyAgents, ROLES);\n if (hasFailure(pathSafety)) return failed('setup', pathSafety);\n // Cleanup uses the APIs required by the old selection too (notably Claude's plugin API).\n const compatibilityAgents = [...new Set([...agents, ...(previous?.agents ?? [])])];\n const runtime = options.runtime === true;\n const daemon = await checkDaemon(layout, options.env, minimumPaseoVersion(compatibilityAgents, runtime || previous?.runtime?.enabled === true));\n if (!daemon.daemon) return failed('setup', daemon.checks);\n const version = daemon.daemon.version;\n const desired = await buildDesired(layout, agents, ROLES, { memoryContract, runtime });\n const stale = await staleFrom(layout, previous, agents, ROLES, runtime);\n const runtimeChecks = [\n ...desired.plugins.map(spec => pluginRangeCheck(spec, version)),\n ...(stale.removePlugins.some(spec => spec.id === RUNTIME_PLUGIN_ID) ? await runtimeDeselectionCheck(layout) : []),\n ];\n const retained = stale.retainedDirectories.length === 0 ? [] : [warn(\n 'room.stale-role-homes-preserved',\n `Preserved ${String(stale.retainedDirectories.length)} deselected role homes because they may contain role-owned credentials or runtime state.`,\n `Use paseo-room remove --apply to delete the entire room after reviewing its credential warning, or remove deselected homes manually: ${stale.retainedDirectories.join(', ')}`,\n )];\n const checks = [...daemon.checks, ...runtimeChecks, ...desired.checks, ...retained];\n if (hasFailure(checks)) return failed('setup', checks);\n\n return withSession(daemon.daemon, async session => {\n const plan = await planRoom(session, desired, stale);\n const { operations, liveProfiles } = plan;\n const pending = operations.filter(operation => operation.action !== 'noop');\n const enabled = desired.plugins.length === 0 ? true : await session.pluginsEnabled();\n const pluginPreconditions = [...desired.plugins.map(spec => pluginsEnabledCheck(spec, enabled)), ...plan.pluginChecks];\n // Diagnostics last: nothing above may be reached only through a warning.\n const preApplyDiagnostics = [...checks, ...pluginPreconditions, ...memoryContractDiagnostic(agents, memoryContract), ...contractProvenance(previous), ...thinkingDiagnostics(liveProfiles, desired.profiles)];\n if (hasFailure(preApplyDiagnostics) || !options.apply) {\n return {\n command: 'setup',\n outcome: hasFailure(preApplyDiagnostics) ? 'failed' : pending.length > 0 ? 'changes-planned' : 'ok',\n changed: false, checks: preApplyDiagnostics, operations,\n } satisfies Result;\n }\n // Keep the old marker until daemon reconciliation succeeds. If a remote write fails,\n // rerunning setup can still discover every stale provider/profile/plugin it must remove.\n const markerPath = join(layout.roomHome, MARKER);\n const markerEntries = desired.entries.filter(entry => entry.path === markerPath);\n await applyEntries(desired.entries.filter(entry => entry.path !== markerPath));\n const ids = Object.keys(desired.providers);\n await session.writeProviders(desired.providers);\n if (stale.providerIds.length > 0) await session.removeProviders(stale.providerIds);\n // Profiles point at providers, so they are written once the providers exist — and\n // only when something changed, since one write replaces the host's whole array.\n let appliedProfiles = liveProfiles;\n if (pending.some(operation => operation.kind === 'profile')) {\n appliedProfiles = mergeProfiles(liveProfiles, desired.profiles, stale.profileIds);\n await session.writeProfiles(appliedProfiles);\n }\n await session.refresh(ids);\n const pluginChecks = await reconcilePlugins(session, desired, stale, plan, pending);\n await applyEntries(markerEntries);\n const appliedMarker: Marker = {\n version: metadata.version, agents: [...agents], roles: [...ROLES], contract: contractDigest(),\n ...(markerMemoryContract(agents, memoryContract) === false ? { claudeMemoryContract: false } : {}),\n ...(desired.runtime === undefined ? {} : { runtime: desired.runtime }),\n };\n const appliedChecks = [...checks, ...pluginPreconditions, ...pluginChecks,\n pass('room.applied', `Room ready at ${layout.roomHome} with ${String(ids.length)} Paseo providers.`),\n ...memoryContractDiagnostic(agents, memoryContract),\n ...contractProvenance(appliedMarker), ...thinkingDiagnostics(appliedProfiles, desired.profiles)];\n return {\n command: 'setup', outcome: hasFailure(appliedChecks) ? 'failed' : 'ok', changed: pending.length > 0,\n checks: appliedChecks, operations,\n } satisfies Result;\n }, sessionOptions(options));\n}\n\nexport async function verify(options: RunOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const rootSafety = await roomPathSafety(layout, [], []);\n if (hasFailure(rootSafety)) return failed('verify', rootSafety);\n const marker = await readMarker(layout);\n if (!marker) {\n return failed('verify', [fail('room.marker', `No room found at ${layout.roomHome}.`, 'Run: paseo-room setup --apply')]);\n }\n const invalid = layoutChecks(layout, marker.agents);\n if (invalid.length > 0) return failed('verify', invalid);\n const pathSafety = await roomPathSafety(layout, marker.agents, marker.roles);\n if (hasFailure(pathSafety)) return failed('verify', pathSafety);\n const runtime = marker.runtime?.enabled === true;\n const daemon = await checkDaemon(layout, options.env, minimumPaseoVersion(marker.agents, runtime));\n if (!daemon.daemon) return failed('verify', daemon.checks);\n const version = daemon.daemon.version;\n const desired = await buildDesired(layout, marker.agents, marker.roles, {\n // The room's own recorded choices, so verify compares against what setup wrote.\n memoryContract: marker.claudeMemoryContract ?? true,\n runtime,\n });\n const runtimeChecks = [\n ...desired.plugins.map(spec => pluginRangeCheck(spec, version)),\n ...(runtime ? [marker.runtime?.generation === desired.runtime?.generation\n ? pass('runtime.generation', `Runtime manifest generation ${String(desired.runtime?.generation)} matches this package.`)\n : fail('runtime.generation', `This room was set up with runtime generation ${String(marker.runtime?.generation)}; this package generates ${String(desired.runtime?.generation)}.`, 'Run: paseo-room setup --runtime --apply')] : []),\n ];\n const checks = [...daemon.checks, ...runtimeChecks, ...desired.checks];\n if (hasFailure(daemon.checks) || hasFailure(desired.checks)) return failed('verify', checks);\n\n return withSession(daemon.daemon, async session => {\n const plan = await planRoom(session, desired, NOTHING_STALE);\n const { operations, liveProfiles } = plan;\n const drifted = operations.filter(operation => operation.action !== 'noop');\n const count = (kind: Operation['kind']): number => drifted.filter(operation => operation.kind === kind).length;\n const providers = count('provider');\n const profiles = count('profile');\n const driftedFiles = drifted.filter(operation => !['provider', 'profile', 'plugin'].includes(operation.kind));\n const files = driftedFiles.length;\n const enabled = desired.plugins.length === 0 ? true : await session.pluginsEnabled();\n const pluginChecks = desired.plugins.flatMap(spec => [\n pluginsEnabledCheck(spec, enabled),\n ...plan.pluginChecks.filter(check => check.id.startsWith(`${spec.check}.`)),\n pluginRuntimeCheck(spec, plan.livePlugins.get(spec.id)),\n ]);\n const all: Check[] = [...checks,\n files === 0\n ? pass('room.files', 'Every managed role file matches the current definition.')\n : fail('room.files', `${fileDriftSummary(driftedFiles)}${fileDriftDetail(driftedFiles.map(operation => operation.target))}`, 'Run: paseo-room setup --apply'),\n providers === 0\n ? pass('room.providers', `All ${String(Object.keys(desired.providers).length)} Paseo providers are registered as expected.`)\n : fail('room.providers', `${String(providers)} Paseo providers are missing or differ.`, 'Run: paseo-room setup --apply'),\n profiles === 0\n ? pass('room.profiles', `All ${String(desired.profiles.length)} Paseo agent profiles are registered as expected.`)\n : fail('room.profiles', `${String(profiles)} Paseo agent profiles are missing or differ.`, 'Run: paseo-room setup --apply'),\n ...pluginChecks,\n // Diagnostics last: a warning never precedes the failure it might be mistaken for.\n ...memoryContractDiagnostic(marker.agents, marker.claudeMemoryContract ?? true),\n ...contractProvenance(marker),\n ...thinkingDiagnostics(liveProfiles, desired.profiles),\n ];\n return {\n command: 'verify', outcome: hasFailure(all) ? 'failed' : 'ok', changed: false, checks: all, operations,\n } satisfies Result;\n }, sessionOptions(options));\n}\n\nexport async function remove(options: RunOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const rootSafety = await roomPathSafety(layout, [], []);\n if (hasFailure(rootSafety)) return failed('remove', rootSafety);\n const marker = await readMarker(layout);\n if (!marker) {\n return failed('remove', [fail('room.marker', `No room found at ${layout.roomHome}.`, 'Nothing to remove; the room home was never created here.')]);\n }\n // A recursive delete needs a floor, so the layout rules gate this command too.\n const invalid = layoutChecks(layout, marker.agents);\n if (invalid.length > 0) return failed('remove', invalid);\n const ids = marker.agents.flatMap(agent => marker.roles.map(role => providerId(agent, role)));\n const profiles = new Set(marker.agents.flatMap(agent => marker.roles.map(role => profileId(agent, role))));\n const plugins = [\n ...(marker.agents.includes('claude') ? [carrierSpec(layout)] : []),\n ...(marker.runtime?.enabled === true ? [runtimeSpec(layout)] : []),\n ];\n const operations: Operation[] = [\n ...ids.map(id => ({ action: 'remove', kind: 'provider', target: id }) satisfies Operation),\n ...[...profiles].map(id => ({ action: 'remove', kind: 'profile', target: id }) satisfies Operation),\n ...plugins.map(spec => ({ action: 'remove', kind: 'plugin', target: spec.id }) satisfies Operation),\n { action: 'remove', kind: 'dir', target: layout.roomHome },\n ];\n const credentialWarning = warn('room.remove.credentials',\n `Deleting ${layout.roomHome} will delete role-owned credential files stored inside it. Native OS keyring entries are not inspected or deleted and may remain. Operator agent-home credentials are untouched.`);\n const runtimeWarnings = await runtimeRemovalWarning(layout);\n if (!options.apply) {\n return { command: 'remove', outcome: 'changes-planned', changed: false, checks: [credentialWarning, ...runtimeWarnings], operations };\n }\n const daemon = await checkDaemon(layout, options.env);\n const checks: Check[] = [credentialWarning, ...runtimeWarnings];\n if (!daemon.daemon) {\n return failed('remove', [\n credentialWarning,\n ...daemon.checks,\n fail(\n 'room.files',\n `Preserved ${layout.roomHome}, including its room marker, because Paseo cleanup could not start.`,\n 'Start Paseo, then run: paseo-room remove --apply',\n ),\n ]);\n }\n try {\n await withSession(daemon.daemon, async session => {\n if (plugins.length > 0) {\n const live = await session.listPlugins();\n // Deregister before the room home is deleted, and never a registration from a foreign path.\n for (const spec of plugins) {\n const plugin = live.find(entry => entry.id === spec.id);\n if (plugin !== undefined && plugin.path !== spec.path) throw new Error(`refusing to remove foreign plugin path ${plugin.path}`);\n }\n for (const spec of plugins) {\n if (live.some(entry => entry.id === spec.id)) await session.removePlugin(spec.id);\n }\n }\n await session.removeProviders(ids);\n const live = await session.readProfiles();\n const kept = live.filter(entry => !profiles.has(String(entry.id)));\n if (kept.length !== live.length) await session.writeProfiles(kept);\n }, sessionOptions(options));\n checks.push(pass('room.providers', `Removed ${String(ids.length)} Paseo providers and their agent profiles.`));\n } catch {\n return failed('remove', [\n credentialWarning,\n fail(\n 'room.providers',\n `Paseo provider/profile cleanup did not complete; ${layout.roomHome} and its room marker were preserved.`,\n 'Restore Paseo connectivity, then run: paseo-room remove --apply',\n ),\n ]);\n }\n // Explicit remove owns the whole room home, including runtime-owned role credentials.\n try {\n await rm(layout.roomHome, { recursive: true, force: true });\n } catch (error) {\n const detail = error instanceof Error ? error.message : 'unknown filesystem error';\n checks.push(fail(\n 'room.files',\n `Removed the Paseo providers and profiles, but could not fully delete ${layout.roomHome}: ${detail}`,\n 'Delete that directory manually after reviewing it for role-owned credentials; the Paseo side is already clean.',\n ));\n const completedOperations = operations.filter(operation => operation.kind !== 'dir');\n return { command: 'remove', outcome: 'failed', changed: true, checks, operations: completedOperations };\n }\n checks.push(pass('room.files', `Deleted ${layout.roomHome}.`));\n return { command: 'remove', outcome: 'ok', changed: true, checks, operations };\n}\n","import * as clack from '@clack/prompts';\nimport { AGENTS, remove, setup, verify, type RunOptions } from './commands.js';\nimport type { Result } from './result.js';\nimport { AGENT_IDS, type AgentId } from './roles.js';\n\nexport interface Prompts {\n select(options: { readonly message: string; readonly options: readonly { readonly value: string; readonly label: string }[] }): Promise<string | symbol>;\n multiselect(options: { readonly message: string; readonly options: readonly { readonly value: AgentId; readonly label: string }[] }): Promise<AgentId[] | symbol>;\n confirm(options: { readonly message: string }): Promise<boolean | symbol>;\n}\nexport const terminalPrompts: Prompts = {\n select: options => clack.select({ message: options.message, options: [...options.options] }),\n multiselect: options => clack.multiselect({ message: options.message, options: [...options.options], required: true }),\n confirm: options => clack.confirm({ message: options.message, initialValue: false }),\n};\n\n/** Guided path over the same commands the flags use; nothing extra happens here. */\nexport async function runWizard(\n prompts: Prompts,\n emit: (result: Result) => number,\n write: (text: string) => void,\n options: RunOptions = {},\n onAction?: (action: string) => void,\n): Promise<number> {\n const cancelled = (): number => { write('Cancelled; nothing was changed.\\n'); return 0; };\n const action = await prompts.select({\n message: 'What do you want to do?',\n options: [\n { value: 'setup', label: 'Set up / update the room (login stays separate)' },\n { value: 'verify', label: 'Verify the current room' },\n { value: 'remove', label: 'Remove the room' },\n ],\n });\n if (typeof action === 'symbol') return cancelled();\n onAction?.(action);\n if (action === 'verify') return emit(await verify(options));\n if (action === 'remove') {\n const preview = await remove(options);\n const status = emit(preview);\n if (preview.outcome !== 'changes-planned') return status;\n const approved = await prompts.confirm({ message: 'Delete the room home, including role credentials, and its Paseo providers?' });\n return approved === true ? emit(await remove({ ...options, apply: true })) : cancelled();\n }\n const agents = await prompts.multiselect({\n message: 'Which coding agents should the room use?',\n options: AGENT_IDS.map(value => ({ value, label: AGENTS[value].label })),\n });\n if (typeof agents === 'symbol' || agents.length === 0) return cancelled();\n // Only meaningful for Claude: the other adapters have no plugin carrier to fall back from.\n let claudeMemoryContract = true;\n if (agents.includes('claude')) {\n const carrier = await prompts.select({\n message: 'Claude role contract carrier: the room plugin is always used. Also write the contract into each role CLAUDE.md?',\n options: [\n { value: 'both', label: 'Yes — keep it as a fallback (recommended; resume behaviour is unproven)' },\n { value: 'plugin', label: 'No — plugin only; CLAUDE.md keeps your global memory alone' },\n ],\n });\n if (typeof carrier === 'symbol') return cancelled();\n claudeMemoryContract = carrier === 'both';\n }\n // Runtime coordination is an explicit opt-in, never a default: it installs trusted plugin code.\n const coordination = await prompts.select({\n message: 'Runtime coordination (preview): track assignments, Peer reports and writer ownership through a trusted Paseo plugin?',\n options: [\n { value: 'off', label: 'No — keep the room as it is (default)' },\n { value: 'runtime', label: 'Yes — install the paseo-room-runtime plugin (trusted, unsandboxed code)' },\n ],\n });\n if (typeof coordination === 'symbol') return cancelled();\n const setupOptions = { ...options, agents, claudeMemoryContract, ...(coordination === 'runtime' ? { runtime: true } : {}) };\n const preview = await setup(setupOptions);\n const status = emit(preview);\n if (preview.outcome !== 'changes-planned') return status;\n const approved = await prompts.confirm({ message: 'Apply these changes? Authentication will not be validated or started.' });\n if (approved !== true) return cancelled();\n return emit(await setup({ ...setupOptions, apply: true }));\n}\n","import { Command, CommanderError, InvalidArgumentError } from 'commander';\nimport metadata from '../package.json' with { type: 'json' };\nimport { loginRole, type LoginSpawner } from './auth.js';\nimport { remove, setup, verify, type RunOptions } from './commands.js';\nimport { exportRuntime } from './export.js';\nimport { ManagedPathError } from './fsops.js';\nimport { renderHuman, renderJson } from './render.js';\nimport { exitCode, fail, failed, type Result } from './result.js';\nimport { AGENT_IDS, type AgentId } from './roles.js';\nimport { PromptAssetError } from './room/prompts.js';\nimport { SkillAssetError } from './room/skills.js';\nimport type { Prompts } from './wizard.js';\n\nexport interface Output {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\nexport interface CliContext {\n readonly isTTY?: boolean;\n readonly prompts?: Prompts;\n readonly options?: RunOptions;\n readonly loginSpawn?: LoginSpawner;\n}\n\n/** Commander passes no initial value, so the first call starts the list. */\nfunction collectAgent(value: string, previous: AgentId[] | undefined): AgentId[] {\n const agent = AGENT_IDS.find(id => id === value);\n if (!agent) throw new InvalidArgumentError(`Unknown agent: ${value}`);\n const seated = previous ?? [];\n return seated.includes(agent) ? seated : [...seated, agent];\n}\n\nconst PATH_FLAGS = ['roomHome', 'codexHome', 'claudeHome', 'piHome', 'codexBin', 'claudeBin', 'piBin', 'paseoBin'] as const;\n\nfunction optionsFrom(raw: Record<string, unknown>, base: RunOptions): RunOptions {\n const paths: Record<string, string> = {};\n for (const flag of PATH_FLAGS) {\n const value = raw[flag];\n if (typeof value === 'string' && value.trim()) paths[flag] = value.trim();\n }\n const agents = Array.isArray(raw.agent) && raw.agent.length > 0 ? (raw.agent as AgentId[]) : undefined;\n return {\n ...base, ...paths, ...(agents ? { agents } : {}), ...(raw.apply === true ? { apply: true } : {}),\n // Commander defaults a --no- flag to true, so only an explicit opt-out is carried.\n ...(raw.claudeMemoryContract === false ? { claudeMemoryContract: false } : {}),\n ...(raw.runtime === true ? { runtime: true } : {}),\n };\n}\n\nfunction failedFromThrown(command: string, error: unknown): Result {\n if (error instanceof PromptAssetError) {\n return failed(command, [fail(\n `${command}.prompt-asset`,\n error.message,\n 'Reinstall paseo-room, then try again.',\n )]);\n }\n if (error instanceof SkillAssetError) {\n return failed(command, [fail(\n `${command}.skill-asset`,\n error.message,\n 'Reinstall paseo-room, then try again.',\n )]);\n }\n // A refused path knows its own remedy, and it is never \"check the daemon\": the room reached\n // the filesystem and stopped there deliberately.\n if (error instanceof ManagedPathError) {\n return failed(command, [fail(`${command}.managed-path`, error.message, error.fix)]);\n }\n const detail = error instanceof Error ? error.message : 'unknown error';\n return failed(command, [fail(\n `${command}.error`,\n detail,\n 'Check that Paseo is running and reachable, then try again.',\n )]);\n}\n\nexport async function runCli(argv: readonly string[], output: Output, context: CliContext = {}): Promise<number> {\n const password = (context.options?.env ?? process.env).PASEO_PASSWORD;\n const redact = (text: string): string => (password ? text.split(password).join('[redacted]') : text);\n // Set once the flags are parsed; the wizard path never sees flags, so text output is right there.\n let json = false;\n const emit = (result: Result): number => {\n output.stdout(redact(json ? renderJson(result) : renderHuman(result)));\n return exitCode(result);\n };\n const isTTY = context.isTTY ?? (process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY);\n const base = context.options ?? {};\n\n if (argv.length === 0) {\n if (!isTTY) {\n output.stderr('paseo-room: no command given. Try: paseo-room setup, verify, remove, auth login, or --help.\\n');\n return 2;\n }\n let wizardCommand = 'wizard';\n try {\n // @clack/prompts is only reachable here, so keep it off the scripted path.\n const { runWizard, terminalPrompts } = await import('./wizard.js');\n return await runWizard(\n context.prompts ?? terminalPrompts,\n emit,\n text => { output.stdout(text); },\n base,\n action => { wizardCommand = action; },\n );\n } catch (error) {\n return emit(failedFromThrown(wizardCommand, error));\n }\n }\n const program = new Command()\n .name('paseo-room')\n .description('Configure Codex/Claude/Pi role homes in $HOME and register them with your local Paseo daemon.')\n .version(metadata.version)\n .usage('<setup|verify|remove|export> [options]\\n auth login <codex|claude|pi> <supervisor|lead|peer> [options]')\n .argument('<command>', 'setup | verify | remove | export | auth')\n .argument('[command-arguments...]', 'auth login <agent> <role>')\n .option('--agent <agent>', 'codex, claude, or pi; repeat to combine (default: codex)', collectAgent)\n .option('--apply', 'actually make the changes (default: dry run)')\n .option('--json', 'machine-readable output')\n .option('--no-claude-memory-contract', 'omit the role contract from Claude role CLAUDE.md files, leaving the room plugin as the only Claude carrier')\n .option('--runtime', 'opt in to runtime coordination (preview): installs the trusted paseo-room-runtime plugin; omit it to deselect')\n .option('--out <dir>', 'export: destination directory (default: a new directory under the room\\'s runtime exports)')\n .option('--include-gate-output', 'export: also copy bounded gate output tails (best-effort masked)')\n .option('--room-home <path>', 'where role homes are written (default: ~/.paseo-room)')\n .option('--codex-home <path>', 'source Codex config (default: ~/.codex)')\n .option('--claude-home <path>', 'source Claude Code config (default: ~/.claude)')\n .option('--pi-home <path>', 'source Pi config (default: ~/.pi/agent)')\n .option('--codex-bin <path>', 'Codex executable (default: found on PATH)')\n .option('--claude-bin <path>', 'Claude Code executable (default: found on PATH)')\n .option('--pi-bin <path>', 'Pi executable (default: found on PATH)')\n .option('--paseo-bin <path>', 'Paseo executable (default: found on PATH)')\n .configureOutput({ writeOut: text => { output.stdout(text); }, writeErr: text => { output.stderr(text); } })\n .exitOverride();\n\n let command: string;\n let commandArguments: string[];\n let options: RunOptions;\n let raw: Record<string, unknown>;\n try {\n program.parse([...argv], { from: 'user' });\n raw = program.opts<Record<string, unknown>>();\n json = raw.json === true;\n command = program.args[0] ?? '';\n commandArguments = program.args.slice(1);\n options = optionsFrom(raw, base);\n } catch (error) {\n if (error instanceof CommanderError && error.exitCode === 0) return 0;\n return 2;\n }\n\n try {\n // Only setup chooses this: verify and remove read the room's recorded choice instead, and\n // auth does not carry it at all. Silently ignoring it would misreport what the run did.\n if (raw.claudeMemoryContract === false && (command === 'verify' || command === 'remove')) {\n output.stderr(`paseo-room ${command}: --no-claude-memory-contract is a setup choice recorded in the room marker; ${command} reads it from there.\\n`);\n return 2;\n }\n if ((raw.out !== undefined || raw.includeGateOutput === true) && command !== 'export') {\n output.stderr(`paseo-room ${command}: --out and --include-gate-output only apply to export.\\n`);\n return 2;\n }\n if (raw.runtime === true && (command === 'verify' || command === 'remove' || command === 'export')) {\n output.stderr(`paseo-room ${command}: --runtime is a setup choice recorded in the room marker; ${command} reads it from there.\\n`);\n return 2;\n }\n if (command === 'auth') {\n if (raw.runtime === true) {\n output.stderr('paseo-room auth login only authenticates a role and does not use --runtime.\\n');\n return 2;\n }\n if (raw.claudeMemoryContract === false) {\n output.stderr('paseo-room auth login only authenticates a role and does not use --no-claude-memory-contract.\\n');\n return 2;\n }\n if (raw.apply === true) {\n output.stderr('paseo-room auth login is already explicit and does not use --apply.\\n');\n return 2;\n }\n if (raw.json === true) {\n output.stderr('paseo-room auth login is interactive and does not support --json.\\n');\n return 2;\n }\n if (raw.agent !== undefined) {\n output.stderr('paseo-room auth login takes exactly one positional agent and does not use --agent.\\n');\n return 2;\n }\n if (commandArguments.length !== 3 || commandArguments[0] !== 'login') {\n output.stderr('Usage: paseo-room auth login <codex|claude|pi> <supervisor|lead|peer>\\n');\n return 2;\n }\n return await loginRole(commandArguments[1] ?? '', commandArguments[2] ?? '', {\n ...options,\n isTTY,\n ...(context.loginSpawn ? { spawn: context.loginSpawn } : {}),\n }, output);\n }\n if (commandArguments.length > 0) {\n output.stderr(`paseo-room ${command}: unexpected arguments: ${commandArguments.join(' ')}\\n`);\n return 2;\n }\n if (command === 'setup') return emit(await setup(options));\n if (command === 'verify') return emit(await verify(options));\n if (command === 'remove') return emit(await remove(options));\n if (command === 'export') {\n return emit(await exportRuntime({\n ...options,\n ...(typeof raw.out === 'string' && raw.out.trim() !== '' ? { out: raw.out.trim() } : {}),\n ...(raw.includeGateOutput === true ? { includeGateOutput: true } : {}),\n }));\n }\n } catch (error) {\n return emit(failedFromThrown(command, error));\n }\n output.stderr(`paseo-room: unknown command \"${command}\". Try: setup, verify, remove, export, or auth login.\\n`);\n return 2;\n}\n","import { copyFile, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport metadata from '../package.json' with { type: 'json' };\nimport { resolveLayout } from './layout.js';\nimport { fail, failed, pass, warn, type Check, type Operation, type Result } from './result.js';\nimport type { RunOptions } from './commands.js';\nimport { readEvent } from './runtime-plugin/server/events/schema.js';\nimport { runtimeRoot } from './runtime-plugin/server/store/project.js';\n\nexport interface ExportOptions extends RunOptions {\n /** Destination directory; defaults to a new directory under the room's runtime exports. */\n readonly out?: string;\n readonly includeGateOutput?: boolean;\n}\n\nconst LIMITATION = 'Briefs, answers, reports and gate commands are stored as written and cannot be proven secret-free; review the export before sharing it.';\n\nasync function isEmptyOrAbsent(path: string): Promise<boolean> {\n try { return (await readdir(path)).length === 0; } catch { return true; }\n}\n\n/**\n * Explicit, read-only export of runtime state (docs/design/runtime-coordination.md §10). Needs\n * no daemon. Only schema-valid events are copied; anything unreadable is listed by name, never\n * by content. Gate output tails stay out unless asked for. Nothing under `runtime/` changes.\n */\nexport async function exportRuntime(options: ExportOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const root = runtimeRoot(layout.roomHome);\n let projects: string[];\n try { projects = (await readdir(join(root, 'projects'))).sort(); } catch { projects = []; }\n if (projects.length === 0) {\n return failed('export', [fail('export.nothing', `No runtime state was found under ${root}.`, 'Runtime coordination records state only after setup --runtime and a first assignment.')]);\n }\n const stamp = new Date().toISOString().replace(/[:.]/g, '-');\n const destination = resolve(options.out ?? join(root, 'exports', stamp));\n if (!await isEmptyOrAbsent(destination)) {\n return failed('export', [fail('export.destination', `${destination} already exists and is not empty.`, 'Choose a new or empty --out directory.')]);\n }\n\n const operations: Operation[] = [{ action: 'create', kind: 'dir', target: destination }];\n const summary: { projectId: string; canonicalRoot: string; events: number; omitted: string[]; gateOutputs: number }[] = [];\n const copies: [string, string][] = [];\n for (const name of projects) {\n const source = join(root, 'projects', name);\n const target = join(destination, 'projects', name);\n let meta: { projectId?: string; canonicalRoot?: string };\n try { meta = JSON.parse(await readFile(join(source, 'meta.json'), 'utf8')) as typeof meta; } catch { meta = {}; }\n const entry = { projectId: meta.projectId ?? name, canonicalRoot: meta.canonicalRoot ?? 'unknown', events: 0, omitted: [] as string[], gateOutputs: 0 };\n copies.push([join(source, 'meta.json'), join(target, 'meta.json')]);\n for (const file of (await readdir(join(source, 'events')).catch(() => [] as string[])).sort()) {\n if (file.startsWith('.tmp-')) continue;\n let valid: boolean;\n try { valid = readEvent(JSON.parse(await readFile(join(source, 'events', file), 'utf8'))).ok; } catch { valid = false; }\n if (valid) { entry.events += 1; copies.push([join(source, 'events', file), join(target, 'events', file)]); }\n else entry.omitted.push(file);\n }\n for (const file of (await readdir(join(source, 'gates')).catch(() => [] as string[])).sort()) {\n if (file.endsWith('.result.json')) copies.push([join(source, 'gates', file), join(target, 'gates', file)]);\n else if (file.endsWith('.log') && options.includeGateOutput === true) { entry.gateOutputs += 1; copies.push([join(source, 'gates', file), join(target, 'gates', file)]); }\n }\n summary.push(entry);\n }\n operations.push(...copies.map(([, target]) => ({ action: 'create', kind: 'file', target }) satisfies Operation));\n operations.push({ action: 'create', kind: 'file', target: join(destination, 'summary.json') });\n\n const checks: Check[] = [\n warn('export.limitation', LIMITATION),\n ...(options.includeGateOutput === true ? [warn('export.gate-output', 'Gate output tails are included; they are best-effort masked only.')] : []),\n ...summary.filter(entry => entry.omitted.length > 0).map(entry => warn('export.omitted', `Project ${entry.projectId}: ${String(entry.omitted.length)} unreadable event file(s) were left out by name: ${entry.omitted.join(', ')}.`)),\n ];\n if (!options.apply) return { command: 'export', outcome: 'changes-planned', changed: false, checks, operations };\n\n await mkdir(destination, { recursive: true, mode: 0o700 });\n for (const [from, to] of copies) {\n await mkdir(join(to, '..'), { recursive: true, mode: 0o700 });\n await copyFile(from, to);\n }\n await writeFile(join(destination, 'summary.json'), `${JSON.stringify({\n schema: 1, exportedAt: new Date().toISOString(), packageVersion: metadata.version, gateOutputIncluded: options.includeGateOutput === true,\n limitation: LIMITATION, projects: summary,\n }, null, 2)}\\n`, { mode: 0o600 });\n return { command: 'export', outcome: 'ok', changed: true, checks: [...checks, pass('export.written', `Exported ${String(summary.length)} project(s) to ${destination}.`)], operations };\n}\n","import type { Result } from './result.js';\n\nexport function renderJson(result: Result): string {\n return `${JSON.stringify({ schemaVersion: 2, ...result }, null, 2)}\\n`;\n}\n\nconst ICONS = { pass: '✓', warn: '!', fail: '✗' } as const;\n\nexport function renderHuman(result: Result): string {\n const lines: string[] = [];\n for (const check of result.checks) {\n lines.push(`${ICONS[check.status]} ${check.message}`);\n if (check.fix) lines.push(` → ${check.fix}`);\n }\n const changes = result.operations.filter(operation => operation.action !== 'noop');\n if (changes.length > 0) {\n lines.push('', result.changed ? 'Applied:' : 'Planned changes:');\n for (const operation of changes) lines.push(` ${operation.action} ${operation.kind} ${operation.target}`);\n const unchanged = result.operations.length - changes.length;\n if (unchanged > 0) lines.push(` (${String(unchanged)} already up to date)`);\n } else if (result.operations.length > 0) {\n lines.push('', 'Everything is already up to date.');\n }\n lines.push('', `${result.command}: ${result.outcome}`);\n return `${lines.join('\\n')}\\n`;\n}\n","#!/usr/bin/env node\nimport { runCli } from './cli.js';\n\nprocess.exitCode = await runCli(process.argv.slice(2), {\n stdout: text => { process.stdout.write(text); },\n stderr: text => { process.stderr.write(text); },\n});\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,UAAY;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,UAAY;AAAA,MACZ,MAAQ;AAAA,MACR,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO;AAAA,MACT;AAAA,MACA,SAAW;AAAA,MACX,QAAU;AAAA,MACV,MAAQ;AAAA,MACR,SAAW;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA,KAAO;AAAA,QACL,cAAc;AAAA,MAChB;AAAA,MACA,OAAS;AAAA,QACP;AAAA,MACF;AAAA,MACA,SAAW;AAAA,QACT,WAAa;AAAA,QACb,MAAQ;AAAA,QACR,MAAQ;AAAA,QACR,gBAAgB;AAAA,QAChB,OAAS;AAAA,QACT,SAAW;AAAA,QACX,QAAU;AAAA,QACV,kBAAkB;AAAA,MACpB;AAAA,MACA,cAAgB;AAAA,QACd,kBAAkB;AAAA,QAClB,oBAAoB;AAAA,QACpB,WAAa;AAAA,QACb,QAAU;AAAA,QACV,aAAa;AAAA,QACb,KAAO;AAAA,MACT;AAAA,MACA,iBAAmB;AAAA,QACjB,cAAc;AAAA,QACd,oBAAoB;AAAA,QACpB,sBAAsB;AAAA,QACtB,eAAe;AAAA,QACf,gBAAgB;AAAA,QAChB,iBAAiB;AAAA,QACjB,QAAU;AAAA,QACV,OAAS;AAAA,QACT,gBAAgB;AAAA,QAChB,MAAQ;AAAA,QACR,YAAc;AAAA,QACd,qBAAqB;AA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AK,CAAC;AAAA,EAC9C;AACA,SAAO,OAAO,gCAAgC,OAAO;AAAA,CAAyD;AAC9G,SAAO;AACT;;;AGpNA,QAAQ,WAAW,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,GAAG;AAAA,EACrD,QAAQ,CAAAG,UAAQ;AAAE,YAAQ,OAAO,MAAMA,KAAI;AAAA,EAAG;AAAA,EAC9C,QAAQ,CAAAA,UAAQ;AAAE,YAAQ,OAAO,MAAMA,KAAI;AAAA,EAAG;AAChD,CAAC;","names":["id","stat","id","id","lstat","readlink","join","stat","title","join","join","resolve","constants","join","lstat","env","argv","resolve","code","current","table","id","readdir","join","readFileSync","join","cache","readFile","join","id","join","id","SHARED","EXECUTABLE","evidence","parsed","spawn","readFile","rm","isAbsolute","join","resolve","asObject","parsed","reason","code","command","id","AUTH_ENV","SHARED","EXECUTABLE","z","parsed","run","id","readFileSync","join","id","z","providerId","createHash","readFileSync","join","sep","z","text","reason","parsed","table","assignment","id","current","code","createHash","z","z","z","z","parsed","text","reason","generation","digest","randomBytes","chmod","lstat","mkdir","readdir","unlink","join","stat","reason","randomBytes","mkdir","readdir","readFile","rename","rm","writeFile","basename","join","z","readdir","join","join","sep","lstat","rm","id","digest","stat","live","preview","status","approved","mkdir","readdir","readFile","writeFile","join","resolve","valid","id","text","runWizard","terminalPrompts","text"]}
1
+ {"version":3,"sources":["../package.json","../src/result.ts","../src/credentials.ts","../src/layout.ts","../src/fsops.ts","../src/roles.ts","../src/room.ts","../src/which.ts","../src/auth.ts","../src/room/prompts.ts","../src/room/instructions.ts","../src/agents/mcp.ts","../src/agents/resources.ts","../src/room/skills.ts","../src/agents/claude.ts","../src/agents/codex.ts","../src/agents/pi.ts","../src/paseo.ts","../src/plugin.ts","../src/runtime-plugin/shared/policy.ts","../src/runtime-plugin/shared/manifest.ts","../src/runtime-plugin/shared/identity.ts","../src/runtime.ts","../src/runtime-plugin/shared/limits.ts","../src/runtime-plugin/server/domain/scope.ts","../src/runtime-plugin/server/domain/state.ts","../src/runtime-plugin/server/domain/receipts.ts","../src/runtime-plugin/server/domain/views.ts","../src/runtime-plugin/server/contracts/assignment.ts","../src/runtime-plugin/server/contracts/actions.ts","../src/runtime-plugin/server/contracts/peer.ts","../src/runtime-plugin/server/events/schema.ts","../src/runtime-plugin/server/store/publish.ts","../src/runtime-plugin/server/store/project.ts","../src/runtime-state.ts","../src/commands.ts","../src/wizard.ts","../src/cli.ts","../src/export.ts","../src/render.ts","../src/index.ts"],"sourcesContent":["{\n \"name\": \"paseo-room\",\n \"version\": \"0.8.0\",\n \"description\": \"One CLI that configures Codex, Claude Code, and Pi role homes in $HOME and registers them with your local Paseo daemon.\",\n \"keywords\": [\n \"paseo\",\n \"codex\",\n \"claude-code\",\n \"pi-coding-agent\",\n \"agent\",\n \"orchestration\",\n \"cli\"\n ],\n \"homepage\": \"https://github.com/cuongntr/paseo-room#readme\",\n \"bugs\": \"https://github.com/cuongntr/paseo-room/issues\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/cuongntr/paseo-room.git\"\n },\n \"license\": \"MIT\",\n \"author\": \"Invoker <cuongnt1987@gmail.com>\",\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"bin\": {\n \"paseo-room\": \"dist/index.js\"\n },\n \"files\": [\n \"dist/\"\n ],\n \"scripts\": {\n \"typecheck\": \"tsc --noEmit && tsc -p src/runtime-plugin\",\n \"lint\": \"eslint . --max-warnings 0\",\n \"test\": \"vitest run\",\n \"test:package\": \"vitest run --config vitest.package.config.ts\",\n \"build\": \"tsup && node --input-type=module -e \\\"import { cpSync, rmSync } from 'node:fs'; for (const [source, target] of [['src/room/prompts', 'dist/prompts'], ['src/room/skills', 'dist/skills'], ['src/plugin-assets', 'dist/plugin-assets'], ['src/runtime-plugin', 'dist/runtime-plugin']]) { rmSync(target, { recursive: true, force: true }); cpSync(source, target, { recursive: true }); }\\\"\",\n \"prepack\": \"npm run build\",\n \"verify\": \"npm run typecheck && npm run lint && npm test && npm run build && npm run test:package\",\n \"attention:eval\": \"node --experimental-transform-types --no-warnings --import ./scripts/ts-resolve.mjs scripts/attention-eval.ts\"\n },\n \"dependencies\": {\n \"@clack/prompts\": \"^1.8.0\",\n \"@getpaseo/client\": \"0.9.1\",\n \"commander\": \"^14.0.3\",\n \"semver\": \"^7.8.5\",\n \"smol-toml\": \"^1.8.0\",\n \"zod\": \"^4.5.4\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^10.0.1\",\n \"@getpaseo/plugin\": \"0.9.1\",\n \"@getpaseo/protocol\": \"0.9.1\",\n \"@types/node\": \"^22.0.0\",\n \"@types/react\": \"19.2.2\",\n \"@types/semver\": \"^7.7.0\",\n \"eslint\": \"^10.10.0\",\n \"react\": \"19.1.0\",\n \"react-native\": \"0.81.5\",\n \"tsup\": \"^8.5.1\",\n \"typescript\": \"~5.9.3\",\n \"typescript-eslint\": \"^8.70.0\",\n \"vitest\": \"^4.1.11\"\n }\n}\n","export type Status = 'pass' | 'warn' | 'fail';\nexport interface Check {\n readonly id: string;\n readonly status: Status;\n readonly message: string;\n readonly fix?: string;\n}\nexport interface Operation {\n readonly action: 'create' | 'update' | 'remove' | 'noop';\n readonly kind: 'dir' | 'file' | 'link' | 'provider' | 'profile' | 'plugin';\n readonly target: string;\n}\nexport type Outcome = 'ok' | 'changes-planned' | 'failed';\nexport interface Result {\n readonly command: string;\n readonly outcome: Outcome;\n readonly changed: boolean;\n readonly checks: readonly Check[];\n readonly operations: readonly Operation[];\n}\n\nexport function pass(id: string, message: string): Check {\n return { id, status: 'pass', message };\n}\nexport function warn(id: string, message: string, fix?: string): Check {\n return { id, status: 'warn', message, ...(fix === undefined ? {} : { fix }) };\n}\nexport function fail(id: string, message: string, fix: string): Check {\n return { id, status: 'fail', message, fix };\n}\nexport function failed(command: string, checks: readonly Check[]): Result {\n return { command, outcome: 'failed', changed: false, checks, operations: [] };\n}\nexport function hasFailure(checks: readonly Check[]): boolean {\n return checks.some(check => check.status === 'fail');\n}\nexport function exitCode(result: Result): number {\n return result.outcome === 'failed' || hasFailure(result.checks) ? 1 : 0;\n}\n","import { lstat, readlink } from 'node:fs/promises';\nimport { warn, type Check } from './result.js';\n\nexport type CredentialPathState =\n | { readonly kind: 'missing' }\n | { readonly kind: 'file' }\n | { readonly kind: 'symlink'; readonly target: string }\n | { readonly kind: 'unsafe'; readonly fileType: string };\n\nexport interface CredentialDiagnostic {\n /** Credential paths are diagnostic-only and must never become managed entries. */\n readonly path: string;\n readonly checks: readonly Check[];\n}\n\nfunction fileType(stat: Awaited<ReturnType<typeof lstat>>): string {\n if (stat.isDirectory()) return 'directory';\n if (stat.isSocket()) return 'socket';\n if (stat.isFIFO()) return 'FIFO';\n if (stat.isCharacterDevice()) return 'character device';\n if (stat.isBlockDevice()) return 'block device';\n return 'unsupported file type';\n}\n\n/** Inspect only path metadata. Credential contents and link targets are never followed. */\nexport async function inspectCredentialPath(path: string): Promise<CredentialPathState> {\n let stat;\n try {\n stat = await lstat(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { kind: 'missing' };\n return { kind: 'unsafe', fileType: 'uninspectable path' };\n }\n if (stat.isFile()) return { kind: 'file' };\n if (!stat.isSymbolicLink()) return { kind: 'unsafe', fileType: fileType(stat) };\n try {\n return { kind: 'symlink', target: await readlink(path) };\n } catch {\n return { kind: 'unsafe', fileType: 'unreadable symbolic link' };\n }\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nexport function roleCommand(\n environment: Readonly<Record<string, string>>,\n executable: string,\n args: readonly string[] = [],\n): string {\n const variables = Object.entries(environment).map(([name, value]) => `${name}=${shellQuote(value)}`);\n return [...variables, ...[executable, ...args].map(shellQuote)].join(' ');\n}\n\nexport interface PreservedCredentialInput {\n readonly id: string;\n readonly agent: string;\n readonly role: string;\n readonly path: string;\n readonly state: Exclude<CredentialPathState, { readonly kind: 'missing' }>;\n readonly login: string;\n readonly status?: string;\n}\n\n/** Produce migration diagnostics for an existing path without claiming authentication. */\nexport function preservedCredentialCheck(input: PreservedCredentialInput): Check {\n const status = input.status ? ` Check status with: ${input.status}.` : '';\n if (input.state.kind === 'file') {\n return warn(`${input.id}.diverged-file-preserve`,\n `${input.agent} ${input.role} auth: configured structurally (diverged-file-preserve); a role-owned credential file exists at ${input.path} and is preserved. Token validity and freshness were not checked.`,\n `If authentication fails, close that role and authenticate it again with: ${input.login}.${status}`);\n }\n if (input.state.kind === 'symlink') {\n return warn(`${input.id}.legacy-shared-risk`,\n `${input.agent} ${input.role} auth: legacy-shared-risk; a credential symlink at ${input.path} -> ${input.state.target} is preserved. Its target was not inspected, followed, or changed.`,\n `Close that role. Remove only the legacy link with: rm -- ${shellQuote(input.path)}. Then create role-owned credentials with: ${input.login}.${status}`);\n }\n return warn(`${input.id}.manual-recovery`,\n `${input.agent} ${input.role} auth: diverged-file-preserve/manual-recovery; ${input.path} is a ${input.state.fileType}, not a credential file. It is preserved without inspection.`,\n `Close that role and inspect the path metadata yourself. Move or remove it manually only when safe, then authenticate with: ${input.login}.${status}`);\n}\n\nexport function presentNames(names: ReadonlySet<string>, supported: readonly string[]): string[] {\n return supported.filter(name => names.has(name));\n}\n\nexport function ambientNamesCheck(id: string, agent: string, role: string, names: readonly string[]): Check {\n return warn(`${id}.ambient-auth-unverifiable`,\n `${agent} ${role} auth: ambient auth unverifiable; ${names.join(', ')} ${names.length === 1 ? 'is' : 'are'} present by name in the setup process. paseo-room does not copy credential values into providers, so availability to the Paseo-launched role, token validity, and freshness were not checked.`);\n}\n","import { homedir } from 'node:os';\nimport { join, resolve, sep } from 'node:path';\nimport { fail, type Check } from './result.js';\nimport type { AgentId, Role } from './roles.js';\n\nexport interface Options {\n readonly roomHome?: string;\n readonly codexHome?: string;\n readonly claudeHome?: string;\n readonly piHome?: string;\n readonly codexBin?: string;\n readonly claudeBin?: string;\n readonly piBin?: string;\n readonly paseoBin?: string;\n}\nexport interface Layout {\n readonly home: string;\n readonly roomHome: string;\n readonly paseoHome: string;\n readonly agentHome: Record<AgentId, string>;\n /** Claude keeps legacy default state beside ~/.claude, but custom config state inside it. */\n readonly claudeState: string;\n readonly bin: Record<AgentId | 'paseo', string>;\n /** The PATH executables are looked up on. Resolved here so nothing reaches for process.env. */\n readonly searchPath: string;\n /** Environment names only, for structural auth diagnostics without retaining values. */\n readonly envNames: ReadonlySet<string>;\n}\n\nfunction pick(...candidates: readonly (string | undefined)[]): string {\n for (const candidate of candidates) if (candidate?.trim()) return candidate.trim();\n throw new Error('Could not determine HOME; pass explicit --room-home and --codex-home/--claude-home paths.');\n}\n\n/** Everything is derived from HOME; flags and environment only override defaults. */\nexport function resolveLayout(options: Options = {}, env: NodeJS.ProcessEnv = process.env): Layout {\n const home = pick(env.HOME, homedir());\n const claudeOverride = options.claudeHome?.trim() || env.CLAUDE_CONFIG_DIR?.trim() || undefined;\n const claudeHome = resolve(pick(claudeOverride, join(home, '.claude')));\n // Relative overrides resolve against the working directory, as a CLI flag should.\n return {\n home,\n roomHome: resolve(pick(options.roomHome, env.PASEO_ROOM_HOME, join(home, '.paseo-room'))),\n paseoHome: resolve(pick(env.PASEO_HOME, join(home, '.paseo'))),\n agentHome: {\n codex: resolve(pick(options.codexHome, env.CODEX_HOME, join(home, '.codex'))),\n claude: claudeHome,\n pi: resolve(pick(options.piHome, env.PI_CODING_AGENT_DIR, join(home, '.pi', 'agent'))),\n },\n claudeState: claudeOverride?.trim() ? join(claudeHome, '.claude.json') : join(home, '.claude.json'),\n bin: {\n codex: pick(options.codexBin, env.CODEX_BIN, 'codex'),\n claude: pick(options.claudeBin, env.CLAUDE_BIN, 'claude'),\n pi: pick(options.piBin, env.PI_BIN, 'pi'),\n paseo: pick(options.paseoBin, env.PASEO_BIN, 'paseo'),\n },\n searchPath: env.PATH ?? '',\n envNames: new Set(Object.keys(env)),\n };\n}\n\n/** True when `path` is the root itself or sits underneath it. */\nexport function contains(root: string, path: string): boolean {\n return path === root || path.startsWith(root.endsWith(sep) ? root : root + sep);\n}\n\n/** The room home must own its directory: no overlap with $HOME or a source agent home. */\nexport function layoutChecks(layout: Layout, agents: readonly AgentId[]): Check[] {\n const checks: Check[] = [];\n if (contains(layout.roomHome, layout.home)) {\n checks.push(fail('room.home', `Refusing to use ${layout.roomHome} as the room home: it contains your home directory.`,\n 'Point --room-home at a dedicated directory, by default ~/.paseo-room.'));\n }\n for (const id of agents) {\n const home = layout.agentHome[id];\n if (contains(layout.roomHome, home) || contains(home, layout.roomHome)) {\n checks.push(fail(`${id}.home`, `The ${id} home ${home} overlaps the room home ${layout.roomHome}.`,\n `Pass --${id}-home pointing at your own ${id} configuration (this happens when setup runs inside a room seat).`));\n }\n }\n return checks;\n}\n\nexport function roleHome(layout: Layout, agent: AgentId, role: Role): string {\n return join(layout.roomHome, 'roles', agent, role);\n}\nexport function sharedRoom(layout: Layout): string {\n return join(layout.roomHome, 'room');\n}\n","import { randomBytes } from 'node:crypto';\nimport { chmod, lstat, mkdir, readdir, readFile, readlink, rename, rm, symlink, unlink, writeFile } from 'node:fs/promises';\nimport type { Stats } from 'node:fs';\nimport { basename, dirname, join } from 'node:path';\nimport type { Operation } from './result.js';\n\n/** A directory the room creates but whose children it does not own. */\nexport interface DirEntry { readonly kind: 'dir'; readonly path: string }\n/** `once` writes the file only when absent: runtime state the agent owns after setup. */\nexport interface FileEntry { readonly kind: 'file'; readonly path: string; readonly content: string; readonly once?: true }\nexport interface LinkEntry { readonly kind: 'link'; readonly path: string; readonly target: string }\n/**\n * A managed path this room declares must not exist, so suppressing generated content\n * removes the stale file instead of leaving an older generation behind. Like every other\n * managed entry it only ever replaces the shape it writes: a regular file. Anything else\n * is refused rather than deleted.\n */\nexport interface AbsentEntry { readonly kind: 'absent'; readonly path: string }\n/**\n * A directory whose whole child inventory the room owns: names outside `children`\n * are removed so a generated projection cannot go stale. Ownership is declared here\n * and never inferred from an ordinary `dir`, so it stays limited to generated\n * projections such as Peer `skills` — never role homes or credential-bearing paths.\n */\nexport interface ManagedDirEntry {\n readonly kind: 'managed-dir';\n readonly path: string;\n readonly children: readonly string[];\n /** The single legacy shape this path may be migrated from: a symlink to this target. */\n readonly legacyLink?: string;\n /**\n * Names inside this directory the room neither writes nor reconciles, because the agent's\n * own runtime owns them. Without this, exact ownership would treat the agent's state as a\n * stale child and try to delete what it did not generate.\n */\n readonly reserved?: readonly string[];\n}\nexport type Entry = DirEntry | FileEntry | LinkEntry | ManagedDirEntry | AbsentEntry;\n\nconst DIR_MODE = 0o700;\nconst FILE_MODE = 0o600;\n\n/**\n * An existing path is not the shape the room manages, so replacing it would destroy\n * something this CLI does not own. Raised before any deletion.\n */\nexport class ManagedPathError extends Error {\n readonly path: string;\n readonly fix: string;\n constructor(path: string, message: string, fix: string) {\n super(message);\n this.name = 'ManagedPathError';\n this.path = path;\n this.fix = fix;\n }\n}\n\nconst MOVE_ASIDE = 'Check that path for role-owned credentials, move it aside manually, then run setup again.';\n\nfunction shape(stat: Stats): string {\n if (stat.isSymbolicLink()) return 'a symbolic link';\n if (stat.isDirectory()) return 'a directory';\n if (stat.isFile()) return 'a regular file';\n return 'a special file';\n}\n\nfunction refuse(path: string, expected: string, stat: Stats): never {\n throw new ManagedPathError(path, `Refusing to replace ${path}: expected ${expected} but found ${shape(stat)}.`, MOVE_ASIDE);\n}\n\nfunction isMissing(error: unknown): boolean {\n return error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT';\n}\n\nasync function lstatOrAbsent(path: string): Promise<Stats | undefined> {\n try { return await lstat(path); } catch (error) {\n if (isMissing(error)) return undefined;\n throw error;\n }\n}\n\n/** Names present under a managed directory that its declaration does not claim. */\nasync function staleChildren(entry: ManagedDirEntry): Promise<string[]> {\n const declared = new Set([...entry.children, ...entry.reserved ?? []]);\n let names: string[];\n try { names = await readdir(entry.path); } catch (error) {\n if (isMissing(error)) return [];\n throw error;\n }\n return names.filter(name => !declared.has(name));\n}\n\nasync function current(entry: Entry): Promise<'absent' | 'same' | 'different'> {\n const stat = await lstatOrAbsent(entry.path);\n // A declared-absent path is already correct when nothing is there.\n if (entry.kind === 'absent') return stat ? 'different' : 'same';\n if (!stat) return 'absent';\n if (entry.kind === 'dir') return stat.isDirectory() ? 'same' : 'different';\n if (entry.kind === 'managed-dir') {\n if (!stat.isDirectory()) return 'different';\n return (await staleChildren(entry)).length === 0 ? 'same' : 'different';\n }\n if (entry.kind === 'link') {\n if (!stat.isSymbolicLink()) return 'different';\n return await readlink(entry.path) === entry.target ? 'same' : 'different';\n }\n if (!stat.isFile()) return 'different';\n if (entry.once) return 'same';\n return await readFile(entry.path, 'utf8') === entry.content ? 'same' : 'different';\n}\n\n/** Everything lives under the room home, which this CLI owns outright. */\nexport async function planEntries(entries: readonly Entry[]): Promise<Operation[]> {\n const operations: Operation[] = [];\n for (const entry of entries) {\n const state = await current(entry);\n operations.push({\n action: state === 'same' ? 'noop' : entry.kind === 'absent' ? 'remove' : state === 'absent' ? 'create' : 'update',\n // A managed directory is still a directory to everything that reports operations.\n kind: entry.kind === 'managed-dir' ? 'dir' : entry.kind === 'absent' ? 'file' : entry.kind,\n target: entry.path,\n });\n }\n return operations;\n}\n\n/** Unique so two runs, or a leftover from a failed one, can never collide. */\nfunction tempSibling(path: string): string {\n return join(dirname(path), `.${basename(path)}.paseo-room-${randomBytes(8).toString('hex')}`);\n}\n\n/** A managed file or link may replace only an absent path or the same shape. */\nasync function assertReplaceable(entry: FileEntry | LinkEntry): Promise<void> {\n const stat = await lstatOrAbsent(entry.path);\n if (!stat) return;\n if (entry.kind === 'link') {\n if (!stat.isSymbolicLink()) refuse(entry.path, 'a symbolic link', stat);\n return;\n }\n if (!stat.isFile()) refuse(entry.path, 'a regular file', stat);\n}\n\n/** Build beside the target and rename, so a reader never sees a half-written path. */\nasync function replaceAtomically(entry: FileEntry | LinkEntry): Promise<void> {\n const temp = tempSibling(entry.path);\n try {\n if (entry.kind === 'link') await symlink(entry.target, temp);\n else {\n await writeFile(temp, entry.content, { mode: FILE_MODE });\n await chmod(temp, FILE_MODE);\n }\n await rename(temp, entry.path);\n } catch (error) {\n await rm(temp, { force: true });\n throw error;\n }\n}\n\nasync function applyDirectory(path: string): Promise<void> {\n const stat = await lstatOrAbsent(path);\n if (stat && !stat.isDirectory()) refuse(path, 'a directory', stat);\n await mkdir(path, { recursive: true, mode: DIR_MODE });\n}\n\n/**\n * Creates the projection, migrating the one declared legacy symlink by unlinking the\n * link alone, and removes only undeclared children that are links or files. An\n * unrecognized shape — including a real child directory — fails instead of being\n * deleted recursively.\n */\nasync function applyManagedDirectory(entry: ManagedDirEntry): Promise<void> {\n const stat = await lstatOrAbsent(entry.path);\n if (stat?.isSymbolicLink() === true) {\n const target = await readlink(entry.path);\n if (entry.legacyLink === undefined || target !== entry.legacyLink) {\n throw new ManagedPathError(entry.path,\n `Refusing to replace ${entry.path}: this room owns that directory, but it is a symbolic link to ${target}.`,\n MOVE_ASIDE);\n }\n // Unlink the alias only; the operator directory it pointed at is never touched.\n await unlink(entry.path);\n await mkdir(entry.path, { recursive: true, mode: DIR_MODE });\n return;\n }\n if (stat && !stat.isDirectory()) refuse(entry.path, 'a directory this room owns', stat);\n await mkdir(entry.path, { recursive: true, mode: DIR_MODE });\n if (!stat) return;\n for (const name of await staleChildren(entry)) {\n const child = join(entry.path, name);\n const childStat = await lstatOrAbsent(child);\n if (!childStat) continue;\n if (!childStat.isFile() && !childStat.isSymbolicLink()) {\n throw new ManagedPathError(child,\n `Refusing to remove ${child}: this room manages ${entry.path} by name, but that stale child is ${shape(childStat)} rather than a generated file or link.`,\n MOVE_ASIDE);\n }\n await rm(child, { force: true });\n }\n}\n\n/**\n * Removes a suppressed managed file. Only a regular file is ever deleted: a directory,\n * link or special file at that path belongs to something this room does not own.\n */\nasync function removeManagedFile(path: string): Promise<void> {\n const stat = await lstatOrAbsent(path);\n if (!stat) return;\n if (!stat.isFile()) refuse(path, 'a regular file this room generated', stat);\n await rm(path, { force: true });\n}\n\n/** Rewrites only what differs, so a repeat run costs stats rather than writes. */\nexport async function applyEntries(entries: readonly Entry[]): Promise<void> {\n for (const entry of entries) {\n if (await current(entry) === 'same') continue;\n if (entry.kind === 'dir') {\n await applyDirectory(entry.path);\n continue;\n }\n if (entry.kind === 'managed-dir') {\n await applyManagedDirectory(entry);\n continue;\n }\n if (entry.kind === 'absent') {\n await removeManagedFile(entry.path);\n continue;\n }\n await mkdir(dirname(entry.path), { recursive: true, mode: DIR_MODE });\n await assertReplaceable(entry);\n await replaceAtomically(entry);\n }\n}\n\nexport async function exists(path: string): Promise<boolean> {\n try { await lstat(path); return true; } catch { return false; }\n}\n\n/** Which of `names` exist under `home`, probed once for all roles that share them. */\nexport async function existingPaths(home: string, names: readonly string[]): Promise<string[]> {\n const paths = names.map(name => join(home, name));\n const present = await Promise.all(paths.map(exists));\n return paths.filter((_, index) => present[index] === true);\n}\n\nexport async function readIfPresent(path: string): Promise<string | undefined> {\n try { return await readFile(path, 'utf8'); } catch { return undefined; }\n}\n","export const ROLES = ['supervisor', 'lead', 'peer'] as const;\nexport type Role = (typeof ROLES)[number];\n\nexport const AGENT_IDS = ['codex', 'claude', 'pi'] as const;\nexport type AgentId = (typeof AGENT_IDS)[number];\n\n/** Supervisor and Lead orchestrate; Peer executes one brief and gets no room tools. */\nexport const ROLE_PASEO_TOOLS: Record<Role, boolean> = { supervisor: true, lead: true, peer: false };\n\n/**\n * Whether a role may be given the opt-in runtime coordinator's assignment-scoped reporting\n * pair, `ask` and `handoff`. This is deliberately not `ROLE_PASEO_TOOLS`: that field is Paseo's\n * native room-tool policy and stays off for Peer, because reporting one's own assignment is not\n * room access. Supervisor and Lead already report through room tools, so only Peer needs it.\n *\n * The flag authorizes nothing by itself. The CLI never writes a reporting server, and no\n * generated provider changes shape from this constant; an installed runtime plugin is the only\n * thing that can act on it, and only for the exact provider it manages. Keeping the two\n * policies separate is the point: a reader can see that granting a report did not grant a\n * control plane, and `verify` still fails if Peer's `paseoTools.enabled` ever flips.\n */\nexport const ROLE_PEER_REPORTING: Record<Role, boolean> = { supervisor: false, lead: false, peer: true };\n\n/**\n * Reasoning effort a seat starts at: Supervisor routes, Lead judges, Peer implements.\n * Deliberately short of the top option on either agent — `ultra` and `ultracode`\n * advertise automatic task delegation, which is a second control plane.\n */\nexport const ROLE_THINKING: Record<Role, string> = { supervisor: 'low', lead: 'high', peer: 'high' };\n\n/**\n * The top option on either agent, which Paseo advertises as maximum reasoning with automatic\n * task delegation. Whether it can still delegate once the room has closed the native\n * multi-agent paths is unverified, so selecting one is reported and never rejected.\n */\nexport const DELEGATING_THINKING = ['ultra', 'ultracode'] as const;\n\n/** Paseo profile appearance encodes the room role, independent of agent runtime. */\nexport const ROLE_ICON: Record<Role, string> = { supervisor: 'eye', lead: 'compass', peer: 'code' };\nexport const ROLE_COLOR: Record<Role, string> = { supervisor: 'violet', lead: 'blue', peer: 'emerald' };\n\n/** Paseo shows these to orchestrating agents, so each one says who may open the seat. */\nexport const ROLE_NOTES: Record<Role, string> = {\n supervisor: 'Human-facing routing seat. Opened by Human, never by another agent; cwd, title and provider label do not prove room membership.',\n lead: 'Sole project technical owner. When opening, copy every present profile launch field. Otherwise reuse only with exact current room Lead provider/mode/workspace evidence plus corroborated ownership. Cwd, title and provider label are not membership. Creates Peer seats only.',\n peer: 'One fresh Lead brief. Open by copying every present profile launch field; require exact current room Peer provider/mode/workspace and paseo.parent-agent-id for its Lead. Cwd, title and provider label are not membership; no orchestration.',\n};\n\nexport function providerId(agent: AgentId, role: Role): string {\n return `${agent}-${role}`;\n}\n/** Distinct from the provider id: a host may already have a profile by that name. */\nexport function profileId(agent: AgentId, role: Role): string {\n return `room-${agent}-${role}`;\n}\nexport function providerLabel(agent: AgentId, role: Role): string {\n const title = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1);\n return `${title(agent)} ${title(role)}`;\n}\n","import { join } from 'node:path';\nimport { z } from 'zod';\nimport { readIfPresent } from './fsops.js';\nimport type { Layout } from './layout.js';\nimport { AGENT_IDS, ROLES, type AgentId, type Role } from './roles.js';\n\nexport const MARKER = 'room.json';\n\nconst markerSchema = z.object({\n version: z.string(),\n agents: z.array(z.enum(AGENT_IDS)).min(1),\n roles: z.array(z.enum(ROLES)).min(1),\n /**\n * The rendered contract generation this room was installed from. Optional because a room\n * written before contract provenance existed has no digest, and such a marker must still\n * parse rather than look like a foreign file.\n */\n contract: z.string().min(1).optional(),\n /**\n * False when this room deliberately suppressed the role contract in Claude's `CLAUDE.md`,\n * leaving the plugin as its only Claude carrier. Optional and defaulted to true so a room\n * written before the option existed keeps parsing and keeps its current behaviour.\n */\n claudeMemoryContract: z.boolean().optional(),\n /**\n * Present only when this room opted in to runtime coordination. Missing means disabled, so a\n * marker written before runtime existed keeps parsing and keeps its behaviour.\n */\n runtime: z.strictObject({ enabled: z.literal(true), generation: z.string().min(1), schema: z.literal(1) }).optional(),\n});\nexport type Marker = z.infer<typeof markerSchema>;\nexport type RuntimeMarker = NonNullable<Marker['runtime']>;\n\n/** Deterministic on purpose: re-running setup must not show a phantom change. */\nexport function renderMarker(\n version: string,\n agents: readonly AgentId[],\n roles: readonly Role[],\n contract?: string,\n claudeMemoryContract?: boolean,\n runtime?: RuntimeMarker,\n): string {\n return JSON.stringify({\n version, agents: [...agents], roles: [...roles],\n ...(contract === undefined ? {} : { contract }),\n // Written only when it differs from the default, so an unchanged room's marker is unchanged.\n ...(claudeMemoryContract === false ? { claudeMemoryContract: false } : {}),\n ...(runtime === undefined ? {} : { runtime }),\n } satisfies Marker, null, 2) + '\\n';\n}\n\n/** Records what setup created, so verify and remove touch nothing else. */\nexport async function readMarker(layout: Layout): Promise<Marker | undefined> {\n const source = await readIfPresent(join(layout.roomHome, MARKER));\n if (source === undefined) return undefined;\n try { return markerSchema.parse(JSON.parse(source)); } catch { return undefined; }\n}\n","import { execFile } from 'node:child_process';\nimport { access, constants } from 'node:fs/promises';\nimport { delimiter, isAbsolute, join, resolve } from 'node:path';\nimport { promisify } from 'node:util';\n\nconst run = promisify(execFile);\n\n/**\n * Resolve a command to an absolute executable path on `searchPath`.\n *\n * Deliberately not canonicalised. Version managers point a stable name at a\n * versioned file — `~/.local/bin/claude` at `versions/2.1.267`, mise's\n * `node/latest` at `node/24.15.0` — and the resolved target is deleted by the\n * next upgrade. Providers store this path, so following the link would pin every\n * seat to a binary that stops existing.\n */\nexport async function which(command: string, searchPath: string): Promise<string | undefined> {\n const candidates = isAbsolute(command) || command.includes('/')\n ? [resolve(command)]\n : searchPath.split(delimiter).filter(Boolean).map(entry => join(entry, command));\n for (const candidate of candidates) {\n try {\n await access(candidate, constants.X_OK);\n return candidate;\n } catch { /* try the next PATH entry */ }\n }\n return undefined;\n}\n\nexport interface CommandOutput {\n readonly ok: boolean;\n readonly stdout: string;\n}\n/** Bounded, shell-free probe. Failures are reported, never thrown. */\nexport async function probe(executable: string, args: readonly string[], env: NodeJS.ProcessEnv): Promise<CommandOutput> {\n try {\n const { stdout } = await run(executable, [...args], { env, timeout: 20_000, maxBuffer: 16 * 1024 * 1024, encoding: 'utf8' });\n return { ok: true, stdout };\n } catch {\n return { ok: false, stdout: '' };\n }\n}\n","import { spawn } from 'node:child_process';\nimport { constants } from 'node:os';\nimport { join } from 'node:path';\nimport { lstat } from 'node:fs/promises';\nimport { roleCommand } from './credentials.js';\nimport { resolveLayout, roleHome, type Options } from './layout.js';\nimport { MARKER, readMarker } from './room.js';\nimport { AGENT_IDS, ROLES, type AgentId, type Role } from './roles.js';\nimport { which } from './which.js';\n\nexport const AUTHENTICATION_GUIDE = 'AUTHENTICATION.md';\n/** A truthy empty override suppresses Pi's role-home APPEND_SYSTEM.md discovery. */\nexport const PI_AUTH_ARGV = ['--no-extensions', '--no-approve', '--append-system-prompt', ''] as const;\n\n/** A copy-paste-safe Pi login command that cannot inherit the caller repository cwd. */\nexport function piLoginCommand(rolePath: string, binary: string): string {\n const command = roleCommand({ PI_CODING_AGENT_DIR: rolePath }, binary, PI_AUTH_ARGV);\n return `cd ${roleCommand({}, rolePath)} && ${command}`;\n}\n\nexport interface LoginOutput {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport interface LoginSpawnOptions {\n readonly env: NodeJS.ProcessEnv;\n readonly cwd?: string;\n readonly shell: false;\n readonly stdio: 'inherit';\n}\n\nexport interface LoginChild {\n once(event: 'error', listener: (error: Error) => void): this;\n once(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;\n}\n\nexport type LoginSpawner = (executable: string, argv: readonly string[], options: LoginSpawnOptions) => LoginChild;\n\nconst spawnLogin: LoginSpawner = (executable, argv, options) => spawn(executable, [...argv], options);\n\nfunction title(value: string): string {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\n\nfunction loginInvocation(agent: AgentId, rolePath: string, binary: string): {\n readonly env: Readonly<Record<string, string>>;\n readonly argv: readonly string[];\n readonly cwd?: string;\n readonly command: string;\n} {\n if (agent === 'codex') {\n const env = { CODEX_HOME: rolePath };\n const argv = ['login'] as const;\n return { env, argv, command: roleCommand(env, binary, argv) };\n }\n if (agent === 'claude') {\n const env = { CLAUDE_CONFIG_DIR: rolePath, CLAUDE_SECURESTORAGE_CONFIG_DIR: rolePath };\n const argv = ['auth', 'login'] as const;\n return { env, argv, command: roleCommand(env, binary, argv) };\n }\n const env = { PI_CODING_AGENT_DIR: rolePath };\n const argv = PI_AUTH_ARGV;\n return { env, argv, cwd: rolePath, command: piLoginCommand(rolePath, binary) };\n}\n\n/** Deterministic, secret-free instructions using setup's resolved executables. */\nexport function renderAuthenticationGuide(\n roomHome: string,\n binaries: Readonly<Partial<Record<AgentId, string>>>,\n agents: readonly AgentId[],\n roles: readonly Role[],\n): string {\n const lines = [\n '# Role authentication',\n '',\n 'Setup and verify do not validate authentication, inspect credential contents, query keyrings,',\n 'or test token freshness. Run the command for each role you want to authenticate.',\n '',\n ];\n for (const agent of agents) {\n const binary = binaries[agent];\n if (!binary) throw new Error(`Cannot render authentication guidance without the resolved ${agent} executable.`);\n lines.push(`## ${agent === 'claude' ? 'Claude Code' : title(agent)}`, '');\n for (const role of roles) {\n const invocation = loginInvocation(agent, join(roomHome, 'roles', agent, role), binary);\n lines.push(`### ${title(role)}`, '', '```sh', invocation.command, '```', '');\n if (agent === 'pi') {\n lines.push('Run `/login`, then exit Pi when authentication completes. This minimal interactive',\n 'login session starts in the role home, not the caller repository, disables extension discovery and',\n 'approval files, and suppresses role-home APPEND_SYSTEM.md discovery;',\n 'it is not equivalent to launching the room seat through Paseo.', '');\n }\n }\n }\n return `${lines.join('\\n').trimEnd()}\\n`;\n}\n\nasync function realDirectory(path: string): Promise<'directory' | 'missing' | 'unsafe'> {\n try {\n return (await lstat(path)).isDirectory() ? 'directory' : 'unsafe';\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'ENOENT' ? 'missing' : 'unsafe';\n }\n}\n\nfunction usageError(output: LoginOutput, detail: string): number {\n output.stderr(`paseo-room auth login: ${detail}\\n`);\n return 2;\n}\n\nexport interface LoginOptions extends Options {\n readonly env?: NodeJS.ProcessEnv;\n readonly isTTY: boolean;\n readonly spawn?: LoginSpawner;\n}\n\n/** Launch one vendor's normal interactive login without touching credential stores itself. */\nexport async function loginRole(\n agentValue: string,\n roleValue: string,\n options: LoginOptions,\n output: LoginOutput,\n): Promise<number> {\n const agent = AGENT_IDS.find(value => value === agentValue);\n if (!agent) return usageError(output, `unknown agent \"${agentValue}\"; expected codex, claude, or pi.`);\n const role = ROLES.find(value => value === roleValue);\n if (!role) return usageError(output, `unknown role \"${roleValue}\"; expected supervisor, lead, or peer.`);\n if (!options.isTTY) {\n output.stderr('paseo-room auth login requires interactive stdin, stdout, and stderr terminals.\\n');\n return 1;\n }\n\n const env = options.env ?? process.env;\n const layout = resolveLayout(options, env);\n if (await realDirectory(layout.roomHome) !== 'directory') {\n output.stderr(`No room found at ${layout.roomHome}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n try {\n if (!(await lstat(join(layout.roomHome, MARKER))).isFile()) throw new Error('not a regular marker');\n } catch {\n output.stderr(`No valid room marker found at ${join(layout.roomHome, MARKER)}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n const marker = await readMarker(layout);\n if (!marker) {\n output.stderr(`No valid room marker found at ${join(layout.roomHome, MARKER)}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n if (!marker.agents.includes(agent)) {\n output.stderr(`${title(agent)} is not selected in this room. Re-run setup with --agent ${agent} --apply.\\n`);\n return 1;\n }\n if (!marker.roles.includes(role)) {\n output.stderr(`${title(role)} is not installed for ${agent} in this room. Re-run setup --apply.\\n`);\n return 1;\n }\n const rolePath = roleHome(layout, agent, role);\n for (const path of [join(layout.roomHome, 'roles'), join(layout.roomHome, 'roles', agent), rolePath]) {\n if (await realDirectory(path) !== 'directory') {\n output.stderr(`The selected ${agent} ${role} role is not safely installed at ${rolePath}. Run: paseo-room setup --apply\\n`);\n return 1;\n }\n }\n\n const binary = await which(layout.bin[agent], layout.searchPath);\n if (!binary) {\n output.stderr(`${title(agent)} executable not found. Install it, or pass --${agent}-bin /path/to/${agent}.\\n`);\n return 1;\n }\n const invocation = loginInvocation(agent, rolePath, binary);\n if (agent === 'pi') {\n output.stdout(`Starting a minimal interactive Pi login session for ${role} in its role home. Run /login, then exit Pi when authentication completes.\\n`);\n output.stdout('Extensions and approval files are disabled, and role APPEND_SYSTEM.md discovery is suppressed.\\n');\n output.stdout('This is not a room-equivalent Paseo launch.\\n');\n } else {\n output.stdout(`Starting ${agent === 'claude' ? 'Claude Code' : 'Codex'} login for ${role}.\\n`);\n }\n\n const childEnv = { ...env, ...invocation.env };\n const launch = options.spawn ?? spawnLogin;\n return new Promise(resolve => {\n let settled = false;\n const finish = (code: number): void => {\n if (settled) return;\n settled = true;\n resolve(code);\n };\n let child: LoginChild;\n try {\n child = launch(binary, invocation.argv, {\n env: childEnv,\n ...(invocation.cwd === undefined ? {} : { cwd: invocation.cwd }),\n shell: false,\n stdio: 'inherit',\n });\n } catch (error) {\n const detail = error instanceof Error ? error.message : 'unknown error';\n output.stderr(`Could not start ${agent} login: ${detail}\\n`);\n finish(1);\n return;\n }\n child.once('error', error => {\n output.stderr(`Could not start ${agent} login: ${error.message}\\n`);\n finish(1);\n });\n child.once('close', (code, signal) => {\n if (code !== null) {\n finish(code);\n return;\n }\n if (signal) {\n const signalNumber = constants.signals[signal];\n const mapped = typeof signalNumber === 'number' ? 128 + signalNumber : 1;\n output.stderr(`${title(agent)} login ended from signal ${signal}; returning ${String(mapped)}.\\n`);\n finish(mapped);\n return;\n }\n output.stderr(`${title(agent)} login ended without an exit code or signal.\\n`);\n finish(1);\n });\n });\n}\n","import { readFileSync } from 'node:fs';\n\nexport const PROMPT_ASSETS = {\n documents: {\n supervisor: { path: 'documents/supervisor.md', kind: 'head' },\n lead: { path: 'documents/lead.md', kind: 'head' },\n peer: { path: 'documents/peer.md', kind: 'head' },\n },\n contract: {\n sharedAuthority: { path: 'contract/shared-authority.md', kind: 'body' },\n sharedSeatIdentity: { path: 'contract/shared-seat-identity.md', kind: 'section' },\n challengeSignals: { path: 'contract/challenge-signals.md', kind: 'section' },\n supervisor: { path: 'contract/supervisor.md', kind: 'body' },\n lead: { path: 'contract/lead.md', kind: 'body' },\n peer: { path: 'contract/peer.md', kind: 'body' },\n },\n pi: {\n communicationStyle: { path: 'pi/communication-style.md', kind: 'capsule' },\n runtime: { path: 'pi/runtime.md', kind: 'capsule' },\n },\n} as const;\n\nexport type PromptAssetGroup = keyof typeof PROMPT_ASSETS;\nexport type PromptAssetKey<Group extends PromptAssetGroup> = keyof (typeof PROMPT_ASSETS)[Group];\nexport type ContractKey = PromptAssetKey<'contract'>;\nexport type DocumentKey = PromptAssetKey<'documents'>;\nexport type PiPromptKey = PromptAssetKey<'pi'>;\n\ntype PromptAssetKind = 'head' | 'section' | 'body' | 'capsule';\ninterface PromptAssetDefinition {\n readonly path: string;\n readonly kind: PromptAssetKind;\n}\n\nexport class PromptAssetError extends Error {\n readonly logicalAsset: string;\n readonly assetUrl: URL;\n\n constructor(logicalAsset: string, assetUrl: URL, detail: string, options?: ErrorOptions) {\n super(`Prompt asset ${logicalAsset} at ${assetUrl.pathname} ${detail} Reinstall paseo-room and try again.`, options);\n this.name = 'PromptAssetError';\n this.logicalAsset = logicalAsset;\n this.assetUrl = assetUrl;\n }\n}\n\nconst cache = new Map<string, string>();\n\nfunction definition<Group extends PromptAssetGroup>(\n group: Group,\n key: PromptAssetKey<Group>,\n): PromptAssetDefinition {\n const assets = PROMPT_ASSETS[group] as Readonly<Record<string, PromptAssetDefinition>>;\n const asset = assets[String(key)];\n if (asset === undefined) throw new Error(`Unknown prompt asset ${group}.${String(key)}.`);\n return asset;\n}\n\nfunction headingCount(source: string, level: 1 | 2): number {\n const prefix = level === 1 ? '# ' : '## ';\n return source.split('\\n').filter(line => line.startsWith(prefix)).length;\n}\n\nfunction validateHeadOrCapsule(source: string, kind: 'head' | 'capsule'): string {\n const trimmed = source.trimEnd();\n if (!trimmed.trim()) throw new Error('is empty.');\n const firstLine = trimmed.split('\\n', 1)[0] ?? '';\n if (!/^# \\S.*$/.test(firstLine) || headingCount(trimmed, 1) !== 1) {\n throw new Error(`${kind === 'head' ? 'document head' : 'Pi capsule'} must begin with exactly one H1 heading.`);\n }\n return trimmed;\n}\n\n/**\n * Renders one H2 section: the heading verbatim, then each blank-line-delimited statement\n * collapsed onto a single bullet, so authoring line wrapping never reaches a model.\n */\nfunction renderSection(heading: string, bodyLines: readonly string[]): string {\n if (bodyLines.some(line => /^#{1,6}\\s/.test(line))) {\n throw new Error('section must not contain additional Markdown headings.');\n }\n const body = bodyLines.join('\\n').trim();\n if (!body) throw new Error('section must contain at least one non-empty statement.');\n const statements = body.split(/\\n\\s*\\n/).map(statement =>\n statement.split('\\n').map(line => line.trim()).join(' '),\n );\n if (statements.some(statement => !statement)) {\n throw new Error('section must contain only non-empty statements.');\n }\n return `${heading}\\n${statements.map(statement => `- ${statement}`).join('\\n')}`;\n}\n\nfunction validateSection(source: string): string {\n const trimmed = source.trimEnd();\n if (!trimmed.trim()) throw new Error('is empty.');\n const lines = trimmed.split('\\n');\n const heading = lines.shift() ?? '';\n if (!/^## \\S.*$/.test(heading) || headingCount(trimmed, 2) !== 1) {\n throw new Error('section must begin with exactly one H2 heading.');\n }\n return renderSection(heading, lines);\n}\n\ninterface SplitSections {\n readonly preface: readonly string[];\n readonly sections: readonly { readonly heading: string; readonly lines: readonly string[] }[];\n}\n\n/** Splits a multi-section asset at its H2 headings, keeping anything before the first one. */\nfunction splitSections(lines: readonly string[]): SplitSections {\n const preface: string[] = [];\n const sections: { heading: string; lines: string[] }[] = [];\n for (const line of lines) {\n if (/^## \\S.*$/.test(line)) {\n sections.push({ heading: line, lines: [] });\n continue;\n }\n const current = sections.at(-1);\n if (current === undefined) preface.push(line);\n else current.lines.push(line);\n }\n return { preface, sections };\n}\n\n/** A role body: one or more H2 sections and nothing above the first of them. */\nfunction validateBody(source: string): string {\n const trimmed = source.trimEnd();\n if (!trimmed.trim()) throw new Error('is empty.');\n const { preface, sections } = splitSections(trimmed.split('\\n'));\n if (sections.length === 0) throw new Error('role body must contain at least one H2 section.');\n if (preface.some(line => line.trim())) {\n throw new Error('role body must not contain content above its first H2 heading.');\n }\n return sections.map(section => renderSection(section.heading, section.lines)).join('\\n\\n');\n}\n\nexport function loadPromptAsset<Group extends PromptAssetGroup>(\n group: Group,\n key: PromptAssetKey<Group>,\n): string {\n const logicalAsset = `${group}.${String(key)}`;\n const cached = cache.get(logicalAsset);\n if (cached !== undefined) return cached;\n\n const asset = definition(group, key);\n const assetUrl = new URL(`./prompts/${asset.path}`, import.meta.url);\n try {\n const source = readFileSync(assetUrl, 'utf8');\n if (source.includes('\\uFFFD')) throw new Error('is not valid UTF-8 text.');\n const validated = validate(source, asset.kind);\n cache.set(logicalAsset, validated);\n return validated;\n } catch (error) {\n if (error instanceof PromptAssetError) throw error;\n const detail = error instanceof Error ? error.message : 'could not be read.';\n throw new PromptAssetError(logicalAsset, assetUrl, detail, { cause: error });\n }\n}\n\nfunction validate(source: string, kind: PromptAssetKind): string {\n switch (kind) {\n case 'section': return validateSection(source);\n case 'body': return validateBody(source);\n default: return validateHeadOrCapsule(source, kind);\n }\n}\n","import { createHash } from 'node:crypto';\nimport { ROLES, type Role } from '../roles.js';\nimport { loadPromptAsset, type ContractKey } from './prompts.js';\n\nexport type InstructionKind = Role;\n\n// Every role carries the same authority floor. The layers above it reach only the seats they\n// belong to: room-seat identity evidence reaches the two seats that open seats, and the\n// challenge vocabulary reaches the two seats that use it. Broadcasting either one is the\n// attention cost the model exists to avoid.\nconst SHARED_KEYS = {\n supervisor: ['sharedAuthority', 'sharedSeatIdentity'],\n lead: ['sharedAuthority', 'sharedSeatIdentity', 'challengeSignals'],\n peer: ['sharedAuthority', 'challengeSignals'],\n} as const satisfies Record<Role, readonly ContractKey[]>;\n\n// Exactly one role body per role: the body is the review unit, so the composition cannot\n// silently drop or duplicate a role's own obligations.\nconst ROLE_KEYS = {\n supervisor: 'supervisor',\n lead: 'lead',\n peer: 'peer',\n} as const satisfies Record<Role, ContractKey>;\n\nexport function instructionKeys(role: Role): readonly ContractKey[] {\n return [...SHARED_KEYS[role], ROLE_KEYS[role]];\n}\n\n/**\n * The room composes role documents only. Repository workflow policy is a repository's own\n * optional root `WORKSPACE_PROTOCOL.md`: the room ships no default copy of it, so nothing\n * here can inject a second, hidden workflow document into a seat.\n */\nexport function renderInstructions(kind: InstructionKind): string {\n return [\n loadPromptAsset('documents', kind),\n ...instructionKeys(kind).map(key => loadPromptAsset('contract', key)),\n ].join('\\n\\n') + '\\n';\n}\n\n/** Every document the room composes, in one fixed order, so a digest over them is stable. */\nexport const INSTRUCTION_KINDS = [...ROLES] as const satisfies readonly InstructionKind[];\n\n/**\n * Identifies the rendered contract generation a room was installed from.\n *\n * Derived from the composed documents rather than the package version: two packages that\n * render identical contracts are the same generation, and editing one prompt asset without a\n * release still changes the digest. Truncated because this is provenance an operator compares\n * by eye, not a security claim.\n */\nexport function contractDigest(): string {\n const hash = createHash('sha256');\n for (const kind of INSTRUCTION_KINDS) hash.update(`${kind}\\u0000${renderInstructions(kind)}\\u0000`);\n return `sha256:${hash.digest('hex').slice(0, 16)}`;\n}\n","import { fail, type Check } from '../result.js';\n\n/**\n * The bounded heuristic: `paseo` as a whole identifier or path token, including a\n * lower-to-upper camel-case boundary. It is not embedded in a larger word, so `paseo`,\n * `paseo-mcp`, `/opt/paseo/bin/serve` and `paseoRoom` match while `grapaseo`,\n * `paseonaut` and `PASEONAUT` do not.\n *\n * This recognizes an obvious configuration collision and says why it matched. It is not a\n * scanner for a hostile or obfuscated endpoint, and matching nothing proves nothing.\n */\nconst PASEO_TOKEN = /(?<![\\p{L}\\p{N}])[Pp][Aa][Ss][Ee][Oo](?=$|[^\\p{L}\\p{N}]|\\p{Lu}\\p{Ll})/u;\n\n/** Declaration fields that name what a server runs or connects to. */\nconst VALUE_FIELDS = ['command', 'url', 'serverUrl', 'httpUrl', 'endpoint'] as const;\n/** Declaration fields that carry a list of such values. */\nconst LIST_FIELDS = ['args'] as const;\n\n/** One recognizable declaration, kept so the diagnostic can state its own evidence. */\nexport interface McpMatch {\n readonly server: string;\n /** `name`, or the declaration field that carried the token. */\n readonly field: 'name' | (typeof VALUE_FIELDS)[number] | (typeof LIST_FIELDS)[number];\n readonly value: string;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** An MCP declaration map exactly as an already-parsed config carries it. */\nexport function serverTable(value: unknown): Record<string, unknown> {\n return asRecord(value) ?? {};\n}\n\n/** Names one side declares and the other does not, in both directions. */\nexport interface NameDivergence {\n /** Declared for the operator but absent from the compared side. */\n readonly missing: readonly string[];\n /** Declared by the compared side but no longer by the operator. */\n readonly extra: readonly string[];\n}\n\n/**\n * Compare two declaration maps by server name alone. Used for seed-once runtime state the\n * room must not synchronize: a name difference is reportable, and nothing about what those\n * servers run is compared, copied, or written back.\n */\nexport function serverNameDivergence(\n operator: Readonly<Record<string, unknown>>,\n compared: Readonly<Record<string, unknown>>,\n): NameDivergence | undefined {\n const operatorNames = new Set(Object.keys(operator));\n const comparedNames = new Set(Object.keys(compared));\n const missing = [...operatorNames].filter(name => !comparedNames.has(name)).sort();\n const extra = [...comparedNames].filter(name => !operatorNames.has(name)).sort();\n return missing.length === 0 && extra.length === 0 ? undefined : { missing, extra };\n}\n\n/**\n * The declaration maps inside a JSON configuration file, read through the named keys only:\n * nothing else in the document — history, credentials, runtime state — is inspected.\n *\n * Every named key is merged, in the order given, because an agent that accepts more than one\n * key loads all of them: stopping at the first table would let a benign one hide a Paseo\n * declaration under a later key. A name declared twice keeps the earlier key's entry at its\n * own name and the later one under a key-qualified name, so no declaration is lost. Invalid\n * JSON, a non-object root, or a named declaration value that is not an object is rejected:\n * an unparseable source cannot truthfully be reported as inspected and clean.\n */\nexport function jsonServerTable(source: string | undefined, keys: readonly string[]): Record<string, unknown> {\n if (source === undefined) return {};\n const root = asRecord(JSON.parse(source));\n if (!root) throw new TypeError('MCP configuration must be a JSON object.');\n const merged: Record<string, unknown> = {};\n for (const key of keys) {\n const value = root[key];\n if (value === undefined) continue;\n const table = asRecord(value);\n if (!table) throw new TypeError(`${key} must be a JSON object.`);\n for (const [server, declaration] of Object.entries(table)) {\n merged[server in merged ? `${server} (${key})` : server] = declaration;\n }\n }\n return merged;\n}\n\n/** Every recognizably Paseo-related declaration, with the evidence that recognized it. */\nexport function detectPaseoServers(servers: Readonly<Record<string, unknown>>): McpMatch[] {\n const matches: McpMatch[] = [];\n for (const [server, declaration] of Object.entries(servers)) {\n if (PASEO_TOKEN.test(server)) matches.push({ server, field: 'name', value: server });\n const fields = asRecord(declaration);\n if (!fields) continue;\n for (const field of VALUE_FIELDS) {\n const value = fields[field];\n if (typeof value === 'string' && PASEO_TOKEN.test(value)) matches.push({ server, field, value });\n }\n for (const field of LIST_FIELDS) {\n const list = fields[field];\n if (!Array.isArray(list)) continue;\n for (const item of list) {\n if (typeof item === 'string' && PASEO_TOKEN.test(item)) matches.push({ server, field, value: item });\n }\n }\n }\n return matches;\n}\n\nfunction evidence(match: McpMatch): string {\n return match.field === 'name' ? `${match.server} (server name)` : `${match.server} (${match.field}: ${match.value})`;\n}\n\n/**\n * Paseo is the room's only control plane, so a Peer-visible MCP server that looks like a\n * second one fails before anything is applied. The room never edits operator configuration:\n * the fix names the source file and leaves the decision with the operator.\n */\nexport function paseoMcpCheck(id: string, path: string, servers: Readonly<Record<string, unknown>>): Check | undefined {\n const matches = detectPaseoServers(servers);\n if (matches.length === 0) return undefined;\n return fail(id,\n `${path} declares MCP servers that are recognizably Paseo-related: ${matches.map(evidence).join('; ')}.`,\n `Remove or rename those servers in ${path} so no room seat reaches Paseo outside its own seat, then run setup again. paseo-room never edits your MCP configuration, and this name check is a bounded heuristic rather than a sandbox.`);\n}\n","import { readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { Entry } from '../fsops.js';\nimport type { Role } from '../roles.js';\n\n/** The one operator resource the room projects child by child rather than aliasing. */\nexport const SKILLS = 'skills';\n\n/** An orchestration skill: advertised to seats that orchestrate, never to Peer. */\nfunction isPaseoSkill(name: string): boolean {\n return name.toLowerCase().startsWith('paseo');\n}\n\n/**\n * Peer has no room tools, so the room also stops loading orchestration surfaces into it.\n * This closes known configuration paths — Peer still has a shell, so it is not containment.\n */\nfunction receivesExecutableResources(role: Role): boolean {\n return role !== 'peer';\n}\n\n/**\n * The room-owned skill reaches the one seat that owns a repository's workflow policy. Peer\n * reads one brief, and Supervisor holds no standing protocol mandate, so neither receives it.\n */\nfunction receivesRoomSkill(role: Role): boolean {\n return role === 'lead';\n}\n\n/** Names under the operator skills directory; a missing directory is an empty projection. */\nasync function skillNames(\n path: string,\n reserved: ReadonlySet<string>,\n keep: (name: string) => boolean,\n): Promise<string[]> {\n try {\n return (await readdir(path)).filter(name => keep(name) && !reserved.has(name.toLowerCase())).sort();\n } catch (error) {\n if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return [];\n throw error;\n }\n}\n\nexport interface RoomSkill {\n /** The child name inside the projected `skills` directory. */\n readonly name: string;\n /** The shared room-owned source each Lead aggregate links to; declared once. */\n readonly source: string;\n}\n\nexport interface RoleResourceInput {\n readonly role: Role;\n /** The role home every generated alias is created inside. */\n readonly target: string;\n /** The operator agent home the shared resources are read from. */\n readonly home: string;\n /** Shared resource basenames in the adapter's declared order, present or not. */\n readonly names: readonly string[];\n /** Absolute operator paths that exist, probed once for every role. */\n readonly shared: readonly string[];\n /** Basenames whose contents can run code, withheld from Peer. */\n readonly executable: readonly string[];\n /**\n * Names inside the projected `skills` directory that the agent's own runtime writes and\n * owns. A case-insensitive operator-name match is not linked, and the declared runtime name is\n * not reconciled: the agent creates its own copy inside the role home, so projecting one would\n * alias runtime state and reconciling one would delete it.\n */\n readonly reservedSkills?: readonly string[];\n /** The room-owned skill; required so an adapter cannot silently leave Lead without it. */\n readonly roomSkill: RoomSkill;\n /** Lead's room-owned aggregate; required even for calls whose current role does not consume it. */\n readonly leadSkillProjection: string;\n}\n\n/**\n * The projected `skills` directory for a role the room owns by exact child inventory, or\n * `undefined` for a role that keeps the whole-directory alias.\n *\n * Peer receives the non-`paseo*` operator skills and no room-owned skill. Lead receives every\n * operator skill plus the room-owned one; a name that collides with it case-insensitively is not\n * linked, because the room-owned copy owns that name inside the Lead aggregate while the\n * operator's own skill stays where it is, untouched. Case-insensitive comparison keeps the\n * projection valid on the default macOS filesystem as well as on case-sensitive filesystems.\n *\n * The projection is declared even when the operator deleted the whole skills directory: an\n * empty managed directory is what lets a later run remove yesterday's child links. Peer's\n * role-home directory also migrates the legacy whole-directory symlink. Lead instead keeps a\n * symlink at that legacy path and projects children into a room-owned aggregate, so an older\n * package can replace the same symlink shape during rollback.\n */\nasync function skillsProjection(\n input: RoleResourceInput,\n path: string,\n alias: string,\n present: ReadonlySet<string>,\n reserved: ReadonlySet<string>,\n): Promise<Entry[] | undefined> {\n const roomSkill = receivesRoomSkill(input.role) ? input.roomSkill : undefined;\n const projectsChildren = !receivesExecutableResources(input.role) || roomSkill !== undefined;\n if (!projectsChildren) return undefined;\n const reservedNames = new Set([...reserved].map(name => name.toLowerCase()));\n const keep = roomSkill === undefined\n ? (name: string): boolean => !isPaseoSkill(name)\n : (name: string): boolean => name.toLowerCase() !== roomSkill.name.toLowerCase();\n const operator = present.has(path) ? await skillNames(path, reservedNames, keep) : [];\n const children = roomSkill === undefined ? operator : [...operator, roomSkill.name];\n const projection = input.role === 'lead' ? input.leadSkillProjection : alias;\n return [\n {\n kind: 'managed-dir', path: projection, children,\n ...(input.role === 'peer' ? { legacyLink: path } : {}),\n ...(reserved.size === 0 ? {} : { reserved: [...reserved] }),\n },\n ...operator.map(child => ({ kind: 'link' as const, path: join(projection, child), target: join(path, child) })),\n ...(roomSkill === undefined\n ? []\n : [{ kind: 'link' as const, path: join(projection, roomSkill.name), target: roomSkill.source }]),\n ...(input.role === 'lead' ? [{ kind: 'link' as const, path: alias, target: projection }] : []),\n ];\n}\n\n/**\n * Supervisor keeps one alias per shared operator resource that exists, so it never gains a\n * broken link. Lead keeps those aliases too, except its `skills` alias points to an exact\n * room-owned aggregate so the room skill can join the operator's own without writing into the\n * operator home. Peer receives no executable resource, and its `skills` is an exact projection\n * of the non-`paseo*` operator skills.\n *\n * A name the agent's own runtime owns inside a projected directory is reserved rather than\n * projected: the room neither aliases it nor counts it stale, so the agent's state survives.\n */\nexport async function roleResourceEntries(input: RoleResourceInput): Promise<Entry[]> {\n const present = new Set(input.shared);\n const executable = new Set(input.executable);\n const reserved = new Set(input.reservedSkills ?? []);\n const entries: Entry[] = [];\n for (const name of input.names) {\n const path = join(input.home, name);\n const alias = join(input.target, name);\n if (name === SKILLS) {\n const projection = await skillsProjection(input, path, alias, present, reserved);\n if (projection !== undefined) {\n entries.push(...projection);\n continue;\n }\n }\n if (!receivesExecutableResources(input.role) && executable.has(name)) continue;\n if (!present.has(path)) continue;\n entries.push({ kind: 'link', path: alias, target: path });\n }\n return entries;\n}\n","import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Entry } from '../fsops.js';\nimport type { Layout } from '../layout.js';\nimport { sharedRoom } from '../layout.js';\nimport type { AgentId } from '../roles.js';\n\n/**\n * The one room-owned Agent Skill. The name is also the child name inside a Lead role home, so\n * an operator skill of the same name is not linked there: the room-owned copy owns that name\n * inside the room, and the operator's own directory is never touched.\n */\nexport const ROOM_SKILL_NAME = 'paseo-project-onboarding';\n\n/**\n * The skill's exact shape: directories the room creates and files it writes, and nothing else.\n * Ownership is declared here rather than inferred from a recursive copy, so a stray file in the\n * package cannot become a managed path.\n */\nconst SKILL_DIRECTORIES = ['references'] as const;\nconst SKILL_FILES = ['SKILL.md', 'references/workspace-protocol-template.md'] as const;\n\nexport class SkillAssetError extends Error {\n readonly logicalAsset: string;\n readonly assetUrl: URL;\n\n constructor(logicalAsset: string, assetUrl: URL, detail: string, options?: ErrorOptions) {\n super(`Skill asset ${logicalAsset} at ${assetUrl.pathname} ${detail} Reinstall paseo-room and try again.`, options);\n this.name = 'SkillAssetError';\n this.logicalAsset = logicalAsset;\n this.assetUrl = assetUrl;\n }\n}\n\nconst cache = new Map<string, string>();\n\nfunction validateSkillAsset(path: string, source: string): string {\n if (source.includes('\\uFFFD')) throw new Error('is not valid UTF-8 text.');\n if (!source.trim()) throw new Error('is empty.');\n if (path === 'SKILL.md') {\n const frontmatter = /^---\\n([\\s\\S]*?)\\n---\\n/.exec(source)?.[1];\n if (frontmatter === undefined) throw new Error('must begin with YAML frontmatter.');\n const declaredName = /^name: (.+)$/m.exec(frontmatter)?.[1];\n if (declaredName !== ROOM_SKILL_NAME) {\n throw new Error(`frontmatter name must be ${ROOM_SKILL_NAME}.`);\n }\n if (!/^description: \\S.+$/m.test(frontmatter)) {\n throw new Error('frontmatter must contain a non-empty single-line description.');\n }\n }\n if (path === 'references/workspace-protocol-template.md'\n && !source.startsWith('# Workspace protocol template (scaffold)\\n')) {\n throw new Error('must begin with the workspace protocol scaffold heading.');\n }\n return source;\n}\n\nfunction loadSkillAsset(path: string): string {\n const cached = cache.get(path);\n if (cached !== undefined) return cached;\n const logicalAsset = `${ROOM_SKILL_NAME}/${path}`;\n const assetUrl = new URL(`./skills/${ROOM_SKILL_NAME}/${path}`, import.meta.url);\n try {\n const validated = validateSkillAsset(path, readFileSync(assetUrl, 'utf8'));\n cache.set(path, validated);\n return validated;\n } catch (error) {\n if (error instanceof SkillAssetError) throw error;\n const detail = error instanceof Error ? error.message : 'could not be read.';\n throw new SkillAssetError(logicalAsset, assetUrl, detail, { cause: error });\n }\n}\n\n/** Where every Lead projection's room-owned skill link points: one shared source copy. */\nexport function roomSkillSource(layout: Layout): string {\n return join(sharedRoom(layout), 'skills', ROOM_SKILL_NAME);\n}\n\n/** Parent of every per-agent room-owned skill projection. */\nexport function skillProjectionRoot(layout: Layout): string {\n return join(sharedRoom(layout), 'skill-projections');\n}\n\n/** Parent of one agent's room-owned skill projections. */\nexport function agentSkillProjectionRoot(layout: Layout, agent: AgentId): string {\n return join(skillProjectionRoot(layout), agent);\n}\n\n/** A room-owned aggregate that lets the role path remain a rollback-compatible symlink. */\nexport function leadSkillProjection(layout: Layout, agent: AgentId): string {\n return join(agentSkillProjectionRoot(layout, agent), 'lead');\n}\n\n/**\n * The shared skill source, by exact file and directory shape. Added once from the command that\n * builds the desired state rather than per adapter, so three seated agents do not declare the\n * same managed paths three times.\n */\nexport function roomSkillEntries(layout: Layout, agents: readonly AgentId[]): Entry[] {\n const root = roomSkillSource(layout);\n return [\n { kind: 'dir', path: join(sharedRoom(layout), 'skills') },\n { kind: 'dir', path: skillProjectionRoot(layout) },\n ...agents.map(agent => ({ kind: 'dir' as const, path: agentSkillProjectionRoot(layout, agent) })),\n { kind: 'managed-dir', path: root, children: ['SKILL.md', ...SKILL_DIRECTORIES] },\n {\n kind: 'managed-dir', path: join(root, 'references'),\n children: SKILL_FILES.filter(path => path.startsWith('references/')).map(path => path.slice('references/'.length)),\n },\n ...SKILL_FILES.map(path => ({\n kind: 'file' as const, path: join(root, path), content: loadSkillAsset(path),\n })),\n ];\n}\n","import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport {\n ambientNamesCheck, inspectCredentialPath, presentNames, preservedCredentialCheck,\n roleCommand, type CredentialDiagnostic,\n} from '../credentials.js';\nimport type { Layout } from '../layout.js';\nimport { roleHome } from '../layout.js';\nimport type { Entry } from '../fsops.js';\nimport { existingPaths, exists, readIfPresent } from '../fsops.js';\nimport { fail, pass, warn, type Check } from '../result.js';\nimport type { Role } from '../roles.js';\nimport { renderInstructions } from '../room/instructions.js';\nimport { which } from '../which.js';\nimport { jsonServerTable, paseoMcpCheck, serverNameDivergence, type NameDivergence } from './mcp.js';\nimport { roleResourceEntries } from './resources.js';\nimport { leadSkillProjection, ROOM_SKILL_NAME, roomSkillSource } from '../room/skills.js';\nimport type { Agent, AgentPlan, BuildOptions } from './types.js';\n\n/** Operator-authored resources shared by reference; native agent definitions stay out. */\nconst SHARED = [\n 'skills', 'plugins', 'commands', 'hooks', 'rules',\n 'output-styles', 'keybindings.json', 'themes',\n] as const;\n/** These carry executable prompts, plugin code, and hook programs: never shared with Peer. */\nconst EXECUTABLE = ['plugins', 'commands', 'hooks'] as const;\n/**\n * Claude's own runtime writes its downloaded skill bucket here, inside whichever home it runs\n * with. It is agent state rather than an operator-authored skill, so the room leaves the name\n * alone in both directions: it is never projected and never reconciled as stale.\n */\nconst RUNTIME_SKILLS = ['synced'] as const;\n/** Claude keeps personal MCP declarations under this one key of its runtime state. */\nconst MCP_KEY = 'mcpServers';\nconst AUTH_ENV = [\n 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN',\n 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY',\n] as const;\nconst CONTROL_PLANE_ENV = {\n CLAUDE_CODE_DISABLE_AGENT_VIEW: '1',\n CLAUDE_CODE_DISABLE_WORKFLOWS: '1',\n} as const;\n/** One native-orchestration deny list, emitted into both Claude and Paseo enforcement surfaces. */\nconst DISALLOWED_TOOLS = [\n 'Task', 'Agent', 'Workflow', 'ListAgents', 'SendMessage', 'TeamCreate', 'TeamDelete',\n 'TaskCreate', 'TaskGet', 'TaskList', 'TaskUpdate',\n 'CronCreate', 'CronDelete', 'CronList',\n] as const;\nconst SECURE_STORAGE_ENV = 'CLAUDE_SECURESTORAGE_CONFIG_DIR';\n/** Copied once so a fresh role home does not re-run interactive onboarding. */\nconst SEEDED_KEYS = ['hasCompletedOnboarding', 'theme', 'installMethod', 'userID', MCP_KEY] as const;\n\nfunction asObject(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};\n}\n\n/** Any unreadable or non-object source is simply an empty starting point. */\nfunction readObject(source: string | undefined): Record<string, unknown> {\n try { return asObject(source === undefined ? {} : JSON.parse(source)); } catch { return {}; }\n}\n\n/** Read optional runtime state, but do not turn an inspection failure into \"no servers\". */\nasync function readStateIfPresent(path: string): Promise<string | undefined> {\n try { return await readFile(path, 'utf8'); } catch (error) {\n if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return undefined;\n throw error;\n }\n}\n\n/** Render only room-owned policy; operator settings are intentionally not imported. */\nexport function renderRoleSettings(role: Role, secureStorageDir?: string): string {\n const settings = {\n // Claude applies settings.env after the launch environment, so repeat provider closures here.\n env: {\n ...CONTROL_PLANE_ENV,\n PASEO_ROOM_ROLE: role,\n ...(secureStorageDir === undefined ? {} : { [SECURE_STORAGE_ENV]: secureStorageDir }),\n },\n // Provider disallowedTools is not sufficient alone; the isolated home carries the same list.\n permissions: { deny: DISALLOWED_TOOLS },\n // These restrictive settings cannot be weakened by another settings scope.\n disableAgentView: true,\n disableWorkflows: true,\n crossSessionInbound: 'refuse',\n };\n return JSON.stringify(settings, null, 2) + '\\n';\n}\n\nexport function renderRoleState(source: string | undefined): string {\n const root = readObject(source);\n const state: Record<string, unknown> = { hasCompletedOnboarding: true };\n for (const key of SEEDED_KEYS) if (key in root) state[key] = root[key];\n return JSON.stringify(state, null, 2) + '\\n';\n}\n\n/**\n * Preserve the operator's global memory, then add the stronger room role contract.\n *\n * With the contract suppressed, the file carries the operator's memory alone: the plugin is\n * then the room's only Claude contract carrier. Returning `undefined` for an operator with no\n * global memory keeps the room from writing a file whose whole content it just removed.\n */\nexport function renderRoleMemory(source: string | undefined, role: Role, contract = true): string | undefined {\n const operator = source?.trim();\n if (!contract) return operator ? `${operator}\\n` : undefined;\n return operator ? `${operator}\\n\\n${renderInstructions(role)}` : renderInstructions(role);\n}\n\nexport async function claudeCredentialDiagnostic(\n layout: Layout,\n role: Role,\n platform: NodeJS.Platform = process.platform,\n binary = 'claude',\n): Promise<CredentialDiagnostic> {\n const home = roleHome(layout, 'claude', role);\n const path = join(home, '.credentials.json');\n const roleEnvironment = { CLAUDE_CONFIG_DIR: home, [SECURE_STORAGE_ENV]: home };\n const login = roleCommand(roleEnvironment, binary, ['auth', 'login']);\n const status = roleCommand(roleEnvironment, binary, ['auth', 'status']);\n const state = await inspectCredentialPath(path);\n const id = `claude.auth.${role}`;\n if (state.kind !== 'missing') {\n return { path, checks: [preservedCredentialCheck({ id, agent: 'Claude', role, path, state, login, status })] };\n }\n const ambient = presentNames(layout.envNames, AUTH_ENV);\n if (ambient.length > 0) return { path, checks: [ambientNamesCheck(id, 'Claude', role, ambient)] };\n if (platform === 'darwin') {\n return { path, checks: [{\n id: `${id}.native-keyring-unverifiable`, status: 'warn',\n message: `Claude ${role} auth: native-keyring unverifiable; the current runtime's secure-storage location is pinned to this role home, but no Keychain entry was queried and older runtime behavior was not assumed. Token validity and freshness were not checked.`,\n fix: `Authenticate this role with: ${login}. If that subcommand is unavailable, launch ${roleCommand(roleEnvironment, binary)} and run /login. Check status with: ${status}.`,\n }] };\n }\n return { path, checks: [{\n id: `${id}.login-required`, status: 'warn',\n message: `Claude ${role} auth: login-required; no role-owned .credentials.json or supported ambient auth environment name was detected. Authentication was not attempted.`,\n fix: `Authenticate this role with: ${login}. If that subcommand is unavailable, launch ${roleCommand(roleEnvironment, binary)} and run /login. Check status with: ${status}.`,\n }] };\n}\n\n/**\n * `.claude.json` is seeded once and runtime-owned afterwards, so a later change to the\n * operator's own MCP inventory never reaches a role home. That is reported rather than\n * repaired: rewriting the file would discard whatever the runtime has since stored in it.\n * Only declared names are compared — no command, URL, argument, credential or history value\n * is read for this check.\n */\nfunction mcpDriftCheck(role: Role, home: string, path: string, divergence: NameDivergence): Check {\n const parts = [\n ...(divergence.missing.length === 0 ? [] : [`not declared for this role: ${divergence.missing.join(', ')}`]),\n ...(divergence.extra.length === 0 ? [] : [`declared only for this role: ${divergence.extra.join(', ')}`]),\n ];\n return warn(`claude.mcp.drift.${role}`,\n `Claude ${role} MCP server names differ from your own Claude MCP servers (${parts.join('; ')}). ${path} is seeded once and owned by Claude afterwards, so paseo-room did not change it; only server names were compared.`,\n `If this role should have the same servers, add them with: CLAUDE_CONFIG_DIR=${home} claude mcp add ... — or delete ${path} and run setup --apply to reseed it from your current Claude state, which discards that role's other runtime state.`);\n}\n\nexport const claudeAgent: Agent = {\n id: 'claude',\n label: 'Claude Code',\n homeEnv: 'CLAUDE_CONFIG_DIR',\n // Agent View and dynamic workflows have entry points beyond model tool calls.\n providerEnv: CONTROL_PLANE_ENV,\n defaultModeId: 'bypassPermissions',\n // Keep the legacy Task name and block current native orchestration,\n // shared task/cron coordination, and cross-session paths. Paseo alone owns\n // agent lifecycle and coordination.\n pins: { disallowedTools: DISALLOWED_TOOLS },\n async build(layout: Layout, roles: readonly Role[], options: BuildOptions = {}): Promise<AgentPlan> {\n const home = layout.agentHome.claude;\n const binary = await which(layout.bin.claude, layout.searchPath);\n if (!binary) {\n return { entries: [], checks: [fail('claude.bin', 'Claude Code executable not found.', 'Install Claude Code, or pass --claude-bin /path/to/claude.')] };\n }\n if (!(await exists(home))) {\n return { entries: [], checks: [fail('claude.home', `No Claude config directory at ${home}.`, 'Run claude once to initialise it, or pass --claude-home.')] };\n }\n const checks: Check[] = [pass('claude.home', `Claude Code found at ${binary} using ${home}.`)];\n\n const memorySource = await readIfPresent(join(home, 'CLAUDE.md'));\n let stateSource: string | undefined;\n let operatorServers: Record<string, unknown>;\n try {\n stateSource = await readStateIfPresent(layout.claudeState);\n // `.claude.json` is runtime-owned after the seed write, so only this one key is interpreted.\n operatorServers = jsonServerTable(stateSource, [MCP_KEY]);\n } catch {\n return { entries: [], checks: [...checks, fail('claude.mcp',\n `Could not read ${layout.claudeState} as a JSON object, so its MCP declarations could not be inspected.`,\n 'Make your Claude state file readable and fix its JSON structure, then run setup again.')] };\n }\n const stateConflict = paseoMcpCheck('claude.mcp', layout.claudeState, operatorServers);\n if (stateConflict) return { entries: [], checks: [...checks, stateConflict] };\n const shared = await existingPaths(home, SHARED);\n const entries: Entry[] = [];\n const credentials: CredentialDiagnostic[] = [];\n const providerEnv: Partial<Record<Role, Readonly<Record<string, string>>>> = {};\n // Held back so a hard conflict found in a later role is never preceded by advice.\n const drift: Check[] = [];\n const roomSkill = { name: ROOM_SKILL_NAME, source: roomSkillSource(layout) };\n for (const role of roles) {\n const target = roleHome(layout, 'claude', role);\n const statePath = join(target, '.claude.json');\n // A seeded role home keeps its own copy, so its declarations are checked as well.\n let roleStateSource: string | undefined;\n let roleServers: Record<string, unknown>;\n try {\n roleStateSource = await readStateIfPresent(statePath);\n roleServers = jsonServerTable(roleStateSource, [MCP_KEY]);\n } catch {\n return { entries: [], checks: [...checks, fail(`claude.mcp.${role}`,\n `Could not read ${statePath} as a JSON object, so its MCP declarations could not be inspected.`,\n 'Make that role-owned Claude state file readable and fix its JSON structure, then run setup again.')] };\n }\n const roleConflict = paseoMcpCheck(`claude.mcp.${role}`, statePath, roleServers);\n if (roleConflict) return { entries: [], checks: [...checks, roleConflict] };\n // Only an already-seeded role home can have drifted: an absent one is about to be\n // seeded from the same operator state this run just read.\n if (roleStateSource !== undefined) {\n const divergence = serverNameDivergence(operatorServers, roleServers);\n if (divergence) drift.push(mcpDriftCheck(role, target, statePath, divergence));\n }\n entries.push({ kind: 'dir', path: target });\n const memoryPath = join(target, 'CLAUDE.md');\n const memory = renderRoleMemory(memorySource, role, options.memoryContract ?? true);\n // Suppressed with no operator memory to carry: remove any file an earlier run wrote,\n // so a stale contract generation cannot outlive the option that turned it off.\n entries.push(memory === undefined\n ? { kind: 'absent', path: memoryPath }\n : { kind: 'file', path: memoryPath, content: memory });\n entries.push({ kind: 'file', path: join(target, 'settings.json'), content: renderRoleSettings(role, target) });\n entries.push({ kind: 'file', path: statePath, content: renderRoleState(stateSource), once: true });\n entries.push(...await roleResourceEntries({\n role, target, home, names: SHARED, shared, executable: EXECUTABLE,\n reservedSkills: RUNTIME_SKILLS, roomSkill,\n leadSkillProjection: leadSkillProjection(layout, 'claude'),\n }));\n credentials.push(await claudeCredentialDiagnostic(layout, role, process.platform, binary));\n providerEnv[role] = { [SECURE_STORAGE_ENV]: target };\n }\n return { entries, credentials, checks: [...checks, ...drift], binary, providerEnv };\n },\n};\n","import { join } from 'node:path';\nimport { parse, stringify, type TomlTable } from 'smol-toml';\nimport { inspectCredentialPath, preservedCredentialCheck, roleCommand, type CredentialDiagnostic } from '../credentials.js';\nimport type { Layout } from '../layout.js';\nimport { roleHome } from '../layout.js';\nimport type { Entry } from '../fsops.js';\nimport { existingPaths, readIfPresent } from '../fsops.js';\nimport { fail, pass, type Check } from '../result.js';\nimport type { Role } from '../roles.js';\nimport { renderInstructions } from '../room/instructions.js';\nimport { probe, which } from '../which.js';\nimport { paseoMcpCheck, serverTable } from './mcp.js';\nimport { roleResourceEntries } from './resources.js';\nimport { leadSkillProjection, ROOM_SKILL_NAME, roomSkillSource } from '../room/skills.js';\nimport type { Agent, AgentPlan } from './types.js';\n\n/** Read-only operator resources every role shares by reference, never by copy. */\nconst SHARED = ['AGENTS.md', 'skills', 'plugins', 'hooks.json'] as const;\n/** Plugins and hooks run operator code, so Peer — which has no room tools — never loads them. */\nconst EXECUTABLE = ['plugins', 'hooks.json'] as const;\nconst CATALOG = 'model-catalog.json';\nexport type CodexCredentialStore = 'file' | 'ephemeral' | 'auto' | 'keyring' | 'unknown';\n\nfunction table(parent: TomlTable, key: string): TomlTable {\n const value = parent[key];\n if (value === undefined || typeof value !== 'object' || Array.isArray(value) || value instanceof Date) {\n return (parent[key] = {});\n }\n return value;\n}\n\n/**\n * Close Codex's native multi-agent features inside one scope: the top-level table, or an\n * active profile, which outranks it.\n */\nfunction pinMultiAgentFeatures(scope: TomlTable): void {\n const features = table(scope, 'features');\n features.multi_agent = false;\n // Newer configs represent v2 as a table; keep that shape rather than writing a\n // boolean at the same key, which would be a TOML conflict.\n if (typeof features.multi_agent_v2 === 'boolean' || features.multi_agent_v2 === undefined) features.multi_agent_v2 = false;\n else table(features, 'multi_agent_v2').enabled = false;\n}\n\nexport interface RoleConfigInput {\n readonly roleDocument: string;\n readonly catalogPath?: string;\n}\n/**\n * Copy the operator's config, then override only the keys the room owns.\n *\n * `model_instructions_file` is deliberately untouched: it *replaces* Codex's base\n * prompt, so writing it would mean vendoring and maintaining a full copy of that\n * prompt. The room contract is additive and belongs in `developer_instructions`.\n */\nexport function renderRoleConfig(source: TomlTable, input: RoleConfigInput): string {\n const config = structuredClone(source);\n config.sandbox_mode = 'danger-full-access';\n config.approval_policy = 'never';\n config.developer_instructions = input.roleDocument;\n if (input.catalogPath) config.model_catalog_json = input.catalogPath;\n // Codex's own multi-agent mode would compete with the room's role contract.\n // `[agents]` stays top-level only: Codex profiles have no such key.\n table(config, 'agents').enabled = false;\n pinMultiAgentFeatures(config);\n // An active profile outranks the top-level keys, so every room-owned key a profile can\n // also carry — sandbox, approval, catalog, features — has to land there too.\n if (typeof config.profile === 'string') {\n const profile = table(table(config, 'profiles'), config.profile);\n profile.sandbox_mode = 'danger-full-access';\n profile.approval_policy = 'never';\n if (input.catalogPath) profile.model_catalog_json = input.catalogPath;\n pinMultiAgentFeatures(profile);\n }\n return stringify(config) + '\\n';\n}\n\nexport function renderCatalog(catalog: unknown): string {\n return JSON.stringify(catalog, (key, value: unknown) => (key === 'multi_agent_version' ? null : value), 2) + '\\n';\n}\n\n/** Facts the captured catalog itself carries. Nothing is inferred beyond them. */\nexport interface CatalogEvidence {\n /** Codex reads the catalog as a JSON object, so any other top-level shape is not one. */\n readonly object: boolean;\n /** How many `multi_agent_version` fields the capture carried, and the copy therefore nulls. */\n readonly markers: number;\n}\n\nexport function catalogEvidence(catalog: unknown): CatalogEvidence {\n let markers = 0;\n const walk = (value: unknown): void => {\n if (Array.isArray(value)) { for (const item of value) walk(item); return; }\n if (value === null || typeof value !== 'object') return;\n for (const [key, nested] of Object.entries(value)) {\n if (key === 'multi_agent_version') markers += 1;\n else walk(nested);\n }\n };\n walk(catalog);\n return { object: catalog !== null && typeof catalog === 'object' && !Array.isArray(catalog), markers };\n}\n\n/** Read only the generated config's non-secret store selector. */\nexport function codexCredentialStore(config: TomlTable): CodexCredentialStore {\n const value = config.cli_auth_credentials_store;\n return value === 'file' || value === 'ephemeral' || value === 'auto' || value === 'keyring'\n ? value\n : 'unknown';\n}\n\nasync function credentialDiagnostic(\n layout: Layout,\n role: Role,\n store: CodexCredentialStore,\n binary: string,\n): Promise<CredentialDiagnostic> {\n const home = roleHome(layout, 'codex', role);\n const path = join(home, 'auth.json');\n const login = roleCommand({ CODEX_HOME: home }, binary, ['login']);\n const status = roleCommand({ CODEX_HOME: home }, binary, ['login', 'status']);\n const state = await inspectCredentialPath(path);\n const id = `codex.auth.${role}`;\n const checks: Check[] = [];\n if (state.kind !== 'missing') {\n checks.push(preservedCredentialCheck({ id, agent: 'Codex', role, path, state, login, status }));\n } else {\n if (store === 'keyring' || store === 'auto') {\n checks.push({\n id: `${id}.native-keyring-unverifiable`, status: 'warn',\n message: `Codex ${role} auth: native-keyring unverifiable; cli_auth_credentials_store is ${store}, and no keyring was queried. Token validity and freshness were not checked.`,\n fix: `Authenticate this role with: ${login}. Check status with: ${status}.`,\n });\n } else {\n const apiKey = layout.envNames.has('OPENAI_API_KEY')\n ? ' OPENAI_API_KEY is present only in the setup process; Codex has not stored it for this role and paseo-room does not copy it into the provider.'\n : '';\n const detail = store === 'ephemeral'\n ? 'cli_auth_credentials_store is ephemeral, so no persistent credential file is expected'\n : `no role-owned auth.json exists${store === 'file' ? ' for the configured file store' : ''}`;\n checks.push({\n id: `${id}.login-required`, status: 'warn',\n message: `Codex ${role} auth: login-required; ${detail}.${apiKey} Authentication was not attempted.`,\n fix: `Authenticate this role with: ${login}. Check status with: ${status}.`,\n });\n }\n }\n if (state.kind !== 'missing' && (store === 'keyring' || store === 'auto')) {\n checks.push({\n id: `${id}.native-keyring-unverifiable`, status: 'warn',\n message: `Codex ${role} auth: native-keyring unverifiable; cli_auth_credentials_store is ${store}, and the preserved auth.json does not prove what the runtime will use. No keyring was queried.`,\n fix: `Check status without exposing credentials: ${status}.`,\n });\n }\n return { path, checks };\n}\n\nexport const codexAgent: Agent = {\n id: 'codex',\n label: 'Codex',\n homeEnv: 'CODEX_HOME',\n defaultModeId: 'full-access',\n // Without these, Paseo's own mode preset (default auto-review) is sent to the\n // app-server and outranks the sandbox/approval keys in the generated config.\n pins: { params: { sandbox_mode: 'danger-full-access', approval_policy: 'never' } },\n async build(layout: Layout, roles: readonly Role[]): Promise<AgentPlan> {\n const checks: Check[] = [];\n const home = layout.agentHome.codex;\n const binary = await which(layout.bin.codex, layout.searchPath);\n if (!binary) {\n return { entries: [], checks: [fail('codex.bin', 'Codex executable not found.', 'Install Codex, or pass --codex-bin /path/to/codex.')] };\n }\n const configPath = join(home, 'config.toml');\n const raw = await readIfPresent(configPath);\n if (raw === undefined) {\n return { entries: [], checks: [fail('codex.home', `No config.toml in ${home}.`, 'Run codex once to initialise it, or pass --codex-home.')] };\n }\n let source: TomlTable;\n try { source = parse(raw); } catch {\n return { entries: [], checks: [fail('codex.config', `Could not read ${configPath} as TOML.`, 'Fix the syntax in your Codex config, then run setup again.')] };\n }\n checks.push(pass('codex.home', `Codex found at ${binary} using ${home}.`));\n // Paseo is the room's only control plane, so a Paseo-looking MCP server fails here,\n // before any managed path is written, rather than being filtered out of the copy.\n const conflict = paseoMcpCheck('codex.mcp', configPath, serverTable(source.mcp_servers));\n if (conflict) return { entries: [], checks: [...checks, conflict] };\n const store = codexCredentialStore(source);\n\n const entries: Entry[] = [];\n const credentials: CredentialDiagnostic[] = [];\n\n // The scrubbed catalog is one of the room's three native multi-agent closures, so a\n // catalog it cannot capture is a build failure, not a silent fall back to the\n // built-in catalog and its collaboration metadata.\n const capture = roleCommand({ CODEX_HOME: home }, binary, ['debug', 'models']);\n const models = await probe(binary, ['debug', 'models'], { HOME: layout.home, CODEX_HOME: home, PATH: layout.searchPath });\n if (!models.ok) {\n return { entries: [], checks: [...checks, fail('codex.catalog',\n 'Codex model catalog unavailable, so native multi-agent metadata cannot be removed.',\n `Run ${capture} to see why it failed, upgrade Codex to a version that prints the JSON catalog, then run setup again.`)] };\n }\n let catalogSource: string;\n let evidence: CatalogEvidence;\n try {\n const parsed: unknown = JSON.parse(models.stdout);\n evidence = catalogEvidence(parsed);\n catalogSource = renderCatalog(parsed);\n } catch {\n return { entries: [], checks: [...checks, fail('codex.catalog',\n 'Codex model catalog was not valid JSON, so native multi-agent metadata cannot be removed.',\n `Check the output of ${capture}, upgrade Codex if it does not print a JSON catalog, then run setup again.`)] };\n }\n // A JSON scalar or array parses but is not a catalog: writing it would point every role\n // at a file Codex cannot load, which is the same closure failure as no catalog at all.\n if (!evidence.object) {\n return { entries: [], checks: [...checks, fail('codex.catalog',\n 'Codex printed valid JSON that is not a model catalog object, so native multi-agent metadata cannot be removed.',\n `Check the output of ${capture}, upgrade Codex to a version that prints the JSON catalog object, then run setup again.`)] };\n }\n checks.push(pass('codex.catalog', evidence.markers === 0\n ? `Codex model catalog captured from ${capture}; it declared no multi_agent_version field, and each role home gets that generated copy instead of Codex's built-in catalog.`\n : `Codex model catalog captured from ${capture}; ${String(evidence.markers)} multi_agent_version field(s) are nulled in the generated copy in each role home.`));\n\n const shared = await existingPaths(home, SHARED);\n const roomSkill = { name: ROOM_SKILL_NAME, source: roomSkillSource(layout) };\n for (const role of roles) {\n const target = roleHome(layout, 'codex', role);\n const catalogPath = join(target, CATALOG);\n const roleDocument = renderInstructions(role);\n entries.push({ kind: 'dir', path: target });\n // Codex reads the brief from developer_instructions; this copy is for the operator.\n entries.push({ kind: 'file', path: join(target, 'role-instructions.md'), content: roleDocument });\n entries.push({\n kind: 'file',\n path: join(target, 'config.toml'),\n content: renderRoleConfig(source, { roleDocument, catalogPath }),\n });\n entries.push({ kind: 'file', path: catalogPath, content: catalogSource });\n entries.push(...await roleResourceEntries({\n role, target, home, names: SHARED, shared, executable: EXECUTABLE, roomSkill,\n leadSkillProjection: leadSkillProjection(layout, 'codex'),\n }));\n credentials.push(await credentialDiagnostic(layout, role, store, binary));\n }\n return { entries, credentials, checks, binary };\n },\n};\n","import { spawn } from 'node:child_process';\nimport { mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { isAbsolute, join, resolve } from 'node:path';\nimport {\n ambientNamesCheck, inspectCredentialPath, presentNames, preservedCredentialCheck,\n type CredentialDiagnostic,\n} from '../credentials.js';\nimport { piLoginCommand } from '../auth.js';\nimport type { Entry } from '../fsops.js';\nimport { existingPaths } from '../fsops.js';\nimport type { Layout } from '../layout.js';\nimport { contains, roleHome } from '../layout.js';\nimport { fail, pass, type Check } from '../result.js';\nimport type { Role } from '../roles.js';\nimport { renderInstructions } from '../room/instructions.js';\nimport { loadPromptAsset } from '../room/prompts.js';\nimport { which } from '../which.js';\nimport { jsonServerTable, paseoMcpCheck } from './mcp.js';\nimport { roleResourceEntries } from './resources.js';\nimport { leadSkillProjection, ROOM_SKILL_NAME, roomSkillSource } from '../room/skills.js';\nimport type { Agent, AgentPlan } from './types.js';\n\nconst PACKAGE_NAME = 'pi-mcp-adapter';\nconst PROBE_ID = 'paseo-room-pi-mcp-probe';\nconst PROBE_TIMEOUT_MS = 10_000;\nconst PROBE_OUTPUT_LIMIT = 1024 * 1024;\nconst SHARED = ['models.json', 'AGENTS.md', 'skills', 'prompts', 'themes', 'keybindings.json', 'mcp.json'] as const;\n/** Pi prompts are its slash commands, so they execute; Peer receives no such resource. */\nconst EXECUTABLE = ['prompts'] as const;\nconst MCP_FILE = 'mcp.json';\n/** Pi accepts either key for its declaration map, so both are read and neither is rewritten. */\nconst MCP_KEYS = ['mcpServers', 'servers'] as const;\n/** Built-in provider key names only; ambient cloud credential files are deliberately not probed. */\nconst AUTH_ENV = [\n 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_OAUTH_TOKEN', 'ANTHROPIC_API_KEY',\n 'OPENAI_API_KEY', 'AZURE_OPENAI_API_KEY', 'GEMINI_API_KEY', 'GOOGLE_CLOUD_API_KEY',\n 'MISTRAL_API_KEY', 'GROQ_API_KEY', 'CEREBRAS_API_KEY', 'XAI_API_KEY',\n 'DEEPSEEK_API_KEY', 'OPENROUTER_API_KEY', 'AI_GATEWAY_API_KEY', 'FIREWORKS_API_KEY',\n 'ZAI_API_KEY', 'MINIMAX_API_KEY', 'OPENCODE_API_KEY', 'KIMI_API_KEY',\n 'COPILOT_GITHUB_TOKEN',\n] as const;\n\nfunction asObject(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? { ...value } : undefined;\n}\n\n/** Copy operator preferences but remove every declaration that can install or load packages. */\nexport function renderPiSettings(source: string | undefined): string {\n const parsed: unknown = source === undefined ? {} : JSON.parse(source);\n const settings = asObject(parsed);\n if (!settings) throw new Error('Pi settings must be a JSON object.');\n delete settings.packages;\n delete settings.extensions;\n return JSON.stringify(settings, null, 2) + '\\n';\n}\n\n/** Preserve the operator append first; room-specific guidance is additive and stronger. */\nexport function renderPiAppend(source: string | undefined, role: Role): string {\n return [\n source?.trim(),\n loadPromptAsset('pi', 'communicationStyle'),\n loadPromptAsset('pi', 'runtime'),\n renderInstructions(role),\n ].filter((part): part is string => Boolean(part)).join('\\n\\n');\n}\n\ninterface ResolvedAdapter {\n readonly entry: string;\n readonly version: string;\n}\n\nfunction adapterFailure(home: string, detail: string): Check {\n return fail('pi.adapter', detail,\n `Install ${PACKAGE_NAME} in ${join(home, 'npm')} with Pi yourself, then run setup again.`);\n}\n\n/** Resolve only Pi's intended global package and its single declared extension entry. */\nexport async function resolvePiAdapter(home: string): Promise<{ readonly adapter?: ResolvedAdapter; readonly check: Check }> {\n const packageRoot = join(home, 'npm', 'node_modules', PACKAGE_NAME);\n const manifestPath = join(packageRoot, 'package.json');\n try {\n const [canonicalRoot, manifestStat, raw] = await Promise.all([\n realpath(packageRoot), stat(manifestPath), readFile(manifestPath, 'utf8'),\n ]);\n if (!manifestStat.isFile()) return { check: adapterFailure(home, `${manifestPath} is not a regular file.`) };\n const manifest = asObject(JSON.parse(raw));\n if (!manifest || manifest.name !== PACKAGE_NAME) {\n return { check: adapterFailure(home, `${manifestPath} does not identify ${PACKAGE_NAME}.`) };\n }\n const pi = asObject(manifest.pi);\n const declared = pi?.extensions;\n if (!Array.isArray(declared) || declared.length !== 1 || typeof declared[0] !== 'string' || !declared[0].trim()) {\n return { check: adapterFailure(home, `${manifestPath} must declare one Pi extension entry.`) };\n }\n const declaration = declared[0];\n if (isAbsolute(declaration)) {\n return { check: adapterFailure(home, `${manifestPath} declares an unsafe absolute extension path.`) };\n }\n const candidate = resolve(packageRoot, declaration);\n const [canonicalEntry, entryStat] = await Promise.all([realpath(candidate), stat(candidate)]);\n if (!contains(canonicalRoot, canonicalEntry) || canonicalEntry === canonicalRoot || !entryStat.isFile()) {\n return { check: adapterFailure(home, `The declared ${PACKAGE_NAME} extension escapes its package or is not a regular file.`) };\n }\n const version = typeof manifest.version === 'string' && manifest.version.trim() ? manifest.version.trim() : 'unknown';\n return {\n adapter: { entry: canonicalEntry, version },\n check: pass('pi.adapter', `${PACKAGE_NAME} ${version} resolved to ${canonicalEntry}.`),\n };\n } catch {\n return { check: adapterFailure(home, `Could not safely resolve ${PACKAGE_NAME} from ${manifestPath}.`) };\n }\n}\n\nexport interface PiProbeOptions {\n readonly timeoutMs?: number;\n readonly outputLimit?: number;\n}\ninterface ProcessResult {\n readonly ok: boolean;\n readonly stdout: string;\n readonly reason?: 'failure' | 'timeout' | 'overflow';\n}\n\nfunction terminateProbe(child: ReturnType<typeof spawn>): void {\n if (child.pid !== undefined) {\n try { process.kill(-child.pid, 'SIGKILL'); } catch { /* the process group may already be gone */ }\n }\n try { child.kill('SIGKILL'); } catch { /* the direct child may already be gone */ }\n child.stdin?.destroy();\n child.stdout?.destroy();\n child.stderr?.destroy();\n}\n\n/** One bounded JSONL request in its own process group and isolated working directory. */\nfunction runProbeProcess(\n executable: string,\n adapterEntry: string,\n env: NodeJS.ProcessEnv,\n options: PiProbeOptions,\n cwd: string,\n): Promise<ProcessResult> {\n const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;\n const outputLimit = options.outputLimit ?? PROBE_OUTPUT_LIMIT;\n const args = ['--mode', 'rpc', '--no-session', '--no-extensions', '--extension', adapterEntry, '--no-approve'];\n return new Promise(resolveResult => {\n const child = spawn(executable, args, { cwd, detached: true, env, stdio: ['pipe', 'pipe', 'pipe'] });\n const stdout: Buffer[] = [];\n let bytes = 0;\n let settled = false;\n const finish = (result: ProcessResult): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolveResult(result);\n };\n const abort = (reason: NonNullable<ProcessResult['reason']>): void => {\n if (settled) return;\n terminateProbe(child);\n finish({ ok: false, stdout: Buffer.concat(stdout).toString('utf8'), reason });\n };\n const capture = (chunk: Buffer, keep: boolean): void => {\n if (settled) return;\n bytes += chunk.length;\n if (bytes > outputLimit) {\n abort('overflow');\n return;\n }\n if (keep) stdout.push(chunk);\n };\n const timer = setTimeout(() => { abort('timeout'); }, timeoutMs);\n child.stdout.on('data', (chunk: Buffer) => { capture(chunk, true); });\n child.stderr.on('data', (chunk: Buffer) => { capture(chunk, false); });\n child.stdout.on('error', () => { abort('failure'); });\n child.stderr.on('error', () => { abort('failure'); });\n child.on('error', () => { abort('failure'); });\n child.on('close', code => {\n const output = Buffer.concat(stdout).toString('utf8');\n finish(code === 0 ? { ok: true, stdout: output } : { ok: false, stdout: output, reason: 'failure' });\n });\n child.stdin.on('error', () => { /* a failed child is reported by close/error */ });\n child.stdin.end(`${JSON.stringify({ id: PROBE_ID, type: 'get_commands' })}\\n`);\n });\n}\n\n/** Pi runs migrations against cwd before RPC, so never probe in the caller's project. */\nasync function runProbe(\n executable: string,\n adapterEntry: string,\n env: NodeJS.ProcessEnv,\n options: PiProbeOptions,\n): Promise<ProcessResult> {\n const createdCwd = await mkdtemp(join(tmpdir(), 'paseo-room-pi-probe-'));\n const cwd = await realpath(createdCwd);\n try {\n return await runProbeProcess(executable, adapterEntry, {\n ...env,\n HOME: cwd,\n PI_CODING_AGENT_DIR: '/dev/null',\n PI_MCP_CONFIG_MODE: 'exclusive',\n PI_OFFLINE: '1',\n }, options, cwd);\n } finally {\n await rm(createdCwd, { force: true, recursive: true });\n }\n}\n\nfunction probeFailure(message: string): Check {\n return fail('pi.capability', message,\n 'Use a Pi and pi-mcp-adapter installation that exposes /mcp through the declared adapter entry.');\n}\n\n/** Authenticate the exact adapter path through Pi's correlated get_commands response. */\nexport async function probePiMcp(\n executable: string,\n adapterEntry: string,\n env: NodeJS.ProcessEnv,\n options: PiProbeOptions = {},\n): Promise<Check> {\n let result: ProcessResult;\n try {\n result = await runProbe(executable, adapterEntry, env, options);\n } catch {\n return probeFailure('Pi capability probe could not create or clean its isolated working directory.');\n }\n if (!result.ok) {\n if (result.reason === 'timeout') return probeFailure('Pi capability probe timed out.');\n if (result.reason === 'overflow') return probeFailure('Pi capability probe exceeded its output limit.');\n return probeFailure('Pi capability probe failed.');\n }\n const correlated: Record<string, unknown>[] = [];\n for (const line of result.stdout.split(/\\r?\\n/).filter(Boolean)) {\n let parsed: unknown;\n try { parsed = JSON.parse(line); } catch { return probeFailure('Pi capability probe returned malformed JSONL.'); }\n const event = asObject(parsed);\n if (!event) return probeFailure('Pi capability probe returned malformed JSONL.');\n if (event.type === 'response' && event.id === PROBE_ID) correlated.push(event);\n }\n if (correlated.length !== 1) return probeFailure('Pi capability probe did not return one correlated get_commands response.');\n const response = correlated[0];\n if (response?.command !== 'get_commands' || response.success !== true) {\n return probeFailure('Pi rejected the get_commands capability probe.');\n }\n const data = asObject(response.data);\n const commands = data?.commands;\n if (!Array.isArray(commands)) return probeFailure('Pi get_commands response was malformed.');\n const matches = commands.map(asObject).filter((command): command is Record<string, unknown> => command?.name === 'mcp');\n if (matches.length !== 1) return probeFailure('Pi did not expose exactly one /mcp command.');\n const command = matches[0];\n if (command?.source !== 'extension') return probeFailure('Pi exposed /mcp from the wrong source.');\n const sourceInfo = asObject(command.sourceInfo);\n if (typeof sourceInfo?.path !== 'string') return probeFailure('Pi did not report the /mcp extension path.');\n try {\n const sourcePath = await realpath(sourceInfo.path);\n if (sourcePath !== adapterEntry) return probeFailure('Pi loaded /mcp from a different extension path.');\n } catch {\n return probeFailure('Pi reported an unresolvable /mcp extension path.');\n }\n return pass('pi.capability', `Pi exposed /mcp from ${adapterEntry}.`);\n}\n\nasync function readPiOptional(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw error;\n }\n}\n\nexport async function piCredentialDiagnostic(layout: Layout, role: Role, binary = 'pi'): Promise<CredentialDiagnostic> {\n const home = roleHome(layout, 'pi', role);\n const path = join(home, 'auth.json');\n const launch = piLoginCommand(home, binary);\n const state = await inspectCredentialPath(path);\n const id = `pi.auth.${role}`;\n if (state.kind !== 'missing') {\n return {\n path,\n checks: [preservedCredentialCheck({\n id, agent: 'Pi', role, path, state,\n login: `${launch}; this starts a minimal, non-room-equivalent interactive login session. Run /login, then exit Pi`,\n })],\n };\n }\n const configured = presentNames(layout.envNames, AUTH_ENV);\n if (configured.length > 0) return { path, checks: [ambientNamesCheck(id, 'Pi', role, configured)] };\n return { path, checks: [{\n id: `${id}.login-required`, status: 'warn',\n message: `Pi ${role} auth: login-required; no role-owned auth.json or known provider environment name was detected. Ambient provider auth may exist, but it was not inspected or validated.`,\n fix: `Start a minimal, non-room-equivalent interactive login session with: ${launch}. Run /login, then exit Pi.`,\n }] };\n}\n\nexport const piAgent: Agent = {\n id: 'pi',\n label: 'Pi',\n homeEnv: 'PI_CODING_AGENT_DIR',\n providerEnv: { PI_MCP_CONFIG_MODE: 'exclusive' },\n pins: {},\n async build(layout: Layout, roles: readonly Role[]): Promise<AgentPlan> {\n const home = layout.agentHome.pi;\n const binary = await which(layout.bin.pi, layout.searchPath);\n if (!binary) {\n return { entries: [], checks: [fail('pi.bin', 'Pi executable not found.', 'Install Pi yourself, or pass --pi-bin /path/to/pi.')] };\n }\n try {\n if (!(await stat(home)).isDirectory()) throw new Error('not a directory');\n } catch {\n return { entries: [], checks: [fail('pi.home', `No Pi config directory at ${home}.`, 'Run Pi once to initialise it, or pass --pi-home.')] };\n }\n const resolved = await resolvePiAdapter(home);\n if (!resolved.adapter) return { entries: [], checks: [resolved.check] };\n const capability = await probePiMcp(binary, resolved.adapter.entry, {\n HOME: layout.home,\n PATH: layout.searchPath,\n PI_CODING_AGENT_DIR: '/dev/null',\n PI_OFFLINE: '1',\n });\n if (capability.status === 'fail') return { entries: [], checks: [resolved.check, capability] };\n\n const settingsPath = join(home, 'settings.json');\n let settings: string;\n try { settings = renderPiSettings(await readPiOptional(settingsPath)); } catch {\n return {\n entries: [], checks: [resolved.check, capability,\n fail('pi.settings', `Could not read ${settingsPath} as a JSON object.`,\n 'Make your Pi settings readable and fix any JSON syntax, then run setup again.')],\n };\n }\n const operatorAppendPath = join(home, 'APPEND_SYSTEM.md');\n let operatorAppend: string | undefined;\n try {\n operatorAppend = await readPiOptional(operatorAppendPath);\n } catch {\n return {\n entries: [], checks: [resolved.check, capability,\n fail('pi.append', `Could not read ${operatorAppendPath}.`,\n 'Make your Pi APPEND_SYSTEM.md readable, then run setup again.')],\n };\n }\n const shared = await existingPaths(home, SHARED);\n // The adapter reads this file as its only config source, so a Paseo-looking server here\n // would be a second control plane. Fail before apply; never edit the operator's file.\n const mcpPath = join(home, MCP_FILE);\n let servers: Record<string, unknown>;\n try {\n servers = jsonServerTable(await readPiOptional(mcpPath), MCP_KEYS);\n } catch {\n return {\n entries: [], checks: [resolved.check, capability,\n fail('pi.mcp', `Could not read ${mcpPath} as a JSON object, so its MCP declarations could not be inspected.`,\n 'Make your Pi mcp.json readable and fix its JSON structure, then run setup again.')],\n };\n }\n const conflict = paseoMcpCheck('pi.mcp', mcpPath, servers);\n if (conflict) return { entries: [], checks: [resolved.check, capability, conflict] };\n const entries: Entry[] = [];\n const credentials: CredentialDiagnostic[] = [];\n const argv: Partial<Record<Role, readonly string[]>> = {};\n const roomSkill = { name: ROOM_SKILL_NAME, source: roomSkillSource(layout) };\n for (const role of roles) {\n const target = roleHome(layout, 'pi', role);\n const appendPath = join(target, 'APPEND_SYSTEM.md');\n entries.push({ kind: 'dir', path: target });\n entries.push({ kind: 'file', path: join(target, 'settings.json'), content: settings });\n entries.push({ kind: 'file', path: appendPath, content: renderPiAppend(operatorAppend, role) });\n entries.push(...await roleResourceEntries({\n role, target, home, names: SHARED, shared, executable: EXECUTABLE, roomSkill,\n leadSkillProjection: leadSkillProjection(layout, 'pi'),\n }));\n credentials.push(await piCredentialDiagnostic(layout, role, binary));\n argv[role] = ['--no-extensions', '--extension', resolved.adapter.entry, '--no-approve', '--append-system-prompt', appendPath];\n }\n return {\n entries,\n credentials,\n checks: [pass('pi.home', `Pi found at ${binary} using ${home}.`), resolved.check, capability],\n binary,\n argv,\n };\n },\n};\n","import type { PaseoClient, PaseoClientConfig } from '@getpaseo/client';\nimport { gte, valid } from 'semver';\nimport { z } from 'zod';\nimport type { Layout } from './layout.js';\nimport { fail, pass, type Check } from './result.js';\nimport type { Profile, Provider } from './agents/types.js';\nimport type { AgentId } from './roles.js';\nimport { probe, which } from './which.js';\n\nexport const MINIMUM_VERSION = '0.8.0-beta.1';\nexport const PI_MINIMUM_VERSION = '0.8.0';\n\n/** Claude and Pi need `0.8.0`; so does the runtime plugin, whose range the caller also checks. */\nexport function minimumPaseoVersion(agents: readonly AgentId[], runtime = false): string {\n return runtime || agents.includes('pi') || agents.includes('claude') ? PI_MINIMUM_VERSION : MINIMUM_VERSION;\n}\n\n/**\n * Read `daemon status --json` for only the four facts compatibility turns on, and read them\n * loosely: this is a CLI's human-facing output, not a versioned protocol type, and it has already\n * changed shape once. `0.8.x` reported `cliVersion`; `0.9.x` dropped it and gained a supervisor\n * `pid` separate from `workerPid`, so the caller supplies the CLI version instead. `localDaemon`\n * is a plain string because its state names are Paseo's to extend — `0.9.x` added `not_ready` —\n * and every name but `running` means the same thing to this tool.\n */\nconst statusSchema = z.object({\n listen: z.string().min(1),\n localDaemon: z.string().min(1),\n cliVersion: z.string().optional(),\n daemonVersion: z.string().nullish(),\n});\n\nexport interface Daemon {\n readonly url: string;\n readonly version: string;\n}\nexport interface DaemonResult {\n readonly checks: readonly Check[];\n readonly daemon?: Daemon;\n}\n\nexport function normalizeUrl(listen: string): string | undefined {\n const match = /^(?:ws:\\/\\/)?([^:/]+|\\[[^\\]]+\\]):(\\d+)$/.exec(listen.trim());\n if (!match) return undefined;\n const [, host = '', port = ''] = match;\n const local = ['localhost', '127.0.0.1', '0.0.0.0', '[::1]', '[::]'].includes(host) ? '127.0.0.1' : host;\n return `ws://${local}:${port}`;\n}\n\n/**\n * The whole compatibility story: is Paseo running, and is it new enough? `cliVersion` is the\n * executable's own version, used only when the status output no longer carries one; comparing it\n * to the daemon is what catches an upgraded CLI whose daemon was never restarted.\n */\nexport function assessStatus(raw: unknown, minimumVersion = MINIMUM_VERSION, cliVersion?: string): DaemonResult {\n const parsed = statusSchema.safeParse(raw);\n if (!parsed.success) {\n return { checks: [fail('paseo.status', 'Paseo status output was not understood.', 'Upgrade Paseo, then run: paseo daemon status --json')] };\n }\n const status = parsed.data;\n if (status.localDaemon !== 'running') {\n return { checks: [fail('paseo.daemon', `Paseo daemon is ${status.localDaemon}.`, 'Start it with: paseo daemon start')] };\n }\n const cli = valid(status.cliVersion ?? cliVersion);\n const daemon = status.daemonVersion == null ? null : valid(status.daemonVersion);\n if (!cli || !daemon) {\n return { checks: [fail('paseo.version', 'Paseo did not report a usable version.', 'Upgrade Paseo to a release that reports semver versions.')] };\n }\n if (cli !== daemon) {\n return { checks: [fail('paseo.version', `Paseo CLI is ${cli} but the running daemon is ${daemon}.`, 'Restart the daemon with: paseo daemon restart')] };\n }\n if (!gte(daemon, minimumVersion)) {\n return { checks: [fail('paseo.version', `Paseo ${daemon} is older than the required ${minimumVersion}.`, 'Upgrade Paseo, then run setup again.')] };\n }\n const url = normalizeUrl(status.listen);\n if (!url) {\n return { checks: [fail('paseo.listen', `Paseo listen address ${status.listen} was not understood.`, 'Use a host:port listen address in the Paseo config.')] };\n }\n return { checks: [pass('paseo.version', `Paseo ${daemon} is running on ${url} (compatible, needs >= ${minimumVersion}).`)], daemon: { url, version: daemon } };\n}\n\nexport async function checkDaemon(layout: Layout, env: NodeJS.ProcessEnv = process.env, minimumVersion = MINIMUM_VERSION): Promise<DaemonResult> {\n const binary = await which(layout.bin.paseo, layout.searchPath);\n if (!binary) {\n return { checks: [fail('paseo.bin', 'Paseo executable not found.', 'Install Paseo, or pass --paseo-bin /path/to/paseo.')] };\n }\n const output = await probe(binary, ['daemon', 'status', '--json'], {\n HOME: layout.home, PASEO_HOME: layout.paseoHome, PATH: layout.searchPath,\n ...(env.PASEO_PASSWORD === undefined ? {} : { PASEO_PASSWORD: env.PASEO_PASSWORD }),\n });\n if (!output.ok) {\n return { checks: [fail('paseo.status', 'Could not read Paseo daemon status.', 'Run: paseo daemon status --json')] };\n }\n let status: unknown;\n try { status = JSON.parse(output.stdout); }\n catch { return assessStatus(undefined, minimumVersion); }\n // Paseo 0.9 stopped reporting the CLI version in status, so ask the same executable we just\n // ran. Only then: a status that still carries one needs no second process.\n const reported = (status as { cliVersion?: unknown } | null)?.cliVersion;\n if (typeof reported === 'string') return assessStatus(status, minimumVersion);\n const version = await probe(binary, ['--version'], { HOME: layout.home, PATH: layout.searchPath });\n return assessStatus(status, minimumVersion, version.ok ? version.stdout.trim() : undefined);\n}\n\nconst configSchema = z.object({\n config: z.object({\n providers: z.record(z.string(), z.unknown()).optional(),\n // Read loosely: entries carry operator fields the room neither knows nor touches.\n agentProfiles: z.array(z.record(z.string(), z.unknown())).optional(),\n pluginsEnabled: z.boolean().optional(),\n }),\n});\nexport type LiveProfile = Record<string, unknown>;\nexport interface LivePlugin {\n readonly id: string;\n readonly path: string;\n readonly enabled: boolean;\n readonly status: string;\n readonly error?: string | undefined;\n}\n\nexport interface Session {\n readProviders(): Promise<Record<string, unknown>>;\n writeProviders(providers: Readonly<Record<string, Provider>>): Promise<void>;\n removeProviders(ids: readonly string[]): Promise<void>;\n readProfiles(): Promise<readonly LiveProfile[]>;\n /** Paseo has no remove-one call for profiles, so this replaces the whole array. */\n writeProfiles(profiles: readonly LiveProfile[]): Promise<void>;\n pluginsEnabled(): Promise<boolean>;\n listPlugins(): Promise<readonly LivePlugin[]>;\n installPlugin(path: string, id: string): Promise<LivePlugin>;\n reloadPlugin(id: string): Promise<LivePlugin>;\n enablePlugin(id: string): Promise<LivePlugin>;\n removePlugin(id: string): Promise<void>;\n refresh(ids: readonly string[]): Promise<void>;\n}\nexport interface RoomClient extends PaseoClient {\n listPlugins(): Promise<LivePlugin[]>;\n installDirectoryPlugin(path: string, id?: string): Promise<LivePlugin>;\n reloadPlugin(id: string): Promise<LivePlugin>;\n enablePlugin(id: string): Promise<LivePlugin>;\n removePlugin(id: string): Promise<void>;\n}\nexport type ClientFactory = (config: PaseoClientConfig) => RoomClient;\n\n/** One connection per command. No retries, no reconnects, no background state. */\nexport async function withSession<T>(\n daemon: Daemon,\n run: (session: Session) => Promise<T>,\n options: { readonly password?: string; readonly factory?: ClientFactory } = {},\n): Promise<T> {\n const quiet = { debug() { /* silent */ }, info() { /* silent */ }, warn() { /* silent */ }, error() { /* silent */ } };\n // Loaded here so the \"Paseo is not running\" path never pays for the SDK.\n const clientConfig: PaseoClientConfig = {\n url: `${daemon.url}/ws`,\n ...(options.password === undefined ? {} : { password: options.password }),\n appVersion: MINIMUM_VERSION,\n connectTimeoutMs: 10_000,\n reconnect: { enabled: false },\n logger: quiet,\n };\n let client: RoomClient;\n if (options.factory !== undefined) {\n client = options.factory(clientConfig);\n } else {\n const [{ createPaseoApi }, { DaemonClient }] = await Promise.all([\n import('@getpaseo/client'), import('@getpaseo/client/internal/daemon-client'),\n ]);\n // The public config types `capabilities` as possibly undefined while DaemonClient's does not,\n // so forward it only when present rather than spreading an explicit undefined.\n const { capabilities, ...config } = clientConfig;\n const raw = new DaemonClient({\n ...config, ...(capabilities === undefined ? {} : { capabilities }),\n clientId: `paseo-room-${String(process.pid)}`, clientType: 'cli',\n });\n client = {\n ...createPaseoApi(raw),\n connect: () => raw.connect(), close: () => raw.close(),\n ensureConnected: () => { raw.ensureConnected(); }, getConnectionState: () => raw.getConnectionState(),\n listPlugins: () => raw.listPlugins(),\n installDirectoryPlugin: (path, id) => raw.installDirectoryPlugin(path, id),\n reloadPlugin: id => raw.reloadPlugin(id), enablePlugin: id => raw.enablePlugin(id),\n removePlugin: id => raw.removePlugin(id),\n };\n }\n try {\n await client.connect();\n return await run({\n async readProviders() {\n const response = configSchema.parse(await client.config.get());\n return response.config.providers ?? {};\n },\n async writeProviders(providers) {\n await client.config.patch({ providers } as unknown as Parameters<PaseoClient['config']['patch']>[0]);\n },\n async removeProviders(ids) {\n await client.config.patch({ removeProviders: [...ids] });\n },\n async readProfiles() {\n const response = configSchema.parse(await client.config.get());\n return response.config.agentProfiles ?? [];\n },\n async writeProfiles(profiles) {\n await client.config.patch({ agentProfiles: [...profiles] } as unknown as Parameters<PaseoClient['config']['patch']>[0]);\n },\n async pluginsEnabled() {\n const response = configSchema.parse(await client.config.get());\n return response.config.pluginsEnabled === true;\n },\n async listPlugins() {\n return await client.listPlugins();\n },\n async installPlugin(path, id) {\n return await client.installDirectoryPlugin(path, id);\n },\n async reloadPlugin(id) {\n return await client.reloadPlugin(id);\n },\n async enablePlugin(id) {\n return await client.enablePlugin(id);\n },\n async removePlugin(id) {\n await client.removePlugin(id);\n },\n async refresh(ids) {\n await client.providers.refresh({ providers: [...ids] });\n },\n });\n } finally {\n await client.close();\n }\n}\n\n/**\n * The provider environment is written whole by the room, so it is compared whole: an\n * added key can enable exactly what the pins close, and a subset test would call that a\n * match. Unrelated *top-level* provider fields remain the operator's.\n */\nfunction envMatches(live: unknown, desired: Readonly<Record<string, string>>): boolean {\n if (live === null || typeof live !== 'object' || Array.isArray(live)) return false;\n const entries = Object.entries(live as Record<string, unknown>);\n return entries.length === Object.keys(desired).length &&\n entries.every(([key, value]) => Object.hasOwn(desired, key) && value === desired[key]);\n}\n\n/** Compare only the keys the room owns; unrelated fields stay the operator's. */\nexport function providerMatches(desired: Provider, live: unknown): boolean {\n if (live === null || typeof live !== 'object') return false;\n const entry = live as Record<string, unknown>;\n const tools = entry.paseoTools;\n const same = (left: unknown, right: unknown): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);\n return entry.extends === desired.extends &&\n same(entry.command, desired.command) &&\n envMatches(entry.env, desired.env) &&\n tools !== null && typeof tools === 'object' &&\n (tools as { enabled?: unknown }).enabled === desired.paseoTools.enabled &&\n // Pins are the room's guarantee: drifting them silently re-enables what they block.\n same(entry.params, desired.params) &&\n same(entry.disallowedTools, desired.disallowedTools);\n}\n\n/** Compare only the fields the room writes on an update; the rest are the operator's. */\nexport function profileMatches(desired: Profile, live: unknown): boolean {\n if (live === null || typeof live !== 'object') return false;\n const entry = live as Record<string, unknown>;\n return entry.name === desired.name && entry.icon === desired.icon && entry.color === desired.color &&\n entry.provider === desired.provider && entry.modeId === desired.modeId && entry.notes === desired.notes;\n}\n\n/**\n * Paseo stores every profile in one host-wide array, so the room rewrites that array\n * rather than patching an entry. Operator profiles pass through untouched, and so does\n * every field of a room profile that the room does not own.\n */\nexport function mergeProfiles(\n live: readonly LiveProfile[],\n desired: readonly Profile[],\n drop: readonly string[],\n): LiveProfile[] {\n const dropped = new Set(drop);\n const wanted = new Map(desired.map(profile => [profile.id, profile]));\n const seen = new Set<string>();\n const kept = live\n .filter(entry => !dropped.has(String(entry.id)))\n .map(entry => {\n const profile = wanted.get(String(entry.id));\n if (!profile) return entry;\n seen.add(profile.id);\n // Model and thinkingOptionId remain operator choices; the room owns the\n // role's visual identity and its no-prompt launch mode.\n const updated: LiveProfile = {\n ...entry, name: profile.name, icon: profile.icon, color: profile.color,\n provider: profile.provider, notes: profile.notes,\n };\n if (profile.modeId === undefined) delete updated.modeId;\n else updated.modeId = profile.modeId;\n return updated;\n });\n return [...kept, ...desired.filter(profile => !seen.has(profile.id)).map(profile => ({ ...profile }))];\n}\n","import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Entry } from './fsops.js';\nimport type { Layout } from './layout.js';\nimport { providerId, type Role } from './roles.js';\nimport { contractDigest, renderInstructions } from './room/instructions.js';\n\nexport const CLAUDE_CARRIER_PLUGIN_ID = 'paseo-room-claude-carrier';\n/** Kept in step with `RUNTIME_PASEO_RANGE`: both bind the same unchanged plugin host contract. */\nexport const CLAUDE_CARRIER_PASEO_RANGE = '>=0.8.0 <0.10.0';\n\nconst STATIC_ASSETS = [\n 'paseo-plugin.json',\n 'package.json',\n 'tsconfig.json',\n 'index.server.ts',\n 'server/carrier.ts',\n] as const;\n\nfunction loadAsset(path: string): string {\n return readFileSync(new URL(`./plugin-assets/${path}`, import.meta.url), 'utf8');\n}\n\nexport function claudeCarrierPluginDir(layout: Layout): string {\n return join(layout.roomHome, 'plugin');\n}\n\n/** A readable TypeScript string literal that preserves the rendered Markdown byte-for-byte. */\nexport function typescriptTemplateLiteral(value: string): string {\n const escaped = value\n .replaceAll('\\\\', '\\\\\\\\')\n .replaceAll('`', '\\\\`')\n .replaceAll('${', '\\\\${');\n return `\\`${escaped}\\``;\n}\n\nexport function renderClaudeCarrierContract(roles: readonly Role[]): string {\n const entries = roles.map(role => {\n const id = JSON.stringify(providerId('claude', role));\n return ` ${id}: ${typescriptTemplateLiteral(renderInstructions(role))},`;\n });\n return [\n '/** Generated by paseo-room. The Markdown prompt assets remain authoritative. */',\n `export const GENERATION = ${JSON.stringify(contractDigest())};`,\n 'export const CONTRACT: Readonly<Record<string, string>> = {',\n ...entries,\n '};',\n '',\n ].join('\\n');\n}\n\nexport function claudeCarrierEntries(layout: Layout, roles: readonly Role[]): Entry[] {\n const root = claudeCarrierPluginDir(layout);\n return [\n { kind: 'dir', path: root },\n { kind: 'dir', path: join(root, 'server') },\n ...STATIC_ASSETS.map(path => ({ kind: 'file' as const, path: join(root, path), content: loadAsset(path) })),\n { kind: 'file', path: join(root, 'server', 'contract.ts'), content: renderClaudeCarrierContract(roles) },\n ];\n}\n","/**\n * The runtime role-policy projection: which runtime operations each room role may invoke.\n *\n * This is the single source for both the CLI, which writes it into the generated room manifest,\n * and the plugin's authorization. It is deliberately not `ROLE_PASEO_TOOLS`: Paseo's built-in\n * room tools stay off for Peer, and the only runtime surface a Peer can ever hold is the\n * assignment-scoped reporting pair (docs/design/runtime-coordination.md D4, §3.4).\n */\n\nexport const RUNTIME_ROLES = ['supervisor', 'lead', 'peer'] as const;\nexport type RuntimeRole = (typeof RUNTIME_ROLES)[number];\n\nexport const RUNTIME_AGENTS = ['codex', 'claude', 'pi'] as const;\nexport type RuntimeAgent = (typeof RUNTIME_AGENTS)[number];\n\nexport const SUPERVISOR_OPERATIONS = ['room_status', 'runtime_findings', 'message_lead', 'attention_feedback'] as const;\nexport const LEAD_OPERATIONS = [\n 'assignment_create', 'assignment_dispatch', 'assignment_answer', 'assignment_rework',\n 'assignment_accept', 'assignment_reject', 'assignment_abandon', 'assignment_close',\n 'assignment_status', 'gate_run', 'workspace_close', 'lease_reclaim',\n] as const;\n/** A closed tuple. Adding a Peer operation is an authority and protocol revision, not a patch. */\nexport const PEER_REPORTING_TOOLS = ['ask', 'handoff'] as const;\n\nexport type SupervisorOperation = (typeof SUPERVISOR_OPERATIONS)[number];\nexport type LeadOperation = (typeof LEAD_OPERATIONS)[number];\nexport type PeerReportingTool = (typeof PEER_REPORTING_TOOLS)[number];\nexport type RuntimeCapability = SupervisorOperation | LeadOperation | PeerReportingTool;\n\nexport const RUNTIME_CAPABILITIES: readonly RuntimeCapability[] = [\n ...SUPERVISOR_OPERATIONS, ...LEAD_OPERATIONS, ...PEER_REPORTING_TOOLS,\n];\n\nexport interface PeerReportingDeclaration {\n readonly protocol: 1;\n readonly tools: readonly ['ask', 'handoff'];\n readonly qualifiedVia: 'exact-room-provider';\n}\n\nexport interface RuntimeRolePolicy {\n readonly capabilities: readonly RuntimeCapability[];\n readonly peerReporting?: PeerReportingDeclaration;\n}\n\nexport const PEER_REPORTING_DECLARATION: PeerReportingDeclaration = {\n protocol: 1,\n tools: ['ask', 'handoff'],\n qualifiedVia: 'exact-room-provider',\n};\n\n/**\n * Projects one role's runtime capabilities. `peerReportingEligible` comes from the canonical\n * `ROLE_PEER_REPORTING` policy; a Peer that is not eligible holds no runtime operation at all.\n */\nexport function runtimeRolePolicy(role: RuntimeRole, peerReportingEligible: boolean): RuntimeRolePolicy {\n if (role === 'supervisor') return { capabilities: [...SUPERVISOR_OPERATIONS] };\n if (role === 'lead') return { capabilities: [...LEAD_OPERATIONS] };\n return peerReportingEligible\n ? { capabilities: [...PEER_REPORTING_TOOLS], peerReporting: PEER_REPORTING_DECLARATION }\n : { capabilities: [] };\n}\n","/**\n * The generated room manifest (docs/design/runtime-coordination.md §3.2): the only bridge from\n * provisioning evidence to runtime recognition. Setup is its only writer; the plugin refuses\n * anything missing, broader than the policy projection, or keyed by a non-exact provider id.\n */\nimport { z } from 'zod';\nimport {\n PEER_REPORTING_TOOLS, RUNTIME_AGENTS, RUNTIME_CAPABILITIES, RUNTIME_ROLES, runtimeRolePolicy,\n} from './policy.js';\n\nexport const MANIFEST_FILE = 'generated/room-manifest.json';\n\nconst generation = z.string().min(1).max(256);\n\nconst peerReportingSchema = z.strictObject({\n protocol: z.literal(1),\n tools: z.tuple([z.literal(PEER_REPORTING_TOOLS[0]), z.literal(PEER_REPORTING_TOOLS[1])]),\n qualifiedVia: z.literal('exact-room-provider'),\n});\n\nconst providerSchema = z.strictObject({\n agent: z.enum(RUNTIME_AGENTS),\n role: z.enum(RUNTIME_ROLES),\n capabilities: z.array(z.enum(RUNTIME_CAPABILITIES as [string, ...string[]])),\n peerReporting: peerReportingSchema.optional(),\n}).superRefine((entry, context) => {\n // A declaration is valid only when it is exactly the projection for its role: never broader,\n // never a Peer operation outside the closed tuple, never reporting on a non-Peer seat.\n const eligible = entry.role === 'peer' && entry.peerReporting !== undefined;\n const expected = runtimeRolePolicy(entry.role, eligible);\n if (JSON.stringify(entry.capabilities) !== JSON.stringify(expected.capabilities)) {\n context.addIssue({ code: 'custom', message: `capabilities do not match the ${entry.role} runtime policy` });\n }\n if (entry.peerReporting !== undefined && entry.role !== 'peer') {\n context.addIssue({ code: 'custom', message: 'peerReporting is only valid on a Peer entry' });\n }\n});\n\n/** Exact provider ids only: a runtime never matches by prefix, label, title or cwd. */\nconst providerId = z.string().regex(/^[a-z0-9][a-z0-9-]*$/).max(128);\n\nexport const runtimeRoomManifestSchema = z.strictObject({\n schema: z.literal(1),\n roomGeneration: generation,\n contractGeneration: generation,\n reportingPolicyGeneration: generation,\n providers: z.record(providerId, providerSchema),\n});\n\nexport type RuntimeRoomManifestV1 = z.infer<typeof runtimeRoomManifestSchema>;\nexport type RuntimeManifestProvider = RuntimeRoomManifestV1['providers'][string];\n","/**\n * Identity of the opt-in runtime coordination plugin. Shared by the server and client entries,\n * and by the CLI that provisions it, so the id and the supported Paseo range have one source.\n *\n * Separate from `paseo-room-claude-carrier` on purpose: a runtime fault must never remove or\n * rewrite the Claude contract carrier (docs/design/runtime-coordination.md D1).\n */\nexport const RUNTIME_PLUGIN_ID = 'paseo-room-runtime';\n\n/**\n * `0.8.0` and `0.9.1` are the live-qualified points. `0.9.x` carries a byte-identical plugin\n * compiler, unchanged lifecycle hooks and an unchanged provider/profile config schema, so the\n * host contract this plugin depends on is the same one `0.8.0` was qualified against. `0.10.0`\n * is unqualified, so the bound stays exclusive.\n */\nexport const RUNTIME_PASEO_RANGE = '>=0.8.0 <0.10.0';\n\n/**\n * Daemon versions on which worktree dispatch passed live qualification\n * (docs/design/runtime-coordination-phase2.md §9). Any other version — or one the plugin cannot\n * read — refuses `isolation: 'worktree'` with `worktree_unqualified`; it is a runtime check, not a\n * change of the plugin's range. `0.9.1`: delta §9.2, 2026-09-23.\n */\nexport const QUALIFIED_WORKTREE_DAEMONS: readonly string[] = ['0.9.1'];\n","import { createHash } from 'node:crypto';\nimport { readdirSync, readFileSync } from 'node:fs';\nimport { join, relative, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { Entry } from './fsops.js';\nimport type { Layout } from './layout.js';\nimport { providerId, ROLE_PEER_REPORTING, type AgentId, type Role } from './roles.js';\nimport { contractDigest } from './room/instructions.js';\nimport { MANIFEST_FILE, runtimeRoomManifestSchema, type RuntimeRoomManifestV1 } from './runtime-plugin/shared/manifest.js';\nimport { RUNTIME_PASEO_RANGE, RUNTIME_PLUGIN_ID } from './runtime-plugin/shared/identity.js';\nimport { runtimeRolePolicy } from './runtime-plugin/shared/policy.js';\n\nexport { RUNTIME_PASEO_RANGE, RUNTIME_PLUGIN_ID };\n\n/** The bundled plugin tree: `src/runtime-plugin` in a checkout, `dist/runtime-plugin` when packed. */\nconst BUNDLE = fileURLToPath(new URL('./runtime-plugin/', import.meta.url));\n\nexport function runtimePluginDir(layout: Layout): string {\n return join(layout.roomHome, 'runtime-plugin');\n}\n\nfunction digest(value: unknown): string {\n return `sha256:${createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 16)}`;\n}\n\n/** Every role's runtime policy, as the canonical reporting policy decides it. */\nfunction reportingPolicy(): Record<Role, ReturnType<typeof runtimeRolePolicy>> {\n return {\n supervisor: runtimeRolePolicy('supervisor', ROLE_PEER_REPORTING.supervisor),\n lead: runtimeRolePolicy('lead', ROLE_PEER_REPORTING.lead),\n peer: runtimeRolePolicy('peer', ROLE_PEER_REPORTING.peer),\n };\n}\n\n/** Changes exactly when the approved reporting policy changes, so a stale plugin can refuse it. */\nexport function reportingPolicyGeneration(): string {\n return digest(reportingPolicy());\n}\n\n/**\n * The generated room manifest: exact provider ids mapped to role capabilities, with\n * `peerReporting` only where `ROLE_PEER_REPORTING` allows it. Deterministic, so rerunning setup\n * shows no phantom change, and validated against the plugin's own strict schema before use.\n */\nexport function renderRuntimeManifest(agents: readonly AgentId[], roles: readonly Role[]): RuntimeRoomManifestV1 {\n const policy = reportingPolicy();\n const providers: RuntimeRoomManifestV1['providers'] = {};\n for (const agent of agents) {\n for (const role of roles) {\n const { capabilities, peerReporting } = policy[role];\n providers[providerId(agent, role)] = {\n agent, role, capabilities: [...capabilities],\n ...(peerReporting === undefined ? {} : { peerReporting: { ...peerReporting, tools: ['ask', 'handoff'] } }),\n };\n }\n }\n const contractGeneration = contractDigest();\n return runtimeRoomManifestSchema.parse({\n schema: 1,\n roomGeneration: digest({ agents: [...agents], roles: [...roles], contractGeneration }),\n contractGeneration,\n reportingPolicyGeneration: reportingPolicyGeneration(),\n providers,\n });\n}\n\nexport function renderRuntimeManifestFile(agents: readonly AgentId[], roles: readonly Role[]): string {\n return `${JSON.stringify(renderRuntimeManifest(agents, roles), null, 2)}\\n`;\n}\n\nexport const LOCATION_MODULE = 'server/generated/location.ts';\n\n/** The per-room locator the plugin reads, since Paseo evaluates it without a file path of its own. */\nexport function renderRuntimeLocation(layout: Layout): string {\n const location = { pluginDirectory: runtimePluginDir(layout), runtimeRoot: join(layout.roomHome, 'runtime', 'v1') };\n return [\n '/** Generated by paseo-room setup for this room. */',\n 'export interface RoomLocation {',\n ' readonly pluginDirectory: string;',\n ' readonly runtimeRoot: string;',\n '}',\n '',\n `export const ROOM_LOCATION: RoomLocation | undefined = ${JSON.stringify(location)};`,\n '',\n ].join('\\n');\n}\n\n/** Relative paths of the bundled plugin tree, directories first so they are planned before files. */\nfunction bundleInventory(): { readonly dirs: string[]; readonly files: string[] } {\n const entries = readdirSync(BUNDLE, { recursive: true, withFileTypes: true });\n const toRelative = (entry: (typeof entries)[number]): string =>\n relative(BUNDLE, join(entry.parentPath, entry.name)).split(sep).join('/');\n return {\n dirs: entries.filter(entry => entry.isDirectory()).map(toRelative).sort(),\n files: entries.filter(entry => entry.isFile()).map(toRelative).sort(),\n };\n}\n\n/**\n * The runtime plugin as ordinary managed entries under `~/.paseo-room/runtime-plugin`. The\n * plugin-owned `~/.paseo-room/runtime` state tree is deliberately absent: setup never plans,\n * compares, replaces or deletes it.\n */\nexport function runtimePluginEntries(layout: Layout, agents: readonly AgentId[], roles: readonly Role[]): Entry[] {\n const root = runtimePluginDir(layout);\n const { dirs, files } = bundleInventory();\n const generatedDir = MANIFEST_FILE.split('/').slice(0, -1).join('/');\n return [\n { kind: 'dir', path: root },\n ...[...new Set([...dirs, generatedDir])].sort().map(path => ({ kind: 'dir' as const, path: join(root, path) })),\n ...files.map(path => ({\n kind: 'file' as const, path: join(root, path),\n content: path === LOCATION_MODULE ? renderRuntimeLocation(layout) : readFileSync(join(BUNDLE, path), 'utf8'),\n })),\n { kind: 'file', path: join(root, MANIFEST_FILE), content: renderRuntimeManifestFile(agents, roles) },\n ];\n}\n","/**\n * Size bounds for every strict runtime input (docs/design/runtime-coordination.md §3.4, D6).\n * Measured in UTF-8 bytes, not UTF-16 code units, so a limit means the same on every side.\n */\nimport { z } from 'zod';\n\nexport const MAX_AGGREGATE_BYTES = 64 * 1024;\nexport const MAX_ARRAY_ITEMS = 64;\nexport const MAX_STRING_BYTES = 8 * 1024;\nexport const MAX_COMMAND_BYTES = 16 * 1024;\nexport const MAX_GATE_TIMEOUT_SECONDS = 3_600;\n\nconst encoder = new TextEncoder();\n\nexport function utf8Bytes(value: string): number {\n return encoder.encode(value).length;\n}\n\n/** A string of 1 byte up to `max` UTF-8 bytes. */\nexport function boundedString(max = MAX_STRING_BYTES): z.ZodString {\n return z.string().refine(value => {\n const bytes = utf8Bytes(value);\n return bytes >= 1 && bytes <= max;\n }, { message: `must be 1 byte to ${String(max)} bytes of UTF-8` });\n}\n\nexport function boundedArray<T extends z.ZodType>(item: T): z.ZodArray<T> {\n return z.array(item).max(MAX_ARRAY_ITEMS);\n}\n\n/** True when the JSON form of `value` fits the aggregate bound; non-serialisable input does not. */\nexport function withinAggregateLimit(value: unknown): boolean {\n try {\n // Typed as string, but undefined and functions serialise to undefined at run time.\n const json = JSON.stringify(value) as string | undefined;\n return json !== undefined && utf8Bytes(json) <= MAX_AGGREGATE_BYTES;\n } catch {\n return false;\n }\n}\n\n/**\n * Concurrent worktree writer leases per project (docs/design/runtime-coordination-phase2.md\n * P2-D1). Fixed: raising it is a design change, not configuration.\n */\nexport const MAX_WORKTREE_LEASES = 3;\n","/**\n * Canonical write-scope grammar and the conservative collision checks behind worktree dispatch\n * (docs/design/runtime-coordination-phase2.md §5).\n *\n * This decides scheduling, not access. Every approximation errs toward \"overlapping\": a false\n * overlap costs Lead one narrower brief, a false \"disjoint\" lets two writers meet on one path.\n * No dependency: glob libraries match a path against a pattern, and this needs the intersection\n * of two patterns (§5.5).\n */\nimport { MAX_STRING_BYTES, utf8Bytes } from '../../shared/limits.js';\n\n/** One normalised scope entry. `segments` always ends in `**`: an entry owns everything below it. */\nexport interface ScopeEntry {\n readonly text: string;\n readonly segments: readonly string[];\n}\n\nexport type ScopeParse =\n | { readonly ok: true; readonly entry: ScopeEntry }\n | { readonly ok: false; readonly item: string; readonly reason: string };\n\nexport type ScopesParse =\n | { readonly ok: true; readonly entries: readonly ScopeEntry[] }\n | { readonly ok: false; readonly item: string; readonly reason: string };\n\nconst GLOBSTAR = '**';\nconst WHOLE_REPOSITORY: ScopeEntry = { text: GLOBSTAR, segments: [GLOBSTAR] };\n\n/** NFC, repeated `/` collapsed, trailing `/` stripped. Refusals are `parseScope`'s job. */\nexport function normalizeScope(raw: string): string {\n return raw.normalize('NFC').replace(/\\/{2,}/g, '/').replace(/\\/+$/, '');\n}\n\nfunction refusal(raw: string, text: string): string | undefined {\n if (utf8Bytes(raw) > MAX_STRING_BYTES) return `longer than ${String(MAX_STRING_BYTES)} bytes`;\n if (text === '') return 'empty';\n if (text.includes('\\\\')) return 'contains a backslash';\n if (text.startsWith('/')) return 'is absolute';\n if (text.startsWith('!')) return 'is a negation';\n if (/[{}]/.test(text)) return 'uses brace expansion';\n if (/[[\\]]/.test(text)) return 'uses a character class';\n if (text.split('/').some(segment => segment === '.' || segment === '..')) return 'has a . or .. segment';\n return undefined;\n}\n\n/** Parse one entry under the §5.1 grammar. A refusal names the entry as written. */\nexport function parseScope(raw: string): ScopeParse {\n const text = normalizeScope(raw);\n const reason = refusal(raw, text);\n if (reason !== undefined) return { ok: false, item: raw, reason };\n // A run of `*` inside a segment means the same as one; a whole-segment run is the globstar.\n const segments = text.split('/').map(segment => (/^\\*+$/.test(segment) && segment.length > 1 ? GLOBSTAR : segment.replace(/\\*{2,}/g, '*')));\n if (segments.at(-1) !== GLOBSTAR) segments.push(GLOBSTAR);\n return { ok: true, entry: { text, segments } };\n}\n\n/** Parse a scope list; an empty list is the whole repository. */\nexport function parseScopes(raws: readonly string[]): ScopesParse {\n if (raws.length === 0) return { ok: true, entries: [WHOLE_REPOSITORY] };\n const entries: ScopeEntry[] = [];\n for (const raw of raws) {\n const parsed = parseScope(raw);\n if (!parsed.ok) return parsed;\n entries.push(parsed.entry);\n }\n return { ok: true, entries };\n}\n\n/** Code points, not UTF-16 units: a `?` stands for one character, as it does for Git. */\nconst codePoints = (value: string): string[] => Array.from(value);\n\n/**\n * Lower-case one code point at a time, keeping any code point whose lower case is longer, so a\n * `?` still counts the same characters on both sides of a comparison.\n */\nfunction fold(value: string): string[] {\n return codePoints(value).map(point => {\n const lower = point.toLowerCase();\n return codePoints(lower).length === 1 ? lower : point;\n });\n}\n\nconst isPattern = (segment: string): boolean => segment.includes('*') || segment.includes('?');\n\n/** Whether a `*`/`?` segment pattern matches a literal segment, both already split into code points. */\nfunction segmentMatches(pattern: readonly string[], literal: readonly string[]): boolean {\n let row = new Array<boolean>(literal.length + 1).fill(false);\n row[literal.length] = true;\n for (let i = pattern.length - 1; i >= 0; i--) {\n const next = new Array<boolean>(literal.length + 1).fill(false);\n for (let j = literal.length; j >= 0; j--) {\n const token = pattern[i];\n if (token === '*') next[j] = (row[j] ?? false) || (j < literal.length && (next[j + 1] ?? false));\n else next[j] = j < literal.length && (token === '?' || token === literal[j]) && (row[j + 1] ?? false);\n }\n row = next;\n }\n return row[0] ?? false;\n}\n\n/** The fixed code points before the first and after the last wildcard. */\nfunction fixedEnds(pattern: readonly string[]): { prefix: string[]; suffix: string[] } {\n const wildcards = pattern.flatMap((point, index) => (point === '*' || point === '?' ? [index] : []));\n return { prefix: pattern.slice(0, wildcards[0]), suffix: pattern.slice((wildcards.at(-1) ?? pattern.length) + 1) };\n}\n\nconst agree = (a: readonly string[], b: readonly string[]): boolean => a.every((point, index) => index >= b.length || point === b[index]);\n\n/** Whether two non-globstar segments could both match one path segment, case-folded. */\nfunction segmentsIntersect(a: string, b: string): boolean {\n const left = fold(a);\n const right = fold(b);\n const leftPattern = isPattern(a);\n const rightPattern = isPattern(b);\n if (!leftPattern && !rightPattern) return left.join('') === right.join('');\n if (!rightPattern) return segmentMatches(left, right);\n if (!leftPattern) return segmentMatches(right, left);\n // Two patterns: disjoint only when a fixed prefix or a fixed suffix provably differs.\n const l = fixedEnds(left);\n const r = fixedEnds(right);\n const suffixesAgree = agree([...l.suffix].reverse(), [...r.suffix].reverse());\n return agree(l.prefix, r.prefix) && suffixesAgree;\n}\n\n/** Could some path match both segment lists? `**` consumes zero or more segments of the other side. */\nfunction sequencesIntersect(a: readonly string[], b: readonly string[]): boolean {\n const width = b.length + 1;\n const table = new Uint8Array((a.length + 1) * width);\n const at = (i: number, j: number): boolean => table[i * width + j] === 1;\n for (let i = a.length; i >= 0; i--) {\n for (let j = b.length; j >= 0; j--) {\n let value: boolean;\n if (i === a.length && j === b.length) value = true;\n else if (i === a.length) value = b[j] === GLOBSTAR && at(i, j + 1);\n else if (j === b.length) value = a[i] === GLOBSTAR && at(i + 1, j);\n else if (a[i] === GLOBSTAR || b[j] === GLOBSTAR) value = at(i + 1, j) || at(i, j + 1);\n else value = segmentsIntersect(a[i] ?? '', b[j] ?? '') && at(i + 1, j + 1);\n table[i * width + j] = value ? 1 : 0;\n }\n }\n return at(0, 0);\n}\n\n/**\n * True when some path could belong to both entries. Case-folded, so a case-insensitive checkout\n * cannot hide an overlap.\n */\nexport function overlaps(a: ScopeEntry, b: ScopeEntry): boolean {\n return sequencesIntersect(a.segments, b.segments);\n}\n\n/** The first overlapping pair across two scope lists, for a refusal that names both entries. */\nexport function firstOverlap(as: readonly ScopeEntry[], bs: readonly ScopeEntry[]): readonly [ScopeEntry, ScopeEntry] | undefined {\n for (const a of as) for (const b of bs) if (overlaps(a, b)) return [a, b];\n return undefined;\n}\n\n/**\n * True when `scope` may write anything under the serial-only path. A serial path owns its whole\n * subtree like any entry, so this is overlap with it.\n */\nexport function reaches(scope: ScopeEntry, serialPath: ScopeEntry): boolean {\n return overlaps(scope, serialPath);\n}\n\n/** Whether a scope's segments match a literal path; the path side is never read as a pattern. */\nfunction pathMatches(scope: readonly string[], path: readonly string[]): boolean {\n let row = new Array<boolean>(path.length + 1).fill(false);\n row[path.length] = true;\n for (let i = scope.length - 1; i >= 0; i--) {\n const segment = scope[i] ?? '';\n const next = new Array<boolean>(path.length + 1).fill(false);\n for (let j = path.length; j >= 0; j--) {\n if (segment === GLOBSTAR) next[j] = (row[j] ?? false) || (j < path.length && (next[j + 1] ?? false));\n else next[j] = j < path.length && segmentMatches(codePoints(segment), codePoints(path[j] ?? '')) && (row[j + 1] ?? false);\n }\n row = next;\n }\n return row[0] ?? false;\n}\n\n/**\n * The changed paths no scope entry covers, in input order. Matched exactly (after NFC), not\n * case-folded: a path that differs only in case is reported, which errs toward evidence.\n */\nexport function conforms(changedPaths: readonly string[], scopes: readonly ScopeEntry[]): string[] {\n return changedPaths.filter(path => {\n const segments = path.normalize('NFC').split('/').filter(segment => segment !== '');\n return !scopes.some(scope => pathMatches(scope.segments, segments));\n });\n}\n","/**\n * Runtime state projection (docs/design/runtime-coordination.md §4.3, §4.4, §5.1, §5.3).\n *\n * Replay folds immutable events into this projection. `checkEvent` decides whether an event is\n * a legal next step without mutating anything; the controller calls it before appending, and\n * replay calls it before applying, so an illegal transition in a ledger pauses the project\n * instead of being silently absorbed. Writer ownership is its own projection: no technical\n * decision about an assignment releases it — only proven archive does.\n *\n * Phase 2 (docs/design/runtime-coordination-phase2.md §4, §5.3) extends a writable reservation\n * with a writer lease on its own worktree. Leases may coexist only with each other, within the\n * fixed cap and with provably disjoint scopes; a writer in Lead's workspace still excludes every\n * other writer. Replay re-checks those rules, so a ledger can never hold two colliding writers.\n */\nimport { MAX_WORKTREE_LEASES } from '../../shared/limits.js';\nimport type { AssignmentCreateInputV1, CandidateRefV1 } from '../contracts/assignment.js';\nimport type { PeerReportReceiptV1 } from '../contracts/peer.js';\nimport type { GateResultV1, RuntimeEventOf, RuntimeEventV1 } from '../events/schema.js';\nimport { firstOverlap, parseScopes, reaches, type ScopeEntry } from './scope.js';\n\nexport type AssignmentState =\n | 'draft' | 'dispatching' | 'active' | 'questioned' | 'blocked' | 'handed-back' | 'rework'\n | 'awaiting-permission' | 'accepted' | 'rejected' | 'abandoned' | 'uncertain';\nexport type ReportingState = 'closed' | 'open' | 'consumed' | 'uncertain';\nexport type Closure = 'open' | 'closing' | 'closed' | 'uncertain';\nexport type OwnershipState = 'reserved' | 'held' | 'releasing' | 'released' | 'uncertain';\n\nexport const TERMINAL_STATES: readonly AssignmentState[] = ['accepted', 'rejected', 'abandoned'];\n\n/** Decided, with nothing left to close: its Peer is archived, or none was ever placed. */\nexport function settled(view: AssignmentView): boolean {\n return TERMINAL_STATES.includes(view.state) && (view.closure === 'closed' || view.peerAgentId === undefined);\n}\n\nexport interface AcceptedReport {\n readonly generation: number;\n readonly tool: 'ask' | 'handoff';\n readonly requestId: string;\n readonly fingerprint: string;\n readonly receipt: PeerReportReceiptV1;\n readonly report: Readonly<Record<string, unknown>>;\n readonly eventId: string;\n}\n\nexport interface GateRun {\n readonly gateRunId: string;\n readonly candidate: CandidateRefV1;\n readonly command: string;\n readonly status: 'running' | 'finished' | 'uncertain';\n readonly result?: GateResultV1;\n}\n\n/**\n * A writer lease on a runtime-created worktree. Its state is the ownership state it extends:\n * reserved → held → releasing → released, or uncertain.\n */\nexport interface WriterLease {\n readonly workspaceId: string;\n /** The requested branch until the worktree exists, then the branch Paseo resolved. */\n readonly branch: string;\n readonly baseCommit: string;\n readonly scopes: readonly string[];\n readonly serialOnly: readonly string[];\n readonly epoch: number;\n readonly worktreePath?: string;\n /** Peers this lease was reclaimed from; none of them may report again. */\n readonly priorAgentIds: readonly string[];\n}\n\nexport interface WriterOwnership {\n readonly assignmentId: string;\n readonly workspaceId: string;\n readonly baseCommit: string;\n readonly agentId?: string;\n readonly state: OwnershipState;\n readonly lease?: WriterLease;\n}\n\nexport type WorkspaceCreateState = 'requested' | 'succeeded' | 'failed' | 'uncertain' | 'refused';\nexport type WorkspaceCloseState = 'open' | 'requested' | 'succeeded' | 'failed' | 'uncertain';\n\n/** A runtime-requested Paseo worktree workspace, one per worktree assignment. */\nexport interface WorkspaceRecord {\n readonly assignmentId: string;\n readonly workspaceId: string;\n readonly idempotencyKey: string;\n readonly baseCommit: string;\n readonly branchName: string;\n readonly worktreeSlug: string;\n readonly create: WorkspaceCreateState;\n readonly createIntentId: string;\n readonly worktreePath?: string;\n readonly branch?: string;\n readonly headCommit?: string;\n readonly close: WorkspaceCloseState;\n readonly closeIntentId?: string;\n readonly discardUncommitted?: boolean;\n readonly archivedAt?: string;\n /** False is cleanup evidence: Paseo archived the record but the directory is still there. */\n readonly directoryRemoved?: boolean;\n readonly eventIds: readonly string[];\n}\n\nexport interface AssignmentView {\n readonly id: string;\n readonly input: AssignmentCreateInputV1;\n readonly leadAgentId: string;\n readonly leadProviderId: string;\n readonly state: AssignmentState;\n readonly closure: Closure;\n readonly reportingGeneration: number;\n readonly reportingState: ReportingState;\n /** The generation whose single `run()` has been requested; one run per generation. */\n readonly runGeneration: number;\n readonly peerProviderId?: string;\n readonly workspaceId?: string;\n readonly peerAgentId?: string;\n readonly observedProviderId?: string;\n readonly observedModel?: string;\n /** Lead's thinking choice at dispatch and its reason; absent when the profile's option was kept. */\n readonly chosenThinking?: string;\n readonly thinkingReason?: string;\n /** The thinking option the bound Peer reported when it was created. */\n readonly observedThinking?: string;\n readonly candidate?: CandidateRefV1;\n readonly inspectedCommit?: string;\n readonly reports: readonly AcceptedReport[];\n readonly gates: readonly GateRun[];\n readonly awaitingPermissionId?: string;\n /** Intents without a terminal result, keyed by intent id. Recovery works from these. */\n readonly openIntents: Readonly<Record<string, RuntimeEventV1['type']>>;\n readonly decision?: { readonly type: 'accepted' | 'rejected' | 'abandoned'; readonly eventId: string };\n /** Changed paths of the current candidate outside its lease's scopes: evidence, not containment. */\n readonly scopeExceeded?: { readonly candidateCommit: string; readonly paths: readonly string[]; readonly eventId: string };\n readonly eventIds: readonly string[];\n}\n\nexport interface NoticeView {\n readonly noticeId: string;\n readonly assignmentId?: string;\n readonly kind: string;\n readonly class: 'record' | 'owner' | 'operator' | 'page';\n readonly state: 'pending' | 'sent' | 'failed' | 'uncertain';\n readonly eventId: string;\n}\n\nexport interface ProjectState {\n readonly projectId: string;\n binding?: { readonly canonicalRoot: string; readonly gitCommonDir: string };\n ownershipConflict?: { readonly leadAgentIds: readonly string[]; readonly eventId: string };\n readonly assignments: Map<string, AssignmentView>;\n readonly ownership: Map<string, WriterOwnership>;\n /** Runtime-requested worktree workspaces, keyed by assignment id. */\n readonly workspaces: Map<string, WorkspaceRecord>;\n readonly notices: Map<string, NoticeView>;\n lastSequence: number;\n}\n\nexport interface Violation {\n readonly eventId: string;\n readonly type: string;\n readonly message: string;\n}\n\nexport function emptyProjectState(projectId: string): ProjectState {\n return { projectId, assignments: new Map(), ownership: new Map(), workspaces: new Map(), notices: new Map(), lastSequence: 0 };\n}\n\n/** Any writer ownership in the project other than released, optionally ignoring one assignment. */\nexport function activeWriter(state: ProjectState, except?: string): WriterOwnership | undefined {\n for (const owner of state.ownership.values()) if (owner.state !== 'released' && owner.assignmentId !== except) return owner;\n return undefined;\n}\n\n/** A writer in Lead's own workspace that is not released: it excludes every other writer. */\nexport function leadWorkspaceWriter(state: ProjectState, except?: string): WriterOwnership | undefined {\n for (const owner of state.ownership.values()) {\n if (owner.state !== 'released' && owner.lease === undefined && owner.assignmentId !== except) return owner;\n }\n return undefined;\n}\n\n/** Worktree leases that are not released. */\nexport function activeLeases(state: ProjectState, except?: string): (WriterOwnership & { readonly lease: WriterLease })[] {\n return [...state.ownership.values()].filter((owner): owner is WriterOwnership & { readonly lease: WriterLease } =>\n owner.lease !== undefined && owner.state !== 'released' && owner.assignmentId !== except);\n}\n\nexport type LeaseCollision =\n | { readonly code: 'writer_exclusive'; readonly message: string }\n | { readonly code: 'writer_uncertain'; readonly message: string }\n | { readonly code: 'lease_cap'; readonly message: string }\n | { readonly code: 'scope_not_canonical'; readonly message: string }\n | { readonly code: 'scope_overlap'; readonly message: string }\n | { readonly code: 'serial_path'; readonly message: string };\n\nfunction parsed(raws: readonly string[], empty: 'whole' | 'none'): readonly ScopeEntry[] | string {\n if (raws.length === 0 && empty === 'none') return [];\n const result = parseScopes(raws);\n return result.ok ? result.entries : `${result.item} ${result.reason}`;\n}\n\n/**\n * The §5.3 collision rules for a new worktree lease, decided on one projection. The controller\n * runs them before recording anything; replay runs them again on `lease.reserved`.\n */\nexport function leaseCollision(state: ProjectState, assignmentId: string, request: { readonly scopes: readonly string[]; readonly serialOnly: readonly string[] }): LeaseCollision | undefined {\n const exclusive = leadWorkspaceWriter(state, assignmentId);\n if (exclusive !== undefined) return { code: 'writer_exclusive', message: `Assignment ${exclusive.assignmentId} writes in Lead's workspace (${exclusive.state}); it excludes every other writer.` };\n const leases = activeLeases(state, assignmentId);\n const uncertain = leases.find(lease => lease.state === 'uncertain');\n if (uncertain !== undefined) return { code: 'writer_uncertain', message: `The writer of ${uncertain.assignmentId} is uncertain; no new writer starts until it is proven stopped.` };\n if (leases.length >= MAX_WORKTREE_LEASES) return { code: 'lease_cap', message: `${String(MAX_WORKTREE_LEASES)} worktree leases are already held in this project.` };\n const mine = parsed(request.scopes, 'whole');\n if (typeof mine === 'string') return { code: 'scope_not_canonical', message: `writeScope item ${mine}.` };\n const serial = parsed(request.serialOnly, 'none');\n if (typeof serial === 'string') return { code: 'scope_not_canonical', message: `serialOnly item ${serial}.` };\n const others = leases.map(lease => ({ lease, scopes: parsed(lease.lease.scopes, 'whole'), serial: parsed(lease.lease.serialOnly, 'none') }));\n for (const other of others) {\n // A recorded lease that no longer parses cannot be proven disjoint.\n if (typeof other.scopes === 'string' || typeof other.serial === 'string') {\n return { code: 'scope_overlap', message: `The scopes of ${other.lease.assignmentId} cannot be compared.` };\n }\n const overlap = firstOverlap(mine, other.scopes);\n if (overlap !== undefined) return { code: 'scope_overlap', message: `${overlap[0].text} overlaps ${overlap[1].text} held by ${other.lease.assignmentId}.` };\n }\n const union = [...serial, ...others.flatMap(other => (typeof other.serial === 'string' ? [] : other.serial))];\n for (const path of union) {\n if (!mine.some(scope => reaches(scope, path))) continue;\n const holder = others.find(other => typeof other.scopes !== 'string' && other.scopes.some(scope => reaches(scope, path)));\n if (holder !== undefined) return { code: 'serial_path', message: `${path.text} is serial-only and ${holder.lease.assignmentId} already writes under it.` };\n }\n return undefined;\n}\n\ntype Check = string | undefined;\n\nfunction need(condition: boolean, message: string): Check {\n return condition ? undefined : message;\n}\n\nfunction assignmentOf(state: ProjectState, event: RuntimeEventV1): AssignmentView | undefined {\n return event.assignmentId === undefined ? undefined : state.assignments.get(event.assignmentId);\n}\n\nfunction inState(assignment: AssignmentView, allowed: readonly AssignmentState[], action: string): Check {\n return need(allowed.includes(assignment.state), `Cannot ${action} while the assignment is ${assignment.state}.`);\n}\n\n/** Why `event` may not follow `state`, or undefined when it is a legal next step. */\nexport function checkEvent(state: ProjectState, event: RuntimeEventV1): Check {\n if (event.projectId !== state.projectId) return 'Event belongs to another project.';\n switch (event.type) {\n case 'project.bound': return need(state.binding === undefined, 'The project is already bound.');\n case 'project.rebound': return need(state.binding !== undefined, 'Only a bound project can be rebound.');\n case 'project.ownership-conflict': return undefined;\n case 'project.ownership-resolved': return need(state.ownershipConflict !== undefined, 'There is no ownership conflict to resolve.');\n case 'notice.pending': return need(!state.notices.has(event.data.noticeId), `Notice ${event.data.noticeId} already exists.`);\n case 'notice.sent': case 'notice.failed': case 'notice.uncertain':\n return need(state.notices.has(event.data.noticeId), `Unknown notice ${event.data.noticeId}.`);\n default: break;\n }\n if (event.type === 'assignment.created') {\n if (event.assignmentId === undefined) return 'An assignment event needs an assignment id.';\n return need(!state.assignments.has(event.assignmentId), `Assignment ${event.assignmentId} already exists.`);\n }\n const assignment = assignmentOf(state, event);\n if (assignment === undefined) return `Event ${event.type} names no known assignment.`;\n const owner = state.ownership.get(assignment.id);\n const writable = assignment.input.mode === 'writable';\n switch (event.type) {\n case 'assignment.dispatch-requested':\n return inState(assignment, ['draft'], 'dispatch')\n ?? need(state.ownershipConflict === undefined, 'Dispatch is paused by a Lead ownership conflict.')\n // The dispatch mode is not known yet: a writer in Lead's workspace excludes both modes,\n // and `agent.create-requested` decides the rest once the mode is recorded.\n ?? need(!writable || leadWorkspaceWriter(state) === undefined, 'Another writer still owns this project.');\n case 'ownership.reserved':\n return need(writable, 'A read-only assignment reserves no writer ownership.')\n ?? inState(assignment, ['dispatching'], 'reserve ownership')\n ?? need(leadWorkspaceWriter(state) === undefined, 'Another writer still owns this project.');\n case 'agent.create-requested': {\n const lease = owner?.lease;\n return inState(assignment, ['dispatching'], 'create the Peer')\n ?? need(!writable || owner?.state === 'reserved', 'A writable Peer is created only after ownership is reserved.')\n ?? need(assignment.peerAgentId === undefined, 'This assignment already has a Peer.')\n // A writer in Lead's workspace excludes every other writer, leased or not.\n ?? need(!writable || lease !== undefined || activeWriter(state, assignment.id) === undefined, 'Another writer still owns this project.')\n ?? need(lease === undefined || (state.workspaces.get(assignment.id)?.create === 'succeeded' && event.data.workspaceId === lease.workspaceId), 'A leased Peer is created only in its proven worktree.');\n }\n case 'agent.create-succeeded': case 'agent.create-failed': case 'agent.create-uncertain':\n return need(assignment.openIntents[event.data.intentId] === 'agent.create-requested'\n || (assignment.state === 'uncertain' && event.type !== 'agent.create-uncertain'), 'No unresolved create intent matches.');\n case 'binding.refused':\n return inState(assignment, ['dispatching'], 'refuse the Peer binding')\n ?? need(assignment.peerAgentId === event.data.agentId, 'The refusal names a different agent than the one created.');\n case 'binding.published':\n return inState(assignment, ['dispatching'], 'bind the Peer')\n ?? need(assignment.peerAgentId === event.data.agentId, 'The binding names a different agent than the one created.');\n case 'ownership.held':\n return need(owner?.state === 'reserved', 'Only reserved ownership becomes held.')\n ?? need(assignment.peerAgentId === event.data.agentId && assignment.observedProviderId !== undefined, 'Ownership is held only by the bound Peer.');\n case 'reporting.generation-opened': {\n const from: Record<typeof event.data.turn, readonly AssignmentState[]> = {\n initial: ['dispatching'], answer: ['questioned'], 'follow-up': ['blocked'], rework: ['rework'],\n };\n return inState(assignment, from[event.data.turn], `open a ${event.data.turn} reporting generation`)\n ?? need(event.data.generation === assignment.reportingGeneration + 1, 'Reporting generations increase by exactly one.')\n ?? need(assignment.reportingState === 'closed' || assignment.reportingState === 'consumed', 'The previous reporting generation is not terminal.')\n ?? need(assignment.observedProviderId !== undefined, 'No proven Peer binding exists.')\n ?? need(!writable || owner?.state === 'held', 'A writable Peer needs held ownership before any turn.');\n }\n case 'run.requested':\n return need(event.data.generation === assignment.reportingGeneration && assignment.reportingState === 'open', 'A run must use the open reporting generation.')\n ?? need(assignment.runGeneration < event.data.generation, 'This reporting generation already has its run.')\n ?? need(!Object.values(assignment.openIntents).includes('run.requested'), 'Another run is still unresolved.');\n case 'run.succeeded': case 'run.failed': case 'run.uncertain':\n return need(assignment.openIntents[event.data.intentId] === 'run.requested'\n || (assignment.state === 'uncertain' && event.type !== 'run.uncertain'), 'No unresolved run intent matches.');\n case 'report.accepted':\n return need(event.data.generation === assignment.reportingGeneration, 'The report names a stale generation.')\n ?? need(assignment.reportingState === 'open' || assignment.reportingState === 'uncertain', 'The reporting generation is not open.')\n ?? inState(assignment, ['active', 'awaiting-permission', 'uncertain'], 'accept a report');\n case 'report.refused': return undefined;\n case 'report.missing':\n return need(event.data.generation === assignment.reportingGeneration, 'Missing report names a stale generation.')\n ?? need(assignment.reportingState === 'open' || assignment.reportingState === 'uncertain', 'The reporting generation is not open.')\n ?? inState(assignment, ['active', 'awaiting-permission', 'uncertain'], 'record a missing report');\n case 'report.uncertain':\n return need(event.data.generation === assignment.reportingGeneration, 'Uncertain report names a stale generation.');\n case 'permission.awaiting':\n return inState(assignment, ['active'], 'await a reporting permission')\n ?? need(event.data.generation === assignment.reportingGeneration && assignment.reportingState === 'open', 'Permission applies only to the open generation.');\n case 'permission.resolved':\n return inState(assignment, ['awaiting-permission'], 'resolve a permission')\n ?? need(assignment.awaitingPermissionId === event.data.permissionRequestId, 'A different permission request is outstanding.');\n case 'assignment.answered': return inState(assignment, ['questioned', 'blocked'], 'answer');\n case 'assignment.rework-requested': return inState(assignment, ['handed-back'], 'request rework');\n case 'assignment.accepted': return inState(assignment, ['handed-back'], 'accept');\n case 'assignment.rejected': return inState(assignment, ['handed-back'], 'reject');\n case 'assignment.abandoned':\n if (assignment.state === 'uncertain') {\n return need(assignment.reportingState !== 'open' && assignment.reportingState !== 'uncertain', 'Abandon an uncertain assignment only after its generation is terminal.')\n ?? need(assignment.closure === 'closing' || assignment.closure === 'uncertain', 'Abandon an uncertain assignment only after archive is requested.');\n }\n return inState(assignment, ['draft', 'questioned', 'blocked', 'handed-back', 'rework'], 'abandon');\n case 'assignment.close-requested':\n return need(TERMINAL_STATES.includes(assignment.state) || assignment.state === 'uncertain', 'Close an assignment only after a technical decision or while it is uncertain.')\n ?? need(assignment.closure === 'open' || assignment.closure === 'uncertain', 'The assignment is already closing or closed.');\n case 'archive.requested':\n return need(assignment.closure === 'closing' || assignment.closure === 'uncertain', 'Archive follows a close request.')\n ?? need(assignment.peerAgentId === event.data.agentId, 'Archive names a different agent.')\n ?? need(!Object.values(assignment.openIntents).includes('archive.requested'), 'Another archive is still unresolved.');\n case 'archive.succeeded': case 'archive.failed': case 'archive.uncertain':\n return need(assignment.openIntents[event.data.intentId] === 'archive.requested'\n || (assignment.closure === 'uncertain' && event.type !== 'archive.uncertain'), 'No unresolved archive intent matches.');\n case 'ownership.releasing':\n return need(owner?.state === 'held', 'Only held ownership starts releasing.')\n ?? need(assignment.closure === 'closing', 'Release starts only after a close request.');\n case 'ownership.released':\n return need(owner?.state === 'releasing' || owner?.state === 'uncertain', 'Only releasing or uncertain ownership is released.')\n ?? need(assignment.closure === 'closed', 'Ownership is released only after archive is proven.');\n case 'ownership.uncertain':\n return need(owner !== undefined && owner.state !== 'released', 'No unreleased ownership to mark uncertain.');\n case 'lease.reserved': {\n const collision = leaseCollision(state, assignment.id, event.data);\n return need(writable, 'A read-only assignment holds no lease.')\n ?? inState(assignment, ['dispatching'], 'reserve a lease')\n ?? need(owner?.state === 'reserved' && owner.lease === undefined && owner.agentId === undefined, 'A lease extends a fresh reservation.')\n ?? need(owner?.workspaceId === event.data.workspaceId && owner.baseCommit === event.data.baseCommit, 'The lease names a different workspace or base than the reservation.')\n ?? (collision === undefined ? undefined : `${collision.code}: ${collision.message}`);\n }\n case 'workspace.create-requested':\n return inState(assignment, ['dispatching'], 'request a worktree')\n ?? need(owner?.state === 'reserved' && owner.lease?.workspaceId === event.data.workspaceId && owner.lease.baseCommit === event.data.baseCommit, 'A worktree is requested only for its reserved lease.')\n ?? need(!state.workspaces.has(assignment.id), 'This assignment already requested its worktree.');\n case 'workspace.create-succeeded': case 'workspace.create-failed': case 'workspace.create-uncertain': case 'workspace.create-refused': {\n const record = state.workspaces.get(assignment.id);\n const from = event.type === 'workspace.create-uncertain' ? ['requested'] : ['requested', 'uncertain'];\n return need(record !== undefined && record.createIntentId === event.data.intentId && from.includes(record.create), 'No unresolved worktree create matches.')\n ?? need(!('workspaceId' in event.data) || event.data.workspaceId === record?.workspaceId, 'The result names a different workspace.');\n }\n case 'lease.reclaimed': {\n const check = reclaimCheck(state, assignment.id);\n if (!check.ok) return check.message;\n return need(event.data.fromEpoch === check.value.lease.epoch && event.data.toEpoch === event.data.fromEpoch + 1, 'A reclaim moves the lease to exactly the next epoch.')\n ?? need(event.data.priorAgentId === check.value.prior, 'The reclaim names a different writer than the lease holder.');\n }\n case 'scope.exceeded':\n return need(owner?.lease !== undefined, 'Only a leased candidate has scopes to exceed.')\n ?? need(assignment.candidate?.commit === event.data.candidateCommit, 'The evidence names a different candidate.');\n case 'workspace.close-requested': {\n const record = state.workspaces.get(assignment.id);\n return need(record?.workspaceId === event.data.workspaceId && (record.create === 'succeeded' || record.create === 'refused'), 'Only a created worktree is closed.')\n ?? need(record?.close === 'open' || record?.close === 'failed', 'The worktree is already closing or closed.')\n ?? need(owner?.state === 'released', 'A worktree closes only after its writer is proven released.')\n ?? need(!event.data.discardUncommitted || event.data.reason !== undefined, 'Discarding uncommitted work needs a reason.');\n }\n case 'workspace.close-succeeded': case 'workspace.close-failed': case 'workspace.close-uncertain': {\n const record = state.workspaces.get(assignment.id);\n const from = event.type === 'workspace.close-uncertain' ? ['requested'] : ['requested', 'uncertain'];\n return need(record !== undefined && record.closeIntentId === event.data.intentId && from.includes(record.close) && record.workspaceId === event.data.workspaceId, 'No unresolved worktree close matches.');\n }\n case 'gate.requested':\n return inState(assignment, ['handed-back'], 'run a gate')\n ?? need(assignment.candidate !== undefined && assignment.candidate.commit === event.data.candidate.commit, 'A gate runs only against the projected candidate.')\n ?? need(!assignment.gates.some(gate => gate.status === 'running'), 'Another gate is still running.');\n case 'gate.finished':\n // A late sidecar may still settle a gate recorded as uncertain after a restart.\n return need(assignment.gates.some(gate => gate.gateRunId === event.data.result.id && gate.status !== 'finished'), 'No unsettled gate matches.');\n case 'gate.uncertain':\n return need(assignment.gates.some(gate => gate.gateRunId === event.data.gateRunId && gate.status === 'running'), 'No running gate matches.');\n default: {\n const exhaustive: never = event;\n return `Unhandled event ${(exhaustive as RuntimeEventV1).type}.`;\n }\n }\n}\n\nfunction update(state: ProjectState, id: string, change: Partial<AssignmentView>, event: RuntimeEventV1): void {\n const current = state.assignments.get(id);\n if (current === undefined) return;\n state.assignments.set(id, { ...current, ...change, eventIds: [...current.eventIds, event.id] });\n}\n\nfunction withIntent(view: AssignmentView, intentId: string, type: RuntimeEventV1['type'] | undefined): Record<string, RuntimeEventV1['type']> {\n const next = { ...view.openIntents };\n if (type === undefined) Reflect.deleteProperty(next, intentId);\n else next[intentId] = type;\n return next;\n}\n\nfunction withoutPermission(view: AssignmentView): AssignmentView {\n const copy: { -readonly [K in keyof AssignmentView]?: AssignmentView[K] } = { ...view };\n delete copy.awaitingPermissionId;\n return copy as AssignmentView;\n}\n\nfunction setOwner(state: ProjectState, id: string, change: Partial<WriterOwnership>): void {\n const current = state.ownership.get(id);\n if (current !== undefined) state.ownership.set(id, { ...current, ...change });\n}\n\nfunction setLease(state: ProjectState, id: string, change: Partial<WriterLease>): void {\n const current = state.ownership.get(id);\n if (current?.lease !== undefined) state.ownership.set(id, { ...current, lease: { ...current.lease, ...change } });\n}\n\nfunction setWorkspace(state: ProjectState, id: string, change: Partial<WorkspaceRecord>, event: RuntimeEventV1): void {\n const current = state.workspaces.get(id);\n if (current !== undefined) state.workspaces.set(id, { ...current, ...change, eventIds: [...current.eventIds, event.id] });\n}\n\n/** A reclaim ends the prior Peer's binding: the assignment dispatches again inside its lease. */\nfunction reclaimed(view: AssignmentView, event: RuntimeEventV1): AssignmentView {\n const copy: { -readonly [K in keyof AssignmentView]?: AssignmentView[K] } = { ...withoutPermission(view) };\n delete copy.peerAgentId;\n delete copy.observedProviderId;\n delete copy.observedModel;\n delete copy.observedThinking;\n return { ...(copy as AssignmentView), state: 'dispatching', reportingState: 'consumed', eventIds: [...view.eventIds, event.id] };\n}\n\nfunction applyReport(state: ProjectState, view: AssignmentView, event: RuntimeEventOf<'report.accepted'>): void {\n const report: AcceptedReport = {\n generation: event.data.generation, tool: event.data.tool, requestId: event.data.requestId,\n fingerprint: event.data.fingerprint, receipt: event.data.receipt, report: event.data.report, eventId: event.id,\n };\n update(state, view.id, {\n state: event.data.receipt.assignmentState,\n reportingState: 'consumed',\n reports: [...view.reports, report],\n ...(event.data.candidate === undefined ? {} : { candidate: event.data.candidate }),\n ...(event.data.inspectedCommit === undefined ? {} : { inspectedCommit: event.data.inspectedCommit }),\n }, event);\n // Scope evidence belongs to one candidate; a new candidate replaces it (or not, if in scope).\n const next = state.assignments.get(view.id);\n if (next?.scopeExceeded !== undefined && event.data.candidate !== undefined && event.data.candidate.commit !== next.scopeExceeded.candidateCommit) {\n const copy: { -readonly [K in keyof AssignmentView]?: AssignmentView[K] } = { ...next };\n delete copy.scopeExceeded;\n state.assignments.set(view.id, copy as AssignmentView);\n }\n}\n\n/** Folds one already-checked event into the projection. */\nexport function applyEvent(state: ProjectState, event: RuntimeEventV1): void {\n state.lastSequence = Math.max(state.lastSequence, event.sequence);\n switch (event.type) {\n case 'project.bound': case 'project.rebound':\n state.binding = { canonicalRoot: event.data.canonicalRoot, gitCommonDir: event.data.gitCommonDir };\n return;\n case 'project.ownership-conflict':\n state.ownershipConflict = { leadAgentIds: event.data.leadAgentIds, eventId: event.id };\n return;\n case 'project.ownership-resolved':\n delete state.ownershipConflict;\n return;\n case 'notice.pending':\n state.notices.set(event.data.noticeId, {\n noticeId: event.data.noticeId, kind: event.data.kind, class: event.data.class, state: 'pending', eventId: event.id,\n ...(event.assignmentId === undefined ? {} : { assignmentId: event.assignmentId }),\n });\n return;\n case 'notice.sent': case 'notice.failed': case 'notice.uncertain': {\n const notice = state.notices.get(event.data.noticeId);\n if (notice !== undefined) state.notices.set(notice.noticeId, { ...notice, state: event.type === 'notice.sent' ? 'sent' : event.type === 'notice.failed' ? 'failed' : 'uncertain' });\n return;\n }\n case 'assignment.created':\n if (event.assignmentId === undefined) return;\n state.assignments.set(event.assignmentId, {\n id: event.assignmentId, input: event.data.input, leadAgentId: event.data.leadAgentId, leadProviderId: event.data.leadProviderId,\n state: 'draft', closure: 'open', reportingGeneration: 0, reportingState: 'closed', runGeneration: 0, reports: [], gates: [],\n openIntents: {}, eventIds: [event.id],\n });\n return;\n default: break;\n }\n const view = assignmentOf(state, event);\n if (view === undefined) return;\n const id = view.id;\n switch (event.type) {\n case 'assignment.dispatch-requested':\n update(state, id, {\n state: 'dispatching', peerProviderId: event.data.peerProviderId, workspaceId: event.data.workspaceId,\n ...(event.data.thinking === undefined ? {} : { chosenThinking: event.data.thinking }),\n ...(event.data.thinkingReason === undefined ? {} : { thinkingReason: event.data.thinkingReason }),\n }, event); return;\n case 'ownership.reserved':\n state.ownership.set(id, { assignmentId: id, workspaceId: event.data.workspaceId, baseCommit: event.data.baseCommit, state: 'reserved' });\n update(state, id, {}, event); return;\n case 'agent.create-requested':\n update(state, id, { openIntents: withIntent(view, event.data.intentId, event.type) }, event); return;\n case 'agent.create-succeeded':\n update(state, id, { peerAgentId: event.data.agentId, openIntents: withIntent(view, event.data.intentId, undefined), ...(view.state === 'uncertain' ? { state: 'dispatching' } : {}) }, event); return;\n case 'agent.create-failed': {\n // Proven: no agent exists, so a reservation without an agent cannot still be writing.\n const owner = state.ownership.get(id);\n if (owner?.state === 'reserved' || (owner?.state === 'uncertain' && owner.agentId === undefined)) setOwner(state, id, { state: 'released' });\n update(state, id, { state: 'blocked', openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n }\n case 'agent.create-uncertain':\n setOwner(state, id, { state: 'uncertain' });\n update(state, id, { state: 'uncertain' }, event); return;\n case 'binding.refused':\n setOwner(state, id, { state: 'uncertain', agentId: event.data.agentId });\n update(state, id, { state: 'uncertain' }, event); return;\n case 'binding.published':\n update(state, id, {\n observedProviderId: event.data.providerId, observedModel: event.data.model, workspaceId: event.data.workspaceId,\n ...(event.data.thinking === undefined ? {} : { observedThinking: event.data.thinking }),\n }, event); return;\n case 'ownership.held':\n setOwner(state, id, { state: 'held', agentId: event.data.agentId });\n update(state, id, {}, event); return;\n case 'reporting.generation-opened':\n update(state, id, { reportingGeneration: event.data.generation, reportingState: 'open' }, event); return;\n case 'run.requested':\n // Active is published with the run intent, before the external call, so a first tool call\n // can never race an internal dispatching, questioned, blocked or rework state.\n update(state, id, { state: 'active', runGeneration: event.data.generation, openIntents: withIntent(view, event.data.intentId, event.type) }, event); return;\n case 'run.succeeded':\n update(state, id, { openIntents: withIntent(view, event.data.intentId, undefined), ...(view.state === 'uncertain' ? { state: 'active', reportingState: 'open' } : {}) }, event); return;\n case 'run.failed':\n update(state, id, { state: 'blocked', reportingState: 'consumed', openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n case 'run.uncertain':\n update(state, id, { state: 'uncertain', reportingState: 'uncertain' }, event); return;\n case 'report.accepted': applyReport(state, view, event); return;\n case 'report.refused': update(state, id, {}, event); return;\n case 'report.missing':\n state.assignments.set(id, { ...withoutPermission(view), state: 'blocked', reportingState: 'consumed', eventIds: [...view.eventIds, event.id] });\n return;\n case 'report.uncertain':\n update(state, id, { state: 'uncertain', reportingState: 'uncertain' }, event); return;\n case 'permission.awaiting':\n update(state, id, { state: 'awaiting-permission', awaitingPermissionId: event.data.permissionRequestId }, event); return;\n case 'permission.resolved':\n state.assignments.set(id, { ...withoutPermission(view), state: 'active', eventIds: [...view.eventIds, event.id] });\n return;\n case 'assignment.answered': update(state, id, {}, event); return;\n case 'assignment.rework-requested': update(state, id, { state: 'rework' }, event); return;\n case 'assignment.accepted': case 'assignment.rejected': case 'assignment.abandoned': {\n const type = event.type === 'assignment.accepted' ? 'accepted' : event.type === 'assignment.rejected' ? 'rejected' : 'abandoned';\n update(state, id, { state: type, decision: { type, eventId: event.id } }, event); return;\n }\n case 'assignment.close-requested': update(state, id, { closure: 'closing' }, event); return;\n case 'archive.requested': update(state, id, { openIntents: withIntent(view, event.data.intentId, event.type) }, event); return;\n case 'archive.succeeded': update(state, id, { closure: 'closed', openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n case 'archive.failed': update(state, id, { closure: 'uncertain', openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n case 'archive.uncertain': update(state, id, { closure: 'uncertain' }, event); return;\n case 'ownership.releasing': setOwner(state, id, { state: 'releasing' }); update(state, id, {}, event); return;\n case 'ownership.released': setOwner(state, id, { state: 'released' }); update(state, id, {}, event); return;\n case 'ownership.uncertain': setOwner(state, id, { state: 'uncertain' }); update(state, id, {}, event); return;\n case 'lease.reserved':\n setOwner(state, id, {\n lease: {\n workspaceId: event.data.workspaceId, branch: event.data.branch, baseCommit: event.data.baseCommit, scopes: event.data.scopes,\n serialOnly: event.data.serialOnly, epoch: event.data.epoch, priorAgentIds: [],\n },\n });\n update(state, id, {}, event); return;\n case 'workspace.create-requested':\n state.workspaces.set(id, {\n assignmentId: id, workspaceId: event.data.workspaceId, idempotencyKey: event.data.idempotencyKey, baseCommit: event.data.baseCommit,\n branchName: event.data.branchName, worktreeSlug: event.data.worktreeSlug, create: 'requested', createIntentId: event.data.intentId,\n close: 'open', eventIds: [event.id],\n });\n update(state, id, { openIntents: withIntent(view, event.data.intentId, event.type) }, event); return;\n case 'workspace.create-succeeded':\n setWorkspace(state, id, { create: 'succeeded', worktreePath: event.data.worktreePath, branch: event.data.branch, headCommit: event.data.headCommit }, event);\n setLease(state, id, { worktreePath: event.data.worktreePath, branch: event.data.branch });\n update(state, id, { openIntents: withIntent(view, event.data.intentId, undefined), ...(view.state === 'uncertain' ? { state: 'dispatching' } : {}) }, event); return;\n case 'workspace.create-failed': case 'workspace.create-refused':\n // No Peer was ever placed in the worktree, so the lease cannot still be writing.\n setWorkspace(state, id, { create: event.type === 'workspace.create-failed' ? 'failed' : 'refused' }, event);\n setOwner(state, id, { state: 'released' });\n update(state, id, { state: 'blocked', openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n case 'workspace.create-uncertain':\n setWorkspace(state, id, { create: 'uncertain' }, event);\n setOwner(state, id, { state: 'uncertain' });\n update(state, id, { state: 'uncertain' }, event); return;\n case 'lease.reclaimed': {\n const owner = state.ownership.get(id);\n const lease = owner?.lease;\n if (owner === undefined || lease === undefined) return;\n const next: { -readonly [K in keyof WriterOwnership]?: WriterOwnership[K] } = { ...owner, state: 'reserved', lease: { ...lease, epoch: event.data.toEpoch, priorAgentIds: [...lease.priorAgentIds, event.data.priorAgentId] } };\n delete next.agentId;\n state.ownership.set(id, next as WriterOwnership);\n state.assignments.set(id, reclaimed(view, event));\n return;\n }\n case 'scope.exceeded':\n update(state, id, { scopeExceeded: { candidateCommit: event.data.candidateCommit, paths: event.data.paths, eventId: event.id } }, event); return;\n case 'workspace.close-requested':\n setWorkspace(state, id, { close: 'requested', closeIntentId: event.data.intentId, discardUncommitted: event.data.discardUncommitted }, event);\n update(state, id, { openIntents: withIntent(view, event.data.intentId, event.type) }, event); return;\n case 'workspace.close-succeeded':\n setWorkspace(state, id, { close: 'succeeded', archivedAt: event.data.archivedAt, directoryRemoved: event.data.directoryRemoved }, event);\n update(state, id, { openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n case 'workspace.close-failed':\n setWorkspace(state, id, { close: 'failed' }, event);\n update(state, id, { openIntents: withIntent(view, event.data.intentId, undefined) }, event); return;\n case 'workspace.close-uncertain':\n setWorkspace(state, id, { close: 'uncertain' }, event);\n update(state, id, {}, event); return;\n case 'gate.requested':\n update(state, id, { gates: [...view.gates, { gateRunId: event.data.gateRunId, candidate: event.data.candidate, command: event.data.command, status: 'running' }] }, event); return;\n case 'gate.finished':\n update(state, id, { gates: view.gates.map(gate => gate.gateRunId === event.data.result.id ? { ...gate, status: 'finished', result: event.data.result } : gate) }, event); return;\n case 'gate.uncertain':\n update(state, id, { gates: view.gates.map(gate => gate.gateRunId === event.data.gateRunId ? { ...gate, status: 'uncertain' } : gate) }, event); return;\n default: return;\n }\n}\n\nexport interface Projection {\n readonly state: ProjectState;\n readonly violations: readonly Violation[];\n}\n\n/** Replays a ledger. The first illegal transition stops folding: state after it is unknown. */\nexport function project(projectId: string, events: readonly RuntimeEventV1[]): Projection {\n const state = emptyProjectState(projectId);\n for (const event of events) {\n const problem = checkEvent(state, event);\n if (problem !== undefined) return { state, violations: [{ eventId: event.id, type: event.type, message: problem }] };\n applyEvent(state, event);\n }\n return { state, violations: [] };\n}\n\nexport interface ReclaimableLease {\n readonly view: AssignmentView;\n readonly lease: WriterLease;\n readonly worktreePath: string;\n readonly prior: string;\n readonly provider: string;\n}\n\nexport type ReclaimCheck =\n | { readonly ok: true; readonly value: ReclaimableLease }\n | { readonly ok: false; readonly code: string; readonly message: string };\n\n/**\n * The one projection rule for a lease reclaim, shared by replay (`lease.reclaimed`), the controller\n * and the panel. What remains after it passes is live proof that the prior Peer stopped.\n */\nexport function reclaimCheck(state: ProjectState, assignmentId: string): ReclaimCheck {\n const refused = (code: string, message: string): ReclaimCheck => ({ ok: false, code, message });\n const view = state.assignments.get(assignmentId);\n const owner = state.ownership.get(assignmentId);\n const lease = owner?.lease;\n const record = state.workspaces.get(assignmentId);\n if (view === undefined || owner === undefined || lease === undefined || record === undefined) return refused('lease_missing', `Assignment ${assignmentId} holds no worktree lease.`);\n if (owner.state === 'released' || owner.state === 'reserved') return refused('lease_state', 'Only a held or uncertain lease is reclaimed.');\n const prior = owner.agentId;\n if (prior === undefined || view.peerAgentId !== prior) return refused('lease_state', 'The reclaim names a different writer than the lease holder.');\n if (TERMINAL_STATES.includes(view.state) || view.state === 'draft' || view.state === 'dispatching') return refused('assignment_state', `Cannot reclaim while the assignment is ${view.state}.`);\n if (view.closure !== 'open') return refused('assignment_state', 'A closing assignment is not reclaimed.');\n if (Object.keys(view.openIntents).length > 0) return refused('effect_unresolved', 'Settle every unresolved effect before a reclaim.');\n if (record.create !== 'succeeded' || record.close !== 'open' || record.worktreePath === undefined) return refused('worktree_unavailable', 'The lease\\'s worktree is not open.');\n if (view.peerProviderId === undefined) return refused('lease_state', 'The assignment names no Peer provider.');\n return { ok: true, value: { view, lease, worktreePath: record.worktreePath, prior, provider: view.peerProviderId } };\n}\n","/**\n * Durable report receipts (docs/design/runtime-coordination.md §3.4).\n *\n * An action fingerprint is the reporting generation, the tool and the canonical validated\n * payload. A retry of an accepted action — same request id, or the same fingerprint under a\n * new id — returns the original receipt and repeats no transition. Everything else aimed at a\n * consumed or foreign generation is refused without consuming anything.\n */\nimport { createHash } from 'node:crypto';\nimport type { PeerReportErrorCodeV1, PeerReportReceiptV1 } from '../contracts/peer.js';\nimport type { AssignmentView } from './state.js';\n\n/** JSON with object keys sorted at every depth, so equal values always hash equally. */\nexport function canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, item]) => item !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(',')}}`;\n }\n return JSON.stringify(value);\n}\n\nexport function sha256(text: string): string {\n return `sha256:${createHash('sha256').update(text).digest('hex')}`;\n}\n\nexport function actionFingerprint(generation: number, tool: 'ask' | 'handoff', payload: unknown): string {\n return sha256(canonicalJson({ generation, tool, payload }));\n}\n\nexport interface CapturedAction {\n /** The generation the bridge captured when it enqueued the call — never re-attributed. */\n readonly generation: number;\n readonly requestId: string;\n readonly fingerprint: string;\n}\n\nexport type ReceiptResolution =\n | { readonly kind: 'replay'; readonly receipt: PeerReportReceiptV1 }\n | { readonly kind: 'refuse'; readonly code: PeerReportErrorCodeV1; readonly message: string }\n | { readonly kind: 'proceed' };\n\n/**\n * Steps 4 and 5 of the §3.4 validation order: the durable-receipt lookup for this binding's\n * captured generation, then the current-generation check. Payload, binding and authorization\n * checks run before this; live and invariant checks run only after `proceed`.\n */\nexport function resolveReceipt(view: AssignmentView, action: CapturedAction): ReceiptResolution {\n const accepted = view.reports.filter(report => report.generation === action.generation);\n const sameRequest = accepted.find(report => report.requestId === action.requestId);\n if (sameRequest !== undefined) {\n return sameRequest.fingerprint === action.fingerprint\n ? { kind: 'replay', receipt: sameRequest.receipt }\n : { kind: 'refuse', code: 'report_conflict', message: 'This request id was already used for a different report.' };\n }\n const sameAction = accepted.find(report => report.fingerprint === action.fingerprint);\n if (sameAction !== undefined) return { kind: 'replay', receipt: sameAction.receipt };\n if (accepted.length > 0) {\n return { kind: 'refuse', code: 'report_stale', message: 'This turn already has an accepted report; a different report is not accepted.' };\n }\n if (action.generation !== view.reportingGeneration) {\n return { kind: 'refuse', code: 'report_stale', message: 'This report belongs to an earlier turn.' };\n }\n if (view.reportingState === 'uncertain') {\n return { kind: 'refuse', code: 'report_uncertain', message: 'An earlier report for this turn is still being confirmed. Retry shortly.' };\n }\n if (view.reportingState !== 'open') {\n return { kind: 'refuse', code: 'report_stale', message: 'No report is expected for this turn.' };\n }\n return { kind: 'proceed' };\n}\n","/**\n * Role-filtered status views (docs/design/runtime-coordination.md D8, D9, §8.1, §8.2).\n *\n * Every claim carries its evidence class. \"Healthy\" means no known enforced or detected failure;\n * it never means a model obeyed its prompt or that the operating system contained anything.\n * Every degraded or pending item names one bounded recovery action. Peer receives no view.\n */\nimport type { RuntimeEventV1 } from '../events/schema.js';\nimport { canonicalJson, sha256 } from './receipts.js';\nimport {\n activeLeases, leadWorkspaceWriter, reclaimCheck, settled, TERMINAL_STATES, type AssignmentView, type ProjectState, type Violation, type WorkspaceRecord,\n} from './state.js';\n\nexport type EvidenceClass = 'enforced' | 'detected' | 'procedural' | 'unverifiable';\nexport type ViewerRole = 'operator' | 'supervisor' | 'lead';\n\nexport interface Claim<T> {\n readonly value: T;\n readonly evidence: EvidenceClass;\n}\n\nexport type FindingKind =\n | 'project-paused' | 'ownership-conflict' | 'uncertain-effect' | 'report-missing' | 'report-uncertain'\n | 'awaiting-permission' | 'notice-failed' | 'worktree-retained' | 'worktree-cleanup' | 'scope-exceeded';\n\nexport interface Finding {\n readonly kind: FindingKind;\n readonly evidence: EvidenceClass;\n readonly message: string;\n readonly recoveryAction: string;\n readonly sourceEventIds: readonly string[];\n readonly assignmentId?: string;\n}\n\nexport interface ReplayHealth {\n readonly status: 'ok' | 'paused';\n readonly problems: readonly { readonly file: string; readonly reason: string; readonly detail: string }[];\n}\n\nexport interface StatusInput {\n readonly projectId: string;\n readonly canonicalRoot: string;\n readonly replay: ReplayHealth;\n readonly violations: readonly Violation[];\n readonly state: ProjectState;\n readonly events: readonly RuntimeEventV1[];\n /** False while Paseo is unreachable: live facts are then labelled stale, never fresh. */\n readonly liveAvailable: boolean;\n /**\n * Whether a directory still exists, for worktrees Paseo archived but left behind. Callers with\n * a filesystem pass it; without it a left-behind directory is assumed still there.\n */\n readonly present?: (path: string) => boolean;\n}\n\nexport interface AssignmentSummary {\n readonly id: string;\n readonly mode: string;\n readonly kind: string;\n readonly outcome: string;\n readonly state: Claim<string>;\n readonly closure: Claim<string>;\n readonly peerProviderId?: string;\n /**\n * The Peer's thinking: what Lead chose and why (absent when it kept the default), and what the\n * Peer reported at creation — both shown, so a choice that was never applied is visible.\n */\n readonly thinking?: { readonly chosen?: string; readonly reason?: string; readonly observed?: string };\n readonly candidate?: Claim<string>;\n}\n\n/** A worktree writer lease (Phase 2). Scopes are scheduling evidence, never containment. */\nexport interface LeaseView {\n readonly assignmentId: string;\n readonly state: Claim<string>;\n readonly epoch: number;\n readonly scopes: readonly string[];\n readonly serialOnly: readonly string[];\n readonly workspaceId: string;\n readonly branch: string;\n readonly worktreePath?: string;\n readonly agentId?: string;\n /** The projection allows a reclaim; the prior Peer must still be proven stopped live. */\n readonly reclaimable: boolean;\n}\n\n/** A runtime-requested worktree, while it may still exist on disk. */\nexport interface WorktreeView {\n readonly assignmentId: string;\n readonly workspaceId: string;\n readonly path?: string;\n readonly branch: string;\n readonly create: Claim<string>;\n readonly close: Claim<string>;\n readonly disposition: WorktreeDisposition;\n}\n\nexport interface ProjectStatusView {\n readonly projectId: string;\n readonly canonicalRoot: string;\n readonly health: Claim<'healthy' | 'attention' | 'paused'>;\n readonly liveFacts: 'fresh' | 'stale';\n readonly writer?: { readonly assignmentId: string; readonly state: Claim<string> };\n readonly leases: readonly LeaseView[];\n readonly worktrees: readonly WorktreeView[];\n /** Said wherever scopes are shown (PRD REQ-011). */\n readonly scopeStatement: string;\n readonly assignments: readonly AssignmentSummary[];\n /** Present when settled assignments are counted instead of listed. */\n readonly settledAssignments?: number;\n readonly findings: readonly Finding[];\n}\n\nexport const SCOPE_STATEMENT = 'Write scopes decide which isolated writers may run at the same time. They prevent collisions; they do not contain a Peer, which can still write anywhere its user can.';\n\nexport interface AssignmentDetailView extends AssignmentSummary {\n readonly brief: AssignmentView['input'];\n readonly leadAgentId: string;\n readonly peerAgentId?: string;\n readonly observedModel?: string;\n readonly reportingGeneration: number;\n readonly peerVerification: readonly Claim<{ readonly command: string; readonly outcome: string }>[];\n readonly runtimeGates: readonly Claim<{ readonly gateRunId: string; readonly status: string; readonly exitCode?: number }>[];\n readonly ownership?: Claim<string>;\n readonly lease?: LeaseView;\n readonly worktree?: WorktreeView;\n readonly scopeExceeded?: Claim<{ readonly candidateCommit: string; readonly paths: readonly string[] }>;\n readonly history: readonly string[];\n}\n\nconst RECOVERY = {\n paused: 'Export the project, inspect the named event file, and quarantine it only if it is confirmed corrupt; the runtime never repairs it.',\n conflict: 'Supervisor or Human confirms the one Lead that owns this project; dispatch stays paused until then.',\n uncertain: 'Inspect the agent in Paseo; when its state is known, let recovery settle it or abandon after archive is requested.',\n missing: 'Lead answers with a follow-up turn or abandons the assignment; prose in the transcript is not a report.',\n reportUncertain: 'Wait for recovery to confirm whether the report was recorded; no later turn starts meanwhile.',\n permission: 'An operator approves or denies the reporting tool permission in Paseo; the runtime never answers it.',\n notice: 'Check the Lead seat is reachable; the notice is retried with the same id.',\n retained: 'Inspect the worktree, then Lead calls workspace_close — or a Human closes it here — with discardUncommitted and a reason to discard its work.',\n cleanup: 'Paseo archived the workspace but left its directory; remove it by hand once nothing in it is needed. The branch is kept.',\n exceeded: 'Review the named paths; accepting this candidate needs an override reason and a residual-risk acknowledgement, or ask for rework.',\n} as const;\n\nfunction leaseView(state: ProjectState, assignmentId: string): LeaseView | undefined {\n const owner = state.ownership.get(assignmentId);\n const lease = owner?.lease;\n if (owner === undefined || lease === undefined) return undefined;\n return {\n assignmentId, state: { value: owner.state, evidence: owner.state === 'uncertain' ? 'unverifiable' : 'enforced' },\n epoch: lease.epoch, scopes: lease.scopes, serialOnly: lease.serialOnly, workspaceId: lease.workspaceId, branch: lease.branch,\n ...(lease.worktreePath === undefined ? {} : { worktreePath: lease.worktreePath }),\n ...(owner.agentId === undefined ? {} : { agentId: owner.agentId }),\n reclaimable: reclaimCheck(state, assignmentId).ok,\n };\n}\n\n/**\n * What a runtime worktree record means on disk — the one rule every view, count and blocker uses.\n * `unresolved`: a create or close is unconfirmed. `active`: its writer is not released.\n * `retained`: writer released, worktree open, waiting for an explicit close. `leftover`: archived\n * by Paseo but its directory is still there. `gone`: never created, or closed and removed.\n */\nexport type WorktreeDisposition = 'unresolved' | 'active' | 'retained' | 'leftover' | 'gone';\n\nexport function worktreeDisposition(state: ProjectState, record: WorkspaceRecord, present: (path: string) => boolean = () => true): WorktreeDisposition {\n if (record.create === 'requested' || record.create === 'uncertain' || record.close === 'requested' || record.close === 'uncertain') return 'unresolved';\n if (record.create === 'failed') return 'gone';\n if (record.close === 'succeeded') {\n return record.directoryRemoved === false && (record.worktreePath === undefined || present(record.worktreePath)) ? 'leftover' : 'gone';\n }\n return state.ownership.get(record.assignmentId)?.state === 'released' ? 'retained' : 'active';\n}\n\nfunction worktreeView(record: WorkspaceRecord, disposition: WorktreeDisposition): WorktreeView {\n const claim = (value: string): Claim<string> => ({ value, evidence: value === 'uncertain' ? 'unverifiable' : 'detected' });\n return {\n assignmentId: record.assignmentId, workspaceId: record.workspaceId, branch: record.branch ?? record.branchName,\n ...(record.worktreePath === undefined ? {} : { path: record.worktreePath }),\n create: claim(record.create), close: claim(record.close), disposition,\n };\n}\n\n/** Every record's disposition, worked out once per view (each may check the disk). */\nfunction dispositions(state: ProjectState, present?: (path: string) => boolean): Map<WorkspaceRecord, WorktreeDisposition> {\n return new Map([...state.workspaces.values()].map(record => [record, worktreeDisposition(state, record, present)]));\n}\n\nfunction eventIdsOf(events: readonly RuntimeEventV1[], assignmentId: string, type: RuntimeEventV1['type']): string[] {\n return events.filter(event => event.assignmentId === assignmentId && event.type === type).map(event => event.id);\n}\n\nexport function findings(input: StatusInput): Finding[] {\n const found: Finding[] = [];\n if (input.replay.status === 'paused' || input.violations.length > 0) {\n found.push({\n kind: 'project-paused', evidence: 'detected',\n message: [...input.replay.problems.map(problem => `${problem.file}: ${problem.reason}`), ...input.violations.map(violation => `${violation.eventId}: ${violation.message}`)].join('; '),\n recoveryAction: RECOVERY.paused, sourceEventIds: input.violations.map(violation => violation.eventId),\n });\n }\n const conflict = input.state.ownershipConflict;\n if (conflict !== undefined) {\n found.push({ kind: 'ownership-conflict', evidence: 'detected', message: `Leads ${conflict.leadAgentIds.join(', ')} both claim this project.`, recoveryAction: RECOVERY.conflict, sourceEventIds: [conflict.eventId] });\n }\n const flagged = new Set<string>();\n for (const view of input.state.assignments.values()) {\n const owner = input.state.ownership.get(view.id);\n if (view.state === 'uncertain' || view.closure === 'uncertain' || owner?.state === 'uncertain' || view.gates.some(gate => gate.status === 'uncertain')) {\n flagged.add(view.id);\n found.push({\n kind: view.reportingState === 'uncertain' ? 'report-uncertain' : 'uncertain-effect', evidence: 'unverifiable', assignmentId: view.id,\n message: `Assignment ${view.id} has an effect whose outcome is not known.`,\n recoveryAction: view.reportingState === 'uncertain' ? RECOVERY.reportUncertain : RECOVERY.uncertain,\n sourceEventIds: view.eventIds.slice(-1),\n });\n }\n if (view.state === 'blocked') {\n const missing = eventIdsOf(input.events, view.id, 'report.missing');\n const last = view.eventIds.at(-1);\n if (last !== undefined && missing.includes(last)) {\n found.push({ kind: 'report-missing', evidence: 'detected', assignmentId: view.id, message: `The Peer turn for ${view.id} ended without an accepted report.`, recoveryAction: RECOVERY.missing, sourceEventIds: [last] });\n }\n }\n if (view.state === 'awaiting-permission') {\n found.push({ kind: 'awaiting-permission', evidence: 'detected', assignmentId: view.id, message: `The Peer for ${view.id} is waiting for permission to call its reporting tool.`, recoveryAction: RECOVERY.permission, sourceEventIds: eventIdsOf(input.events, view.id, 'permission.awaiting').slice(-1) });\n }\n }\n for (const [record, disposition] of dispositions(input.state, input.present)) {\n const ids = record.eventIds.slice(-1);\n if (record.create === 'uncertain' || record.close === 'uncertain') {\n if (!flagged.has(record.assignmentId)) {\n found.push({ kind: 'uncertain-effect', evidence: 'unverifiable', assignmentId: record.assignmentId, message: `The worktree ${record.create === 'uncertain' ? 'create' : 'close'} of ${record.assignmentId} is unconfirmed.`, recoveryAction: RECOVERY.uncertain, sourceEventIds: ids });\n }\n } else if (disposition === 'retained') {\n found.push({ kind: 'worktree-retained', evidence: 'detected', assignmentId: record.assignmentId, message: `The worktree of ${record.assignmentId} (${record.worktreePath ?? record.workspaceId}) was ${record.create === 'refused' ? 'refused and not closed' : 'retained after its writer was released'}.`, recoveryAction: RECOVERY.retained, sourceEventIds: ids });\n } else if (disposition === 'leftover') {\n found.push({ kind: 'worktree-cleanup', evidence: 'detected', assignmentId: record.assignmentId, message: `The worktree of ${record.assignmentId} is closed but ${record.worktreePath ?? 'its directory'} remains.`, recoveryAction: RECOVERY.cleanup, sourceEventIds: ids });\n }\n }\n for (const view of input.state.assignments.values()) {\n const exceeded = view.scopeExceeded;\n if (exceeded !== undefined && !TERMINAL_STATES.includes(view.state)) {\n found.push({ kind: 'scope-exceeded', evidence: 'detected', assignmentId: view.id, message: `The candidate of ${view.id} changes ${exceeded.paths.join(', ')} outside its write scope.`, recoveryAction: RECOVERY.exceeded, sourceEventIds: [exceeded.eventId] });\n }\n }\n for (const notice of input.state.notices.values()) {\n if (notice.state === 'failed' || notice.state === 'uncertain') {\n found.push({ kind: 'notice-failed', evidence: notice.state === 'failed' ? 'detected' : 'unverifiable', message: `Notice ${notice.noticeId} (${notice.kind}) was not confirmed delivered.`, recoveryAction: RECOVERY.notice, sourceEventIds: [notice.eventId], ...(notice.assignmentId === undefined ? {} : { assignmentId: notice.assignmentId }) });\n }\n }\n return found;\n}\n\nfunction stateClaim(view: AssignmentView): Claim<string> {\n return { value: view.state, evidence: view.state === 'uncertain' ? 'unverifiable' : 'enforced' };\n}\n\nfunction summary(view: AssignmentView): AssignmentSummary {\n const thinking = {\n ...(view.chosenThinking === undefined ? {} : { chosen: view.chosenThinking }),\n ...(view.thinkingReason === undefined ? {} : { reason: view.thinkingReason }),\n ...(view.observedThinking === undefined ? {} : { observed: view.observedThinking }),\n };\n return {\n id: view.id, mode: view.input.mode, kind: view.input.kind, outcome: view.input.outcome,\n state: stateClaim(view),\n closure: { value: view.closure, evidence: view.closure === 'uncertain' ? 'unverifiable' : view.closure === 'closed' ? 'detected' : 'enforced' },\n ...(view.peerProviderId === undefined ? {} : { peerProviderId: view.peerProviderId }),\n ...(Object.keys(thinking).length === 0 ? {} : { thinking }),\n ...(view.candidate === undefined ? {} : { candidate: { value: view.candidate.commit, evidence: 'detected' as const } }),\n };\n}\n\n/**\n * Project status is the same for every viewer that may see it — Supervisor, Lead and the\n * operator — except that `countSettled` counts settled assignments instead of listing them, so a\n * long-lived project fits one Supervisor tool result. `ViewerRole` has no Peer member, so a Peer\n * cannot be handed a view at all.\n */\nexport function projectStatusView(input: StatusInput, options: { readonly countSettled?: boolean } = {}): ProjectStatusView {\n const found = findings(input);\n const paused = found.some(finding => finding.kind === 'project-paused' || finding.kind === 'ownership-conflict');\n // The one writer in Lead's workspace; isolated writers are listed under `leases`.\n const writer = leadWorkspaceWriter(input.state);\n const all = [...input.state.assignments.values()];\n const shown = options.countSettled === true ? all.filter(view => !settled(view)) : all;\n return {\n projectId: input.projectId,\n canonicalRoot: input.canonicalRoot,\n health: { value: paused ? 'paused' : found.length > 0 ? 'attention' : 'healthy', evidence: 'detected' },\n liveFacts: input.liveAvailable ? 'fresh' : 'stale',\n ...(writer === undefined ? {} : { writer: { assignmentId: writer.assignmentId, state: { value: writer.state, evidence: writer.state === 'uncertain' ? 'unverifiable' : 'enforced' } } }),\n leases: activeLeases(input.state).flatMap(owner => leaseView(input.state, owner.assignmentId) ?? []),\n worktrees: [...dispositions(input.state, input.present)].filter(([, disposition]) => disposition !== 'gone').map(([record, disposition]) => worktreeView(record, disposition)),\n scopeStatement: SCOPE_STATEMENT,\n assignments: shown.map(summary),\n ...(options.countSettled === true ? { settledAssignments: all.length - shown.length } : {}),\n findings: found,\n };\n}\n\n/** Full assignment detail is for Lead and the operator; Supervisor observes summaries only. */\nexport function assignmentDetailView(state: ProjectState, assignmentId: string, role: ViewerRole, present?: (path: string) => boolean): AssignmentDetailView | undefined {\n if (role === 'supervisor') return undefined;\n const view = state.assignments.get(assignmentId);\n if (view === undefined) return undefined;\n const owner = state.ownership.get(view.id);\n const lease = leaseView(state, view.id);\n const record = state.workspaces.get(view.id);\n const handoff = [...view.reports].reverse().find(report => report.tool === 'handoff');\n const verification = Array.isArray(handoff?.report.verification) ? handoff.report.verification as readonly { command?: unknown; outcome?: unknown }[] : [];\n return {\n ...summary(view),\n brief: view.input,\n leadAgentId: view.leadAgentId,\n ...(view.peerAgentId === undefined ? {} : { peerAgentId: view.peerAgentId }),\n ...(view.observedModel === undefined ? {} : { observedModel: view.observedModel }),\n reportingGeneration: view.reportingGeneration,\n // The Peer's own gate report is a procedural claim: the runtime cannot prove it ran.\n peerVerification: verification.map(entry => ({ value: { command: String(entry.command), outcome: String(entry.outcome) }, evidence: 'procedural' as const })),\n runtimeGates: view.gates.map(gate => ({\n value: { gateRunId: gate.gateRunId, status: gate.status, ...(gate.result?.exitCode === undefined ? {} : { exitCode: gate.result.exitCode }) },\n evidence: gate.status === 'uncertain' ? 'unverifiable' as const : 'enforced' as const,\n })),\n ...(owner === undefined ? {} : { ownership: { value: owner.state, evidence: owner.state === 'uncertain' ? 'unverifiable' as const : 'enforced' as const } }),\n ...(lease === undefined ? {} : { lease }),\n ...(record === undefined ? {} : { worktree: worktreeView(record, worktreeDisposition(state, record, present)) }),\n ...(view.scopeExceeded === undefined ? {} : { scopeExceeded: { value: { candidateCommit: view.scopeExceeded.candidateCommit, paths: view.scopeExceeded.paths }, evidence: 'detected' as const } }),\n history: view.eventIds,\n };\n}\n\n/** A stable content revision: unchanged views keep the same revision. */\nexport function revision(view: unknown): string {\n return sha256(canonicalJson(view)).slice('sha256:'.length, 'sha256:'.length + 24);\n}\n\nexport interface QuiescenceBlocker {\n readonly kind: 'assignment' | 'ownership' | 'lease' | 'worktree' | 'archive' | 'gate' | 'delivery' | 'intent';\n readonly id: string;\n readonly detail: string;\n}\n\n/**\n * True when nothing the runtime started is still active or uncertain, so deselection cannot\n * strand a writer, a managed Peer, a gate or a delivery (docs/design/runtime-coordination.md §10),\n * a worktree lease or an unresolved worktree create or close (Phase 2 delta §8). A retained\n * worktree whose writer is released does not block: it is Paseo's, and stays for a decision.\n */\nexport function quiescence(state: ProjectState): { readonly quiescent: boolean; readonly blockers: readonly QuiescenceBlocker[] } {\n const blockers: QuiescenceBlocker[] = [];\n for (const view of state.assignments.values()) {\n if (view.state !== 'draft' && !TERMINAL_STATES.includes(view.state)) blockers.push({ kind: 'assignment', id: view.id, detail: `is ${view.state}` });\n if (view.peerAgentId !== undefined && view.closure !== 'closed') blockers.push({ kind: 'archive', id: view.id, detail: `managed Peer ${view.peerAgentId} is not archived (${view.closure})` });\n for (const gate of view.gates) {\n // A running gate always blocks. An uncertain one blocks until its Peer is proven archived:\n // after that nothing can act on it, and nothing could ever settle it further.\n if (gate.status === 'running' || (gate.status === 'uncertain' && view.closure !== 'closed')) {\n blockers.push({ kind: 'gate', id: gate.gateRunId, detail: `gate is ${gate.status}` });\n }\n }\n for (const [intent, type] of Object.entries(view.openIntents)) blockers.push({ kind: 'intent', id: intent, detail: `${type} has no result` });\n }\n for (const owner of state.ownership.values()) {\n if (owner.state === 'released') continue;\n blockers.push(owner.lease === undefined\n ? { kind: 'ownership', id: owner.assignmentId, detail: `writer ownership is ${owner.state}` }\n : { kind: 'lease', id: owner.assignmentId, detail: `worktree lease (epoch ${String(owner.lease.epoch)}) is ${owner.state}` });\n }\n for (const record of state.workspaces.values()) {\n if (worktreeDisposition(state, record) === 'unresolved') {\n blockers.push({ kind: 'worktree', id: record.workspaceId, detail: `worktree of ${record.assignmentId} is unresolved (create ${record.create}, close ${record.close})` });\n }\n }\n for (const notice of state.notices.values()) {\n if (notice.state === 'pending' || notice.state === 'uncertain') blockers.push({ kind: 'delivery', id: notice.noticeId, detail: `notice is ${notice.state}` });\n }\n return { quiescent: blockers.length === 0, blockers };\n}\n\n/** Runtime worktrees that may still be on disk: retained ones Paseo still lists, and leftover directories. */\nexport function worktreesOnDisk(state: ProjectState, present?: (path: string) => boolean): { readonly retained: number; readonly leftover: number } {\n const values = [...dispositions(state, present).values()];\n return { retained: values.filter(value => value === 'retained').length, leftover: values.filter(value => value === 'leftover').length };\n}\n","/**\n * Assignment input and evidence shapes (docs/design/runtime-coordination.md §4.3, §4.4).\n * Structural only: semantic rules such as mode/kind compatibility or a writable gate belong to\n * the domain validator, so every refusal there carries an actionable reason.\n */\nimport { z } from 'zod';\nimport { boundedArray, boundedString, MAX_COMMAND_BYTES, MAX_GATE_TIMEOUT_SECONDS } from '../../shared/limits.js';\n\nexport const ASSIGNMENT_MODES = ['writable', 'read-only'] as const;\nexport const ASSIGNMENT_KINDS = ['engineer', 'architect', 'reviewer', 'scout'] as const;\nexport type AssignmentMode = (typeof ASSIGNMENT_MODES)[number];\nexport type AssignmentKind = (typeof ASSIGNMENT_KINDS)[number];\n\n/** A full Git object id: SHA-1 or SHA-256. Abbreviations are refused, never resolved. */\nexport const commitSchema = z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/);\n\nexport const gateSpecSchema = z.strictObject({\n command: boundedString(MAX_COMMAND_BYTES),\n timeoutSeconds: z.number().int().min(1).max(MAX_GATE_TIMEOUT_SECONDS),\n runtimeRerun: z.enum(['none', 'optional', 'required']),\n processContractVersion: z.literal(1),\n});\nexport type GateSpecV1 = z.infer<typeof gateSpecSchema>;\n\nconst items = boundedArray(boundedString());\n\nexport const assignmentCreateSchema = z.strictObject({\n mode: z.enum(ASSIGNMENT_MODES),\n kind: z.enum(ASSIGNMENT_KINDS),\n outcome: boundedString(),\n prerequisites: items,\n writeScope: items,\n exclusions: items,\n invariants: items,\n acceptanceEvidence: items,\n gate: gateSpecSchema.optional(),\n expectedHandoff: items,\n reopenConditions: items,\n baseCommit: commitSchema,\n});\nexport type AssignmentCreateInputV1 = z.infer<typeof assignmentCreateSchema>;\n\nexport const candidateRefSchema = z.strictObject({\n kind: z.literal('git-commit'),\n commit: commitSchema,\n baseCommit: commitSchema,\n changedPaths: z.array(z.string().min(1)),\n workspaceId: z.string().min(1),\n branch: z.string().min(1).optional(),\n});\nexport type CandidateRefV1 = z.infer<typeof candidateRefSchema>;\n","/**\n * Inputs of the Supervisor and Lead action tools (docs/design/runtime-coordination.md §3.4, D4).\n * Operation names come from the shared role-policy projection; this module only types payloads.\n */\nimport { z } from 'zod';\nimport { boundedArray, boundedString } from '../../shared/limits.js';\nimport type { LeadOperation, SupervisorOperation } from '../../shared/policy.js';\nimport { assignmentCreateSchema } from './assignment.js';\n\n/** Runtime-minted assignment ids; never a Paseo agent id or a path. */\nexport const assignmentIdSchema = z.string().regex(/^asg_[A-Za-z0-9_-]{8,64}$/);\nconst reason = boundedString();\nconst assignment = { assignmentId: assignmentIdSchema };\n\nexport const SUPERVISOR_ACTION_SCHEMAS = {\n room_status: z.strictObject({}),\n runtime_findings: z.strictObject({}),\n // `project` names a project in the caller's portfolio: a runtime project id, the project key or\n // the repository's name. Omitted, it is the caller's own working project, or its only project.\n message_lead: z.strictObject({ message: boundedString(), project: z.string().min(1).max(4_096).optional() }),\n attention_feedback: z.strictObject({ id: z.string().regex(/^att_[A-Za-z0-9_-]{8,32}$/), verdict: z.enum(['useful', 'noise', 'unknown']) }),\n} as const satisfies Record<SupervisorOperation, z.ZodType>;\n\nexport const LEAD_ACTION_SCHEMAS = {\n assignment_create: assignmentCreateSchema,\n // An eligible exact Peer provider id from the room manifest; the model is never selectable.\n // `worktree` asks the runtime for an isolated worktree; the default is Phase 1's shared\n // workspace. `serialOnly` names paths that admit one writer at a time, quoted from the\n // repository's own protocol (docs/design/runtime-coordination-phase2.md P2-D1, §5.3).\n assignment_dispatch: z.strictObject({\n ...assignment,\n peerProvider: z.string().min(1).max(128),\n isolation: z.enum(['lead-workspace', 'worktree']).optional(),\n serialOnly: boundedArray(boundedString()).optional(),\n // A thinking option the operator allows for that Peer provider, and why; omitted, the Peer\n // launches on its profile's option (docs/design/runtime-coordination-peer-effort.md E-D2).\n thinking: z.string().min(1).max(64).optional(),\n thinkingReason: boundedString(1024).optional(),\n }),\n assignment_answer: z.strictObject({ ...assignment, answer: boundedString() }),\n assignment_rework: z.strictObject({ ...assignment, instructions: boundedString() }),\n assignment_accept: z.strictObject({\n ...assignment,\n reason,\n // Required by the domain when the Peer gate or a required rerun is red; never a waiver of\n // a missing gate.\n override: z.strictObject({ reason, residualRiskAcknowledged: z.literal(true) }).optional(),\n }),\n assignment_reject: z.strictObject({ ...assignment, reason }),\n assignment_abandon: z.strictObject({ ...assignment, reason }),\n assignment_close: z.strictObject(assignment),\n assignment_status: z.strictObject({ assignmentId: assignmentIdSchema.optional() }),\n gate_run: z.strictObject(assignment),\n // Discarding a retained worktree's uncommitted work is Lead's explicit decision, with a reason.\n workspace_close: z.strictObject({ ...assignment, discardUncommitted: z.literal(true).optional(), reason: reason.optional() })\n .refine(input => input.discardUncommitted !== true || input.reason !== undefined, { message: 'discardUncommitted needs a reason', path: ['reason'] }),\n lease_reclaim: z.strictObject({ ...assignment, reason }),\n} as const satisfies Record<LeadOperation, z.ZodType>;\n","/**\n * The Peer reporting tools, `ask` and `handoff` (docs/design/runtime-coordination.md §3.4).\n *\n * No schema here accepts a room, project, assignment, agent, parent, provider, model,\n * recipient, candidate or lifecycle identifier: the server derives every identity from its own\n * binding. The one `handoff` detail variant a Peer may use is chosen by the server from the\n * bound assignment's work kind; a Peer can neither choose nor change it.\n */\nimport { z } from 'zod';\nimport { boundedArray, boundedString, MAX_COMMAND_BYTES, withinAggregateLimit } from '../../shared/limits.js';\nimport type { PeerReportingTool } from '../../shared/policy.js';\nimport type { AssignmentKind } from './assignment.js';\n\nconst text = boundedString();\nconst texts = boundedArray(text);\n\nexport const verificationReportSchema = z.strictObject({\n command: boundedString(MAX_COMMAND_BYTES),\n outcome: z.enum(['passed', 'failed', 'not-run']),\n note: text.optional(),\n});\nexport type VerificationReportV1 = z.infer<typeof verificationReportSchema>;\n\nexport const askInputSchema = z.strictObject({\n question: text,\n blockingContext: text,\n evidence: texts,\n});\nexport type AskInputV1 = z.infer<typeof askInputSchema>;\n\nexport const HANDOFF_DETAILS = {\n engineer: z.strictObject({ kind: z.literal('engineer') }),\n architect: z.strictObject({\n kind: z.literal('architect'),\n alternatives: texts,\n strongestCounterargument: text,\n reversalConditions: texts,\n evidence: texts,\n }),\n reviewer: z.strictObject({\n kind: z.literal('reviewer'),\n findings: boundedArray(z.strictObject({ claim: text, evidence: texts })),\n }),\n scout: z.strictObject({\n kind: z.literal('scout'),\n evidence: texts,\n remainingUnknowns: texts,\n confidence: z.enum(['low', 'medium', 'high']),\n }),\n} as const satisfies Record<AssignmentKind, z.ZodType>;\n\nconst handoffBase = {\n summary: text,\n deliverables: texts,\n verification: boundedArray(verificationReportSchema),\n residualRisks: texts,\n evidence: texts,\n};\n\n/** The strict `handoff` input for exactly one bound work kind. */\nexport function handoffInputSchema<K extends AssignmentKind>(kind: K) {\n return z.discriminatedUnion('completion', [\n z.strictObject({ ...handoffBase, completion: z.literal('blocked'), blocker: text }),\n z.strictObject({ ...handoffBase, completion: z.literal('partial'), blocker: text }),\n z.strictObject({ ...handoffBase, completion: z.literal('complete'), details: HANDOFF_DETAILS[kind] }),\n ]);\n}\nexport type HandoffInputV1 = z.infer<ReturnType<typeof handoffInputSchema>>;\n\nexport const PEER_REPORT_ERROR_CODES = [\n 'report_malformed', 'report_unauthorized', 'report_stale', 'report_conflict',\n 'report_state', 'report_precondition', 'report_uncertain',\n] as const;\nexport type PeerReportErrorCodeV1 = (typeof PEER_REPORT_ERROR_CODES)[number];\n\nexport const peerReportReceiptSchema = z.strictObject({\n schema: z.literal(1),\n receipt: z.string().min(1).max(128),\n tool: z.enum(['ask', 'handoff']),\n status: z.literal('accepted'),\n assignmentState: z.enum(['questioned', 'blocked', 'handed-back']),\n});\nexport type PeerReportReceiptV1 = z.infer<typeof peerReportReceiptSchema>;\n\nexport const peerReportErrorSchema = z.strictObject({\n schema: z.literal(1),\n error: z.strictObject({\n code: z.enum(PEER_REPORT_ERROR_CODES),\n message: boundedString(1024),\n retryable: z.boolean(),\n }),\n});\nexport type PeerReportErrorV1 = z.infer<typeof peerReportErrorSchema>;\n\nexport type PeerToolParse =\n | { readonly ok: true; readonly tool: 'ask'; readonly input: AskInputV1 }\n | { readonly ok: true; readonly tool: 'handoff'; readonly input: HandoffInputV1 }\n | { readonly ok: false; readonly message: string };\n\n/**\n * Parses raw Peer tool input for the bound work kind. The aggregate bound is checked on the raw\n * value first, so an oversize payload is refused before any field is interpreted.\n */\nexport function parsePeerToolInput(tool: PeerReportingTool, kind: AssignmentKind, raw: unknown): PeerToolParse {\n if (!withinAggregateLimit(raw)) return { ok: false, message: 'Report exceeds the 64 KiB aggregate limit.' };\n if (tool === 'ask') {\n const parsed = askInputSchema.safeParse(raw);\n return parsed.success ? { ok: true, tool, input: parsed.data } : { ok: false, message: z.prettifyError(parsed.error) };\n }\n const parsed = handoffInputSchema(kind).safeParse(raw);\n return parsed.success ? { ok: true, tool, input: parsed.data } : { ok: false, message: z.prettifyError(parsed.error) };\n}\n","/**\n * The closed runtime event union (docs/design/runtime-coordination.md §4.2).\n *\n * Writers can emit only a declared `type` at its declared `payloadVersion`, with a strict\n * payload. Readers keep strict envelopes but ignore unknown additive fields at the top level of\n * a supported payload, and refuse an unknown type or an unsupported payload version — which\n * pauses that project rather than reading it as empty. A breaking payload change adds a new\n * payload version beside the old reader; it never edits a v1 shape in place.\n */\nimport { z } from 'zod';\nimport { boundedString, MAX_COMMAND_BYTES } from '../../shared/limits.js';\nimport { PEER_REPORTING_TOOLS, RUNTIME_ROLES } from '../../shared/policy.js';\nimport { assignmentIdSchema } from '../contracts/actions.js';\nimport { assignmentCreateSchema, candidateRefSchema, commitSchema, gateSpecSchema } from '../contracts/assignment.js';\nimport { PEER_REPORT_ERROR_CODES, peerReportReceiptSchema } from '../contracts/peer.js';\n\nexport const EVENT_SCHEMA = 'paseo-room.runtime-event';\n\nconst id = z.string().min(1).max(128);\nconst text = boundedString();\nconst reason = boundedString(1024);\n/** A provider thinking option id, as Paseo lists it for a model. */\nconst thinkingOption = z.string().min(1).max(64);\nconst generation = z.number().int().min(1);\nconst digest = z.string().regex(/^sha256:[0-9a-f]{64}$/);\nconst timestamp = z.iso.datetime({ offset: true });\n/** A Paseo workspace id the runtime chose before asking for it (delta P2-D3). */\nexport const workspaceIdSchema = z.string().regex(/^wks_[a-f0-9]{16}$/);\nconst branch = z.string().min(1).max(256);\nconst epoch = z.number().int().min(1);\nconst scopes = z.array(boundedString()).max(64);\n\nexport const gateResultSchema = z.strictObject({\n id,\n assignmentId: assignmentIdSchema,\n candidate: candidateRefSchema,\n command: boundedString(MAX_COMMAND_BYTES),\n startedAt: timestamp,\n finishedAt: timestamp.optional(),\n exitCode: z.number().int().optional(),\n signal: z.string().min(1).max(32).optional(),\n timedOut: z.boolean(),\n termination: z.enum(['exited', 'signaled', 'killed', 'uncertain']),\n processContractVersion: z.literal(1),\n environmentPolicyVersion: z.literal(1),\n outputDigest: digest,\n outputTailAttachment: z.string().min(1).max(256).optional(),\n workspaceMoved: z.boolean(),\n});\nexport type GateResultV1 = z.infer<typeof gateResultSchema>;\n\nexport const NOTICE_DISPOSITIONS = ['record', 'panel', 'lead-now', 'supervisor-digest', 'supervisor-now', 'operator-now', 'human-required'] as const;\nexport const NOTICE_CLASSES = ['record', 'owner', 'operator', 'page'] as const;\n\n/**\n * Every payload, as a raw shape. Intent/result pairs share one `intentId` so replay can\n * find an intent that never reached a terminal result.\n */\nexport const EVENT_PAYLOADS = {\n // Project binding and Lead ownership (§4.1, §5.2).\n 'project.bound': { canonicalRoot: z.string().min(1), gitCommonDir: z.string().min(1) },\n 'project.rebound': { canonicalRoot: z.string().min(1), gitCommonDir: z.string().min(1), previousRoot: z.string().min(1) },\n 'project.ownership-conflict': { leadAgentIds: z.array(id).min(2), leadProviderIds: z.array(id).min(1) },\n 'project.ownership-resolved': { keptLeadAgentId: id, decidedBy: z.enum(['evidence', 'human']) },\n\n // Assignment lifecycle decided by Lead or Human (§5.1).\n 'assignment.created': { input: assignmentCreateSchema, leadAgentId: id, leadProviderId: id },\n // Lead's thinking choice within the operator's envelope, and why (peer-effort delta E-D2, E-D4).\n 'assignment.dispatch-requested': { peerProviderId: id, workspaceId: id, thinking: thinkingOption.optional(), thinkingReason: reason.optional() },\n 'assignment.answered': { answer: text },\n 'assignment.rework-requested': { instructions: text },\n 'assignment.accepted': {\n candidate: candidateRefSchema.optional(),\n inspectedCommit: commitSchema.optional(),\n reason,\n override: z.strictObject({ reason, residualRiskAcknowledged: z.literal(true) }).optional(),\n gateResultId: id.optional(),\n },\n 'assignment.rejected': { reason },\n 'assignment.abandoned': { reason },\n 'assignment.close-requested': {},\n\n // Writer ownership, independent of assignment state (§5.3).\n 'ownership.reserved': { workspaceId: id, baseCommit: commitSchema },\n 'ownership.held': { agentId: id },\n 'ownership.releasing': { agentId: id },\n 'ownership.released': { agentId: id, archivedAt: timestamp },\n 'ownership.uncertain': { reason },\n\n // External effects: agent creation, turn delivery and archive (§6).\n // `agentId` and `idempotencyKey` are chosen before the call, so recovery reissues the identical\n // request (Phase 2 delta P2-D3). Optional and additive: a Phase 1 reader ignores them.\n 'agent.create-requested': {\n intentId: id, peerProviderId: id, workspaceId: id, parentAgentId: id, label: id,\n agentId: z.uuid().optional(), idempotencyKey: z.string().min(1).max(512).optional(),\n },\n 'agent.create-succeeded': { intentId: id, agentId: id },\n 'agent.create-failed': { intentId: id, reason },\n 'agent.create-uncertain': { intentId: id, reason },\n // A created Peer whose fresh snapshot did not prove provider, parent, workspace, idleness\n // and no prior prompt. It is archived, never adopted or prompted (§3.3, §5.3).\n 'binding.refused': { agentId: id, reason },\n 'binding.published': {\n agentId: id, providerId: id, model: z.string().min(1).max(256), parentAgentId: id, workspaceId: id, roomGeneration: id,\n thinking: thinkingOption.optional(),\n },\n 'reporting.generation-opened': { generation, capabilityHash: digest, turn: z.enum(['initial', 'answer', 'rework', 'follow-up']) },\n 'run.requested': { intentId: id, generation, promptDigest: digest },\n 'run.succeeded': { intentId: id, generation },\n 'run.failed': { intentId: id, generation, reason },\n 'run.uncertain': { intentId: id, generation, reason },\n 'archive.requested': { intentId: id, agentId: id },\n 'archive.succeeded': { intentId: id, agentId: id, archivedAt: timestamp, liveStatus: z.literal('closed') },\n 'archive.failed': { intentId: id, agentId: id, reason },\n 'archive.uncertain': { intentId: id, agentId: id, reason },\n\n // Peer reporting (§3.4). Report content is evidence; identity and candidate are derived.\n 'report.accepted': {\n generation,\n tool: z.enum(PEER_REPORTING_TOOLS),\n requestId: id,\n fingerprint: digest,\n receipt: peerReportReceiptSchema,\n report: z.record(z.string(), z.unknown()),\n candidate: candidateRefSchema.optional(),\n inspectedCommit: commitSchema.optional(),\n },\n 'report.refused': { generation: generation.optional(), tool: z.string().min(1).max(64), requestId: id, code: z.enum(PEER_REPORT_ERROR_CODES), reason },\n 'report.missing': { generation },\n 'report.uncertain': { generation, requestId: id.optional(), reason },\n 'permission.awaiting': { generation, permissionRequestId: id, tool: z.enum(PEER_REPORTING_TOOLS) },\n 'permission.resolved': { generation, permissionRequestId: id, outcome: z.enum(['allowed', 'denied', 'other']) },\n\n // Independent runtime gate (D6).\n 'gate.requested': {\n gateRunId: id, candidate: candidateRefSchema, command: boundedString(MAX_COMMAND_BYTES),\n timeoutSeconds: gateSpecSchema.shape.timeoutSeconds,\n processContractVersion: z.literal(1), environmentPolicyVersion: z.literal(1),\n },\n 'gate.finished': { result: gateResultSchema },\n 'gate.uncertain': { gateRunId: id, reason },\n\n // Phase 2 worktree concurrency (docs/design/runtime-coordination-phase2.md §4). A writer lease\n // extends the assignment's ownership with its own worktree, scopes and epoch.\n 'lease.reserved': { workspaceId: workspaceIdSchema, branch, baseCommit: commitSchema, scopes, serialOnly: scopes, epoch: z.literal(1) },\n 'workspace.create-requested': {\n intentId: id, workspaceId: workspaceIdSchema, idempotencyKey: z.string().min(1).max(512), baseCommit: commitSchema,\n branchName: branch, worktreeSlug: z.string().min(1).max(128),\n },\n // Written only after the Git proof (P2-D4); `branch` is the name Paseo resolved.\n 'workspace.create-succeeded': { intentId: id, workspaceId: workspaceIdSchema, worktreePath: z.string().min(1).max(4096), branch, headCommit: commitSchema },\n 'workspace.create-failed': { intentId: id, reason },\n 'workspace.create-uncertain': { intentId: id, reason },\n // Created but failed its proof: no Peer is ever placed there, and a close follows.\n 'workspace.create-refused': { intentId: id, workspaceId: workspaceIdSchema, reason },\n 'lease.reclaimed': { fromEpoch: epoch, toEpoch: epoch, priorAgentId: id, decidedBy: z.enum(['lead', 'human']), reason },\n // Handoff evidence, not containment (§5.4).\n 'scope.exceeded': { candidateCommit: commitSchema, paths: z.array(z.string().min(1)).min(1) },\n 'workspace.close-requested': { intentId: id, workspaceId: workspaceIdSchema, discardUncommitted: z.boolean(), reason: reason.optional() },\n 'workspace.close-succeeded': { intentId: id, workspaceId: workspaceIdSchema, archivedAt: timestamp, directoryRemoved: z.boolean() },\n 'workspace.close-failed': { intentId: id, workspaceId: workspaceIdSchema, reason },\n 'workspace.close-uncertain': { intentId: id, workspaceId: workspaceIdSchema, reason },\n\n // Deterministic notices (D9). Delivery is at least once with a stable id.\n 'notice.pending': {\n noticeId: id, kind: z.string().min(1).max(64), class: z.enum(NOTICE_CLASSES), disposition: z.enum(NOTICE_DISPOSITIONS),\n recipientAgentId: id.optional(), recipientRole: z.enum(RUNTIME_ROLES).exclude(['peer']).optional(), text,\n },\n 'notice.sent': { noticeId: id },\n 'notice.failed': { noticeId: id, reason },\n 'notice.uncertain': { noticeId: id, reason },\n} as const satisfies Record<string, z.ZodRawShape>;\n\nexport type EventType = keyof typeof EVENT_PAYLOADS;\nexport const EVENT_TYPES = Object.keys(EVENT_PAYLOADS) as EventType[];\n/**\n * Payload versions this runtime can read. Phase 1 emits and reads only version 1 of every type;\n * a later breaking payload adds its version here beside the retained v1 reader.\n */\nexport const SUPPORTED_PAYLOAD_VERSIONS: Readonly<Record<EventType, readonly number[]>> = Object.fromEntries(\n EVENT_TYPES.map(type => [type, [1]] as const),\n) as unknown as Record<EventType, readonly number[]>;\n\nconst actorSchema = z.strictObject({\n source: z.enum(['human', 'plugin', 'seat', 'paseo']),\n role: z.enum(RUNTIME_ROLES).optional(),\n agentId: id.optional(),\n providerId: id.optional(),\n});\n\nconst envelope = {\n schema: z.literal(EVENT_SCHEMA),\n version: z.literal(1),\n id: z.string().regex(/^evt_[A-Za-z0-9_-]{8,64}$/),\n sequence: z.number().int().min(1),\n projectId: z.uuid(),\n assignmentId: assignmentIdSchema.optional(),\n actor: actorSchema,\n causationId: id.optional(),\n idempotencyKey: id.optional(),\n occurredAt: timestamp,\n};\n\ntype Shapes = typeof EVENT_PAYLOADS;\ntype EnvelopeFields = z.infer<z.ZodObject<typeof envelope>>;\nexport type RuntimeEventV1 = {\n [K in EventType]: EnvelopeFields & { readonly type: K; readonly payloadVersion: 1; readonly data: z.infer<z.ZodObject<Shapes[K]>> }\n}[EventType];\nexport type RuntimeEventOf<K extends EventType> = Extract<RuntimeEventV1, { type: K }>;\n\nfunction variants(strict: boolean) {\n return EVENT_TYPES.map(type => z.strictObject({\n ...envelope,\n type: z.literal(type),\n payloadVersion: z.literal(1),\n data: strict ? z.strictObject(EVENT_PAYLOADS[type]) : z.object(EVENT_PAYLOADS[type]),\n }));\n}\n\nconst [firstWriter, ...restWriters] = variants(true);\nconst [firstReader, ...restReaders] = variants(false);\nif (firstWriter === undefined || firstReader === undefined) throw new Error('The runtime event union is empty.');\nconst writerSchema = z.discriminatedUnion('type', [firstWriter, ...restWriters]);\nconst readerSchema = z.discriminatedUnion('type', [firstReader, ...restReaders]);\n\n/** Strict validation before persistence; a writer never publishes anything else. */\nexport function validateForWrite(event: unknown): RuntimeEventV1 {\n return writerSchema.parse(event) as RuntimeEventV1;\n}\n\nexport type EventReadResult =\n | { readonly ok: true; readonly event: RuntimeEventV1 }\n | { readonly ok: false; readonly reason: 'unknown-type' | 'unsupported-version' | 'invalid'; readonly detail: string };\n\n/** Forward-tolerant within a supported payload version; fail-closed everywhere else. */\nexport function readEvent(value: unknown): EventReadResult {\n if (typeof value !== 'object' || value === null) return { ok: false, reason: 'invalid', detail: 'Event is not an object.' };\n const { type, payloadVersion } = value as { type?: unknown; payloadVersion?: unknown };\n if (typeof type !== 'string' || !Object.hasOwn(EVENT_PAYLOADS, type)) {\n return { ok: false, reason: 'unknown-type', detail: `Unknown event type ${typeof type === 'string' ? type : typeof type}.` };\n }\n if (typeof payloadVersion !== 'number' || !SUPPORTED_PAYLOAD_VERSIONS[type as EventType].includes(payloadVersion)) {\n return { ok: false, reason: 'unsupported-version', detail: `Unsupported payload version ${String(payloadVersion)} for ${type}.` };\n }\n const parsed = readerSchema.safeParse(value);\n return parsed.success\n ? { ok: true, event: parsed.data as RuntimeEventV1 }\n : { ok: false, reason: 'invalid', detail: z.prettifyError(parsed.error) };\n}\n","/**\n * No-clobber atomic publication for runtime state (docs/design/runtime-coordination.md §4.2).\n *\n * A file is written whole to a unique sibling temporary, fsynced, and published with `link()` to\n * a name that did not exist. `link()` fails with EEXIST instead of replacing, so a published\n * file can never be overwritten — not by an overlapping plugin reload and not by a retry. A\n * filesystem that cannot hard-link fails closed; there is deliberately no rename fallback,\n * because rename silently replaces an existing target.\n */\nimport { randomBytes } from 'node:crypto';\nimport { chmod, link, lstat, mkdir, open, readdir, unlink } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nexport const TEMPORARY_PREFIX = '.tmp-';\nexport const PRIVATE_DIR_MODE = 0o700;\nexport const PRIVATE_FILE_MODE = 0o600;\n\n/** Where a crash-boundary test may interrupt a publication. Production passes no hook. */\nexport type PublishStep = 'temporary-written' | 'temporary-synced' | 'linked' | 'temporary-removed';\nexport type PublishHook = (step: PublishStep) => void;\n\nexport class PublishUnsupportedError extends Error {\n constructor(directory: string, cause: unknown) {\n super(`The filesystem at ${directory} cannot publish runtime state without the risk of overwriting it (hard links unavailable).`, { cause });\n this.name = 'PublishUnsupportedError';\n }\n}\n\nexport class AlreadyPublishedError extends Error {\n constructor(readonly path: string) {\n super(`${path} is already published and is never replaced.`);\n this.name = 'AlreadyPublishedError';\n }\n}\n\nfunction code(error: unknown): string | undefined {\n return typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : undefined;\n}\n\nconst UNSUPPORTED = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EXDEV', 'EMLINK']);\n\n/** Creates a room-owned runtime directory as 0700. Existing directories are tightened, never loosened. */\nexport async function ensurePrivateDirectory(path: string): Promise<void> {\n await mkdir(path, { recursive: true, mode: PRIVATE_DIR_MODE });\n const stat = await lstat(path);\n if (!stat.isDirectory()) throw new Error(`${path} is not a directory.`);\n if ((stat.mode & 0o777) !== PRIVATE_DIR_MODE) await chmod(path, PRIVATE_DIR_MODE);\n}\n\nasync function writeTemporary(directory: string, content: string | Uint8Array, hook?: PublishHook): Promise<string> {\n const temporary = join(directory, `${TEMPORARY_PREFIX}${String(process.pid)}-${randomBytes(8).toString('hex')}`);\n const handle = await open(temporary, 'wx', PRIVATE_FILE_MODE);\n try {\n await handle.writeFile(content);\n hook?.('temporary-written');\n await handle.sync();\n hook?.('temporary-synced');\n } finally {\n await handle.close();\n }\n return temporary;\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n // Directory fsync makes the new name durable. Some platforms refuse it; the file itself is\n // already synced, so that refusal is tolerated rather than failing the publication.\n let handle;\n try {\n handle = await open(directory, 'r');\n await handle.sync();\n } catch (error) {\n if (!['EISDIR', 'EINVAL', 'EPERM', 'EBADF', 'ENOTSUP'].includes(code(error) ?? '')) throw error;\n } finally {\n await handle?.close();\n }\n}\n\nasync function publishWith(\n directory: string,\n content: string | Uint8Array,\n allocate: (attempt: number) => string | undefined,\n hook?: PublishHook,\n): Promise<string> {\n const temporary = await writeTemporary(directory, content, hook);\n let published: string | undefined;\n try {\n for (let attempt = 0; ; attempt += 1) {\n const name = allocate(attempt);\n if (name === undefined) break;\n const target = join(directory, name);\n try {\n await link(temporary, target);\n published = target;\n break;\n } catch (error) {\n const reason = code(error);\n if (reason === 'EEXIST') continue;\n if (reason !== undefined && UNSUPPORTED.has(reason)) throw new PublishUnsupportedError(directory, error);\n throw error;\n }\n }\n if (published !== undefined) hook?.('linked');\n } finally {\n await unlink(temporary).catch(() => undefined);\n }\n if (published === undefined) return '';\n hook?.('temporary-removed');\n await syncDirectory(directory);\n return published;\n}\n\n/**\n * Publishes `content` under exactly `name`. An existing file is never replaced: the call throws\n * `AlreadyPublishedError` and leaves both the existing file and nothing else behind.\n */\nexport async function publishOnce(directory: string, name: string, content: string | Uint8Array, hook?: PublishHook): Promise<string> {\n const path = await publishWith(directory, content, attempt => (attempt === 0 ? name : undefined), hook);\n if (path === '') throw new AlreadyPublishedError(join(directory, name));\n return path;\n}\n\n/**\n * Publishes `content` under the first free name `allocate` offers. EEXIST moves to the next\n * attempt, so two concurrent writers both succeed under distinct names and neither overwrites.\n */\nexport async function publishAllocating(\n directory: string,\n content: string | Uint8Array,\n allocate: (attempt: number) => string,\n options: { readonly maxAttempts?: number; readonly hook?: PublishHook } = {},\n): Promise<string> {\n const maxAttempts = options.maxAttempts ?? 64;\n const path = await publishWith(directory, content, attempt => (attempt < maxAttempts ? allocate(attempt) : undefined), options.hook);\n if (path === '') throw new Error(`Could not allocate a free name in ${directory} after ${String(maxAttempts)} attempts.`);\n return path;\n}\n\n/** Temporary files a crash left behind. They are never read as state; callers report them. */\nexport async function staleTemporaries(directory: string): Promise<string[]> {\n const names = await readdir(directory);\n return names.filter(name => name.startsWith(TEMPORARY_PREFIX)).sort();\n}\n","/**\n * Per-project runtime store (docs/design/runtime-coordination.md §4.1, §4.2).\n *\n * Immutable `meta.json` and immutable event files are the only authority. Everything under\n * `cache/` is disposable and rebuilt from replay. A project whose events cannot be read in full\n * is paused with its evidence preserved — never read as an empty ledger, never auto-repaired.\n */\nimport { randomBytes, randomUUID } from 'node:crypto';\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, join } from 'node:path';\nimport { z } from 'zod';\nimport { EVENT_SCHEMA, readEvent, validateForWrite, type RuntimeEventV1 } from '../events/schema.js';\nimport {\n AlreadyPublishedError, ensurePrivateDirectory, PRIVATE_FILE_MODE, publishOnce, staleTemporaries,\n} from './publish.js';\n\nexport const RUNTIME_LAYOUT_VERSION = 'v1';\nconst EVENT_FILE = /^(\\d{12})\\.json$/;\nconst MAX_SEQUENCE_ATTEMPTS = 64;\n\nexport function runtimeRoot(roomHome: string): string {\n return join(roomHome, 'runtime', RUNTIME_LAYOUT_VERSION);\n}\n\nconst metaSchema = z.strictObject({\n schema: z.literal(1),\n projectId: z.uuid(),\n createdAt: z.iso.datetime({ offset: true }),\n canonicalRoot: z.string().min(1),\n gitCommonDir: z.string().min(1),\n});\nexport type ProjectMeta = z.infer<typeof metaSchema>;\n\nexport interface ReplayProblem {\n readonly file: string;\n readonly reason: 'unknown-type' | 'unsupported-version' | 'invalid' | 'unreadable' | 'sequence-mismatch' | 'duplicate-id' | 'foreign-project' | 'unexpected-file';\n readonly detail: string;\n}\n\nexport interface ReplayResult {\n /** `paused` means the ledger is not fully readable; callers must refuse every mutation. */\n readonly status: 'ok' | 'paused';\n readonly events: readonly RuntimeEventV1[];\n readonly problems: readonly ReplayProblem[];\n /** Sequence numbers absent between 1 and the last event. Allowed and reported. */\n readonly gaps: readonly number[];\n readonly staleTemporaries: readonly string[];\n}\n\n/** An event as a writer supplies it; the store assigns envelope identity and order. */\nexport type NewEvent = Omit<RuntimeEventV1, 'schema' | 'version' | 'id' | 'sequence' | 'projectId' | 'occurredAt'>;\n\nfunction eventName(sequence: number): string {\n return `${String(sequence).padStart(12, '0')}.json`;\n}\n\nfunction slug(root: string): string {\n const name = basename(root).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32);\n return name === '' ? 'project' : name;\n}\n\nexport class ProjectStore {\n private lastSequence = 0;\n\n private constructor(readonly directory: string, readonly meta: ProjectMeta, private readonly now: () => Date) {}\n\n get eventsDirectory(): string { return join(this.directory, 'events'); }\n get cacheDirectory(): string { return join(this.directory, 'cache'); }\n get gatesDirectory(): string { return join(this.directory, 'gates'); }\n get quarantineDirectory(): string { return join(this.directory, 'quarantine'); }\n\n /** Opens an existing project directory; refuses one whose `meta.json` is not exactly v1. */\n static async open(directory: string, now: () => Date = () => new Date()): Promise<ProjectStore> {\n const meta = metaSchema.parse(JSON.parse(await readFile(join(directory, 'meta.json'), 'utf8')));\n return new ProjectStore(directory, meta, now);\n }\n\n /**\n * Binds a new project to its canonical Git common directory. Identity is a minted UUID, never\n * a hash of a movable path; a moved repository is rebound only by an explicit operator action.\n */\n static async create(\n root: string,\n binding: { readonly canonicalRoot: string; readonly gitCommonDir: string },\n now: () => Date = () => new Date(),\n ): Promise<ProjectStore> {\n const projects = join(root, 'projects');\n await ensurePrivateDirectory(projects);\n const projectId = randomUUID();\n const directory = join(projects, `${slug(binding.canonicalRoot)}-${projectId}`);\n await ensurePrivateDirectory(directory);\n for (const child of ['events', 'cache', 'gates', 'quarantine']) await ensurePrivateDirectory(join(directory, child));\n const meta: ProjectMeta = { schema: 1, projectId, createdAt: now().toISOString(), ...binding };\n await publishOnce(directory, 'meta.json', `${JSON.stringify(meta, null, 2)}\\n`);\n const store = new ProjectStore(directory, meta, now);\n await store.append({ type: 'project.bound', payloadVersion: 1, actor: { source: 'plugin' }, data: { ...binding } });\n return store;\n }\n\n /** Finds the project bound to this Git common directory. Never matches by name, remote or cwd. */\n static async find(root: string, gitCommonDir: string, now?: () => Date): Promise<ProjectStore | undefined> {\n for (const store of await ProjectStore.list(root, now)) {\n if (store.meta.gitCommonDir === gitCommonDir) return store;\n }\n return undefined;\n }\n\n static async list(root: string, now?: () => Date): Promise<ProjectStore[]> {\n const projects = join(root, 'projects');\n let names: string[];\n try { names = await readdir(projects); } catch { return []; }\n const stores: ProjectStore[] = [];\n for (const name of names.sort()) {\n try { stores.push(await ProjectStore.open(join(projects, name), now)); } catch { /* reported by diagnostics, never adopted */ }\n }\n return stores;\n }\n\n /** Reads every event strictly. Any unreadable file pauses the project; nothing is moved. */\n async replay(): Promise<ReplayResult> {\n const names = (await readdir(this.eventsDirectory)).sort();\n const problems: ReplayProblem[] = [];\n const events: RuntimeEventV1[] = [];\n const ids = new Map<string, string>();\n for (const name of names) {\n if (name.startsWith('.tmp-')) continue;\n const match = EVENT_FILE.exec(name);\n if (!match) { problems.push({ file: name, reason: 'unexpected-file', detail: 'Not a runtime event file name.' }); continue; }\n let raw: string;\n let value: unknown;\n try {\n raw = await readFile(join(this.eventsDirectory, name), 'utf8');\n value = JSON.parse(raw);\n } catch (error) {\n problems.push({ file: name, reason: 'unreadable', detail: error instanceof Error ? error.message : String(error) });\n continue;\n }\n const read = readEvent(value);\n if (!read.ok) { problems.push({ file: name, reason: read.reason, detail: read.detail }); continue; }\n const event = read.event;\n if (event.sequence !== Number(match[1])) {\n problems.push({ file: name, reason: 'sequence-mismatch', detail: `File name does not match sequence ${String(event.sequence)}.` });\n continue;\n }\n if (event.projectId !== this.meta.projectId) {\n problems.push({ file: name, reason: 'foreign-project', detail: `Event belongs to project ${event.projectId}.` });\n continue;\n }\n const previous = ids.get(event.id);\n if (previous !== undefined) {\n problems.push({ file: name, reason: 'duplicate-id', detail: `Event id ${event.id} is also used by ${previous}.` });\n continue;\n }\n ids.set(event.id, name);\n events.push(event);\n }\n const gaps: number[] = [];\n let expected = 1;\n for (const event of events) {\n for (; expected < event.sequence; expected += 1) gaps.push(expected);\n expected = event.sequence + 1;\n }\n const highest = names.map(name => EVENT_FILE.exec(name)?.[1]).filter((value): value is string => value !== undefined).map(Number);\n this.lastSequence = Math.max(this.lastSequence, 0, ...highest);\n return {\n status: problems.length === 0 ? 'ok' : 'paused',\n events,\n problems,\n gaps,\n staleTemporaries: await staleTemporaries(this.eventsDirectory),\n };\n }\n\n /**\n * Validates and publishes one event at the next free sequence. A concurrent writer that took\n * that sequence causes reallocation, never replacement.\n */\n async append(event: NewEvent): Promise<RuntimeEventV1> {\n if (this.lastSequence === 0) await this.replay();\n // Fixed per call, so concurrent appends probe successive free sequences instead of skipping.\n const base = this.lastSequence;\n for (let attempt = 0; attempt < MAX_SEQUENCE_ATTEMPTS; attempt += 1) {\n const sequence = base + 1 + attempt;\n const full = validateForWrite({\n ...event,\n schema: EVENT_SCHEMA,\n version: 1,\n id: `evt_${randomBytes(12).toString('hex')}`,\n sequence,\n projectId: this.meta.projectId,\n occurredAt: this.now().toISOString(),\n });\n try {\n await publishOnce(this.eventsDirectory, eventName(sequence), `${JSON.stringify(full)}\\n`);\n this.lastSequence = Math.max(this.lastSequence, sequence);\n return full;\n } catch (error) {\n if (!(error instanceof AlreadyPublishedError)) throw error;\n }\n }\n throw new Error(`Could not allocate an event sequence in ${this.eventsDirectory}.`);\n }\n\n /** Writes one disposable derived view. Cache files may be replaced; they are never authority. */\n async writeCache(name: string, content: string): Promise<void> {\n await mkdir(this.cacheDirectory, { recursive: true, mode: 0o700 });\n const temporary = join(this.cacheDirectory, `.tmp-${String(process.pid)}-${randomBytes(6).toString('hex')}`);\n await writeFile(temporary, content, { mode: PRIVATE_FILE_MODE });\n await rename(temporary, join(this.cacheDirectory, name));\n }\n\n async readCache(name: string): Promise<string | undefined> {\n try { return await readFile(join(this.cacheDirectory, name), 'utf8'); } catch { return undefined; }\n }\n\n /** Deletes every cached view; the next replay rebuilds them. */\n async clearCache(): Promise<void> {\n await rm(this.cacheDirectory, { recursive: true, force: true });\n await ensurePrivateDirectory(this.cacheDirectory);\n }\n\n /** Moves one named event file aside. Only an explicit operator action calls this. */\n async quarantine(file: string): Promise<void> {\n if (!EVENT_FILE.test(file) && !file.startsWith('.tmp-')) throw new Error(`${file} is not a runtime event file.`);\n await ensurePrivateDirectory(this.quarantineDirectory);\n await rename(join(this.eventsDirectory, file), join(this.quarantineDirectory, file));\n }\n}\n","import { existsSync } from 'node:fs';\nimport { readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { project } from './runtime-plugin/server/domain/state.js';\nimport { quiescence, worktreesOnDisk, type QuiescenceBlocker } from './runtime-plugin/server/domain/views.js';\nimport { ProjectStore, runtimeRoot } from './runtime-plugin/server/store/project.js';\n\n/**\n * A read-only look at the runtime state a room recorded, using the plugin's own replay and\n * projection. The CLI never writes, repairs or quarantines anything under `runtime/`.\n */\nexport interface RuntimeStateSummary {\n readonly root: string;\n readonly projects: number;\n /** Everything still active or uncertain; a paused ledger counts, since it cannot be proven quiet. */\n readonly blockers: readonly (QuiescenceBlocker & { readonly project: string })[];\n /** Runtime worktrees Paseo still lists, awaiting a close. They are Paseo's; the CLI never closes them. */\n readonly retainedWorktrees: number;\n /** Directories Paseo archived but left behind. The CLI never deletes them either. */\n readonly leftoverDirectories: number;\n}\n\nexport async function inspectRuntimeState(roomHome: string): Promise<RuntimeStateSummary> {\n const root = runtimeRoot(roomHome);\n const names = await readdir(join(root, 'projects')).catch(() => [] as string[]);\n const blockers: (QuiescenceBlocker & { project: string })[] = [];\n const stores: ProjectStore[] = [];\n let retained = 0;\n let leftover = 0;\n for (const name of names.sort()) {\n try {\n stores.push(await ProjectStore.open(join(root, 'projects', name)));\n } catch {\n // Unreadable metadata is unknown state, never an empty project.\n blockers.push({ project: name, kind: 'assignment', id: name, detail: 'has unreadable project metadata' });\n }\n }\n for (const store of stores) {\n const replay = await store.replay();\n const projection = project(store.meta.projectId, replay.events);\n if (replay.status !== 'ok' || projection.violations.length > 0) {\n blockers.push({ project: store.meta.canonicalRoot, kind: 'assignment', id: store.meta.projectId, detail: 'the project ledger is paused and cannot be proven quiet' });\n continue;\n }\n for (const blocker of quiescence(projection.state).blockers) blockers.push({ ...blocker, project: store.meta.canonicalRoot });\n const onDisk = worktreesOnDisk(projection.state, existsSync);\n retained += onDisk.retained;\n leftover += onDisk.leftover;\n }\n return { root, projects: names.length, blockers, retainedWorktrees: retained, leftoverDirectories: leftover };\n}\n\nexport function describeBlockers(summary: RuntimeStateSummary, limit = 5): string {\n const shown = summary.blockers.slice(0, limit).map(blocker => `${blocker.project}: ${blocker.kind} ${blocker.id} ${blocker.detail}`);\n const more = summary.blockers.length > limit ? `; and ${String(summary.blockers.length - limit)} more` : '';\n return `${shown.join('; ')}${more}`;\n}\n","import { join, sep } from 'node:path';\nimport { lstat, rm } from 'node:fs/promises';\nimport { satisfies } from 'semver';\nimport metadata from '../package.json' with { type: 'json' };\nimport { claudeAgent } from './agents/claude.js';\nimport { codexAgent } from './agents/codex.js';\nimport { piAgent } from './agents/pi.js';\nimport type { Agent, AgentPlan, BuildOptions, Profile, Provider } from './agents/types.js';\nimport { AUTHENTICATION_GUIDE, renderAuthenticationGuide } from './auth.js';\nimport { applyEntries, exists, planEntries, type Entry } from './fsops.js';\nimport { layoutChecks, resolveLayout, roleHome, sharedRoom, type Layout, type Options } from './layout.js';\nimport { checkDaemon, mergeProfiles, minimumPaseoVersion, profileMatches, providerMatches, withSession, type ClientFactory, type LivePlugin, type LiveProfile, type Session } from './paseo.js';\nimport { CLAUDE_CARRIER_PASEO_RANGE, CLAUDE_CARRIER_PLUGIN_ID, claudeCarrierEntries, claudeCarrierPluginDir } from './plugin.js';\nimport { fail, failed, hasFailure, pass, warn, type Check, type Operation, type Result } from './result.js';\nimport { contractDigest } from './room/instructions.js';\nimport {\n agentSkillProjectionRoot, leadSkillProjection, roomSkillEntries, roomSkillSource, skillProjectionRoot,\n} from './room/skills.js';\nimport { MARKER, readMarker, renderMarker, type Marker, type RuntimeMarker } from './room.js';\nimport {\n renderRuntimeManifest, RUNTIME_PASEO_RANGE, RUNTIME_PLUGIN_ID, runtimePluginDir, runtimePluginEntries,\n} from './runtime.js';\nimport { describeBlockers, inspectRuntimeState, type RuntimeStateSummary } from './runtime-state.js';\nimport { DELEGATING_THINKING, profileId, providerId, providerLabel, ROLES, ROLE_COLOR, ROLE_ICON, ROLE_NOTES, ROLE_PASEO_TOOLS, ROLE_THINKING, type AgentId, type Role } from './roles.js';\n\nexport const AGENTS: Record<AgentId, Agent> = { codex: codexAgent, claude: claudeAgent, pi: piAgent };\n\nexport interface RunOptions extends Options {\n readonly agents?: readonly AgentId[];\n readonly apply?: boolean;\n /**\n * Write the role contract into Claude's `CLAUDE.md` as well as the plugin. Defaults to true:\n * the plugin is the strong carrier, but whether a resumed session re-enters its creation hook\n * is unproven, so the file fallback is only dropped when asked for.\n */\n readonly claudeMemoryContract?: boolean;\n /** Opt in to runtime coordination (preview). A per-run setup choice, recorded in the marker. */\n readonly runtime?: boolean;\n readonly env?: NodeJS.ProcessEnv;\n readonly factory?: ClientFactory;\n}\n\nfunction sessionOptions(options: RunOptions): { password?: string; factory?: ClientFactory } {\n const password = (options.env ?? process.env).PASEO_PASSWORD;\n return { ...(password === undefined ? {} : { password }), ...(options.factory ? { factory: options.factory } : {}) };\n}\n\n/** The only per-agent differences are the home variable and the provider pins. */\nfunction roleProviders(\n layout: Layout,\n agent: Agent,\n plan: { readonly binary: string; readonly argv?: AgentPlan['argv']; readonly providerEnv?: AgentPlan['providerEnv'] },\n roles: readonly Role[],\n): Record<string, Provider> {\n return Object.fromEntries(roles.map(role => [providerId(agent.id, role), {\n extends: agent.id,\n label: providerLabel(agent.id, role),\n command: [plan.binary, ...(plan.argv?.[role] ?? [])],\n env: { ...agent.providerEnv, ...plan.providerEnv?.[role], [agent.homeEnv]: roleHome(layout, agent.id, role) },\n paseoTools: { enabled: ROLE_PASEO_TOOLS[role] },\n ...agent.pins,\n }]));\n}\n\n/** The picker preset that points at a provider, so a seat is one click rather than four. */\nfunction roleProfiles(agent: Agent, roles: readonly Role[]): Profile[] {\n return roles.map(role => ({\n id: profileId(agent.id, role),\n name: providerLabel(agent.id, role),\n icon: ROLE_ICON[role],\n color: ROLE_COLOR[role],\n provider: providerId(agent.id, role),\n ...(agent.defaultModeId === undefined ? {} : { modeId: agent.defaultModeId }),\n thinkingOptionId: ROLE_THINKING[role],\n notes: ROLE_NOTES[role],\n }));\n}\n\n/**\n * A trusted Paseo plugin the room owns. The Claude carrier and the runtime are separate\n * plugins with separate ids, paths and diagnostics, so a fault in one never names or touches the\n * other (docs/design/runtime-coordination.md D1).\n */\ninterface PluginSpec {\n readonly id: string;\n readonly path: string;\n /** Check id prefix: `<prefix>.enabled`, `<prefix>.path`, `<prefix>.runtime`. */\n readonly check: string;\n readonly running: string;\n readonly enabledPass: string;\n readonly enabledFail: string;\n /**\n * The manifest's `requirements.paseo`. Paseo refuses to install a plugin outside it, so the\n * room states the same bound as its own check rather than letting `--apply` surface the\n * daemon's error. Its id is explicit because the two plugins were named independently.\n */\n readonly paseoRange: string;\n readonly rangeCheck: string;\n readonly rangeRemedy: string;\n}\n\nfunction carrierSpec(layout: Layout): PluginSpec {\n return {\n id: CLAUDE_CARRIER_PLUGIN_ID, path: claudeCarrierPluginDir(layout), check: 'claude.plugin',\n running: 'Claude contract carrier plugin',\n enabledPass: 'Paseo plugins are enabled for the required Claude contract carrier.',\n enabledFail: 'Claude rooms require the paseo-room trusted server plugin, but Paseo plugins are disabled. Plugins are trusted, unsandboxed code with access to the daemon machine.',\n paseoRange: CLAUDE_CARRIER_PASEO_RANGE, rangeCheck: 'claude.paseo-range',\n rangeRemedy: 'Use a Paseo release inside that range, or upgrade paseo-room, then run setup again.',\n };\n}\n\nfunction runtimeSpec(layout: Layout): PluginSpec {\n return {\n id: RUNTIME_PLUGIN_ID, path: runtimePluginDir(layout), check: 'runtime.plugin',\n running: 'Runtime coordination plugin (preview)',\n enabledPass: 'Paseo plugins are enabled for the runtime coordination plugin.',\n enabledFail: 'Runtime coordination is a trusted server plugin, but Paseo plugins are disabled. Plugins are trusted, unsandboxed code with access to the daemon machine.',\n paseoRange: RUNTIME_PASEO_RANGE, rangeCheck: 'runtime.paseo-range',\n rangeRemedy: 'Use a Paseo release inside that range, or run setup without --runtime.',\n };\n}\n\ninterface Desired {\n readonly entries: readonly Entry[];\n readonly providers: Readonly<Record<string, Provider>>;\n readonly profiles: readonly Profile[];\n readonly checks: readonly Check[];\n /** Room plugins this selection requires, carrier first. */\n readonly plugins: readonly PluginSpec[];\n readonly runtime?: RuntimeMarker;\n}\nasync function buildDesired(\n layout: Layout,\n agents: readonly AgentId[],\n roles: readonly Role[],\n build: BuildOptions & { readonly runtime?: boolean } = {},\n): Promise<Desired> {\n // The room-owned skill source is composed once here rather than per adapter, so three\n // seated agents cannot declare the same managed paths three times.\n const entries: Entry[] = [\n { kind: 'dir', path: layout.roomHome },\n { kind: 'dir', path: sharedRoom(layout) },\n // Earlier versions generated a default workspace protocol template here. The room ships no\n // default protocol now, so the old generated regular file is declared absent and removed.\n { kind: 'absent', path: join(sharedRoom(layout), 'WORKSPACE_PROTOCOL.md') },\n ...roomSkillEntries(layout, agents),\n ];\n const providers: Record<string, Provider> = {};\n const profiles: Profile[] = [];\n const checks: Check[] = [];\n const binaries: Partial<Record<AgentId, string>> = {};\n for (const id of agents) {\n const agent = AGENTS[id];\n const plan = await agent.build(layout, roles, build);\n entries.push(...plan.entries);\n checks.push(...plan.checks);\n const credentials = plan.credentials ?? [];\n checks.push(...credentials.flatMap(credential => credential.checks));\n const credentialPaths = new Set(credentials.map(credential => credential.path));\n const collisions = plan.entries.filter(entry => credentialPaths.has(entry.path));\n if (collisions.length > 0) {\n checks.push(fail(`${id}.credentials`,\n `${agent.label} produced managed entries for preserve-only credential paths: ${collisions.map(entry => entry.path).join(', ')}.`,\n 'This is an adapter defect; do not apply the plan.'));\n }\n if (plan.binary === undefined) continue;\n binaries[id] = plan.binary;\n Object.assign(providers, roleProviders(layout, agent, {\n binary: plan.binary,\n ...(plan.argv ? { argv: plan.argv } : {}),\n ...(plan.providerEnv ? { providerEnv: plan.providerEnv } : {}),\n }, roles));\n profiles.push(...roleProfiles(agent, roles));\n }\n if (agents.every(id => binaries[id] !== undefined)) {\n entries.push({\n kind: 'file',\n path: join(layout.roomHome, AUTHENTICATION_GUIDE),\n content: renderAuthenticationGuide(layout.roomHome, binaries, agents, roles),\n });\n checks.push(warn('room.authentication-not-validated',\n `Role authentication was not validated. Login instructions are managed at ${join(layout.roomHome, AUTHENTICATION_GUIDE)}.`,\n 'After setup --apply, follow that guide or run: paseo-room auth login <agent> <role>'));\n }\n const plugins: PluginSpec[] = [];\n if (agents.includes('claude')) {\n plugins.push(carrierSpec(layout));\n entries.push(...claudeCarrierEntries(layout, roles));\n }\n let runtime: RuntimeMarker | undefined;\n if (build.runtime === true) {\n plugins.push(runtimeSpec(layout));\n entries.push(...runtimePluginEntries(layout, agents, roles));\n runtime = { enabled: true, generation: renderRuntimeManifest(agents, roles).roomGeneration, schema: 1 };\n }\n entries.push({ kind: 'file', path: join(layout.roomHome, MARKER), content: renderMarker(metadata.version, agents, roles, contractDigest(), markerMemoryContract(agents, build.memoryContract ?? true), runtime) });\n return { entries, providers, profiles, checks, plugins, ...(runtime === undefined ? {} : { runtime }) };\n}\n\n/**\n * The marker records which rendered contract generation installed this room, so an operator\n * who upgrades the package can see that the seats now hold older text. A room installed\n * before provenance existed has no digest, which is reported the same way rather than\n * treated as a broken marker.\n */\nfunction contractProvenance(previous: Marker | undefined): Check[] {\n const digest = contractDigest();\n if (!previous) return [];\n if (previous.contract === digest) {\n return [pass('room.contract', `Role contract generation ${digest} matches this package.`)];\n }\n const held = previous.contract === undefined\n ? `was installed before the room recorded its contract generation (package ${previous.version})`\n : `holds contract generation ${previous.contract}`;\n return [warn('room.contract',\n `This room ${held}; this package renders ${digest}. Managed role documents are rewritten by setup, and a running seat keeps the text it started with.`,\n 'Run: paseo-room setup --apply, then restart the affected seats.')];\n}\n\n/**\n * `thinkingOptionId` is seeded once and the operator's afterwards, so a risky selection is\n * reported rather than corrected. Nothing here changes provider selection, profile writes, or\n * exit status.\n */\nfunction thinkingDiagnostics(live: readonly LiveProfile[], desired: readonly Profile[]): Check[] {\n const owned = new Set(desired.map(profile => profile.id));\n const selected = live\n .filter(entry => owned.has(String(entry.id)))\n .filter(entry => DELEGATING_THINKING.some(option => option === entry.thinkingOptionId))\n .map(entry => `${String(entry.id)} (${String(entry.thinkingOptionId)})`)\n .sort();\n if (selected.length === 0) return [];\n return [warn('room.thinking',\n `${String(selected.length)} room seats are set to a top reasoning option that Paseo describes as including automatic task delegation: ${selected.join(', ')}. Whether that option can actually delegate once the room has closed the native multi-agent paths is unverified: paseo-room has not verified whether those closures prevent that option from delegating, and left your selection in place.`,\n `Choose a lower reasoning option for those seats in Paseo if you want the room's own defaults (${ROLE_THINKING.supervisor} for Supervisor, ${ROLE_THINKING.lead} for Lead and Peer).`)];\n}\n\n/**\n * Names what kind of drift was found. A path the room suppressed needs deleting rather than\n * rewriting, so reporting every difference as \"missing or outdated\" would name the wrong fix.\n */\nfunction fileDriftSummary(drifted: readonly Operation[]): string {\n const removals = drifted.filter(operation => operation.action === 'remove').length;\n const count = String(drifted.length);\n const subject = drifted.length === 1 ? 'managed role file is' : 'managed role files are';\n if (removals === 0) return `${count} ${subject} missing or outdated.`;\n if (removals === drifted.length) return `${count} ${subject} present but suppressed by this room.`;\n return `${count} ${subject} missing or outdated, and ${String(removals)} of them are present but suppressed by this room.`;\n}\n\n/** Catalog copies are one of the room's three native multi-agent closures, so their drift is named. */\nfunction fileDriftDetail(targets: readonly string[]): string {\n const catalogs = targets.filter(target => target.endsWith(`${sep}model-catalog.json`));\n if (catalogs.length === 0) return '';\n const count = catalogs.length === 1 ? 'One of them is a generated Codex model catalog' : `${String(catalogs.length)} of them are generated Codex model catalogs`;\n return ` ${count}, so those seats currently lack the scrubbed catalog closure rather than only older contract text.`;\n}\n\ninterface Stale {\n readonly providerIds: readonly string[];\n readonly profileIds: readonly string[];\n /** Room plugins a previous selection registered that this one does not. */\n readonly removePlugins: readonly PluginSpec[];\n /** Role homes are retained during setup because runtime-owned credentials may be inside. */\n readonly retainedDirectories: readonly string[];\n}\nconst NOTHING_STALE: Stale = { providerIds: [], profileIds: [], removePlugins: [], retainedDirectories: [] };\n\nasync function safeDirectory(path: string, checks: Check[]): Promise<boolean> {\n try {\n const stat = await lstat(path);\n if (stat.isDirectory()) return true;\n checks.push(fail('room.path-safety',\n `Refusing to traverse ${path}: every existing room directory ancestor must be a real directory, not a symbolic link or another file type.`,\n 'Move the path aside manually after checking it for role-owned credentials, then run the command again.'));\n return false;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;\n checks.push(fail('room.path-safety', `Could not inspect room directory ${path} without following links.`,\n 'Fix its parent permissions or move the path manually, then run the command again.'));\n return false;\n }\n}\n\n/** Refuse managed writes through any existing room-relative directory alias. */\nasync function roomPathSafety(layout: Layout, agents: readonly AgentId[], roles: readonly Role[]): Promise<Check[]> {\n const checks: Check[] = [];\n if (!await safeDirectory(layout.roomHome, checks)) return checks;\n\n const room = sharedRoom(layout);\n const roomIsSafe = await safeDirectory(room, checks);\n // Calls with no agents are root-only checks used before marker discovery and by explicit remove.\n // Recursive removal unlinks nested symlinks without following them, so it must remain able to\n // delete a broken room; setup and verify make a later full pass with the affected agents.\n if (roomIsSafe && agents.length > 0) {\n const skills = join(room, 'skills');\n if (await safeDirectory(skills, checks)) {\n const source = roomSkillSource(layout);\n if (await safeDirectory(source, checks)) await safeDirectory(join(source, 'references'), checks);\n }\n const projections = skillProjectionRoot(layout);\n if (await safeDirectory(projections, checks)) {\n for (const agent of agents) {\n const agentRoot = agentSkillProjectionRoot(layout, agent);\n if (await safeDirectory(agentRoot, checks)) await safeDirectory(leadSkillProjection(layout, agent), checks);\n }\n }\n }\n\n const rolesHome = join(layout.roomHome, 'roles');\n if (!await safeDirectory(rolesHome, checks)) return checks;\n for (const agent of agents) {\n const agentHome = join(rolesHome, agent);\n if (!await safeDirectory(agentHome, checks)) continue;\n for (const role of roles) await safeDirectory(roleHome(layout, agent, role), checks);\n }\n return checks;\n}\n\n/** A previous setup may have seated agents or roles this one does not: drop those. */\nasync function staleFrom(\n layout: Layout, previous: Marker | undefined, agents: readonly AgentId[], roles: readonly Role[], runtime: boolean,\n): Promise<Stale> {\n if (!previous) return NOTHING_STALE;\n const kept = new Set(agents.flatMap(agent => roles.map(role => providerId(agent, role))));\n const providerIds: string[] = [];\n const profileIds: string[] = [];\n const retainedDirectories: string[] = [];\n for (const agent of previous.agents) {\n for (const role of previous.roles) {\n if (kept.has(providerId(agent, role))) continue;\n providerIds.push(providerId(agent, role));\n profileIds.push(profileId(agent, role));\n const path = roleHome(layout, agent, role);\n if (await exists(path)) retainedDirectories.push(path);\n }\n }\n return {\n providerIds,\n profileIds,\n removePlugins: [\n ...(previous.agents.includes('claude') && !agents.includes('claude') ? [carrierSpec(layout)] : []),\n ...(previous.runtime?.enabled === true && !runtime ? [runtimeSpec(layout)] : []),\n ],\n retainedDirectories,\n };\n}\n\ninterface Plan {\n readonly operations: readonly Operation[];\n /** Carried out of the plan so apply rewrites the array it actually compared against. */\n readonly liveProfiles: readonly LiveProfile[];\n readonly livePlugins: ReadonlyMap<string, LivePlugin>;\n readonly pluginChecks: readonly Check[];\n}\n\nfunction pluginPlan(spec: PluginSpec, wanted: boolean, plugins: readonly LivePlugin[]): {\n operation?: Operation; livePlugin?: LivePlugin; checks: Check[];\n} {\n const livePlugin = plugins.find(plugin => plugin.id === spec.id);\n if (livePlugin !== undefined && livePlugin.path !== spec.path) {\n return {\n livePlugin,\n checks: [fail(`${spec.check}.path`,\n `Plugin ${spec.id} is registered from ${livePlugin.path}, not the room-owned path ${spec.path}.`,\n 'Move or remove that conflicting plugin registration manually, then run setup again.')],\n };\n }\n if (wanted) {\n const healthy = livePlugin?.enabled === true && livePlugin.status === 'running' && livePlugin.error === undefined;\n return {\n ...(livePlugin === undefined ? {} : { livePlugin }),\n operation: { action: livePlugin === undefined ? 'create' : healthy ? 'noop' : 'update', kind: 'plugin', target: spec.id },\n checks: [],\n };\n }\n return {\n ...(livePlugin === undefined ? {} : { livePlugin }),\n operation: { action: livePlugin === undefined ? 'noop' : 'remove', kind: 'plugin', target: spec.id },\n checks: [],\n };\n}\n\n/** One definition of drift, shared by the command that fixes it and the one that reports it. */\nasync function planRoom(session: Session, desired: Desired, stale: Stale): Promise<Plan> {\n const inspectPlugins = desired.plugins.length > 0 || stale.removePlugins.length > 0;\n const [live, liveProfiles, plugins] = await Promise.all([\n session.readProviders(), session.readProfiles(), inspectPlugins ? session.listPlugins() : Promise.resolve([]),\n ]);\n const byId = new Map(liveProfiles.map(entry => [String(entry.id), entry]));\n const planned = [\n ...desired.plugins.map(spec => pluginPlan(spec, true, plugins)),\n ...stale.removePlugins.map(spec => pluginPlan(spec, false, plugins)),\n ];\n const livePlugins = new Map<string, LivePlugin>();\n for (const plugin of planned) if (plugin.livePlugin !== undefined) livePlugins.set(plugin.livePlugin.id, plugin.livePlugin);\n return {\n liveProfiles,\n livePlugins,\n pluginChecks: planned.flatMap(plugin => plugin.checks),\n operations: [\n ...await planEntries(desired.entries),\n ...Object.entries(desired.providers).map(([id, provider]) => ({\n action: !(id in live) ? 'create' : providerMatches(provider, live[id]) ? 'noop' : 'update',\n kind: 'provider',\n target: id,\n }) satisfies Operation),\n ...desired.profiles.map(profile => ({\n action: !byId.has(profile.id) ? 'create' : profileMatches(profile, byId.get(profile.id)) ? 'noop' : 'update',\n kind: 'profile',\n target: profile.id,\n }) satisfies Operation),\n ...stale.providerIds.filter(id => id in live).map(id => ({ action: 'remove', kind: 'provider', target: id }) satisfies Operation),\n ...stale.profileIds.filter(id => byId.has(id)).map(id => ({ action: 'remove', kind: 'profile', target: id }) satisfies Operation),\n ...planned.flatMap(plugin => (plugin.operation === undefined ? [] : [plugin.operation])),\n ],\n };\n}\n\nfunction pluginsEnabledCheck(spec: PluginSpec, enabled: boolean): Check {\n return enabled\n ? pass(`${spec.check}.enabled`, spec.enabledPass)\n : fail(`${spec.check}.enabled`, spec.enabledFail,\n 'Review that trust boundary, enable plugins in Paseo Settings, reload Paseo, then run setup again.');\n}\n\nfunction pluginRuntimeCheck(spec: PluginSpec, plugin: LivePlugin | undefined): Check {\n if (plugin === undefined) {\n return fail(`${spec.check}.runtime`, `Plugin ${spec.id} is not registered.`, 'Run: paseo-room setup --apply');\n }\n if (plugin.path !== spec.path) {\n return fail(`${spec.check}.runtime`, `Plugin ${spec.id} is registered from ${plugin.path}, not ${spec.path}.`,\n 'Move or remove that conflicting plugin registration manually, then run setup again.');\n }\n if (!plugin.enabled || plugin.status !== 'running' || plugin.error !== undefined) {\n const detail = plugin.error === undefined ? `status ${plugin.status}` : `${plugin.status}: ${plugin.error}`;\n return fail(`${spec.check}.runtime`, `Plugin ${spec.id} is not running (${detail}).`, 'Run: paseo-room setup --apply');\n }\n return pass(`${spec.check}.runtime`, `${spec.running} is running from ${spec.path}.`);\n}\n\nasync function reconcilePlugins(session: Session, desired: Desired, stale: Stale, plan: Plan, pending: readonly Operation[]): Promise<Check[]> {\n for (const spec of stale.removePlugins) {\n if (plan.livePlugins.has(spec.id)) await session.removePlugin(spec.id);\n }\n const checks: Check[] = [];\n for (const spec of desired.plugins) {\n let plugin = plan.livePlugins.get(spec.id);\n if (plugin === undefined) {\n plugin = await session.installPlugin(spec.path, spec.id);\n } else {\n if (!plugin.enabled) plugin = await session.enablePlugin(spec.id);\n const filesChanged = pending.some(operation =>\n (operation.kind === 'file' || operation.kind === 'dir') && operation.target.startsWith(`${spec.path}${sep}`),\n );\n const needsReload = filesChanged || plugin.status !== 'running' || plugin.error !== undefined;\n if (needsReload) plugin = await session.reloadPlugin(spec.id);\n }\n checks.push(pluginRuntimeCheck(spec, plugin));\n }\n return checks;\n}\n\n/**\n * A room plugin's range is exact on both ends: `0.8.0` and `0.9.1` are live-qualified and\n * `0.10.0` is unqualified. Selecting the plugin accepts that bound; not selecting it never\n * raises the baseline, which stays the floor `minimumPaseoVersion` reports.\n */\nfunction pluginRangeCheck(spec: PluginSpec, version: string): Check {\n return satisfies(version, spec.paseoRange)\n ? pass(spec.rangeCheck, `Paseo ${version} is inside the ${spec.running} range ${spec.paseoRange}.`)\n : fail(spec.rangeCheck, `${spec.running} supports Paseo ${spec.paseoRange}; the running daemon is ${version}.`, spec.rangeRemedy);\n}\n\n/**\n * Deselecting runtime must not strand work it recorded: it is refused while any assignment,\n * writer ownership, managed Peer archive, gate or delivery is active or uncertain. Once quiet,\n * the plugin is unregistered and the recorded state is kept for export or a later re-enable.\n */\nasync function runtimeDeselectionCheck(layout: Layout): Promise<Check[]> {\n const summary = await inspectRuntimeState(layout.roomHome);\n if (summary.projects === 0) return [];\n if (summary.blockers.length > 0) {\n return [fail('runtime.deselect',\n `Runtime coordination still has active or uncertain work: ${describeBlockers(summary)}.`,\n 'Keep --runtime and finish, close or abandon that work first; the runtime state is preserved either way.')];\n }\n return [warn('runtime.state-retained',\n `Runtime coordination is quiet; its recorded state for ${String(summary.projects)} project(s) stays at ${summary.root}.${worktreeNote(summary, 'gone')}`,\n 'Export it with: paseo-room export --out <dir>, or keep it for a later --runtime.')];\n}\n\n/**\n * Retained runtime worktrees and left-behind directories belong to Paseo and the operator: named,\n * counted, never deleted by the CLI. The remedy depends on whether the runtime panel still exists.\n */\nfunction worktreeNote(summary: RuntimeStateSummary, panel: 'available' | 'gone'): string {\n const parts: string[] = [];\n if (summary.retainedWorktrees > 0) {\n parts.push(` ${String(summary.retainedWorktrees)} runtime worktree(s) remain open in Paseo; the CLI does not close them — ${panel === 'available'\n ? 'close them from the runtime panel first'\n : 'archive them in Paseo, or re-enable --runtime and close them from the runtime panel'}.`);\n }\n if (summary.leftoverDirectories > 0) {\n parts.push(` ${String(summary.leftoverDirectories)} closed worktree director(ies) were left on disk by a failed teardown; remove them by hand once nothing in them is needed.`);\n }\n return parts.join('');\n}\n\n/** Whole-room removal keeps its destructive meaning, but says what runtime history it deletes. */\nasync function runtimeRemovalWarning(layout: Layout): Promise<Check[]> {\n const summary = await inspectRuntimeState(layout.roomHome).catch(() => undefined);\n if (summary === undefined || summary.projects === 0) return [];\n const active = summary.blockers.length > 0 ? ` It still has active or uncertain work: ${describeBlockers(summary)}.` : '';\n return [warn('room.remove.runtime-state',\n `Deleting ${layout.roomHome} also deletes runtime coordination history for ${String(summary.projects)} project(s).${active}${worktreeNote(summary, 'available')}`,\n 'Export it first with: paseo-room export --out <dir>')];\n}\n\n/**\n * The marker value for the Claude memory-contract choice. A room with no Claude seat records\n * nothing: the choice only describes Claude's `CLAUDE.md`, and storing it anyway would leave\n * state in the marker that nothing generated and nothing reads.\n */\nfunction markerMemoryContract(agents: readonly AgentId[], memoryContract: boolean): boolean | undefined {\n return agents.includes('claude') ? memoryContract : undefined;\n}\n\n/**\n * With the file carrier suppressed, the plugin is the room's only Claude carrier. The plugin\n * is verified, so this is not a silent risk — but whether a resumed session re-enters the\n * creation hook is unproven, so the operator is told what they gave up rather than reassured.\n */\nfunction memoryContractDiagnostic(agents: readonly AgentId[], memoryContract: boolean): Check[] {\n if (memoryContract || !agents.includes('claude')) return [];\n return [warn('claude.memory-contract',\n 'Claude role CLAUDE.md files carry your global memory only: the role contract was not written to them, so the trusted server plugin is this room\\'s only Claude carrier. Only a newly created agent passes through its creation hook, and whether a resumed session re-enters that hook is unproven.',\n 'Drop --no-claude-memory-contract and run setup --apply to restore the file fallback.')];\n}\n\n/** The whole product: write the role homes, then register them with Paseo. */\nexport async function setup(options: RunOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const agents = options.agents ?? ['codex'];\n const memoryContract = options.claudeMemoryContract ?? true;\n const invalid = layoutChecks(layout, agents);\n if (invalid.length > 0) return failed('setup', invalid);\n const rootSafety = await roomPathSafety(layout, [], []);\n if (hasFailure(rootSafety)) return failed('setup', rootSafety);\n const previous = await readMarker(layout);\n const safetyAgents = [...new Set([...agents, ...(previous?.agents ?? [])])];\n const pathSafety = await roomPathSafety(layout, safetyAgents, ROLES);\n if (hasFailure(pathSafety)) return failed('setup', pathSafety);\n // Cleanup uses the APIs required by the old selection too (notably Claude's plugin API).\n const compatibilityAgents = [...new Set([...agents, ...(previous?.agents ?? [])])];\n const runtime = options.runtime === true;\n const daemon = await checkDaemon(layout, options.env, minimumPaseoVersion(compatibilityAgents, runtime || previous?.runtime?.enabled === true));\n if (!daemon.daemon) return failed('setup', daemon.checks);\n const version = daemon.daemon.version;\n const desired = await buildDesired(layout, agents, ROLES, { memoryContract, runtime });\n const stale = await staleFrom(layout, previous, agents, ROLES, runtime);\n const runtimeChecks = [\n ...desired.plugins.map(spec => pluginRangeCheck(spec, version)),\n ...(stale.removePlugins.some(spec => spec.id === RUNTIME_PLUGIN_ID) ? await runtimeDeselectionCheck(layout) : []),\n ];\n const retained = stale.retainedDirectories.length === 0 ? [] : [warn(\n 'room.stale-role-homes-preserved',\n `Preserved ${String(stale.retainedDirectories.length)} deselected role homes because they may contain role-owned credentials or runtime state.`,\n `Use paseo-room remove --apply to delete the entire room after reviewing its credential warning, or remove deselected homes manually: ${stale.retainedDirectories.join(', ')}`,\n )];\n const checks = [...daemon.checks, ...runtimeChecks, ...desired.checks, ...retained];\n if (hasFailure(checks)) return failed('setup', checks);\n\n return withSession(daemon.daemon, async session => {\n const plan = await planRoom(session, desired, stale);\n const { operations, liveProfiles } = plan;\n const pending = operations.filter(operation => operation.action !== 'noop');\n const enabled = desired.plugins.length === 0 ? true : await session.pluginsEnabled();\n const pluginPreconditions = [...desired.plugins.map(spec => pluginsEnabledCheck(spec, enabled)), ...plan.pluginChecks];\n // Diagnostics last: nothing above may be reached only through a warning.\n const preApplyDiagnostics = [...checks, ...pluginPreconditions, ...memoryContractDiagnostic(agents, memoryContract), ...contractProvenance(previous), ...thinkingDiagnostics(liveProfiles, desired.profiles)];\n if (hasFailure(preApplyDiagnostics) || !options.apply) {\n return {\n command: 'setup',\n outcome: hasFailure(preApplyDiagnostics) ? 'failed' : pending.length > 0 ? 'changes-planned' : 'ok',\n changed: false, checks: preApplyDiagnostics, operations,\n } satisfies Result;\n }\n // Keep the old marker until daemon reconciliation succeeds. If a remote write fails,\n // rerunning setup can still discover every stale provider/profile/plugin it must remove.\n const markerPath = join(layout.roomHome, MARKER);\n const markerEntries = desired.entries.filter(entry => entry.path === markerPath);\n await applyEntries(desired.entries.filter(entry => entry.path !== markerPath));\n const ids = Object.keys(desired.providers);\n await session.writeProviders(desired.providers);\n if (stale.providerIds.length > 0) await session.removeProviders(stale.providerIds);\n // Profiles point at providers, so they are written once the providers exist — and\n // only when something changed, since one write replaces the host's whole array.\n let appliedProfiles = liveProfiles;\n if (pending.some(operation => operation.kind === 'profile')) {\n appliedProfiles = mergeProfiles(liveProfiles, desired.profiles, stale.profileIds);\n await session.writeProfiles(appliedProfiles);\n }\n await session.refresh(ids);\n const pluginChecks = await reconcilePlugins(session, desired, stale, plan, pending);\n await applyEntries(markerEntries);\n const appliedMarker: Marker = {\n version: metadata.version, agents: [...agents], roles: [...ROLES], contract: contractDigest(),\n ...(markerMemoryContract(agents, memoryContract) === false ? { claudeMemoryContract: false } : {}),\n ...(desired.runtime === undefined ? {} : { runtime: desired.runtime }),\n };\n const appliedChecks = [...checks, ...pluginPreconditions, ...pluginChecks,\n pass('room.applied', `Room ready at ${layout.roomHome} with ${String(ids.length)} Paseo providers.`),\n ...memoryContractDiagnostic(agents, memoryContract),\n ...contractProvenance(appliedMarker), ...thinkingDiagnostics(appliedProfiles, desired.profiles)];\n return {\n command: 'setup', outcome: hasFailure(appliedChecks) ? 'failed' : 'ok', changed: pending.length > 0,\n checks: appliedChecks, operations,\n } satisfies Result;\n }, sessionOptions(options));\n}\n\nexport async function verify(options: RunOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const rootSafety = await roomPathSafety(layout, [], []);\n if (hasFailure(rootSafety)) return failed('verify', rootSafety);\n const marker = await readMarker(layout);\n if (!marker) {\n return failed('verify', [fail('room.marker', `No room found at ${layout.roomHome}.`, 'Run: paseo-room setup --apply')]);\n }\n const invalid = layoutChecks(layout, marker.agents);\n if (invalid.length > 0) return failed('verify', invalid);\n const pathSafety = await roomPathSafety(layout, marker.agents, marker.roles);\n if (hasFailure(pathSafety)) return failed('verify', pathSafety);\n const runtime = marker.runtime?.enabled === true;\n const daemon = await checkDaemon(layout, options.env, minimumPaseoVersion(marker.agents, runtime));\n if (!daemon.daemon) return failed('verify', daemon.checks);\n const version = daemon.daemon.version;\n const desired = await buildDesired(layout, marker.agents, marker.roles, {\n // The room's own recorded choices, so verify compares against what setup wrote.\n memoryContract: marker.claudeMemoryContract ?? true,\n runtime,\n });\n const runtimeChecks = [\n ...desired.plugins.map(spec => pluginRangeCheck(spec, version)),\n ...(runtime ? [marker.runtime?.generation === desired.runtime?.generation\n ? pass('runtime.generation', `Runtime manifest generation ${String(desired.runtime?.generation)} matches this package.`)\n : fail('runtime.generation', `This room was set up with runtime generation ${String(marker.runtime?.generation)}; this package generates ${String(desired.runtime?.generation)}.`, 'Run: paseo-room setup --runtime --apply')] : []),\n ];\n const checks = [...daemon.checks, ...runtimeChecks, ...desired.checks];\n if (hasFailure(daemon.checks) || hasFailure(desired.checks)) return failed('verify', checks);\n\n return withSession(daemon.daemon, async session => {\n const plan = await planRoom(session, desired, NOTHING_STALE);\n const { operations, liveProfiles } = plan;\n const drifted = operations.filter(operation => operation.action !== 'noop');\n const count = (kind: Operation['kind']): number => drifted.filter(operation => operation.kind === kind).length;\n const providers = count('provider');\n const profiles = count('profile');\n const driftedFiles = drifted.filter(operation => !['provider', 'profile', 'plugin'].includes(operation.kind));\n const files = driftedFiles.length;\n const enabled = desired.plugins.length === 0 ? true : await session.pluginsEnabled();\n const pluginChecks = desired.plugins.flatMap(spec => [\n pluginsEnabledCheck(spec, enabled),\n ...plan.pluginChecks.filter(check => check.id.startsWith(`${spec.check}.`)),\n pluginRuntimeCheck(spec, plan.livePlugins.get(spec.id)),\n ]);\n const all: Check[] = [...checks,\n files === 0\n ? pass('room.files', 'Every managed role file matches the current definition.')\n : fail('room.files', `${fileDriftSummary(driftedFiles)}${fileDriftDetail(driftedFiles.map(operation => operation.target))}`, 'Run: paseo-room setup --apply'),\n providers === 0\n ? pass('room.providers', `All ${String(Object.keys(desired.providers).length)} Paseo providers are registered as expected.`)\n : fail('room.providers', `${String(providers)} Paseo providers are missing or differ.`, 'Run: paseo-room setup --apply'),\n profiles === 0\n ? pass('room.profiles', `All ${String(desired.profiles.length)} Paseo agent profiles are registered as expected.`)\n : fail('room.profiles', `${String(profiles)} Paseo agent profiles are missing or differ.`, 'Run: paseo-room setup --apply'),\n ...pluginChecks,\n // Diagnostics last: a warning never precedes the failure it might be mistaken for.\n ...memoryContractDiagnostic(marker.agents, marker.claudeMemoryContract ?? true),\n ...contractProvenance(marker),\n ...thinkingDiagnostics(liveProfiles, desired.profiles),\n ];\n return {\n command: 'verify', outcome: hasFailure(all) ? 'failed' : 'ok', changed: false, checks: all, operations,\n } satisfies Result;\n }, sessionOptions(options));\n}\n\nexport async function remove(options: RunOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const rootSafety = await roomPathSafety(layout, [], []);\n if (hasFailure(rootSafety)) return failed('remove', rootSafety);\n const marker = await readMarker(layout);\n if (!marker) {\n return failed('remove', [fail('room.marker', `No room found at ${layout.roomHome}.`, 'Nothing to remove; the room home was never created here.')]);\n }\n // A recursive delete needs a floor, so the layout rules gate this command too.\n const invalid = layoutChecks(layout, marker.agents);\n if (invalid.length > 0) return failed('remove', invalid);\n const ids = marker.agents.flatMap(agent => marker.roles.map(role => providerId(agent, role)));\n const profiles = new Set(marker.agents.flatMap(agent => marker.roles.map(role => profileId(agent, role))));\n const plugins = [\n ...(marker.agents.includes('claude') ? [carrierSpec(layout)] : []),\n ...(marker.runtime?.enabled === true ? [runtimeSpec(layout)] : []),\n ];\n const operations: Operation[] = [\n ...ids.map(id => ({ action: 'remove', kind: 'provider', target: id }) satisfies Operation),\n ...[...profiles].map(id => ({ action: 'remove', kind: 'profile', target: id }) satisfies Operation),\n ...plugins.map(spec => ({ action: 'remove', kind: 'plugin', target: spec.id }) satisfies Operation),\n { action: 'remove', kind: 'dir', target: layout.roomHome },\n ];\n const credentialWarning = warn('room.remove.credentials',\n `Deleting ${layout.roomHome} will delete role-owned credential files stored inside it. Native OS keyring entries are not inspected or deleted and may remain. Operator agent-home credentials are untouched.`);\n const runtimeWarnings = await runtimeRemovalWarning(layout);\n if (!options.apply) {\n return { command: 'remove', outcome: 'changes-planned', changed: false, checks: [credentialWarning, ...runtimeWarnings], operations };\n }\n const daemon = await checkDaemon(layout, options.env);\n const checks: Check[] = [credentialWarning, ...runtimeWarnings];\n if (!daemon.daemon) {\n return failed('remove', [\n credentialWarning,\n ...daemon.checks,\n fail(\n 'room.files',\n `Preserved ${layout.roomHome}, including its room marker, because Paseo cleanup could not start.`,\n 'Start Paseo, then run: paseo-room remove --apply',\n ),\n ]);\n }\n try {\n await withSession(daemon.daemon, async session => {\n if (plugins.length > 0) {\n const live = await session.listPlugins();\n // Deregister before the room home is deleted, and never a registration from a foreign path.\n for (const spec of plugins) {\n const plugin = live.find(entry => entry.id === spec.id);\n if (plugin !== undefined && plugin.path !== spec.path) throw new Error(`refusing to remove foreign plugin path ${plugin.path}`);\n }\n for (const spec of plugins) {\n if (live.some(entry => entry.id === spec.id)) await session.removePlugin(spec.id);\n }\n }\n await session.removeProviders(ids);\n const live = await session.readProfiles();\n const kept = live.filter(entry => !profiles.has(String(entry.id)));\n if (kept.length !== live.length) await session.writeProfiles(kept);\n }, sessionOptions(options));\n checks.push(pass('room.providers', `Removed ${String(ids.length)} Paseo providers and their agent profiles.`));\n } catch {\n return failed('remove', [\n credentialWarning,\n fail(\n 'room.providers',\n `Paseo provider/profile cleanup did not complete; ${layout.roomHome} and its room marker were preserved.`,\n 'Restore Paseo connectivity, then run: paseo-room remove --apply',\n ),\n ]);\n }\n // Explicit remove owns the whole room home, including runtime-owned role credentials.\n try {\n await rm(layout.roomHome, { recursive: true, force: true });\n } catch (error) {\n const detail = error instanceof Error ? error.message : 'unknown filesystem error';\n checks.push(fail(\n 'room.files',\n `Removed the Paseo providers and profiles, but could not fully delete ${layout.roomHome}: ${detail}`,\n 'Delete that directory manually after reviewing it for role-owned credentials; the Paseo side is already clean.',\n ));\n const completedOperations = operations.filter(operation => operation.kind !== 'dir');\n return { command: 'remove', outcome: 'failed', changed: true, checks, operations: completedOperations };\n }\n checks.push(pass('room.files', `Deleted ${layout.roomHome}.`));\n return { command: 'remove', outcome: 'ok', changed: true, checks, operations };\n}\n","import * as clack from '@clack/prompts';\nimport { AGENTS, remove, setup, verify, type RunOptions } from './commands.js';\nimport type { Result } from './result.js';\nimport { AGENT_IDS, type AgentId } from './roles.js';\n\nexport interface Prompts {\n select(options: { readonly message: string; readonly options: readonly { readonly value: string; readonly label: string }[] }): Promise<string | symbol>;\n multiselect(options: { readonly message: string; readonly options: readonly { readonly value: AgentId; readonly label: string }[] }): Promise<AgentId[] | symbol>;\n confirm(options: { readonly message: string }): Promise<boolean | symbol>;\n}\nexport const terminalPrompts: Prompts = {\n select: options => clack.select({ message: options.message, options: [...options.options] }),\n multiselect: options => clack.multiselect({ message: options.message, options: [...options.options], required: true }),\n confirm: options => clack.confirm({ message: options.message, initialValue: false }),\n};\n\n/** Guided path over the same commands the flags use; nothing extra happens here. */\nexport async function runWizard(\n prompts: Prompts,\n emit: (result: Result) => number,\n write: (text: string) => void,\n options: RunOptions = {},\n onAction?: (action: string) => void,\n): Promise<number> {\n const cancelled = (): number => { write('Cancelled; nothing was changed.\\n'); return 0; };\n const action = await prompts.select({\n message: 'What do you want to do?',\n options: [\n { value: 'setup', label: 'Set up / update the room (login stays separate)' },\n { value: 'verify', label: 'Verify the current room' },\n { value: 'remove', label: 'Remove the room' },\n ],\n });\n if (typeof action === 'symbol') return cancelled();\n onAction?.(action);\n if (action === 'verify') return emit(await verify(options));\n if (action === 'remove') {\n const preview = await remove(options);\n const status = emit(preview);\n if (preview.outcome !== 'changes-planned') return status;\n const approved = await prompts.confirm({ message: 'Delete the room home, including role credentials, and its Paseo providers?' });\n return approved === true ? emit(await remove({ ...options, apply: true })) : cancelled();\n }\n const agents = await prompts.multiselect({\n message: 'Which coding agents should the room use?',\n options: AGENT_IDS.map(value => ({ value, label: AGENTS[value].label })),\n });\n if (typeof agents === 'symbol' || agents.length === 0) return cancelled();\n // Only meaningful for Claude: the other adapters have no plugin carrier to fall back from.\n let claudeMemoryContract = true;\n if (agents.includes('claude')) {\n const carrier = await prompts.select({\n message: 'Claude role contract carrier: the room plugin is always used. Also write the contract into each role CLAUDE.md?',\n options: [\n { value: 'both', label: 'Yes — keep it as a fallback (recommended; resume behaviour is unproven)' },\n { value: 'plugin', label: 'No — plugin only; CLAUDE.md keeps your global memory alone' },\n ],\n });\n if (typeof carrier === 'symbol') return cancelled();\n claudeMemoryContract = carrier === 'both';\n }\n // Runtime coordination is an explicit opt-in, never a default: it installs trusted plugin code.\n const coordination = await prompts.select({\n message: 'Runtime coordination (preview): track assignments, Peer reports and writer ownership through a trusted Paseo plugin?',\n options: [\n { value: 'off', label: 'No — keep the room as it is (default)' },\n { value: 'runtime', label: 'Yes — install the paseo-room-runtime plugin (trusted, unsandboxed code)' },\n ],\n });\n if (typeof coordination === 'symbol') return cancelled();\n const setupOptions = { ...options, agents, claudeMemoryContract, ...(coordination === 'runtime' ? { runtime: true } : {}) };\n const preview = await setup(setupOptions);\n const status = emit(preview);\n if (preview.outcome !== 'changes-planned') return status;\n const approved = await prompts.confirm({ message: 'Apply these changes? Authentication will not be validated or started.' });\n if (approved !== true) return cancelled();\n return emit(await setup({ ...setupOptions, apply: true }));\n}\n","import { Command, CommanderError, InvalidArgumentError } from 'commander';\nimport metadata from '../package.json' with { type: 'json' };\nimport { loginRole, type LoginSpawner } from './auth.js';\nimport { remove, setup, verify, type RunOptions } from './commands.js';\nimport { exportRuntime } from './export.js';\nimport { ManagedPathError } from './fsops.js';\nimport { renderHuman, renderJson } from './render.js';\nimport { exitCode, fail, failed, type Result } from './result.js';\nimport { AGENT_IDS, type AgentId } from './roles.js';\nimport { PromptAssetError } from './room/prompts.js';\nimport { SkillAssetError } from './room/skills.js';\nimport type { Prompts } from './wizard.js';\n\nexport interface Output {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\nexport interface CliContext {\n readonly isTTY?: boolean;\n readonly prompts?: Prompts;\n readonly options?: RunOptions;\n readonly loginSpawn?: LoginSpawner;\n}\n\n/** Commander passes no initial value, so the first call starts the list. */\nfunction collectAgent(value: string, previous: AgentId[] | undefined): AgentId[] {\n const agent = AGENT_IDS.find(id => id === value);\n if (!agent) throw new InvalidArgumentError(`Unknown agent: ${value}`);\n const seated = previous ?? [];\n return seated.includes(agent) ? seated : [...seated, agent];\n}\n\nconst PATH_FLAGS = ['roomHome', 'codexHome', 'claudeHome', 'piHome', 'codexBin', 'claudeBin', 'piBin', 'paseoBin'] as const;\n\nfunction optionsFrom(raw: Record<string, unknown>, base: RunOptions): RunOptions {\n const paths: Record<string, string> = {};\n for (const flag of PATH_FLAGS) {\n const value = raw[flag];\n if (typeof value === 'string' && value.trim()) paths[flag] = value.trim();\n }\n const agents = Array.isArray(raw.agent) && raw.agent.length > 0 ? (raw.agent as AgentId[]) : undefined;\n return {\n ...base, ...paths, ...(agents ? { agents } : {}), ...(raw.apply === true ? { apply: true } : {}),\n // Commander defaults a --no- flag to true, so only an explicit opt-out is carried.\n ...(raw.claudeMemoryContract === false ? { claudeMemoryContract: false } : {}),\n ...(raw.runtime === true ? { runtime: true } : {}),\n };\n}\n\nfunction failedFromThrown(command: string, error: unknown): Result {\n if (error instanceof PromptAssetError) {\n return failed(command, [fail(\n `${command}.prompt-asset`,\n error.message,\n 'Reinstall paseo-room, then try again.',\n )]);\n }\n if (error instanceof SkillAssetError) {\n return failed(command, [fail(\n `${command}.skill-asset`,\n error.message,\n 'Reinstall paseo-room, then try again.',\n )]);\n }\n // A refused path knows its own remedy, and it is never \"check the daemon\": the room reached\n // the filesystem and stopped there deliberately.\n if (error instanceof ManagedPathError) {\n return failed(command, [fail(`${command}.managed-path`, error.message, error.fix)]);\n }\n const detail = error instanceof Error ? error.message : 'unknown error';\n return failed(command, [fail(\n `${command}.error`,\n detail,\n 'Check that Paseo is running and reachable, then try again.',\n )]);\n}\n\nexport async function runCli(argv: readonly string[], output: Output, context: CliContext = {}): Promise<number> {\n const password = (context.options?.env ?? process.env).PASEO_PASSWORD;\n const redact = (text: string): string => (password ? text.split(password).join('[redacted]') : text);\n // Set once the flags are parsed; the wizard path never sees flags, so text output is right there.\n let json = false;\n const emit = (result: Result): number => {\n output.stdout(redact(json ? renderJson(result) : renderHuman(result)));\n return exitCode(result);\n };\n const isTTY = context.isTTY ?? (process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY);\n const base = context.options ?? {};\n\n if (argv.length === 0) {\n if (!isTTY) {\n output.stderr('paseo-room: no command given. Try: paseo-room setup, verify, remove, auth login, or --help.\\n');\n return 2;\n }\n let wizardCommand = 'wizard';\n try {\n // @clack/prompts is only reachable here, so keep it off the scripted path.\n const { runWizard, terminalPrompts } = await import('./wizard.js');\n return await runWizard(\n context.prompts ?? terminalPrompts,\n emit,\n text => { output.stdout(text); },\n base,\n action => { wizardCommand = action; },\n );\n } catch (error) {\n return emit(failedFromThrown(wizardCommand, error));\n }\n }\n const program = new Command()\n .name('paseo-room')\n .description('Configure Codex/Claude/Pi role homes in $HOME and register them with your local Paseo daemon.')\n .version(metadata.version)\n .usage('<setup|verify|remove|export> [options]\\n auth login <codex|claude|pi> <supervisor|lead|peer> [options]')\n .argument('<command>', 'setup | verify | remove | export | auth')\n .argument('[command-arguments...]', 'auth login <agent> <role>')\n .option('--agent <agent>', 'codex, claude, or pi; repeat to combine (default: codex)', collectAgent)\n .option('--apply', 'actually make the changes (default: dry run)')\n .option('--json', 'machine-readable output')\n .option('--no-claude-memory-contract', 'omit the role contract from Claude role CLAUDE.md files, leaving the room plugin as the only Claude carrier')\n .option('--runtime', 'opt in to runtime coordination (preview): installs the trusted paseo-room-runtime plugin; omit it to deselect')\n .option('--out <dir>', 'export: destination directory (default: a new directory under the room\\'s runtime exports)')\n .option('--include-gate-output', 'export: also copy bounded gate output tails (best-effort masked)')\n .option('--room-home <path>', 'where role homes are written (default: ~/.paseo-room)')\n .option('--codex-home <path>', 'source Codex config (default: ~/.codex)')\n .option('--claude-home <path>', 'source Claude Code config (default: ~/.claude)')\n .option('--pi-home <path>', 'source Pi config (default: ~/.pi/agent)')\n .option('--codex-bin <path>', 'Codex executable (default: found on PATH)')\n .option('--claude-bin <path>', 'Claude Code executable (default: found on PATH)')\n .option('--pi-bin <path>', 'Pi executable (default: found on PATH)')\n .option('--paseo-bin <path>', 'Paseo executable (default: found on PATH)')\n .configureOutput({ writeOut: text => { output.stdout(text); }, writeErr: text => { output.stderr(text); } })\n .exitOverride();\n\n let command: string;\n let commandArguments: string[];\n let options: RunOptions;\n let raw: Record<string, unknown>;\n try {\n program.parse([...argv], { from: 'user' });\n raw = program.opts<Record<string, unknown>>();\n json = raw.json === true;\n command = program.args[0] ?? '';\n commandArguments = program.args.slice(1);\n options = optionsFrom(raw, base);\n } catch (error) {\n if (error instanceof CommanderError && error.exitCode === 0) return 0;\n return 2;\n }\n\n try {\n // Only setup chooses this: verify and remove read the room's recorded choice instead, and\n // auth does not carry it at all. Silently ignoring it would misreport what the run did.\n if (raw.claudeMemoryContract === false && (command === 'verify' || command === 'remove')) {\n output.stderr(`paseo-room ${command}: --no-claude-memory-contract is a setup choice recorded in the room marker; ${command} reads it from there.\\n`);\n return 2;\n }\n if ((raw.out !== undefined || raw.includeGateOutput === true) && command !== 'export') {\n output.stderr(`paseo-room ${command}: --out and --include-gate-output only apply to export.\\n`);\n return 2;\n }\n if (raw.runtime === true && (command === 'verify' || command === 'remove' || command === 'export')) {\n output.stderr(`paseo-room ${command}: --runtime is a setup choice recorded in the room marker; ${command} reads it from there.\\n`);\n return 2;\n }\n if (command === 'auth') {\n if (raw.runtime === true) {\n output.stderr('paseo-room auth login only authenticates a role and does not use --runtime.\\n');\n return 2;\n }\n if (raw.claudeMemoryContract === false) {\n output.stderr('paseo-room auth login only authenticates a role and does not use --no-claude-memory-contract.\\n');\n return 2;\n }\n if (raw.apply === true) {\n output.stderr('paseo-room auth login is already explicit and does not use --apply.\\n');\n return 2;\n }\n if (raw.json === true) {\n output.stderr('paseo-room auth login is interactive and does not support --json.\\n');\n return 2;\n }\n if (raw.agent !== undefined) {\n output.stderr('paseo-room auth login takes exactly one positional agent and does not use --agent.\\n');\n return 2;\n }\n if (commandArguments.length !== 3 || commandArguments[0] !== 'login') {\n output.stderr('Usage: paseo-room auth login <codex|claude|pi> <supervisor|lead|peer>\\n');\n return 2;\n }\n return await loginRole(commandArguments[1] ?? '', commandArguments[2] ?? '', {\n ...options,\n isTTY,\n ...(context.loginSpawn ? { spawn: context.loginSpawn } : {}),\n }, output);\n }\n if (commandArguments.length > 0) {\n output.stderr(`paseo-room ${command}: unexpected arguments: ${commandArguments.join(' ')}\\n`);\n return 2;\n }\n if (command === 'setup') return emit(await setup(options));\n if (command === 'verify') return emit(await verify(options));\n if (command === 'remove') return emit(await remove(options));\n if (command === 'export') {\n return emit(await exportRuntime({\n ...options,\n ...(typeof raw.out === 'string' && raw.out.trim() !== '' ? { out: raw.out.trim() } : {}),\n ...(raw.includeGateOutput === true ? { includeGateOutput: true } : {}),\n }));\n }\n } catch (error) {\n return emit(failedFromThrown(command, error));\n }\n output.stderr(`paseo-room: unknown command \"${command}\". Try: setup, verify, remove, export, or auth login.\\n`);\n return 2;\n}\n","import { copyFile, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport metadata from '../package.json' with { type: 'json' };\nimport { resolveLayout } from './layout.js';\nimport { fail, failed, pass, warn, type Check, type Operation, type Result } from './result.js';\nimport type { RunOptions } from './commands.js';\nimport { readEvent } from './runtime-plugin/server/events/schema.js';\nimport { runtimeRoot } from './runtime-plugin/server/store/project.js';\n\nexport interface ExportOptions extends RunOptions {\n /** Destination directory; defaults to a new directory under the room's runtime exports. */\n readonly out?: string;\n readonly includeGateOutput?: boolean;\n}\n\nconst LIMITATION = 'Briefs, answers, reports and gate commands are stored as written and cannot be proven secret-free; review the export before sharing it.';\n\nasync function isEmptyOrAbsent(path: string): Promise<boolean> {\n try { return (await readdir(path)).length === 0; } catch { return true; }\n}\n\n/**\n * Explicit, read-only export of runtime state (docs/design/runtime-coordination.md §10). Needs\n * no daemon. Only schema-valid events are copied; anything unreadable is listed by name, never\n * by content. Gate output tails stay out unless asked for. Nothing under `runtime/` changes.\n */\nexport async function exportRuntime(options: ExportOptions = {}): Promise<Result> {\n const layout = resolveLayout(options, options.env);\n const root = runtimeRoot(layout.roomHome);\n let projects: string[];\n try { projects = (await readdir(join(root, 'projects'))).sort(); } catch { projects = []; }\n if (projects.length === 0) {\n return failed('export', [fail('export.nothing', `No runtime state was found under ${root}.`, 'Runtime coordination records state only after setup --runtime and a first assignment.')]);\n }\n const stamp = new Date().toISOString().replace(/[:.]/g, '-');\n const destination = resolve(options.out ?? join(root, 'exports', stamp));\n if (!await isEmptyOrAbsent(destination)) {\n return failed('export', [fail('export.destination', `${destination} already exists and is not empty.`, 'Choose a new or empty --out directory.')]);\n }\n\n const operations: Operation[] = [{ action: 'create', kind: 'dir', target: destination }];\n const summary: { projectId: string; canonicalRoot: string; events: number; omitted: string[]; gateOutputs: number }[] = [];\n const copies: [string, string][] = [];\n for (const name of projects) {\n const source = join(root, 'projects', name);\n const target = join(destination, 'projects', name);\n let meta: { projectId?: string; canonicalRoot?: string };\n try { meta = JSON.parse(await readFile(join(source, 'meta.json'), 'utf8')) as typeof meta; } catch { meta = {}; }\n const entry = { projectId: meta.projectId ?? name, canonicalRoot: meta.canonicalRoot ?? 'unknown', events: 0, omitted: [] as string[], gateOutputs: 0 };\n copies.push([join(source, 'meta.json'), join(target, 'meta.json')]);\n for (const file of (await readdir(join(source, 'events')).catch(() => [] as string[])).sort()) {\n if (file.startsWith('.tmp-')) continue;\n let valid: boolean;\n try { valid = readEvent(JSON.parse(await readFile(join(source, 'events', file), 'utf8'))).ok; } catch { valid = false; }\n if (valid) { entry.events += 1; copies.push([join(source, 'events', file), join(target, 'events', file)]); }\n else entry.omitted.push(file);\n }\n for (const file of (await readdir(join(source, 'gates')).catch(() => [] as string[])).sort()) {\n if (file.endsWith('.result.json')) copies.push([join(source, 'gates', file), join(target, 'gates', file)]);\n else if (file.endsWith('.log') && options.includeGateOutput === true) { entry.gateOutputs += 1; copies.push([join(source, 'gates', file), join(target, 'gates', file)]); }\n }\n summary.push(entry);\n }\n operations.push(...copies.map(([, target]) => ({ action: 'create', kind: 'file', target }) satisfies Operation));\n operations.push({ action: 'create', kind: 'file', target: join(destination, 'summary.json') });\n\n const checks: Check[] = [\n warn('export.limitation', LIMITATION),\n ...(options.includeGateOutput === true ? [warn('export.gate-output', 'Gate output tails are included; they are best-effort masked only.')] : []),\n ...summary.filter(entry => entry.omitted.length > 0).map(entry => warn('export.omitted', `Project ${entry.projectId}: ${String(entry.omitted.length)} unreadable event file(s) were left out by name: ${entry.omitted.join(', ')}.`)),\n ];\n if (!options.apply) return { command: 'export', outcome: 'changes-planned', changed: false, checks, operations };\n\n await mkdir(destination, { recursive: true, mode: 0o700 });\n for (const [from, to] of copies) {\n await mkdir(join(to, '..'), { recursive: true, mode: 0o700 });\n await copyFile(from, to);\n }\n await writeFile(join(destination, 'summary.json'), `${JSON.stringify({\n schema: 1, exportedAt: new Date().toISOString(), packageVersion: metadata.version, gateOutputIncluded: options.includeGateOutput === true,\n limitation: LIMITATION, projects: summary,\n }, null, 2)}\\n`, { mode: 0o600 });\n return { command: 'export', outcome: 'ok', changed: true, checks: [...checks, pass('export.written', `Exported ${String(summary.length)} project(s) to ${destination}.`)], operations };\n}\n","import type { Result } from './result.js';\n\nexport function renderJson(result: Result): string {\n return `${JSON.stringify({ schemaVersion: 2, ...result }, null, 2)}\\n`;\n}\n\nconst ICONS = { pass: '✓', warn: '!', fail: '✗' } as const;\n\nexport function renderHuman(result: Result): string {\n const lines: string[] = [];\n for (const check of result.checks) {\n lines.push(`${ICONS[check.status]} ${check.message}`);\n if (check.fix) lines.push(` → ${check.fix}`);\n }\n const changes = result.operations.filter(operation => operation.action !== 'noop');\n if (changes.length > 0) {\n lines.push('', result.changed ? 'Applied:' : 'Planned changes:');\n for (const operation of changes) lines.push(` ${operation.action} ${operation.kind} ${operation.target}`);\n const unchanged = result.operations.length - changes.length;\n if (unchanged > 0) lines.push(` (${String(unchanged)} already up to date)`);\n } else if (result.operations.length > 0) {\n lines.push('', 'Everything is already up to date.');\n }\n lines.push('', `${result.command}: ${result.outcome}`);\n return `${lines.join('\\n')}\\n`;\n}\n","#!/usr/bin/env node\nimport { runCli } from './cli.js';\n\nprocess.exitCode = await runCli(process.argv.slice(2), {\n stdout: text => { process.stdout.write(text); },\n stderr: text => { process.stderr.write(text); },\n});\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,UAAY;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,UAAY;AAAA,MACZ,MAAQ;AAAA,MACR,YAAc;AAAA,QACZ,MAAQ;AAAA,QACR,KAAO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AAC;AAAA,QACtF,GAAI,IAAI,sBAAsB,OAAO,EAAE,mBAAmB,KAAK,IAAI,CAAC;AAAA,MACtE,CAAC,CAAC;AAAA,IACJ;AAAA,EACF,SAAS,OAAO;AACd,WAAO,KAAK,iBAAiB,SAAS,KAAK,CAAC;AAAA,EAC9C;AACA,SAAO,OAAO,gCAAgC,OAAO;AAAA,CAAyD;AAC9G,SAAO;AACT;;;AGpNA,QAAQ,WAAW,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,GAAG;AAAA,EACrD,QAAQ,CAAAG,UAAQ;AAAE,YAAQ,OAAO,MAAMA,KAAI;AAAA,EAAG;AAAA,EAC9C,QAAQ,CAAAA,UAAQ;AAAE,YAAQ,OAAO,MAAMA,KAAI;AAAA,EAAG;AAChD,CAAC;","names":["id","stat","id","id","lstat","readlink","join","stat","title","join","join","resolve","constants","join","lstat","env","argv","resolve","settled","code","current","table","id","readdir","join","readFileSync","join","cache","readFile","join","id","join","id","SHARED","EXECUTABLE","evidence","parsed","spawn","readFile","rm","isAbsolute","join","resolve","asObject","parsed","settled","reason","code","command","id","AUTH_ENV","SHARED","EXECUTABLE","z","parsed","run","id","readFileSync","join","id","z","providerId","createHash","readFileSync","join","sep","z","text","reason","parsed","table","assignment","id","current","code","createHash","z","z","z","z","parsed","text","reason","generation","digest","randomBytes","chmod","lstat","mkdir","readdir","unlink","join","stat","reason","randomBytes","mkdir","readdir","readFile","rename","rm","writeFile","basename","join","z","readdir","join","join","sep","lstat","rm","id","digest","stat","live","preview","status","approved","mkdir","readdir","readFile","writeFile","join","resolve","valid","id","text","runWizard","terminalPrompts","text"]}