@delorenj/pjangler 1.4.2 → 1.4.3

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 (39) hide show
  1. package/dist/index.js +3336 -1359
  2. package/dist/index.js.map +7 -0
  3. package/dist/mcp-server.js +1520 -838
  4. package/dist/mcp-server.js.map +7 -0
  5. package/dist/prompt.js +2 -1
  6. package/dist/prompt.js.map +7 -0
  7. package/package.json +8 -4
  8. package/templates/hermes-agent/copier.yml +16 -3
  9. package/templates/hermes-agent/template/.runtime-scaffold/memories/MEMORY.md +7 -4
  10. package/templates/hermes-agent/template/.scripts/10-hermes-profile.sh +88 -94
  11. package/templates/hermes-agent/template/.scripts/20-runtime-repo.sh +44 -21
  12. package/templates/hermes-agent/template/.scripts/30-telegram.sh +182 -171
  13. package/templates/hermes-agent/template/.scripts/31-slack.sh +260 -165
  14. package/templates/hermes-agent/template/.scripts/40-plane.sh +45 -36
  15. package/templates/hermes-agent/template/.scripts/42-ticket-provider.sh +210 -41
  16. package/templates/hermes-agent/template/.scripts/70-systemd.sh +129 -15
  17. package/templates/hermes-agent/template/.scripts/80-registry.sh +42 -6
  18. package/templates/hermes-agent/template/.scripts/99-summary.sh +69 -16
  19. package/templates/hermes-agent/template/.scripts/_lib.sh +773 -0
  20. package/templates/hermes-agent/template/.scripts/channel-transaction.py +2340 -0
  21. package/templates/hermes-agent/template/.scripts/config.example.toml +8 -2
  22. package/templates/hermes-agent/template/.scripts/credential-launch.sh +5 -1
  23. package/templates/hermes-agent/template/.scripts/heartbeat.sh +2 -3
  24. package/templates/hermes-agent/template/.scripts/lib/profile-config-lock.py +182 -0
  25. package/templates/hermes-agent/template/.scripts/lib/profile-config-seed.py +108 -0
  26. package/templates/hermes-agent/template/.scripts/lib/ticket-provider.sh +9 -0
  27. package/templates/hermes-agent/template/.scripts/lib/voice-config.py +546 -0
  28. package/templates/hermes-agent/template/.scripts/providers/linear.sh +24 -1
  29. package/templates/hermes-agent/template/.scripts/providers/plane.sh +54 -8
  30. package/templates/hermes-agent/template/.scripts/providers/trello.sh +25 -2
  31. package/templates/hermes-agent/template/.scripts/sentinel/bin/issue-autonomous-review.sh +5 -16
  32. package/templates/hermes-agent/template/.scripts/sentinel/bin/issue-close-gate.sh +2 -16
  33. package/templates/hermes-agent/template/.scripts/sentinel/docs/autonomous-delegated-review.md +13 -19
  34. package/templates/hermes-agent/template/.scripts/sentinel/docs/bloodbank-events.md +29 -36
  35. package/templates/hermes-agent/template/.scripts/sentinel.prompt.md.jinja +7 -8
  36. package/templates/hermes-agent/template/.scripts/store-onepassword-secret.py +260 -0
  37. package/templates/hermes-agent/template/SOUL.md.jinja +14 -16
  38. package/templates/hermes-agent/template/hermes.jinja +1 -1
  39. package/templates/hermes-agent/template/role.yaml.jinja +11 -4
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/utils/style.ts", "../src/notebook/types.ts", "../src/utils/tree-diff.ts", "../src/lifecycle/preflight.ts", "../src/project/RegistryStore.ts", "../src/project/boardUrl.ts", "../src/utils/version.ts", "../src/project/boardQuery.ts", "../src/project/index.ts", "../src/notebook/config.ts", "../src/notebook/notes.ts", "../src/notebook/output.ts", "../src/notebook/remote-mutation-schema.ts", "../src/notebook/state.ts", "../src/notebook/open-notebook-client.ts", "../src/notebook/git-evidence.ts", "../src/notebook/remote-mutation-journal.ts", "../src/notebook/reconcile.ts", "../src/notebook/summarizer.ts", "../src/notebook/capture.ts", "../src/mcp-server.ts", "../src/recipes/Recipe.ts", "../src/commands/Command.ts", "../src/recipes/types.ts", "../src/parity/rules.ts", "../src/recipes/supported-clis.ts", "../src/parity/pack.ts", "../src/recipes/AgentHooksRecipe.ts", "../src/recipes/BmadRecipe.ts", "../src/commands/AddDockerfile.ts", "../src/commands/AddDockerCompose.ts", "../src/commands/AddDockerignore.ts", "../src/recipes/DockerRecipe.ts", "../src/commands/hermes/EnsureTemplateConfig.ts", "../src/commands/hermes/PromptForAgentConfig.ts", "../src/commands/hermes/types.ts", "../src/commands/hermes/ValidateHermesOptions.ts", "../src/commands/hermes/RunCopierTemplate.ts", "../src/commands/hermes/UntrackHermesRuntimes.ts", "../src/commands/hermes/WireTelegram.ts", "../src/commands/hermes/WireEmail.ts", "../src/commands/hermes/PrintHermesSummary.ts", "../src/commands/hermes/ApplyDeferredExternalEffects.ts", "../src/commands/hermes/ApplyDeferredHostEffects.ts", "../src/recipes/HermesAgentRecipe.ts", "../src/recipes/MiseOpInjectRecipe.ts", "../src/recipes/MiseRecipe.ts", "../src/commands/NodeCommands.ts", "../src/recipes/NodeRecipe.ts", "../src/recipes/ProjectRecipe.ts", "../src/recipes/NotebookRecipe.ts", "../src/notebook/checks.ts", "../src/notebook/module.ts", "../src/notebook/overview.ts", "../src/notebook/observation.ts", "../src/notebook/hooks.ts", "../src/recipes/registry.ts", "../src/recipes/catalog.ts", "../src/commands/AgentHooksCommands.ts", "../src/commands/AddMiseToml.ts", "../src/commands/AddMiseBaseToml.ts", "../src/commands/AddMiseTasksStructure.ts", "../src/commands/AddMiseBaseScript.ts", "../src/commands/AddMiseCodegraphScript.ts", "../src/commands/AddDotenv.ts", "../src/parity/index.ts", "../src/commands/WireMiseOpInject.ts", "../src/utils/registry.ts", "../src/describe/index.ts", "../src/describe/activity.ts"],
4
+ "sourcesContent": ["// Zero-dependency ANSI styling + iconography for pjangler CLI output.\n//\n// Color is emitted only to a capable TTY. We honor NO_COLOR\n// (https://no-color.org/), FORCE_COLOR, TERM=dumb, and stdout TTY detection so\n// that piped / redirected / `--json` / MCP (non-TTY) output stays clean and\n// machine-parseable. Unicode glyphs are width-1 and rendered unconditionally so\n// column alignment holds whether or not color is active.\n\nconst env = process.env;\n\nfunction detectColor(): boolean {\n // NO_COLOR: present and non-empty disables color regardless of value.\n if (\"NO_COLOR\" in env && env.NO_COLOR !== \"\") return false;\n const force = env.FORCE_COLOR;\n if (force === \"0\" || force === \"false\") return false;\n if (force !== undefined && force !== \"\") return true;\n if (env.TERM === \"dumb\") return false;\n return Boolean(process.stdout.isTTY);\n}\n\n/** Whether ANSI color codes should be emitted for this process. */\nexport const colorEnabled: boolean = detectColor();\n\ntype Colorize = (value: string | number) => string;\n\nfunction sgr(open: number, close: number): Colorize {\n const prefix = `\\x1b[${open}m`;\n const suffix = `\\x1b[${close}m`;\n return (value) => (colorEnabled ? `${prefix}${value}${suffix}` : String(value));\n}\n\nexport const bold = sgr(1, 22);\nexport const dim = sgr(2, 22);\nexport const italic = sgr(3, 23);\nexport const underline = sgr(4, 24);\nexport const red = sgr(31, 39);\nexport const green = sgr(32, 39);\nexport const yellow = sgr(33, 39);\nexport const blue = sgr(34, 39);\nexport const magenta = sgr(35, 39);\nexport const cyan = sgr(36, 39);\nexport const gray = sgr(90, 39);\n\n/** Small, alignment-safe (width-1) glyph vocabulary shared across commands. */\nexport const glyph = {\n pass: \"\u2714\",\n fail: \"\u2716\",\n warn: \"\u26A0\",\n skip: \"\u25CB\",\n info: \"\u2139\",\n arrow: \"\u21B3\",\n bullet: \"\u2022\",\n dot: \"\u00B7\",\n add: \"+\",\n chevron: \"\u25B8\",\n pointer: \"\u276F\",\n} as const;\n\nexport interface StatusStyle {\n glyph: string;\n color: Colorize;\n label: string;\n}\n\n// Covers both audit statuses (pass/fail/warn/skip) and migration result\n// statuses (applied/noop/blocked/skipped/partial).\nconst STATUS_STYLES: Record<string, StatusStyle> = {\n pass: { glyph: glyph.pass, color: green, label: \"pass\" },\n fail: { glyph: glyph.fail, color: red, label: \"fail\" },\n warn: { glyph: glyph.warn, color: yellow, label: \"warn\" },\n skip: { glyph: glyph.skip, color: gray, label: \"skip\" },\n applied: { glyph: glyph.pass, color: green, label: \"applied\" },\n noop: { glyph: glyph.skip, color: gray, label: \"noop\" },\n blocked: { glyph: glyph.fail, color: red, label: \"blocked\" },\n skipped: { glyph: glyph.skip, color: gray, label: \"skipped\" },\n partial: { glyph: glyph.warn, color: yellow, label: \"partial\" },\n};\n\n/** Resolve icon + color + label for a rule/migration status string. */\nexport function statusStyle(status: string): StatusStyle {\n return STATUS_STYLES[status] ?? { glyph: glyph.dot, color: dim, label: status };\n}\n\n/** Color a short project lifecycle status (planned/active/archived/\u2026). */\nexport function projectStatusColor(status: string): Colorize {\n switch (status) {\n case \"active\":\n return green;\n case \"planned\":\n return yellow;\n case \"archived\":\n return gray;\n default:\n return cyan;\n }\n}\n\n/** A section heading: colored marker + bold title. */\nexport function heading(title: string, marker: string = glyph.chevron): string {\n return `${cyan(bold(marker))} ${bold(title)}`;\n}\n\n/** Join fragments with a dim middot separator ( \u00B7 ). */\nexport function joinDot(fragments: string[]): string {\n return fragments.join(dim(` ${glyph.dot} `));\n}\n\n// ---------------------------------------------------------------------------\n// Width-aware layout\n//\n// The default idiom in this codebase is pad-then-color \u2014 pad the RAW string,\n// then colorize the padded result \u2014 and it must stay that way, because\n// String.padEnd counts the invisible escape bytes toward the target width.\n// `cyan(\"mise\").padEnd(12)` is a silent no-op: the colored string is already 14\n// characters long, so nothing is added and the column collapses.\n//\n// The helpers below are for the case pad-then-color cannot cover: a cell built\n// from SEVERAL colored fragments, where there is no single raw string left to\n// pad. There the pad has to be measured against visible width and placed\n// outside the color runs.\n// ---------------------------------------------------------------------------\n\n// eslint-disable-next-line no-control-regex\nconst ANSI_PATTERN = /\\x1b\\[[0-9;]*m/g;\n\n/** Drop SGR escapes, leaving what the terminal actually shows. */\nexport function stripAnsi(value: string): string {\n return value.replace(ANSI_PATTERN, \"\");\n}\n\n/** Rendered column count of a possibly-colored string. */\nexport function visibleWidth(value: string): number {\n return stripAnsi(value).length;\n}\n\n/** Right-pad to `width` measured in VISIBLE columns; pad stays unstyled. */\nexport function padVisible(value: string, width: number): string {\n return value + \" \".repeat(Math.max(0, width - visibleWidth(value)));\n}\n\n/** Truncate to `width` visible columns, marking the cut with an ellipsis. */\nexport function truncateVisible(value: string, width: number): string {\n if (width <= 0) return \"\";\n const plain = stripAnsi(value);\n if (plain.length <= width) return value;\n // Truncating mid-escape would leak color into the rest of the line, so only\n // plain strings are cut; a colored value is reduced to its visible text.\n if (plain.length !== value.length) return width <= 1 ? \"\u2026\" : `${plain.slice(0, width - 1)}\u2026`;\n return width <= 1 ? \"\u2026\" : `${value.slice(0, width - 1)}\u2026`;\n}\n\n/**\n * Usable terminal width.\n *\n * The `> 0` guard is load-bearing rather than defensive: `columns` is\n * undefined on a pipe AND can be reported as 0 by a real pty, so a plain\n * `?? fallback` still yields a zero-width layout.\n */\nexport function terminalWidth(stream: { columns?: number } = process.stdout, fallback = 100): number {\n const columns = stream.columns;\n return typeof columns === \"number\" && columns > 0 ? columns : fallback;\n}\n\n/** Greedy word wrap over visible width. Returns at least one (possibly empty) line. */\nexport function wrapVisible(text: string, width: number): string[] {\n if (width <= 0) return [text];\n const lines: string[] = [];\n let current = \"\";\n for (const word of text.split(/\\s+/).filter(Boolean)) {\n if (!current) {\n current = word;\n } else if (visibleWidth(current) + 1 + visibleWidth(word) <= width) {\n current = `${current} ${word}`;\n } else {\n lines.push(current);\n current = word;\n }\n // A single word longer than the column gets hard-split rather than\n // pushing the whole layout sideways.\n while (visibleWidth(current) > width) {\n lines.push(current.slice(0, width));\n current = current.slice(width);\n }\n }\n lines.push(current);\n return lines;\n}\n", "export const NOTEBOOK_SCHEMA_VERSION = 1 as const;\nexport const NOTEBOOK_POLICY_VERSION = \"project-notebook.v1\" as const;\n\nconst CREDENTIAL_KEY = /(?:^|[_-])(?:password|passwd|api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|private[_-]?key|credential|authorization)(?:$|[_-])/iu;\nconst SECRET_SHAPED_VALUE = /(?:-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|(?<![A-Za-z0-9])eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}(?![A-Za-z0-9])|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|(?:password|api[_-]?key|access[_-]?token|client[_-]?secret)\\s*[:=]\\s*[^\\s]{8,})/iu;\n\n/** Return the first credential-bearing field/value path in a Notebook-owned\n * configuration surface. Environment variable *names* and op:// references\n * are not credential values; raw credential-shaped material is rejected. */\nexport function notebookCredentialMaterialPath(value: unknown): string | null {\n const seen = new WeakSet<object>();\n let visited = 0;\n const walk = (candidate: unknown, path: string, depth: number): string | null => {\n if (++visited > 2_000 || depth > 20) return `${path}.[structure-limit]`;\n if (typeof candidate === \"string\") return SECRET_SHAPED_VALUE.test(candidate) ? path : null;\n if (!candidate || typeof candidate !== \"object\") return null;\n if (seen.has(candidate)) return `${path}.[cycle]`;\n seen.add(candidate);\n if (Array.isArray(candidate)) {\n for (let index = 0; index < candidate.length; index++) {\n const found = walk(candidate[index], `${path}[${index}]`, depth + 1);\n if (found) return found;\n }\n return null;\n }\n for (const [key, child] of Object.entries(candidate as Record<string, unknown>)) {\n const childPath = path ? `${path}.${key}` : key;\n if (CREDENTIAL_KEY.test(key)) return childPath;\n const found = walk(child, childPath, depth + 1);\n if (found) return found;\n }\n return null;\n };\n return walk(value, \"notebook\", 0);\n}\n\nexport type NotebookBindingState = \"disabled\" | \"planned\" | \"linked\";\nexport type NotebookHealth = \"unconfigured\" | \"healthy\" | \"drifted\" | \"unavailable\" | \"blocked\" | null;\nexport type NotebookRemoteCheck = \"pass\" | \"fail\" | \"skip\";\nexport type NotebookReceiptState =\n | \"queued\"\n | \"processing\"\n | \"succeeded\"\n | \"failed\"\n | \"retry-exhausted\"\n | \"blocked-missing-baseline\";\nexport type NotebookAttemptOrigin = \"automatic\" | \"operator\";\nexport type NotebookNoteKind = \"overview\" | \"user-note\" | \"document\" | \"session-capture\";\n\nexport type NotebookErrorCode =\n | \"INVALID_INPUT\"\n | \"NOT_CONFIGURED\"\n | \"AUTHENTICATION_FAILED\"\n | \"NOT_FOUND\"\n | \"CONFLICT\"\n | \"CROSS_PROJECT\"\n | \"DRIFT_DETECTED\"\n | \"THROTTLED\"\n | \"TIMEOUT\"\n | \"SERVICE_UNAVAILABLE\"\n | \"REMOTE_PROTOCOL_ERROR\"\n | \"INTERNAL_ERROR\";\n\nexport class NotebookError extends Error {\n override readonly name = \"NotebookError\";\n\n constructor(\n readonly code: NotebookErrorCode,\n message: string,\n readonly retryable = false,\n readonly details: Record<string, unknown> = {},\n options?: ErrorOptions,\n ) {\n super(message, options);\n }\n}\n\nexport function notebookExitCode(code: NotebookErrorCode): number {\n switch (code) {\n case \"INVALID_INPUT\": return 2;\n case \"NOT_CONFIGURED\":\n case \"AUTHENTICATION_FAILED\": return 3;\n case \"NOT_FOUND\":\n case \"CONFLICT\":\n case \"CROSS_PROJECT\":\n case \"DRIFT_DETECTED\": return 4;\n case \"THROTTLED\":\n case \"TIMEOUT\":\n case \"SERVICE_UNAVAILABLE\": return 5;\n case \"REMOTE_PROTOCOL_ERROR\":\n case \"INTERNAL_ERROR\": return 6;\n }\n}\n\nexport interface NotebookLimitsV1 {\n schema_version: 1;\n overview_max_chars: number;\n request_max_bytes: number;\n response_max_bytes: number;\n note_max_bytes: number;\n source_file_max_bytes: number;\n list_max_items: number;\n note_detail_fetch_concurrency: number;\n excerpt_max_chars: number;\n diagnostic_max_chars: number;\n overall_timeout_ms: number;\n hook_session_start_timeout_ms: number;\n hook_session_end_timeout_ms: number;\n hook_payload_max_bytes: number;\n receipt_succeeded_retention_days: number;\n receiptless_session_retention_seconds: number;\n unresolved_receipt_max_count: number;\n unresolved_receipt_max_bytes: number;\n /** Shared serialized ceiling for SessionBaselineV1 and CaptureReceiptV1 state records. */\n receipt_max_bytes: number;\n automatic_attempt_limit: number;\n lease_seconds: number;\n integrity_max_entries: number;\n refusal_max_entries: number;\n}\n\n/**\n * One versioned source for every finite v1 boundary. Operators may tighten\n * these values in global registry configuration; adapters and hooks must not\n * invent private defaults.\n */\nexport const DEFAULT_NOTEBOOK_LIMITS: Readonly<NotebookLimitsV1> = Object.freeze({\n schema_version: 1,\n overview_max_chars: 4_000,\n request_max_bytes: 1_048_576,\n response_max_bytes: 4_194_304,\n note_max_bytes: 1_048_576,\n source_file_max_bytes: 524_288,\n list_max_items: 1_000,\n note_detail_fetch_concurrency: 8,\n excerpt_max_chars: 320,\n diagnostic_max_chars: 512,\n overall_timeout_ms: 5_000,\n hook_session_start_timeout_ms: 2_000,\n hook_session_end_timeout_ms: 250,\n hook_payload_max_bytes: 1_048_576,\n receipt_succeeded_retention_days: 30,\n receiptless_session_retention_seconds: 86_400,\n unresolved_receipt_max_count: 100,\n unresolved_receipt_max_bytes: 8_388_608,\n receipt_max_bytes: 131_072,\n automatic_attempt_limit: 2,\n lease_seconds: 300,\n integrity_max_entries: 20,\n refusal_max_entries: 100,\n});\n\nexport interface NotebookAuthConfigV1 {\n mode: \"none\" | \"environment\";\n env_var?: string;\n}\n\nexport interface NotebookPolicyV1 {\n enabled: boolean;\n session_start_enabled: boolean;\n session_capture_enabled: boolean;\n overview_max_chars: number;\n documentation_globs: string[];\n overview_references?: string[];\n excluded_globs?: string[];\n}\n\nexport interface NotebookGlobalConfigV1 {\n base_url?: string;\n auth?: NotebookAuthConfigV1;\n defaults?: Partial<NotebookPolicyV1>;\n limits?: Partial<NotebookLimitsV1>;\n summarizer?: { executable: string; args?: string[] };\n [key: string]: unknown;\n}\n\nexport interface ProjectNotebookBindingV1 {\n state: NotebookBindingState;\n notebook_id?: string;\n notebook_name?: string;\n overview_note_id?: string;\n blocked_reason?: string;\n [key: string]: unknown;\n}\n\nexport interface ProjectNotebookConfigV1 {\n binding: ProjectNotebookBindingV1;\n policy?: Partial<NotebookPolicyV1>;\n /** Optional operator-owned display name; stable identity remains the project slug and remote ID. */\n display_name?: string;\n [key: string]: unknown;\n}\n\nexport interface EffectiveNotebookConfigV1 {\n schema_version: 1;\n project_slug: string;\n repo_path: string;\n base_url: string | null;\n auth: NotebookAuthConfigV1;\n policy: NotebookPolicyV1;\n limits: NotebookLimitsV1;\n binding: ProjectNotebookBindingV1;\n configuration_provenance: Record<string, \"default\" | \"registry-global\" | \"project-registry\" | \"manifest-policy\">;\n summarizer?: { executable: string; args: string[] };\n}\n\nexport interface OpenNotebookNotebookV1 {\n id: string;\n name: string;\n description?: string | null;\n archived?: boolean;\n created_at?: string | null;\n updated_at?: string | null;\n}\n\nexport interface OpenNotebookNoteV1 {\n id: string;\n title: string;\n content: string;\n note_type: string;\n created_at: string | null;\n updated_at: string | null;\n}\n\nexport interface NoteSummaryV1 {\n id: string;\n title: string;\n note_type: string;\n created_at: string | null;\n updated_at: string | null;\n excerpt: string;\n}\n\nexport interface NoteDetailV1 extends Omit<NoteSummaryV1, \"excerpt\"> {\n content: string;\n}\n\nexport interface OverviewReferenceV1 {\n path: string;\n status: \"present\" | \"missing\";\n git_revision?: string;\n content_sha256?: string;\n reason?: string;\n}\n\nexport interface OverviewDescriptorV1 {\n schema_version: 1;\n project_slug: string;\n project_name: string;\n purpose: string;\n references: OverviewReferenceV1[];\n compiler_policy_version: string;\n}\n\nexport interface PjanglerNoteEnvelopeV1 {\n schema_version: 1;\n project_slug: string;\n kind: NotebookNoteKind;\n logical_id: string;\n source_path?: string;\n source_revision?: string;\n content_sha256?: string;\n session_key?: string;\n captured_at?: string;\n policy_version?: string;\n overview_descriptor?: OverviewDescriptorV1;\n}\n\nexport interface NotebookProjectSummaryV1 {\n slug: string;\n repo_path: string;\n}\n\nexport interface NotebookEnvelopeV1<T = unknown> {\n schema_version: 1;\n ok: boolean;\n command: string;\n project: NotebookProjectSummaryV1;\n notebook: {\n binding_state: NotebookBindingState;\n health: NotebookHealth;\n id: string | null;\n name: string | null;\n };\n data: T | null;\n error: null | {\n code: NotebookErrorCode;\n message: string;\n retryable: boolean;\n details: Record<string, unknown>;\n };\n next_actions: string[];\n}\n\nexport interface SessionBaselineV1 {\n schema_version: 1;\n session_key: string;\n project_slug: string;\n client: string;\n created_at: string;\n repo_path_digest: string;\n git_head: string | null;\n git_status_digest: string | null;\n policy_version: string;\n tracked_path_digests: Record<string, string>;\n pre_dirty_paths: string[];\n complete: boolean;\n incomplete_reasons: string[];\n}\n\nexport interface OverviewClaimV1 {\n schema_version: 1;\n session_key: string;\n project_slug: string;\n created_at: string;\n overview_note_id: string;\n content_sha256: string;\n}\n\nexport interface CaptureReceiptV1 {\n schema_version: 1;\n receipt_id: string;\n logical_id: string;\n session_key: string;\n project_slug: string;\n repo_path_digest: string;\n baseline_ref: string | null;\n manual_baseline_ref?: string;\n end_revision: string | null;\n end_status_digest: string | null;\n state: NotebookReceiptState;\n automatic_attempts_used: number;\n automatic_attempt_limit: number;\n manual_retry_count: number;\n attempt_origin: NotebookAttemptOrigin;\n lease_owner: string | null;\n lease_deadline: string | null;\n created_at: string;\n updated_at: string;\n exclusion_counts: Record<string, number>;\n summary_mode: \"configured\" | \"deterministic-fallback\" | null;\n note_logical_ids: string[];\n remote_note_ids: string[];\n error_category: NotebookErrorCode | null;\n retryable: boolean;\n diagnostic: string | null;\n serialized_bytes: number;\n}\n\nexport interface CaptureReceiptSummaryV1 {\n receipt_id: string;\n logical_id: string;\n session_key: string;\n state: NotebookReceiptState;\n created_at: string;\n updated_at: string;\n automatic_attempts_used: number;\n automatic_attempt_limit: number;\n manual_retry_count: number;\n attempt_origin: NotebookAttemptOrigin;\n error_category: NotebookErrorCode | null;\n retryable: boolean;\n diagnostic: string | null;\n summary_mode: \"configured\" | \"deterministic-fallback\" | null;\n exclusion_counts: Record<string, number>;\n note_logical_ids: string[];\n remote_note_ids: string[];\n serialized_bytes: number;\n}\n\nexport type RetentionRefusalReason = \"count-cap\" | \"byte-cap\" | \"both\";\n\nexport interface RetentionRefusalV1 {\n schema_version: 1;\n session_key: string;\n baseline_created_at: string;\n refused_at: string;\n reason: RetentionRefusalReason;\n current_count: number;\n current_bytes: number;\n candidate_bytes: number;\n max_count: number;\n max_bytes: number;\n next_actions: string[];\n}\n\nexport interface RetentionRefusalSummaryV1 extends Omit<RetentionRefusalV1, \"schema_version\" | \"baseline_created_at\"> {\n outcome: \"capture-refused-history\";\n}\n\nexport interface CaptureIntegrityEntryV1 {\n entry_id: string;\n reason: \"invalid-json\" | \"unreadable\" | \"non-regular\" | \"invalid-schema\" | \"oversize\" | \"unsafe-permissions\";\n}\n\nexport interface CaptureAdmissionSummaryV1 {\n unresolved_count: number | null;\n unresolved_count_lower_bound: number;\n unresolved_bytes: number | null;\n unresolved_bytes_lower_bound: number;\n unmeasurable_entry_count: number;\n integrity_entries: CaptureIntegrityEntryV1[];\n receipt_caps: { max_count: number; max_bytes: number };\n receiptless_session_count: number;\n stale_receiptless_session_count: number;\n active_refusals: RetentionRefusalSummaryV1[];\n}\n\nexport interface RemoteMutationJournalSummaryV1 {\n operation_id: string;\n kind: \"notebook.create\" | \"note.create\";\n logical_marker: string;\n session_key: string | null;\n state: \"prepared\" | \"possibly-dispatched\" | \"reconciled\";\n binding_id: string | null;\n candidate_ids: string[];\n result_category: string;\n next_action: string;\n}\n\nexport interface NotebookFindingV1 {\n id: string;\n title: string;\n status: \"pass\" | \"fail\" | \"warn\" | \"skip\";\n summary: string;\n details: string[];\n fixable: boolean;\n}\n\nexport const UNRESOLVED_RECEIPT_STATES: ReadonlySet<NotebookReceiptState> = new Set([\n \"queued\",\n \"processing\",\n \"failed\",\n \"retry-exhausted\",\n \"blocked-missing-baseline\",\n]);\n", "import { createHash } from \"node:crypto\";\nimport { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\n\nexport type TreeSnapshot = Map<string, string>;\n\n/** Snapshot operator-visible project files while excluding Git internals. */\nexport function snapshotTree(root: string, current = root, snapshot: TreeSnapshot = new Map()): TreeSnapshot {\n if (!existsSync(current)) return snapshot;\n const rel = relative(root, current) || \".\";\n if (rel === \".git\" || rel.startsWith(`.git${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`)) return snapshot;\n const stat = lstatSync(current);\n if (stat.isSymbolicLink()) {\n snapshot.set(rel, `link:${readlinkSync(current)}`);\n } else if (stat.isFile()) {\n snapshot.set(rel, `file:${createHash(\"sha256\").update(readFileSync(current)).digest(\"hex\")}:${stat.mode & 0o777}`);\n } else if (stat.isDirectory()) {\n snapshot.set(rel, `dir:${stat.mode & 0o777}`);\n for (const name of readdirSync(current)) snapshotTree(root, join(current, name), snapshot);\n } else {\n snapshot.set(rel, `other:${stat.mode}`);\n }\n return snapshot;\n}\n\nexport function changedTreePaths(root: string, before: TreeSnapshot, after: TreeSnapshot): string[] {\n return [...new Set([...before.keys(), ...after.keys()])]\n .filter((path) => path !== \".\" && before.get(path) !== after.get(path))\n .map((path) => join(root, path))\n .sort();\n}\n", "import { createHash } from \"node:crypto\";\nimport {\n accessSync,\n constants,\n existsSync,\n lstatSync,\n readFileSync,\n readdirSync,\n realpathSync,\n statSync,\n} from \"node:fs\";\nimport { tmpdir, userInfo } from \"node:os\";\nimport { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from \"node:path\";\nimport YAML from \"yaml\";\n\nexport interface LifecycleEligibilityResult {\n ok: boolean;\n error?: string;\n}\n\nexport interface TrustedCopierResult extends LifecycleEligibilityResult {\n executable?: string;\n realExecutable?: string;\n layout?: string;\n identity?: TrustedCopierIdentity;\n}\n\nexport interface TrustedCopierFileIdentity {\n path: string;\n realPath: string;\n sha256: string;\n size: number;\n device: number;\n inode: number;\n mode: number;\n uid: number;\n gid: number;\n}\n\n/**\n * Read-only provenance captured before an MCP apply.\n *\n * `executable` is the canonical launcher, not the PATH entry. Callers must\n * revalidate the full identity immediately before their first write and then\n * invoke this exact path. This makes a PATH swap irrelevant and detects a\n * package/launcher replacement between the handler preflight and execution.\n */\nexport interface TrustedCopierIdentity {\n executable: string;\n resolvedFrom: string;\n layout: \"uv-tool\";\n version: string;\n toolRoot: string;\n interpreter: TrustedCopierFileIdentity;\n files: readonly TrustedCopierFileIdentity[];\n}\n\nexport interface TrustedCopierOptions {\n targetDir: string;\n env?: NodeJS.ProcessEnv;\n /** Test-only dependency injection. MCP callers always use the OS account home. */\n homeDir?: string;\n temporaryDir?: string;\n /** Kept for API compatibility; mutable layout allowlists are no longer trusted. */\n systemRoots?: readonly string[];\n}\n\nexport interface RenderedHermesEligibilityOptions {\n pjanglerRoot: string;\n targetDir: string;\n roleDir: string;\n targetRepo: string;\n role: string;\n agentId: string;\n}\n\nfunction containedBy(parent: string, candidate: string): boolean {\n const rel = relative(resolve(parent), resolve(candidate));\n return rel === \"\" || (!rel.startsWith(\"..\") && !isAbsolute(rel));\n}\n\nfunction firstExecutableOnPath(env: NodeJS.ProcessEnv): string | undefined {\n for (const rawEntry of (env.PATH ?? \"\").split(delimiter)) {\n const entry = rawEntry || process.cwd();\n const candidate = resolve(entry, process.platform === \"win32\" ? \"copier.exe\" : \"copier\");\n try {\n accessSync(candidate, constants.X_OK);\n const stat = lstatSync(candidate);\n if (stat.isFile() || stat.isSymbolicLink()) return candidate;\n } catch {\n // Continue to the next PATH entry. Resolution itself must never execute a\n // candidate, because a shadowed program is exactly what this gate rejects.\n }\n }\n return undefined;\n}\n\nfunction sha256(path: string): string {\n return createHash(\"sha256\").update(readFileSync(path)).digest(\"base64url\");\n}\n\nfunction fingerprint(path: string): TrustedCopierFileIdentity {\n const absolute = resolve(path);\n const realPath = realpathSync(absolute);\n const stat = statSync(realPath);\n if (!stat.isFile()) throw new Error(`${absolute} is not a regular file`);\n return {\n path: absolute,\n realPath,\n sha256: sha256(realPath),\n size: stat.size,\n device: stat.dev,\n inode: stat.ino,\n mode: stat.mode,\n uid: stat.uid,\n gid: stat.gid,\n };\n}\n\nfunction sameFingerprint(expected: TrustedCopierFileIdentity): LifecycleEligibilityResult {\n try {\n const actual = fingerprint(expected.path);\n for (const key of [\"realPath\", \"sha256\", \"size\", \"device\", \"inode\", \"mode\", \"uid\", \"gid\"] as const) {\n if (actual[key] !== expected[key]) {\n return { ok: false, error: `trusted Copier identity changed at ${expected.path} (${key})` };\n }\n }\n return { ok: true };\n } catch (error) {\n return {\n ok: false,\n error: `trusted Copier identity is unavailable at ${expected.path}: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n}\n\nfunction consoleScriptContract(path: string): LifecycleEligibilityResult & { interpreter?: string } {\n let text: string;\n try {\n text = readFileSync(path, \"utf8\").slice(0, 32 * 1024);\n } catch (error) {\n return { ok: false, error: `cannot read Copier launcher: ${error instanceof Error ? error.message : String(error)}` };\n }\n const firstLine = text.split(/\\r?\\n/, 1)[0] ?? \"\";\n if (!firstLine.startsWith(\"#!\")) return { ok: false, error: \"Copier launcher has no executable shebang\" };\n const shebang = firstLine.slice(2).trim().split(/\\s+/);\n if (shebang.length !== 1 || !isAbsolute(shebang[0] ?? \"\")) {\n return { ok: false, error: \"Copier launcher must use one absolute Python interpreter\" };\n }\n const interpreterPath = resolve(shebang[0]!);\n const interpreter = basename(interpreterPath);\n if (!/^python(?:\\d+(?:\\.\\d+)*)?$/.test(interpreter)) {\n return { ok: false, error: \"Copier launcher is not an absolute Python console script\" };\n }\n if (!/from\\s+copier\\.__main__\\s+import\\s+CopierApp/.test(text) || !/CopierApp\\.run\\s*\\(/.test(text)) {\n return { ok: false, error: \"Copier launcher does not match the Copier 9 console-script contract\" };\n }\n return { ok: true, interpreter: interpreterPath };\n}\n\nfunction defaultUvToolRoots(home: string): string[] {\n return [\n join(home, \".local\", \"share\", \"uv\", \"tools\", \"copier\"),\n join(home, \"Library\", \"Application Support\", \"uv\", \"tools\", \"copier\"),\n ].map((path) => resolve(path));\n}\n\nfunction locateUvSitePackages(toolRoot: string): string {\n const lib = join(toolRoot, \"lib\");\n const candidates: string[] = [];\n for (const entry of readdirSync(lib, { withFileTypes: true })) {\n if (!entry.isDirectory() || !/^python\\d+(?:\\.\\d+)*$/.test(entry.name)) continue;\n const sitePackages = join(lib, entry.name, \"site-packages\");\n if (existsSync(sitePackages)) candidates.push(sitePackages);\n }\n if (candidates.length !== 1) throw new Error(`expected one UV Copier site-packages directory, found ${candidates.length}`);\n return realpathSync(candidates[0]!);\n}\n\nfunction parseRecordLine(line: string): { relativePath: string; digest: string; size: number } | undefined {\n // Copier's wheel paths contain no CSV quoting. Reject rather than attempting\n // a permissive parse if a future/unexpected distribution does.\n if (!line || line.includes('\"')) return undefined;\n const parts = line.split(\",\");\n if (parts.length !== 3 || !parts[1]?.startsWith(\"sha256=\") || !/^\\d+$/.test(parts[2] ?? \"\")) return undefined;\n return {\n relativePath: parts[0]!,\n digest: parts[1]!.slice(\"sha256=\".length),\n size: Number(parts[2]),\n };\n}\n\nfunction attestUvCopier(candidate: string, realCandidate: string, home: string): TrustedCopierResult {\n const toolRoot = defaultUvToolRoots(home).find((root) => realCandidate === join(root, \"bin\", \"copier\"));\n if (!toolRoot) {\n return { ok: false, error: `refusing untrusted PATH-shadowed Copier executable: ${candidate}` };\n }\n\n const supportedEntries = new Set([\n join(home, \".local\", \"bin\", \"copier\"),\n join(toolRoot, \"bin\", \"copier\"),\n ].map((path) => resolve(path)));\n if (!supportedEntries.has(resolve(candidate))) {\n return { ok: false, error: `refusing non-canonical UV Copier entry point: ${candidate}` };\n }\n\n try {\n const launcher = consoleScriptContract(realCandidate);\n if (!launcher.ok || !launcher.interpreter) {\n return { ...launcher, executable: realCandidate, realExecutable: realCandidate };\n }\n const expectedInterpreter = join(toolRoot, \"bin\", basename(launcher.interpreter));\n if (resolve(launcher.interpreter) !== resolve(expectedInterpreter)) {\n return { ok: false, error: \"UV Copier launcher interpreter is outside the attested tool environment\" };\n }\n\n const interpreterReal = realpathSync(launcher.interpreter);\n const uvPythonRoots = [\n join(home, \".local\", \"share\", \"uv\", \"python\"),\n join(home, \"Library\", \"Application Support\", \"uv\", \"python\"),\n ];\n if (!uvPythonRoots.some((root) => containedBy(root, interpreterReal))) {\n return { ok: false, error: \"UV Copier interpreter is not managed by the canonical UV Python installation\" };\n }\n\n const receiptPath = join(toolRoot, \"uv-receipt.toml\");\n const receipt = readFileSync(receiptPath, \"utf8\");\n if (!/requirements\\s*=\\s*\\[[\\s\\S]*?name\\s*=\\s*[\"']copier[\"']/.test(receipt)\n || !/entrypoints\\s*=\\s*\\[[\\s\\S]*?name\\s*=\\s*[\"']copier[\"'][\\s\\S]*?from\\s*=\\s*[\"']copier[\"']/.test(receipt)) {\n return { ok: false, error: \"UV tool receipt does not bind the copier entry point to the Copier package\" };\n }\n\n const sitePackages = locateUvSitePackages(toolRoot);\n const distInfos = readdirSync(sitePackages, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && /^copier-[^-]+\\.dist-info$/i.test(entry.name))\n .map((entry) => join(sitePackages, entry.name));\n if (distInfos.length !== 1) {\n return { ok: false, error: `expected one installed Copier distribution, found ${distInfos.length}` };\n }\n const distInfo = realpathSync(distInfos[0]!);\n const metadataPath = join(distInfo, \"METADATA\");\n const entryPointsPath = join(distInfo, \"entry_points.txt\");\n const recordPath = join(distInfo, \"RECORD\");\n const metadata = readFileSync(metadataPath, \"utf8\");\n const name = metadata.match(/^Name:\\s*(.+)$/mi)?.[1]?.trim();\n const version = metadata.match(/^Version:\\s*(.+)$/mi)?.[1]?.trim();\n if (name?.toLowerCase() !== \"copier\" || !version || !/^9(?:\\.|$)/.test(version)) {\n return { ok: false, error: \"installed distribution is not a Copier 9 package\" };\n }\n const entryPoints = readFileSync(entryPointsPath, \"utf8\");\n if (!/^copier\\s*=\\s*copier\\.__main__:CopierApp\\.run\\s*$/m.test(entryPoints)) {\n return { ok: false, error: \"installed Copier distribution has an unexpected console entry point\" };\n }\n\n const recordEntries = readFileSync(recordPath, \"utf8\")\n .split(/\\r?\\n/)\n .map(parseRecordLine)\n .filter((entry): entry is NonNullable<typeof entry> => Boolean(entry));\n const selected = recordEntries.filter((entry) => {\n const normalized = entry.relativePath.replaceAll(\"\\\\\", \"/\");\n return normalized.startsWith(\"copier/\")\n || normalized === `${basename(distInfo)}/METADATA`\n || normalized === `${basename(distInfo)}/entry_points.txt`\n || normalized === \"../../../bin/copier\";\n });\n if (!selected.some((entry) => entry.relativePath === \"../../../bin/copier\")\n || !selected.some((entry) => entry.relativePath.replaceAll(\"\\\\\", \"/\") === \"copier/__main__.py\")) {\n return { ok: false, error: \"Copier RECORD does not bind its launcher and package entry point\" };\n }\n\n const attestedFiles = new Map<string, TrustedCopierFileIdentity>();\n for (const entry of selected) {\n const path = resolve(sitePackages, entry.relativePath);\n const allowed = path === realCandidate || containedBy(sitePackages, path);\n if (!allowed) return { ok: false, error: `Copier RECORD path escapes the tool environment: ${entry.relativePath}` };\n const actualDigest = sha256(path);\n const actualSize = statSync(path).size;\n if (actualDigest !== entry.digest || actualSize !== entry.size) {\n return { ok: false, error: `Copier RECORD integrity mismatch: ${entry.relativePath}` };\n }\n attestedFiles.set(resolve(path), fingerprint(path));\n }\n for (const path of [realCandidate, join(toolRoot, \"pyvenv.cfg\"), receiptPath, metadataPath, entryPointsPath, recordPath]) {\n attestedFiles.set(resolve(path), fingerprint(path));\n }\n\n const identity: TrustedCopierIdentity = {\n executable: realCandidate,\n resolvedFrom: resolve(candidate),\n layout: \"uv-tool\",\n version,\n toolRoot,\n interpreter: fingerprint(launcher.interpreter),\n files: [...attestedFiles.values()].sort((left, right) => left.path.localeCompare(right.path)),\n };\n return {\n ok: true,\n executable: identity.executable,\n realExecutable: identity.executable,\n layout: identity.layout,\n identity,\n };\n } catch (error) {\n return { ok: false, error: `cannot attest UV Copier installation: ${error instanceof Error ? error.message : String(error)}` };\n }\n}\n\nexport function verifyTrustedCopierIdentity(identity: TrustedCopierIdentity): LifecycleEligibilityResult {\n if (!isAbsolute(identity.executable) || resolve(identity.executable) !== resolve(identity.files.find((file) => file.path === identity.executable)?.path ?? \"\")) {\n return { ok: false, error: \"trusted Copier identity has no canonical absolute launcher\" };\n }\n const interpreter = sameFingerprint(identity.interpreter);\n if (!interpreter.ok) return interpreter;\n for (const file of identity.files) {\n const verified = sameFingerprint(file);\n if (!verified.ok) return verified;\n }\n return { ok: true };\n}\n\n/**\n * Resolve and attest Copier without executing it.\n *\n * MCP apply paths accept the first PATH match only when it resolves to the\n * canonical Copier UV tool for the operating-system account. Layout or\n * launcher text alone is not provenance: the UV receipt, absolute interpreter,\n * Copier 9 distribution metadata, entry point, PEP-376 RECORD hashes, package\n * files, venv metadata, and interpreter are bound into an identity. pip-user,\n * pipx, pyenv, Homebrew, and arbitrary system locations remain usable by the\n * interactive CLI but fail closed for MCP apply unless a future implementation\n * can establish an equally strong package identity. An earlier shadow is never\n * skipped in favor of a later executable.\n */\nexport function preflightTrustedCopier(options: TrustedCopierOptions): TrustedCopierResult {\n const env = options.env ?? process.env;\n // Do not let an ambient HOME redirect the trust root. Tests can inject a\n // synthetic account home explicitly; production MCP callers cannot.\n const home = resolve(options.homeDir ?? userInfo().homedir);\n const temporary = resolve(options.temporaryDir ?? tmpdir());\n const target = resolve(options.targetDir);\n const candidate = firstExecutableOnPath(env);\n if (!candidate) return { ok: false, error: \"copier not found on PATH\" };\n\n let realCandidate: string;\n try {\n realCandidate = realpathSync(candidate);\n } catch (error) {\n return { ok: false, error: `cannot resolve Copier launcher: ${error instanceof Error ? error.message : String(error)}` };\n }\n\n for (const [label, root] of [[\"target\", target], [\"temporary\", temporary]] as const) {\n if (containedBy(root, candidate) || containedBy(root, realCandidate)) {\n return { ok: false, error: `refusing ${label}-local Copier executable: ${candidate}` };\n }\n }\n\n return attestUvCopier(candidate, realCandidate, home);\n}\n\nfunction regularContainedFile(root: string, path: string, label: string): LifecycleEligibilityResult {\n try {\n const rootReal = realpathSync(root);\n const fileReal = realpathSync(path);\n if (!containedBy(rootReal, fileReal)) return { ok: false, error: `${label} escapes its vendored template root` };\n if (!lstatSync(path).isFile()) return { ok: false, error: `${label} is not a regular file` };\n return { ok: true };\n } catch (error) {\n return { ok: false, error: `${label} is unavailable: ${error instanceof Error ? error.message : String(error)}` };\n }\n}\n\nfunction parseCopierConfig(templateRoot: string, label: string): { result: LifecycleEligibilityResult; config?: Record<string, unknown> } {\n const configPath = join(templateRoot, \"copier.yml\");\n const file = regularContainedFile(templateRoot, configPath, `${label} copier.yml`);\n if (!file.ok) return { result: file };\n try {\n const parsed = YAML.parse(readFileSync(configPath, \"utf8\"));\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return { result: { ok: false, error: `${label} copier.yml must contain a mapping` } };\n }\n const config = parsed as Record<string, unknown>;\n if (config._subdirectory !== \"template\") {\n return { result: { ok: false, error: `${label} copier.yml must render the template subdirectory` } };\n }\n if (!/^9(?:\\.|$)/.test(String(config._min_copier_version ?? \"\"))) {\n return { result: { ok: false, error: `${label} requires an unsupported Copier contract` } };\n }\n return { result: { ok: true }, config };\n } catch (error) {\n return { result: { ok: false, error: `${label} copier.yml is invalid: ${error instanceof Error ? error.message : String(error)}` } };\n }\n}\n\nfunction requireFiles(templateRoot: string, files: readonly string[], label: string): LifecycleEligibilityResult {\n for (const rel of files) {\n const result = regularContainedFile(templateRoot, join(templateRoot, rel), `${label} ${rel}`);\n if (!result.ok) return result;\n }\n return { ok: true };\n}\n\nexport function preflightCommonProjectTemplate(pjanglerRoot: string): LifecycleEligibilityResult {\n const templateRoot = join(resolve(pjanglerRoot), \"templates\", \"commonproject\");\n const parsed = parseCopierConfig(templateRoot, \"CommonProject template\");\n if (!parsed.result.ok) return parsed.result;\n const files = requireFiles(templateRoot, [\n \"template/.project.json.jinja\",\n \"template/.copier-answers.yml.jinja\",\n \"template/.env.op\",\n \"template/AGENTS.md.jinja\",\n \"template/mise.toml.jinja\",\n ], \"CommonProject template\");\n if (!files.ok) return files;\n const projectJson = readFileSync(join(templateRoot, \"template\", \".project.json.jinja\"), \"utf8\");\n for (const key of [\"project_name\", \"project_slug\", \"repo_path\", \"ticket_provider\", \"agents\"]) {\n if (!projectJson.includes(`\\\"${key}\\\"`)) return { ok: false, error: `CommonProject projection is missing ${key}` };\n }\n return { ok: true };\n}\n\nexport function preflightHermesTemplate(pjanglerRoot: string, env: NodeJS.ProcessEnv = process.env): LifecycleEligibilityResult {\n const templateRoot = join(resolve(pjanglerRoot), \"templates\", \"hermes-agent\");\n const explicit = env.PJANGLER_HERMES_TEMPLATE?.trim();\n if (explicit) {\n try {\n if (realpathSync(resolve(explicit)) !== realpathSync(templateRoot)) {\n return { ok: false, error: \"MCP Hermes apply requires the version-locked vendored template\" };\n }\n } catch (error) {\n return { ok: false, error: `Hermes template override is unavailable: ${error instanceof Error ? error.message : String(error)}` };\n }\n }\n const parsed = parseCopierConfig(templateRoot, \"Hermes template\");\n if (!parsed.result.ok) return parsed.result;\n const required = requireFiles(templateRoot, [\n \"template/role.yaml.jinja\",\n \"template/SOUL.md.jinja\",\n \"template/hermes.jinja\",\n \"template/.scripts/_lib.sh\",\n \"template/.scripts/01-config.sh\",\n \"template/.scripts/05-fleet-env.sh\",\n \"template/.scripts/10-hermes-profile.sh\",\n \"template/.scripts/20-runtime-repo.sh\",\n \"template/.scripts/30-telegram.sh\",\n \"template/.scripts/31-slack.sh\",\n \"template/.scripts/42-ticket-provider.sh\",\n \"template/.scripts/70-systemd.sh\",\n \"template/.scripts/80-registry.sh\",\n ], \"Hermes template\");\n if (!required.ok) return required;\n\n const role = readFileSync(join(templateRoot, \"template\", \"role.yaml.jinja\"), \"utf8\");\n if (!/^bloodbank:\\s*$[\\s\\S]*?^\\s+enabled:\\s+(?:true|false)\\s*$/m.test(role)) {\n return { ok: false, error: \"Hermes role projection must declare bloodbank.enabled as a strict boolean\" };\n }\n const library = readFileSync(join(templateRoot, \"template\", \".scripts\", \"_lib.sh\"), \"utf8\");\n if (!library.includes(\"PJANGLER_PROJECT_ROOT\") || !library.includes('\"$explicit\"/agents/hermes/*')) {\n return { ok: false, error: \"Hermes project-root resolver must honor the explicitly contained MCP target\" };\n }\n const skipPlane = readFileSync(join(templateRoot, \"template\", \".scripts\", \"42-ticket-provider.sh\"), \"utf8\");\n const guard = skipPlane.indexOf('if [[ \"${SKIP_PLANE:-0}\" == \"1\" ]]');\n const firstSource = skipPlane.search(/^source\\s/m);\n if (guard < 0 || firstSource < 0 || guard > firstSource) {\n return { ok: false, error: \"Hermes ticket-provider skip guard must precede all sourced provider/config logic\" };\n }\n // 30/31 write into the profile root 10-hermes-profile.sh creates, so they\n // must defer with it. Without the guard both died on \"required profile root\n // is unavailable\" and took every deferred MCP render down with them.\n for (const script of [\"01-config.sh\", \"05-fleet-env.sh\", \"10-hermes-profile.sh\", \"30-telegram.sh\", \"31-slack.sh\", \"80-registry.sh\"]) {\n const text = readFileSync(join(templateRoot, \"template\", \".scripts\", script), \"utf8\");\n const hostGuard = text.indexOf('if [[ \"${SKIP_HOST_STATE:-0}\" == \"1\" ]]');\n const source = text.search(/^source\\s/m);\n if (hostGuard < 0 || source < 0 || hostGuard > source) {\n return { ok: false, error: `Hermes ${script} host-state guard must precede all sourced config/fleet logic` };\n }\n }\n const tasks = Array.isArray(parsed.config?._tasks) ? parsed.config._tasks.map(String) : [];\n for (const script of [\"20-runtime-repo.sh\", \"42-ticket-provider.sh\", \"70-systemd.sh\", \"80-registry.sh\"]) {\n if (!tasks.some((task) => task.includes(script))) return { ok: false, error: `Hermes copier task list is missing ${script}` };\n }\n return { ok: true };\n}\n\n/**\n * Validate the trusted Copier projection before any host-global script runs.\n *\n * The executable and version-locked template were attested before Copier was\n * launched. This second, read-only gate proves that the rendered identity,\n * strict lifecycle metadata, local project registration, and every script we\n * may execute in the host/external tails are exactly the expected projection.\n */\nexport function preflightRenderedHermes(options: RenderedHermesEligibilityOptions): LifecycleEligibilityResult {\n const target = resolve(options.targetDir);\n const roleDir = resolve(options.roleDir);\n if (!containedBy(target, roleDir)) return { ok: false, error: \"rendered Hermes role escapes its project target\" };\n try {\n const stat = lstatSync(roleDir);\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n return { ok: false, error: \"rendered Hermes role must be a real directory\" };\n }\n } catch (error) {\n return { ok: false, error: `rendered Hermes role is unavailable: ${error instanceof Error ? error.message : String(error)}` };\n }\n\n const templateScripts = join(resolve(options.pjanglerRoot), \"templates\", \"hermes-agent\", \"template\", \".scripts\");\n const renderedScripts = join(roleDir, \".scripts\");\n const requiredFiles = [\n \"role.yaml\",\n \"SOUL.md\",\n \"hermes\",\n \".gitignore\",\n \".runtime-scaffold/README.md\",\n ...[\"_lib.sh\", \"01-config.sh\", \"05-fleet-env.sh\", \"10-hermes-profile.sh\", \"20-runtime-repo.sh\", \"42-ticket-provider.sh\", \"70-systemd.sh\", \"80-registry.sh\"]\n .map((script) => `.scripts/${script}`),\n ];\n const required = requireFiles(roleDir, requiredFiles, \"rendered Hermes role\");\n if (!required.ok) return required;\n\n for (const script of [\"_lib.sh\", \"01-config.sh\", \"05-fleet-env.sh\", \"10-hermes-profile.sh\", \"20-runtime-repo.sh\", \"42-ticket-provider.sh\", \"70-systemd.sh\", \"80-registry.sh\"]) {\n try {\n if (readFileSync(join(renderedScripts, script), \"utf8\") !== readFileSync(join(templateScripts, script), \"utf8\")) {\n return { ok: false, error: `rendered Hermes script differs from the attested template: ${script}` };\n }\n } catch (error) {\n return { ok: false, error: `cannot attest rendered Hermes script ${script}: ${error instanceof Error ? error.message : String(error)}` };\n }\n }\n\n let role: Record<string, unknown>;\n try {\n const parsed = YAML.parse(readFileSync(join(roleDir, \"role.yaml\"), \"utf8\")) as unknown;\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return { ok: false, error: \"rendered Hermes role.yaml must contain a mapping\" };\n }\n role = parsed as Record<string, unknown>;\n } catch (error) {\n return { ok: false, error: `rendered Hermes role.yaml is invalid: ${error instanceof Error ? error.message : String(error)}` };\n }\n if (role.repo !== options.targetRepo || role.role !== options.role || role.agent_id !== options.agentId) {\n return { ok: false, error: \"rendered Hermes role identity does not match the requested repo/role/agent\" };\n }\n const bloodbank = role.bloodbank as Record<string, unknown> | undefined;\n if (!bloodbank || typeof bloodbank.enabled !== \"boolean\") {\n return { ok: false, error: \"rendered Hermes bloodbank.enabled must be a strict boolean\" };\n }\n const deployment = role.deployment as Record<string, unknown> | undefined;\n if (!deployment || deployment.local_only !== true || deployment.systemd !== \"deferred\") {\n return { ok: false, error: \"rendered Hermes deployment must remain local-only/deferred until external grants run\" };\n }\n\n const manifestPath = join(target, \".project.json\");\n if (existsSync(manifestPath)) {\n try {\n const manifest = JSON.parse(readFileSync(manifestPath, \"utf8\")) as Record<string, unknown>;\n const agents = manifest.agents as Record<string, Record<string, unknown>> | undefined;\n const declared = agents?.[options.agentId];\n if (!declared\n || declared.role !== options.role\n || declared.role_dir !== relative(target, roleDir)\n || declared.provisioning_state !== \"provisioned\") {\n return { ok: false, error: \"rendered Hermes role is not canonically registered in .project.json\" };\n }\n } catch (error) {\n return { ok: false, error: `cannot validate rendered Hermes project registration: ${error instanceof Error ? error.message : String(error)}` };\n }\n }\n return { ok: true };\n}\n\nexport function preflightMcpLifecycle(options: {\n pjanglerRoot: string;\n targetDir: string;\n commonProject: boolean;\n hermes: boolean;\n env?: NodeJS.ProcessEnv;\n}): TrustedCopierResult {\n const copier = preflightTrustedCopier({ targetDir: options.targetDir, env: options.env });\n if (!copier.ok) return copier;\n if (options.commonProject) {\n const common = preflightCommonProjectTemplate(options.pjanglerRoot);\n if (!common.ok) return { ...common, executable: copier.executable, realExecutable: copier.realExecutable };\n }\n if (options.hermes) {\n const hermes = preflightHermesTemplate(options.pjanglerRoot, options.env);\n if (!hermes.ok) return { ...hermes, executable: copier.executable, realExecutable: copier.realExecutable };\n }\n return copier;\n}\n", "import { Pool } from \"pg\";\nimport type { PoolClient } from \"pg\";\nimport type {\n ProjectRecord,\n ProjectRegistry,\n ProjectAgentRecord,\n ProjectTicketProvider,\n SourceArtifact,\n ProjectAutomation,\n} from \"./index\";\nimport type { NotebookGlobalConfigV1, ProjectNotebookBindingV1 } from \"../notebook/types\";\nimport {\n PROJECT_REGISTRY_SCHEMA_VERSION,\n createSafeRecord,\n getOwnRecordValue,\n loadProjectRegistry,\n saveProjectRegistry,\n validateProjectRegistry,\n} from \"./index\";\n\nconst PROJECT_OWNED_KEYS = new Set([\n \"name\", \"slug\", \"repo_path\", \"description\", \"status\", \"source_artifacts\", \"template\",\n \"ticket_provider\", \"agents\", \"automation\", \"notebook\", \"created_at\", \"updated_at\",\n]);\nconst REGISTRY_OWNED_KEYS = new Set([\"schema_version\", \"notebook\", \"projects\"]);\n\nfunction projectExtensions(record: ProjectRecord): Record<string, unknown> {\n return Object.fromEntries(Object.entries(record).filter(([key]) => !PROJECT_OWNED_KEYS.has(key)));\n}\n\nfunction registryExtensions(registry: ProjectRegistry): Record<string, unknown> {\n return Object.fromEntries(Object.entries(registry).filter(([key]) => !REGISTRY_OWNED_KEYS.has(key)));\n}\n\n// ---------------------------------------------------------------------------\n// RegistryStore interface\n// ---------------------------------------------------------------------------\n\nexport interface RegistryStore {\n load(): Promise<ProjectRegistry>;\n save(registry: ProjectRegistry): Promise<void>;\n upsert(slug: string, record: ProjectRecord): Promise<void>;\n getBySlug(slug: string): Promise<ProjectRecord | undefined>;\n getByRepoPath(repoPath: string): Promise<ProjectRecord | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// YamlRegistryStore \u2014 wraps the existing YAML behavior identically\n// ---------------------------------------------------------------------------\n\nexport class YamlRegistryStore implements RegistryStore {\n constructor(private readonly path: string) {}\n\n async load(): Promise<ProjectRegistry> {\n return loadProjectRegistry(this.path);\n }\n\n async save(registry: ProjectRegistry): Promise<void> {\n saveProjectRegistry(registry, this.path);\n }\n\n async upsert(slug: string, record: ProjectRecord): Promise<void> {\n validateProjectRegistry({\n schema_version: PROJECT_REGISTRY_SCHEMA_VERSION,\n projects: createSafeRecord([[slug, record]]),\n });\n const registry = await this.load();\n registry.projects[slug] = record;\n await this.save(registry);\n }\n\n async getBySlug(slug: string): Promise<ProjectRecord | undefined> {\n const registry = await this.load();\n return getOwnRecordValue(registry.projects, slug);\n }\n\n async getByRepoPath(repoPath: string): Promise<ProjectRecord | undefined> {\n const registry = await this.load();\n return Object.values(registry.projects).find(\n (p) => p.repo_path === repoPath\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// PgRegistryStore \u2014 maps ProjectRecord \u2194 projects/repos/boards/agents\n// Writes ONLY rows it owns (slug IS NOT NULL). Never mutates slug IS NULL rows.\n// ---------------------------------------------------------------------------\n\nexport interface PgRegistryConfig {\n host: string;\n port: number;\n user: string;\n password: string;\n database: string;\n}\n\nexport function pgRegistryConfigFromEnv(\n env: NodeJS.ProcessEnv = process.env\n): PgRegistryConfig {\n return {\n host: env.PGHOST || \"localhost\",\n port: parseInt(env.PGPORT || \"5432\", 10),\n user: env.PGUSER || \"delorenj\",\n password: env.PGPASSWORD || \"\",\n database: env.PGDATABASE || \"33god\",\n };\n}\n\nexport class PgRegistryStore implements RegistryStore {\n private pool: Pool;\n\n constructor(config: PgRegistryConfig) {\n this.pool = new Pool({\n host: config.host,\n port: config.port,\n user: config.user,\n password: config.password,\n database: config.database,\n });\n }\n\n async load(): Promise<ProjectRegistry> {\n const client = await this.pool.connect();\n try {\n const { rows } = await client.query<{\n id: string;\n name: string | null;\n description: string | null;\n slug: string | null;\n status: string | null;\n source_artifacts: SourceArtifact[] | null;\n template: ProjectRecord[\"template\"] | null;\n automation: ProjectAutomation | null;\n notebook: ProjectNotebookBindingV1 | null;\n pjangler_extensions: Record<string, unknown> | null;\n created_at: Date;\n updated_at: Date;\n repo_id: string | null;\n local_path: string | null;\n }>(\n `SELECT p.id, p.name, p.description, p.slug, p.status,\n p.source_artifacts, p.template, p.automation, p.notebook, p.pjangler_extensions,\n p.created_at, p.updated_at,\n r.id AS repo_id, r.local_path\n FROM public.projects p\n LEFT JOIN public.repos r ON r.project_id = p.id\n WHERE p.slug IS NOT NULL`\n );\n\n const projects = createSafeRecord<ProjectRecord>();\n for (const row of rows) {\n const slug = row.slug!;\n const ticketProvider = await this.loadTicketProvider(client, row.id);\n const agents = await this.loadAgents(client, row.id, slug);\n projects[slug] = {\n ...(row.pjangler_extensions ?? {}),\n name: row.name ?? \"\",\n slug,\n repo_path: row.local_path ?? \"\",\n description: row.description ?? \"\",\n // Read-time fallback for legacy rows whose status column is NULL.\n // Deliberately NOT the new-project default (PJAN-26 = \"active\"):\n // load() feeds save()/upsert(), so flipping this would retroactively\n // rewrite every pre-existing NULL-status row to \"active\" on the next\n // write. New records get their status from planProjectInit().\n status: row.status ?? \"planned\",\n source_artifacts: row.source_artifacts ?? [],\n template: row.template ?? {\n commonproject: { enabled: false, primary_language: \"python\" },\n },\n ticket_provider: ticketProvider,\n agents,\n automation: row.automation ?? undefined,\n notebook: row.notebook && Object.keys(row.notebook).length ? row.notebook : undefined,\n created_at: row.created_at.toISOString(),\n updated_at: row.updated_at.toISOString(),\n };\n }\n\n let settings: { schema_version: number; notebook: NotebookGlobalConfigV1 | null; extensions: Record<string, unknown> | null } | undefined;\n try {\n const settingsResult = await client.query<{ schema_version: number; notebook: NotebookGlobalConfigV1 | null; extensions: Record<string, unknown> | null }>(\n `SELECT schema_version, notebook, extensions FROM public.pjangler_registry_settings WHERE scope = 'global'`,\n );\n settings = settingsResult.rows[0];\n } catch (error) {\n if ((error as { code?: string }).code !== \"42P01\" && (error as { code?: string }).code !== \"42703\") throw error;\n }\n const registry: ProjectRegistry = {\n ...(settings?.extensions ?? {}),\n schema_version: PROJECT_REGISTRY_SCHEMA_VERSION,\n ...(settings?.notebook && Object.keys(settings.notebook).length ? { notebook: settings.notebook } : {}),\n projects,\n };\n validateProjectRegistry(registry);\n return registry;\n } finally {\n client.release();\n }\n }\n\n async save(registry: ProjectRegistry): Promise<void> {\n validateProjectRegistry(registry);\n const client = await this.pool.connect();\n try {\n await client.query(\"BEGIN\");\n await this.upsertSettingsInTx(client, registry);\n // save() mirrors the authoritative YAML registry, including owned\n // removals. Rows with slug IS NULL remain outside PJangler ownership.\n await client.query(\n `DELETE FROM public.projects\n WHERE slug IS NOT NULL AND NOT (slug = ANY($1::text[]))`,\n [Object.keys(registry.projects)],\n );\n for (const [slug, record] of Object.entries(registry.projects)) {\n await this.upsertInTx(client, slug, record);\n }\n await client.query(\"COMMIT\");\n } catch (err) {\n await client.query(\"ROLLBACK\");\n throw err;\n } finally {\n client.release();\n }\n }\n\n async upsert(slug: string, record: ProjectRecord): Promise<void> {\n validateProjectRegistry({\n schema_version: PROJECT_REGISTRY_SCHEMA_VERSION,\n projects: createSafeRecord([[slug, record]]),\n });\n const client = await this.pool.connect();\n try {\n await client.query(\"BEGIN\");\n await this.upsertInTx(client, slug, record);\n await client.query(\"COMMIT\");\n } catch (err) {\n await client.query(\"ROLLBACK\");\n throw err;\n } finally {\n client.release();\n }\n }\n\n async getBySlug(slug: string): Promise<ProjectRecord | undefined> {\n const registry = await this.load();\n return getOwnRecordValue(registry.projects, slug);\n }\n\n async getByRepoPath(repoPath: string): Promise<ProjectRecord | undefined> {\n const registry = await this.load();\n return Object.values(registry.projects).find(\n (p) => p.repo_path === repoPath\n );\n }\n\n async close(): Promise<void> {\n await this.pool.end();\n }\n\n // --- private helpers ---\n\n private async upsertInTx(\n client: PoolClient,\n slug: string,\n record: ProjectRecord\n ): Promise<void> {\n // SAFETY: never touch rows where slug IS NULL (legacy rows owned by another component)\n if (!slug) throw new Error(\"PgRegistryStore.upsert: slug is required\");\n\n // 1. Upsert project row\n const projectResult = await client.query<{ id: string }>(\n `INSERT INTO public.projects (name, description, slug, status, source_artifacts, template, automation, notebook, pjangler_extensions)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)\n ON CONFLICT (slug) WHERE slug IS NOT NULL\n DO UPDATE SET\n name = EXCLUDED.name,\n description = EXCLUDED.description,\n status = EXCLUDED.status,\n source_artifacts = EXCLUDED.source_artifacts,\n template = EXCLUDED.template,\n automation = EXCLUDED.automation,\n notebook = EXCLUDED.notebook,\n pjangler_extensions = EXCLUDED.pjangler_extensions\n RETURNING id`,\n [\n record.name,\n record.description,\n slug,\n record.status,\n JSON.stringify(record.source_artifacts),\n JSON.stringify(record.template),\n record.automation ? JSON.stringify(record.automation) : null,\n JSON.stringify(record.notebook ?? {}),\n JSON.stringify(projectExtensions(record)),\n ]\n );\n const projectId = projectResult.rows[0]?.id;\n if (!projectId) throw new Error(`Failed to upsert project: ${slug}`);\n\n // 2. Upsert repo row\n await client.query(\n `INSERT INTO public.repos (project_id, local_path)\n VALUES ($1, $2)\n ON CONFLICT (local_path)\n DO UPDATE SET project_id = EXCLUDED.project_id\n RETURNING id`,\n [projectId, record.repo_path]\n );\n\n const repoResult = await client.query<{ id: string }>(\n `SELECT id FROM public.repos WHERE project_id = $1 AND local_path = $2`,\n [projectId, record.repo_path]\n );\n const repoId = repoResult.rows[0]?.id;\n if (!repoId) throw new Error(`Failed to find repo for project ${slug} at path ${record.repo_path}`);\n\n // 3. Upsert ticket provider\n await this.upsertTicketProvider(client, projectId, repoId, record.ticket_provider);\n\n // 4. Sync agents (delete + insert)\n await client.query(\n `DELETE FROM public.project_agents WHERE project_id = $1`,\n [projectId]\n );\n for (const [agentKey, agent] of Object.entries(record.agents)) {\n await client.query(\n `INSERT INTO public.project_agents (repo_id, project_id, agent_key, role, role_dir, provisioning_state)\n VALUES ($1, $2, $3, $4, $5, $6)`,\n [repoId, projectId, agentKey, agent.role, agent.role_dir ?? null, agent.provisioning_state]\n );\n }\n }\n\n private async upsertSettingsInTx(client: PoolClient, registry: ProjectRegistry): Promise<void> {\n await client.query(\n `INSERT INTO public.pjangler_registry_settings (scope, schema_version, notebook, extensions)\n VALUES ('global', $1, $2, $3)\n ON CONFLICT (scope) DO UPDATE SET\n schema_version = EXCLUDED.schema_version,\n notebook = EXCLUDED.notebook,\n extensions = EXCLUDED.extensions`,\n [registry.schema_version, JSON.stringify(registry.notebook ?? {}), JSON.stringify(registryExtensions(registry))],\n );\n }\n\n private async loadTicketProvider(\n client: PoolClient,\n projectId: string\n ): Promise<ProjectTicketProvider> {\n const { rows } = await client.query<{\n provider_type: string;\n workspace: string | null;\n identifier: string | null;\n identifier_source: string | null;\n identifier_fetched_at: Date | string | null;\n board_id: string | null;\n board_confirmed_at: Date | string | null;\n state: string | null;\n }>(\n `SELECT provider_type, workspace, identifier, identifier_source, identifier_fetched_at, board_id, board_confirmed_at, state\n FROM public.project_ticket_boards\n WHERE project_id = $1\n LIMIT 1`,\n [projectId]\n );\n if (!rows.length) {\n return { type: \"plane\", workspace: \"33god\", identifier: \"\", board_id: \"\", state: \"planned\" };\n }\n const row = rows[0]!;\n const fetchedAt = row.identifier_fetched_at;\n const confirmedAt = row.board_confirmed_at;\n return {\n type: row.provider_type,\n workspace: row.workspace ?? undefined,\n identifier: row.identifier ?? undefined,\n // Provenance is a column, not an extension blob: dropping it here would\n // silently demote every provider-confirmed board back to a guess.\n identifier_source: (row.identifier_source as ProjectTicketProvider[\"identifier_source\"]) ?? undefined,\n identifier_fetched_at: fetchedAt\n ? (fetchedAt instanceof Date ? fetchedAt.toISOString() : String(fetchedAt))\n : undefined,\n board_id: row.board_id ?? undefined,\n // Board-binding provenance is its own column for the same reason\n // identifier provenance is: dropping it demotes every honest link.\n board_confirmed_at: confirmedAt\n ? (confirmedAt instanceof Date ? confirmedAt.toISOString() : String(confirmedAt))\n : undefined,\n state: (row.state as ProjectTicketProvider[\"state\"]) ?? undefined,\n };\n }\n\n private async loadAgents(\n client: PoolClient,\n projectId: string,\n slug: string\n ): Promise<Record<string, ProjectAgentRecord>> {\n const { rows } = await client.query<{\n agent_key: string;\n role: string;\n role_dir: string | null;\n provisioning_state: string;\n }>(\n `SELECT agent_key, role, role_dir, provisioning_state\n FROM public.project_agents\n WHERE project_id = $1`,\n [projectId]\n );\n const agents = createSafeRecord<ProjectAgentRecord>();\n for (const row of rows) {\n agents[row.agent_key] = {\n role: row.role,\n provisioning_state: row.provisioning_state as ProjectAgentRecord[\"provisioning_state\"],\n role_dir: row.role_dir ?? undefined,\n };\n }\n return agents;\n }\n\n private async upsertTicketProvider(\n client: PoolClient,\n projectId: string,\n repoId: string,\n tp: ProjectTicketProvider\n ): Promise<void> {\n // Delete existing and re-insert (simplest for sync)\n await client.query(\n `DELETE FROM public.project_ticket_boards WHERE project_id = $1`,\n [projectId]\n );\n await client.query(\n `INSERT INTO public.project_ticket_boards\n (repo_id, project_id, provider_type, workspace, identifier, identifier_source, identifier_fetched_at, board_id, board_confirmed_at, state)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,\n [\n repoId,\n projectId,\n tp.type,\n tp.workspace ?? null,\n tp.identifier ?? null,\n tp.identifier_source ?? null,\n tp.identifier_fetched_at ?? null,\n tp.board_id ?? null,\n tp.board_confirmed_at ?? null,\n tp.state ?? null,\n ]\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// DualWriteRegistryStore \u2014 writes BOTH yaml (authoritative) AND PG;\n// reads from yaml.\n// ---------------------------------------------------------------------------\n\nexport class DualWriteRegistryStore implements RegistryStore {\n constructor(\n private readonly yaml: YamlRegistryStore,\n private readonly pg: PgRegistryStore\n ) {}\n\n async load(): Promise<ProjectRegistry> {\n return this.yaml.load();\n }\n\n async save(registry: ProjectRegistry): Promise<void> {\n await this.yaml.save(registry);\n try {\n await this.pg.save(registry);\n } catch (err) {\n console.error(`[DualWriteRegistryStore] PG write failed (yaml is authoritative): ${err instanceof Error ? err.message : err}`);\n }\n }\n\n async upsert(slug: string, record: ProjectRecord): Promise<void> {\n await this.yaml.upsert(slug, record);\n try {\n await this.pg.upsert(slug, record);\n } catch (err) {\n console.error(`[DualWriteRegistryStore] PG upsert failed (yaml is authoritative): ${err instanceof Error ? err.message : err}`);\n }\n }\n\n async getBySlug(slug: string): Promise<ProjectRecord | undefined> {\n return this.yaml.getBySlug(slug);\n }\n\n async getByRepoPath(repoPath: string): Promise<ProjectRecord | undefined> {\n return this.yaml.getByRepoPath(repoPath);\n }\n\n async close(): Promise<void> {\n await this.pg.close();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory \u2014 returns the right store based on PJ_REGISTRY_PG env flag\n// ---------------------------------------------------------------------------\n\nexport const PJ_REGISTRY_PG_ENV = \"PJ_REGISTRY_PG\";\n\nexport function isPgRegistryEnabled(\n env: NodeJS.ProcessEnv = process.env\n): boolean {\n return env[PJ_REGISTRY_PG_ENV] === \"1\" || env[PJ_REGISTRY_PG_ENV] === \"true\";\n}\n\nlet _store: RegistryStore | undefined;\nlet _storePath: string | undefined;\n\nexport function getRegistryStore(\n path: string,\n env: NodeJS.ProcessEnv = process.env\n): RegistryStore {\n if (_store && _storePath === path) return _store;\n\n const yamlStore = new YamlRegistryStore(path);\n\n if (isPgRegistryEnabled(env)) {\n const pgStore = new PgRegistryStore(pgRegistryConfigFromEnv(env));\n _store = new DualWriteRegistryStore(yamlStore, pgStore);\n } else {\n _store = yamlStore;\n }\n _storePath = path;\n return _store;\n}\n\nexport function resetRegistryStore(): void {\n _store = undefined;\n _storePath = undefined;\n}\n", "// Ticket-provider URL derivation \u2014 the one place a board or work-item URL is\n// constructed.\n//\n// `src/project/index.ts` has long declared the rule (\"board URLs are derived\n// from provider + workspace + board_id at runtime; the manifest stores only\n// stable identity\") without anywhere actually performing it, so every caller\n// that wanted a URL either hand-assembled one or persisted a stale\n// `board_url`. This module is that missing function.\n//\n// Deliberately dependency-free \u2014 node builtins only, no imports from\n// `./index`. `src/prompt.ts` is a separate size-critical bundle that runs on\n// every shell prompt, and pulling the registry (or the parity rule set behind\n// it) into that bundle would cost more than the whole feature is worth.\n\nimport { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\n\nexport const DEFAULT_PLANE_BASE = \"https://plane.delo.sh\";\nexport const DEFAULT_PLANE_WORKSPACE = \"33god\";\n\n/** The `.project.json` `ticket_provider` block, as far as URL building cares. */\nexport interface TicketProviderFacts {\n type?: string;\n workspace?: string;\n identifier?: string;\n board_id?: string;\n}\n\nexport interface BoardUrlOptions {\n /** Explicit work item: `71`, `PJAN-71`, or `pjan-71`. Wins over `branch`. */\n ref?: string;\n /** Branch name to mine for a ticket reference when `ref` is absent. */\n branch?: string;\n env?: NodeJS.ProcessEnv;\n home?: string;\n}\n\n/**\n * Where the Hermes template keeps `[plane] base`.\n *\n * NOTE: twin of `resolveTemplateConfigPath` in\n * `src/commands/hermes/EnsureTemplateConfig.ts`. That module cannot be\n * imported here without dragging the command layer into the prompt bundle.\n * `tests/pjan-72-regressions.mjs` carries a drift tripwire on the pair.\n */\nexport function resolveTemplateConfigPath(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {\n const fromEnv = env.HERMES_TEMPLATE_CONFIG;\n if (fromEnv && fromEnv.trim()) return fromEnv.trim();\n const xdg = env.XDG_CONFIG_HOME?.trim();\n const base = xdg && xdg.length ? xdg : join(home, \".config\");\n return join(base, \"hermes-agent-template\", \"config.toml\");\n}\n\n/**\n * Read `key` from `[section]` of a small TOML file.\n *\n * Scoped to exactly what this module needs \u2014 two string scalars out of a\n * generated config. Not a TOML parser, and deliberately not pretending to be\n * one: anything it cannot confidently read comes back undefined and the caller\n * falls through to a default.\n */\nexport function readTomlScalar(text: string, section: string, key: string): string | undefined {\n let inSection = false;\n for (const raw of text.split(\"\\n\")) {\n const line = raw.trim();\n if (!line || line.startsWith(\"#\")) continue;\n if (line.startsWith(\"[\")) {\n inSection = line === `[${section}]`;\n continue;\n }\n if (!inSection) continue;\n const eq = line.indexOf(\"=\");\n if (eq === -1) continue;\n if (line.slice(0, eq).trim() !== key) continue;\n const value = line.slice(eq + 1).trim();\n const quoted = /^\"([^\"]*)\"|^'([^']*)'/.exec(value);\n if (quoted) return quoted[1] ?? quoted[2];\n const bare = (value.split(\"#\")[0] ?? \"\").trim();\n return bare || undefined;\n }\n return undefined;\n}\n\nfunction readTemplateConfig(env: NodeJS.ProcessEnv, home: string): string | undefined {\n try {\n const path = resolveTemplateConfigPath(env, home);\n return existsSync(path) ? readFileSync(path, \"utf8\") : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Plane instance base URL.\n *\n * Precedence mirrors the shell adapter at\n * `agents/hermes/pm/.scripts/providers/plane.sh:22` \u2014 env override first, then\n * the generated template config, then the fleet default \u2014 so the CLI and the\n * PM agent can never disagree about which Plane they are talking to.\n */\nexport function planeBase(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {\n const fromEnv = env.PLANE_BASE?.trim();\n if (fromEnv) return fromEnv.replace(/\\/+$/, \"\");\n const config = readTemplateConfig(env, home);\n const fromConfig = config ? readTomlScalar(config, \"plane\", \"base\")?.trim() : undefined;\n if (fromConfig) return fromConfig.replace(/\\/+$/, \"\");\n return DEFAULT_PLANE_BASE;\n}\n\n/**\n * Workspace slug for a board binding: manifest, then generated template\n * config, then the fleet default.\n *\n * Exported for `boardQuery.ts`, which needs the identical chain to build API\n * URLs. A second copy of this fallback order is exactly how the CLI and the PM\n * agent would end up querying two different workspaces.\n */\nexport function planeWorkspace(provider: TicketProviderFacts, env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string | undefined {\n const fromManifest = provider.workspace?.trim();\n if (fromManifest) return fromManifest;\n const config = readTemplateConfig(env, home);\n const fromConfig = config ? readTomlScalar(config, \"plane\", \"workspace\")?.trim() : undefined;\n return fromConfig || DEFAULT_PLANE_WORKSPACE;\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Pull a ticket reference out of a branch name.\n *\n * `fix/PJAN-67-mcp-fail-closed` \u2192 `PJAN-67`. CLAUDE.md already requires branch\n * names to carry a ticket reference, so this is the common path rather than a\n * clever edge case.\n *\n * The `\\b` before the identifier is what keeps `XPJAN-3` from reading as\n * `PJAN-3`, and requiring a literal `-` after it keeps `PJANX-3` out too.\n */\nexport function extractTicketRef(branch: string | undefined, identifier: string | undefined): string | undefined {\n if (!branch || !identifier) return undefined;\n const ident = identifier.trim();\n if (!ident) return undefined;\n const match = new RegExp(`\\\\b${escapeRegExp(ident)}-(\\\\d+)\\\\b`, \"i\").exec(branch);\n return match ? `${ident.toUpperCase()}-${match[1]}` : undefined;\n}\n\n/**\n * Normalize user input into a work-item reference.\n *\n * A bare number is completed with this project's identifier. A fully-qualified\n * reference is accepted as-is even when its prefix belongs to another\n * project \u2014 Plane's browse route is workspace-scoped, not project-scoped, so\n * `board DECK-21` resolves correctly from inside the pjangler repo.\n */\nexport function normalizeTicketRef(input: string | undefined, identifier: string | undefined): string | undefined {\n const value = input?.trim();\n if (!value) return undefined;\n if (/^\\d+$/.test(value)) {\n const ident = identifier?.trim();\n return ident ? `${ident.toUpperCase()}-${value}` : undefined;\n }\n const qualified = /^([A-Za-z][A-Za-z0-9]*)-(\\d+)$/.exec(value);\n if (!qualified) return undefined;\n return `${qualified[1]!.toUpperCase()}-${qualified[2]!}`;\n}\n\n/** Explicit ref beats branch inference beats nothing. */\nexport function resolveTicketRef(provider: TicketProviderFacts, options: BoardUrlOptions): string | undefined {\n return (\n normalizeTicketRef(options.ref, provider.identifier) ??\n extractTicketRef(options.branch, provider.identifier)\n );\n}\n\n/**\n * Board URL, or the URL of one work item on it.\n *\n * Route shapes were read off the live instance's router manifest rather than\n * its documentation:\n * `:workspaceSlug/browse/:workItem`\n * `:workspaceSlug/projects/:projectId/issues`\n *\n * Returns undefined rather than guessing when there is no board to point at.\n */\nexport function boardUrl(provider: TicketProviderFacts | undefined, options: BoardUrlOptions = {}): string | undefined {\n if (!provider) return undefined;\n const env = options.env ?? process.env;\n const home = options.home ?? homedir();\n const type = (provider.type || \"plane\").trim().toLowerCase();\n const boardId = provider.board_id?.trim();\n if (!boardId) return undefined;\n\n if (type === \"trello\") {\n // Trello addresses cards by an opaque short id, not by `<IDENT>-<n>`, so a\n // ticket reference cannot be resolved to a card without an API round trip.\n // Opening the board is the honest answer; silently ignoring the ref would\n // not be.\n return `https://trello.com/b/${boardId}`;\n }\n if (type !== \"plane\") return undefined;\n\n const workspace = planeWorkspace(provider, env, home);\n if (!workspace) return undefined;\n const base = planeBase(env, home);\n const ref = resolveTicketRef(provider, options);\n return ref\n ? `${base}/${workspace}/browse/${ref}`\n : `${base}/${workspace}/projects/${boardId}/issues`;\n}\n\n/** Nearest ancestor holding a `.project.json`, starting at `from`. */\nexport function findProjectRoot(from: string): string | undefined {\n let dir = resolve(from);\n for (;;) {\n if (existsSync(join(dir, \".project.json\"))) return dir;\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n/** The `ticket_provider` block, or undefined when absent or unreadable. */\nexport function readTicketProvider(root: string): TicketProviderFacts | undefined {\n try {\n const manifest = JSON.parse(readFileSync(join(root, \".project.json\"), \"utf8\")) as Record<string, unknown>;\n const provider = manifest.ticket_provider;\n if (!provider || typeof provider !== \"object\") return undefined;\n return provider as TicketProviderFacts;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Current branch, read straight out of `.git/HEAD`.\n *\n * No subprocess: this runs on the shell-prompt path, where spawning git would\n * cost more than everything else here combined. Handles the `.git`-as-a-file\n * form used by worktrees and submodules. A detached HEAD has no branch, so\n * there is no reference to mine and undefined is the truthful answer.\n */\nexport function currentBranch(from: string): string | undefined {\n try {\n let dir = resolve(from);\n for (;;) {\n const dotgit = join(dir, \".git\");\n if (existsSync(dotgit)) {\n let gitDir = dotgit;\n if (statSync(dotgit).isFile()) {\n const pointer = /^gitdir:\\s*(.+)$/m.exec(readFileSync(dotgit, \"utf8\"));\n if (!pointer) return undefined;\n const target = pointer[1]!.trim();\n gitDir = isAbsolute(target) ? target : resolve(dir, target);\n }\n const head = readFileSync(join(gitDir, \"HEAD\"), \"utf8\").trim();\n const ref = /^ref:\\s*refs\\/heads\\/(.+)$/.exec(head);\n return ref ? ref[1]!.trim() : undefined;\n }\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n } catch {\n return undefined;\n }\n}\n\n/**\n * Full resolution from a working directory: the URL this project's prompt\n * segment points at.\n */\nexport function resolveBoardUrl(cwd: string, ref?: string, env: NodeJS.ProcessEnv = process.env): string | undefined {\n const root = findProjectRoot(cwd);\n if (!root) return undefined;\n const provider = readTicketProvider(root);\n if (!provider) return undefined;\n return boardUrl(provider, { ref, branch: currentBranch(root), env });\n}\n", "import { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/**\n * The package version, read from package.json at runtime so the CLI and MCP\n * server always report what `mise run version:bump` actually shipped \u2014 never\n * a hardcoded literal (PJAN-2: `pj --version` lied with \"1.0.0\" forever).\n * Walks up from this module's directory so it works from src/ (dev) and from\n * the bundled dist/ (published install) alike.\n */\nexport const PJANGLER_VERSION: string = (() => {\n try {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 4; i++) {\n try {\n const raw = readFileSync(join(dir, \"package.json\"), \"utf8\");\n return JSON.parse(raw).version ?? \"0.0.0\";\n } catch {\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n }\n } catch {\n // fall through\n }\n return \"0.0.0\";\n})();\n", "// Ticket-board reads \u2014 the \"what is on this board\" half of the board surface.\n//\n// `boardUrl.ts` answers *where* a board is; this module answers *what is on\n// it*. They stay separate files on purpose: boardUrl is imported by\n// `src/prompt.ts`, which runs on every shell prompt, and none of what lives\n// here \u2014 HTTP, cursor pagination, credential resolution \u2014 belongs in that\n// bundle. Everything URL-shaped is delegated back to boardUrl rather than\n// rebuilt, so a board link printed by `pj board` and one printed by\n// `pj board status` cannot disagree.\n//\n// Every command in this module resolves its project implicitly, by walking up\n// from the working directory to the nearest `.project.json`. There is no\n// `--project` flag by design: the board binding is a property of where you\n// are standing.\n\nimport { spawnSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { basename, join } from \"node:path\";\nimport {\n boardUrl,\n findProjectRoot,\n planeBase,\n planeWorkspace,\n readTicketProvider,\n type TicketProviderFacts,\n} from \"./boardUrl\";\nimport { PJANGLER_VERSION } from \"../utils/version\";\n\n/** Providers a `.project.json` may bind a board to. */\nexport const BOARD_PROVIDERS = [\"plane\", \"trello\", \"linear\"] as const;\nexport type BoardProvider = (typeof BOARD_PROVIDERS)[number];\n\n/**\n * Plane's five state groups. Every provider normalizes onto this vocabulary,\n * so \"started\" means the same thing regardless of what the board calls its\n * columns \u2014 this board spells `started` as both \"In Progress\" and, if it ever\n * grows one, \"In Review\".\n */\nexport const BOARD_STATE_GROUPS = [\"backlog\", \"unstarted\", \"started\", \"completed\", \"cancelled\"] as const;\nexport type BoardStateGroup = (typeof BOARD_STATE_GROUPS)[number];\n\nexport interface BoardTicket {\n /** Display reference: `PJAN-86`. Falls back to the raw sequence number. */\n key: string;\n /** Provider-side id, needed by anything that wants to mutate the ticket. */\n id: string;\n title: string;\n /** The board's own column name, e.g. \"In Progress\". */\n state: string;\n /** Normalized group the column belongs to. */\n stateGroup: string;\n createdAt: string;\n updatedAt: string;\n /**\n * Newest of created/updated. \"Most recently added *or* updated\" is one\n * ordering, not two, and this is the key it sorts on.\n */\n touchedAt: string;\n url: string | undefined;\n}\n\nexport interface BoardModule {\n id: string;\n name: string;\n description: string;\n /** Provider status, e.g. backlog / planned / in-progress / completed. */\n status: string;\n totalIssues: number;\n completedIssues: number;\n startedIssues: number;\n updatedAt: string;\n url: string | undefined;\n}\n\n/** A resolved project root plus whatever board binding it carries. */\nexport interface ProjectHandle {\n root: string;\n slug: string;\n facts: TicketProviderFacts | undefined;\n}\n\n/** A project whose board binding is complete enough to query. */\nexport interface BoardContext {\n root: string;\n slug: string;\n provider: BoardProvider;\n facts: TicketProviderFacts;\n env: NodeJS.ProcessEnv;\n home: string;\n}\n\n/**\n * A failure with a message already written for a human at a terminal.\n *\n * The CLI prints `.message` verbatim and exits 1, so every throw site here is\n * responsible for saying what went wrong *and* what would fix it.\n */\nexport class BoardError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BoardError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Implicit project resolution\n// ---------------------------------------------------------------------------\n\n/**\n * The project's slug.\n *\n * Same rule as the shell prompt (`src/prompt.ts`): the manifest's\n * `project_slug` when it has one, else the directory name. A manifest too\n * broken to parse still sits in a directory with a name, and that name is a\n * truthful answer.\n */\nexport function readProjectSlug(root: string): string {\n try {\n const manifest = JSON.parse(readFileSync(join(root, \".project.json\"), \"utf8\")) as Record<string, unknown>;\n const slug = manifest.project_slug;\n if (typeof slug === \"string\" && slug.trim()) return slug.trim();\n } catch {\n // fall through to the directory name\n }\n return basename(root);\n}\n\n/** Nearest enclosing project, or a message explaining there isn't one. */\nexport function resolveProject(cwd: string): ProjectHandle {\n const root = findProjectRoot(cwd);\n if (!root) {\n throw new BoardError(\n `not inside a pjangler project: no .project.json in ${cwd} or any parent directory`,\n );\n }\n return { root, slug: readProjectSlug(root), facts: readTicketProvider(root) };\n}\n\n/** The bound provider, or a message explaining what the manifest is missing. */\nexport function resolveProvider(handle: ProjectHandle): BoardProvider {\n const type = handle.facts?.type?.trim().toLowerCase();\n if (!type) {\n throw new BoardError(\n `no ticket board bound for ${handle.slug}: ${join(handle.root, \".project.json\")} has no ticket_provider.type`,\n );\n }\n if (!(BOARD_PROVIDERS as readonly string[]).includes(type)) {\n throw new BoardError(\n `unsupported ticket_provider.type \"${type}\" in ${join(handle.root, \".project.json\")} \u2014 expected one of ${BOARD_PROVIDERS.join(\", \")}`,\n );\n }\n return type as BoardProvider;\n}\n\n/** Full resolution: project root, slug, provider, and the binding facts. */\nexport function resolveBoardContext(\n cwd: string,\n env: NodeJS.ProcessEnv = process.env,\n home: string = homedir(),\n): BoardContext {\n const handle = resolveProject(cwd);\n const provider = resolveProvider(handle);\n return { root: handle.root, slug: handle.slug, provider, facts: handle.facts ?? {}, env, home };\n}\n\n// ---------------------------------------------------------------------------\n// Plane credentials\n//\n// The chain mirrors `agents/hermes/pm/.scripts/providers/plane.sh` exactly. If\n// the CLI and the PM agent resolved different keys they would silently read\n// different boards, which is worse than either of them simply failing.\n// ---------------------------------------------------------------------------\n\n/** `33god` \u2192 `PLANE_33GOD_API_KEY`; an empty workspace \u2192 `PLANE_DEFAULT_API_KEY`. */\nexport function workspaceEnvKey(workspace: string | undefined): string {\n const key = (workspace ?? \"default\").toUpperCase().replace(/[^A-Z0-9]/g, \"_\");\n return `PLANE_${key || \"DEFAULT\"}_API_KEY`;\n}\n\n/**\n * Read one exact assignment out of a dotenv file, as inert data.\n *\n * Never sourced: the shared fleet file may carry command substitutions or\n * credential helpers that a read has no business executing.\n */\nexport function dotenvValue(path: string, key: string): string | undefined {\n let text: string;\n try {\n text = readFileSync(path, \"utf8\");\n } catch {\n return undefined;\n }\n for (const raw of text.split(\"\\n\")) {\n let line = raw.trim();\n if (!line || line.startsWith(\"#\")) continue;\n if (line.startsWith(\"export \")) line = line.slice(7).trimStart();\n const eq = line.indexOf(\"=\");\n if (eq === -1) continue;\n if (line.slice(0, eq).trim() !== key) continue;\n let value = line.slice(eq + 1).trim();\n const first = value[0];\n if (value.length >= 2 && first && (first === '\"' || first === \"'\") && value.endsWith(first)) {\n value = value.slice(1, -1);\n }\n return value || undefined;\n }\n return undefined;\n}\n\n/**\n * Resolve an `op://` reference to its value, leaving anything else alone.\n *\n * Deferred to the last possible moment and never written anywhere: the\n * resolved secret exists only in this process, for the length of one request.\n */\nexport function resolveSecretValue(value: string): string {\n if (!value.startsWith(\"op://\")) return value;\n const result = spawnSync(\"op\", [\"read\", value], { encoding: \"utf8\" });\n if (result.error || result.status !== 0) {\n const detail = (result.stderr || result.error?.message || \"op read failed\").trim();\n throw new BoardError(`could not resolve the credential ${value} from 1Password: ${detail}`);\n }\n const resolved = result.stdout.trim();\n if (!resolved) throw new BoardError(`1Password returned an empty value for ${value}`);\n return resolved;\n}\n\n/** Environment variables consulted for a workspace, in precedence order. */\nexport function planeApiKeyNames(workspace: string | undefined): string[] {\n return [\"PLANE_API_KEY\", workspaceEnvKey(workspace)];\n}\n\n/**\n * The API key for a workspace: environment first, then the shared fleet\n * dotenv, with `op://` references resolved at the end.\n */\nexport function resolvePlaneApiKey(\n workspace: string | undefined,\n env: NodeJS.ProcessEnv = process.env,\n home: string = homedir(),\n): string | undefined {\n const fleetEnv = env.HERMES_FLEET_ENV?.trim() || join(home, \".hermes\", \"fleet.env\");\n const scoped = workspaceEnvKey(workspace);\n const candidates = [\n env.PLANE_API_KEY,\n env[scoped],\n dotenvValue(fleetEnv, scoped),\n dotenvValue(fleetEnv, \"PLANE_API_KEY\"),\n ];\n for (const candidate of candidates) {\n const value = candidate?.trim();\n if (value) return resolveSecretValue(value);\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Plane HTTP\n// ---------------------------------------------------------------------------\n\ninterface PlaneClient {\n base: string;\n workspace: string;\n board: string;\n apiKey: string;\n timeoutMs: number;\n pageSize: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 15_000;\nconst DEFAULT_PAGE_SIZE = 100;\n\n/**\n * Runaway guard, not a result cap: at the default page size this is 20,000\n * work items. Exhausting it means something is wrong with the cursor, so the\n * loop raises rather than returning a silently short list.\n */\nconst MAX_PAGES = 200;\n\nfunction positiveInt(raw: string | undefined, fallback: number): number {\n const value = Number(raw);\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;\n}\n\nfunction planeClient(ctx: BoardContext): PlaneClient {\n const board = ctx.facts.board_id?.trim();\n if (!board) {\n throw new BoardError(\n `no board linked for ${ctx.slug}: ${join(ctx.root, \".project.json\")} has an empty ticket_provider.board_id`,\n );\n }\n const workspace = planeWorkspace(ctx.facts, ctx.env, ctx.home);\n if (!workspace) {\n throw new BoardError(`no Plane workspace resolved for ${ctx.slug} (ticket_provider.workspace is empty)`);\n }\n const apiKey = resolvePlaneApiKey(workspace, ctx.env, ctx.home);\n if (!apiKey) {\n throw new BoardError(\n `no Plane API key for workspace \"${workspace}\": set ${planeApiKeyNames(workspace).join(\" or \")}, ` +\n `or add one to ${ctx.env.HERMES_FLEET_ENV?.trim() || join(ctx.home, \".hermes\", \"fleet.env\")}`,\n );\n }\n return {\n base: planeBase(ctx.env, ctx.home),\n workspace,\n board,\n apiKey,\n timeoutMs: positiveInt(ctx.env.PJANGLER_BOARD_TIMEOUT_MS, DEFAULT_TIMEOUT_MS),\n pageSize: positiveInt(ctx.env.PJANGLER_BOARD_PAGE_SIZE, DEFAULT_PAGE_SIZE),\n };\n}\n\nasync function planeGet(\n client: PlaneClient,\n path: string,\n params: Record<string, string | number> = {},\n): Promise<unknown> {\n const url = new URL(\n `${client.base}/api/v1/workspaces/${encodeURIComponent(client.workspace)}` +\n `/projects/${encodeURIComponent(client.board)}/${path}`,\n );\n for (const [key, value] of Object.entries(params)) url.searchParams.set(key, String(value));\n\n let response: Response;\n try {\n response = await fetch(url, {\n headers: { \"X-API-Key\": client.apiKey, \"User-Agent\": `pjangler/${PJANGLER_VERSION}` },\n signal: AbortSignal.timeout(client.timeoutMs),\n });\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new BoardError(`could not reach Plane at ${client.base} (${path}): ${detail}`);\n }\n if (!response.ok) {\n const credentials = response.status === 401 || response.status === 403;\n throw new BoardError(\n `Plane returned ${response.status} for ${path}` +\n (credentials\n ? ` \u2014 the API key was rejected; check ${planeApiKeyNames(client.workspace).join(\" / \")}`\n : response.status === 404\n ? ` \u2014 no such board in workspace \"${client.workspace}\"; check ticket_provider.board_id`\n : \"\"),\n );\n }\n try {\n return await response.json();\n } catch {\n throw new BoardError(`Plane returned a non-JSON body for ${path}`);\n }\n}\n\ninterface PlaneCursorPage {\n results?: unknown;\n next_cursor?: string;\n next_page_results?: boolean;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Every row on a paginated route.\n *\n * Plane v1 answers some routes with a bare array and others with a cursor\n * envelope, so both shapes are accepted. Following the cursor to exhaustion is\n * not optional here: `states`/`state_group` query filters are accepted and\n * then *ignored* by this API, so `board status` has to select client-side over\n * the complete set \u2014 a single page would quietly drop started work.\n */\nasync function planeGetAll(\n client: PlaneClient,\n path: string,\n params: Record<string, string | number> = {},\n): Promise<Record<string, unknown>[]> {\n const rows: Record<string, unknown>[] = [];\n let cursor: string | undefined;\n\n for (let page = 0; page < MAX_PAGES; page++) {\n const query = { per_page: client.pageSize, ...params, ...(cursor ? { cursor } : {}) };\n const body = await planeGet(client, path, query);\n\n if (Array.isArray(body)) {\n rows.push(...body.filter(isRecord));\n return rows;\n }\n if (!isRecord(body)) return rows;\n\n const envelope = body as PlaneCursorPage;\n if (Array.isArray(envelope.results)) rows.push(...envelope.results.filter(isRecord));\n if (!envelope.next_page_results || !envelope.next_cursor) return rows;\n cursor = envelope.next_cursor;\n }\n\n throw new BoardError(\n `Plane pagination did not terminate after ${MAX_PAGES} pages of ${path} \u2014 refusing to report a truncated list`,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Normalization\n// ---------------------------------------------------------------------------\n\nfunction str(value: unknown): string {\n return typeof value === \"string\" ? value : value == null ? \"\" : String(value);\n}\n\nfunction num(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\n/** Plane returns `issue.state` as a bare UUID, so the states map is required. */\nasync function planeStates(client: PlaneClient): Promise<Map<string, { name: string; group: string }>> {\n const rows = await planeGetAll(client, \"states/\");\n const map = new Map<string, { name: string; group: string }>();\n for (const row of rows) {\n const id = str(row.id);\n if (id) map.set(id, { name: str(row.name), group: str(row.group) });\n }\n return map;\n}\n\n/** Later of the two stamps \u2014 the single key \"added or updated\" orders on. */\nfunction touched(createdAt: string, updatedAt: string): string {\n if (!createdAt) return updatedAt;\n if (!updatedAt) return createdAt;\n return Date.parse(updatedAt) >= Date.parse(createdAt) ? updatedAt : createdAt;\n}\n\nfunction toTicket(\n row: Record<string, unknown>,\n states: Map<string, { name: string; group: string }>,\n ctx: BoardContext,\n): BoardTicket {\n const identifier = ctx.facts.identifier?.trim().toUpperCase();\n const sequence = str(row.sequence_id);\n const key = identifier && sequence ? `${identifier}-${sequence}` : sequence || str(row.id);\n const state = states.get(str(row.state));\n const createdAt = str(row.created_at);\n const updatedAt = str(row.updated_at);\n return {\n key,\n id: str(row.id),\n title: str(row.name),\n state: state?.name ?? \"\",\n stateGroup: state?.group ?? \"\",\n createdAt,\n updatedAt,\n touchedAt: touched(createdAt, updatedAt),\n // Reuse the one URL derivation rather than assembling a second one.\n url: boardUrl(ctx.facts, { ref: key, env: ctx.env, home: ctx.home }),\n };\n}\n\nfunction byTouchedDesc(a: BoardTicket, b: BoardTicket): number {\n return Date.parse(b.touchedAt) - Date.parse(a.touchedAt);\n}\n\n// ---------------------------------------------------------------------------\n// Queries\n// ---------------------------------------------------------------------------\n\nfunction requirePlane(ctx: BoardContext, verb: string): PlaneClient {\n if (ctx.provider !== \"plane\") {\n throw new BoardError(\n `board ${verb} is not wired for ${ctx.provider} yet \u2014 only plane boards can be read. ` +\n `\"pj board provider\" and \"pj board slug\" work for every provider.`,\n );\n }\n return planeClient(ctx);\n}\n\n/**\n * Work items in a `started` state group, most recently added or updated first.\n *\n * The group, not the column name, is the selector: a board that renames \"In\n * Progress\" or adds \"In Review\" keeps working without a config change.\n */\nexport async function fetchStartedTickets(ctx: BoardContext, limit?: number): Promise<BoardTicket[]> {\n const client = requirePlane(ctx, \"status\");\n const [states, rows] = await Promise.all([\n planeStates(client),\n planeGetAll(client, \"issues/\", { order_by: \"-updated_at\" }),\n ]);\n const started = rows\n .map((row) => toTicket(row, states, ctx))\n .filter((ticket) => ticket.stateGroup === \"started\")\n .sort(byTouchedDesc);\n return typeof limit === \"number\" && limit > 0 ? started.slice(0, limit) : started;\n}\n\n/**\n * The N most recently added or updated work items in any state.\n *\n * Ordering is asked of the server and then re-applied locally, because the\n * server orders by `updated_at` alone while this command promises \"added *or*\n * updated\". They agree on every row Plane has ever returned here; the local\n * sort is what makes the promise true rather than merely likely.\n */\nexport async function fetchRecentTickets(ctx: BoardContext, limit: number): Promise<BoardTicket[]> {\n const client = requirePlane(ctx, \"recent\");\n const [states, rows] = await Promise.all([\n planeStates(client),\n planeGetAll(client, \"issues/\", { order_by: \"-updated_at\" }),\n ]);\n return rows\n .map((row) => toTicket(row, states, ctx))\n .sort(byTouchedDesc)\n .slice(0, Math.max(0, limit));\n}\n\n/** The board's modules, most recently updated first. */\nexport async function fetchModules(ctx: BoardContext): Promise<BoardModule[]> {\n const client = requirePlane(ctx, \"modules\");\n const rows = await planeGetAll(client, \"modules/\");\n const base = planeBase(ctx.env, ctx.home);\n return rows\n .map((row) => ({\n id: str(row.id),\n name: str(row.name),\n description: str(row.description),\n status: str(row.status),\n totalIssues: num(row.total_issues),\n completedIssues: num(row.completed_issues),\n startedIssues: num(row.started_issues),\n updatedAt: touched(str(row.created_at), str(row.updated_at)),\n url: str(row.id)\n ? `${base}/${client.workspace}/projects/${client.board}/modules/${str(row.id)}`\n : undefined,\n }))\n .sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { isIP } from \"node:net\";\nimport { chmodSync, closeSync, copyFileSync, existsSync, fchmodSync, fsyncSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep, win32 } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport YAML from \"yaml\";\nimport { DEFAULT_NOTEBOOK_LIMITS, notebookCredentialMaterialPath, type NotebookGlobalConfigV1, type NotebookLimitsV1, type ProjectNotebookBindingV1, type ProjectNotebookConfigV1 } from \"../notebook/types\";\nimport { bold, cyan, dim, green, yellow, glyph } from \"../utils/style\";\nimport { changedTreePaths, snapshotTree } from \"../utils/tree-diff\";\nimport {\n verifyTrustedCopierIdentity,\n type TrustedCopierIdentity,\n} from \"../lifecycle/preflight\";\nimport {\n isPgRegistryEnabled,\n PgRegistryStore,\n pgRegistryConfigFromEnv,\n type RegistryStore,\n type DualWriteRegistryStore,\n} from \"./RegistryStore\";\nimport { dotenvValue, workspaceEnvKey } from \"./boardQuery\";\n\nexport { isPgRegistryEnabled, pgRegistryConfigFromEnv, PgRegistryStore, type RegistryStore, type DualWriteRegistryStore };\n\nexport const PROJECT_REGISTRY_ENV = \"PJ_PROJECT_REGISTRY\";\nexport const PROJECT_SOURCE_SKILL_ROOTS_ENV = \"PJ_SOURCE_SKILL_ROOTS\";\n/** Override the directory holding the `tp` provider adapters (`<provider>.sh`). */\nexport const TICKET_PROVIDER_ADAPTERS_ENV = \"PJ_TICKET_PROVIDER_ADAPTERS\";\nexport const PROJECT_REGISTRY_SCHEMA_VERSION = 1;\n/**\n * Lifecycle status stamped on a NEWLY created project record (PJAN-26).\n * The project lifecycle is planned -> active -> archived; bootstrapping a\n * project means work has started, so new records begin \"active\".\n * Applies to new records only \u2014 existing records keep their recorded status.\n */\nexport const DEFAULT_NEW_PROJECT_STATUS = \"active\";\nexport const BOARD_URL_DEPRECATION_WARNING = \"boardUrl is deprecated and ignored; board URLs are derived at runtime and are never persisted.\";\n\nexport interface SourceArtifact {\n kind: \"skill\" | \"template\" | \"package\" | string;\n path: string;\n package_name?: string;\n}\n\nexport type SupportedTicketProvider = \"plane\" | \"trello\";\n\n/**\n * Where a board identifier came from.\n *\n * \"provider\" \u2014 read back from the ticket provider's own API. The only source\n * a linked board may be backed by.\n * \"proposed\" \u2014 pjangler minted a placeholder from the project name. Nothing has\n * confirmed it exists, so it may not be treated as a board key.\n */\nexport const PROJECT_IDENTIFIER_SOURCES = [\"provider\", \"proposed\"] as const;\nexport type ProjectIdentifierSource = (typeof PROJECT_IDENTIFIER_SOURCES)[number];\n\n/**\n * Providers that ASSIGN the board identifier themselves.\n *\n * Plane mints a key for every board and hands it back, so a Plane record whose\n * key is a local guess is a routing lie. Trello has no such concept at all: the\n * short prefix on a Trello record is something we chose and Trello merely\n * echoes, which is why a Trello identifier can never be `provider`-sourced \u2014\n * and why \"is this board real?\" has to be a separate question from \"did the\n * provider name it?\".\n */\nexport const IDENTIFIER_ASSIGNING_PROVIDERS = [\"plane\", \"linear\"] as const;\n\nexport function providerAssignsIdentifiers(type: string | undefined): boolean {\n return (IDENTIFIER_ASSIGNING_PROVIDERS as readonly string[]).includes((type ?? \"\").trim());\n}\n\n/** Lifecycle states a board binding may occupy. */\nexport const TICKET_PROVIDER_STATES = [\"planned\", \"linked\", \"skipped\"] as const;\n\n/** The command that reads identifiers back from the provider and repairs drift. */\nexport const IDENTIFIER_REPAIR_COMMAND = \"pj project identity --all --apply\";\n\nexport interface ProjectTicketProvider {\n type: SupportedTicketProvider | string;\n workspace?: string;\n identifier?: string;\n /** Provenance of `identifier`. Absent on legacy records; treated as \"proposed\". */\n identifier_source?: ProjectIdentifierSource | string;\n /**\n * ISO-8601 instant this identity was ESTABLISHED by a provider read.\n *\n * Not a poll timestamp: re-confirming the same value leaves it alone, so a\n * reconciliation run that changes nothing writes nothing.\n */\n identifier_fetched_at?: string;\n board_id?: string;\n /**\n * ISO-8601 instant the provider confirmed `board_id` names a real board.\n *\n * This is BOARD-binding provenance, and it is a different question from\n * `identifier_source`. Plane answers both at once \u2014 listing a board yields\n * its key \u2014 but Trello can only ever answer the first, so conflating them is\n * what let a Trello record claim Trello had assigned a key it never saw.\n */\n board_confirmed_at?: string;\n /** Legacy input only. New manifests derive board URLs from provider/workspace/board_id. */\n board_url?: string;\n state?: \"planned\" | \"linked\" | \"skipped\" | string;\n}\n\nexport interface ProjectAgentRecord {\n role: string;\n provisioning_state: \"planned\" | \"provisioned\" | \"skipped\" | string;\n role_dir?: string;\n}\n\nexport interface ProjectAutomation {\n reconcile?: {\n enabled: boolean;\n grace_hours: number;\n auto_review: boolean;\n };\n}\n\nexport interface ProjectRecord {\n [key: string]: unknown;\n name: string;\n slug: string;\n repo_path: string;\n description: string;\n status: \"planned\" | \"active\" | \"archived\" | string;\n source_artifacts: SourceArtifact[];\n template: {\n commonproject: {\n enabled: boolean;\n primary_language: string;\n };\n };\n ticket_provider: ProjectTicketProvider;\n agents: Record<string, ProjectAgentRecord>;\n automation?: ProjectAutomation;\n /** Authoritative Registry binding; policy overrides live in .project.json. */\n notebook?: ProjectNotebookBindingV1;\n created_at: string;\n updated_at: string;\n}\n\nexport interface ProjectRegistry {\n [key: string]: unknown;\n schema_version: number;\n notebook?: NotebookGlobalConfigV1;\n projects: Record<string, ProjectRecord>;\n}\n\nexport interface ProjectManifest {\n [key: string]: unknown;\n project_name: string;\n project_description: string;\n project_slug: string;\n repo_path: string;\n ticket_provider: {\n type: string;\n workspace: string;\n identifier: string;\n identifier_source?: string;\n identifier_fetched_at?: string;\n board_id: string;\n /** Stamped by the provider adapter the moment the provider handed the board back. */\n board_confirmed_at?: string;\n state?: string;\n };\n agents: Record<string, { role: string; role_dir?: string; provisioning_state?: string }>;\n automation?: ProjectAutomation;\n /** Read-only binding projection plus repository policy overrides. */\n notebook?: ProjectNotebookConfigV1;\n}\n\nexport interface ProjectInitInput {\n name: string;\n description?: string;\n targetDir?: string;\n sourceSkill?: string;\n primaryLanguage?: string;\n provisionAgent?: boolean;\n agentRole?: string;\n apply?: boolean;\n live?: boolean;\n /** Deprecated no-op retained for API compatibility; runtime is always role-local and ignored. */\n provisionRuntimeRepo?: boolean;\n /** Explicit external-effect grants. MCP callers pass these as false unless positively opted in. */\n provisionTicketBoard?: boolean;\n enableSystemd?: boolean;\n /** Subtractive ticket-provider gate; always dominates live/positive consent. */\n skipPlane?: boolean;\n registryPath?: string;\n projectSlug?: string;\n projectIdentifier?: string;\n packageName?: string;\n ticketProvider?: SupportedTicketProvider | string;\n planeWorkspace?: string;\n planeProjectId?: string;\n /** Provider-agnostic board binding (preferred over the plane* aliases). */\n boardId?: string;\n /** Deprecated. Board URLs are derived from provider/workspace/board_id and are not persisted. */\n boardUrl?: string;\n boardWorkspace?: string;\n pjanglerRoot?: string;\n cwd?: string;\n scaffold?: boolean;\n agentHooksLayer?: boolean;\n force?: boolean;\n overwrite?: boolean;\n now?: Date;\n}\n\nexport type ProjectInitAction =\n | {\n kind: \"registry.upsert\";\n registryPath: string;\n slug: string;\n project: ProjectRecord;\n }\n | {\n kind: \"copier.copy.commonproject\";\n cwd: string;\n command: string[];\n targetDir: string;\n data: Record<string, string>;\n overwrite: boolean;\n }\n | {\n kind: \"project.write-manifest\";\n path: string;\n manifest: ProjectManifest;\n }\n | {\n kind: \"ticket-provider.create-or-link\";\n enabled: boolean;\n live: boolean;\n provider: string;\n workspace: string;\n identifier: string;\n /** Repo the board is bound to; also where a repo-local `.env` credential is looked up. */\n repoPath: string;\n /** Board display name handed to the adapter's `create_board`. */\n boardName: string;\n /** Board description handed to the adapter's `create_board`. */\n description: string;\n /** Empty until the board is created or an explicit `--board-id` was supplied. */\n boardId: string;\n state: string;\n reason?: string;\n }\n | {\n kind: \"hermes.provision-agent\";\n enabled: boolean;\n local: boolean;\n targetDir: string;\n targetRepo: string;\n role: string;\n context: {\n skipPlane: boolean;\n skipBloodbank: boolean;\n skipSystemd: boolean;\n };\n };\n\nexport interface ProjectInitPlan {\n ok: true;\n apply: boolean;\n dryRun: boolean;\n live: boolean;\n registryPath: string;\n project: ProjectRecord;\n manifest: ProjectManifest;\n actions: ProjectInitAction[];\n warnings?: string[];\n}\n\nexport interface ProjectInitExecutionResult {\n ok: boolean;\n plan: ProjectInitPlan;\n logs: string[];\n errors: string[];\n changedFiles: string[];\n}\n\nexport interface ProjectInitExecutionOptions {\n /** Required by MCP create paths; interactive CLI callers may omit it. */\n trustedCopier?: TrustedCopierIdentity;\n requireTrustedCopier?: boolean;\n}\n\nexport interface ProjectDoctorResult {\n ok: boolean;\n registryPath: string;\n checkedProjects: string[];\n issues: Array<{ level: \"error\" | \"warn\"; slug?: string; message: string }>;\n}\n\nfunction synchronizeCopierIdentity(manifestPath: string, manifest: ProjectManifest): string[] {\n const answersPath = join(dirname(manifestPath), \".copier-answers.yml\");\n if (!existsSync(answersPath)) return [];\n const current = readFileSync(answersPath, \"utf8\");\n const document = YAML.parseDocument(current);\n if (document.errors.length) return [];\n const name = String(document.get(\"project_name\") ?? \"\");\n const description = String(document.get(\"project_description\") ?? \"\");\n if (name === manifest.project_name && description === manifest.project_description) return [];\n document.set(\"project_name\", manifest.project_name);\n document.set(\"project_description\", manifest.project_description);\n const next = String(document);\n if (next === current) return [];\n writeFileSync(answersPath, next, \"utf8\");\n return [answersPath];\n}\n\nconst DEFAULT_SOURCE_SKILL_ROOTS = [\n \"/home/delorenj/code/skillex/all-skills\",\n join(homedir(), \".agents\", \"skills\"),\n join(homedir(), \".codex\", \"skills\"),\n];\n\nexport function projectRegistryPath(env: NodeJS.ProcessEnv = process.env): string {\n return expandHome(env[PROJECT_REGISTRY_ENV] || join(homedir(), \".config\", \"pjangler\", \"projects.yaml\"));\n}\n\n/**\n * Create a string-keyed dictionary with no inherited keys or magic\n * `__proto__` setter. Registry slugs and agent identifiers are caller- or\n * file-controlled, so plain `{}` objects are not safe lookup/storage maps.\n */\nexport function createSafeRecord<T>(\n entries: Iterable<readonly [string, T]> = [],\n): Record<string, T> {\n const record = Object.create(null) as Record<string, T>;\n for (const [key, value] of entries) record[key] = value;\n return record;\n}\n\n/** Read a dictionary entry only when the key is an own data property. */\nexport function getOwnRecordValue<T>(record: Readonly<Record<string, T>>, key: string): T | undefined {\n return Object.hasOwn(record, key) ? record[key] : undefined;\n}\n\nexport function emptyProjectRegistry(): ProjectRegistry {\n return { schema_version: PROJECT_REGISTRY_SCHEMA_VERSION, projects: createSafeRecord() };\n}\n\nexport function loadProjectRegistry(path = projectRegistryPath()): ProjectRegistry {\n if (!existsSync(path)) return emptyProjectRegistry();\n const raw = YAML.parse(readFileSync(path, \"utf8\")) as unknown;\n if (raw == null) return emptyProjectRegistry();\n if (!isRecord(raw)) throw new Error(`Project registry must be a mapping: ${path}`);\n const registry = raw as Partial<ProjectRegistry>;\n const projects = createSafeRecord<ProjectRecord>();\n if (isRecord(registry.projects)) {\n for (const [slug, rawProject] of Object.entries(registry.projects)) {\n if (!isRecord(rawProject)) {\n projects[slug] = rawProject as ProjectRecord;\n continue;\n }\n projects[slug] = {\n ...rawProject,\n agents: isRecord(rawProject.agents)\n ? createSafeRecord(Object.entries(rawProject.agents) as Array<[string, ProjectAgentRecord]>)\n : rawProject.agents,\n } as ProjectRecord;\n }\n }\n const normalized: ProjectRegistry = {\n ...registry,\n schema_version: Number(registry.schema_version ?? PROJECT_REGISTRY_SCHEMA_VERSION),\n projects,\n };\n validateProjectRegistry(normalized);\n return normalized;\n}\n\nconst PROJECT_REGISTRY_OWNED_KEYS = [\n \"name\", \"slug\", \"repo_path\", \"description\", \"status\", \"source_artifacts\", \"template\",\n \"ticket_provider\", \"agents\", \"automation\", \"notebook\", \"created_at\", \"updated_at\",\n] as const;\nconst PROJECT_NOTEBOOK_OWNED_KEYS = [\"state\", \"notebook_id\", \"notebook_name\", \"overview_note_id\", \"blocked_reason\"] as const;\nconst TICKET_PROVIDER_OWNED_KEYS = [\"type\", \"workspace\", \"identifier\", \"identifier_source\", \"identifier_fetched_at\", \"board_id\", \"board_confirmed_at\", \"board_url\", \"state\"] as const;\nconst GLOBAL_NOTEBOOK_OWNED_KEYS = [\"base_url\", \"auth\", \"defaults\", \"limits\", \"summarizer\"] as const;\nconst GLOBAL_NOTEBOOK_AUTH_OWNED_KEYS = [\"mode\", \"env_var\"] as const;\nconst GLOBAL_NOTEBOOK_DEFAULTS_OWNED_KEYS = [\"enabled\", \"session_start_enabled\", \"session_capture_enabled\", \"overview_max_chars\", \"documentation_globs\", \"overview_references\", \"excluded_globs\"] as const;\nconst GLOBAL_NOTEBOOK_LIMITS_OWNED_KEYS = Object.keys(DEFAULT_NOTEBOOK_LIMITS);\nconst GLOBAL_NOTEBOOK_SUMMARIZER_OWNED_KEYS = [\"executable\", \"args\"] as const;\n\ntype RegistryYamlDocument = ReturnType<typeof YAML.parseDocument>;\ntype YamlPath = Array<string | number>;\n\nfunction yamlPlain(document: RegistryYamlDocument, path: YamlPath): unknown {\n let value = document.toJS() as unknown;\n for (const key of path) {\n if (typeof key === \"number\" && Array.isArray(value)) value = value[key];\n else if (typeof key === \"string\" && isRecord(value)) value = value[key];\n else return undefined;\n }\n return value;\n}\n\nfunction sameYamlValue(document: RegistryYamlDocument, path: YamlPath, desired: unknown): boolean {\n try { return JSON.stringify(yamlPlain(document, path)) === JSON.stringify(desired); }\n catch { return false; }\n}\n\nfunction setYamlLeaf(document: RegistryYamlDocument, path: YamlPath, desired: unknown): void {\n if (sameYamlValue(document, path, desired)) return;\n const current = document.getIn(path, true) as unknown;\n if (YAML.isScalar(current) && (desired === null || typeof desired !== \"object\")) {\n current.value = desired as never;\n return;\n }\n document.setIn(path, desired);\n}\n\n/** Merge desired values into existing CST nodes so comments/style on unchanged\n * values and unknown extension keys survive. Only explicitly owned keys may be\n * deleted when absent from the authoritative in-memory value. */\nfunction mergeYamlMapping(\n document: RegistryYamlDocument,\n path: YamlPath,\n desired: Record<string, unknown>,\n ownedKeys: readonly string[] = [],\n): void {\n if (sameYamlValue(document, path, desired)) return;\n const current = document.getIn(path, true) as unknown;\n if (!YAML.isMap(current)) {\n document.setIn(path, desired);\n return;\n }\n for (const key of ownedKeys) if (!Object.hasOwn(desired, key)) document.deleteIn([...path, key]);\n for (const [key, value] of Object.entries(desired)) {\n const child = [...path, key];\n if (isRecord(value)) {\n const childOwned = key === \"notebook\" ? PROJECT_NOTEBOOK_OWNED_KEYS\n : key === \"ticket_provider\" ? TICKET_PROVIDER_OWNED_KEYS\n : path.length === 1 && path[0] === \"notebook\" && key === \"auth\" ? GLOBAL_NOTEBOOK_AUTH_OWNED_KEYS\n : path.length === 1 && path[0] === \"notebook\" && key === \"defaults\" ? GLOBAL_NOTEBOOK_DEFAULTS_OWNED_KEYS\n : path.length === 1 && path[0] === \"notebook\" && key === \"limits\" ? GLOBAL_NOTEBOOK_LIMITS_OWNED_KEYS\n : path.length === 1 && path[0] === \"notebook\" && key === \"summarizer\" ? GLOBAL_NOTEBOOK_SUMMARIZER_OWNED_KEYS\n : [];\n mergeYamlMapping(document, child, value, childOwned);\n } else setYamlLeaf(document, child, value);\n }\n}\n\nfunction fsyncDirectory(path: string): void {\n try {\n const fd = openSync(path, \"r\");\n try { fsyncSync(fd); } finally { closeSync(fd); }\n } catch { /* best effort on platforms that cannot fsync directories */ }\n}\n\nexport function saveProjectRegistry(registry: ProjectRegistry, path = projectRegistryPath()): void {\n validateProjectRegistry(registry);\n mkdirSync(dirname(path), { recursive: true });\n let text: string;\n let mode = 0o644;\n if (existsSync(path)) {\n const stat = lstatSync(path);\n if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Project registry must be a regular file: ${path}`);\n mode = stat.mode & 0o777;\n const current = readFileSync(path, \"utf8\");\n const document = YAML.parseDocument(current);\n if (document.errors.length) throw new Error(`Project registry YAML is invalid: ${path}`);\n setYamlLeaf(document, [\"schema_version\"], registry.schema_version);\n if (registry.notebook !== undefined) mergeYamlMapping(document, [\"notebook\"], registry.notebook, GLOBAL_NOTEBOOK_OWNED_KEYS);\n else document.delete(\"notebook\");\n if (!document.has(\"projects\")) document.set(\"projects\", {});\n const parsed = document.toJS() as unknown;\n const existingProjects = isRecord(parsed) && isRecord(parsed.projects) ? parsed.projects : {};\n for (const slug of Object.keys(existingProjects)) if (!Object.hasOwn(registry.projects, slug)) document.deleteIn([\"projects\", slug]);\n for (const [slug, project] of Object.entries(registry.projects)) {\n mergeYamlMapping(document, [\"projects\", slug], project, PROJECT_REGISTRY_OWNED_KEYS);\n }\n text = String(document);\n if (text === current) return;\n } else {\n text = YAML.stringify(registry, { lineWidth: 0 });\n }\n const temp = `${path}.${process.pid}.${Date.now()}.tmp`;\n let fd: number | undefined;\n try {\n fd = openSync(temp, \"wx\", mode);\n writeFileSync(fd, text, \"utf8\");\n fchmodSync(fd, mode);\n fsyncSync(fd);\n closeSync(fd);\n fd = undefined;\n renameSync(temp, path);\n chmodSync(path, mode);\n fsyncDirectory(dirname(path));\n } catch (error) {\n if (fd !== undefined) try { closeSync(fd); } catch { /* retain original error */ }\n try { unlinkSync(temp); } catch { /* retain original error */ }\n throw error;\n }\n}\n\nexport function validateProjectRegistry(registry: ProjectRegistry): void {\n if (registry.schema_version !== PROJECT_REGISTRY_SCHEMA_VERSION) {\n throw new Error(`Unsupported project registry schema_version: ${registry.schema_version}`);\n }\n validateGlobalNotebookConfig(registry.notebook);\n if (!isRecord(registry.projects)) throw new Error(\"Project registry projects must be a mapping\");\n const slugs = new Set<string>();\n const repoPaths = new Map<string, string>();\n const identifiers = new Map<string, string>();\n const boardIds = new Map<string, string>();\n const notebookIds = new Map<string, string>();\n const overviewNoteIds = new Map<string, string>();\n for (const [slug, project] of Object.entries(registry.projects)) {\n validateProjectRecord(project, slug);\n if (slugs.has(project.slug)) throw new Error(`Duplicate project slug: ${project.slug}`);\n slugs.add(project.slug);\n const repoKey = resolve(project.repo_path);\n const existingRepoSlug = repoPaths.get(repoKey);\n if (existingRepoSlug && existingRepoSlug !== slug) {\n throw new Error(`Duplicate project repo_path: ${project.repo_path} used by ${existingRepoSlug} and ${slug}`);\n }\n repoPaths.set(repoKey, slug);\n const scope = ticketProviderScope(project.ticket_provider);\n // R4: two projects cannot own the same board. An EMPTY board_id is not a\n // board, it is the absence of one, and 22 records legitimately share it.\n const boardId = project.ticket_provider.board_id?.trim();\n if (boardId) {\n const boardKey = `${scope}\\u0000${boardId}`;\n const existingBoardSlug = boardIds.get(boardKey);\n if (existingBoardSlug && existingBoardSlug !== slug) {\n throw new Error(`Duplicate project board_id: ${boardId} in ${scope.replace(\"\\u0000\", \"/\")} used by ${existingBoardSlug} and ${slug}`);\n }\n boardIds.set(boardKey, slug);\n }\n const identifier = project.ticket_provider.identifier?.toUpperCase();\n if (identifier) {\n const identifierKey = `${scope}\\u0000${identifier}`;\n const existingIdentifierSlug = identifiers.get(identifierKey);\n if (existingIdentifierSlug && existingIdentifierSlug !== slug) {\n throw new Error(`Duplicate project identifier: ${identifier} in ${scope.replace(\"\\u0000\", \"/\")} used by ${existingIdentifierSlug} and ${slug}`);\n }\n identifiers.set(identifierKey, slug);\n }\n const notebookId = project.notebook?.notebook_id;\n if (notebookId) {\n const existingNotebookSlug = notebookIds.get(notebookId);\n if (existingNotebookSlug && existingNotebookSlug !== slug) throw new Error(`Duplicate project notebook_id: ${notebookId} used by ${existingNotebookSlug} and ${slug}`);\n notebookIds.set(notebookId, slug);\n }\n const overviewNoteId = project.notebook?.overview_note_id;\n if (overviewNoteId) {\n const existingOverviewSlug = overviewNoteIds.get(overviewNoteId);\n if (existingOverviewSlug && existingOverviewSlug !== slug) throw new Error(`Duplicate project overview_note_id: ${overviewNoteId} used by ${existingOverviewSlug} and ${slug}`);\n overviewNoteIds.set(overviewNoteId, slug);\n }\n }\n}\n\n/**\n * The uniqueness scope for a board binding: provider type plus workspace.\n * Identifiers are unique WITHIN a workspace and nowhere else \u2014 Plane will\n * happily assign `AAI` in automaticai and something else named `AAI` in a\n * different workspace, and both are legitimate.\n */\nfunction ticketProviderScope(provider: ProjectTicketProvider): string {\n return `${provider.type ?? \"\"}\\u0000${(provider.workspace ?? \"\").toLowerCase()}`;\n}\n\nfunction validateGlobalNotebookConfig(value: unknown): void {\n if (value === undefined) return;\n if (!isRecord(value)) throw new Error(\"Project registry notebook must be a mapping\");\n const credentialPath = notebookCredentialMaterialPath(value);\n if (credentialPath) throw new Error(`Project registry Notebook configuration contains forbidden credential material at ${credentialPath}`);\n if (value.base_url !== undefined) {\n if (typeof value.base_url !== \"string\" || !value.base_url.trim()) throw new Error(\"Project registry notebook.base_url must be a nonempty URL\");\n let url: URL;\n try { url = new URL(value.base_url); } catch { throw new Error(\"Project registry notebook.base_url must be an absolute URL\"); }\n if (url.username || url.password || url.search || url.hash) throw new Error(\"Project registry notebook.base_url may not contain credentials, query, or fragment\");\n const hostname = url.hostname.toLowerCase();\n const host = hostname.startsWith(\"[\") && hostname.endsWith(\"]\") ? hostname.slice(1, -1) : hostname;\n const loopback = hostname === \"localhost\" || host === \"::1\" || /^127(?:\\.\\d{1,3}){3}$/u.test(host);\n if (isIP(host) !== 0 && !loopback) throw new Error(\"Project registry notebook.base_url may not use a numeric non-loopback host\");\n if (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && loopback)) throw new Error(\"Project registry notebook.base_url must use HTTPS or loopback HTTP\");\n }\n if (value.auth !== undefined) {\n if (!isRecord(value.auth) || (value.auth.mode !== \"none\" && value.auth.mode !== \"environment\")) throw new Error(\"Project registry notebook.auth is invalid\");\n if (value.auth.mode === \"environment\" && value.auth.env_var !== \"OPEN_NOTEBOOK_PASSWORD\") throw new Error(\"Project registry notebook.auth.env_var must be OPEN_NOTEBOOK_PASSWORD\");\n if (value.auth.mode === \"none\" && value.auth.env_var !== undefined) throw new Error(\"Project registry notebook.auth none mode may not name a credential variable\");\n }\n const boundedList = (candidate: unknown, name: string): void => {\n if (!Array.isArray(candidate) || candidate.length > 100 || candidate.some((entry) => typeof entry !== \"string\" || !entry || Buffer.byteLength(entry, \"utf8\") > 512)) throw new Error(`Project registry notebook.defaults.${name} must be a bounded string list`);\n };\n if (value.defaults !== undefined) {\n if (!isRecord(value.defaults)) throw new Error(\"Project registry notebook.defaults must be a mapping\");\n for (const key of [\"enabled\", \"session_start_enabled\", \"session_capture_enabled\"] as const) {\n if (value.defaults[key] !== undefined && typeof value.defaults[key] !== \"boolean\") throw new Error(`Project registry notebook.defaults.${key} must be boolean`);\n }\n if (value.defaults.overview_max_chars !== undefined && (!Number.isSafeInteger(value.defaults.overview_max_chars) || Number(value.defaults.overview_max_chars) <= 0)) throw new Error(\"Project registry notebook.defaults.overview_max_chars must be a positive integer\");\n for (const key of [\"documentation_globs\", \"overview_references\", \"excluded_globs\"] as const) if (value.defaults[key] !== undefined) boundedList(value.defaults[key], key);\n }\n const limits = { ...DEFAULT_NOTEBOOK_LIMITS } as NotebookLimitsV1;\n if (value.limits !== undefined) {\n if (!isRecord(value.limits)) throw new Error(\"Project registry notebook.limits must be a mapping\");\n for (const key of Object.keys(DEFAULT_NOTEBOOK_LIMITS) as Array<keyof NotebookLimitsV1>) {\n const configured = value.limits[key];\n if (configured === undefined) continue;\n if (!Number.isSafeInteger(configured) || Number(configured) <= 0) throw new Error(`Project registry notebook.limits.${key} must be a positive integer`);\n limits[key] = Number(configured) as never;\n }\n }\n if (limits.schema_version !== 1) throw new Error(\"Project registry notebook.limits.schema_version must be 1\");\n if (limits.receipt_max_bytes > limits.unresolved_receipt_max_bytes) throw new Error(\"Project registry notebook receipt_max_bytes may not exceed unresolved_receipt_max_bytes\");\n if (limits.hook_payload_max_bytes > DEFAULT_NOTEBOOK_LIMITS.hook_payload_max_bytes) throw new Error(\"Project registry notebook hook_payload_max_bytes exceeds the packaged ceiling\");\n if (limits.note_detail_fetch_concurrency > DEFAULT_NOTEBOOK_LIMITS.note_detail_fetch_concurrency) throw new Error(\"Project registry notebook note_detail_fetch_concurrency exceeds the packaged ceiling\");\n if (limits.lease_seconds * 1_000 <= limits.overall_timeout_ms) throw new Error(\"Project registry notebook lease_seconds must exceed one request timeout\");\n if (isRecord(value.defaults) && value.defaults.overview_max_chars !== undefined && Number(value.defaults.overview_max_chars) > limits.note_max_bytes) throw new Error(\"Project registry notebook overview_max_chars exceeds note_max_bytes\");\n if (value.summarizer !== undefined) {\n if (!isRecord(value.summarizer) || typeof value.summarizer.executable !== \"string\" || !isAbsolute(value.summarizer.executable)\n || value.summarizer.executable.includes(\"\\0\") || Buffer.byteLength(value.summarizer.executable, \"utf8\") > 1_024) throw new Error(\"Project registry notebook.summarizer executable must be a bounded absolute path\");\n if (value.summarizer.args !== undefined && (!Array.isArray(value.summarizer.args) || value.summarizer.args.length > 32\n || value.summarizer.args.some((entry) => typeof entry !== \"string\" || entry.includes(\"\\0\") || Buffer.byteLength(entry, \"utf8\") > 1_024))) throw new Error(\"Project registry notebook.summarizer args must be bounded strings\");\n }\n}\n\n/**\n * Build the `.project.json` ticket_provider block for a supported provider.\n * Board URLs are derived from provider + workspace + board_id at runtime; the\n * manifest stores only stable identity. Lane\u2192state mapping is NOT stored here \u2014\n * that is per-repo config because kanban columns vary board to board.\n */\nexport function normalizeTicketProvider(value?: string): SupportedTicketProvider {\n const type = (value || \"plane\").trim().toLowerCase();\n if (type === \"plane\" || type === \"trello\") return type;\n throw new Error(`Unsupported ticket provider: ${value}. Supported providers: plane, trello`);\n}\n\nexport function buildTicketProviderBlock(input: {\n type?: string;\n identifier: string;\n /**\n * Omitted means pjangler proposed the identifier and nothing confirmed it.\n * Only a provider-confirmed identifier may back a \"linked\" board.\n */\n identifierSource?: ProjectIdentifierSource;\n identifierFetchedAt?: string;\n boardId?: string;\n /**\n * Instant the provider confirmed `boardId` is a real board. Omitted means\n * nothing confirmed it, and an unconfirmed binding can never be \"linked\".\n */\n boardConfirmedAt?: string;\n workspace?: string;\n}): ProjectTicketProvider {\n const type = normalizeTicketProvider(input.type);\n const boardId = input.boardId ?? \"\";\n const identifierSource: ProjectIdentifierSource = input.identifierSource ?? \"proposed\";\n const fetchedAt = identifierSource === \"provider\" ? input.identifierFetchedAt : undefined;\n // Reading a key back out of the provider FOR THIS BOARD confirms the binding\n // as a side effect, so a caller that supplies one need not supply both.\n const confirmedAt = input.boardConfirmedAt ?? (boardId ? fetchedAt : undefined);\n const provenClaim = !providerAssignsIdentifiers(type) || identifierSource === \"provider\";\n return {\n type,\n workspace: input.workspace ?? (type === \"trello\" ? \"\" : \"33god\"),\n identifier: input.identifier,\n identifier_source: identifierSource,\n ...(fetchedAt ? { identifier_fetched_at: fetchedAt } : {}),\n board_id: boardId,\n ...(confirmedAt ? { board_confirmed_at: confirmedAt } : {}),\n state: boardId && confirmedAt && provenClaim ? \"linked\" : \"planned\",\n };\n}\n\n/**\n * Credentials a provider adapter needs, as groups of ALTERNATIVES: every group\n * must be satisfied by at least one of its names.\n *\n * This must not be narrower than what the adapter itself accepts. It was:\n * pjangler asked only for `PLANE_API_KEY` while `providers/plane.sh` falls back\n * to `PLANE_<WORKSPACE>_API_KEY` (env or `~/.hermes/fleet.env`, `op://` refs\n * included). On a host whose only Plane credential is `PLANE_33GOD_API_KEY` \u2014\n * which is every host here \u2014 pjangler declared \"no credentials\", skipped the\n * board, and left the record `planned` while the adapter would have succeeded.\n */\nfunction ticketProviderKeyGroups(provider: string, workspace?: string): string[][] {\n if (provider === \"trello\") return [[\"TRELLO_KEY\"], [\"TRELLO_TOKEN\"]];\n return [[...new Set([\"PLANE_API_KEY\", workspaceEnvKey(workspace)])]];\n}\n\n/**\n * Env var a provider adapter reads its credential from. Mirrors the KEYVAR\n * switch in agents/hermes/pm/.scripts/42-ticket-provider.sh.\n */\nexport function ticketProviderKeyVar(provider: string, workspace?: string): string {\n return ticketProviderKeyGroups(provider, workspace)[0]!.join(\" or \");\n}\n\n/** Every credential name a provider adapter may read, in precedence order. */\nfunction ticketProviderKeyVars(provider: string, workspace?: string): string[] {\n return ticketProviderKeyGroups(provider, workspace).flat();\n}\n\n/** Repo convention: exported secrets live in `<config>/zshyzsh/secrets.zsh`. */\nexport function ticketProviderSecretsPath(env: NodeJS.ProcessEnv = process.env): string {\n const base = env.XDG_CONFIG_HOME || join(env.HOME || homedir(), \".config\");\n return join(base, \"zshyzsh\", \"secrets.zsh\");\n}\n\n/** The fleet dotenv the Hermes adapters read, honouring HERMES_FLEET_ENV. */\nexport function ticketProviderFleetEnvPath(env: NodeJS.ProcessEnv = process.env): string {\n return env.HERMES_FLEET_ENV?.trim() || join(env.HOME || homedir(), \".hermes\", \"fleet.env\");\n}\n\n/** Pull `KEY=value` / `export KEY=value` assignments for the requested keys only. */\nfunction readShellAssignments(path: string, keys: string[]): Record<string, string> {\n const found: Record<string, string> = {};\n if (!existsSync(path)) return found;\n let text: string;\n try {\n text = readFileSync(path, \"utf8\");\n } catch {\n return found;\n }\n const wanted = new Set(keys);\n for (const rawLine of text.split(/\\r?\\n/)) {\n const line = rawLine.trim();\n if (!line || line.startsWith(\"#\")) continue;\n const match = /^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);\n if (!match) continue;\n const key = match[1]!;\n if (!wanted.has(key) || found[key] !== undefined) continue;\n let value = match[2]!.trim();\n const quote = value[0];\n if ((quote === '\"' || quote === \"'\") && value.length > 1 && value.endsWith(quote)) {\n value = value.slice(1, -1);\n } else {\n value = value.split(/\\s+#/)[0]!.trim();\n }\n if (value) found[key] = value;\n }\n return found;\n}\n\n/**\n * Resolve ticket-provider credentials the way the rest of the repo does:\n * process env -> repo `.env` -> `~/.hermes/fleet.env` -> the exported zshyzsh\n * secrets file. Never prompts, and callers must never log `values` \u2014 `source`\n * is the loggable part.\n *\n * Values are returned exactly as found, `op://` references included: the\n * adapters resolve those themselves at the last moment, so a reference never\n * has to be dereferenced here.\n */\nexport function resolveTicketProviderCredentials(input: {\n keys: string[];\n repoPath?: string;\n env?: NodeJS.ProcessEnv;\n}): { values: Record<string, string>; sources: Record<string, string> } {\n const env = input.env ?? process.env;\n const values: Record<string, string> = {};\n const sources: Record<string, string> = {};\n const missing = () => input.keys.filter((key) => !values[key]);\n\n for (const key of input.keys) {\n const fromEnv = env[key];\n if (fromEnv) {\n values[key] = fromEnv;\n sources[key] = \"environment\";\n }\n }\n\n const candidates: string[] = [];\n if (input.repoPath) candidates.push(join(input.repoPath, \".env\"));\n candidates.push(ticketProviderFleetEnvPath(env));\n candidates.push(ticketProviderSecretsPath(env));\n\n for (const candidate of candidates) {\n const outstanding = missing();\n if (!outstanding.length) break;\n const assignments = readShellAssignments(candidate, outstanding);\n for (const [key, value] of Object.entries(assignments)) {\n values[key] = value;\n sources[key] = candidate;\n }\n }\n\n return { values, sources };\n}\n\n/**\n * Locate a `tp` provider adapter (`<provider>.sh`). Resolution mirrors\n * resolveTemplateRoot() in src/commands/AgentHooksCommands.ts: an env override\n * first, then a walk up from this module so it works from source, from the\n * bundled `dist/`, and from the published npm package (which ships\n * `templates/`), then the canonical ~/code/pjangler checkout.\n *\n * The distributable `templates/hermes-agent` submodule wins over the repo-local\n * `agents/hermes/pm` tree so pjangler runs the same adapter it ships to users.\n */\nexport function resolveTicketProviderAdapter(provider: string, env: NodeJS.ProcessEnv = process.env): string | undefined {\n const file = `${provider}.sh`;\n const candidates: string[] = [];\n const override = env[TICKET_PROVIDER_ADAPTERS_ENV];\n if (override) candidates.push(join(override, file));\n const relativeRoots = [\n join(\"templates\", \"hermes-agent\", \"template\", \".scripts\", \"providers\"),\n join(\"agents\", \"hermes\", \"pm\", \".scripts\", \"providers\"),\n ];\n try {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let depth = 0; depth < 8; depth++) {\n for (const relativeRoot of relativeRoots) candidates.push(join(dir, relativeRoot, file));\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n } catch {\n /* import.meta.url unavailable \u2014 rely on the other candidates */\n }\n for (const relativeRoot of relativeRoots) {\n candidates.push(join(homedir(), \"code\", \"pjangler\", relativeRoot, file));\n }\n return candidates.find((candidate) => existsSync(candidate));\n}\n\nexport interface TicketProviderBoardResult {\n ok: boolean;\n /** True when the action was intentionally not performed (e.g. no credentials). */\n skipped: boolean;\n boardId?: string;\n /** The identifier the PROVIDER assigned, read off its own response. */\n identifier?: string;\n boardUrl?: string;\n logs: string[];\n error?: string;\n}\n\n/**\n * Create (or link, the adapters are idempotent) the repo's ticket board by\n * invoking the same `create_board` op that\n * agents/hermes/pm/.scripts/42-ticket-provider.sh uses.\n *\n * Missing credentials are a graceful skip, never a failure \u2014 an operator\n * without creds must still get a working init, exactly as 42-ticket-provider.sh\n * behaves.\n */\nexport function provisionTicketProviderBoard(\n action: Extract<ProjectInitAction, { kind: \"ticket-provider.create-or-link\" }>,\n env: NodeJS.ProcessEnv = process.env\n): TicketProviderBoardResult {\n const provider = action.provider;\n const groups = ticketProviderKeyGroups(provider, action.workspace);\n const { values } = resolveTicketProviderCredentials({\n keys: ticketProviderKeyVars(provider, action.workspace),\n repoPath: action.repoPath,\n env,\n });\n\n const unsatisfied = groups.filter((group) => !group.some((key) => values[key]));\n if (unsatisfied.length) {\n const names = unsatisfied.map((group) => group.join(\" or \")).join(\" and \");\n return {\n ok: true,\n skipped: true,\n logs: [\n `ticket-provider: ${names} not set; skipping ${provider} board creation (state stays \"planned\"). ` +\n `Set it in the environment, ${join(action.repoPath, \".env\")}, ${ticketProviderFleetEnvPath(env)}, ` +\n `or ${ticketProviderSecretsPath(env)} \u2014 or pass --board-id to link an existing board.`,\n ],\n };\n }\n\n const adapter = resolveTicketProviderAdapter(provider, env);\n if (!adapter) {\n return {\n ok: false,\n skipped: false,\n logs: [],\n error:\n `ticket-provider: no ${provider} adapter found. ` +\n `Set ${TICKET_PROVIDER_ADAPTERS_ENV} to a directory containing ${provider}.sh.`,\n };\n }\n\n const redact = (text: string): string =>\n Object.values(values).reduce((acc, secret) => (secret ? acc.split(secret).join(\"***\") : acc), text);\n\n // The adapters resolve their board binding from the nearest .project.json\n // above their own role dir (`$0/../..`), NOT from the cwd or the environment.\n // Running the vendored adapter in place would therefore make it inherit\n // pjangler's own workspace/board. Stage it inside a throwaway repo shaped\n // like a Hermes role tree whose .project.json carries exactly this plan's\n // binding, so the adapter resolves the workspace we intend.\n const staging = mkdtempSync(join(tmpdir(), \"pjangler-tp-\"));\n try {\n const providersDir = join(staging, \"agents\", \"hermes\", \"pm\", \".scripts\", \"providers\");\n mkdirSync(providersDir, { recursive: true });\n writeFileSync(\n join(staging, \".project.json\"),\n `${JSON.stringify(\n {\n project_name: action.boardName,\n repo_path: action.repoPath,\n ticket_provider: {\n type: provider,\n workspace: action.workspace,\n identifier: action.identifier,\n board_id: \"\",\n state: \"planned\",\n },\n },\n null,\n 2\n )}\\n`,\n \"utf8\"\n );\n const staged = join(providersDir, `${provider}.sh`);\n copyFileSync(adapter, staged);\n\n const childEnv: NodeJS.ProcessEnv = { ...env, ...values, TICKET_PROVIDER: provider };\n if (provider === \"plane\" && action.workspace) childEnv.PLANE_WORKSPACE = action.workspace;\n\n const result = spawnSync(\"sh\", [staged, \"create_board\", action.boardName, action.identifier, action.description], {\n cwd: existsSync(action.repoPath) ? action.repoPath : staging,\n encoding: \"utf8\",\n env: childEnv,\n });\n\n if (result.error) {\n return {\n ok: false,\n skipped: false,\n logs: [],\n error: `ticket-provider: could not run the ${provider} adapter: ${redact(result.error.message)}`,\n };\n }\n const stderr = redact((result.stderr ?? \"\").trim());\n if (result.status !== 0) {\n return {\n ok: false,\n skipped: false,\n logs: [],\n error:\n `ticket-provider: ${provider} create_board failed (exit ${result.status ?? \"unknown\"})` +\n `${stderr ? `: ${stderr}` : \"\"}`,\n };\n }\n\n const stdout = (result.stdout ?? \"\").trim();\n const lastLine = stdout.split(/\\r?\\n/).filter((line) => line.trim()).pop() ?? \"\";\n let parsed: unknown;\n try {\n parsed = JSON.parse(lastLine);\n } catch {\n return {\n ok: false,\n skipped: false,\n logs: [],\n error: `ticket-provider: ${provider} create_board returned unparseable output: ${redact(lastLine) || \"(empty)\"}`,\n };\n }\n const boardId = isRecord(parsed) && typeof parsed.board_id === \"string\" ? parsed.board_id.trim() : \"\";\n if (!boardId) {\n return {\n ok: false,\n skipped: false,\n logs: [],\n error: `ticket-provider: ${provider} create_board returned no board_id`,\n };\n }\n const identifier = isRecord(parsed) && typeof parsed.identifier === \"string\" ? parsed.identifier.trim() : \"\";\n if (!identifier) {\n return {\n ok: false,\n skipped: false,\n logs: [],\n error:\n `ticket-provider: ${provider} create_board returned no identifier. ` +\n `The adapter must echo the identifier the provider assigned; pjangler no longer invents one.`,\n };\n }\n const boardUrl = isRecord(parsed) && typeof parsed.board_url === \"string\" ? parsed.board_url : undefined;\n return {\n ok: true,\n skipped: false,\n boardId,\n identifier,\n boardUrl,\n logs: [`ticket-provider: ${provider} board linked (${identifier} \u2192 ${boardId})`],\n };\n } finally {\n rmSync(staging, { recursive: true, force: true });\n }\n}\n\nexport function defaultProjectAutomation(): ProjectAutomation {\n return {\n reconcile: {\n enabled: false,\n grace_hours: 0,\n auto_review: true,\n },\n };\n}\n\nexport function slugifyProjectName(value: string): string {\n return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"project\";\n}\n\nconst SAFE_PATH_SEGMENT = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;\n\n/**\n * Validate caller-controlled names that become one filesystem path segment.\n * Keep this capability open-ended (roles are not an enum), while excluding\n * every spelling that can change the directory reached by a later join().\n */\nexport function validateSafePathSegment(value: string, label: string): string {\n const normalized = value.trim();\n const unsafe =\n !normalized ||\n normalized !== value ||\n normalized === \".\" ||\n normalized === \"..\" ||\n isAbsolute(normalized) ||\n win32.isAbsolute(normalized) ||\n normalized.includes(\"/\") ||\n normalized.includes(\"\\\\\") ||\n !SAFE_PATH_SEGMENT.test(normalized);\n if (unsafe) {\n throw new Error(\n `${label} must be a non-empty safe single path segment using letters, numbers, dots, underscores, or hyphens (no dot segments, absolute paths, separators, or traversal)`,\n );\n }\n return normalized;\n}\n\nfunction prospectiveRealPath(path: string): string {\n let cursor = resolve(path);\n const suffix: string[] = [];\n while (!existsSync(cursor)) {\n const parent = dirname(cursor);\n if (parent === cursor) return resolve(path);\n suffix.unshift(basename(cursor));\n cursor = parent;\n }\n return resolve(realpathSync(cursor), ...suffix);\n}\n\n/** Resolve a prospective child and reject lexical or symlink-assisted escape. */\nexport function resolveContainedPath(parentDir: string, candidate: string, label: string): string {\n const physicalParent = prospectiveRealPath(parentDir);\n const physicalCandidate = prospectiveRealPath(candidate);\n const fromParent = relative(physicalParent, physicalCandidate);\n if (!fromParent || fromParent === \"..\" || fromParent.startsWith(`..${sep}`) || isAbsolute(fromParent)) {\n throw new Error(`${label} must remain contained beneath parent directory ${resolve(parentDir)}`);\n }\n return resolve(candidate);\n}\n\n/**\n * PROPOSE an identifier from a project name.\n *\n * This is a placeholder, never a board key. The provider assigns the real\n * identifier and `pj project identity` reads it back; anything this function\n * returns lands with `identifier_source: \"proposed\"` and can never satisfy the\n * linked-board invariant on its own. The registry drifted for months because\n * four code paths treated a string slice as authoritative.\n */\nexport function proposeProjectIdentifier(value: string): string {\n const compact = value.replace(/[^A-Za-z0-9]/g, \"\").toUpperCase();\n const identifier = compact.slice(0, 4) || \"PROJ\";\n return identifier.length >= 2 ? identifier : `${identifier}XX`.slice(0, 4);\n}\n\nexport function normalizeAgentRole(value?: string): string {\n return value === undefined ? \"pm\" : validateSafePathSegment(value, \"Agent role\");\n}\n\n/**\n * Decide whether the CommonProject scaffold should include the project-scoped\n * agent-hooks + skill fan-out layer. Explicit input wins; then the\n * PJ_AGENT_HOOKS_LAYER env override (0/false | 1/true); otherwise the layer is\n * SKIPPED when the machine already runs a global agent-hooks install\n * (~/.agents/hooks), so a fresh project never re-injects the same hooks into the\n * caller's shared per-user CLI configs (~/.codex, ~/.kimi-code, ...).\n */\nexport function resolveAgentHooksLayer(input?: boolean, env: NodeJS.ProcessEnv = process.env): boolean {\n if (typeof input === \"boolean\") return input;\n const override = env.PJ_AGENT_HOOKS_LAYER;\n if (override === \"0\" || override === \"false\") return false;\n if (override === \"1\" || override === \"true\") return true;\n return !existsSync(join(homedir(), \".agents\", \"hooks\"));\n}\n\nfunction jsonStable(value: unknown): string {\n return JSON.stringify(value);\n}\n\nfunction projectRecordEquivalent(a: ProjectRecord | undefined, b: ProjectRecord): boolean {\n if (!a) return false;\n const { created_at: _aCreated, updated_at: _aUpdated, ...aComparable } = a;\n const { created_at: _bCreated, updated_at: _bUpdated, ...bComparable } = b;\n return jsonStable(aComparable) === jsonStable(bComparable);\n}\n\nexport function defaultProjectTargetDir(name: string, cwd = process.cwd()): string {\n const compactName = name.replace(/[^A-Za-z0-9._-]/g, \"\");\n const safeName = SAFE_PATH_SEGMENT.test(compactName) ? compactName : slugifyProjectName(name);\n return resolve(dirname(resolve(cwd)), validateSafePathSegment(safeName, \"Generated project directory\"));\n}\n\nexport function sourceSkillRoots(env: NodeJS.ProcessEnv = process.env): string[] {\n const configuredRoots = (env[PROJECT_SOURCE_SKILL_ROOTS_ENV] || \"\")\n .split(delimiter)\n .map((root) => root.trim())\n .filter(Boolean);\n const seen = new Set<string>();\n const roots: string[] = [];\n for (const root of [...DEFAULT_SOURCE_SKILL_ROOTS, ...configuredRoots]) {\n const normalized = resolve(expandHome(root));\n if (seen.has(normalized)) continue;\n seen.add(normalized);\n roots.push(normalized);\n }\n return roots;\n}\n\nexport function resolveSourceSkillPath(sourceSkill?: string, env: NodeJS.ProcessEnv = process.env): string | undefined {\n if (!sourceSkill) return undefined;\n const expanded = expandHome(sourceSkill);\n const direct = resolve(expanded);\n if (existsSync(direct)) return direct;\n\n const name = basename(sourceSkill);\n const roots = sourceSkillRoots(env);\n for (const root of roots) {\n const candidate = join(root, name);\n if (existsSync(candidate)) return candidate;\n }\n\n const searched = roots.length ? ` Searched roots: ${roots.join(\", \")}.` : \"\";\n const hint = `${searched} Add project-specific roots with ${PROJECT_SOURCE_SKILL_ROOTS_ENV}.`;\n throw new Error(`Source skill not found: ${sourceSkill}.${hint}`);\n}\n\nexport function planProjectInit(input: ProjectInitInput): ProjectInitPlan {\n if (!input.name.trim()) throw new Error(\"Project name is required\");\n const slug = input.projectSlug === undefined\n ? validateSafePathSegment(slugifyProjectName(input.name), \"Project slug\")\n : validateSafePathSegment(input.projectSlug, \"Project slug\");\n const agentRole = normalizeAgentRole(input.agentRole);\n const registryPath = resolve(projectRegistryPath({ ...process.env, [PROJECT_REGISTRY_ENV]: input.registryPath || process.env[PROJECT_REGISTRY_ENV] }));\n const registry = loadProjectRegistry(registryPath);\n const now = (input.now ?? new Date()).toISOString();\n const targetDir = resolve(input.targetDir ?? defaultProjectTargetDir(input.name, input.cwd));\n const identifier = (input.projectIdentifier ?? proposeProjectIdentifier(input.name)).toUpperCase();\n const existing = getOwnRecordValue(registry.projects, slug);\n // A board provisioned by an earlier run lives in the registry, not in the CLI\n // flags \u2014 inherit it so re-running init re-links instead of minting a second\n // board.\n const resolvedBoardId = input.boardId ?? input.planeProjectId ?? (existing?.ticket_provider?.board_id || undefined);\n const inheritedProvenance =\n existing?.ticket_provider?.identifier_source === \"provider\"\n && existing.ticket_provider.identifier?.toUpperCase() === identifier\n && (existing.ticket_provider.board_id || undefined) === resolvedBoardId\n ? {\n identifierSource: \"provider\" as const,\n ...(existing.ticket_provider.identifier_fetched_at\n ? { identifierFetchedAt: existing.ticket_provider.identifier_fetched_at }\n : {}),\n }\n : undefined;\n // Board-binding provenance is inherited on its own terms. A Trello board the\n // provider already confirmed stays confirmed even though its key is \u2014 and\n // always will be \u2014 a proposal.\n const inheritedBoardConfirmation =\n resolvedBoardId\n && (existing?.ticket_provider?.board_id || undefined) === resolvedBoardId\n && existing?.ticket_provider?.board_confirmed_at\n ? { boardConfirmedAt: existing.ticket_provider.board_confirmed_at }\n : undefined;\n const sourceSkillPath = resolveSourceSkillPath(input.sourceSkill);\n const overwrite = input.overwrite ?? input.force ?? false;\n const agents = createSafeRecord<ProjectAgentRecord>(Object.entries(existing?.agents ?? {}));\n if (input.provisionAgent) {\n agents[agentRole] = {\n role: agentRole,\n provisioning_state: \"planned\",\n };\n }\n const scaffold = input.scaffold ?? true;\n\n const candidateProject: ProjectRecord = {\n ...(existing ?? {}),\n name: input.name,\n slug,\n repo_path: targetDir,\n description: input.description ?? \"\",\n // A project the CLI is bootstrapping is being worked on right now, so a\n // NEW record starts \"active\" (PJAN-26). This is a default for new records,\n // NOT a migration: an already-registered project keeps whatever lifecycle\n // status it has (\"planned\"/\"active\"/\"archived\"), so re-running init (or the\n // sync path) never rewrites it.\n // NOTE: unrelated to `ticket_provider.state` and `agents.*.provisioning_state`,\n // which are different lifecycles and still default to \"planned\".\n status: existing?.status ?? DEFAULT_NEW_PROJECT_STATUS,\n source_artifacts: sourceSkillPath\n ? [{ kind: \"skill\", path: sourceSkillPath, package_name: input.packageName ?? slug }]\n : [],\n template: {\n commonproject: {\n enabled: true,\n primary_language: input.primaryLanguage ?? \"python\",\n },\n },\n ticket_provider: buildTicketProviderBlock({\n type: input.ticketProvider ?? \"plane\",\n identifier,\n boardId: resolvedBoardId,\n workspace: input.boardWorkspace ?? input.planeWorkspace,\n // Provenance survives a re-plan. Without this, re-running init on an\n // already-confirmed board would demote it back to \"planned\" because the\n // CLI has no way to re-derive where the identifier came from.\n ...(inheritedProvenance ?? {}),\n ...(inheritedBoardConfirmation ?? {}),\n }),\n agents,\n automation: existing?.automation ?? defaultProjectAutomation(),\n notebook: existing?.notebook\n ? { ...existing.notebook, notebook_name: input.name.trim() }\n : { state: \"planned\", notebook_name: input.name.trim() },\n created_at: existing?.created_at ?? now,\n updated_at: now,\n };\n const project: ProjectRecord = {\n ...candidateProject,\n updated_at: projectRecordEquivalent(existing, candidateProject) ? existing!.updated_at : now,\n };\n\n validateNoDuplicateProject(registry, project, overwrite);\n\n const pjanglerRoot = resolve(input.pjanglerRoot ?? resolvePjanglerRoot());\n const manifest = projectManifestFromRegistryProject(project);\n const apply = input.apply ?? false;\n const live = input.live ?? false;\n // Structured callers (notably MCP) pass explicit booleans so `live` alone\n // grants no remote effect. provisionRuntimeRepo is a deprecated no-op: the\n // only supported runtime is ignored role-local state.\n //\n // The board is NOT an optional garnish behind `--live`. It used to be, and\n // that is exactly how 11 of 24 registry records ended up carrying\n // `board_id: \"\"`: `pj init` is the designated ingress, it registered the\n // project, silently dropped the board action from the plan, printed nothing\n // about it, and exited 0. A record with no board fails the registry's own\n // contract \u2014 `board_confirmed_at` and `identifier_source` exist to say a\n // provider confirmed this board, and there is nothing for them to describe.\n //\n // So board provisioning defaults ON, and the only way out is the subtractive\n // `skipPlane` gate (CLI `--skip-board`), which the operator must ask for.\n // `--live` keeps its meaning for effects that change the HOST rather than the\n // project's own identity: systemd units, the notebook endpoint, and the\n // Hermes agent's own external tail.\n const provisionTicketBoard = input.provisionTicketBoard ?? true;\n const enableSystemd = input.enableSystemd ?? live;\n const skipPlane = input.skipPlane ?? false;\n const boardEnabled = provisionTicketBoard && !skipPlane;\n const systemdEnabled = live && enableSystemd && process.platform !== \"darwin\";\n // The AGENT's external tail is a host effect and stays behind `--live`.\n const agentBoardEffect = live && boardEnabled;\n const anyExternalAgentEffect = agentBoardEffect || systemdEnabled;\n const actions: ProjectInitAction[] = [\n { kind: \"registry.upsert\", registryPath, slug, project },\n ];\n if (scaffold) {\n actions.push(buildCommonProjectCopierAction({\n pjanglerRoot,\n targetDir,\n projectName: project.name,\n projectDescription: project.description,\n projectSlug: project.slug,\n ticketProvider: project.ticket_provider.type,\n planeWorkspace: project.ticket_provider.workspace ?? \"33god\",\n planeProjectId: project.ticket_provider.board_id ?? \"\",\n ticketWorkspace: project.ticket_provider.workspace ?? \"\",\n boardId: project.ticket_provider.board_id ?? \"\",\n projectIdentifier: identifier,\n primaryLanguage: project.template.commonproject.primary_language,\n agentHooksLayer: resolveAgentHooksLayer(input.agentHooksLayer),\n overwrite,\n }));\n }\n actions.push(\n { kind: \"project.write-manifest\", path: join(targetDir, \".project.json\"), manifest },\n {\n kind: \"ticket-provider.create-or-link\",\n enabled: boardEnabled,\n live,\n provider: project.ticket_provider.type,\n workspace: project.ticket_provider.workspace ?? \"33god\",\n identifier,\n repoPath: targetDir,\n boardName: project.name,\n description: project.description || `Ticket board for ${project.slug}`,\n boardId: project.ticket_provider.board_id ?? \"\",\n state: project.ticket_provider.board_id ? \"linked\" : \"planned\",\n reason: skipPlane\n ? \"ticket-provider action disabled by skipPlane=true (--skip-board)\"\n : project.ticket_provider.board_id\n ? \"board already linked; no provider call\"\n : !provisionTicketBoard\n ? \"ticket-provider action requires explicit provisionTicketBoard=true\"\n : `create or link the ${project.ticket_provider.type} board \"${project.name}\" (${identifier}) via the ticket-provider adapter`,\n },\n {\n kind: \"hermes.provision-agent\",\n enabled: input.provisionAgent ?? false,\n local: !anyExternalAgentEffect,\n targetDir,\n targetRepo: slug,\n role: agentRole,\n context: {\n skipPlane: !agentBoardEffect,\n // Per-agent Bloodbank consumers are retired. Agent ingress always\n // stays on the fleet-shared gateway, regardless of live/local mode.\n skipBloodbank: true,\n skipSystemd: !systemdEnabled,\n },\n }\n );\n\n return {\n ok: true,\n apply,\n dryRun: !apply,\n live,\n registryPath,\n project,\n manifest,\n actions,\n ...(input.boardUrl !== undefined ? { warnings: [BOARD_URL_DEPRECATION_WARNING] } : {}),\n };\n}\n\n/**\n * Fold a freshly provisioned board back into the plan's projections: the\n * registry record (shared object with the `registry.upsert` action), the\n * in-memory manifest, the action itself, and the on-disk `.project.json`.\n *\n * `buildTicketProviderBlock` owns the planned -> linked flip, so board_id and\n * state can never disagree. Returns the files it changed.\n */\nfunction linkTicketProviderBoard(\n plan: ProjectInitPlan,\n action: Extract<ProjectInitAction, { kind: \"ticket-provider.create-or-link\" }>,\n boardId: string,\n identifier: string,\n now: Date = new Date()\n): string[] {\n const block = buildTicketProviderBlock({\n type: action.provider,\n // The PROVIDER's identifier, not the one we proposed on the way in.\n identifier,\n identifierSource: \"provider\",\n identifierFetchedAt: now.toISOString(),\n boardId,\n workspace: action.workspace,\n });\n action.identifier = identifier;\n plan.project.ticket_provider = block;\n const manifestProvider = {\n type: block.type,\n workspace: block.workspace ?? \"\",\n identifier: block.identifier ?? \"\",\n identifier_source: block.identifier_source ?? \"proposed\",\n ...(block.identifier_fetched_at ? { identifier_fetched_at: block.identifier_fetched_at } : {}),\n board_id: block.board_id ?? \"\",\n // The provider just handed this board back, and the manifest is where that\n // confirmation lives for every later reader of the repo.\n ...(block.board_confirmed_at ? { board_confirmed_at: block.board_confirmed_at } : {}),\n state: block.state ?? \"linked\",\n };\n plan.manifest.ticket_provider = manifestProvider;\n action.boardId = boardId;\n action.state = manifestProvider.state;\n\n const manifestPath = join(action.repoPath, \".project.json\");\n let next: Record<string, unknown>;\n if (existsSync(manifestPath)) {\n // Preserve whatever the scaffold (or the operator) already put in the file.\n let existing: Record<string, unknown> = {};\n try {\n const parsed: unknown = JSON.parse(readFileSync(manifestPath, \"utf8\"));\n if (isRecord(parsed)) existing = parsed;\n } catch {\n existing = {};\n }\n const existingProvider = isRecord(existing.ticket_provider) ? existing.ticket_provider : {};\n next = { ...existing, ticket_provider: { ...existingProvider, ...manifestProvider } };\n } else {\n mkdirSync(dirname(manifestPath), { recursive: true });\n next = plan.manifest as unknown as Record<string, unknown>;\n }\n const text = `${JSON.stringify(next, null, 2)}\\n`;\n if (!existsSync(manifestPath) || readFileSync(manifestPath, \"utf8\") !== text) {\n writeFileSync(manifestPath, text, \"utf8\");\n return [manifestPath];\n }\n return [];\n}\n\nexport async function executeProjectInitPlan(\n plan: ProjectInitPlan,\n options: ProjectInitExecutionOptions = {},\n): Promise<ProjectInitExecutionResult> {\n const logs: string[] = [];\n const errors: string[] = [];\n const changedFiles: string[] = [];\n if (!plan.apply) return { ok: true, plan, logs, errors, changedFiles };\n\n const registry = loadProjectRegistry(plan.registryPath);\n let pendingRegistryAction: Extract<ProjectInitAction, { kind: \"registry.upsert\" }> | undefined;\n for (const action of plan.actions) {\n if (action.kind === \"copier.copy.commonproject\") {\n if (options.requireTrustedCopier && !options.trustedCopier) {\n errors.push(\"MCP project apply requires a preflight-attested Copier identity\");\n break;\n }\n if (options.trustedCopier) {\n const verified = verifyTrustedCopierIdentity(options.trustedCopier);\n if (!verified.ok) {\n errors.push(`Copier provenance revalidation failed: ${verified.error ?? \"unknown identity failure\"}`);\n break;\n }\n }\n logs.push(\n action.data.agent_hooks_layer === \"false\"\n ? \"commonproject: agent-hooks layer skipped (global ~/.agents/hooks detected \u2014 no per-user CLI injection)\"\n : \"commonproject: agent-hooks layer included\"\n );\n mkdirSync(dirname(action.targetDir), { recursive: true });\n const before = snapshotTree(action.targetDir);\n const copierExecutable = options.trustedCopier?.executable ?? action.command[0]!;\n const copierEnv = options.trustedCopier ? { ...process.env } : undefined;\n if (copierEnv) {\n delete copierEnv.PYTHONHOME;\n delete copierEnv.PYTHONPATH;\n copierEnv.PYTHONNOUSERSITE = \"1\";\n copierEnv.PYTHONSAFEPATH = \"1\";\n }\n const result = spawnSync(copierExecutable, action.command.slice(1), {\n encoding: \"utf8\",\n cwd: action.cwd,\n ...(copierEnv ? { env: copierEnv } : {}),\n });\n const copierChanges = changedTreePaths(action.targetDir, before, snapshotTree(action.targetDir));\n changedFiles.push(...copierChanges);\n if (result.stdout?.trim()) logs.push(result.stdout.trim());\n if (result.stderr?.trim()) logs.push(result.stderr.trim());\n if (result.error) {\n const code = (result.error as NodeJS.ErrnoException).code;\n errors.push(\n code === \"ENOENT\"\n ? \"copier not found on PATH. Install with: uv tool install copier or pip install copier\"\n : `copier failed: ${result.error.message}`\n );\n break;\n }\n if (result.status !== 0) {\n errors.push(`copier exited with status ${result.status ?? \"unknown\"}`);\n break;\n }\n } else if (action.kind === \"project.write-manifest\") {\n mkdirSync(dirname(action.path), { recursive: true });\n let value = action.manifest as unknown as Record<string, unknown>;\n if (existsSync(action.path)) {\n try {\n const currentValue = JSON.parse(readFileSync(action.path, \"utf8\")) as unknown;\n if (isRecord(currentValue)) {\n const currentNotebook = isRecord(currentValue.notebook) ? currentValue.notebook : {};\n const desiredNotebook = isRecord(value.notebook) ? value.notebook : {};\n value = {\n ...currentValue,\n ...value,\n ticket_provider: { ...(isRecord(currentValue.ticket_provider) ? currentValue.ticket_provider : {}), ...(isRecord(value.ticket_provider) ? value.ticket_provider : {}) },\n agents: { ...(isRecord(currentValue.agents) ? currentValue.agents : {}), ...(isRecord(value.agents) ? value.agents : {}) },\n ...(value.notebook ? {\n notebook: {\n ...currentNotebook,\n ...desiredNotebook,\n ...(isRecord(desiredNotebook.binding) ? { binding: { ...(isRecord(currentNotebook.binding) ? currentNotebook.binding : {}), ...desiredNotebook.binding } } : {}),\n ...(isRecord(desiredNotebook.policy) ? { policy: { ...(isRecord(currentNotebook.policy) ? currentNotebook.policy : {}), ...desiredNotebook.policy } } : {}),\n },\n } : {}),\n };\n }\n } catch { /* invalid existing manifest is replaced by the validated plan */ }\n }\n const next = `${JSON.stringify(value, null, 2)}\\n`;\n const current = existsSync(action.path) ? readFileSync(action.path, \"utf8\") : undefined;\n if (current !== next) {\n writeFileSync(action.path, next, \"utf8\");\n changedFiles.push(action.path);\n }\n changedFiles.push(...synchronizeCopierIdentity(action.path, action.manifest));\n } else if (action.kind === \"registry.upsert\") {\n pendingRegistryAction = action;\n } else if (action.kind === \"ticket-provider.create-or-link\") {\n if (!action.enabled) {\n logs.push(`ticket-provider.create-or-link skipped (${action.reason ?? \"disabled by plan\"})`);\n } else if (action.boardId) {\n logs.push(`ticket-provider: ${action.provider} board already linked (${action.identifier} \u2192 ${action.boardId}); nothing to create`);\n } else {\n const outcome = provisionTicketProviderBoard(action);\n logs.push(...outcome.logs);\n if (!outcome.ok) {\n errors.push(outcome.error ?? `ticket-provider: ${action.provider} board provisioning failed`);\n } else if (outcome.boardId && outcome.identifier) {\n changedFiles.push(...linkTicketProviderBoard(plan, action, outcome.boardId, outcome.identifier));\n pendingRegistryAction ??= {\n kind: \"registry.upsert\",\n registryPath: plan.registryPath,\n slug: plan.project.slug,\n project: plan.project,\n };\n }\n }\n } else if (action.kind === \"hermes.provision-agent\") {\n logs.push(action.enabled ? \"hermes.provision-agent planned for the caller to execute\" : \"hermes.provision-agent skipped\");\n }\n }\n\n if (pendingRegistryAction && errors.length === 0) {\n if (!projectRecordEquivalent(getOwnRecordValue(registry.projects, pendingRegistryAction.slug), pendingRegistryAction.project)) {\n registry.projects[pendingRegistryAction.slug] = pendingRegistryAction.project;\n saveProjectRegistry(registry, pendingRegistryAction.registryPath);\n changedFiles.push(pendingRegistryAction.registryPath);\n\n if (isPgRegistryEnabled()) {\n try {\n const pgStore = new PgRegistryStore(pgRegistryConfigFromEnv());\n await pgStore.save(registry);\n await pgStore.close();\n logs.push(\"registry: PG dual-write complete\");\n } catch (pgErr) {\n logs.push(`registry: PG dual-write failed (yaml is authoritative): ${pgErr instanceof Error ? pgErr.message : pgErr}`);\n }\n }\n }\n }\n\n return { ok: errors.length === 0, plan, logs, errors, changedFiles: [...new Set(changedFiles)].sort() };\n}\n\nexport function projectManifestFromRegistryProject(project: ProjectRecord): ProjectManifest {\n const agents = Object.fromEntries(\n Object.entries(project.agents).map(([name, agent]) => [\n `${project.slug}-${name}`,\n {\n role: agent.role,\n role_dir: agent.role_dir,\n provisioning_state: agent.provisioning_state,\n },\n ])\n );\n return {\n project_name: project.name,\n project_description: project.description,\n project_slug: project.slug,\n repo_path: project.repo_path,\n ticket_provider: {\n type: project.ticket_provider.type,\n workspace: project.ticket_provider.workspace ?? \"\",\n identifier: project.ticket_provider.identifier ?? \"\",\n board_id: project.ticket_provider.board_id ?? \"\",\n state: project.ticket_provider.state,\n },\n agents,\n automation: project.automation ?? defaultProjectAutomation(),\n ...(project.notebook ? { notebook: { binding: { ...project.notebook } } } : {}),\n };\n}\n\nexport function formatProjectInitPlan(plan: ProjectInitPlan): string {\n const lines = [\"\"];\n const title = `${bold(plan.project.name)} ${dim(`(${plan.project.slug})`)}`;\n lines.push(` ${cyan(bold(glyph.chevron))} ${title}${plan.dryRun ? ` ${dim(glyph.dot)} ${yellow(\"dry run\")}` : \"\"}`);\n lines.push(` ${dim(\"registry\".padEnd(8))} ${dim(plan.registryPath)}`);\n lines.push(` ${dim(\"target\".padEnd(8))} ${dim(plan.project.repo_path)}`);\n for (const warning of plan.warnings ?? []) lines.push(` ${yellow(glyph.warn)} ${warning}`);\n lines.push(\"\");\n lines.push(` ${bold(\"Actions\")} ${dim(`(${plan.actions.length})`)}`);\n if (!plan.actions.length) lines.push(` ${dim(\"(nothing to do)\")}`);\n for (const action of plan.actions) {\n lines.push(` ${cyan(glyph.bullet)} ${action.kind}`);\n if (action.kind === \"copier.copy.commonproject\") lines.push(` ${dim(`target: ${action.targetDir}`)}`);\n if (action.kind === \"project.write-manifest\") lines.push(` ${dim(`path: ${action.path}`)}`);\n if (action.kind === \"ticket-provider.create-or-link\") {\n const target = [action.provider, action.workspace, action.identifier].filter(Boolean).join(\"/\");\n lines.push(` ${dim(`board: ${target} ${glyph.dot} ${action.boardName}`)}`);\n lines.push(` ${dim(`state: ${action.state}${action.boardId ? ` (${action.boardId})` : \"\"}`)}`);\n if (action.reason) lines.push(` ${dim(`note: ${action.reason}`)}`);\n }\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n/**\n * List projects, newest work first.\n *\n * The old `status` column is gone. It rendered the registry's lifecycle string,\n * which read \"planned\" for 22 of 27 registered projects \u2014 including ones with\n * commits the same day \u2014 so it sorted nothing and told the reader nothing. Its\n * slot now holds real recency.\n *\n * Activity is passed in rather than computed here so this stays a pure\n * formatter, and so the caller can scan the registry concurrently. Projects\n * with no activity entry (a repo_path that no longer exists, of which the live\n * registry has two) sort last and render \"never\".\n */\nexport function formatProjectList(\n registry: ProjectRegistry,\n activityByPath: ReadonlyMap<string, { relative: string; updatedUnix: number | null; active: boolean }> = new Map(),\n): string {\n const ageOf = (project: ProjectRecord) => activityByPath.get(project.repo_path);\n const projects = Object.values(registry.projects).sort((a, b) => {\n const left = ageOf(a)?.updatedUnix ?? -1;\n const right = ageOf(b)?.updatedUnix ?? -1;\n if (left !== right) return right - left;\n return a.slug.localeCompare(b.slug);\n });\n if (!projects.length) return `\\n ${dim(\"No projects registered.\")}\\n`;\n\n const relativeOf = (project: ProjectRecord) => ageOf(project)?.relative ?? \"never\";\n const slugWidth = projects.reduce((width, project) => Math.max(width, project.slug.length), 0);\n const idWidth = projects.reduce((width, project) => Math.max(width, String(project.ticket_provider.identifier ?? \"\").length), 0);\n const ageWidth = projects.reduce((width, project) => Math.max(width, relativeOf(project).length), 0);\n\n const lines = [\"\", ` ${bold(\"Projects\")} ${dim(`(${projects.length})`)} ${dim(\"newest work first\")}`, \"\"];\n for (const project of projects) {\n const activity = ageOf(project);\n const slug = bold(project.slug.padEnd(slugWidth));\n const identifier = cyan(String(project.ticket_provider.identifier ?? \"\").padEnd(idWidth));\n // Pad BEFORE coloring: ANSI escapes are invisible but still count toward\n // String.padEnd's length, so padding a colored string misaligns the column.\n const padded = relativeOf(project).padEnd(ageWidth);\n const age = activity?.active ? green(padded) : activity?.updatedUnix ? yellow(padded) : dim(padded);\n lines.push(` ${slug} ${identifier} ${age} ${dim(project.repo_path)}`);\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n/**\n * Did a provider actually confirm this board?\n *\n * The registry's three-field contract answers this and nothing else does:\n * `board_id` is a claim, `board_confirmed_at` is the provider's answer, and\n * `state: \"linked\"` is the two agreeing. A record missing any of them is a\n * project whose board does not exist as far as anything downstream can tell.\n */\nexport function isBoardConfirmed(provider: ProjectTicketProvider | undefined): boolean {\n return Boolean(provider?.board_id && provider.board_confirmed_at && provider.state === \"linked\");\n}\n\n/** What `pj init` promised about the board, and what it actually delivered. */\nexport interface BoardDelivery {\n /** The plan meant to reach a board (not suppressed by --skip-board). */\n intended: boolean;\n confirmed: boolean;\n provider: string;\n workspace: string;\n identifier: string;\n boardId: string;\n state: string;\n /** Why the board action did not run, when it did not. */\n reason?: string;\n}\n\nexport function boardDelivery(plan: ProjectInitPlan): BoardDelivery {\n const action = plan.actions.find((entry) => entry.kind === \"ticket-provider.create-or-link\");\n const provider = plan.project.ticket_provider;\n return {\n intended: action?.kind === \"ticket-provider.create-or-link\" ? action.enabled : false,\n confirmed: isBoardConfirmed(provider),\n provider: provider.type,\n workspace: provider.workspace ?? \"\",\n identifier: provider.identifier ?? \"\",\n boardId: provider.board_id ?? \"\",\n state: provider.state ?? \"planned\",\n ...(action?.kind === \"ticket-provider.create-or-link\" && action.reason ? { reason: action.reason } : {}),\n };\n}\n\n/**\n * Drop one project from the registry. The repo on disk and the provider board\n * are deliberately left alone \u2014 this removes a REGISTRY RECORD, nothing else.\n */\nexport interface ProjectRemovalResult {\n ok: boolean;\n apply: boolean;\n registryPath: string;\n slug: string;\n removed: ProjectRecord;\n}\n\nexport function removeProjectRecord(input: {\n slug: string;\n apply?: boolean;\n registryPath?: string;\n}): ProjectRemovalResult {\n const registryPath = resolve(\n projectRegistryPath({ ...process.env, [PROJECT_REGISTRY_ENV]: input.registryPath || process.env[PROJECT_REGISTRY_ENV] }),\n );\n const registry = loadProjectRegistry(registryPath);\n // getProject throws \"Project not found in registry: <slug>\" for an unknown\n // slug, which is the refusal this command owes the caller.\n const removed = getProject(registry, input.slug);\n const apply = input.apply ?? false;\n if (apply) {\n delete registry.projects[input.slug];\n saveProjectRegistry(registry, registryPath);\n }\n return { ok: true, apply, registryPath, slug: input.slug, removed };\n}\n\nexport function getProject(registry: ProjectRegistry, slug: string): ProjectRecord {\n const project = getOwnRecordValue(registry.projects, slug);\n if (!project) throw new Error(`Project not found in registry: ${slug}`);\n return project;\n}\n\nexport function doctorProjectRegistry(registryPath = projectRegistryPath(), slug?: string): ProjectDoctorResult {\n const issues: ProjectDoctorResult[\"issues\"] = [];\n const registry = loadProjectRegistry(registryPath);\n const projects = slug ? [[slug, getProject(registry, slug)] as const] : Object.entries(registry.projects);\n for (const [projectSlug, project] of projects) {\n if (!existsSync(project.repo_path)) {\n issues.push({ level: \"warn\", slug: projectSlug, message: `repo_path does not exist: ${project.repo_path}` });\n } else if (!statSync(project.repo_path).isDirectory()) {\n issues.push({ level: \"error\", slug: projectSlug, message: `repo_path is not a directory: ${project.repo_path}` });\n } else {\n const manifestPath = join(project.repo_path, \".project.json\");\n if (!existsSync(manifestPath)) issues.push({ level: \"warn\", slug: projectSlug, message: \".project.json is missing\" });\n }\n for (const artifact of project.source_artifacts) {\n if (artifact.path && !existsSync(artifact.path)) {\n issues.push({ level: \"warn\", slug: projectSlug, message: `source artifact missing: ${artifact.path}` });\n }\n }\n }\n return {\n ok: !issues.some((issue) => issue.level === \"error\"),\n registryPath,\n checkedProjects: projects.map(([projectSlug]) => projectSlug),\n issues,\n };\n}\n\nexport function buildCommonProjectCopierAction(input: {\n pjanglerRoot: string;\n targetDir: string;\n projectName: string;\n projectDescription?: string;\n projectSlug: string;\n ticketProvider: string;\n planeWorkspace: string;\n planeProjectId?: string;\n boardId?: string;\n ticketWorkspace?: string;\n projectIdentifier: string;\n primaryLanguage: string;\n agentHooksLayer?: boolean;\n overwrite: boolean;\n}): Extract<ProjectInitAction, { kind: \"copier.copy.commonproject\" }> {\n const templateDir = join(input.pjanglerRoot, \"templates\", \"commonproject\");\n const data: Record<string, string> = {\n project_name: input.projectName,\n project_description: input.projectDescription ?? \"\",\n project_slug: input.projectSlug,\n ticket_provider: input.ticketProvider,\n plane_workspace: input.planeWorkspace,\n plane_project_id: input.planeProjectId ?? \"\",\n ticket_workspace: input.ticketWorkspace ?? input.planeWorkspace,\n board_id: input.boardId ?? input.planeProjectId ?? \"\",\n project_identifier: input.projectIdentifier,\n primary_language: input.primaryLanguage,\n agent_hooks_layer: (input.agentHooksLayer ?? true) ? \"true\" : \"false\",\n };\n // `--vcs-ref=HEAD` is load-bearing (PJAN-49). Whenever `templates/commonproject`\n // resolves to a git repo *root* \u2014 a standalone clone rather than a submodule\n // gitlink \u2014 copier treats it as a VCS template and, with no ref, checks out the\n // latest PEP440 tag instead of the checked-out commit. Every template change\n // since that tag then silently vanishes from generated projects. Pinning HEAD\n // renders the commit the superproject actually points at, and is a no-op when\n // the template is a plain directory. Same treatment as the hermes-agent\n // template in src/commands/hermes/RunCopierTemplate.ts.\n const command = [\"copier\", \"copy\", \"--trust\", \"--vcs-ref=HEAD\", templateDir, input.targetDir, \"--defaults\"];\n for (const [key, value] of Object.entries(data)) command.push(\"--data\", `${key}=${value}`);\n if (input.overwrite) command.push(\"--overwrite\");\n return {\n kind: \"copier.copy.commonproject\",\n cwd: input.pjanglerRoot,\n command,\n targetDir: input.targetDir,\n data,\n overwrite: input.overwrite,\n };\n}\n\nexport function resolvePjanglerRoot(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n while (dir !== dirname(dir)) {\n if (existsSync(join(dir, \"package.json\")) && existsSync(join(dir, \"templates\", \"commonproject\", \"copier.yml\"))) return dir;\n dir = dirname(dir);\n }\n return resolve(process.cwd());\n}\n\nfunction validateNoDuplicateProject(registry: ProjectRegistry, project: ProjectRecord, overwrite: boolean): void {\n const existingSameSlug = getOwnRecordValue(registry.projects, project.slug);\n if (existingSameSlug && !overwrite && resolve(existingSameSlug.repo_path) !== resolve(project.repo_path)) {\n throw new Error(`Project slug already exists in registry: ${project.slug}`);\n }\n for (const [slug, existing] of Object.entries(registry.projects)) {\n if (slug === project.slug) continue;\n if (resolve(existing.repo_path) === resolve(project.repo_path)) {\n throw new Error(`Project repo_path already registered by ${slug}: ${project.repo_path}`);\n }\n if (ticketProviderScope(existing.ticket_provider) !== ticketProviderScope(project.ticket_provider)) continue;\n if (existing.ticket_provider.board_id?.trim() && existing.ticket_provider.board_id === project.ticket_provider.board_id) {\n throw new Error(`Project board_id already registered by ${slug}: ${project.ticket_provider.board_id}`);\n }\n if (existing.ticket_provider.identifier && existing.ticket_provider.identifier.toUpperCase() === project.ticket_provider.identifier?.toUpperCase()) {\n throw new Error(`Project identifier already registered by ${slug}: ${project.ticket_provider.identifier}`);\n }\n }\n}\n\nfunction validateProjectRecord(project: ProjectRecord, key: string): void {\n validateSafePathSegment(key, `Project registry key ${key}`);\n if (!isRecord(project)) throw new Error(`Project ${key} must be a mapping`);\n if (!project.name) throw new Error(`Project ${key} missing name`);\n if (!project.slug) throw new Error(`Project ${key} missing slug`);\n validateSafePathSegment(project.slug, `Project ${key} slug`);\n if (project.slug !== key) throw new Error(`Project key ${key} does not match slug ${project.slug}`);\n if (!project.repo_path) throw new Error(`Project ${key} missing repo_path`);\n if (!Array.isArray(project.source_artifacts)) throw new Error(`Project ${key} source_artifacts must be a list`);\n if (!isRecord(project.ticket_provider)) throw new Error(`Project ${key} ticket_provider must be a mapping`);\n const provider = project.ticket_provider as ProjectTicketProvider;\n // R1\n if (provider.state !== undefined && !(TICKET_PROVIDER_STATES as readonly string[]).includes(provider.state)) {\n throw new Error(`Project ${key} ticket_provider.state must be one of ${TICKET_PROVIDER_STATES.join(\" | \")}; got ${JSON.stringify(provider.state)}`);\n }\n // R2\n if (provider.identifier_source !== undefined && !(PROJECT_IDENTIFIER_SOURCES as readonly string[]).includes(provider.identifier_source)) {\n throw new Error(`Project ${key} ticket_provider.identifier_source must be one of ${PROJECT_IDENTIFIER_SOURCES.join(\" | \")}; got ${JSON.stringify(provider.identifier_source)}`);\n }\n // R3 \u2014 BOARD-binding provenance. \"linked\" means the provider confirmed this\n // board exists, and nothing else. That is a question every provider can\n // answer, including one that assigns no identifiers at all.\n if (provider.state === \"linked\" && !(provider.board_id && provider.board_confirmed_at)) {\n throw new Error(\n `Project ${key} ticket_provider.state is \"linked\" but its board binding is not provider-confirmed ` +\n `(board_id=${JSON.stringify(provider.board_id ?? \"\")}, ` +\n `board_confirmed_at=${JSON.stringify(provider.board_confirmed_at ?? \"\")}). Run \\`${IDENTIFIER_REPAIR_COMMAND}\\`.`\n );\n }\n // R3a \u2014 IDENTIFIER provenance, which is a separate claim. Saying the provider\n // assigned this key requires a key and the instant it was read back.\n if (provider.identifier_source === \"provider\" && !(provider.identifier && provider.identifier_fetched_at)) {\n throw new Error(\n `Project ${key} ticket_provider.identifier_source is \"provider\" but no identifier was read back ` +\n `(identifier=${JSON.stringify(provider.identifier ?? \"\")}, ` +\n `identifier_fetched_at=${JSON.stringify(provider.identifier_fetched_at ?? \"\")}). Run \\`${IDENTIFIER_REPAIR_COMMAND}\\`.`\n );\n }\n // R3b \u2014 and where the provider DOES assign identifiers, a link must carry the\n // one it assigned. This is the original invariant, now scoped to the\n // providers it is actually true of: a Plane board key routes live webhook\n // traffic, so a guess wearing \"linked\" is the whole defect.\n if (provider.state === \"linked\" && providerAssignsIdentifiers(provider.type) && provider.identifier_source !== \"provider\") {\n throw new Error(\n `Project ${key} ticket_provider.state is \"linked\" on ${provider.type}, which assigns its own identifiers, ` +\n `but identifier_source=${JSON.stringify(provider.identifier_source ?? \"\")} ` +\n `(identifier=${JSON.stringify(provider.identifier ?? \"\")}). Run \\`${IDENTIFIER_REPAIR_COMMAND}\\`.`\n );\n }\n if (!isRecord(project.agents)) throw new Error(`Project ${key} agents must be a mapping`);\n if (project.notebook !== undefined) {\n if (!isRecord(project.notebook)) throw new Error(`Project ${key} notebook must be a mapping`);\n const credentialPath = notebookCredentialMaterialPath(project.notebook);\n if (credentialPath) throw new Error(`Project ${key} Notebook binding contains forbidden credential material at ${credentialPath}`);\n if (project.notebook.state !== \"disabled\" && project.notebook.state !== \"planned\" && project.notebook.state !== \"linked\") throw new Error(`Project ${key} notebook state is invalid`);\n if (project.notebook.state === \"linked\" && (!project.notebook.notebook_id || !project.notebook.overview_note_id)) throw new Error(`Project ${key} linked notebook is missing stable IDs`);\n for (const field of [\"notebook_id\", \"notebook_name\", \"overview_note_id\", \"blocked_reason\"] as const) {\n const value = project.notebook[field];\n if (value !== undefined && (typeof value !== \"string\" || value.length === 0 || Buffer.byteLength(value, \"utf8\") > 512 || /[\\u0000-\\u001f\\u007f]/u.test(value))) throw new Error(`Project ${key} notebook.${field} is invalid`);\n }\n }\n for (const [agentKey, agent] of Object.entries(project.agents)) {\n validateSafePathSegment(agentKey, `Project ${key} agent key ${agentKey}`);\n if (!isRecord(agent)) throw new Error(`Project ${key} agent ${agentKey} must be a mapping`);\n if (typeof agent.role !== \"string\" || !agent.role) throw new Error(`Project ${key} agent ${agentKey} missing role`);\n validateSafePathSegment(agent.role, `Project ${key} agent ${agentKey} role`);\n }\n}\n\nfunction expandHome(path: string): string {\n if (path === \"~\") return homedir();\n if (path.startsWith(\"~/\")) return join(homedir(), path.slice(2));\n return path;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { isIP } from \"node:net\";\nimport { closeSync, existsSync, fchmodSync, fsyncSync, lstatSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport {\n getOwnRecordValue,\n loadProjectRegistry,\n projectRegistryPath,\n saveProjectRegistry,\n type ProjectManifest,\n type ProjectRecord,\n type ProjectRegistry,\n} from \"../project/index\";\nimport {\n DEFAULT_NOTEBOOK_LIMITS,\n NOTEBOOK_SCHEMA_VERSION,\n NotebookError,\n notebookCredentialMaterialPath,\n type EffectiveNotebookConfigV1,\n type NotebookAuthConfigV1,\n type NotebookGlobalConfigV1,\n type NotebookLimitsV1,\n type NotebookPolicyV1,\n type ProjectNotebookBindingV1,\n type ProjectNotebookConfigV1,\n} from \"./types\";\n\nconst DEFAULT_POLICY: Readonly<NotebookPolicyV1> = Object.freeze({\n enabled: true,\n session_start_enabled: false,\n session_capture_enabled: false,\n overview_max_chars: 4_000,\n documentation_globs: [\"**/*.md\", \"**/*.mdx\"],\n});\n\nexport interface ResolvedNotebookProjectV1 {\n registry: ProjectRegistry;\n project: ProjectRecord;\n manifest: ProjectManifest | null;\n registry_path: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction realOrResolved(path: string): string {\n const absolute = resolve(path);\n return existsSync(absolute) ? realpathSync(absolute) : absolute;\n}\n\nfunction readManifest(repoPath: string): ProjectManifest | null {\n const path = resolve(repoPath, \".project.json\");\n if (!existsSync(path)) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(path, \"utf8\")) as unknown;\n } catch {\n throw new NotebookError(\"INVALID_INPUT\", `${path} is not valid JSON`);\n }\n if (!isRecord(parsed)) return null;\n validateManifestNotebookSurface(parsed.notebook);\n return parsed as unknown as ProjectManifest;\n}\n\nconst MANIFEST_NOTEBOOK_KEYS = new Set([\"binding\", \"policy\", \"display_name\"]);\nconst MANIFEST_POLICY_KEYS = new Set([\"enabled\", \"session_start_enabled\", \"session_capture_enabled\", \"overview_max_chars\", \"documentation_globs\", \"overview_references\", \"excluded_globs\"]);\n\nfunction validateManifestNotebookSurface(value: unknown): void {\n if (value === undefined) return;\n if (!isRecord(value)) throw new NotebookError(\"NOT_CONFIGURED\", \"Manifest notebook must be a mapping\");\n const credentialPath = notebookCredentialMaterialPath(value);\n if (credentialPath) throw new NotebookError(\"NOT_CONFIGURED\", `Manifest Notebook configuration contains forbidden credential material at ${credentialPath}`);\n for (const key of Object.keys(value)) {\n if (!MANIFEST_NOTEBOOK_KEYS.has(key) && !key.startsWith(\"x_\")) {\n throw new NotebookError(\"NOT_CONFIGURED\", `Manifest notebook.${key} is not an allowed policy or binding projection field`);\n }\n }\n if (value.binding !== undefined && !isRecord(value.binding)) throw new NotebookError(\"NOT_CONFIGURED\", \"Manifest notebook.binding must be a mapping\");\n if (value.policy !== undefined) {\n if (!isRecord(value.policy)) throw new NotebookError(\"NOT_CONFIGURED\", \"Manifest notebook.policy must be a mapping\");\n for (const key of Object.keys(value.policy)) {\n if (!MANIFEST_POLICY_KEYS.has(key) && !key.startsWith(\"x_\")) throw new NotebookError(\"NOT_CONFIGURED\", `Manifest notebook.policy.${key} is not an allowed policy field`);\n }\n }\n}\n\nexport function resolveNotebookProject(repoArg = process.cwd(), registryFile = projectRegistryPath()): ResolvedNotebookProjectV1 {\n const registry = loadProjectRegistry(registryFile);\n const requested = realOrResolved(repoArg);\n const matches = Object.values(registry.projects).filter((project) => realOrResolved(project.repo_path) === requested);\n if (matches.length === 0) throw new NotebookError(\"NOT_FOUND\", `Repository is not registered: ${requested}`);\n if (matches.length > 1) throw new NotebookError(\"CONFLICT\", `More than one Registry project maps to repository: ${requested}`);\n const project = matches[0]!;\n return { registry, project, manifest: readManifest(project.repo_path), registry_path: registryFile };\n}\n\nexport function resolveNotebookProjectBySlug(projectSlug: string, registryFile = projectRegistryPath()): ResolvedNotebookProjectV1 {\n const registry = loadProjectRegistry(registryFile);\n const project = getOwnRecordValue(registry.projects, projectSlug);\n if (!project) throw new NotebookError(\"NOT_FOUND\", `Project is not registered: ${projectSlug}`);\n return { registry, project, manifest: readManifest(project.repo_path), registry_path: registryFile };\n}\n\nexport function validateNotebookBaseUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new NotebookError(\"NOT_CONFIGURED\", \"Notebook base_url must be an absolute URL\");\n }\n if (url.username || url.password || url.search || url.hash) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"Notebook base_url may not contain credentials, query parameters, or a fragment\");\n }\n const hostname = url.hostname.toLowerCase();\n const unbracketed = hostname.startsWith(\"[\") && hostname.endsWith(\"]\") ? hostname.slice(1, -1) : hostname;\n const loopback = hostname === \"localhost\" || unbracketed === \"::1\" || /^127(?:\\.\\d{1,3}){3}$/u.test(unbracketed);\n if (isIP(unbracketed) !== 0 && !loopback) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"Notebook base_url may not use a numeric non-loopback host\");\n }\n if (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && loopback)) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"Notebook base_url must use HTTPS or loopback HTTP\");\n }\n url.pathname = url.pathname.replace(/\\/+$/u, \"\");\n return url.toString().replace(/\\/$/u, \"\");\n}\n\nexport function validateNotebookAuth(value: unknown): NotebookAuthConfigV1 {\n if (value == null) return { mode: \"none\" };\n if (!isRecord(value) || (value.mode !== \"none\" && value.mode !== \"environment\")) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"Notebook auth.mode must be none or environment\");\n }\n if (value.mode === \"none\") return { mode: \"none\" };\n if (typeof value.env_var !== \"string\" || !/^[A-Z_][A-Z0-9_]{0,127}$/u.test(value.env_var)) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"Notebook auth.env_var must be a safe environment variable name\");\n }\n // The canonical global hook wrappers deliberately forward only this one\n // allowlisted credential. Accepting another name here would make the CLI\n // appear configured while SessionStart/SessionEnd silently lacked auth.\n if (value.env_var !== \"OPEN_NOTEBOOK_PASSWORD\") {\n throw new NotebookError(\"NOT_CONFIGURED\", \"Notebook hooks support only auth.env_var OPEN_NOTEBOOK_PASSWORD\");\n }\n return { mode: \"environment\", env_var: \"OPEN_NOTEBOOK_PASSWORD\" };\n}\n\nfunction positiveInteger(value: unknown, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (!Number.isSafeInteger(value) || Number(value) <= 0) throw new NotebookError(\"NOT_CONFIGURED\", `Notebook limit ${name} must be a finite positive integer`);\n return Number(value);\n}\n\nexport function resolveNotebookLimits(overrides: Partial<NotebookLimitsV1> = {}): NotebookLimitsV1 {\n const result = { ...DEFAULT_NOTEBOOK_LIMITS } as NotebookLimitsV1;\n for (const key of Object.keys(DEFAULT_NOTEBOOK_LIMITS) as Array<keyof NotebookLimitsV1>) {\n if (key === \"schema_version\") continue;\n result[key] = positiveInteger(overrides[key], DEFAULT_NOTEBOOK_LIMITS[key], key) as never;\n }\n result.schema_version = NOTEBOOK_SCHEMA_VERSION;\n if (result.receipt_max_bytes > result.unresolved_receipt_max_bytes) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"receipt_max_bytes may not exceed unresolved_receipt_max_bytes\");\n }\n if (result.hook_payload_max_bytes > DEFAULT_NOTEBOOK_LIMITS.hook_payload_max_bytes) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"hook_payload_max_bytes may tighten but not exceed the packaged absolute ceiling\");\n }\n if (result.note_detail_fetch_concurrency > DEFAULT_NOTEBOOK_LIMITS.note_detail_fetch_concurrency) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"note_detail_fetch_concurrency may tighten but not exceed the packaged fanout ceiling\");\n }\n if (result.lease_seconds * 1_000 <= result.overall_timeout_ms) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"lease_seconds must exceed one bounded remote request timeout so workers can renew without overlap\");\n }\n return result;\n}\n\nfunction stringList(value: unknown, fallback: string[], name: string): string[] {\n if (value === undefined) return [...fallback];\n if (!Array.isArray(value) || value.length > 100 || value.some((entry) => typeof entry !== \"string\" || entry.length === 0 || Buffer.byteLength(entry, \"utf8\") > 512)) {\n throw new NotebookError(\"NOT_CONFIGURED\", `Notebook policy ${name} must be a bounded string list`);\n }\n return [...value];\n}\n\nfunction resolvePolicy(globalDefaults: unknown, manifestPolicy: unknown, limits: NotebookLimitsV1): NotebookPolicyV1 {\n const global = isRecord(globalDefaults) ? globalDefaults : {};\n const local = isRecord(manifestPolicy) ? manifestPolicy : {};\n const pick = (key: string): unknown => Object.hasOwn(local, key) ? local[key] : global[key];\n const boolean = (key: string, fallback: boolean): boolean => {\n const value = pick(key);\n if (value === undefined) return fallback;\n if (typeof value !== \"boolean\") throw new NotebookError(\"NOT_CONFIGURED\", `Notebook policy ${key} must be boolean`);\n return value;\n };\n const overview = positiveInteger(pick(\"overview_max_chars\"), limits.overview_max_chars, \"overview_max_chars\");\n if (overview > limits.note_max_bytes) throw new NotebookError(\"NOT_CONFIGURED\", \"overview_max_chars exceeds the note ceiling\");\n return {\n enabled: boolean(\"enabled\", DEFAULT_POLICY.enabled),\n session_start_enabled: boolean(\"session_start_enabled\", DEFAULT_POLICY.session_start_enabled),\n session_capture_enabled: boolean(\"session_capture_enabled\", DEFAULT_POLICY.session_capture_enabled),\n overview_max_chars: overview,\n documentation_globs: stringList(pick(\"documentation_globs\"), [...DEFAULT_POLICY.documentation_globs], \"documentation_globs\"),\n ...(pick(\"overview_references\") !== undefined\n ? { overview_references: stringList(pick(\"overview_references\"), [], \"overview_references\") }\n : {}),\n ...(pick(\"excluded_globs\") !== undefined\n ? { excluded_globs: stringList(pick(\"excluded_globs\"), [], \"excluded_globs\") }\n : {}),\n };\n}\n\nfunction projectNotebook(project: ProjectRecord): ProjectNotebookConfigV1 {\n const raw = (project as ProjectRecord & { notebook?: unknown }).notebook;\n if (!isRecord(raw)) return { binding: { state: \"disabled\" }, policy: { enabled: false } };\n const bindingRaw = isRecord(raw.binding) ? raw.binding : raw;\n const state = bindingRaw.state;\n if (state !== \"disabled\" && state !== \"planned\" && state !== \"linked\") {\n throw new NotebookError(\"NOT_CONFIGURED\", `Project ${project.slug} notebook binding state is invalid`);\n }\n const binding: ProjectNotebookBindingV1 = { ...bindingRaw, state } as ProjectNotebookBindingV1;\n for (const key of [\"notebook_id\", \"notebook_name\", \"overview_note_id\", \"blocked_reason\"] as const) {\n if (binding[key] !== undefined && (typeof binding[key] !== \"string\" || binding[key]!.length > 512)) {\n throw new NotebookError(\"NOT_CONFIGURED\", `Project ${project.slug} notebook.${key} is invalid`);\n }\n }\n return { ...raw, binding, policy: isRecord(raw.policy) ? raw.policy as Partial<NotebookPolicyV1> : undefined };\n}\n\nfunction manifestNotebookPolicy(manifest: ProjectManifest | null): unknown {\n if (!manifest) return undefined;\n const notebook = (manifest as ProjectManifest & { notebook?: unknown }).notebook;\n return isRecord(notebook) ? notebook.policy : undefined;\n}\n\nexport function notebookDisplayName(resolved: ResolvedNotebookProjectV1): string {\n const raw = resolved.manifest && (resolved.manifest as ProjectManifest & { notebook?: unknown }).notebook;\n const override = isRecord(raw) ? raw.display_name : undefined;\n if (override !== undefined) {\n if (typeof override !== \"string\" || !override.trim() || override.length > 512 || /[\\u0000-\\u001f\\u007f]/u.test(override)) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"Manifest notebook.display_name must be a bounded display name without control characters\");\n }\n return override.trim();\n }\n if (!resolved.project.name.trim() || resolved.project.name.length > 512 || /[\\u0000-\\u001f\\u007f]/u.test(resolved.project.name)) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"Project name cannot supply a safe Companion Notebook display name\");\n }\n return resolved.project.name.trim();\n}\n\nexport function resolveEffectiveNotebookConfig(resolved: ResolvedNotebookProjectV1): EffectiveNotebookConfigV1 {\n const globalRaw = (resolved.registry as ProjectRegistry & { notebook?: unknown }).notebook;\n const global = isRecord(globalRaw) ? globalRaw as NotebookGlobalConfigV1 : {};\n const project = projectNotebook(resolved.project);\n const limits = resolveNotebookLimits(isRecord(global.limits) ? global.limits as Partial<NotebookLimitsV1> : {});\n const declared = isRecord((resolved.project as ProjectRecord & { notebook?: unknown }).notebook);\n const localPolicy = manifestNotebookPolicy(resolved.manifest);\n const resolvedPolicy = resolvePolicy(global.defaults, localPolicy, limits);\n const policy = declared ? resolvedPolicy : { ...resolvedPolicy, enabled: false };\n const baseUrl = typeof global.base_url === \"string\" && global.base_url.trim() ? validateNotebookBaseUrl(global.base_url) : null;\n const auth = validateNotebookAuth(global.auth);\n let summarizer: { executable: string; args: string[] } | undefined;\n if (global.summarizer !== undefined) {\n if (!isRecord(global.summarizer) || typeof global.summarizer.executable !== \"string\"\n || !global.summarizer.executable.startsWith(\"/\") || global.summarizer.executable.includes(\"\\0\")\n || Buffer.byteLength(global.summarizer.executable, \"utf8\") > 1_024) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"Notebook summarizer executable must be a bounded absolute path\");\n }\n const rawArgs = global.summarizer.args ?? [];\n if (!Array.isArray(rawArgs) || rawArgs.length > 32\n || rawArgs.some((item) => typeof item !== \"string\" || item.includes(\"\\0\") || Buffer.byteLength(item, \"utf8\") > 1_024)) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"Notebook summarizer argv must be a bounded string list\");\n }\n summarizer = { executable: global.summarizer.executable, args: [...rawArgs] as string[] };\n }\n return {\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n project_slug: resolved.project.slug,\n repo_path: realOrResolved(resolved.project.repo_path),\n base_url: baseUrl,\n auth,\n policy,\n limits,\n binding: project.binding,\n configuration_provenance: {\n base_url: baseUrl ? \"registry-global\" : \"default\",\n auth: global.auth ? \"registry-global\" : \"default\",\n policy: localPolicy ? \"manifest-policy\" : global.defaults ? \"registry-global\" : \"default\",\n binding: \"project-registry\",\n limits: global.limits ? \"registry-global\" : \"default\",\n },\n ...(summarizer ? { summarizer } : {}),\n };\n}\n\nexport function loadEffectiveNotebookConfig(repoArg = process.cwd(), registryFile = projectRegistryPath()): EffectiveNotebookConfigV1 {\n return resolveEffectiveNotebookConfig(resolveNotebookProject(repoArg, registryFile));\n}\n\nexport function runtimeNotebookCredential(config: EffectiveNotebookConfigV1, env: NodeJS.ProcessEnv = process.env): string | undefined {\n if (config.auth.mode !== \"environment\") return undefined;\n const value = env[config.auth.env_var!];\n if (!value) throw new NotebookError(\"NOT_CONFIGURED\", `Notebook auth environment variable ${config.auth.env_var} is not set`);\n return value;\n}\n\nexport function requireRemoteNotebookConfig(config: EffectiveNotebookConfigV1): string {\n if (!config.policy.enabled) throw new NotebookError(\"NOT_CONFIGURED\", \"Project Notebook is disabled for this repository\");\n if (!config.base_url) throw new NotebookError(\"NOT_CONFIGURED\", \"Notebook base_url is not configured\");\n return config.base_url;\n}\n\nexport function registryProjectBySlug(registry: ProjectRegistry, slug: string): ProjectRecord {\n const project = getOwnRecordValue(registry.projects, slug);\n if (!project) throw new NotebookError(\"NOT_FOUND\", `Project is not registered: ${slug}`);\n return project;\n}\n\nexport function persistProjectNotebookBinding(\n resolved: ResolvedNotebookProjectV1,\n binding: ProjectNotebookBindingV1,\n policy?: Partial<NotebookPolicyV1>,\n): string[] {\n const changed: string[] = [];\n const manifestPath = resolve(resolved.project.repo_path, \".project.json\");\n const manifestRaw = existsSync(manifestPath)\n ? JSON.parse(readFileSync(manifestPath, \"utf8\")) as Record<string, unknown>\n : {};\n if (!isRecord(manifestRaw)) throw new NotebookError(\"INVALID_INPUT\", `${manifestPath} must contain a JSON object`);\n validateManifestNotebookSurface(manifestRaw.notebook);\n const manifestNotebook = isRecord(manifestRaw.notebook) ? manifestRaw.notebook : {};\n const previousBinding = isRecord(manifestNotebook.binding) ? manifestNotebook.binding : {};\n const foreignBinding = Object.fromEntries(Object.entries(previousBinding).filter(([key]) => ![\"state\", \"notebook_id\", \"notebook_name\", \"overview_note_id\", \"blocked_reason\"].includes(key)));\n const previousPolicy = isRecord(manifestNotebook.policy) ? manifestNotebook.policy : {};\n const manifestNext = {\n ...manifestRaw,\n notebook: {\n ...manifestNotebook,\n binding: { ...foreignBinding, ...binding },\n ...(policy ? { policy: { ...previousPolicy, ...policy } } : {}),\n },\n };\n const manifestText = `${JSON.stringify(manifestNext, null, 2)}\\n`;\n if (!existsSync(manifestPath) || readFileSync(manifestPath, \"utf8\") !== manifestText) {\n let mode = 0o644;\n if (existsSync(manifestPath)) {\n const current = lstatSync(manifestPath);\n if (!current.isFile() || current.isSymbolicLink()) throw new NotebookError(\"CONFLICT\", `${manifestPath} must be a regular non-symlink file`);\n mode = current.mode & 0o777;\n }\n const temp = resolve(dirname(manifestPath), `.${process.pid}.${randomUUID()}.project.json.tmp`);\n const fd = openSync(temp, \"wx\", mode);\n try {\n writeFileSync(fd, manifestText, \"utf8\");\n fchmodSync(fd, mode);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n renameSync(temp, manifestPath);\n try {\n const directory = openSync(dirname(manifestPath), \"r\");\n try { fsyncSync(directory); } finally { closeSync(directory); }\n } catch { /* directory fsync is not portable; file fsync remains enforced */ }\n changed.push(manifestPath);\n }\n\n const current = (resolved.project as ProjectRecord & { notebook?: unknown }).notebook;\n resolved.project.notebook = { ...(isRecord(current) ? current : { state: \"planned\" }), ...binding } as ProjectNotebookBindingV1;\n const registryBefore = existsSync(resolved.registry_path) ? readFileSync(resolved.registry_path, \"utf8\") : null;\n saveProjectRegistry(resolved.registry, resolved.registry_path);\n const registryAfter = existsSync(resolved.registry_path) ? readFileSync(resolved.registry_path, \"utf8\") : null;\n if (registryBefore !== registryAfter) changed.push(resolved.registry_path);\n return changed;\n}\n\nexport function persistProjectNotebookDeclaration(resolved: ResolvedNotebookProjectV1): string[] {\n const current = (resolved.project as ProjectRecord & { notebook?: unknown }).notebook;\n const binding: ProjectNotebookBindingV1 = isRecord(current)\n ? projectNotebook(resolved.project).binding\n : { state: \"planned\", notebook_name: resolved.project.name };\n return persistProjectNotebookBinding(resolved, binding, {\n enabled: true,\n session_start_enabled: false,\n session_capture_enabled: false,\n });\n}\n", "import { createHash, randomUUID } from \"node:crypto\";\nimport {\n NOTEBOOK_SCHEMA_VERSION,\n NotebookError,\n type NoteDetailV1,\n type NoteSummaryV1,\n type OpenNotebookNoteV1,\n type PjanglerNoteEnvelopeV1,\n} from \"./types\";\n\nexport const NOTE_ENVELOPE_PREFIX = \"<!-- pjangler-note-v1:\";\nconst NOTE_ENVELOPE_RE = /^<!-- pjangler-note-v1:([A-Za-z0-9_-]+) -->\\r?\\n/;\n\nexport function canonicalJson(value: unknown): string {\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\" || typeof value === \"bigint\") throw new NotebookError(\"INVALID_INPUT\", \"Canonical JSON value is not JSON-compatible\");\n if (value === null || typeof value !== \"object\") {\n const encoded = JSON.stringify(value);\n if (encoded === undefined) throw new NotebookError(\"INVALID_INPUT\", \"Canonical JSON value is not serializable\");\n return encoded;\n }\n if (Array.isArray(value)) return `[${value.map((item) => item === undefined ? \"null\" : canonicalJson(item)).join(\",\")}]`;\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record).filter((key) => record[key] !== undefined).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(\",\")}}`;\n}\n\nexport function sha256Hex(value: string | Uint8Array): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nexport function base64UrlEncode(value: string): string {\n return Buffer.from(value, \"utf8\").toString(\"base64url\");\n}\n\nexport function encodeNoteEnvelope(envelope: PjanglerNoteEnvelopeV1): string {\n validateNoteEnvelope(envelope);\n return `${NOTE_ENVELOPE_PREFIX}${base64UrlEncode(canonicalJson(envelope))} -->`;\n}\n\nexport function withNoteEnvelope(envelope: PjanglerNoteEnvelopeV1, body: string): string {\n return `${encodeNoteEnvelope(envelope)}\\n${body}`;\n}\n\nexport function parseNoteEnvelope(content: string, maxBytes = 16_384): { envelope: PjanglerNoteEnvelopeV1; body: string } | null {\n const firstNewline = content.indexOf(\"\\n\");\n const prefixBytes = Buffer.byteLength(firstNewline >= 0 ? content.slice(0, firstNewline + 1) : content, \"utf8\");\n if (prefixBytes > maxBytes) return null;\n const match = NOTE_ENVELOPE_RE.exec(content);\n if (!match) return null;\n try {\n const decoded = Buffer.from(match[1]!, \"base64url\").toString(\"utf8\");\n if (Buffer.byteLength(decoded, \"utf8\") > maxBytes) return null;\n const parsed = JSON.parse(decoded) as unknown;\n validateNoteEnvelope(parsed);\n return { envelope: parsed, body: content.slice(match[0].length) };\n } catch {\n return null;\n }\n}\n\nexport function validateNoteEnvelope(value: unknown): asserts value is PjanglerNoteEnvelopeV1 {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Invalid PJangler note envelope\");\n const envelope = value as Partial<PjanglerNoteEnvelopeV1>;\n if (envelope.schema_version !== NOTEBOOK_SCHEMA_VERSION) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Unsupported PJangler note envelope version\");\n if (!isBoundedString(envelope.project_slug, 128) || !isBoundedString(envelope.logical_id, 256)) {\n throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Invalid PJangler note identity\");\n }\n if (!([\"overview\", \"user-note\", \"document\", \"session-capture\"] as const).includes(envelope.kind as never)) {\n throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Invalid PJangler note kind\");\n }\n const allowed = new Set([\"schema_version\", \"project_slug\", \"kind\", \"logical_id\", \"source_path\", \"source_revision\", \"content_sha256\", \"session_key\", \"captured_at\", \"policy_version\", \"overview_descriptor\"]);\n if (Object.keys(value as Record<string, unknown>).some((key) => !allowed.has(key))) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"PJangler note envelope contains an unknown field\");\n if (envelope.source_path !== undefined && (!isBoundedString(envelope.source_path, 1_024) || envelope.source_path.startsWith(\"/\") || envelope.source_path.includes(\"\\0\") || envelope.source_path.split(/[\\\\/]/u).includes(\"..\"))) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Invalid PJangler source path\");\n if (envelope.source_revision !== undefined && !isBoundedString(envelope.source_revision, 256)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Invalid PJangler source revision\");\n for (const [name, digest] of [[\"content_sha256\", envelope.content_sha256], [\"session_key\", envelope.session_key]] as const) {\n if (digest !== undefined && !/^[a-f0-9]{64}$/u.test(digest)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", `Invalid PJangler ${name}`);\n }\n if (envelope.captured_at !== undefined && (typeof envelope.captured_at !== \"string\" || !Number.isFinite(Date.parse(envelope.captured_at)))) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Invalid PJangler capture timestamp\");\n if (envelope.policy_version !== undefined && !isBoundedString(envelope.policy_version, 128)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Invalid PJangler policy version\");\n if (envelope.kind === \"overview\") {\n if (envelope.logical_id !== overviewLogicalId(envelope.project_slug)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Overview logical ID does not match project slug\");\n validateOverviewDescriptor(envelope.overview_descriptor, envelope.project_slug);\n } else if (envelope.overview_descriptor !== undefined) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Only Overview notes may carry an Overview descriptor\");\n if (envelope.kind === \"user-note\" && !/^user-note:v1:[a-f0-9-]{16,64}$/iu.test(envelope.logical_id)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Invalid user-note logical ID\");\n if ((envelope.kind === \"document\" || envelope.kind === \"session-capture\") && !/^[a-f0-9]{64}$/u.test(envelope.logical_id)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Invalid managed note logical ID\");\n if (envelope.kind === \"document\" && (!envelope.source_path || !envelope.source_revision || !envelope.content_sha256 || !envelope.session_key || !envelope.captured_at || !envelope.policy_version)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Document envelope is missing required provenance\");\n if (envelope.kind === \"session-capture\" && (!envelope.content_sha256 || !envelope.session_key || !envelope.captured_at || !envelope.policy_version)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Session capture envelope is missing required provenance\");\n}\n\nfunction isBoundedString(value: unknown, max: number): value is string {\n return typeof value === \"string\" && value.length > 0 && value.length <= max;\n}\n\nfunction validateOverviewDescriptor(value: unknown, projectSlug: string): void {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Overview descriptor is missing or invalid\");\n const descriptor = value as Record<string, unknown>;\n const allowed = new Set([\"schema_version\", \"project_slug\", \"project_name\", \"purpose\", \"references\", \"compiler_policy_version\"]);\n if (Object.keys(descriptor).some((key) => !allowed.has(key)) || descriptor.schema_version !== 1 || descriptor.project_slug !== projectSlug\n || !isBoundedString(descriptor.project_name, 256) || !isBoundedString(descriptor.purpose, 4_000)\n || !isBoundedString(descriptor.compiler_policy_version, 128) || !Array.isArray(descriptor.references) || descriptor.references.length > 100) {\n throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Overview descriptor shape is invalid\");\n }\n const paths = new Set<string>();\n for (const referenceValue of descriptor.references) {\n if (!referenceValue || typeof referenceValue !== \"object\" || Array.isArray(referenceValue)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Overview reference is invalid\");\n const reference = referenceValue as Record<string, unknown>;\n const referenceAllowed = new Set([\"path\", \"status\", \"git_revision\", \"content_sha256\", \"reason\"]);\n if (Object.keys(reference).some((key) => !referenceAllowed.has(key)) || !isBoundedString(reference.path, 1_024)\n || String(reference.path).startsWith(\"/\") || String(reference.path).split(/[\\\\/]/u).includes(\"..\") || paths.has(String(reference.path))\n || (reference.status !== \"present\" && reference.status !== \"missing\")) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Overview reference shape is invalid\");\n paths.add(String(reference.path));\n if (reference.status === \"present\") {\n if (!isBoundedString(reference.git_revision, 256) || !/^[a-f0-9]{64}$/u.test(String(reference.content_sha256 ?? \"\")) || reference.reason !== undefined) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Present Overview reference provenance is invalid\");\n } else if (!isBoundedString(reference.reason, 128) || reference.git_revision !== undefined || reference.content_sha256 !== undefined) {\n throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Missing Overview reference provenance is invalid\");\n }\n }\n}\n\nexport function userNoteLogicalId(operationId: string = randomUUID()): string {\n return `user-note:v1:${operationId}`;\n}\n\nexport function overviewLogicalId(projectSlug: string): string {\n return `overview:v1:${projectSlug}`;\n}\n\nexport function documentLogicalId(projectSlug: string, sourcePath: string): string {\n return sha256Hex(`pjangler-document-v1\\0${projectSlug}\\0${sourcePath.normalize(\"NFC\")}`);\n}\n\nexport function sessionCaptureLogicalId(sessionKey: string): string {\n return sha256Hex(`pjangler-capture-v1\\0${sessionKey}`);\n}\n\nfunction truncateUtf8(value: string, maxBytes: number): string {\n let used = 0;\n const result: string[] = [];\n for (const point of value) {\n const bytes = Buffer.byteLength(point, \"utf8\");\n if (used + bytes > maxBytes) break;\n result.push(point);\n used += bytes;\n }\n return result.join(\"\");\n}\n\nexport function noteDetail(note: OpenNotebookNoteV1, maxBytes: number): NoteDetailV1 {\n const parsed = parseNoteEnvelope(note.content);\n return {\n id: note.id,\n title: note.title,\n note_type: note.note_type,\n created_at: note.created_at,\n updated_at: note.updated_at,\n content: truncateUtf8(parsed?.body ?? note.content, maxBytes),\n };\n}\n\nexport function noteSummary(note: OpenNotebookNoteV1, excerptMaxChars: number): NoteSummaryV1 {\n const body = parseNoteEnvelope(note.content)?.body ?? note.content;\n const excerpt = Array.from(body.replace(/\\s+/gu, \" \").trim()).slice(0, excerptMaxChars).join(\"\");\n return {\n id: note.id,\n title: note.title,\n note_type: note.note_type,\n created_at: note.created_at,\n updated_at: note.updated_at,\n excerpt,\n };\n}\n\nexport interface LocalSearchResultV1 {\n items: NoteSummaryV1[];\n next_cursor: null;\n query_tokens: string[];\n}\n\nexport function tokenizeSearch(value: string): string[] {\n const tokens = value.normalize(\"NFKC\").toLocaleLowerCase(\"und\").match(/[\\p{L}\\p{N}]+/gu) ?? [];\n return [...new Set(tokens)];\n}\n\nfunction countTokens(haystack: string[], needle: string): number {\n let count = 0;\n for (const token of haystack) if (token === needle) count += 1;\n return count;\n}\n\nexport function searchNotesLocally(notes: readonly OpenNotebookNoteV1[], query: string, limit: number, excerptMaxChars: number): LocalSearchResultV1 {\n const queryTokens = tokenizeSearch(query);\n if (!queryTokens.length) throw new NotebookError(\"INVALID_INPUT\", \"Search query must contain at least one letter or number\");\n if (!Number.isSafeInteger(limit) || limit < 1) throw new NotebookError(\"INVALID_INPUT\", \"Search limit must be a positive integer\");\n\n const scored = notes.flatMap((note) => {\n const body = parseNoteEnvelope(note.content)?.body ?? note.content;\n const titleTokens = tokenizeSearch(note.title);\n const bodyTokens = tokenizeSearch(body);\n if (!queryTokens.every((token) => titleTokens.includes(token) || bodyTokens.includes(token))) return [];\n const score = queryTokens.reduce((sum, token) => sum + (10 * countTokens(titleTokens, token)) + countTokens(bodyTokens, token), 0);\n return [{ note, body, score }];\n });\n\n const timestamp = (value: string | null): number => {\n const parsed = Date.parse(value ?? \"\");\n return Number.isFinite(parsed) ? parsed : 0;\n };\n scored.sort((left, right) =>\n right.score - left.score\n || timestamp(right.note.updated_at) - timestamp(left.note.updated_at)\n || left.note.id.localeCompare(right.note.id, \"en\"));\n\n return {\n items: scored.slice(0, limit).map(({ note, body }) => {\n const normalizedBody = body.replace(/\\s+/gu, \" \").trim().normalize(\"NFKC\");\n const lower = normalizedBody.toLocaleLowerCase(\"und\");\n const starts = queryTokens.map((token) => lower.indexOf(token)).filter((index) => index >= 0);\n const start = starts.length ? Math.min(...starts) : 0;\n return { ...noteSummary(note, excerptMaxChars), excerpt: Array.from(normalizedBody.slice(start)).slice(0, excerptMaxChars).join(\"\") };\n }),\n next_cursor: null,\n query_tokens: queryTokens,\n };\n}\n", "import {\n NOTEBOOK_SCHEMA_VERSION,\n NotebookError,\n notebookExitCode,\n type EffectiveNotebookConfigV1,\n type NotebookEnvelopeV1,\n type NotebookErrorCode,\n type NotebookHealth,\n} from \"./types\";\n\nfunction bounded(value: string, max = 512): string {\n return value.replace(/[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/gu, \"\").slice(0, max);\n}\n\nexport function successEnvelope<T>(command: string, config: EffectiveNotebookConfigV1, data: T, health: NotebookHealth = null, nextActions: string[] = []): NotebookEnvelopeV1<T> {\n return {\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n ok: true,\n command,\n project: { slug: config.project_slug, repo_path: config.repo_path },\n notebook: {\n binding_state: config.binding.state,\n health,\n id: config.binding.notebook_id ?? null,\n name: config.binding.notebook_name ?? null,\n },\n data,\n error: null,\n next_actions: nextActions.map((item) => bounded(item)),\n };\n}\n\nexport function failureEnvelope(command: string, config: EffectiveNotebookConfigV1, error: unknown, health: NotebookHealth = null, nextActions: string[] = []): NotebookEnvelopeV1<never> {\n const normalized = normalizeNotebookError(error);\n return {\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n ok: false,\n command,\n project: { slug: config.project_slug, repo_path: config.repo_path },\n notebook: {\n binding_state: config.binding.state,\n health,\n id: config.binding.notebook_id ?? null,\n name: config.binding.notebook_name ?? null,\n },\n data: null,\n error: {\n code: normalized.code,\n message: bounded(normalized.message),\n retryable: normalized.retryable,\n details: sanitizeDetails(normalized.details),\n },\n next_actions: nextActions.map((item) => bounded(item)),\n };\n}\n\nexport function normalizeNotebookError(error: unknown): NotebookError {\n if (error instanceof NotebookError) return error;\n // Unknown exceptions are not an operator-facing protocol. Runtime, parser,\n // filesystem, and tool messages routinely contain absolute paths, payload\n // fragments, or ambient secret values. Preserve the original only as an\n // in-memory cause and expose one stable categorized diagnostic.\n return new NotebookError(\"INTERNAL_ERROR\", \"Project Notebook encountered an unexpected internal error\", false, {}, { cause: error });\n}\n\nexport function renderNotebookJson(envelope: NotebookEnvelopeV1): string {\n validateNotebookEnvelope(envelope);\n return `${JSON.stringify(envelope, null, 2)}\\n`;\n}\n\nexport function notebookEnvelopeExitCode(envelope: NotebookEnvelopeV1): number {\n return envelope.ok || !envelope.error ? 0 : notebookExitCode(envelope.error.code);\n}\n\nfunction sanitizeDetails(details: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(details).slice(0, 20)) {\n if (typeof value === \"string\") result[key] = bounded(value);\n else if (typeof value === \"number\" || typeof value === \"boolean\" || value === null) result[key] = value;\n }\n return result;\n}\n\nexport function validateNotebookEnvelope(value: NotebookEnvelopeV1): void {\n const invalid = (reason: string): never => { throw new NotebookError(\"INTERNAL_ERROR\", `Notebook command produced an invalid JSON v1 envelope: ${reason}`); };\n const record = (candidate: unknown, reason: string): Record<string, unknown> => {\n if (!candidate || typeof candidate !== \"object\" || Array.isArray(candidate)) invalid(reason);\n return candidate as Record<string, unknown>;\n };\n const exact = (candidate: Record<string, unknown>, keys: readonly string[], reason: string): void => {\n const actual = Object.keys(candidate).sort();\n const expected = [...keys].sort();\n if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) invalid(reason);\n };\n const string = (candidate: unknown, reason: string, max = 4_096, allowEmpty = false): candidate is string => {\n if (typeof candidate !== \"string\" || (!allowEmpty && candidate.length === 0) || Buffer.byteLength(candidate, \"utf8\") > max || /[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/u.test(candidate)) invalid(reason);\n return true;\n };\n const nullableString = (candidate: unknown, reason: string, max = 4_096): void => {\n if (candidate !== null) string(candidate, reason, max);\n };\n const integer = (candidate: unknown, reason: string): void => {\n if (!Number.isSafeInteger(candidate) || Number(candidate) < 0) invalid(reason);\n };\n const stringList = (candidate: unknown, reason: string, maxItems = 1_000): void => {\n if (!Array.isArray(candidate) || (candidate as unknown[]).length > maxItems) invalid(reason);\n for (const item of candidate as unknown[]) string(item, reason, 4_096);\n };\n const errorCodes = new Set<NotebookErrorCode>([\"INVALID_INPUT\", \"NOT_CONFIGURED\", \"AUTHENTICATION_FAILED\", \"NOT_FOUND\", \"CONFLICT\", \"CROSS_PROJECT\", \"DRIFT_DETECTED\", \"THROTTLED\", \"TIMEOUT\", \"SERVICE_UNAVAILABLE\", \"REMOTE_PROTOCOL_ERROR\", \"INTERNAL_ERROR\"]);\n const commands = new Set([\n \"notebook.status\", \"notebook.create\", \"notebook.notes.list\", \"notebook.notes.add\", \"notebook.notes.get\", \"notebook.notes.update\", \"notebook.notes.delete\", \"notebook.notes.search\",\n \"notebook.overview.get\", \"notebook.overview.set\", \"notebook.capture.list\", \"notebook.capture.retry\", \"notebook.audit\", \"notebook.migrate\",\n \"notebook.skill\",\n ]);\n const root = record(value, \"root must be an object\");\n exact(root, [\"schema_version\", \"ok\", \"command\", \"project\", \"notebook\", \"data\", \"error\", \"next_actions\"], \"root fields differ from v1\");\n if (root.schema_version !== 1 || typeof root.ok !== \"boolean\" || typeof root.command !== \"string\" || !commands.has(root.command)) invalid(\"schema version, ok, or command is invalid\");\n const project = record(root.project, \"project must be an object\");\n exact(project, [\"slug\", \"repo_path\"], \"project fields differ from v1\");\n string(project.slug, \"project slug is invalid\", 128);\n string(project.repo_path, \"project repo_path is invalid\", 4_096);\n const notebook = record(root.notebook, \"notebook must be an object\");\n exact(notebook, [\"binding_state\", \"health\", \"id\", \"name\"], \"notebook fields differ from v1\");\n if (!new Set([\"disabled\", \"planned\", \"linked\"]).has(String(notebook.binding_state))) invalid(\"binding state is invalid\");\n if (!new Set([null, \"unconfigured\", \"healthy\", \"drifted\", \"unavailable\", \"blocked\"]).has(notebook.health as null | string)) invalid(\"health is invalid\");\n nullableString(notebook.id, \"notebook id is invalid\", 512);\n nullableString(notebook.name, \"notebook name is invalid\", 512);\n stringList(root.next_actions, \"next_actions is invalid\", 20);\n if (root.ok === (root.error !== null) || (root.ok ? root.data === null : root.data !== null)) invalid(\"success/error invariant failed\");\n if (!root.ok) {\n const error = record(root.error, \"error must be an object\");\n exact(error, [\"code\", \"message\", \"retryable\", \"details\"], \"error fields differ from v1\");\n if (typeof error.code !== \"string\" || !errorCodes.has(error.code as NotebookErrorCode)) invalid(\"error code is invalid\");\n string(error.message, \"error message is invalid\", 512);\n if (typeof error.retryable !== \"boolean\") invalid(\"error retryable is invalid\");\n const details = record(error.details, \"error details must be an object\");\n if (Object.keys(details).length > 20 || Object.entries(details).some(([key, item]) => !key || !([\"string\", \"number\", \"boolean\"].includes(typeof item) || item === null))) invalid(\"error details are invalid\");\n return;\n }\n\n const noteSummary = (candidate: unknown, detail: boolean): void => {\n const note = record(candidate, \"note must be an object\");\n exact(note, [\"id\", \"title\", \"note_type\", \"created_at\", \"updated_at\", detail ? \"content\" : \"excerpt\"], \"note fields differ from v1\");\n for (const key of [\"id\", \"title\", \"note_type\"] as const) string(note[key], `note ${key} is invalid`, 4_096);\n nullableString(note.created_at, \"note created_at is invalid\", 128);\n nullableString(note.updated_at, \"note updated_at is invalid\", 128);\n string(note[detail ? \"content\" : \"excerpt\"], `note ${detail ? \"content\" : \"excerpt\"} is invalid`, detail ? 1_048_576 : 16_384, true);\n };\n const receipt = (candidate: unknown): void => {\n const item = record(candidate, \"capture receipt must be an object\");\n exact(item, [\"receipt_id\", \"logical_id\", \"session_key\", \"state\", \"created_at\", \"updated_at\", \"automatic_attempts_used\", \"automatic_attempt_limit\", \"manual_retry_count\", \"attempt_origin\", \"error_category\", \"retryable\", \"diagnostic\", \"summary_mode\", \"exclusion_counts\", \"note_logical_ids\", \"remote_note_ids\", \"serialized_bytes\"], \"receipt fields differ from v1\");\n for (const key of [\"receipt_id\", \"logical_id\", \"session_key\", \"created_at\", \"updated_at\"] as const) string(item[key], `receipt ${key} is invalid`, 512);\n if (!new Set([\"queued\", \"processing\", \"succeeded\", \"failed\", \"retry-exhausted\", \"blocked-missing-baseline\"]).has(String(item.state))) invalid(\"receipt state is invalid\");\n for (const key of [\"automatic_attempts_used\", \"automatic_attempt_limit\", \"manual_retry_count\", \"serialized_bytes\"] as const) integer(item[key], `receipt ${key} is invalid`);\n if (item.attempt_origin !== \"automatic\" && item.attempt_origin !== \"operator\") invalid(\"receipt attempt origin is invalid\");\n if (item.error_category !== null && (typeof item.error_category !== \"string\" || !errorCodes.has(item.error_category as NotebookErrorCode))) invalid(\"receipt error category is invalid\");\n if (typeof item.retryable !== \"boolean\") invalid(\"receipt retryable is invalid\");\n nullableString(item.diagnostic, \"receipt diagnostic is invalid\", 512);\n if (item.summary_mode !== null && item.summary_mode !== \"configured\" && item.summary_mode !== \"deterministic-fallback\") invalid(\"receipt summary mode is invalid\");\n const exclusions = record(item.exclusion_counts, \"receipt exclusions must be an object\");\n if (Object.entries(exclusions).some(([key, count]) => !key || !Number.isSafeInteger(count) || Number(count) < 0)) invalid(\"receipt exclusions are invalid\");\n stringList(item.note_logical_ids, \"receipt logical IDs are invalid\");\n stringList(item.remote_note_ids, \"receipt remote IDs are invalid\");\n };\n const finding = (candidate: unknown): void => {\n const item = record(candidate, \"finding must be an object\");\n exact(item, [\"id\", \"title\", \"status\", \"summary\", \"details\", \"fixable\"], \"finding fields differ from v1\");\n for (const key of [\"id\", \"title\", \"summary\"] as const) string(item[key], `finding ${key} is invalid`, 4_096);\n if (!new Set([\"pass\", \"fail\", \"warn\", \"skip\"]).has(String(item.status)) || typeof item.fixable !== \"boolean\") invalid(\"finding status/fixable is invalid\");\n stringList(item.details, \"finding details are invalid\", 100);\n };\n const admission = (candidate: unknown): void => {\n const item = record(candidate, \"capture admission must be an object\");\n exact(item, [\"unresolved_count\", \"unresolved_count_lower_bound\", \"unresolved_bytes\", \"unresolved_bytes_lower_bound\", \"unmeasurable_entry_count\", \"integrity_entries\", \"receipt_caps\", \"receiptless_session_count\", \"stale_receiptless_session_count\", \"active_refusals\"], \"capture admission fields differ from v1\");\n for (const key of [\"unresolved_count_lower_bound\", \"unresolved_bytes_lower_bound\", \"unmeasurable_entry_count\", \"receiptless_session_count\", \"stale_receiptless_session_count\"] as const) integer(item[key], `capture admission ${key} is invalid`);\n for (const key of [\"unresolved_count\", \"unresolved_bytes\"] as const) if (item[key] !== null) integer(item[key], `capture admission ${key} is invalid`);\n const caps = record(item.receipt_caps, \"receipt caps must be an object\"); exact(caps, [\"max_count\", \"max_bytes\"], \"receipt cap fields differ from v1\"); integer(caps.max_count, \"receipt max_count is invalid\"); integer(caps.max_bytes, \"receipt max_bytes is invalid\");\n if (!Array.isArray(item.integrity_entries) || !Array.isArray(item.active_refusals)) invalid(\"capture admission lists are invalid\");\n for (const entryValue of item.integrity_entries as unknown[]) { const entry = record(entryValue, \"integrity entry is invalid\"); exact(entry, [\"entry_id\", \"reason\"], \"integrity entry fields differ from v1\"); string(entry.entry_id, \"integrity entry id is invalid\"); string(entry.reason, \"integrity reason is invalid\"); }\n for (const refusalValue of item.active_refusals as unknown[]) { const refusal = record(refusalValue, \"retention refusal is invalid\"); exact(refusal, [\"outcome\", \"session_key\", \"refused_at\", \"reason\", \"current_count\", \"current_bytes\", \"candidate_bytes\", \"max_count\", \"max_bytes\", \"next_actions\"], \"retention refusal fields differ from v1\"); if (refusal.outcome !== \"capture-refused-history\") invalid(\"retention refusal outcome is invalid\"); for (const key of [\"session_key\", \"refused_at\", \"reason\"] as const) string(refusal[key], `retention refusal ${key} is invalid`); for (const key of [\"current_count\", \"current_bytes\", \"candidate_bytes\", \"max_count\", \"max_bytes\"] as const) integer(refusal[key], `retention refusal ${key} is invalid`); stringList(refusal.next_actions, \"retention refusal actions are invalid\", 10); }\n };\n const data = record(root.data, \"data must be an object\");\n switch (root.command) {\n case \"notebook.create\": exact(data, [\"created\", \"adopted\", \"notebook_id\", \"overview_note_id\"], \"create fields differ from v1\"); if (typeof data.created !== \"boolean\" || typeof data.adopted !== \"boolean\") invalid(\"create flags are invalid\"); string(data.notebook_id, \"created notebook id is invalid\"); string(data.overview_note_id, \"created Overview id is invalid\"); break;\n case \"notebook.notes.list\": exact(data, [\"items\", \"next_cursor\"], \"note list fields differ from v1\"); if (!Array.isArray(data.items)) invalid(\"note list items are invalid\"); (data.items as unknown[]).forEach((item) => noteSummary(item, false)); nullableString(data.next_cursor, \"note cursor is invalid\", 16_384); break;\n case \"notebook.notes.search\": exact(data, [\"items\", \"next_cursor\", \"query_tokens\"], \"search fields differ from v1\"); if (!Array.isArray(data.items) || data.next_cursor !== null) invalid(\"search list/cursor is invalid\"); (data.items as unknown[]).forEach((item) => noteSummary(item, false)); stringList(data.query_tokens, \"query tokens are invalid\", 100); break;\n case \"notebook.notes.add\": case \"notebook.notes.get\": case \"notebook.notes.update\": exact(data, [\"note\"], \"note detail fields differ from v1\"); noteSummary(data.note, true); break;\n case \"notebook.notes.delete\": exact(data, [\"deleted_id\"], \"delete fields differ from v1\"); string(data.deleted_id, \"deleted id is invalid\"); break;\n case \"notebook.overview.get\": case \"notebook.overview.set\": exact(data, [\"note\", \"updated\", \"drift\"], \"Overview fields differ from v1\"); noteSummary(data.note, true); if (typeof data.updated !== \"boolean\" || !Array.isArray(data.drift)) invalid(\"Overview update/drift is invalid\"); for (const driftValue of data.drift as unknown[]) { const drift = record(driftValue, \"Overview drift is invalid\"); exact(drift, [\"path\", \"reason\"], \"Overview drift fields differ from v1\"); string(drift.path, \"Overview drift path is invalid\"); string(drift.reason, \"Overview drift reason is invalid\"); } break;\n case \"notebook.capture.list\": exact(data, [\"items\", \"next_cursor\"], \"capture list fields differ from v1\"); if (!Array.isArray(data.items)) invalid(\"capture items are invalid\"); (data.items as unknown[]).forEach(receipt); if (data.next_cursor !== null) string(data.next_cursor, \"capture cursor is invalid\"); break;\n case \"notebook.capture.retry\": exact(data, [\"receipt\"], \"capture retry fields differ from v1\"); receipt(data.receipt); break;\n case \"notebook.audit\": exact(data, [\"rules\", \"audited_at\", \"remote_check\", \"capture_admission\"], \"audit fields differ from v1\"); if (!Array.isArray(data.rules)) invalid(\"audit rules are invalid\"); (data.rules as unknown[]).forEach(finding); string(data.audited_at, \"audit time is invalid\", 128); if (!new Set([\"pass\", \"fail\", \"skip\"]).has(String(data.remote_check))) invalid(\"audit remote_check is invalid\"); admission(data.capture_admission); break;\n case \"notebook.status\": exact(data, [\"policy\", \"configuration_provenance\", \"remote_check\", \"unresolved_receipt_count\", \"unresolved_receipt_bytes\", \"receipt_caps\", \"capture_admission\", \"findings\"], \"status fields differ from v1\"); record(data.policy, \"status policy is invalid\"); record(data.configuration_provenance, \"status provenance is invalid\"); if (!new Set([\"pass\", \"fail\", \"skip\"]).has(String(data.remote_check))) invalid(\"status remote_check is invalid\"); if (data.unresolved_receipt_count !== null) integer(data.unresolved_receipt_count, \"status unresolved count is invalid\"); if (data.unresolved_receipt_bytes !== null) integer(data.unresolved_receipt_bytes, \"status unresolved bytes is invalid\"); { const caps = record(data.receipt_caps, \"status receipt caps are invalid\"); exact(caps, [\"max_count\", \"max_bytes\"], \"status cap fields differ from v1\"); integer(caps.max_count, \"status max_count is invalid\"); integer(caps.max_bytes, \"status max_bytes is invalid\"); } admission(data.capture_admission); if (!Array.isArray(data.findings)) invalid(\"status findings are invalid\"); (data.findings as unknown[]).forEach(finding); break;\n case \"notebook.skill\": exact(data, [\"status\", \"summary\", \"source\", \"drift\", \"changed_files\"], \"skill projection fields differ from v1\"); if (!new Set([\"clean\", \"planned\", \"repaired\", \"blocked\"]).has(String(data.status))) invalid(\"skill projection status is invalid\"); string(data.summary, \"skill projection summary is invalid\", 4_096); nullableString(data.source, \"skill projection source is invalid\", 4_096); stringList(data.drift, \"skill projection drift is invalid\", 20); stringList(data.changed_files, \"skill projection changed files are invalid\", 1_000); break;\n case \"notebook.migrate\": exact(data, [\"dry_run\", \"selected_rules\", \"results\", \"changed_files\"], \"migration fields differ from v1\"); if (typeof data.dry_run !== \"boolean\" || !Array.isArray(data.results)) invalid(\"migration plan is invalid\"); stringList(data.selected_rules, \"migration selected rules are invalid\", 20); stringList(data.changed_files, \"migration changed files are invalid\", 1_000); for (const resultValue of data.results as unknown[]) { const result = record(resultValue, \"migration result is invalid\"); exact(result, [\"id\", \"status\", \"summary\"], \"migration result fields differ from v1\"); string(result.id, \"migration result id is invalid\"); string(result.summary, \"migration result summary is invalid\"); if (!new Set([\"planned\", \"applied\", \"noop\", \"blocked\"]).has(String(result.status))) invalid(\"migration result status is invalid\"); } break;\n }\n}\n\nexport function errorCode(value: unknown): NotebookErrorCode {\n return normalizeNotebookError(value).code;\n}\n", "export type RemoteMutationJournalState = \"prepared\" | \"possibly-dispatched\" | \"reconciled\" | \"committed\";\nexport type DefinitiveRemoteMutationHttpStatus = 400 | 422;\n\nexport interface RemoteMutationJournalV1 {\n schema_version: 1;\n operation_id: string;\n project_slug: string;\n kind: \"notebook.create\" | \"note.create\";\n logical_marker: string;\n input_digest: string;\n dispatch_digest?: string;\n binding_id?: string;\n session_key?: string;\n state: RemoteMutationJournalState;\n prepared_at: string;\n updated_at: string;\n candidate_ids: string[];\n diagnostic: string | null;\n definitive_http_status?: DefinitiveRemoteMutationHttpStatus;\n result_category: \"prepared\" | \"possibly-dispatched\" | \"definitive-http-rejection\" | \"reconciled-zero\" | \"reconciled-one\" | \"reconciled-many\" | \"committed\";\n next_action: string;\n}\n\nconst REQUIRED_KEYS = [\n \"schema_version\", \"operation_id\", \"project_slug\", \"kind\", \"logical_marker\", \"input_digest\", \"state\",\n \"prepared_at\", \"updated_at\", \"candidate_ids\", \"diagnostic\", \"result_category\", \"next_action\",\n] as const;\nconst OPTIONAL_KEYS = [\"binding_id\", \"session_key\", \"dispatch_digest\", \"definitive_http_status\"] as const;\nconst OPERATION_ID_RE = /^[a-f0-9-]{16,64}$/iu;\nconst DIGEST_RE = /^[a-f0-9]{64}$/u;\nconst PROJECT_SLUG_RE = /^[a-z0-9][a-z0-9._-]{0,127}$/iu;\n\nfunction bounded(value: unknown, max: number): value is string {\n return typeof value === \"string\" && value.length > 0 && Buffer.byteLength(value, \"utf8\") <= max && !/[\\u0000-\\u001f\\u007f]/u.test(value);\n}\n\nfunction timestamp(value: unknown): value is string {\n return bounded(value, 64) && Number.isFinite(Date.parse(value));\n}\n\nexport function remoteMutationResultCategory(state: RemoteMutationJournalState, candidateCount: number, definitiveHttpStatus?: DefinitiveRemoteMutationHttpStatus): RemoteMutationJournalV1[\"result_category\"] {\n if (state === \"prepared\") return \"prepared\";\n if (state === \"possibly-dispatched\") return definitiveHttpStatus === undefined ? \"possibly-dispatched\" : \"definitive-http-rejection\";\n if (state === \"committed\") return \"committed\";\n return candidateCount === 0 ? \"reconciled-zero\" : candidateCount === 1 ? \"reconciled-one\" : \"reconciled-many\";\n}\n\nexport function remoteMutationNextAction(state: RemoteMutationJournalState, candidateCount: number, definitiveHttpStatus?: DefinitiveRemoteMutationHttpStatus): string {\n if (state === \"prepared\") return \"dispatch once only after the durable possibly-dispatched latch\";\n if (state === \"possibly-dispatched\") return definitiveHttpStatus === undefined\n ? \"reconcile by stable marker only; do not POST again\"\n : \"reconcile by stable marker; a different corrected input may dispatch once only after zero candidates\";\n if (state === \"committed\") return \"none\";\n return candidateCount === 1\n ? \"persist durable binding or note ownership before commit\"\n : \"resolve the zero-or-many candidate conflict without another blind POST\";\n}\n\nexport function parseRemoteMutationJournal(value: unknown): RemoteMutationJournalV1 | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const item = value as Record<string, unknown>;\n const keys = Object.keys(item);\n const allowed = new Set<string>([...REQUIRED_KEYS, ...OPTIONAL_KEYS]);\n if (!REQUIRED_KEYS.every((key) => Object.hasOwn(item, key)) || keys.some((key) => !allowed.has(key))) return null;\n if (item.schema_version !== 1 || typeof item.operation_id !== \"string\" || !OPERATION_ID_RE.test(item.operation_id)) return null;\n if (typeof item.project_slug !== \"string\" || !PROJECT_SLUG_RE.test(item.project_slug)) return null;\n if (item.kind !== \"notebook.create\" && item.kind !== \"note.create\") return null;\n if (item.state !== \"prepared\" && item.state !== \"possibly-dispatched\" && item.state !== \"reconciled\" && item.state !== \"committed\") return null;\n if (!bounded(item.logical_marker, 512) || typeof item.input_digest !== \"string\" || !DIGEST_RE.test(item.input_digest)) return null;\n if (item.dispatch_digest !== undefined && (typeof item.dispatch_digest !== \"string\" || !DIGEST_RE.test(item.dispatch_digest))) return null;\n if (item.session_key !== undefined && (typeof item.session_key !== \"string\" || !DIGEST_RE.test(item.session_key))) return null;\n if (item.binding_id !== undefined && !bounded(item.binding_id, 512)) return null;\n if (item.definitive_http_status !== undefined && item.definitive_http_status !== 400 && item.definitive_http_status !== 422) return null;\n if (!timestamp(item.prepared_at) || !timestamp(item.updated_at) || Date.parse(item.updated_at) < Date.parse(item.prepared_at)) return null;\n if (!Array.isArray(item.candidate_ids) || item.candidate_ids.length > 20\n || item.candidate_ids.some((entry) => !bounded(entry, 512))\n || new Set(item.candidate_ids).size !== item.candidate_ids.length) return null;\n if (item.diagnostic !== null && (typeof item.diagnostic !== \"string\" || Buffer.byteLength(item.diagnostic, \"utf8\") > 512 || /[\\u0000-\\u001f\\u007f]/u.test(item.diagnostic))) return null;\n const candidateCount = item.candidate_ids.length;\n if (item.state === \"prepared\" && candidateCount !== 0) return null;\n if (item.state === \"possibly-dispatched\" && candidateCount !== 0) return null;\n if (item.definitive_http_status !== undefined && (item.state !== \"possibly-dispatched\" || candidateCount !== 0 || item.diagnostic === null)) return null;\n if (item.state === \"committed\" && (candidateCount !== 1 || item.diagnostic !== null)) return null;\n if (item.result_category !== remoteMutationResultCategory(item.state, candidateCount, item.definitive_http_status as DefinitiveRemoteMutationHttpStatus | undefined)) return null;\n if (item.next_action !== remoteMutationNextAction(item.state, candidateCount, item.definitive_http_status as DefinitiveRemoteMutationHttpStatus | undefined)) return null;\n return item as unknown as RemoteMutationJournalV1;\n}\n", "import { createHash, randomUUID } from \"node:crypto\";\nimport {\n closeSync,\n chmodSync,\n constants,\n existsSync,\n fchmodSync,\n fstatSync,\n fsyncSync,\n lstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n readSync,\n readdirSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n type Dirent,\n type Stats,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, parse, relative, resolve, sep } from \"node:path\";\nimport { canonicalJson, sessionCaptureLogicalId, sha256Hex } from \"./notes\";\nimport { parseRemoteMutationJournal } from \"./remote-mutation-schema\";\nimport {\n NOTEBOOK_SCHEMA_VERSION,\n NotebookError,\n UNRESOLVED_RECEIPT_STATES,\n type CaptureAdmissionSummaryV1,\n type CaptureIntegrityEntryV1,\n type CaptureReceiptSummaryV1,\n type CaptureReceiptV1,\n type NotebookLimitsV1,\n type OverviewClaimV1,\n type RetentionRefusalReason,\n type RetentionRefusalSummaryV1,\n type RetentionRefusalV1,\n type RemoteMutationJournalSummaryV1,\n type SessionBaselineV1,\n} from \"./types\";\n\nexport const NOTEBOOK_STATE_VERSION = \"v1\";\nconst SESSION_KEY_RE = /^[a-f0-9]{64}$/u;\nconst RECEIPT_ID_RE = /^[a-f0-9]{64}$/u;\nconst GIT_OBJECT_RE = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;\nconst NOTEBOOK_ERROR_CODES = new Set([\n \"INVALID_INPUT\", \"NOT_CONFIGURED\", \"AUTHENTICATION_FAILED\", \"NOT_FOUND\", \"CONFLICT\", \"CROSS_PROJECT\",\n \"DRIFT_DETECTED\", \"THROTTLED\", \"TIMEOUT\", \"SERVICE_UNAVAILABLE\", \"REMOTE_PROTOCOL_ERROR\", \"INTERNAL_ERROR\",\n]);\nconst DIRECTORY_OPEN_FLAGS = constants.O_RDONLY | (constants.O_DIRECTORY ?? 0) | (constants.O_NOFOLLOW ?? 0);\n\nexport function notebookStateRoot(env: NodeJS.ProcessEnv = process.env): string {\n const base = env.XDG_STATE_HOME || join(env.HOME || homedir(), \".local\", \"state\");\n return resolve(base, \"pjangler\", \"notebook\", NOTEBOOK_STATE_VERSION);\n}\n\nexport function deriveSessionKey(projectSlug: string, client: string, clientSessionId: string): string {\n if (!projectSlug || !client || !clientSessionId) throw new NotebookError(\"INVALID_INPUT\", \"project slug, client, and client session id are required\");\n return createHash(\"sha256\").update(`pjangler-session-v1\\0${projectSlug}\\0${client}\\0${clientSessionId}`, \"utf8\").digest(\"hex\");\n}\n\nexport function deriveReceiptId(sessionKey: string): string {\n assertDigest(sessionKey, \"session key\");\n return sha256Hex(`pjangler-receipt-v1\\0${sessionKey}`);\n}\n\nexport function repoPathDigest(repoPath: string): string {\n return sha256Hex(`pjangler-repo-path-v1\\0${resolve(repoPath)}`);\n}\n\nfunction assertDigest(value: string, label: string): void {\n if (!SESSION_KEY_RE.test(value)) throw new NotebookError(\"INVALID_INPUT\", `Invalid ${label}`);\n}\n\nfunction projectStateDir(root: string, projectSlug: string): string {\n if (!/^[a-z0-9][a-z0-9._-]{0,127}$/iu.test(projectSlug)) throw new NotebookError(\"INVALID_INPUT\", \"Invalid project slug for Notebook state\");\n return join(resolve(root), \"projects\", sha256Hex(`pjangler-project-state-v1\\0${projectSlug}`));\n}\n\nfunction assertContained(root: string, candidate: string): void {\n const rel = relative(resolve(root), resolve(candidate));\n if (!rel || (!rel.startsWith(`..${sep}`) && rel !== \"..\" && !rel.startsWith(sep))) return;\n throw new NotebookError(\"INTERNAL_ERROR\", \"Notebook state path escaped its root\");\n}\n\nfunction assertNoSymlinkComponents(path: string, allowMissing: boolean): void {\n const absolute = resolve(path);\n const parsed = parse(absolute);\n let cursor = parsed.root;\n let missing = false;\n for (const part of absolute.slice(parsed.root.length).split(sep).filter(Boolean)) {\n cursor = join(cursor, part);\n if (missing) continue;\n try {\n const stat = lstatSync(cursor);\n if (stat.isSymbolicLink()) throw new NotebookError(\"INTERNAL_ERROR\", \"Notebook state path contains a symlink component\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n if (!allowMissing) throw new NotebookError(\"INTERNAL_ERROR\", \"Notebook state path does not exist\");\n missing = true;\n }\n }\n}\n\n/**\n * Open an absolute directory one component at a time with O_NOFOLLOW. The\n * returned descriptor pins the directory inode, so leaf operations can use\n * /proc/self/fd rather than resolving an attacker-swappable pathname again.\n * Project Notebook state is Linux/XDG scoped; failing closed when procfs is\n * unavailable is safer than silently weakening the containment contract.\n */\nfunction openPinnedDirectory(path: string, root: string, create: boolean): number {\n const absolute = resolve(path);\n const absoluteRoot = resolve(root);\n assertContained(absoluteRoot, absolute);\n if (!existsSync(\"/proc/self/fd\")) throw new NotebookError(\"INTERNAL_ERROR\", \"Descriptor-pinned Notebook state requires procfs\");\n\n const parsed = parse(absolute);\n let fd = openSync(parsed.root, DIRECTORY_OPEN_FLAGS);\n let cursor = parsed.root;\n try {\n for (const part of absolute.slice(parsed.root.length).split(sep).filter(Boolean)) {\n const child = `/proc/self/fd/${fd}/${part}`;\n cursor = join(cursor, part);\n let childFd: number;\n try {\n childFd = openSync(child, DIRECTORY_OPEN_FLAGS);\n } catch (error) {\n if (!create || (error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n try { mkdirSync(child, { mode: 0o700 }); }\n catch (mkdirError) {\n if ((mkdirError as NodeJS.ErrnoException).code !== \"EEXIST\") throw mkdirError;\n }\n childFd = openSync(child, DIRECTORY_OPEN_FLAGS);\n }\n closeSync(fd);\n fd = childFd;\n const stat = fstatSync(fd);\n if (!stat.isDirectory()) throw new NotebookError(\"INTERNAL_ERROR\", \"Notebook state path component is not a directory\");\n if (cursor === absoluteRoot || relative(absoluteRoot, cursor).startsWith(\"..\") === false) assertOwned(stat);\n }\n return fd;\n } catch (error) {\n closeSync(fd);\n if ((error as NodeJS.ErrnoException).code === \"ELOOP\" || (error as NodeJS.ErrnoException).code === \"ENOTDIR\") {\n throw new NotebookError(\"INTERNAL_ERROR\", \"Notebook state path contains a symlink component\");\n }\n throw error;\n }\n}\n\nfunction pinnedLeaf(parentFd: number, path: string): string {\n return `/proc/self/fd/${parentFd}/${basename(path)}`;\n}\n\nfunction assertOwned(stat: Stats): void {\n if (typeof process.getuid === \"function\" && stat.uid !== process.getuid()) {\n throw new NotebookError(\"INTERNAL_ERROR\", \"Notebook state path is not owned by the current user\");\n }\n}\n\nfunction ensureDirectory(path: string, root: string): void {\n const absoluteRoot = resolve(root);\n const absolute = resolve(path);\n assertContained(absoluteRoot, absolute);\n const fd = openPinnedDirectory(absolute, absoluteRoot, true);\n try {\n const stat = fstatSync(fd);\n if (!stat.isDirectory()) throw new NotebookError(\"INTERNAL_ERROR\", \"Notebook state directory is not a real directory\");\n assertOwned(stat);\n fchmodSync(fd, 0o700);\n fsyncSync(fd);\n } finally { closeSync(fd); }\n}\n\nexport interface NotebookStatePaths {\n root: string;\n project: string;\n baselines: string;\n claims: string;\n receipts: string;\n refusals: string;\n journals: string;\n locks: string;\n}\n\nfunction notebookStatePaths(root: string, projectSlug: string): NotebookStatePaths {\n const absoluteRoot = resolve(root);\n const project = projectStateDir(absoluteRoot, projectSlug);\n return {\n root: absoluteRoot,\n project,\n baselines: join(project, \"baselines\"),\n claims: join(project, \"claims\"),\n receipts: join(project, \"receipts\"),\n refusals: join(project, \"refusals\"),\n journals: join(project, \"journals\"),\n locks: join(project, \"locks\"),\n };\n}\n\nexport function ensureNotebookState(root: string, projectSlug: string): NotebookStatePaths {\n const paths = notebookStatePaths(root, projectSlug);\n const { root: absoluteRoot, project } = paths;\n for (const path of [absoluteRoot, join(absoluteRoot, \"projects\"), project, paths.baselines, paths.claims, paths.receipts, paths.refusals, paths.journals, paths.locks]) {\n ensureDirectory(path, absoluteRoot);\n }\n return paths;\n}\n\nfunction jsonLine(value: unknown): string {\n return `${canonicalJson(value)}\\n`;\n}\n\nfunction fsyncDirectory(path: string): void {\n let fd: number | undefined;\n try {\n fd = openPinnedDirectory(path, path, false);\n fsyncSync(fd);\n } catch { /* best effort on filesystems without directory fsync */ }\n finally { if (fd !== undefined) closeSync(fd); }\n}\n\nfunction readStateDirectory(path: string, root: string): Dirent[] {\n const fd = openPinnedDirectory(path, root, false);\n try { return readdirSync(`/proc/self/fd/${fd}`, { withFileTypes: true }); }\n finally { closeSync(fd); }\n}\n\nexport function readNotebookStateDirectory(path: string, root: string): Dirent[] {\n assertContained(root, path);\n return readStateDirectory(path, root);\n}\n\nfunction unlinkStateFile(path: string, root: string, allowMissing = false): boolean {\n assertContained(root, path);\n const parentFd = openPinnedDirectory(dirname(path), root, false);\n const target = pinnedLeaf(parentFd, path);\n let fileFd: number | undefined;\n try {\n try { fileFd = openSync(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)); }\n catch (error) {\n if (allowMissing && (error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw error;\n }\n const stat = fstatSync(fileFd);\n if (!stat.isFile() || (stat.mode & 0o777) !== 0o600) {\n throw new NotebookError(\"CONFLICT\", \"Refusing to remove a suspect Notebook state entry; run pj notebook audit --json\");\n }\n assertOwned(stat);\n unlinkSync(target);\n fsyncSync(parentFd);\n return true;\n } finally {\n if (fileFd !== undefined) closeSync(fileFd);\n closeSync(parentFd);\n }\n}\n\nfunction renameStateFile(source: string, target: string, root: string): void {\n if (dirname(source) !== dirname(target)) throw new NotebookError(\"INTERNAL_ERROR\", \"Notebook state rename crossed directories\");\n const parentFd = openPinnedDirectory(dirname(source), root, false);\n const sourcePath = pinnedLeaf(parentFd, source);\n const targetPath = pinnedLeaf(parentFd, target);\n let sourceFd: number | undefined;\n try {\n sourceFd = openSync(sourcePath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));\n const stat = fstatSync(sourceFd);\n if (!stat.isFile() || (stat.mode & 0o777) !== 0o600) throw new NotebookError(\"CONFLICT\", \"Notebook state rename source has an integrity finding\");\n assertOwned(stat);\n try {\n lstatSync(targetPath);\n throw new NotebookError(\"CONFLICT\", \"Notebook state rename target already exists\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n renameSync(sourcePath, targetPath);\n fsyncSync(parentFd);\n } finally {\n if (sourceFd !== undefined) closeSync(sourceFd);\n closeSync(parentFd);\n }\n}\n\nexport function atomicWriteJson(path: string, value: unknown, root: string, afterParentPinned?: () => void): number {\n assertContained(root, path);\n ensureDirectory(dirname(path), root);\n const text = jsonLine(value);\n const parentFd = openPinnedDirectory(dirname(path), root, false);\n const target = pinnedLeaf(parentFd, path);\n const tempName = `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`;\n const temp = `/proc/self/fd/${parentFd}/${tempName}`;\n let existingIdentity: { dev: number | bigint; ino: number | bigint } | null = null;\n try {\n // Deterministic seam for the ancestor/leaf swap regression. Production\n // callers omit it; the operation itself remains pinned to parentFd.\n afterParentPinned?.();\n try {\n const existingFd = openSync(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));\n try {\n const existing = fstatSync(existingFd);\n if (!existing.isFile()) throw new NotebookError(\"INTERNAL_ERROR\", \"Refusing to replace a non-regular Notebook state file\");\n assertOwned(existing);\n if ((existing.mode & 0o777) !== 0o600) throw new NotebookError(\"CONFLICT\", \"Refusing to replace a Notebook state file with unsafe permissions\");\n existingIdentity = { dev: existing.dev, ino: existing.ino };\n } finally { closeSync(existingFd); }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n\n const fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);\n try {\n writeFileSync(fd, text, \"utf8\");\n fsyncSync(fd);\n } finally { closeSync(fd); }\n\n try {\n const current = lstatSync(target);\n if (!existingIdentity || !current.isFile() || current.isSymbolicLink()\n || current.dev !== existingIdentity.dev || current.ino !== existingIdentity.ino) {\n throw new NotebookError(\"CONFLICT\", \"Notebook state target changed during atomic update; preserving both entries for audit\");\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\" || existingIdentity) throw error;\n }\n renameSync(temp, target);\n fsyncSync(parentFd);\n } catch (error) {\n try { unlinkSync(temp); } catch { /* preserve the original failure */ }\n throw error;\n } finally {\n closeSync(parentFd);\n }\n return Buffer.byteLength(text, \"utf8\");\n}\n\nfunction exclusiveWrite(path: string, text: string, root: string): boolean {\n assertContained(root, path);\n const parentFd = openPinnedDirectory(dirname(path), root, false);\n const target = pinnedLeaf(parentFd, path);\n let fd: number;\n try {\n fd = openSync(target, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);\n } catch (error) {\n closeSync(parentFd);\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") return false;\n throw error;\n }\n try {\n writeFileSync(fd, text, \"utf8\");\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n try { fsyncSync(parentFd); } finally { closeSync(parentFd); }\n return true;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction hasExactKeys(value: Record<string, unknown>, required: readonly string[], optional: readonly string[] = []): boolean {\n const keys = Object.keys(value);\n const allowed = new Set([...required, ...optional]);\n return required.every((key) => Object.hasOwn(value, key)) && keys.every((key) => allowed.has(key));\n}\n\nfunction boundedString(value: unknown, max: number, allowEmpty = false): value is string {\n return typeof value === \"string\" && (allowEmpty || value.length > 0) && value.length <= max && !/[\\u0000-\\u001f\\u007f]/u.test(value);\n}\n\nfunction isoTimestamp(value: unknown): value is string {\n return typeof value === \"string\" && value.length <= 64 && Number.isFinite(Date.parse(value));\n}\n\nfunction safeNonnegativeInteger(value: unknown, max = Number.MAX_SAFE_INTEGER): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0 && value <= max;\n}\n\nfunction boundedStringArray(value: unknown, maxItems: number, maxChars: number, allowControls = false): value is string[] {\n return Array.isArray(value) && value.length <= maxItems && value.every((entry) => typeof entry === \"string\" && entry.length > 0\n && entry.length <= maxChars && (allowControls || !/[\\u0000-\\u001f\\u007f]/u.test(entry)));\n}\n\nfunction parseBaseline(value: unknown): SessionBaselineV1 | null {\n if (!isObject(value) || !hasExactKeys(value, [\n \"schema_version\", \"session_key\", \"project_slug\", \"client\", \"created_at\", \"repo_path_digest\", \"git_head\",\n \"git_status_digest\", \"policy_version\", \"tracked_path_digests\", \"pre_dirty_paths\", \"complete\", \"incomplete_reasons\",\n ])) return null;\n if (value.schema_version !== 1 || typeof value.session_key !== \"string\" || !SESSION_KEY_RE.test(value.session_key)) return null;\n if (!boundedString(value.project_slug, 128) || !boundedString(value.client, 64) || !isoTimestamp(value.created_at)) return null;\n if (typeof value.repo_path_digest !== \"string\" || !RECEIPT_ID_RE.test(value.repo_path_digest)) return null;\n if (value.git_head !== null && (typeof value.git_head !== \"string\" || !GIT_OBJECT_RE.test(value.git_head))) return null;\n if (value.git_status_digest !== null && (typeof value.git_status_digest !== \"string\" || !RECEIPT_ID_RE.test(value.git_status_digest))) return null;\n if (!boundedString(value.policy_version, 128) || typeof value.complete !== \"boolean\") return null;\n if (!isObject(value.tracked_path_digests) || Object.keys(value.tracked_path_digests).length > 1_000\n || !Object.entries(value.tracked_path_digests).every(([path, digest]) => path.length > 0 && path.length <= 4_096 && !path.includes(\"\\0\") && typeof digest === \"string\" && RECEIPT_ID_RE.test(digest))) return null;\n if (!boundedStringArray(value.pre_dirty_paths, 2_000, 4_096, true) || (value.pre_dirty_paths as string[]).some((path) => path.includes(\"\\0\"))) return null;\n if (!Array.isArray(value.incomplete_reasons) || value.incomplete_reasons.length > 20\n || !value.incomplete_reasons.every((reason) => boundedString(reason, 128))) return null;\n return value as unknown as SessionBaselineV1;\n}\n\nfunction parseClaim(value: unknown): OverviewClaimV1 | null {\n if (!isObject(value) || !hasExactKeys(value, [\"schema_version\", \"session_key\", \"project_slug\", \"created_at\", \"overview_note_id\", \"content_sha256\"])) return null;\n if (value.schema_version !== 1 || typeof value.session_key !== \"string\" || !SESSION_KEY_RE.test(value.session_key)) return null;\n if (!boundedString(value.project_slug, 128) || !isoTimestamp(value.created_at) || !boundedString(value.overview_note_id, 512)) return null;\n if (typeof value.content_sha256 !== \"string\" || !RECEIPT_ID_RE.test(value.content_sha256)) return null;\n return value as unknown as OverviewClaimV1;\n}\n\nfunction parseReceipt(value: unknown): CaptureReceiptV1 | null {\n const required = [\n \"schema_version\", \"receipt_id\", \"logical_id\", \"session_key\", \"project_slug\", \"repo_path_digest\", \"baseline_ref\",\n \"end_revision\", \"end_status_digest\", \"state\", \"automatic_attempts_used\", \"automatic_attempt_limit\", \"manual_retry_count\",\n \"attempt_origin\", \"lease_owner\", \"lease_deadline\", \"created_at\", \"updated_at\", \"exclusion_counts\", \"summary_mode\",\n \"note_logical_ids\", \"remote_note_ids\", \"error_category\", \"retryable\", \"diagnostic\", \"serialized_bytes\",\n ];\n if (!isObject(value) || !hasExactKeys(value, required, [\"manual_baseline_ref\"])) return null;\n if (value.schema_version !== 1 || typeof value.receipt_id !== \"string\" || !RECEIPT_ID_RE.test(value.receipt_id)\n || typeof value.session_key !== \"string\" || !SESSION_KEY_RE.test(value.session_key)) return null;\n if (value.logical_id !== sessionCaptureLogicalId(value.session_key) || !boundedString(value.project_slug, 128)\n || typeof value.repo_path_digest !== \"string\" || !RECEIPT_ID_RE.test(value.repo_path_digest)) return null;\n for (const ref of [value.baseline_ref, value.end_revision]) if (ref !== null && !boundedString(ref, 512)) return null;\n if (value.end_status_digest !== null && (typeof value.end_status_digest !== \"string\" || !RECEIPT_ID_RE.test(value.end_status_digest))) return null;\n if (value.manual_baseline_ref !== undefined && (!boundedString(value.manual_baseline_ref, 512) || value.baseline_ref !== value.manual_baseline_ref)) return null;\n const states = [\"queued\", \"processing\", \"succeeded\", \"failed\", \"retry-exhausted\", \"blocked-missing-baseline\"];\n if (typeof value.state !== \"string\" || !states.includes(value.state)) return null;\n if (!safeNonnegativeInteger(value.automatic_attempts_used, 1_000_000) || !safeNonnegativeInteger(value.automatic_attempt_limit, 1_000_000)\n || value.automatic_attempt_limit < 1 || value.automatic_attempts_used > value.automatic_attempt_limit\n || !safeNonnegativeInteger(value.manual_retry_count, 1_000_000)) return null;\n if (value.attempt_origin !== \"automatic\" && value.attempt_origin !== \"operator\") return null;\n const processing = value.state === \"processing\";\n if (processing ? (!boundedString(value.lease_owner, 128) || !isoTimestamp(value.lease_deadline)) : (value.lease_owner !== null || value.lease_deadline !== null)) return null;\n if (!isoTimestamp(value.created_at) || !isoTimestamp(value.updated_at) || Date.parse(value.updated_at) < Date.parse(value.created_at)) return null;\n if (!isObject(value.exclusion_counts) || Object.keys(value.exclusion_counts).length > 100\n || !Object.entries(value.exclusion_counts).every(([key, count]) => boundedString(key, 128) && safeNonnegativeInteger(count, 1_000_000))) return null;\n if (value.summary_mode !== null && value.summary_mode !== \"configured\" && value.summary_mode !== \"deterministic-fallback\") return null;\n if (!boundedStringArray(value.note_logical_ids, 2_000, 512) || !boundedStringArray(value.remote_note_ids, 2_000, 512)) return null;\n if (value.error_category !== null && (typeof value.error_category !== \"string\" || !NOTEBOOK_ERROR_CODES.has(value.error_category))) return null;\n if (typeof value.retryable !== \"boolean\" || (value.diagnostic !== null && !boundedString(value.diagnostic, 4_096))) return null;\n if (!safeNonnegativeInteger(value.serialized_bytes) || value.serialized_bytes < 1) return null;\n if (value.state === \"succeeded\" && (value.summary_mode === null || value.error_category !== null || value.retryable || value.diagnostic !== null)) return null;\n if (value.state === \"failed\" && (value.error_category === null || value.diagnostic === null)) return null;\n if (value.state === \"blocked-missing-baseline\" && (value.error_category !== \"CONFLICT\" || value.retryable || value.diagnostic === null)) return null;\n return value as unknown as CaptureReceiptV1;\n}\n\nfunction parseRefusal(value: unknown): RetentionRefusalV1 | null {\n if (!isObject(value) || !hasExactKeys(value, [\n \"schema_version\", \"session_key\", \"baseline_created_at\", \"refused_at\", \"reason\", \"current_count\", \"current_bytes\",\n \"candidate_bytes\", \"max_count\", \"max_bytes\", \"next_actions\",\n ])) return null;\n if (value.schema_version !== 1 || typeof value.session_key !== \"string\" || !SESSION_KEY_RE.test(value.session_key)\n || !isoTimestamp(value.baseline_created_at) || !isoTimestamp(value.refused_at)\n || Date.parse(value.refused_at) < Date.parse(value.baseline_created_at)) return null;\n if (!(value.reason === \"count-cap\" || value.reason === \"byte-cap\" || value.reason === \"both\")) return null;\n if (![value.current_count, value.current_bytes, value.candidate_bytes, value.max_count, value.max_bytes]\n .every((entry) => safeNonnegativeInteger(entry)) || value.candidate_bytes === 0 || value.max_count === 0 || value.max_bytes === 0) return null;\n const countBlocked = (value.current_count as number) + 1 > (value.max_count as number);\n const byteBlocked = (value.current_bytes as number) + (value.candidate_bytes as number) > (value.max_bytes as number);\n if (!countBlocked && !byteBlocked) return null;\n if (value.reason !== capReason(countBlocked, byteBlocked)) return null;\n if (!boundedStringArray(value.next_actions, 2, 2_048) || value.next_actions.length !== 2\n || !value.next_actions[0]!.startsWith(\"pj notebook capture list \") || !value.next_actions[1]!.startsWith(\"pj notebook capture retry \")) return null;\n return value as unknown as RetentionRefusalV1;\n}\n\nfunction safeReadJson(path: string, maxBytes: number): { value?: unknown; reason?: CaptureIntegrityEntryV1[\"reason\"]; bytes: number } {\n let parentFd: number;\n try { parentFd = openPinnedDirectory(dirname(path), dirname(path), false); }\n catch { return { reason: \"non-regular\", bytes: 0 }; }\n let fd: number;\n try { fd = openSync(pinnedLeaf(parentFd, path), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)); }\n catch (error) {\n closeSync(parentFd);\n return { reason: (error as NodeJS.ErrnoException).code === \"ELOOP\" ? \"non-regular\" : \"unreadable\", bytes: 0 };\n }\n try {\n const stat = fstatSync(fd);\n if (!stat.isFile()) return { reason: \"non-regular\", bytes: 0 };\n if ((stat.mode & 0o777) !== 0o600) return { reason: \"unsafe-permissions\", bytes: stat.size };\n try { assertOwned(stat); } catch { return { reason: \"unsafe-permissions\", bytes: stat.size }; }\n if ((stat.mode & 0o444) === 0) return { reason: \"unreadable\", bytes: 0 };\n if (stat.size > maxBytes) return { reason: \"oversize\", bytes: stat.size };\n const chunks: Buffer[] = [];\n let total = 0;\n while (true) {\n const chunk = Buffer.allocUnsafe(Math.min(8_192, maxBytes + 1 - total));\n const count = readSync(fd, chunk, 0, chunk.length, null);\n if (!count) break;\n total += count;\n if (total > maxBytes) return { reason: \"oversize\", bytes: total };\n chunks.push(chunk.subarray(0, count));\n }\n const after = fstatSync(fd);\n if (after.size !== stat.size || total !== stat.size) return { reason: \"unreadable\", bytes: total };\n return { value: JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(Buffer.concat(chunks, total))) as unknown, bytes: total };\n } catch (error) {\n return { reason: error instanceof SyntaxError || error instanceof TypeError ? \"invalid-json\" : \"unreadable\", bytes: 0 };\n } finally { closeSync(fd); closeSync(parentFd); }\n}\n\nfunction safeEntryId(kind: string, name: string): string {\n return `${kind}/${/^[a-zA-Z0-9._-]{1,160}$/u.test(name) ? name : sha256Hex(name).slice(0, 24)}`;\n}\n\nfunction readBaseline(path: string, maxBytes: number): SessionBaselineV1 | null {\n if (!existsSync(path)) return null;\n const read = safeReadJson(path, maxBytes);\n return read.value === undefined ? null : parseBaseline(read.value);\n}\n\nfunction baselineReceiptByteCeiling(limits: NotebookLimitsV1): number {\n return limits.receipt_max_bytes;\n}\n\nexport interface BaselineCreateInput {\n limits: NotebookLimitsV1;\n session_key: string;\n project_slug: string;\n client: string;\n created_at: string;\n repo_path: string;\n git_head: string | null;\n git_status_digest: string | null;\n policy_version: string;\n tracked_path_digests: Record<string, string>;\n pre_dirty_paths: string[];\n complete: boolean;\n incomplete_reasons: string[];\n}\n\nexport function createSessionBaseline(root: string, input: BaselineCreateInput): { baseline: SessionBaselineV1; created: boolean } {\n assertDigest(input.session_key, \"session key\");\n const paths = ensureNotebookState(root, input.project_slug);\n const path = join(paths.baselines, `${input.session_key}.json`);\n const maxBytes = baselineReceiptByteCeiling(input.limits);\n const existing = readBaseline(path, maxBytes);\n if (existing) return { baseline: existing, created: false };\n const baseline: SessionBaselineV1 = {\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n session_key: input.session_key,\n project_slug: input.project_slug,\n client: input.client.slice(0, 64),\n created_at: input.created_at,\n repo_path_digest: repoPathDigest(input.repo_path),\n git_head: input.git_head,\n git_status_digest: input.git_status_digest,\n policy_version: input.policy_version,\n tracked_path_digests: Object.fromEntries(Object.entries(input.tracked_path_digests).sort(([a], [b]) => a.localeCompare(b, \"en\")).slice(0, 1_000)),\n pre_dirty_paths: [...new Set(input.pre_dirty_paths)].sort().slice(0, 2_000),\n complete: input.complete,\n incomplete_reasons: input.incomplete_reasons.slice(0, 20).map((item) => item.slice(0, 128)),\n };\n let text = jsonLine(baseline);\n if (Buffer.byteLength(text, \"utf8\") > maxBytes) {\n baseline.complete = false;\n baseline.tracked_path_digests = {};\n baseline.pre_dirty_paths = [];\n baseline.incomplete_reasons = [...new Set([\"baseline-byte-ceiling\", ...baseline.incomplete_reasons])].slice(0, 20);\n text = jsonLine(baseline);\n }\n if (Buffer.byteLength(text, \"utf8\") > maxBytes) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"Notebook receipt_max_bytes is too small for a minimal SessionStart baseline\");\n }\n if (!parseBaseline(baseline)) throw new NotebookError(\"INTERNAL_ERROR\", \"SessionStart baseline failed its own v1 schema validation\");\n if (!exclusiveWrite(path, text, paths.root)) {\n const won = readBaseline(path, maxBytes);\n if (!won) throw new NotebookError(\"INTERNAL_ERROR\", \"Concurrent baseline creation produced unreadable state\");\n return { baseline: won, created: false };\n }\n return { baseline, created: true };\n}\n\nexport function createOverviewClaim(root: string, input: Omit<OverviewClaimV1, \"schema_version\">): { claim: OverviewClaimV1; created: boolean } {\n assertDigest(input.session_key, \"session key\");\n const paths = ensureNotebookState(root, input.project_slug);\n const path = join(paths.claims, `${input.session_key}.overview`);\n if (existsSync(path)) {\n const read = safeReadJson(path, 65_536);\n const existing = read.value === undefined ? null : parseClaim(read.value);\n if (!existing) throw new NotebookError(\"CONFLICT\", \"Overview claim has an integrity finding\");\n return { claim: existing, created: false };\n }\n const claim: OverviewClaimV1 = { schema_version: NOTEBOOK_SCHEMA_VERSION, ...input };\n if (!exclusiveWrite(path, jsonLine(claim), paths.root)) {\n const read = safeReadJson(path, 65_536);\n const existing = read.value === undefined ? null : parseClaim(read.value);\n if (!existing) throw new NotebookError(\"CONFLICT\", \"Concurrent Overview claim creation produced invalid state\");\n return { claim: existing, created: false };\n }\n return { claim, created: true };\n}\n\nexport function readOverviewClaim(root: string, projectSlug: string, sessionKey: string): OverviewClaimV1 | null {\n assertDigest(sessionKey, \"session key\");\n const paths = notebookStatePaths(root, projectSlug);\n const path = join(paths.claims, `${sessionKey}.overview`);\n if (!existsSync(path)) return null;\n const read = safeReadJson(path, 65_536);\n return read.value === undefined ? null : parseClaim(read.value);\n}\n\nexport function readSessionBaseline(root: string, projectSlug: string, sessionKey: string, limits: NotebookLimitsV1): SessionBaselineV1 | null {\n assertDigest(sessionKey, \"session key\");\n const paths = ensureNotebookState(root, projectSlug);\n return readBaseline(join(paths.baselines, `${sessionKey}.json`), baselineReceiptByteCeiling(limits));\n}\n\nfunction acquireLock(paths: NotebookStatePaths, maxWaitMs: number): () => void {\n const lock = join(paths.locks, \"admission.lock\");\n const deadline = Date.now() + Math.max(1, maxWaitMs);\n const token = randomUUID();\n const record = () => ({\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n token,\n pid: process.pid,\n acquired_at: new Date().toISOString(),\n expires_at: new Date(Date.now() + Math.max(5_000, maxWaitMs * 20)).toISOString(),\n });\n while (true) {\n if (exclusiveWrite(lock, jsonLine(record()), paths.root)) {\n return () => {\n const current = safeReadJson(lock, 8_192);\n if (current.value && typeof current.value === \"object\" && !Array.isArray(current.value)\n && (current.value as Record<string, unknown>).token === token) {\n try { unlinkStateFile(lock, paths.root); } catch { /* a recovered lease is no longer ours */ }\n }\n };\n }\n\n const read = safeReadJson(lock, 8_192);\n const held = read.value && typeof read.value === \"object\" && !Array.isArray(read.value)\n ? read.value as Record<string, unknown>\n : null;\n const heldToken = typeof held?.token === \"string\" && /^[a-f0-9-]{16,64}$/iu.test(held.token) ? held.token : null;\n const expiresAt = typeof held?.expires_at === \"string\" ? Date.parse(held.expires_at) : Number.NaN;\n if (read.reason || !heldToken || !Number.isFinite(expiresAt)) {\n throw new NotebookError(\"CONFLICT\", \"Notebook state lock has an integrity finding; preserve it and run pj notebook audit --json\");\n }\n if (Date.now() >= expiresAt) {\n // Recovery is serialized by a token-specific claim. A crashed owner can\n // no longer leave admission permanently blocked, and contenders never\n // remove a lock whose token differs from the one they proved stale.\n const recovery = join(paths.locks, `recovery-${heldToken}.lock`);\n const recoveryRecord = jsonLine({ schema_version: NOTEBOOK_SCHEMA_VERSION, stale_token: heldToken, recovery_token: token, expires_at: new Date(Date.now() + 5_000).toISOString() });\n if (exclusiveWrite(recovery, recoveryRecord, paths.root)) {\n try {\n const verify = safeReadJson(lock, 8_192);\n const currentToken = verify.value && typeof verify.value === \"object\" && !Array.isArray(verify.value)\n ? (verify.value as Record<string, unknown>).token\n : null;\n const currentExpiry = verify.value && typeof verify.value === \"object\" && !Array.isArray(verify.value)\n ? Date.parse(String((verify.value as Record<string, unknown>).expires_at ?? \"\"))\n : Number.NaN;\n if (currentToken === heldToken && Number.isFinite(currentExpiry) && Date.now() >= currentExpiry) {\n const recovered = join(paths.locks, `.recovered-${heldToken}-${randomUUID()}.json`);\n renameStateFile(lock, recovered, paths.root);\n unlinkStateFile(recovered, paths.root);\n }\n } finally {\n try { unlinkStateFile(recovery, paths.root); } catch { /* next audit reports a stranded recovery claim */ }\n }\n continue;\n }\n }\n if (Date.now() >= deadline) throw new NotebookError(\"TIMEOUT\", \"Notebook capture admission lock is busy\", true);\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);\n }\n}\n\nexport function withNotebookStateLock<T>(root: string, projectSlug: string, maxWaitMs: number, operation: (paths: NotebookStatePaths) => T): T {\n const paths = ensureNotebookState(root, projectSlug);\n const release = acquireLock(paths, maxWaitMs);\n try { return operation(paths); }\n finally { release(); }\n}\n\nexport function readNotebookStateJson(path: string, root: string, maxBytes: number): { value?: unknown; reason?: CaptureIntegrityEntryV1[\"reason\"]; bytes: number } {\n assertContained(root, path);\n return safeReadJson(path, maxBytes);\n}\n\nexport function createNotebookStateJsonExclusive(path: string, value: unknown, root: string): boolean {\n return exclusiveWrite(path, jsonLine(value), root);\n}\n\ninterface ReceiptScan {\n receipts: CaptureReceiptV1[];\n unresolvedCount: number;\n unresolvedBytes: number;\n integrity: CaptureIntegrityEntryV1[];\n integrityCount: number;\n referencedSessions: Set<string>;\n}\n\ninterface AuxiliaryScan {\n integrity: CaptureIntegrityEntryV1[];\n integrityCount: number;\n knownBytes: number;\n referencedSessions: Set<string>;\n unresolvedJournals: RemoteMutationJournalSummaryV1[];\n}\n\nexport interface CaptureAdmissionInspectionV1 extends CaptureAdmissionSummaryV1 {\n unresolvedJournals: RemoteMutationJournalSummaryV1[];\n}\n\nfunction addBoundedIntegrity(target: AuxiliaryScan, limits: NotebookLimitsV1, entry: CaptureIntegrityEntryV1, knownBytes = 0): void {\n target.integrityCount += 1;\n target.knownBytes += Math.max(0, knownBytes);\n if (target.integrity.length < limits.integrity_max_entries) target.integrity.push(entry);\n}\n\nfunction journalReference(value: unknown): { sessionKey?: string; unresolved: boolean; summary?: RemoteMutationJournalSummaryV1 } | null {\n const item = parseRemoteMutationJournal(value);\n if (!item) return null;\n const unresolved = item.state !== \"committed\";\n return {\n ...(item.session_key ? { sessionKey: item.session_key } : {}),\n unresolved,\n ...(unresolved ? { summary: {\n operation_id: item.operation_id,\n kind: item.kind,\n logical_marker: item.logical_marker,\n session_key: item.session_key ?? null,\n state: item.state as \"prepared\" | \"possibly-dispatched\" | \"reconciled\",\n binding_id: item.binding_id ?? null,\n candidate_ids: [...item.candidate_ids],\n result_category: item.result_category,\n next_action: item.next_action,\n } } : {}),\n };\n}\n\nfunction scanAuxiliaryState(paths: NotebookStatePaths, limits: NotebookLimitsV1): AuxiliaryScan {\n const scan: AuxiliaryScan = { integrity: [], integrityCount: 0, knownBytes: 0, referencedSessions: new Set(), unresolvedJournals: [] };\n const specifications = [\n { kind: \"baselines\", dir: paths.baselines, suffix: \".json\", maxBytes: baselineReceiptByteCeiling(limits), parse: parseBaseline, key: (value: SessionBaselineV1) => value.session_key },\n { kind: \"claims\", dir: paths.claims, suffix: \".overview\", maxBytes: limits.receipt_max_bytes, parse: parseClaim, key: (value: OverviewClaimV1) => value.session_key },\n { kind: \"refusals\", dir: paths.refusals, suffix: \".json\", maxBytes: limits.receipt_max_bytes, parse: parseRefusal, key: (value: RetentionRefusalV1) => value.session_key },\n ] as const;\n for (const specification of specifications) {\n if (!existsSync(specification.dir)) continue;\n let entries: Dirent[];\n try { entries = readStateDirectory(specification.dir, paths.root); }\n catch { addBoundedIntegrity(scan, limits, { entry_id: specification.kind, reason: \"unreadable\" }); continue; }\n for (const entry of entries) {\n const entryId = safeEntryId(specification.kind, entry.name);\n if (!entry.isFile() || entry.isSymbolicLink() || !entry.name.endsWith(specification.suffix)) {\n addBoundedIntegrity(scan, limits, { entry_id: entryId, reason: \"non-regular\" });\n continue;\n }\n const read = safeReadJson(join(specification.dir, entry.name), specification.maxBytes);\n if (read.reason || read.value === undefined) {\n addBoundedIntegrity(scan, limits, { entry_id: entryId, reason: read.reason ?? \"invalid-json\" }, read.bytes);\n continue;\n }\n const parsed = specification.parse(read.value as never) as SessionBaselineV1 | OverviewClaimV1 | RetentionRefusalV1 | null;\n const expectedKey = parsed ? specification.key(parsed as never) : null;\n const expectedName = expectedKey ? `${expectedKey}${specification.suffix}` : null;\n if (!parsed || expectedName !== entry.name) addBoundedIntegrity(scan, limits, { entry_id: entryId, reason: \"invalid-schema\" }, read.bytes);\n }\n }\n\n if (existsSync(paths.journals)) {\n let entries: Dirent[];\n try { entries = readStateDirectory(paths.journals, paths.root); }\n catch { addBoundedIntegrity(scan, limits, { entry_id: \"journals\", reason: \"unreadable\" }); entries = []; }\n for (const entry of entries) {\n const entryId = safeEntryId(\"journals\", entry.name);\n if (!entry.isFile() || entry.isSymbolicLink() || !entry.name.endsWith(\".json\")) {\n addBoundedIntegrity(scan, limits, { entry_id: entryId, reason: \"non-regular\" });\n continue;\n }\n const read = safeReadJson(join(paths.journals, entry.name), limits.receipt_max_bytes);\n if (read.reason || read.value === undefined) {\n addBoundedIntegrity(scan, limits, { entry_id: entryId, reason: read.reason ?? \"invalid-json\" }, read.bytes);\n continue;\n }\n const reference = journalReference(read.value);\n const operationId = reference && typeof (read.value as Record<string, unknown>).operation_id === \"string\"\n ? (read.value as Record<string, unknown>).operation_id as string\n : null;\n if (!reference || `${operationId}.json` !== entry.name) {\n addBoundedIntegrity(scan, limits, { entry_id: entryId, reason: \"invalid-schema\" }, read.bytes);\n continue;\n }\n if (reference.unresolved && reference.sessionKey) scan.referencedSessions.add(reference.sessionKey);\n if (reference.summary) scan.unresolvedJournals.push(reference.summary);\n }\n }\n if (existsSync(paths.locks)) {\n let entries: Dirent[];\n try { entries = readStateDirectory(paths.locks, paths.root); }\n catch { addBoundedIntegrity(scan, limits, { entry_id: \"locks\", reason: \"unreadable\" }); entries = []; }\n for (const entry of entries) {\n const entryId = safeEntryId(\"locks\", entry.name);\n if (!entry.isFile() || entry.isSymbolicLink()) {\n addBoundedIntegrity(scan, limits, { entry_id: entryId, reason: \"non-regular\" });\n continue;\n }\n const read = safeReadJson(join(paths.locks, entry.name), 8_192);\n if (read.reason || read.value === undefined) {\n addBoundedIntegrity(scan, limits, { entry_id: entryId, reason: read.reason ?? \"invalid-json\" }, read.bytes);\n continue;\n }\n const item = read.value && typeof read.value === \"object\" && !Array.isArray(read.value) ? read.value as Record<string, unknown> : null;\n const token = entry.name === \"admission.lock\" ? item?.token : item?.recovery_token;\n const expiry = Date.parse(String(item?.expires_at ?? \"\"));\n const expectedRecovery = entry.name.startsWith(\"recovery-\") && entry.name.endsWith(\".lock\") && item?.stale_token === entry.name.slice(9, -5);\n if (!item || item.schema_version !== 1 || typeof token !== \"string\" || !Number.isFinite(expiry)\n || (entry.name !== \"admission.lock\" && !expectedRecovery) || Date.now() >= expiry) {\n addBoundedIntegrity(scan, limits, { entry_id: entryId, reason: \"invalid-schema\" }, read.bytes);\n }\n }\n }\n return scan;\n}\n\nfunction scanReceipts(paths: NotebookStatePaths, limits: NotebookLimitsV1): ReceiptScan {\n const receipts: CaptureReceiptV1[] = [];\n const integrity: CaptureIntegrityEntryV1[] = [];\n const referencedSessions = new Set<string>();\n let unresolvedCount = 0;\n let unresolvedBytes = 0;\n let integrityCount = 0;\n const addIntegrity = (entry: CaptureIntegrityEntryV1, knownBytes = 0) => {\n integrityCount += 1;\n unresolvedCount += 1;\n unresolvedBytes += Math.max(0, knownBytes);\n if (integrity.length < limits.integrity_max_entries) integrity.push(entry);\n };\n if (!existsSync(paths.receipts)) return { receipts, unresolvedCount, unresolvedBytes, referencedSessions, integrity, integrityCount };\n let entries;\n try { entries = readStateDirectory(paths.receipts, paths.root); } catch {\n addIntegrity({ entry_id: \"receipts\", reason: \"unreadable\" });\n return { receipts, unresolvedCount, unresolvedBytes, referencedSessions, integrity, integrityCount };\n }\n for (const entry of entries) {\n const entryId = safeEntryId(\"receipts\", entry.name);\n const path = join(paths.receipts, entry.name);\n if (!entry.isFile() || entry.isSymbolicLink() || !/^[a-f0-9]{64}\\.json$/u.test(entry.name)) {\n addIntegrity({ entry_id: entryId, reason: \"non-regular\" });\n continue;\n }\n const read = safeReadJson(path, limits.receipt_max_bytes);\n if (read.reason || read.value === undefined) {\n addIntegrity({ entry_id: entryId, reason: read.reason ?? \"invalid-json\" }, read.bytes);\n continue;\n }\n const receipt = parseReceipt(read.value);\n if (!receipt || `${receipt.receipt_id}.json` !== entry.name || receipt.serialized_bytes !== read.bytes) {\n addIntegrity({ entry_id: entryId, reason: \"invalid-schema\" }, read.bytes);\n continue;\n }\n receipts.push(receipt);\n referencedSessions.add(receipt.session_key);\n if (UNRESOLVED_RECEIPT_STATES.has(receipt.state)) {\n unresolvedCount += 1;\n unresolvedBytes += read.bytes;\n }\n }\n return { receipts, unresolvedCount, unresolvedBytes, integrity, integrityCount, referencedSessions };\n}\n\nfunction scanBaselines(paths: NotebookStatePaths, nowMs: number, limits: NotebookLimitsV1, referenced: Set<string>): { current: number; stale: number } {\n let current = 0;\n let stale = 0;\n if (!existsSync(paths.baselines)) return { current, stale };\n for (const entry of readStateDirectory(paths.baselines, paths.root)) {\n if (!entry.isFile() || !entry.name.endsWith(\".json\")) continue;\n const baseline = readBaseline(join(paths.baselines, entry.name), baselineReceiptByteCeiling(limits));\n if (!baseline || referenced.has(baseline.session_key)) continue;\n const expires = Date.parse(baseline.created_at) + limits.receiptless_session_retention_seconds * 1_000;\n if (nowMs >= expires) stale += 1;\n else current += 1;\n }\n return { current, stale };\n}\n\nfunction scanRefusals(paths: NotebookStatePaths, nowMs: number, limits: NotebookLimitsV1, scan: ReceiptScan): RetentionRefusalSummaryV1[] {\n const result: RetentionRefusalSummaryV1[] = [];\n if (!existsSync(paths.refusals)) return result;\n const entries = readStateDirectory(paths.refusals, paths.root)\n .sort((a, b) => a.name.localeCompare(b.name, \"en\"))\n .slice(0, limits.refusal_max_entries);\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".json\")) continue;\n const read = safeReadJson(join(paths.refusals, entry.name), limits.receipt_max_bytes);\n const marker = read.value === undefined ? null : parseRefusal(read.value);\n if (!marker || `${marker.session_key}.json` !== entry.name) continue;\n if (nowMs >= Date.parse(marker.baseline_created_at) + limits.receiptless_session_retention_seconds * 1_000) continue;\n result.push({\n outcome: \"capture-refused-history\",\n session_key: marker.session_key,\n refused_at: marker.refused_at,\n reason: marker.reason,\n current_count: scan.unresolvedCount,\n current_bytes: scan.unresolvedBytes,\n candidate_bytes: marker.candidate_bytes,\n max_count: limits.unresolved_receipt_max_count,\n max_bytes: limits.unresolved_receipt_max_bytes,\n next_actions: [...marker.next_actions],\n });\n }\n return result.sort((a, b) => a.refused_at.localeCompare(b.refused_at) || a.session_key.localeCompare(b.session_key));\n}\n\nexport function captureAdmissionSummary(root: string, projectSlug: string, limits: NotebookLimitsV1, now = new Date()): CaptureAdmissionInspectionV1 {\n const paths = notebookStatePaths(root, projectSlug);\n const scan = scanReceipts(paths, limits);\n const auxiliary = scanAuxiliaryState(paths, limits);\n const referenced = new Set([...scan.referencedSessions, ...auxiliary.referencedSessions]);\n const baselines = scanBaselines(paths, now.getTime(), limits, referenced);\n const exact = scan.integrityCount === 0 && auxiliary.integrityCount === 0;\n const integrity = [...scan.integrity, ...auxiliary.integrity].slice(0, limits.integrity_max_entries);\n const integrityCount = scan.integrityCount + auxiliary.integrityCount;\n return {\n unresolved_count: exact ? scan.unresolvedCount : null,\n unresolved_count_lower_bound: scan.unresolvedCount,\n unresolved_bytes: exact ? scan.unresolvedBytes : null,\n unresolved_bytes_lower_bound: scan.unresolvedBytes + auxiliary.knownBytes,\n unmeasurable_entry_count: integrityCount,\n integrity_entries: integrity,\n receipt_caps: { max_count: limits.unresolved_receipt_max_count, max_bytes: limits.unresolved_receipt_max_bytes },\n receiptless_session_count: baselines.current,\n stale_receiptless_session_count: baselines.stale,\n active_refusals: scanRefusals(paths, now.getTime(), limits, scan),\n unresolvedJournals: auxiliary.unresolvedJournals.sort((a, b) => a.operation_id.localeCompare(b.operation_id, \"en\")).slice(0, limits.integrity_max_entries),\n };\n}\n\nexport function publicCaptureAdmissionSummary(summary: CaptureAdmissionInspectionV1): CaptureAdmissionSummaryV1 {\n const { unresolvedJournals: _internalJournals, ...publicSummary } = summary;\n return publicSummary;\n}\n\nfunction createCandidate(input: {\n sessionKey: string;\n projectSlug: string;\n repoPath: string;\n baseline: SessionBaselineV1 | null;\n endRevision: string | null;\n endStatusDigest: string | null;\n now: Date;\n limits: NotebookLimitsV1;\n}): { receipt: CaptureReceiptV1; text: string; bytes: number } {\n const receiptId = deriveReceiptId(input.sessionKey);\n const timestamp = input.now.toISOString();\n const receipt: CaptureReceiptV1 = {\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n receipt_id: receiptId,\n logical_id: sessionCaptureLogicalId(input.sessionKey),\n session_key: input.sessionKey,\n project_slug: input.projectSlug,\n repo_path_digest: repoPathDigest(input.repoPath),\n baseline_ref: input.baseline?.git_head ?? null,\n end_revision: input.endRevision,\n end_status_digest: input.endStatusDigest,\n state: \"queued\",\n automatic_attempts_used: 0,\n automatic_attempt_limit: input.limits.automatic_attempt_limit,\n manual_retry_count: 0,\n attempt_origin: \"automatic\",\n lease_owner: null,\n lease_deadline: null,\n created_at: timestamp,\n updated_at: timestamp,\n exclusion_counts: {},\n summary_mode: null,\n note_logical_ids: [],\n remote_note_ids: [],\n error_category: null,\n retryable: false,\n diagnostic: null,\n serialized_bytes: 1,\n };\n let text = jsonLine(receipt);\n for (let attempt = 0; attempt < 8; attempt++) {\n const bytes = Buffer.byteLength(text, \"utf8\");\n if (receipt.serialized_bytes === bytes) return { receipt, text, bytes };\n receipt.serialized_bytes = bytes;\n text = jsonLine(receipt);\n }\n throw new NotebookError(\"INTERNAL_ERROR\", \"Capture receipt serialized size did not converge\");\n}\n\nfunction capReason(countBlocked: boolean, byteBlocked: boolean): RetentionRefusalReason {\n return countBlocked && byteBlocked ? \"both\" : countBlocked ? \"count-cap\" : \"byte-cap\";\n}\n\nfunction recoveryActions(receiptId: string, repoPath: string): string[] {\n return [\n `pj notebook capture list ${repoPath}`,\n `pj notebook capture retry ${receiptId} ${repoPath} (add --baseline GIT_REF for blocked-missing-baseline)`,\n ];\n}\n\nfunction removeValidRefusal(paths: NotebookStatePaths, sessionKey: string, limits: NotebookLimitsV1): void {\n const path = join(paths.refusals, `${sessionKey}.json`);\n if (!existsSync(path)) return;\n const read = safeReadJson(path, limits.receipt_max_bytes);\n const marker = read.value === undefined ? null : parseRefusal(read.value);\n if (!marker || marker.session_key !== sessionKey) return;\n unlinkStateFile(path, paths.root);\n}\n\nexport type CaptureAdmissionResult =\n | { outcome: \"deduplicated\"; receipt: CaptureReceiptV1 }\n | { outcome: \"admitted\"; receipt: CaptureReceiptV1; candidate_bytes: number }\n | { outcome: \"retention-pressure\"; marker: RetentionRefusalV1; diagnostic: string }\n | { outcome: \"state-integrity\"; summary: CaptureAdmissionSummaryV1; diagnostic: string };\n\nexport function admitCaptureReceipt(input: {\n root: string;\n projectSlug: string;\n repoPath: string;\n sessionKey: string;\n endRevision: string | null;\n endStatusDigest: string | null;\n limits: NotebookLimitsV1;\n now?: Date;\n}): CaptureAdmissionResult {\n assertDigest(input.sessionKey, \"session key\");\n const now = input.now ?? new Date();\n const paths = ensureNotebookState(input.root, input.projectSlug);\n const release = acquireLock(paths, Math.min(100, input.limits.hook_session_end_timeout_ms));\n try {\n const receiptId = deriveReceiptId(input.sessionKey);\n const receiptPath = join(paths.receipts, `${receiptId}.json`);\n if (existsSync(receiptPath)) {\n const read = safeReadJson(receiptPath, input.limits.receipt_max_bytes);\n const receipt = read.value === undefined ? null : parseReceipt(read.value);\n if (receipt && receipt.receipt_id === receiptId && receipt.session_key === input.sessionKey && receipt.serialized_bytes === read.bytes) {\n removeValidRefusal(paths, input.sessionKey, input.limits);\n return { outcome: \"deduplicated\", receipt };\n }\n }\n\n const scanBefore = scanReceipts(paths, input.limits);\n const auxiliaryBefore = scanAuxiliaryState(paths, input.limits);\n const referencedBefore = new Set([...scanBefore.referencedSessions, ...auxiliaryBefore.referencedSessions]);\n const baselinePath = join(paths.baselines, `${input.sessionKey}.json`);\n let baseline = readBaseline(baselinePath, baselineReceiptByteCeiling(input.limits));\n if (baseline) {\n const expired = now.getTime() >= Date.parse(baseline.created_at) + input.limits.receiptless_session_retention_seconds * 1_000;\n if (expired && !referencedBefore.has(input.sessionKey) && scanBefore.integrityCount === 0 && auxiliaryBefore.integrityCount === 0) {\n unlinkStateFile(baselinePath, paths.root);\n const claimPath = join(paths.claims, `${input.sessionKey}.overview`);\n unlinkStateFile(claimPath, paths.root, true);\n const refusalPath = join(paths.refusals, `${input.sessionKey}.json`);\n unlinkStateFile(refusalPath, paths.root, true);\n baseline = null;\n }\n }\n\n const candidate = createCandidate({\n sessionKey: input.sessionKey,\n projectSlug: input.projectSlug,\n repoPath: input.repoPath,\n baseline,\n endRevision: input.endRevision,\n endStatusDigest: input.endStatusDigest,\n now,\n limits: input.limits,\n });\n if (candidate.bytes > input.limits.receipt_max_bytes) throw new NotebookError(\"INTERNAL_ERROR\", \"Capture receipt candidate exceeds its per-receipt ceiling\");\n\n const summary = captureAdmissionSummary(input.root, input.projectSlug, input.limits, now);\n if (summary.unmeasurable_entry_count > 0 || summary.unresolved_count === null || summary.unresolved_bytes === null) {\n const ids = summary.integrity_entries.map((entry) => entry.entry_id).join(\",\");\n return {\n outcome: \"state-integrity\",\n summary,\n diagnostic: `state-integrity: this session was not captured; unresolved bytes>=${summary.unresolved_bytes_lower_bound} exact=unknown unmeasurable=${summary.unmeasurable_entry_count} entries=${ids}; run pj notebook audit ${input.repoPath} --local-only --json, repair the reported entry in place without deleting it, then rerun pj notebook audit ${input.repoPath} --local-only --json`,\n };\n }\n\n const countBlocked = summary.unresolved_count + 1 > input.limits.unresolved_receipt_max_count;\n const byteBlocked = summary.unresolved_bytes + candidate.bytes > input.limits.unresolved_receipt_max_bytes;\n if (countBlocked || byteBlocked) {\n const actions = recoveryActions(receiptId, input.repoPath);\n const refusalPath = join(paths.refusals, `${input.sessionKey}.json`);\n const oldRead = existsSync(refusalPath) ? safeReadJson(refusalPath, input.limits.receipt_max_bytes) : undefined;\n const old = oldRead?.value === undefined ? null : parseRefusal(oldRead.value);\n const marker: RetentionRefusalV1 = {\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n session_key: input.sessionKey,\n baseline_created_at: old?.baseline_created_at ?? baseline?.created_at ?? now.toISOString(),\n refused_at: now.toISOString(),\n reason: capReason(countBlocked, byteBlocked),\n current_count: summary.unresolved_count,\n current_bytes: summary.unresolved_bytes,\n candidate_bytes: candidate.bytes,\n max_count: input.limits.unresolved_receipt_max_count,\n max_bytes: input.limits.unresolved_receipt_max_bytes,\n next_actions: actions,\n };\n atomicWriteJson(refusalPath, marker, paths.root);\n return {\n outcome: \"retention-pressure\",\n marker,\n diagnostic: `retention-pressure: this session was not captured; unresolved count=${marker.current_count}/${marker.max_count} bytes=${marker.current_bytes}/${marker.max_bytes} candidate_bytes=${marker.candidate_bytes} reason=${marker.reason}; run ${actions[0]}, then ${actions[1]}`,\n };\n }\n\n if (!exclusiveWrite(receiptPath, candidate.text, paths.root)) {\n const read = safeReadJson(receiptPath, input.limits.receipt_max_bytes);\n const receipt = read.value === undefined ? null : parseReceipt(read.value);\n if (!receipt) throw new NotebookError(\"INTERNAL_ERROR\", \"Concurrent receipt creation produced invalid state\");\n return { outcome: \"deduplicated\", receipt };\n }\n removeValidRefusal(paths, input.sessionKey, input.limits);\n return { outcome: \"admitted\", receipt: candidate.receipt, candidate_bytes: candidate.bytes };\n } finally {\n release();\n }\n}\n\nexport function receiptSummary(receipt: CaptureReceiptV1): CaptureReceiptSummaryV1 {\n return {\n receipt_id: receipt.receipt_id,\n logical_id: receipt.logical_id,\n session_key: receipt.session_key,\n state: receipt.state,\n created_at: receipt.created_at,\n updated_at: receipt.updated_at,\n automatic_attempts_used: receipt.automatic_attempts_used,\n automatic_attempt_limit: receipt.automatic_attempt_limit,\n manual_retry_count: receipt.manual_retry_count,\n attempt_origin: receipt.attempt_origin,\n error_category: receipt.error_category,\n retryable: receipt.retryable,\n diagnostic: receipt.diagnostic,\n summary_mode: receipt.summary_mode,\n exclusion_counts: { ...receipt.exclusion_counts },\n note_logical_ids: [...receipt.note_logical_ids],\n remote_note_ids: [...receipt.remote_note_ids],\n serialized_bytes: receipt.serialized_bytes,\n };\n}\n\nexport function listCaptureReceipts(root: string, projectSlug: string, limits: NotebookLimitsV1, state?: string): CaptureReceiptSummaryV1[] {\n const paths = notebookStatePaths(root, projectSlug);\n const scan = scanReceipts(paths, limits);\n if (scan.integrityCount) throw new NotebookError(\"CONFLICT\", \"Notebook capture state has integrity findings\", false, { entries: scan.integrityCount });\n if (state && !([\"queued\", \"processing\", \"succeeded\", \"failed\", \"retry-exhausted\", \"blocked-missing-baseline\"] as const).includes(state as never)) {\n throw new NotebookError(\"INVALID_INPUT\", `Unknown capture receipt state: ${state}`);\n }\n return scan.receipts\n .filter((receipt) => !state || receipt.state === state)\n .sort((a, b) => b.updated_at.localeCompare(a.updated_at) || a.receipt_id.localeCompare(b.receipt_id))\n .map(receiptSummary);\n}\n\nexport function readCaptureReceipt(root: string, projectSlug: string, receiptId: string, limits: NotebookLimitsV1): CaptureReceiptV1 {\n if (!RECEIPT_ID_RE.test(receiptId)) throw new NotebookError(\"INVALID_INPUT\", \"Invalid receipt ID\");\n const paths = notebookStatePaths(root, projectSlug);\n const path = join(paths.receipts, `${receiptId}.json`);\n if (!existsSync(path)) throw new NotebookError(\"NOT_FOUND\", `Capture receipt not found: ${receiptId}`);\n const read = safeReadJson(path, limits.receipt_max_bytes);\n const receipt = read.value === undefined ? null : parseReceipt(read.value);\n if (!receipt || receipt.serialized_bytes !== read.bytes) throw new NotebookError(\"CONFLICT\", `Capture receipt has an integrity finding: ${receiptId}`);\n return receipt;\n}\n\nfunction writeReceipt(paths: NotebookStatePaths, receipt: CaptureReceiptV1, limit: number): CaptureReceiptV1 {\n let text = jsonLine(receipt);\n for (let i = 0; i < 8; i++) {\n const bytes = Buffer.byteLength(text, \"utf8\");\n if (bytes > limit) throw new NotebookError(\"CONFLICT\", \"Receipt transition exceeds its per-receipt ceiling\");\n if (receipt.serialized_bytes === bytes) {\n atomicWriteJson(join(paths.receipts, `${receipt.receipt_id}.json`), receipt, paths.root);\n return receipt;\n }\n receipt.serialized_bytes = bytes;\n text = jsonLine(receipt);\n }\n throw new NotebookError(\"INTERNAL_ERROR\", \"Receipt transition size did not converge\");\n}\n\nexport interface CaptureReceiptVersionV1 {\n state: CaptureReceiptV1[\"state\"];\n updated_at: string;\n lease_owner: string | null;\n}\n\nexport function captureReceiptVersion(receipt: CaptureReceiptV1): CaptureReceiptVersionV1 {\n return { state: receipt.state, updated_at: receipt.updated_at, lease_owner: receipt.lease_owner };\n}\n\nfunction nextReceiptTimestamp(receipt: CaptureReceiptV1, now: Date): string {\n const requested = now.getTime();\n const previous = Date.parse(receipt.updated_at);\n return new Date(Number.isFinite(previous) && requested <= previous ? previous + 1 : requested).toISOString();\n}\n\nexport function authorizeCaptureRetry(input: {\n root: string;\n projectSlug: string;\n receiptId: string;\n limits: NotebookLimitsV1;\n baseline?: string;\n validateBaseline?: (gitRef: string) => boolean;\n now?: Date;\n}): CaptureReceiptV1 {\n const paths = ensureNotebookState(input.root, input.projectSlug);\n const release = acquireLock(paths, 1_000);\n try {\n const receipt = readCaptureReceipt(input.root, input.projectSlug, input.receiptId, input.limits);\n if (receipt.state === \"blocked-missing-baseline\") {\n if (!input.baseline) throw new NotebookError(\"INVALID_INPUT\", \"blocked-missing-baseline requires --baseline GIT_REF\");\n if (!input.validateBaseline?.(input.baseline)) throw new NotebookError(\"INVALID_INPUT\", \"--baseline must name a contained committed Git reference\");\n receipt.manual_baseline_ref = input.baseline;\n receipt.baseline_ref = input.baseline;\n } else if (receipt.state !== \"failed\" && receipt.state !== \"retry-exhausted\") {\n throw new NotebookError(\"CONFLICT\", `Receipt in state ${receipt.state} cannot be retried`);\n }\n receipt.state = \"queued\";\n receipt.manual_retry_count += 1;\n receipt.attempt_origin = \"operator\";\n receipt.lease_owner = null;\n receipt.lease_deadline = null;\n receipt.updated_at = nextReceiptTimestamp(receipt, input.now ?? new Date());\n receipt.error_category = null;\n receipt.retryable = false;\n receipt.diagnostic = null;\n return writeReceipt(paths, receipt, input.limits.receipt_max_bytes);\n } finally { release(); }\n}\n\nexport function claimCaptureReceipt(input: {\n root: string;\n projectSlug: string;\n receiptId: string;\n limits: NotebookLimitsV1;\n workerId?: string;\n now?: Date;\n}): CaptureReceiptV1 {\n const paths = ensureNotebookState(input.root, input.projectSlug);\n const release = acquireLock(paths, 1_000);\n try {\n const receipt = readCaptureReceipt(input.root, input.projectSlug, input.receiptId, input.limits);\n const now = input.now ?? new Date();\n const resumingExpiredLease = receipt.state === \"processing\" && Boolean(receipt.lease_deadline) && Date.parse(receipt.lease_deadline!) <= now.getTime();\n const resumingAutomaticFailure = receipt.state === \"failed\" && receipt.attempt_origin === \"automatic\" && receipt.retryable\n && receipt.automatic_attempts_used < receipt.automatic_attempt_limit;\n if (receipt.state !== \"queued\" && !resumingExpiredLease && !resumingAutomaticFailure) throw new NotebookError(\"CONFLICT\", `Receipt in state ${receipt.state} cannot be claimed`);\n if (receipt.attempt_origin === \"automatic\") {\n if (receipt.automatic_attempts_used >= receipt.automatic_attempt_limit) {\n if (resumingExpiredLease) {\n receipt.state = \"retry-exhausted\";\n receipt.lease_owner = null;\n receipt.lease_deadline = null;\n receipt.updated_at = nextReceiptTimestamp(receipt, now);\n receipt.retryable = false;\n receipt.diagnostic = \"Expired worker lease exhausted the finite automatic attempt budget\";\n writeReceipt(paths, receipt, input.limits.receipt_max_bytes);\n }\n throw new NotebookError(\"CONFLICT\", \"Automatic capture attempt budget is exhausted\");\n }\n receipt.automatic_attempts_used += 1;\n }\n receipt.state = \"processing\";\n receipt.lease_owner = (input.workerId ?? `${process.pid}-${randomUUID()}`).slice(0, 128);\n receipt.lease_deadline = new Date(now.getTime() + input.limits.lease_seconds * 1_000).toISOString();\n receipt.updated_at = nextReceiptTimestamp(receipt, now);\n return writeReceipt(paths, receipt, input.limits.receipt_max_bytes);\n } finally { release(); }\n}\n\nexport function renewCaptureReceiptLease(input: {\n root: string;\n projectSlug: string;\n receiptId: string;\n limits: NotebookLimitsV1;\n expected: CaptureReceiptVersionV1;\n now?: Date;\n}): CaptureReceiptV1 {\n const paths = ensureNotebookState(input.root, input.projectSlug);\n const release = acquireLock(paths, 1_000);\n try {\n const receipt = readCaptureReceipt(input.root, input.projectSlug, input.receiptId, input.limits);\n if (receipt.state !== \"processing\" || !receipt.lease_owner\n || receipt.state !== input.expected.state || receipt.updated_at !== input.expected.updated_at || receipt.lease_owner !== input.expected.lease_owner) {\n throw new NotebookError(\"CONFLICT\", \"Capture receipt lease changed; stale worker renewal rejected\");\n }\n const now = input.now ?? new Date();\n receipt.lease_deadline = new Date(now.getTime() + input.limits.lease_seconds * 1_000).toISOString();\n receipt.updated_at = nextReceiptTimestamp(receipt, now);\n return writeReceipt(paths, receipt, input.limits.receipt_max_bytes);\n } finally { release(); }\n}\n\nexport function transitionCaptureReceipt(input: {\n root: string;\n projectSlug: string;\n receiptId: string;\n limits: NotebookLimitsV1;\n expected: CaptureReceiptVersionV1;\n state: CaptureReceiptV1[\"state\"];\n errorCategory?: CaptureReceiptV1[\"error_category\"];\n retryable?: boolean;\n diagnostic?: string | null;\n exclusionCounts?: Record<string, number>;\n summaryMode?: CaptureReceiptV1[\"summary_mode\"];\n noteLogicalIds?: string[];\n remoteNoteIds?: string[];\n endRevision?: string | null;\n endStatusDigest?: string | null;\n now?: Date;\n}): CaptureReceiptV1 {\n const paths = ensureNotebookState(input.root, input.projectSlug);\n const release = acquireLock(paths, 1_000);\n try {\n const receipt = readCaptureReceipt(input.root, input.projectSlug, input.receiptId, input.limits);\n if (receipt.state !== input.expected.state || receipt.updated_at !== input.expected.updated_at || receipt.lease_owner !== input.expected.lease_owner) {\n throw new NotebookError(\"CONFLICT\", \"Capture receipt changed after it was claimed; stale worker transition rejected\");\n }\n if (receipt.state === \"processing\" && !receipt.lease_owner) throw new NotebookError(\"CONFLICT\", \"Processing receipt has no valid lease owner\");\n const allowed: Record<CaptureReceiptV1[\"state\"], ReadonlySet<CaptureReceiptV1[\"state\"]>> = {\n queued: new Set([\"processing\"]),\n processing: new Set([\"succeeded\", \"failed\", \"retry-exhausted\", \"blocked-missing-baseline\"]),\n failed: new Set([\"queued\"]),\n \"retry-exhausted\": new Set(),\n \"blocked-missing-baseline\": new Set(),\n succeeded: new Set(),\n };\n if (!allowed[receipt.state].has(input.state)) throw new NotebookError(\"CONFLICT\", `Capture receipt cannot transition from ${receipt.state} to ${input.state}`);\n receipt.state = input.state;\n receipt.updated_at = nextReceiptTimestamp(receipt, input.now ?? new Date());\n receipt.lease_owner = null;\n receipt.lease_deadline = null;\n receipt.error_category = input.errorCategory ?? null;\n receipt.retryable = input.retryable ?? false;\n receipt.diagnostic = input.diagnostic?.slice(0, input.limits.diagnostic_max_chars) ?? null;\n if (input.exclusionCounts) receipt.exclusion_counts = { ...input.exclusionCounts };\n if (input.summaryMode !== undefined) receipt.summary_mode = input.summaryMode;\n if (input.noteLogicalIds) receipt.note_logical_ids = [...new Set(input.noteLogicalIds)].slice(0, 2_000);\n if (input.remoteNoteIds) receipt.remote_note_ids = [...new Set(input.remoteNoteIds)].slice(0, 2_000);\n if (input.endRevision !== undefined) receipt.end_revision = input.endRevision;\n if (input.endStatusDigest !== undefined) receipt.end_status_digest = input.endStatusDigest;\n return writeReceipt(paths, receipt, input.limits.receipt_max_bytes);\n } finally { release(); }\n}\n\nexport function pruneNotebookState(root: string, projectSlug: string, limits: NotebookLimitsV1, now = new Date()): string[] {\n const paths = ensureNotebookState(root, projectSlug);\n const release = acquireLock(paths, 1_000);\n const removed: string[] = [];\n try {\n const scan = scanReceipts(paths, limits);\n const auxiliary = scanAuxiliaryState(paths, limits);\n if (scan.integrityCount || auxiliary.integrityCount) return removed;\n const successCutoff = now.getTime() - limits.receipt_succeeded_retention_days * 86_400_000;\n for (const receipt of scan.receipts) {\n if (receipt.state !== \"succeeded\" || Date.parse(receipt.updated_at) > successCutoff) continue;\n const path = join(paths.receipts, `${receipt.receipt_id}.json`);\n unlinkStateFile(path, paths.root);\n removed.push(safeEntryId(\"receipts\", basename(path)));\n }\n const remaining = scanReceipts(paths, limits);\n const remainingAuxiliary = scanAuxiliaryState(paths, limits);\n const referenced = new Set([...remaining.referencedSessions, ...remainingAuxiliary.referencedSessions]);\n for (const entry of readStateDirectory(paths.baselines, paths.root)) {\n if (!entry.isFile() || !entry.name.endsWith(\".json\")) continue;\n const path = join(paths.baselines, entry.name);\n const baseline = readBaseline(path, baselineReceiptByteCeiling(limits));\n if (!baseline || referenced.has(baseline.session_key)) continue;\n if (now.getTime() < Date.parse(baseline.created_at) + limits.receiptless_session_retention_seconds * 1_000) continue;\n unlinkStateFile(path, paths.root);\n removed.push(safeEntryId(\"baselines\", entry.name));\n const claim = join(paths.claims, `${baseline.session_key}.overview`);\n if (unlinkStateFile(claim, paths.root, true)) removed.push(safeEntryId(\"claims\", basename(claim)));\n const refusal = join(paths.refusals, `${baseline.session_key}.json`);\n if (unlinkStateFile(refusal, paths.root, true)) removed.push(safeEntryId(\"refusals\", basename(refusal)));\n }\n fsyncDirectory(paths.project);\n return removed;\n } finally { release(); }\n}\n\nexport function currentRetentionPressure(summary: CaptureAdmissionSummaryV1): Array<{ code: \"retention-pressure\"; session_key?: string; reason: RetentionRefusalReason | \"current-usage\" }> {\n if (summary.unresolved_count === null || summary.unresolved_bytes === null) return [];\n const findings: Array<{ code: \"retention-pressure\"; session_key?: string; reason: RetentionRefusalReason | \"current-usage\" }> = [];\n if (summary.unresolved_count >= summary.receipt_caps.max_count || summary.unresolved_bytes >= summary.receipt_caps.max_bytes) {\n findings.push({ code: \"retention-pressure\", reason: \"current-usage\" });\n }\n for (const marker of summary.active_refusals) {\n const countBlocked = summary.unresolved_count + 1 > summary.receipt_caps.max_count;\n const byteBlocked = summary.unresolved_bytes + marker.candidate_bytes > summary.receipt_caps.max_bytes;\n if (countBlocked || byteBlocked) findings.push({ code: \"retention-pressure\", session_key: marker.session_key, reason: capReason(countBlocked, byteBlocked) });\n }\n return findings;\n}\n\nexport function statePathForReceipt(root: string, projectSlug: string, receiptId: string): string {\n if (!RECEIPT_ID_RE.test(receiptId)) throw new NotebookError(\"INVALID_INPUT\", \"Invalid receipt ID\");\n return join(projectStateDir(root, projectSlug), \"receipts\", `${receiptId}.json`);\n}\n", "import { runtimeNotebookCredential, validateNotebookBaseUrl } from \"./config\";\nimport {\n NotebookError,\n type EffectiveNotebookConfigV1,\n type OpenNotebookNotebookV1,\n type OpenNotebookNoteV1,\n} from \"./types\";\n\nexport interface OpenNotebookHealthV1 {\n version: string | null;\n auth_enabled: boolean | null;\n}\n\nexport interface OpenNotebookClientOptions {\n fetch?: typeof globalThis.fetch;\n env?: NodeJS.ProcessEnv;\n /** Absolute performance.now() deadline shared by a composite hook action. */\n deadlineMonotonicMs?: number;\n}\n\ntype RequestOptions = {\n method?: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n body?: Record<string, unknown>;\n allowEmpty?: boolean;\n possiblyDispatched?: () => void;\n definitivelyRejected?: (status: 400 | 422) => void;\n skipAuthProbe?: boolean;\n suppressAuthorization?: boolean;\n deadlineMonotonicMs?: number;\n};\n\nexport type OpenNotebookTransportNoteType = \"human\" | \"ai\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction boundedString(value: unknown, name: string, max = 1_048_576): string {\n if (typeof value !== \"string\" || value.length > max) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", `Open Notebook returned invalid ${name}`);\n return value;\n}\n\nfunction optionalString(value: unknown, name: string, max = 8_192): string | null | undefined {\n if (value == null) return value as null | undefined;\n return boundedString(value, name, max);\n}\n\nfunction responseTimestamp(value: Record<string, unknown>, current: \"created\" | \"updated\", legacy: \"created_at\" | \"updated_at\", subject: \"notebook\" | \"note\"): string | null | undefined {\n return optionalString(value[current] !== undefined ? value[current] : value[legacy], `${subject} ${current}`, 128);\n}\n\nexport function normalizeOpenNotebookNoteType(value: string | undefined): OpenNotebookTransportNoteType {\n const normalized = value ?? \"human\";\n if (normalized !== \"human\" && normalized !== \"ai\") throw new NotebookError(\"INVALID_INPUT\", \"Open Notebook note_type must be human or ai\");\n return normalized;\n}\n\nfunction parseNotebook(value: unknown): OpenNotebookNotebookV1 {\n if (!isRecord(value)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook returned an invalid notebook\");\n return {\n id: boundedString(value.id, \"notebook id\", 512),\n name: boundedString(value.name, \"notebook name\", 4_096),\n description: optionalString(value.description, \"notebook description\", 16_384),\n archived: typeof value.archived === \"boolean\" ? value.archived : undefined,\n created_at: responseTimestamp(value, \"created\", \"created_at\", \"notebook\"),\n updated_at: responseTimestamp(value, \"updated\", \"updated_at\", \"notebook\"),\n };\n}\n\ntype ScopedNoteListItemV1 = Omit<OpenNotebookNoteV1, \"content\"> & { content: string | null };\n\nfunction parseNoteRecord(value: unknown, noteMaxBytes: number, allowNullContent: boolean): ScopedNoteListItemV1 {\n if (!isRecord(value)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook returned an invalid note\");\n const content = value.content === null && allowNullContent ? null : boundedString(value.content, \"note content\", noteMaxBytes);\n if (content !== null && Buffer.byteLength(content, \"utf8\") > noteMaxBytes) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook note content exceeds the configured ceiling\");\n const noteType = boundedString(value.note_type, \"note type\", 128);\n if (noteType !== \"human\" && noteType !== \"ai\") throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook returned an unsupported note type\");\n return {\n id: boundedString(value.id, \"note id\", 512),\n title: boundedString(value.title, \"note title\", 4_096),\n content,\n note_type: noteType,\n created_at: responseTimestamp(value, \"created\", \"created_at\", \"note\") ?? null,\n updated_at: responseTimestamp(value, \"updated\", \"updated_at\", \"note\") ?? null,\n };\n}\n\nfunction parseScopedNoteListItem(value: unknown, noteMaxBytes: number): ScopedNoteListItemV1 {\n return parseNoteRecord(value, noteMaxBytes, true);\n}\n\nfunction parseNote(value: unknown, noteMaxBytes: number): OpenNotebookNoteV1 {\n const note = parseNoteRecord(value, noteMaxBytes, false);\n if (note.content === null) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook returned invalid note content\");\n return note as OpenNotebookNoteV1;\n}\n\nfunction errorForStatus(status: number, message: string): NotebookError {\n if (status === 400 || status === 422) return new NotebookError(\"INVALID_INPUT\", message, false, { http_status: status, definitive_rejection: true });\n if (status === 401 || status === 403) return new NotebookError(\"AUTHENTICATION_FAILED\", message);\n if (status === 404) return new NotebookError(\"NOT_FOUND\", message);\n if (status === 409) return new NotebookError(\"CONFLICT\", message);\n if (status === 429) return new NotebookError(\"THROTTLED\", message, true);\n if (status >= 500) return new NotebookError(\"SERVICE_UNAVAILABLE\", message, true);\n return new NotebookError(\"REMOTE_PROTOCOL_ERROR\", message);\n}\n\nasync function readResponseBody(response: Response, maxBytes: number): Promise<Buffer> {\n const declared = Number(response.headers.get(\"content-length\") ?? \"0\");\n if (Number.isFinite(declared) && declared > maxBytes) {\n try { await response.body?.cancel(); } catch { /* best-effort transport release */ }\n throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook response exceeds the configured ceiling\");\n }\n if (!response.body) return Buffer.alloc(0);\n const reader = response.body.getReader();\n const chunks: Buffer[] = [];\n let bytes = 0;\n try {\n while (true) {\n const next = await reader.read();\n if (next.done) break;\n const chunk = Buffer.from(next.value);\n bytes += chunk.byteLength;\n if (bytes > maxBytes) {\n try { await reader.cancel(); } catch { /* preserve the bounded protocol error */ }\n throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook response exceeds the configured ceiling\");\n }\n chunks.push(chunk);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks, bytes);\n}\n\n/** Sole HTTP adapter for Open Notebook. Domain callers never construct URLs. */\nexport class OpenNotebookClient {\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly baseUrl: string;\n private readonly env: NodeJS.ProcessEnv;\n private readonly deadlineMonotonicMs?: number;\n private authEnabled: boolean | null | undefined;\n\n constructor(readonly config: EffectiveNotebookConfigV1, options: OpenNotebookClientOptions = {}) {\n if (!config.base_url) throw new NotebookError(\"NOT_CONFIGURED\", \"Notebook base_url is not configured\");\n this.baseUrl = validateNotebookBaseUrl(config.base_url);\n this.fetchImpl = options.fetch ?? globalThis.fetch;\n this.env = options.env ?? process.env;\n this.deadlineMonotonicMs = options.deadlineMonotonicMs;\n }\n\n async health(): Promise<OpenNotebookHealthV1> {\n const value = await this.request(\"/api/config\", { skipAuthProbe: true, suppressAuthorization: true });\n if (!isRecord(value)) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook /api/config returned a non-object\");\n const version = typeof value.version === \"string\"\n ? value.version.slice(0, 128)\n : typeof value.app_version === \"string\" ? value.app_version.slice(0, 128) : null;\n const authEnabled = await this.authStatus();\n return { version, auth_enabled: authEnabled };\n }\n\n async authStatus(): Promise<boolean> {\n const value = await this.request(\"/api/auth/status\", { skipAuthProbe: true, suppressAuthorization: true });\n if (!isRecord(value) || typeof value.auth_enabled !== \"boolean\") throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook auth status returned an invalid response\");\n this.authEnabled = value.auth_enabled;\n return value.auth_enabled;\n }\n\n async listNotebooks(): Promise<OpenNotebookNotebookV1[]> {\n const value = await this.request(\"/api/notebooks\");\n if (!Array.isArray(value) || value.length > this.config.limits.list_max_items) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook notebook list is invalid or incomplete under configured limits\");\n return value.map(parseNotebook);\n }\n\n async createNotebook(input: { name: string; description?: string }, possiblyDispatched?: () => void): Promise<OpenNotebookNotebookV1> {\n return parseNotebook(await this.request(\"/api/notebooks\", { method: \"POST\", body: input, possiblyDispatched }));\n }\n\n async updateNotebook(id: string, input: { name?: string; description?: string; archived?: boolean }): Promise<OpenNotebookNotebookV1> {\n return parseNotebook(await this.request(`/api/notebooks/${encodeURIComponent(id)}`, { method: \"PUT\", body: input }));\n }\n\n async listNotes(notebookId: string): Promise<OpenNotebookNoteV1[]> {\n const operationDeadline = Math.min(\n this.deadlineMonotonicMs ?? Number.POSITIVE_INFINITY,\n performance.now() + this.config.limits.overall_timeout_ms,\n );\n const value = await this.request(`/api/notes?notebook_id=${encodeURIComponent(notebookId)}`, { deadlineMonotonicMs: operationDeadline });\n if (!Array.isArray(value) || value.length > this.config.limits.list_max_items) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook scoped note list is invalid or incomplete under configured limits\");\n const members = value.map((item) => parseScopedNoteListItem(item, this.config.limits.note_max_bytes));\n if (new Set(members.map((item) => item.id)).size !== members.length) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook scoped note list contains duplicate IDs\");\n const notes = new Array<OpenNotebookNoteV1>(members.length);\n let nextIndex = 0;\n const hydrate = async (): Promise<void> => {\n while (true) {\n const index = nextIndex;\n nextIndex += 1;\n const member = members[index];\n if (!member) return;\n const detail = parseNote(await this.request(`/api/notes/${encodeURIComponent(member.id)}`, { deadlineMonotonicMs: operationDeadline }), this.config.limits.note_max_bytes);\n if (detail.id !== member.id) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook note detail ID does not match the proven notebook member\");\n notes[index] = detail;\n }\n };\n const workerCount = Math.min(members.length, this.config.limits.note_detail_fetch_concurrency);\n await Promise.all(Array.from({ length: workerCount }, () => hydrate()));\n return notes;\n }\n\n async createNote(notebookId: string, input: { title: string; content: string; note_type?: string }, possiblyDispatched?: () => void, definitivelyRejected?: (status: 400 | 422) => void): Promise<OpenNotebookNoteV1> {\n if (Buffer.byteLength(input.content, \"utf8\") > this.config.limits.note_max_bytes) throw new NotebookError(\"INVALID_INPUT\", \"Note content exceeds the configured ceiling\");\n const noteType = normalizeOpenNotebookNoteType(input.note_type);\n return parseNote(await this.request(\"/api/notes\", {\n method: \"POST\",\n body: { notebook_id: notebookId, title: input.title, content: input.content, note_type: noteType },\n possiblyDispatched,\n definitivelyRejected,\n }), this.config.limits.note_max_bytes);\n }\n\n async getOwnedNote(notebookId: string, noteId: string): Promise<OpenNotebookNoteV1> {\n const notes = await this.listNotes(notebookId);\n const note = notes.find((item) => item.id === noteId);\n if (!note) throw new NotebookError(\"NOT_FOUND\", `Note is not a proven member of the bound notebook: ${noteId}`);\n return note;\n }\n\n async updateOwnedNote(notebookId: string, noteId: string, input: { title?: string; content?: string }): Promise<OpenNotebookNoteV1> {\n if (input.content !== undefined && Buffer.byteLength(input.content, \"utf8\") > this.config.limits.note_max_bytes) throw new NotebookError(\"INVALID_INPUT\", \"Note content exceeds the configured ceiling\");\n await this.getOwnedNote(notebookId, noteId);\n return parseNote(await this.request(`/api/notes/${encodeURIComponent(noteId)}`, { method: \"PUT\", body: input }), this.config.limits.note_max_bytes);\n }\n\n async deleteOwnedNote(notebookId: string, noteId: string): Promise<void> {\n await this.getOwnedNote(notebookId, noteId);\n await this.request(`/api/notes/${encodeURIComponent(noteId)}`, { method: \"DELETE\", allowEmpty: true });\n }\n\n private async ensureAuthProbe(): Promise<void> {\n if (this.authEnabled !== undefined) return;\n if (this.config.auth.mode === \"none\") { this.authEnabled = null; return; }\n try {\n await this.authStatus();\n } catch (error) {\n // A real 401/403 remains authoritative. Other config-probe failures do\n // not downgrade the requested operation or cause credentials to leak.\n if (error instanceof NotebookError && error.code === \"AUTHENTICATION_FAILED\") throw error;\n this.authEnabled = null;\n }\n }\n\n private async request(path: string, options: RequestOptions = {}): Promise<unknown> {\n if (!options.skipAuthProbe) await this.ensureAuthProbe();\n const method = options.method ?? \"GET\";\n const url = new URL(path, `${this.baseUrl}/`);\n if (url.origin !== new URL(this.baseUrl).origin) throw new NotebookError(\"INVALID_INPUT\", \"Open Notebook request escaped the configured origin\");\n const body = options.body === undefined ? undefined : JSON.stringify(options.body);\n if (body !== undefined && Buffer.byteLength(body, \"utf8\") > this.config.limits.request_max_bytes) throw new NotebookError(\"INVALID_INPUT\", \"Open Notebook request exceeds the configured ceiling\");\n const headers: Record<string, string> = { Accept: \"application/json\" };\n if (body !== undefined) headers[\"Content-Type\"] = \"application/json\";\n if (!options.suppressAuthorization && this.config.auth.mode === \"environment\" && this.authEnabled !== false) {\n headers.Authorization = `Bearer ${runtimeNotebookCredential(this.config, this.env)}`;\n }\n const deadline = Math.min(\n this.deadlineMonotonicMs ?? Number.POSITIVE_INFINITY,\n options.deadlineMonotonicMs ?? Number.POSITIVE_INFINITY,\n );\n const remaining = deadline === Number.POSITIVE_INFINITY\n ? this.config.limits.overall_timeout_ms\n : Math.floor(deadline - performance.now());\n if (remaining <= 0) throw new NotebookError(\"TIMEOUT\", \"Open Notebook request timed out\", true);\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), Math.max(1, Math.min(this.config.limits.overall_timeout_ms, remaining)));\n try {\n options.possiblyDispatched?.();\n const response = await this.fetchImpl(url, {\n method,\n headers,\n body,\n redirect: \"manual\",\n signal: controller.signal,\n });\n if (response.status >= 300 && response.status < 400) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook redirect was rejected\");\n if (!response.ok) {\n if (response.status === 400 || response.status === 422) options.definitivelyRejected?.(response.status);\n try { await readResponseBody(response, Math.min(this.config.limits.response_max_bytes, 4_096)); }\n catch { /* preserve the categorized HTTP status without response data */ }\n throw errorForStatus(response.status, `Open Notebook returned HTTP ${response.status}`);\n }\n if (options.allowEmpty && (response.status === 204 || response.headers.get(\"content-length\") === \"0\")) return null;\n const buffer = await readResponseBody(response, this.config.limits.response_max_bytes);\n if (!buffer.byteLength && options.allowEmpty) return null;\n try { return JSON.parse(buffer.toString(\"utf8\")) as unknown; }\n catch { throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Open Notebook returned malformed JSON\"); }\n } catch (error) {\n if (error instanceof NotebookError) throw error;\n if (controller.signal.aborted || (error as Error).name === \"AbortError\") throw new NotebookError(\"TIMEOUT\", \"Open Notebook request timed out\", true);\n throw new NotebookError(\"SERVICE_UNAVAILABLE\", \"Open Notebook request failed\", true, {}, { cause: error });\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from \"node:fs\";\nimport { extname, join, parse, relative, resolve, sep } from \"node:path\";\nimport { sha256Hex } from \"./notes\";\nimport { NotebookError, type EffectiveNotebookConfigV1, type SessionBaselineV1 } from \"./types\";\n\nexport interface GitSnapshotV1 {\n head: string | null;\n status_digest: string | null;\n dirty_paths: string[];\n tracked_path_digests: Record<string, string>;\n complete: boolean;\n reasons: string[];\n}\n\nexport interface EligibleDocumentV1 {\n path: string;\n source_revision: string;\n content_sha256: string;\n start_content_sha256?: string;\n content: string;\n}\n\nexport interface GitEvidenceSelectionV1 {\n documents: EligibleDocumentV1[];\n changed_paths: string[];\n exclusions: Record<string, number>;\n end_revision: string | null;\n end_status_digest: string | null;\n}\n\nfunction git(repo: string, args: string[], maxBuffer = 4 * 1024 * 1024, timeout = 5_000): { ok: boolean; stdout: string } {\n const result = spawnSync(\"git\", args, { cwd: repo, encoding: \"utf8\", maxBuffer, timeout, shell: false });\n return { ok: result.status === 0, stdout: result.stdout ?? \"\" };\n}\n\nfunction statusPaths(value: string): string[] {\n const entries = value.split(\"\\0\");\n const paths: string[] = [];\n for (let index = 0; index < entries.length; index++) {\n const entry = entries[index];\n if (!entry) continue;\n const status = entry.slice(0, 2);\n const path = entry.slice(3);\n if (path) paths.push(path);\n if (/[RC]/u.test(status)) {\n const prior = entries[++index];\n if (prior) paths.push(prior);\n }\n }\n return paths;\n}\n\nexport function captureGitSnapshot(repoPath: string, config?: EffectiveNotebookConfigV1, deadlineMonotonicMs?: number): GitSnapshotV1 {\n const configuredTimeout = config?.limits.overall_timeout_ms ?? 5_000;\n const remaining = (): number => deadlineMonotonicMs === undefined\n ? configuredTimeout\n : Math.max(0, Math.min(configuredTimeout, Math.floor(deadlineMonotonicMs - performance.now())));\n const boundedGit = (args: string[]) => {\n const timeout = remaining();\n return timeout > 0 ? git(repoPath, args, 4 * 1024 * 1024, timeout) : { ok: false, stdout: \"\" };\n };\n const headResult = boundedGit([\"rev-parse\", \"--verify\", \"HEAD\"]);\n const statusResult = boundedGit([\"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\"]);\n const reasons: string[] = [];\n if (deadlineMonotonicMs !== undefined && remaining() === 0) reasons.push(\"hook-deadline-exhausted\");\n if (!headResult.ok) reasons.push(\"missing-committed-head\");\n if (!statusResult.ok) reasons.push(\"git-status-failed\");\n const trackedPathDigests: Record<string, string> = {};\n if (config) {\n const trackedResult = boundedGit([\"ls-files\", \"-z\"]);\n if (!trackedResult.ok) reasons.push(\"git-tracked-files-failed\");\n else {\n const candidates = trackedResult.stdout.split(\"\\0\").filter(Boolean)\n .filter((path) => config.policy.documentation_globs.some((glob) => matchesSimpleGlob(path, glob)))\n .filter((path) => !config.policy.excluded_globs?.some((glob) => matchesSimpleGlob(path, glob)))\n .sort((a, b) => a.localeCompare(b, \"en\"));\n if (candidates.length > config.limits.list_max_items) reasons.push(\"tracked-document-limit\");\n for (const path of candidates.slice(0, config.limits.list_max_items)) {\n if (deadlineMonotonicMs !== undefined && remaining() === 0) { reasons.push(\"hook-deadline-exhausted\"); break; }\n if (looksGenerated(path)) continue;\n const file = readSafeEvidenceText(repoPath, path, config.limits.source_file_max_bytes);\n if (file.status !== \"present\") continue;\n trackedPathDigests[path] = file.content_sha256;\n }\n }\n }\n return {\n head: headResult.ok ? headResult.stdout.trim() : null,\n status_digest: statusResult.ok ? sha256Hex(statusResult.stdout) : null,\n dirty_paths: statusResult.ok ? [...new Set(statusPaths(statusResult.stdout))].sort() : [],\n tracked_path_digests: trackedPathDigests,\n complete: reasons.length === 0,\n reasons: [...new Set(reasons)],\n };\n}\n\nexport function validateCommittedGitRef(repoPath: string, gitRef: string): boolean {\n if (!gitRef || gitRef.length > 256 || gitRef.startsWith(\"-\")) return false;\n return git(repoPath, [\"rev-parse\", \"--verify\", `${gitRef}^{commit}`], 64 * 1024).ok;\n}\n\nfunction safeRelative(repoPath: string, relativePath: string): { root: string; candidate: string } | null {\n if (!relativePath || relativePath.includes(\"\\0\") || relativePath.startsWith(\"/\") || relativePath.split(/[\\\\/]/u).includes(\"..\")) return null;\n const root = realpathSync(repoPath);\n const candidate = resolve(root, relativePath);\n const rel = relative(root, candidate);\n if (rel === \"..\" || rel.startsWith(`..${sep}`) || rel.startsWith(sep)) return null;\n return { root, candidate };\n}\n\nexport type SafeEvidenceReadV1 =\n | { status: \"present\"; content: string; content_sha256: string; bytes: number }\n | { status: \"excluded\"; reason: \"unsafe-path\" | \"not-regular\" | \"oversize\" | \"binary\" | \"secret-like\" | \"changed-during-read\" };\n\nfunction hasSymlinkComponent(root: string, candidate: string): boolean {\n const rel = relative(root, candidate);\n let cursor = root;\n for (const part of rel.split(sep).filter(Boolean)) {\n cursor = join(cursor, part);\n try { if (lstatSync(cursor).isSymbolicLink()) return true; }\n catch { return true; }\n }\n return false;\n}\n\nexport function readSafeEvidenceText(repoPath: string, relativePath: string, maxBytes: number): SafeEvidenceReadV1 {\n const safe = safeRelative(repoPath, relativePath);\n if (!safe || hasSymlinkComponent(safe.root, safe.candidate)) return { status: \"excluded\", reason: \"unsafe-path\" };\n let fd: number;\n try { fd = openSync(safe.candidate, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)); }\n catch { return { status: \"excluded\", reason: \"not-regular\" }; }\n try {\n const before = fstatSync(fd);\n if (!before.isFile()) return { status: \"excluded\", reason: \"not-regular\" };\n if (before.size > maxBytes) return { status: \"excluded\", reason: \"oversize\" };\n let physical: string;\n try { physical = realpathSync(`/proc/self/fd/${fd}`); }\n catch { return { status: \"excluded\", reason: \"unsafe-path\" }; }\n const physicalRel = relative(safe.root, physical);\n if (physicalRel === \"..\" || physicalRel.startsWith(`..${sep}`) || physicalRel.startsWith(sep)) return { status: \"excluded\", reason: \"unsafe-path\" };\n const chunks: Buffer[] = [];\n let total = 0;\n while (true) {\n const chunk = Buffer.allocUnsafe(Math.min(8_192, maxBytes + 1 - total));\n const count = readSync(fd, chunk, 0, chunk.length, null);\n if (!count) break;\n total += count;\n if (total > maxBytes) return { status: \"excluded\", reason: \"oversize\" };\n chunks.push(chunk.subarray(0, count));\n }\n const after = fstatSync(fd);\n if (after.dev !== before.dev || after.ino !== before.ino || after.size !== before.size || total !== before.size) return { status: \"excluded\", reason: \"changed-during-read\" };\n const bytes = Buffer.concat(chunks, total);\n if (bytes.includes(0)) return { status: \"excluded\", reason: \"binary\" };\n let content: string;\n try { content = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes); }\n catch { return { status: \"excluded\", reason: \"binary\" }; }\n if (looksSecret(relativePath, content)) return { status: \"excluded\", reason: \"secret-like\" };\n return { status: \"present\", content, content_sha256: sha256Hex(bytes), bytes: total };\n } finally { closeSync(fd); }\n}\n\nfunction looksGenerated(path: string): boolean {\n return /(^|\\/)(dist|build|coverage|node_modules|vendor|\\.next|_site)(\\/|$)/u.test(path)\n || /(?:\\.min\\.|\\.generated\\.|-lock\\.)/u.test(path);\n}\n\nfunction looksSecret(path: string, content: string): boolean {\n if (/(^|\\/)(\\.env(?:\\.|$)|id_(?:rsa|ed25519)$)|(?:secret|credential|private[-_]?key)/iu.test(path)) return true;\n return /(?:BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|(?:api[_-]?key|password|token)\\s*[:=]\\s*[\"']?[A-Za-z0-9_+\\/-]{16,})/iu.test(content);\n}\n\nfunction matchesSimpleGlob(path: string, glob: string): boolean {\n // v1 defaults are suffix globs; support the common bounded subset without a\n // shell or a dependency whose semantics differ by platform.\n if (glob === \"**/*.md\") return path.toLowerCase().endsWith(\".md\");\n if (glob === \"**/*.mdx\") return path.toLowerCase().endsWith(\".mdx\");\n if (glob.startsWith(\"**/*.\")) return extname(path).toLowerCase() === `.${glob.slice(5).toLowerCase()}`;\n return path === glob;\n}\n\nfunction addExclusion(record: Record<string, number>, reason: string): void {\n record[reason] = (record[reason] ?? 0) + 1;\n}\n\nexport function selectEligibleDocuments(config: EffectiveNotebookConfigV1, baseline: SessionBaselineV1, manualBaselineRef?: string): GitEvidenceSelectionV1 {\n const repo = config.repo_path;\n const startRef = manualBaselineRef ?? baseline.git_head;\n if (!startRef || !validateCommittedGitRef(repo, startRef)) throw new NotebookError(\"INVALID_INPUT\", \"Capture baseline is not a committed Git reference\");\n const end = captureGitSnapshot(repo);\n if (!end.head) throw new NotebookError(\"CONFLICT\", \"Repository has no committed end revision\");\n\n const committed = git(repo, [\"diff\", \"--name-only\", \"-z\", `${startRef}..${end.head}`], 4 * 1024 * 1024, config.limits.overall_timeout_ms);\n const working = git(repo, [\"diff\", \"--name-only\", \"-z\", \"HEAD\"], 4 * 1024 * 1024, config.limits.overall_timeout_ms);\n const staged = git(repo, [\"diff\", \"--cached\", \"--name-only\", \"-z\"], 4 * 1024 * 1024, config.limits.overall_timeout_ms);\n if (!committed.ok || !working.ok || !staged.ok) throw new NotebookError(\"INTERNAL_ERROR\", \"Git evidence selection failed\");\n const uncommitted = new Set([...working.stdout.split(\"\\0\"), ...staged.stdout.split(\"\\0\")].filter(Boolean));\n const allChanged = [...new Set([...committed.stdout.split(\"\\0\"), ...uncommitted].filter(Boolean))].sort();\n const changed = allChanged.slice(0, config.limits.list_max_items);\n const trackedResult = git(repo, [\"ls-files\", \"-z\"], 4 * 1024 * 1024, config.limits.overall_timeout_ms);\n if (!trackedResult.ok) throw new NotebookError(\"INTERNAL_ERROR\", \"Git tracked-file enumeration failed\");\n const tracked = new Set(trackedResult.stdout.split(\"\\0\").filter(Boolean));\n const preDirty = new Set(baseline.pre_dirty_paths);\n const exclusions: Record<string, number> = {};\n const documents: EligibleDocumentV1[] = [];\n if (allChanged.length > changed.length) addExclusion(exclusions, \"changed-path-limit\");\n\n for (const path of changed) {\n if (manualBaselineRef && uncommitted.has(path)) { addExclusion(exclusions, \"manual-baseline-uncommitted\"); continue; }\n if (!tracked.has(path)) { addExclusion(exclusions, \"untracked\"); continue; }\n if (!config.policy.documentation_globs.some((glob) => matchesSimpleGlob(path, glob))) { addExclusion(exclusions, \"policy\"); continue; }\n if (config.policy.excluded_globs?.some((glob) => matchesSimpleGlob(path, glob))) { addExclusion(exclusions, \"excluded\"); continue; }\n if (looksGenerated(path)) { addExclusion(exclusions, \"generated\"); continue; }\n const file = readSafeEvidenceText(repo, path, config.limits.source_file_max_bytes);\n if (file.status !== \"present\") { addExclusion(exclusions, file.reason); continue; }\n const startDigest = baseline.tracked_path_digests[path];\n if (preDirty.has(path) && (!startDigest || startDigest === file.content_sha256)) {\n addExclusion(exclusions, startDigest ? \"pre-existing-dirty-unchanged\" : \"pre-existing-dirty-unknown\");\n continue;\n }\n documents.push({ path, source_revision: end.head, content_sha256: file.content_sha256, ...(startDigest ? { start_content_sha256: startDigest } : {}), content: file.content });\n }\n return {\n documents,\n changed_paths: changed,\n exclusions,\n end_revision: end.head,\n end_status_digest: end.status_digest,\n };\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport { canonicalJson, sha256Hex } from \"./notes\";\nimport {\n parseRemoteMutationJournal,\n remoteMutationNextAction,\n remoteMutationResultCategory,\n type DefinitiveRemoteMutationHttpStatus,\n type RemoteMutationJournalState,\n type RemoteMutationJournalV1,\n} from \"./remote-mutation-schema\";\nimport {\n atomicWriteJson,\n createNotebookStateJsonExclusive,\n ensureNotebookState,\n readNotebookStateDirectory,\n readNotebookStateJson,\n withNotebookStateLock,\n} from \"./state\";\nimport { NOTEBOOK_SCHEMA_VERSION, NotebookError } from \"./types\";\n\nexport type { RemoteMutationJournalState, RemoteMutationJournalV1 } from \"./remote-mutation-schema\";\n\nfunction journalPath(root: string, projectSlug: string, operationId: string): string {\n if (!/^[a-f0-9-]{16,64}$/iu.test(operationId)) throw new NotebookError(\"INVALID_INPUT\", \"Invalid remote mutation operation ID\");\n return join(ensureNotebookState(root, projectSlug).journals, `${operationId}.json`);\n}\n\nexport function remoteMutationJournalPath(root: string, projectSlug: string, operationId: string): string {\n return journalPath(root, projectSlug, operationId);\n}\n\nexport function mutationInputDigest(value: unknown): string {\n return sha256Hex(`pjangler-remote-mutation-v1\\0${canonicalJson(value)}`);\n}\n\nfunction assertBoundedJournalText(value: string, label: string): void {\n if (!value || Buffer.byteLength(value, \"utf8\") > 512 || /[\\u0000-\\u001f\\u007f]/u.test(value)) {\n throw new NotebookError(\"INVALID_INPUT\", `Invalid remote mutation ${label}`);\n }\n}\n\nexport function listRemoteMutationJournals(root: string, projectSlug: string): RemoteMutationJournalV1[] {\n const paths = ensureNotebookState(root, projectSlug);\n const journals: RemoteMutationJournalV1[] = [];\n for (const entry of readNotebookStateDirectory(paths.journals, paths.root)) {\n if (!entry.isFile() || entry.isSymbolicLink() || !/^[a-f0-9-]{16,64}\\.json$/iu.test(entry.name)) {\n throw new NotebookError(\"CONFLICT\", `Remote mutation journal state-integrity finding: journals/${entry.name}`);\n }\n const read = readNotebookStateJson(join(paths.journals, entry.name), paths.root, 65_536);\n const journal = read.value === undefined ? null : parseRemoteMutationJournal(read.value);\n if (!journal || `${journal.operation_id}.json` !== entry.name) {\n throw new NotebookError(\"CONFLICT\", `Remote mutation journal state-integrity finding: journals/${entry.name}`);\n }\n journals.push(journal);\n }\n return journals.sort((a, b) => a.prepared_at.localeCompare(b.prepared_at) || a.operation_id.localeCompare(b.operation_id));\n}\n\nexport function findActiveRemoteMutation(root: string, projectSlug: string, kind: RemoteMutationJournalV1[\"kind\"], inputDigest: string): RemoteMutationJournalV1 | undefined {\n return listRemoteMutationJournals(root, projectSlug).find((item) => item.kind === kind && item.input_digest === inputDigest && item.state !== \"committed\");\n}\n\nexport function prepareRemoteMutation(input: {\n root: string;\n projectSlug: string;\n kind: RemoteMutationJournalV1[\"kind\"];\n logicalMarker: string;\n inputDigest: string;\n dispatchDigest?: string;\n sessionKey?: string;\n bindingId?: string;\n operationId?: string;\n now?: Date;\n}): RemoteMutationJournalV1 {\n if (!/^[a-f0-9]{64}$/u.test(input.inputDigest)) throw new NotebookError(\"INVALID_INPUT\", \"Invalid remote mutation input digest\");\n if (input.dispatchDigest !== undefined && !/^[a-f0-9]{64}$/u.test(input.dispatchDigest)) throw new NotebookError(\"INVALID_INPUT\", \"Invalid remote mutation dispatch digest\");\n if (input.sessionKey && !/^[a-f0-9]{64}$/u.test(input.sessionKey)) throw new NotebookError(\"INVALID_INPUT\", \"Invalid remote mutation session key\");\n assertBoundedJournalText(input.logicalMarker, \"logical marker\");\n if (input.bindingId !== undefined) assertBoundedJournalText(input.bindingId, \"binding ID\");\n return withNotebookStateLock(input.root, input.projectSlug, 1_000, (paths) => {\n const active = listRemoteMutationJournals(input.root, input.projectSlug)\n .find((item) => item.kind === input.kind && item.state !== \"committed\"\n && (item.input_digest === input.inputDigest || item.logical_marker === input.logicalMarker));\n if (active) {\n if (active.state !== \"prepared\") return active;\n if (active.input_digest === input.inputDigest && active.dispatch_digest === input.dispatchDigest) return active;\n const requested = (input.now ?? new Date()).getTime();\n const previous = Date.parse(active.updated_at);\n const { dispatch_digest: _dispatchDigest, ...activeWithoutDispatchDigest } = active;\n const updated: RemoteMutationJournalV1 = {\n ...activeWithoutDispatchDigest,\n input_digest: input.inputDigest,\n ...(input.dispatchDigest ? { dispatch_digest: input.dispatchDigest } : {}),\n ...(input.bindingId ? { binding_id: input.bindingId } : {}),\n ...(input.sessionKey ? { session_key: input.sessionKey } : {}),\n updated_at: new Date(Number.isFinite(previous) && requested <= previous ? previous + 1 : requested).toISOString(),\n diagnostic: \"prepared input superseded before dispatch\",\n };\n atomicWriteJson(journalPath(input.root, input.projectSlug, active.operation_id), updated, paths.root);\n return updated;\n }\n const now = (input.now ?? new Date()).toISOString();\n const journal: RemoteMutationJournalV1 = {\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n operation_id: input.operationId ?? randomUUID(),\n project_slug: input.projectSlug,\n kind: input.kind,\n logical_marker: input.logicalMarker,\n input_digest: input.inputDigest,\n ...(input.dispatchDigest ? { dispatch_digest: input.dispatchDigest } : {}),\n ...(input.bindingId ? { binding_id: input.bindingId } : {}),\n ...(input.sessionKey ? { session_key: input.sessionKey } : {}),\n state: \"prepared\",\n prepared_at: now,\n updated_at: now,\n candidate_ids: [],\n diagnostic: null,\n result_category: \"prepared\",\n next_action: remoteMutationNextAction(\"prepared\", 0),\n };\n if (!createNotebookStateJsonExclusive(journalPath(input.root, input.projectSlug, journal.operation_id), journal, paths.root)) {\n throw new NotebookError(\"CONFLICT\", \"Concurrent remote mutation journal reservation collided\");\n }\n return journal;\n });\n}\n\nexport function transitionRemoteMutation(input: {\n root: string;\n journal: RemoteMutationJournalV1;\n state: RemoteMutationJournalState;\n candidateIds?: string[];\n diagnostic?: string | null;\n now?: Date;\n}): RemoteMutationJournalV1 {\n return withNotebookStateLock(input.root, input.journal.project_slug, 1_000, (paths) => {\n const path = journalPath(input.root, input.journal.project_slug, input.journal.operation_id);\n const read = readNotebookStateJson(path, paths.root, 65_536);\n const current = read.value === undefined ? null : parseRemoteMutationJournal(read.value);\n if (!current) throw new NotebookError(\"CONFLICT\", \"Remote mutation journal has an integrity finding\");\n if (current.state !== input.journal.state || current.updated_at !== input.journal.updated_at\n || canonicalJson(current.candidate_ids) !== canonicalJson(input.journal.candidate_ids)) {\n throw new NotebookError(\"CONFLICT\", \"Remote mutation journal changed; stale transition rejected\");\n }\n const allowed: Record<RemoteMutationJournalState, ReadonlySet<RemoteMutationJournalState>> = {\n prepared: new Set([\"possibly-dispatched\", \"reconciled\"]),\n \"possibly-dispatched\": new Set([\"reconciled\"]),\n reconciled: new Set([\"committed\"]),\n committed: new Set(),\n };\n if (!allowed[current.state].has(input.state)) throw new NotebookError(\"CONFLICT\", \"Remote mutation journal transition is not allowed by the v1 state machine\");\n const candidates = [...new Set(input.candidateIds ?? current.candidate_ids)];\n if (candidates.length > 20 || candidates.some((item) => typeof item !== \"string\" || !item || Buffer.byteLength(item, \"utf8\") > 512 || /[\\u0000-\\u001f\\u007f]/u.test(item))) {\n throw new NotebookError(\"INVALID_INPUT\", \"Remote mutation candidates exceed the bounded v1 schema\");\n }\n if (input.state === \"possibly-dispatched\" && candidates.length !== 0) throw new NotebookError(\"CONFLICT\", \"Possibly-dispatched journal cannot claim candidates before reconciliation\");\n if (input.state === \"committed\" && candidates.length !== 1) throw new NotebookError(\"CONFLICT\", \"Committed journal requires exactly one reconciled candidate\");\n if (input.diagnostic !== undefined && input.diagnostic !== null && (Buffer.byteLength(input.diagnostic, \"utf8\") > 512 || /[\\u0000-\\u001f\\u007f]/u.test(input.diagnostic))) {\n throw new NotebookError(\"INVALID_INPUT\", \"Remote mutation diagnostic exceeds the bounded v1 schema\");\n }\n const requested = (input.now ?? new Date()).getTime();\n const previous = Date.parse(current.updated_at);\n const { definitive_http_status: _definitiveHttpStatus, ...currentWithoutRejection } = current;\n const next: RemoteMutationJournalV1 = {\n ...currentWithoutRejection,\n state: input.state,\n updated_at: new Date(Number.isFinite(previous) && requested <= previous ? previous + 1 : requested).toISOString(),\n candidate_ids: candidates,\n diagnostic: input.state === \"committed\" ? null : input.diagnostic === undefined ? current.diagnostic : input.diagnostic,\n result_category: remoteMutationResultCategory(input.state, candidates.length),\n next_action: remoteMutationNextAction(input.state, candidates.length),\n };\n atomicWriteJson(path, next, paths.root);\n return next;\n });\n}\n\nexport function markRemoteMutationDefinitivelyRejected(input: {\n root: string;\n journal: RemoteMutationJournalV1;\n status: DefinitiveRemoteMutationHttpStatus;\n now?: Date;\n}): RemoteMutationJournalV1 {\n return withNotebookStateLock(input.root, input.journal.project_slug, 1_000, (paths) => {\n const path = journalPath(input.root, input.journal.project_slug, input.journal.operation_id);\n const read = readNotebookStateJson(path, paths.root, 65_536);\n const current = read.value === undefined ? null : parseRemoteMutationJournal(read.value);\n if (!current) throw new NotebookError(\"CONFLICT\", \"Remote mutation journal has an integrity finding\");\n if (current.state !== input.journal.state || current.updated_at !== input.journal.updated_at\n || current.input_digest !== input.journal.input_digest || current.dispatch_digest !== input.journal.dispatch_digest\n || current.diagnostic !== input.journal.diagnostic || current.definitive_http_status !== input.journal.definitive_http_status\n || canonicalJson(current.candidate_ids) !== canonicalJson(input.journal.candidate_ids)) {\n throw new NotebookError(\"CONFLICT\", \"Remote mutation journal changed; stale definitive rejection rejected\");\n }\n if (current.state !== \"possibly-dispatched\" || current.candidate_ids.length !== 0) {\n throw new NotebookError(\"CONFLICT\", \"Only an unresolved dispatched mutation can record a definitive HTTP rejection\");\n }\n const requested = (input.now ?? new Date()).getTime();\n const previous = Date.parse(current.updated_at);\n const next: RemoteMutationJournalV1 = {\n ...current,\n updated_at: new Date(Number.isFinite(previous) && requested <= previous ? previous + 1 : requested).toISOString(),\n diagnostic: `Open Notebook definitively rejected HTTP ${input.status}`,\n definitive_http_status: input.status,\n result_category: remoteMutationResultCategory(current.state, 0, input.status),\n next_action: remoteMutationNextAction(current.state, 0, input.status),\n };\n atomicWriteJson(path, next, paths.root);\n return next;\n });\n}\n\nexport function rearmRemoteMutationAfterDefinitiveRejection(input: {\n root: string;\n journal: RemoteMutationJournalV1;\n inputDigest: string;\n dispatchDigest: string;\n observedCandidateIds: string[];\n legacyV114InputDigest?: string;\n now?: Date;\n}): RemoteMutationJournalV1 {\n if (!/^[a-f0-9]{64}$/u.test(input.inputDigest)) throw new NotebookError(\"INVALID_INPUT\", \"Invalid corrected remote mutation input digest\");\n if (!/^[a-f0-9]{64}$/u.test(input.dispatchDigest)) throw new NotebookError(\"INVALID_INPUT\", \"Invalid corrected remote mutation dispatch digest\");\n if (input.legacyV114InputDigest !== undefined && !/^[a-f0-9]{64}$/u.test(input.legacyV114InputDigest)) throw new NotebookError(\"INVALID_INPUT\", \"Invalid legacy v1.14 remote mutation input digest\");\n if (input.observedCandidateIds.length !== 0) throw new NotebookError(\"CONFLICT\", \"A remote mutation with candidates cannot be rearmed\");\n return withNotebookStateLock(input.root, input.journal.project_slug, 1_000, (paths) => {\n const path = journalPath(input.root, input.journal.project_slug, input.journal.operation_id);\n const read = readNotebookStateJson(path, paths.root, 65_536);\n const current = read.value === undefined ? null : parseRemoteMutationJournal(read.value);\n if (!current) throw new NotebookError(\"CONFLICT\", \"Remote mutation journal has an integrity finding\");\n if (current.state !== input.journal.state || current.updated_at !== input.journal.updated_at\n || current.input_digest !== input.journal.input_digest || current.dispatch_digest !== input.journal.dispatch_digest\n || current.diagnostic !== input.journal.diagnostic || current.definitive_http_status !== input.journal.definitive_http_status\n || canonicalJson(current.candidate_ids) !== canonicalJson(input.journal.candidate_ids)) {\n throw new NotebookError(\"CONFLICT\", \"Remote mutation journal changed; stale corrected-input rearm rejected\");\n }\n if (current.kind !== \"note.create\" || current.state !== \"possibly-dispatched\" || current.candidate_ids.length !== 0) {\n throw new NotebookError(\"CONFLICT\", \"Only a zero-candidate rejected note mutation can be rearmed\");\n }\n if (current.dispatch_digest === input.dispatchDigest) {\n throw new NotebookError(\"CONFLICT\", \"Definitively rejected note transport input must change before one retry is allowed\");\n }\n const explicitRejection = current.definitive_http_status === 400 || current.definitive_http_status === 422;\n const legacyV114Rejection = current.definitive_http_status === undefined\n && current.diagnostic === \"possibly-dispatched\"\n && current.dispatch_digest === undefined\n && input.legacyV114InputDigest !== undefined\n && current.input_digest === input.legacyV114InputDigest;\n if (!explicitRejection && !legacyV114Rejection) {\n throw new NotebookError(\"CONFLICT\", \"Remote note dispatch is ambiguous; corrected input cannot be posted without a definitive rejection\");\n }\n const requested = (input.now ?? new Date()).getTime();\n const previous = Date.parse(current.updated_at);\n const { definitive_http_status: _definitiveHttpStatus, ...currentWithoutRejection } = current;\n const next: RemoteMutationJournalV1 = {\n ...currentWithoutRejection,\n state: \"prepared\",\n input_digest: input.inputDigest,\n dispatch_digest: input.dispatchDigest,\n updated_at: new Date(Number.isFinite(previous) && requested <= previous ? previous + 1 : requested).toISOString(),\n candidate_ids: [],\n diagnostic: legacyV114Rejection\n ? \"corrected v1.14 note_type input rearmed after definitive legacy rejection\"\n : \"corrected input rearmed after definitive HTTP rejection\",\n result_category: remoteMutationResultCategory(\"prepared\", 0),\n next_action: remoteMutationNextAction(\"prepared\", 0),\n };\n atomicWriteJson(path, next, paths.root);\n return next;\n });\n}\n\nexport function remoteMutationExists(root: string, projectSlug: string, operationId: string): boolean {\n return listRemoteMutationJournals(root, projectSlug).some((journal) => journal.operation_id === operationId);\n}\n\nexport function commitReconciledRemoteMutation(root: string, journal: RemoteMutationJournalV1, now?: Date): RemoteMutationJournalV1 {\n if (journal.state === \"committed\") return journal;\n if (journal.state !== \"reconciled\" || journal.candidate_ids.length !== 1) {\n throw new NotebookError(\"CONFLICT\", \"Remote mutation cannot commit before exactly one candidate and durable ownership\");\n }\n return transitionRemoteMutation({ root, journal, state: \"committed\", now, diagnostic: null });\n}\n", "import { NotebookError, type OpenNotebookNotebookV1, type OpenNotebookNoteV1 } from \"./types\";\nimport { parseNoteEnvelope } from \"./notes\";\nimport { normalizeOpenNotebookNoteType, OpenNotebookClient } from \"./open-notebook-client\";\nimport {\n markRemoteMutationDefinitivelyRejected,\n mutationInputDigest,\n prepareRemoteMutation,\n rearmRemoteMutationAfterDefinitiveRejection,\n transitionRemoteMutation,\n type RemoteMutationJournalV1,\n} from \"./remote-mutation-journal\";\n\nfunction sameCandidateSet(left: string[], right: string[]): boolean {\n const normalize = (items: string[]) => [...items].sort((a, b) => a.localeCompare(b));\n return JSON.stringify(normalize(left)) === JSON.stringify(normalize(right));\n}\n\nfunction recordReconciliation(input: {\n stateRoot: string;\n journal: RemoteMutationJournalV1;\n candidateIds: string[];\n duplicateDiagnostic: string;\n}): RemoteMutationJournalV1 {\n if (input.journal.state === \"reconciled\") {\n if (!sameCandidateSet(input.journal.candidate_ids, input.candidateIds)) {\n throw new NotebookError(\"CONFLICT\", \"Reconciled remote mutation candidate set changed; durable ownership must be repaired explicitly\");\n }\n return input.journal;\n }\n if (input.candidateIds.length === 0) return input.journal;\n return transitionRemoteMutation({\n root: input.stateRoot,\n journal: input.journal,\n state: \"reconciled\",\n candidateIds: input.candidateIds,\n diagnostic: input.candidateIds.length > 1 ? input.duplicateDiagnostic : null,\n });\n}\n\nexport function projectNotebookMarker(projectSlug: string): string {\n return `pjangler.project.v1:${projectSlug}`;\n}\n\nfunction ambiguous(kind: string, ids: string[]): never {\n throw new NotebookError(\"CONFLICT\", `More than one ${kind} matches the stable PJangler marker`, false, { candidate_count: ids.length });\n}\n\nexport async function reconcileProjectNotebook(input: {\n stateRoot: string;\n projectSlug: string;\n name: string;\n description?: string;\n client: OpenNotebookClient;\n beforeRemote?: () => void;\n}): Promise<{ notebook: OpenNotebookNotebookV1; created: boolean; adopted: boolean; journal: RemoteMutationJournalV1 }> {\n const marker = projectNotebookMarker(input.projectSlug);\n const description = input.description?.trim() ? `${marker}\\n${input.description.trim()}` : marker;\n const digest = mutationInputDigest({ kind: \"notebook.create\", marker, name: input.name, description });\n let journal = prepareRemoteMutation({\n root: input.stateRoot,\n projectSlug: input.projectSlug,\n kind: \"notebook.create\",\n logicalMarker: marker,\n inputDigest: digest,\n });\n\n const reconcile = async (): Promise<OpenNotebookNotebookV1[]> => {\n input.beforeRemote?.();\n const candidates = (await input.client.listNotebooks()).filter((notebook) => notebook.description?.split(/\\r?\\n/u)[0] === marker);\n journal = recordReconciliation({\n stateRoot: input.stateRoot,\n journal,\n candidateIds: candidates.map((item) => item.id),\n duplicateDiagnostic: \"duplicate stable marker\",\n });\n return candidates;\n };\n\n let candidates = await reconcile();\n if (candidates.length > 1) ambiguous(\"notebook\", candidates.map((item) => item.id));\n if (candidates.length === 1) {\n let candidate = candidates[0]!;\n if (candidate.name !== input.name || candidate.description !== description || candidate.archived === true) {\n input.beforeRemote?.();\n candidate = await input.client.updateNotebook(candidate.id, { name: input.name, description, archived: false });\n if (candidate.name !== input.name || candidate.description !== description || candidate.archived === true) {\n throw new NotebookError(\"DRIFT_DETECTED\", \"Stable-marker notebook metadata could not be repaired exactly\");\n }\n }\n return { notebook: candidate, created: false, adopted: true, journal };\n }\n if (journal.state !== \"prepared\") {\n throw new NotebookError(\"CONFLICT\", \"Notebook create may have been dispatched; reconcile before another POST\", false, { operation_id: journal.operation_id });\n }\n // The latch below is persisted immediately before fetch receives the request.\n input.beforeRemote?.();\n await input.client.createNotebook({ name: input.name, description }, () => {\n journal = transitionRemoteMutation({ root: input.stateRoot, journal, state: \"possibly-dispatched\", diagnostic: \"possibly-dispatched\" });\n });\n candidates = await reconcile();\n if (candidates.length > 1) ambiguous(\"notebook\", candidates.map((item) => item.id));\n if (candidates.length !== 1) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Created notebook could not be reconciled by its stable marker\");\n const candidate = candidates[0]!;\n if (candidate.name !== input.name || candidate.description !== description || candidate.archived === true) {\n throw new NotebookError(\"DRIFT_DETECTED\", \"Created notebook did not satisfy the exact marker/name/archive contract\");\n }\n return { notebook: candidate, created: true, adopted: false, journal };\n}\n\nexport async function reconcileManagedNote(input: {\n stateRoot: string;\n projectSlug: string;\n notebookId: string;\n logicalId: string;\n title: string;\n content: string;\n noteType?: string;\n client: OpenNotebookClient;\n sessionKey?: string;\n inputDigest?: string;\n operationId?: string;\n beforeRemote?: () => void;\n}): Promise<{ note: OpenNotebookNoteV1; created: boolean; adopted: boolean; journal: RemoteMutationJournalV1 }> {\n const desiredEnvelope = parseNoteEnvelope(input.content)?.envelope;\n if (!desiredEnvelope || desiredEnvelope.project_slug !== input.projectSlug || desiredEnvelope.logical_id !== input.logicalId) {\n throw new NotebookError(\"INVALID_INPUT\", \"Managed note create requires an exact owned PJangler envelope\");\n }\n const noteType = normalizeOpenNotebookNoteType(input.noteType);\n const digest = input.inputDigest ?? mutationInputDigest({ kind: \"note.create\", notebook_id: input.notebookId, logical_id: input.logicalId, title: input.title, content: input.content });\n const dispatchDigest = mutationInputDigest({ kind: \"note.create\", notebook_id: input.notebookId, logical_id: input.logicalId, title: input.title, content: input.content, note_type: noteType });\n let journal = prepareRemoteMutation({\n root: input.stateRoot,\n projectSlug: input.projectSlug,\n kind: \"note.create\",\n logicalMarker: input.logicalId,\n inputDigest: digest,\n dispatchDigest,\n sessionKey: input.sessionKey,\n bindingId: input.notebookId,\n operationId: input.operationId,\n });\n const reconcile = async (): Promise<OpenNotebookNoteV1[]> => {\n input.beforeRemote?.();\n const notes = await input.client.listNotes(input.notebookId);\n const candidates = notes.filter((note) => parseNoteEnvelope(note.content)?.envelope.logical_id === input.logicalId);\n journal = recordReconciliation({\n stateRoot: input.stateRoot,\n journal,\n candidateIds: candidates.map((item) => item.id),\n duplicateDiagnostic: \"duplicate logical id\",\n });\n return candidates;\n };\n let candidates = await reconcile();\n if (candidates.length > 1) ambiguous(\"note\", candidates.map((item) => item.id));\n if (candidates.length === 1) {\n let candidate = candidates[0]!;\n const owned = parseNoteEnvelope(candidate.content)?.envelope;\n if (!owned || owned.project_slug !== input.projectSlug || owned.kind !== desiredEnvelope.kind || owned.logical_id !== input.logicalId) {\n throw new NotebookError(\"CONFLICT\", \"Managed logical ID is occupied by a foreign or forged note envelope\");\n }\n if (candidate.title !== input.title || candidate.content !== input.content) {\n input.beforeRemote?.();\n candidate = await input.client.updateOwnedNote(input.notebookId, candidate.id, { title: input.title, content: input.content });\n if (candidate.title !== input.title || candidate.content !== input.content) {\n throw new NotebookError(\"DRIFT_DETECTED\", \"Managed note metadata/content could not be repaired exactly\");\n }\n }\n return { note: candidate, created: false, adopted: true, journal };\n }\n if (journal.state !== \"prepared\") {\n journal = rearmRemoteMutationAfterDefinitiveRejection({\n root: input.stateRoot,\n journal,\n inputDigest: digest,\n dispatchDigest,\n observedCandidateIds: candidates.map((item) => item.id),\n ...(input.noteType === undefined && input.inputDigest === undefined ? { legacyV114InputDigest: digest } : {}),\n });\n }\n input.beforeRemote?.();\n await input.client.createNote(input.notebookId, { title: input.title, content: input.content, note_type: noteType }, () => {\n journal = transitionRemoteMutation({ root: input.stateRoot, journal, state: \"possibly-dispatched\", diagnostic: \"possibly-dispatched\" });\n }, (status) => {\n journal = markRemoteMutationDefinitivelyRejected({ root: input.stateRoot, journal, status });\n });\n candidates = await reconcile();\n if (candidates.length > 1) ambiguous(\"note\", candidates.map((item) => item.id));\n if (candidates.length !== 1) throw new NotebookError(\"REMOTE_PROTOCOL_ERROR\", \"Created note could not be reconciled by its logical ID\");\n const candidate = candidates[0]!;\n const owned = parseNoteEnvelope(candidate.content)?.envelope;\n if (!owned || owned.project_slug !== input.projectSlug || owned.kind !== desiredEnvelope.kind || owned.logical_id !== input.logicalId\n || candidate.title !== input.title || candidate.content !== input.content) {\n throw new NotebookError(\"DRIFT_DETECTED\", \"Created managed note failed exact ownership/content reconciliation\");\n }\n return { note: candidate, created: true, adopted: false, journal };\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { isAbsolute } from \"node:path\";\nimport { NotebookError, type EffectiveNotebookConfigV1 } from \"./types\";\n\nexport interface CaptureSummaryV1 {\n schema_version: 1;\n mode: \"configured\" | \"deterministic-fallback\";\n summary: string;\n}\n\nexport interface CaptureSummaryEvidenceV1 {\n documents: Array<{ path: string; content: string; content_sha256: string; start_content_sha256?: string; source_revision: string }>;\n changedPaths: string[];\n exclusions: Record<string, number>;\n endRevision?: string | null;\n endStatusDigest?: string | null;\n baselineRef?: string | null;\n}\n\ninterface EvidenceItemV1 {\n evidence_id: string;\n kind: \"eligible-document\" | \"changed-path\" | \"verification\" | \"unresolved\";\n path?: string;\n content?: string;\n content_sha256?: string;\n value?: string;\n}\n\nfunction evidenceItems(evidence: CaptureSummaryEvidenceV1): EvidenceItemV1[] {\n const items: EvidenceItemV1[] = [];\n const eligible = new Set(evidence.documents.map((item) => item.path));\n for (const [index, document] of evidence.documents.slice(0, 100).entries()) items.push({\n evidence_id: `doc-${String(index + 1).padStart(3, \"0\")}`,\n kind: \"eligible-document\",\n path: document.path,\n content: document.content,\n content_sha256: document.content_sha256,\n value: `start=${document.start_content_sha256 ?? \"unknown\"}; end=${document.content_sha256}; revision=${document.source_revision}`,\n });\n for (const [index, path] of evidence.changedPaths.filter((item) => !eligible.has(item)).slice(0, 100).entries()) {\n items.push({ evidence_id: `path-${String(index + 1).padStart(3, \"0\")}`, kind: \"changed-path\", path });\n }\n if (evidence.baselineRef) items.push({ evidence_id: \"verify-baseline\", kind: \"verification\", value: `committed baseline ${evidence.baselineRef}` });\n if (evidence.endRevision) items.push({ evidence_id: \"verify-end-revision\", kind: \"verification\", value: `committed end revision ${evidence.endRevision}` });\n if (evidence.endStatusDigest) items.push({ evidence_id: \"verify-end-status\", kind: \"verification\", value: `bounded Git status digest ${evidence.endStatusDigest}` });\n for (const [reason, count] of Object.entries(evidence.exclusions).sort(([a], [b]) => a.localeCompare(b, \"en\")).slice(0, 100)) {\n items.push({ evidence_id: `unresolved-${items.filter((item) => item.kind === \"unresolved\").length + 1}`, kind: \"unresolved\", value: `${reason}: ${count}` });\n }\n return items;\n}\n\nfunction safeMarkdownValue(value: string): string {\n return JSON.stringify(Array.from(value).slice(0, 512).join(\"\"));\n}\n\nfunction truncateUtf8(value: string, maxBytes: number): string {\n const suffix = \"\\n\\n[Capture summary truncated by project-notebook.v1 policy]\";\n if (Buffer.byteLength(value, \"utf8\") <= maxBytes) return value;\n const suffixBytes = Buffer.byteLength(suffix, \"utf8\");\n let used = 0;\n const result: string[] = [];\n for (const point of value) {\n const bytes = Buffer.byteLength(point, \"utf8\");\n if (used + bytes > Math.max(0, maxBytes - suffixBytes)) break;\n result.push(point);\n used += bytes;\n }\n return `${result.join(\"\")}${suffix}`;\n}\n\nfunction fallback(evidence: CaptureSummaryEvidenceV1, maxBytes: number): string {\n const documents = evidence.documents.length ? evidence.documents.slice(0, 100).map((item) => `- ${safeMarkdownValue(item.path)} (${item.content_sha256})`).join(\"\\n\") : \"- None proved.\";\n const eligible = new Set(evidence.documents.map((item) => item.path));\n const other = evidence.changedPaths.filter((item) => !eligible.has(item));\n const paths = other.length ? other.slice(0, 100).map((item) => `- ${safeMarkdownValue(item)}`).join(\"\\n\") : \"- None recorded.\";\n const verification = [\n evidence.baselineRef ? `- Baseline commit: ${evidence.baselineRef}` : \"- Baseline commit: unavailable\",\n evidence.endRevision ? `- End commit: ${evidence.endRevision}` : \"- End commit: unavailable\",\n evidence.endStatusDigest ? `- End status digest: ${evidence.endStatusDigest}` : \"- End status digest: unavailable\",\n ].join(\"\\n\");\n const unresolved = Object.keys(evidence.exclusions).length\n ? Object.entries(evidence.exclusions).sort(([a], [b]) => a.localeCompare(b, \"en\")).map(([reason, count]) => `- ${reason}: ${count}`).join(\"\\n\")\n : \"- None recorded.\";\n return truncateUtf8([\n \"## Changed eligible documents\", documents,\n \"\", \"## Other changed path names\", paths,\n \"\", \"## Verification evidence\", verification,\n \"\", \"## Unresolved or uncommitted work\", unresolved,\n \"\", \"## Insufficient evidence\", \"No deployment, runtime-health, or external-success conclusion is supported by this repository-only capture.\",\n ].join(\"\\n\"), maxBytes);\n}\n\nfunction words(value: string): Set<string> {\n return new Set((value.normalize(\"NFKC\").toLocaleLowerCase(\"und\").match(/[\\p{L}\\p{N}]{4,}/gu) ?? []));\n}\n\nfunction validateClaims(value: unknown, items: EvidenceItemV1[], noteMaxBytes: number): string | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const record = value as Record<string, unknown>;\n if (record.schema_version !== 1 || !Array.isArray(record.claims) || record.claims.length < 1 || record.claims.length > 50\n || Object.keys(record).some((key) => key !== \"schema_version\" && key !== \"claims\")) return null;\n const byId = new Map(items.map((item) => [item.evidence_id, item]));\n const rendered: string[] = [\"## Session outcome\"];\n for (const claimValue of record.claims) {\n if (!claimValue || typeof claimValue !== \"object\" || Array.isArray(claimValue)) return null;\n const claim = claimValue as Record<string, unknown>;\n if (Object.keys(claim).some((key) => key !== \"text\" && key !== \"evidence_ids\") || typeof claim.text !== \"string\"\n || !claim.text.trim() || Buffer.byteLength(claim.text, \"utf8\") > 1_024 || !Array.isArray(claim.evidence_ids)\n || claim.evidence_ids.length < 1 || claim.evidence_ids.length > 10 || claim.evidence_ids.some((id) => typeof id !== \"string\" || !byId.has(id))) return null;\n if (/(?:deploy(?:ed|ment)?|production|runtime healthy|shipped|released)/iu.test(claim.text)) return null;\n const claimWords = words(claim.text);\n const cited = claim.evidence_ids.map((id) => byId.get(String(id))!);\n const citedWords = words(cited.map((item) => `${item.path ?? \"\"} ${item.value ?? \"\"} ${item.content ?? \"\"}`).join(\" \"));\n if (![...claimWords].some((word) => citedWords.has(word))) return null;\n rendered.push(`- ${claim.text.trim()} [${claim.evidence_ids.join(\", \")}]`);\n }\n const result = rendered.join(\"\\n\");\n return Buffer.byteLength(result, \"utf8\") <= noteMaxBytes ? result : null;\n}\n\nexport function summarizeCapture(config: EffectiveNotebookConfigV1, evidence: CaptureSummaryEvidenceV1): CaptureSummaryV1 {\n const fallbackSummary = fallback(evidence, config.limits.note_max_bytes);\n if (!config.summarizer) return { schema_version: 1, mode: \"deterministic-fallback\", summary: fallbackSummary };\n assertSummarizerConfig(config);\n const items = evidenceItems(evidence);\n const payload = JSON.stringify({ schema_version: 1, evidence: items });\n if (Buffer.byteLength(payload, \"utf8\") > config.limits.request_max_bytes) return { schema_version: 1, mode: \"deterministic-fallback\", summary: fallbackSummary };\n const result = spawnSync(config.summarizer.executable, config.summarizer.args, {\n cwd: config.repo_path,\n input: Buffer.from(payload, \"utf8\"),\n timeout: config.limits.overall_timeout_ms,\n maxBuffer: config.limits.response_max_bytes,\n shell: false,\n env: { PATH: \"/usr/bin:/bin\", LANG: \"C.UTF-8\", LC_ALL: \"C.UTF-8\" },\n });\n if (result.status !== 0 || result.error || !result.stdout || result.stdout.length > config.limits.response_max_bytes) return { schema_version: 1, mode: \"deterministic-fallback\", summary: fallbackSummary };\n try {\n const decoded = new TextDecoder(\"utf-8\", { fatal: true }).decode(result.stdout);\n const summary = validateClaims(JSON.parse(decoded) as unknown, items, config.limits.note_max_bytes);\n return summary ? { schema_version: 1, mode: \"configured\", summary } : { schema_version: 1, mode: \"deterministic-fallback\", summary: fallbackSummary };\n } catch {\n return { schema_version: 1, mode: \"deterministic-fallback\", summary: fallbackSummary };\n }\n}\n\nexport function assertSummarizerConfig(config: EffectiveNotebookConfigV1): void {\n if (config.summarizer && (!isAbsolute(config.summarizer.executable) || config.summarizer.executable.includes(\"\\0\")\n || config.summarizer.args.length > 32 || config.summarizer.args.some((arg) => arg.includes(\"\\0\") || Buffer.byteLength(arg, \"utf8\") > 1_024))) {\n throw new NotebookError(\"NOT_CONFIGURED\", \"Configured Notebook summarizer command is invalid\");\n }\n}\n", "import { encodeNoteEnvelope, sha256Hex } from \"./notes\";\nimport { selectEligibleDocuments } from \"./git-evidence\";\nimport type { NotebookModule } from \"./module\";\nimport { reconcileManagedNote } from \"./reconcile\";\nimport { commitReconciledRemoteMutation, listRemoteMutationJournals, type RemoteMutationJournalV1 } from \"./remote-mutation-journal\";\nimport {\n claimCaptureReceipt,\n captureReceiptVersion,\n readCaptureReceipt,\n readSessionBaseline,\n renewCaptureReceiptLease,\n transitionCaptureReceipt,\n} from \"./state\";\nimport { summarizeCapture } from \"./summarizer\";\nimport {\n NOTEBOOK_POLICY_VERSION,\n NOTEBOOK_SCHEMA_VERSION,\n NotebookError,\n type CaptureReceiptV1,\n type OpenNotebookNoteV1,\n type PjanglerNoteEnvelopeV1,\n} from \"./types\";\nimport { normalizeNotebookError } from \"./output\";\n\nexport interface CaptureWorkerResultV1 {\n receipt: CaptureReceiptV1;\n processed: boolean;\n}\n\nexport function safeDocumentTitle(sourcePath: string, maxBytes = 4_096): string {\n const escaped = JSON.stringify(sourcePath.normalize(\"NFC\")).slice(1, -1);\n let used = 0;\n const points: string[] = [];\n for (const point of escaped) {\n const bytes = Buffer.byteLength(point, \"utf8\");\n if (used + bytes > maxBytes) break;\n points.push(point);\n used += bytes;\n }\n const title = points.join(\"\");\n if (!title || /[\\u0000-\\u001f\\u007f]/u.test(title)) throw new NotebookError(\"INVALID_INPUT\", \"Git evidence path could not be rendered as a safe note title\");\n return title;\n}\n\nexport function finalizeSucceededReceiptJournals(module: NotebookModule, receipt: CaptureReceiptV1): string[] {\n if (receipt.state !== \"succeeded\") return [];\n const local = module.contextBySlug(receipt.project_slug, false);\n const bindingId = local.config.binding.state === \"linked\" ? local.config.binding.notebook_id : undefined;\n if (!bindingId) return [];\n const ownership = new Map(receipt.note_logical_ids.map((logicalId, index) => [logicalId, receipt.remote_note_ids[index]]));\n const committed: string[] = [];\n for (const journal of listRemoteMutationJournals(module.stateRoot, receipt.project_slug)) {\n if (journal.state !== \"reconciled\" || journal.kind !== \"note.create\" || journal.session_key !== receipt.session_key\n || journal.binding_id !== bindingId || journal.candidate_ids.length !== 1\n || ownership.get(journal.logical_marker) !== journal.candidate_ids[0]) continue;\n commitReconciledRemoteMutation(module.stateRoot, journal);\n committed.push(journal.operation_id);\n }\n return committed.sort();\n}\n\nfunction managedContent(envelope: PjanglerNoteEnvelopeV1, body: string, maxBytes: number, truncate: boolean): { content: string; body: string } {\n const marker = `${encodeNoteEnvelope(envelope)}\\n`;\n const available = maxBytes - Buffer.byteLength(marker, \"utf8\");\n if (available < 0) throw new NotebookError(\"INVALID_INPUT\", \"Managed note ownership envelope exceeds the configured note ceiling\");\n if (Buffer.byteLength(body, \"utf8\") <= available) return { content: `${marker}${body}`, body };\n if (!truncate) throw new NotebookError(\"INVALID_INPUT\", \"Eligible document plus ownership envelope exceeds the configured note ceiling\");\n const suffix = \"\\n\\n[Session capture truncated by project-notebook.v1 policy]\";\n const budget = Math.max(0, available - Buffer.byteLength(suffix, \"utf8\"));\n let used = 0;\n const points: string[] = [];\n for (const point of body) {\n const bytes = Buffer.byteLength(point, \"utf8\");\n if (used + bytes > budget) break;\n points.push(point);\n used += bytes;\n }\n const fitted = `${points.join(\"\")}${suffix}`;\n return { content: `${marker}${fitted}`, body: fitted };\n}\n\nfunction bindingId(receipt: CaptureReceiptV1, module: NotebookModule): { notebookId: string; client: ReturnType<NotebookModule[\"context\"]>[\"client\"]; config: ReturnType<NotebookModule[\"context\"]>[\"config\"] } {\n const ctx = module.contextBySlug(receipt.project_slug, true);\n if (!ctx.config.binding.notebook_id || ctx.config.binding.state !== \"linked\") throw new NotebookError(\"NOT_CONFIGURED\", \"Capture project notebook is not linked\");\n return { notebookId: ctx.config.binding.notebook_id, client: ctx.client!, config: ctx.config };\n}\n\nasync function upsertManaged(input: {\n module: NotebookModule;\n receipt: CaptureReceiptV1;\n notebookId: string;\n client: NonNullable<ReturnType<NotebookModule[\"context\"]>[\"client\"]>;\n logicalId: string;\n title: string;\n content: string;\n beforeRemote?: () => void;\n}): Promise<{ note: OpenNotebookNoteV1; journal?: RemoteMutationJournalV1 }> {\n const created = await reconcileManagedNote({\n stateRoot: input.module.stateRoot,\n projectSlug: input.receipt.project_slug,\n notebookId: input.notebookId,\n logicalId: input.logicalId,\n title: input.title,\n content: input.content,\n client: input.client,\n sessionKey: input.receipt.session_key,\n beforeRemote: input.beforeRemote,\n });\n return { note: created.note, journal: created.journal };\n}\n\nasync function processClaimed(module: NotebookModule, receipt: CaptureReceiptV1, leaseUpdated: (receipt: CaptureReceiptV1) => void): Promise<CaptureReceiptV1> {\n let active = receipt;\n const linked = bindingId(active, module);\n let baseline = readSessionBaseline(module.stateRoot, active.project_slug, active.session_key, linked.config.limits);\n if ((!baseline || !baseline.complete) && active.manual_baseline_ref) {\n // Operator recovery supplies only a committed boundary. It deliberately\n // carries no invented SessionStart dirty-path provenance; the evidence\n // selector excludes all current uncommitted paths under manual mode.\n baseline = {\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n session_key: active.session_key,\n project_slug: active.project_slug,\n client: \"operator-manual-baseline\",\n created_at: active.created_at,\n repo_path_digest: active.repo_path_digest,\n git_head: active.manual_baseline_ref,\n git_status_digest: null,\n policy_version: NOTEBOOK_POLICY_VERSION,\n tracked_path_digests: {},\n pre_dirty_paths: [],\n complete: true,\n incomplete_reasons: [\"manual-baseline-pre-dirty-unknown\"],\n };\n }\n if (!baseline || !baseline.complete) {\n return transitionCaptureReceipt({\n root: module.stateRoot,\n projectSlug: receipt.project_slug,\n receiptId: active.receipt_id,\n limits: linked.config.limits,\n expected: captureReceiptVersion(active),\n state: \"blocked-missing-baseline\",\n errorCategory: \"CONFLICT\",\n retryable: false,\n diagnostic: \"A complete SessionStart baseline is required; retry with an explicit committed --baseline GIT_REF\",\n });\n }\n const renew = (): void => {\n active = renewCaptureReceiptLease({\n root: module.stateRoot,\n projectSlug: active.project_slug,\n receiptId: active.receipt_id,\n limits: linked.config.limits,\n expected: captureReceiptVersion(active),\n });\n leaseUpdated(active);\n };\n const evidence = selectEligibleDocuments(linked.config, baseline, active.manual_baseline_ref);\n const logicalIds: string[] = [];\n const remoteIds: string[] = [];\n const journals: RemoteMutationJournalV1[] = [];\n\n for (const document of evidence.documents) {\n renew();\n const logicalId = sha256Hex(`pjangler-document-v1\\0${active.project_slug}\\0${document.path.normalize(\"NFC\")}`);\n const envelope: PjanglerNoteEnvelopeV1 = {\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n project_slug: active.project_slug,\n kind: \"document\",\n logical_id: logicalId,\n source_path: document.path,\n source_revision: document.source_revision,\n content_sha256: document.content_sha256,\n session_key: active.session_key,\n captured_at: active.created_at,\n policy_version: NOTEBOOK_POLICY_VERSION,\n };\n let documentContent: string;\n try { documentContent = managedContent(envelope, document.content, linked.config.limits.note_max_bytes, false).content; }\n catch (error) {\n if (!(error instanceof NotebookError) || error.code !== \"INVALID_INPUT\") throw error;\n evidence.exclusions[\"note-envelope-oversize\"] = (evidence.exclusions[\"note-envelope-oversize\"] ?? 0) + 1;\n continue;\n }\n const upserted = await upsertManaged({\n module,\n receipt: active,\n notebookId: linked.notebookId,\n client: linked.client!,\n logicalId,\n title: safeDocumentTitle(document.path),\n content: documentContent,\n beforeRemote: renew,\n });\n const note = upserted.note;\n if (upserted.journal) journals.push(upserted.journal);\n logicalIds.push(logicalId);\n remoteIds.push(note.id);\n }\n\n const summary = summarizeCapture(linked.config, {\n documents: evidence.documents,\n changedPaths: evidence.changed_paths,\n exclusions: evidence.exclusions,\n endRevision: evidence.end_revision,\n endStatusDigest: evidence.end_status_digest,\n baselineRef: baseline.git_head,\n });\n let captureEnvelope: PjanglerNoteEnvelopeV1 = {\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n project_slug: active.project_slug,\n kind: \"session-capture\",\n logical_id: active.logical_id,\n ...(evidence.end_revision ? { source_revision: evidence.end_revision } : {}),\n content_sha256: sha256Hex(summary.summary),\n session_key: active.session_key,\n captured_at: active.created_at,\n policy_version: NOTEBOOK_POLICY_VERSION,\n };\n let fittedSummary = managedContent(captureEnvelope, summary.summary, linked.config.limits.note_max_bytes, true);\n if (fittedSummary.body !== summary.summary) {\n captureEnvelope = { ...captureEnvelope, content_sha256: sha256Hex(fittedSummary.body) };\n fittedSummary = managedContent(captureEnvelope, fittedSummary.body, linked.config.limits.note_max_bytes, true);\n }\n renew();\n const captureUpsert = await upsertManaged({\n module,\n receipt: active,\n notebookId: linked.notebookId,\n client: linked.client!,\n logicalId: active.logical_id,\n title: `Session Capture ${active.created_at}`,\n content: fittedSummary.content,\n beforeRemote: renew,\n });\n const captureNote = captureUpsert.note;\n if (captureUpsert.journal) journals.push(captureUpsert.journal);\n logicalIds.push(active.logical_id);\n remoteIds.push(captureNote.id);\n const completed = transitionCaptureReceipt({\n root: module.stateRoot,\n projectSlug: active.project_slug,\n receiptId: active.receipt_id,\n limits: linked.config.limits,\n expected: captureReceiptVersion(active),\n state: \"succeeded\",\n exclusionCounts: evidence.exclusions,\n summaryMode: summary.mode,\n noteLogicalIds: logicalIds,\n remoteNoteIds: remoteIds,\n endRevision: evidence.end_revision,\n endStatusDigest: evidence.end_status_digest,\n });\n for (const journal of journals) commitReconciledRemoteMutation(module.stateRoot, journal);\n return completed;\n}\n\nexport async function runCaptureWorker(module: NotebookModule, projectSlug: string, receiptId: string): Promise<CaptureWorkerResultV1> {\n const local = module.contextBySlug(projectSlug, false);\n let receipt = readCaptureReceipt(module.stateRoot, projectSlug, receiptId, local.config.limits);\n if (receipt.state === \"succeeded\") return { receipt, processed: finalizeSucceededReceiptJournals(module, receipt).length > 0 };\n while (true) {\n receipt = claimCaptureReceipt({ root: module.stateRoot, projectSlug, receiptId, limits: local.config.limits });\n try {\n const completed = await processClaimed(module, receipt, (updated) => { receipt = updated; });\n return { receipt: completed, processed: true };\n } catch (error) {\n const normalized = normalizeNotebookError(error);\n if (receipt.attempt_origin === \"operator\") {\n receipt = transitionCaptureReceipt({\n root: module.stateRoot,\n projectSlug,\n receiptId,\n limits: local.config.limits,\n expected: captureReceiptVersion(receipt),\n state: \"retry-exhausted\",\n errorCategory: normalized.code,\n retryable: normalized.retryable,\n diagnostic: normalized.message,\n });\n return { receipt, processed: true };\n }\n const budgetRemains = normalized.retryable && receipt.automatic_attempts_used < receipt.automatic_attempt_limit;\n receipt = transitionCaptureReceipt({\n root: module.stateRoot,\n projectSlug,\n receiptId,\n limits: local.config.limits,\n expected: captureReceiptVersion(receipt),\n state: budgetRemains ? \"failed\" : receipt.automatic_attempts_used >= receipt.automatic_attempt_limit ? \"retry-exhausted\" : \"failed\",\n errorCategory: normalized.code,\n retryable: normalized.retryable,\n diagnostic: normalized.message,\n });\n if (!budgetRemains) return { receipt, processed: true };\n receipt = transitionCaptureReceipt({\n root: module.stateRoot,\n projectSlug,\n receiptId,\n limits: local.config.limits,\n expected: captureReceiptVersion(receipt),\n state: \"queued\",\n errorCategory: normalized.code,\n retryable: true,\n diagnostic: normalized.message,\n });\n }\n }\n}\n", "#!/usr/bin/env node\nimport { existsSync, statSync } from \"node:fs\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\nimport { getRecipeInfo, getRecipeNames, COMMAND_REGISTRY, RECIPE_REGISTRY } from \"./utils/registry\";\nimport type { CommandContext } from \"./commands/Command\";\nimport type { HermesAgentContext, TicketProvider } from \"./commands/hermes/types\";\nimport { PJANGLER_VERSION } from \"./utils/version\";\nimport { lifecycleContext, recipeRegistry, formatAuditReport, getParityRuleIds, runAudit, runMigration } from \"./parity/index\";\nimport { describeProject, formatProjectDescription } from \"./describe/index\";\nimport {\n getProject,\n loadProjectRegistry,\n normalizeAgentRole,\n planProjectInit,\n projectRegistryPath,\n proposeProjectIdentifier,\n resolveContainedPath,\n type ProjectManifest,\n validateSafePathSegment,\n} from \"./project/index\";\nimport type { ProjectRecipeInput, ProjectRecipeResult } from \"./recipes/ProjectRecipe\";\nimport type { LifecycleContext } from \"./recipes/types\";\nimport { preflightMcpLifecycle, type TrustedCopierIdentity } from \"./lifecycle/preflight\";\n\nconst server = new McpServer({\n name: \"pjangler-mcp\",\n version: PJANGLER_VERSION,\n});\n\nconst TICKET_PROVIDER_SCHEMA = z.enum([\"plane\", \"trello\"]);\nconst BOARD_URL_COMPAT_SCHEMA = z.string()\n .optional()\n .describe(\"Deprecated compatibility input. Ignored; board URLs are derived at runtime and are never persisted.\")\n .meta({ deprecated: true });\nconst RUNTIME_REPO_COMPAT_SCHEMA = z.boolean()\n .optional()\n .describe(\"Deprecated no-op. Hermes always converges ignored role-local runtime state and never provisions a per-agent GitHub repository.\")\n .meta({ deprecated: true });\n\nfunction safePathSegmentSchema(label: string) {\n return z.string().superRefine((value, context) => {\n try {\n validateSafePathSegment(value, label);\n } catch (error) {\n context.addIssue({ code: \"custom\", message: error instanceof Error ? error.message : String(error) });\n }\n });\n}\n\nconst PROJECT_SLUG_SCHEMA = safePathSegmentSchema(\"Project slug\")\n .describe(\"A safe single path segment used as the project registry slug.\");\nconst AGENT_ROLE_SCHEMA = safePathSegmentSchema(\"Agent role\")\n .describe(\"An arbitrary safe single path segment used beneath agents/hermes; not a fixed role enum.\");\nconst TARGET_REPO_SCHEMA = safePathSegmentSchema(\"Hermes target repository\")\n .describe(\"A safe repository/profile identity segment; defaults to the target directory basename.\");\nconst EXPLICIT_TARGET_DIR_SCHEMA = z.string().refine((value) => value.trim().length > 0, {\n message: \"targetDir must be a non-empty explicit path\",\n});\n\nconst INTERACTIVE_RECIPE_IDS = new Set([\"hermes-agent\"]);\nconst GENERIC_RECIPE_NAMES = getRecipeNames().filter((name) => !INTERACTIVE_RECIPE_IDS.has(name));\nif (GENERIC_RECIPE_NAMES.length === 0) throw new Error(\"No non-interactive recipes are registered for generic MCP execution\");\n\ninterface ExternalEffectConsentInput {\n live?: boolean;\n local?: boolean;\n /** Deprecated no-op compatibility fields; neither grants nor subtracts authority. */\n provisionRuntimeRepo?: boolean;\n skipRuntimeRepo?: boolean;\n provisionTicketBoard?: boolean;\n enableSystemd?: boolean;\n skipPlane?: boolean;\n skipSystemd?: boolean;\n}\n\ninterface ExternalEffectSelection {\n ticketBoard: boolean;\n systemd: boolean;\n}\n\n/**\n * Resolve explicit positive grants before any handler performs filesystem or\n * subprocess work. Negative/local flags may only subtract authority; they can\n * never enable an effect by themselves.\n */\nfunction validateExternalEffectConsent(\n input: ExternalEffectConsentInput,\n options: { requireNonLocal: boolean },\n): ExternalEffectSelection {\n const selected: ExternalEffectSelection = {\n ticketBoard: input.provisionTicketBoard === true,\n systemd: input.enableSystemd === true,\n };\n const anySelected = selected.ticketBoard || selected.systemd;\n if (anySelected && input.live !== true) {\n throw new Error(\"External Hermes effects require live=true in addition to explicit positive opt-ins\");\n }\n if (anySelected && options.requireNonLocal && input.local !== false) {\n throw new Error(\"External Hermes effects require local=false in addition to live=true and explicit positive opt-ins\");\n }\n if (selected.ticketBoard && input.skipPlane === true) {\n throw new Error(\"provisionTicketBoard=true contradicts skipPlane=true\");\n }\n if (selected.systemd && input.skipSystemd === true) {\n throw new Error(\"enableSystemd=true contradicts skipSystemd=true\");\n }\n if (selected.systemd && process.platform === \"darwin\") {\n throw new Error(\"enableSystemd=true is unavailable on macOS\");\n }\n return selected;\n}\n\nfunction resolveTargetDir(targetDir?: string): string {\n const dir = resolve(targetDir ?? process.cwd());\n if (!existsSync(dir)) {\n throw new Error(`Target directory does not exist: ${dir}`);\n }\n if (!statSync(dir).isDirectory()) {\n throw new Error(`Target path is not a directory: ${dir}`);\n }\n return dir;\n}\n\nfunction resolvePjanglerRoot(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n while (dir !== dirname(dir)) {\n if (existsSync(join(dir, \"package.json\")) && existsSync(join(dir, \"templates\", \"commonproject\", \"copier.yml\"))) {\n return dir;\n }\n dir = dirname(dir);\n }\n throw new Error(\"Unable to resolve pjangler root\");\n}\n\nfunction slugify(value: string): string {\n return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"project\";\n}\n\nfunction asText(payload: unknown) {\n return { content: [{ type: \"text\" as const, text: typeof payload === \"string\" ? payload : JSON.stringify(payload, null, 2) }] };\n}\n\nfunction publicProjectPlan(plan: ReturnType<typeof planProjectInit>) {\n return {\n ...plan,\n actions: plan.actions.map((action) => {\n if (action.kind !== \"hermes.provision-agent\") return action;\n return {\n ...action,\n context: {\n skipPlane: action.context.skipPlane,\n skipSystemd: action.context.skipSystemd,\n },\n };\n }),\n };\n}\n\nfunction publicCompositeProjectResponse<T extends object>(payload: T, plan: ReturnType<typeof planProjectInit>) {\n const projectedPlan = publicProjectPlan(plan);\n const hasNestedPlan = \"plan\" in payload;\n const provisionsAgent = plan.actions.some((action) => action.kind === \"hermes.provision-agent\" && action.enabled);\n return {\n ...payload,\n ...(hasNestedPlan ? { plan: projectedPlan } : {}),\n ...(provisionsAgent ? {\n bloodbankMode: \"fleet-shared\" as const,\n runtimeMode: \"role-local-ignored\" as const,\n } : {}),\n };\n}\n\nasync function executeRegisteredProjectPlan(\n plan: ReturnType<typeof planProjectInit>,\n agentContext?: Partial<HermesAgentContext>,\n lifecycleOverrides: Partial<LifecycleContext> = {},\n trustedCopier?: TrustedCopierIdentity,\n) {\n const plannedAgent = plan.actions.find((action) => action.kind === \"hermes.provision-agent\" && action.enabled);\n const projectInput: ProjectRecipeInput = {\n plan,\n mode: plan.actions.some((action) => action.kind === \"copier.copy.commonproject\") ? \"create\" : \"sync\",\n selectedRuleIds: [],\n selectedOperations: plan.actions.map((action) => action.kind),\n trustedCopier,\n requireTrustedCopier: Boolean(\n plan.actions.some((action) => action.kind === \"copier.copy.commonproject\")\n || plannedAgent?.kind === \"hermes.provision-agent\",\n ),\n agentContext: plannedAgent?.kind === \"hermes.provision-agent\"\n ? {\n ...agentContext,\n trustedCopier,\n deferredExternalEffects: {\n ticketBoard: !plannedAgent.context.skipPlane,\n systemd: !plannedAgent.context.skipSystemd,\n owner: \"project\",\n },\n }\n : agentContext,\n quiet: true,\n };\n return await recipeRegistry.initRecipe(\n \"project\",\n lifecycleContext(plan.project.repo_path, false, false, {\n ...agentContext,\n ...lifecycleOverrides,\n force: lifecycleOverrides.force ?? agentContext?.force ?? plan.actions.some((action) => action.kind === \"copier.copy.commonproject\" && action.overwrite),\n live: lifecycleOverrides.live ?? plan.live,\n quiet: lifecycleOverrides.quiet ?? true,\n }),\n projectInput,\n ) as ProjectRecipeResult;\n}\n\nfunction projectPreflightFailure(\n plan: ReturnType<typeof planProjectInit>,\n errors: readonly string[],\n audit?: ReturnType<typeof runAudit>,\n): ProjectRecipeResult {\n return {\n recipeId: \"project\",\n ok: false,\n dryRun: false,\n changedFiles: [],\n logs: [],\n errors: [...errors],\n phases: [{\n id: \"project.preflight:lifecycle\",\n status: \"failed\",\n changedFiles: [],\n message: errors.join(\"; \"),\n }],\n plan,\n mode: plan.actions.some((action) => action.kind === \"copier.copy.commonproject\") ? \"create\" : \"sync\",\n audit,\n selectedOperations: plan.actions.map((action) => action.kind),\n selectedParityRules: [],\n };\n}\n\n/**\n * Reject non-repairable, already-present Hermes identity/scaffold failures\n * before trusted Copier or any host script runs. The pm-scaffold audit is\n * filesystem-only, so this check cannot itself invoke git, systemd, a provider,\n * or another subprocess.\n */\nfunction preflightExistingHermesScaffold(targetDir: string): string | undefined {\n if (!existsSync(join(targetDir, \"agents\", \"hermes\"))) return undefined;\n const owner = recipeRegistry.ownerOf(\"hermes.pm-scaffold\");\n if (!owner) return \"Hermes lifecycle owner is unavailable\";\n const finding = owner.check.audit(lifecycleContext(targetDir, true));\n if ((finding.status === \"fail\" || finding.status === \"warn\") && !finding.fixable) {\n const detail = finding.details.length ? ` (${finding.details.join(\"; \")})` : \"\";\n return `${finding.id}: ${finding.summary}${detail}`;\n }\n return undefined;\n}\n\n/**\n * Establish every lifecycle failure knowable without mutation before the\n * project transaction. Existing syncs may project a new canonical manifest,\n * so sot.project-json is the one current finding covered by that planned local\n * action. All other current drift would survive the operation and must block.\n */\ninterface ProjectApplyPreflight {\n failure?: ProjectRecipeResult;\n trustedCopier?: TrustedCopierIdentity;\n}\n\nfunction plannedNotebookBindingRepairsDrift(plan: ReturnType<typeof planProjectInit>): boolean {\n if (!plan.actions.some((action) => action.kind === \"project.write-manifest\")) return false;\n const authoritative = plan.project.notebook;\n const notebook = (plan.manifest as ProjectManifest & { notebook?: unknown }).notebook;\n const projected = notebook && typeof notebook === \"object\" && !Array.isArray(notebook)\n ? (notebook as Record<string, unknown>).binding\n : undefined;\n if (!authoritative || typeof authoritative !== \"object\" || !projected || typeof projected !== \"object\" || Array.isArray(projected)) return false;\n const projectedRecord = projected as Record<string, unknown>;\n return [\"state\", \"notebook_id\", \"notebook_name\", \"overview_note_id\", \"blocked_reason\"].every(\n (key) => (authoritative as unknown as Record<string, unknown>)[key] === projectedRecord[key],\n );\n}\n\nfunction preflightProjectApply(\n plan: ReturnType<typeof planProjectInit>,\n pjanglerRoot: string,\n): ProjectApplyPreflight {\n const createsScaffold = plan.actions.some((action) => action.kind === \"copier.copy.commonproject\");\n const provisionsAgent = plan.actions.some((action) => action.kind === \"hermes.provision-agent\" && action.enabled);\n\n if (!createsScaffold && provisionsAgent) {\n const hermesBlocker = preflightExistingHermesScaffold(plan.project.repo_path);\n if (hermesBlocker) return { failure: projectPreflightFailure(plan, [hermesBlocker]) };\n }\n\n if (!createsScaffold) {\n const audit = runAudit(plan.project.repo_path);\n const blocking = audit.rules.filter((finding) => {\n if (finding.status === \"pass\" || finding.status === \"skip\") return false;\n if (finding.id === \"sot.project-json\") return false;\n if (finding.id === \"notebook.binding\" && plannedNotebookBindingRepairsDrift(plan)) return false;\n if (provisionsAgent && finding.id.startsWith(\"hermes.\")) return false;\n return true;\n });\n if (blocking.length) {\n return {\n failure: projectPreflightFailure(\n plan,\n blocking.map((finding) => `${finding.id}: ${finding.summary}`),\n audit,\n ),\n };\n }\n }\n\n if (createsScaffold || provisionsAgent) {\n const eligibility = preflightMcpLifecycle({\n pjanglerRoot,\n targetDir: plan.project.repo_path,\n commonProject: createsScaffold,\n hermes: provisionsAgent,\n });\n if (!eligibility.ok) {\n return {\n failure: projectPreflightFailure(plan, [`Lifecycle preflight failed: ${eligibility.error ?? \"unknown eligibility failure\"}`]),\n };\n }\n if (!eligibility.identity) {\n return {\n failure: projectPreflightFailure(plan, [\"Lifecycle preflight failed: Copier attestation returned no executable identity\"]),\n };\n }\n return { trustedCopier: eligibility.identity };\n }\n return {};\n}\n\nfunction auditSummary(report: ReturnType<typeof runAudit>) {\n const counts = report.rules.reduce<Record<string, number>>((acc, rule) => {\n acc[rule.status] = (acc[rule.status] ?? 0) + 1;\n return acc;\n }, {});\n const nextActions = report.rules\n .filter((rule) => (rule.status === \"fail\" || rule.status === \"warn\") && rule.fixable)\n .map((rule) => `pjangler_migrate_project ${rule.id}`);\n return { counts, nextActions };\n}\n\nfunction migrationSummary(report: ReturnType<typeof runMigration>) {\n const counts = report.results.reduce<Record<string, number>>((acc, result) => {\n acc[result.status] = (acc[result.status] ?? 0) + 1;\n return acc;\n }, {});\n return { counts, changedFileCount: report.changedFiles.length };\n}\n\nfunction parityGuidance() {\n return {\n skill: \"@33god-projects\",\n guidance: \"Use these tools before editing a project so the repo SOT, agent files, mise hooks, and Hermes role scaffold are current.\",\n workflows: [\n \"audit -> pjangler_audit_project\",\n \"migrate -> pjangler_migrate_project\",\n \"bootstrap -> pjangler_bootstrap_33god_project\",\n \"agent provisioning -> pjangler_deploy_hermes_agent\",\n ],\n };\n}\n\nasync function runRecipeWithCapture(recipeName: string, context: CommandContext): Promise<{ success: boolean; logs: string[]; errors: string[] }> {\n if (!recipeRegistry.get(recipeName)) {\n return {\n success: false,\n logs: [],\n errors: [`Unknown recipe: ${recipeName}. Available: ${getRecipeNames().join(\", \")}`],\n };\n }\n try {\n // MCP owns stdout. Force every registry dispatch into capture/silent mode;\n // callers cannot weaken this by supplying a context value.\n const ctx = lifecycleContext(context.targetDir, Boolean(context.dryRun), false, { ...context, quiet: true });\n const result = await recipeRegistry.initRecipe(recipeName, ctx, {});\n return { success: result.ok, logs: result.logs, errors: result.errors };\n } catch (err) {\n return { success: false, logs: [], errors: [err instanceof Error ? err.message : String(err)] };\n }\n}\n\nserver.registerTool(\n \"pjangler_list_capabilities\",\n {\n title: \"List pjangler capabilities\",\n description: \"Returns available recipes, commands, parity rules, workflows, and @33god-projects tool guidance.\",\n inputSchema: z.strictObject({}),\n },\n async () => {\n const payload = {\n recipes: Object.values(RECIPE_REGISTRY).filter((r) => !INTERACTIVE_RECIPE_IDS.has(r.name)).map((r) => ({\n name: r.name,\n description: r.description,\n commands: r.commands,\n })),\n dedicatedRecipes: [\n {\n name: \"hermes-agent\",\n description: \"Non-interactive Hermes provisioning with explicit local and external-effect consent gates.\",\n tool: \"pjangler_deploy_hermes_agent\",\n },\n ],\n commands: Object.values(COMMAND_REGISTRY).map((c) => ({\n name: c.name,\n description: c.description,\n group: c.group,\n })),\n parityRules: getParityRuleIds(),\n recommendedWorkflows: {\n unfamiliarRepo: [\"pjangler_describe_project\", \"pjangler_audit_project\"],\n existingProject: [\"pjangler_describe_project\", \"pjangler_audit_project\", \"pjangler_migrate_project\"],\n new33godProject: [\"pjangler_project_init\", \"pjangler_bootstrap_33god_project\", \"pjangler_audit_project\"],\n hermesAgentProvisioning: [\"pjangler_deploy_hermes_agent\", \"pjangler_audit_project\"],\n },\n skillSynergy: parityGuidance(),\n };\n\n return asText(payload);\n }\n);\n\nserver.registerTool(\n \"pjangler_list_parity_rules\",\n {\n title: \"List pjangler parity rules\",\n description: \"Returns parity rule ids plus brief @33god-projects guidance.\",\n inputSchema: z.strictObject({}),\n },\n async () => asText({ parityRules: getParityRuleIds(), guidance: parityGuidance() })\n);\n\nserver.registerTool(\n \"pjangler_audit_project\",\n {\n title: \"Audit project parity\",\n description: \"Runs pjangler parity audit for a project and returns structured findings with summary counts and next actions.\",\n inputSchema: z.strictObject({\n targetDir: z.string().optional(),\n json: z.boolean().optional(),\n }),\n },\n async ({ targetDir, json }) => {\n try {\n const resolvedTarget = resolveTargetDir(targetDir);\n const report = runAudit(resolvedTarget);\n const payload = { ...report, summary: auditSummary(report), guidance: parityGuidance() };\n return asText(json === false ? formatAuditReport(report) : payload);\n } catch (err) {\n return { isError: true, content: [{ type: \"text\" as const, text: err instanceof Error ? err.message : String(err) }] };\n }\n }\n);\n\nserver.registerTool(\n \"pjangler_migrate_project\",\n {\n title: \"Migrate project parity\",\n description: \"Runs one pjangler parity migration rule, or all rules, against a project.\",\n inputSchema: z.strictObject({\n targetDir: z.string().optional(),\n ruleId: z.string().optional(),\n all: z.boolean().optional(),\n dryRun: z.boolean().optional(),\n acceptRegistryMatches: z.boolean().optional(),\n }),\n },\n async ({ targetDir, ruleId, all, dryRun, acceptRegistryMatches }) => {\n try {\n const runAll = all ?? false;\n if (!runAll && !ruleId) throw new Error(\"Either ruleId or all=true is required\");\n if (runAll && ruleId) throw new Error(\"Pass either ruleId or all=true, not both\");\n const resolvedTarget = resolveTargetDir(targetDir);\n const report = runMigration(ruleId, resolvedTarget, dryRun ?? true, runAll, acceptRegistryMatches ?? false);\n return {\n isError: !report.ok,\n ...asText({\n ok: report.ok,\n repo: report.repo,\n dryRun: report.dryRun,\n selectedRules: report.selectedRules,\n changedFiles: report.changedFiles,\n results: report.results,\n summary: migrationSummary(report),\n }),\n };\n } catch (err) {\n return { isError: true, content: [{ type: \"text\" as const, text: err instanceof Error ? err.message : String(err) }] };\n }\n }\n);\n\nserver.registerTool(\n \"pjangler_bootstrap_33god_project\",\n {\n title: \"Bootstrap a new @33god project\",\n description: \"Create a new CommonProject-based 33god repo with optional non-interactive Hermes provisioning. Preview is the default; each external effect requires live=true plus an explicit positive opt-in.\",\n inputSchema: z.strictObject({\n parentDir: z.string().optional(),\n targetDir: z.string().optional(),\n projectName: z.string(),\n projectDescription: z.string().optional(),\n projectSlug: PROJECT_SLUG_SCHEMA.optional(),\n ticketProvider: TICKET_PROVIDER_SCHEMA.optional(),\n boardId: z.string().optional(),\n boardUrl: BOARD_URL_COMPAT_SCHEMA,\n workspace: z.string().optional(),\n planeWorkspace: z.string().optional(),\n planeProjectId: z.string().optional(),\n projectIdentifier: z.string().optional(),\n primaryLanguage: z.string().optional(),\n skipPlane: z.boolean().optional(),\n provisionAgent: z.boolean().optional(),\n agentRole: AGENT_ROLE_SCHEMA.optional(),\n agentPurpose: z.string().optional(),\n local: z.boolean().optional(),\n provisionRuntimeRepo: RUNTIME_REPO_COMPAT_SCHEMA,\n provisionTicketBoard: z.boolean().optional().describe(\"Explicitly opt in to ticket-board provisioning; also requires live=true, local=false, and skipPlane!=true.\"),\n enableSystemd: z.boolean().optional().describe(\"Explicitly opt in to systemd installation/enablement; also requires live=true and local=false.\"),\n force: z.boolean().optional(),\n overwrite: z.boolean().optional(),\n dryRun: z.boolean().optional(),\n registryPath: z.string().optional(),\n sourceSkill: z.string().optional(),\n live: z.boolean().optional(),\n }),\n },\n async (input) => {\n try {\n const externalEffects = validateExternalEffectConsent(\n { ...input, skipPlane: input.skipPlane ?? true },\n { requireNonLocal: true },\n );\n const pjanglerRoot = resolvePjanglerRoot();\n const projectSlug = validateSafePathSegment(input.projectSlug ?? slugify(input.projectName), \"Project slug\");\n const explicitTargetDir = input.targetDir ? resolve(input.targetDir) : undefined;\n const parentDir = resolve(input.parentDir ?? (explicitTargetDir ? dirname(explicitTargetDir) : process.cwd()));\n if (!existsSync(parentDir) || !statSync(parentDir).isDirectory()) throw new Error(`Parent directory does not exist: ${parentDir}`);\n const targetDir = resolveContainedPath(\n parentDir,\n explicitTargetDir ?? join(parentDir, projectSlug),\n \"Bootstrap target\",\n );\n const overwrite = input.overwrite ?? input.force ?? false;\n const dryRun = input.dryRun ?? true;\n const local = input.local ?? true;\n const skipPlane = input.skipPlane ?? true;\n const ticketProvider = input.ticketProvider ?? \"plane\";\n const boardId = input.boardId ?? input.planeProjectId ?? \"\";\n if (externalEffects.ticketBoard && ticketProvider === \"plane\" && !boardId) {\n throw new Error(\"boardId or planeProjectId is required when skipPlane=false for Plane; keep skipPlane=true for safe local bootstrap\");\n }\n if (!dryRun && existsSync(targetDir) && !overwrite) throw new Error(`Target already exists: ${targetDir} (set force/overwrite=true to re-render)`);\n\n const plan = planProjectInit({\n name: input.projectName,\n description: input.projectDescription,\n targetDir,\n projectSlug,\n sourceSkill: input.sourceSkill,\n primaryLanguage: input.primaryLanguage ?? \"python\",\n provisionAgent: input.provisionAgent ?? false,\n agentRole: input.agentRole ?? \"pm\",\n apply: !dryRun,\n live: input.live ?? false,\n provisionTicketBoard: externalEffects.ticketBoard,\n enableSystemd: externalEffects.systemd,\n skipPlane,\n registryPath: input.registryPath,\n // A PROPOSAL only. The provider assigns the real identifier and\n // `pj project identity` reads it back; MCP never mints a board key.\n projectIdentifier: input.projectIdentifier ?? proposeProjectIdentifier(projectSlug),\n ticketProvider,\n boardId,\n boardUrl: input.boardUrl,\n boardWorkspace: input.workspace ?? input.planeWorkspace,\n planeWorkspace: input.planeWorkspace ?? \"33god\",\n planeProjectId: input.planeProjectId,\n pjanglerRoot,\n overwrite,\n });\n\n if (dryRun) {\n return asText(publicCompositeProjectResponse({ ...publicProjectPlan(plan), guidance: parityGuidance() }, plan));\n }\n\n const preflight = preflightProjectApply(plan, pjanglerRoot);\n if (preflight.failure) {\n return {\n isError: true,\n ...asText(publicCompositeProjectResponse(\n { ...preflight.failure, ...(plan.warnings ? { warnings: plan.warnings } : {}), guidance: parityGuidance() },\n plan,\n )),\n };\n }\n\n const plannedAgent = plan.actions.find((action) => action.kind === \"hermes.provision-agent\");\n const result = await executeRegisteredProjectPlan(plan, input.provisionAgent ? {\n targetRepo: projectSlug,\n role: input.agentRole ?? \"pm\",\n agentPurpose: input.agentPurpose ?? `Project manager for ${input.projectName}`,\n local: plannedAgent?.kind === \"hermes.provision-agent\" ? plannedAgent.local : local,\n force: overwrite,\n skipTelegram: true,\n skipEmail: true,\n skipPlane: plannedAgent?.kind === \"hermes.provision-agent\" ? plannedAgent.context.skipPlane : true,\n skipBloodbank: true,\n skipSystemd: plannedAgent?.kind === \"hermes.provision-agent\" ? plannedAgent.context.skipSystemd : true,\n } : undefined, {\n force: overwrite,\n live: input.live ?? false,\n quiet: true,\n }, preflight.trustedCopier);\n if (!result.ok) {\n return {\n isError: true,\n ...asText(publicCompositeProjectResponse(\n { ...result, ...(plan.warnings ? { warnings: plan.warnings } : {}), guidance: parityGuidance() },\n plan,\n )),\n };\n }\n\n const agentResult = input.provisionAgent\n ? {\n success: Boolean(result.agentResult?.ok),\n logs: result.agentResult?.logs ?? [],\n errors: result.agentResult?.errors ?? (result.ok ? [] : result.errors),\n }\n : undefined;\n return asText(publicCompositeProjectResponse(\n { ...result, agentResult, ...(plan.warnings ? { warnings: plan.warnings } : {}), guidance: parityGuidance() },\n plan,\n ));\n } catch (err) {\n return { isError: true, content: [{ type: \"text\" as const, text: err instanceof Error ? err.message : String(err) }] };\n }\n }\n);\n\nserver.registerTool(\n \"pjangler_project_init\",\n {\n title: \"Initialize a pjangler project\",\n description: \"Plan or apply a registry-backed CommonProject project init. Preview is the default; writes require apply=true and each external effect requires live=true plus an explicit positive opt-in.\",\n inputSchema: z.strictObject({\n name: z.string(),\n description: z.string().optional(),\n targetDir: z.string().optional(),\n sourceSkill: z.string().optional(),\n primaryLanguage: z.string().optional(),\n provisionAgent: z.boolean().optional(),\n agentRole: AGENT_ROLE_SCHEMA.optional(),\n apply: z.boolean().optional(),\n live: z.boolean().optional(),\n provisionRuntimeRepo: RUNTIME_REPO_COMPAT_SCHEMA,\n provisionTicketBoard: z.boolean().optional().describe(\"Explicitly opt in to ticket-board provisioning; also requires live=true and skipPlane!=true.\"),\n enableSystemd: z.boolean().optional().describe(\"Explicitly opt in to Hermes systemd installation/enablement; also requires live=true.\"),\n skipPlane: z.boolean().optional().describe(\"Disable project-board planning and provider invocation even when live=true.\"),\n slug: PROJECT_SLUG_SCHEMA.optional(),\n identifier: z.string().optional(),\n ticketProvider: TICKET_PROVIDER_SCHEMA.optional(),\n boardId: z.string().optional(),\n boardUrl: BOARD_URL_COMPAT_SCHEMA,\n workspace: z.string().optional(),\n registryPath: z.string().optional(),\n force: z.boolean().optional(),\n }),\n },\n async (input) => {\n try {\n const externalEffects = validateExternalEffectConsent(input, { requireNonLocal: false });\n const plan = planProjectInit({\n name: input.name,\n description: input.description,\n targetDir: input.targetDir,\n sourceSkill: input.sourceSkill,\n primaryLanguage: input.primaryLanguage,\n provisionAgent: input.provisionAgent ?? false,\n agentRole: input.agentRole,\n apply: input.apply ?? false,\n live: input.live ?? false,\n provisionTicketBoard: externalEffects.ticketBoard,\n enableSystemd: externalEffects.systemd,\n skipPlane: input.skipPlane ?? false,\n projectSlug: input.slug,\n projectIdentifier: input.identifier,\n ticketProvider: input.ticketProvider,\n boardId: input.boardId,\n boardUrl: input.boardUrl,\n boardWorkspace: input.workspace,\n registryPath: input.registryPath,\n force: input.force ?? false,\n overwrite: input.force ?? false,\n scaffold: !(input.targetDir && existsSync(join(resolve(input.targetDir), \".git\"))),\n });\n if (!input.apply) return asText(publicCompositeProjectResponse(publicProjectPlan(plan), plan));\n const preflight = preflightProjectApply(plan, resolvePjanglerRoot());\n if (preflight.failure) {\n return {\n isError: true,\n ...asText(publicCompositeProjectResponse(\n { ...preflight.failure, ...(plan.warnings ? { warnings: plan.warnings } : {}) },\n plan,\n )),\n };\n }\n const result = await executeRegisteredProjectPlan(plan, undefined, {\n force: input.force ?? false,\n live: input.live ?? false,\n quiet: true,\n }, preflight.trustedCopier);\n return {\n isError: !result.ok,\n ...asText(publicCompositeProjectResponse(\n { ...result, ...(plan.warnings ? { warnings: plan.warnings } : {}) },\n plan,\n )),\n };\n } catch (err) {\n return { isError: true, content: [{ type: \"text\" as const, text: err instanceof Error ? err.message : String(err) }] };\n }\n }\n);\n\nserver.registerTool(\n \"pjangler_project_list\",\n {\n title: \"List pjangler registry projects\",\n description: \"Return projects from the pjangler central registry.\",\n inputSchema: z.strictObject({\n registryPath: z.string().optional(),\n }),\n },\n async ({ registryPath }) => asText(loadProjectRegistry(registryPath ?? projectRegistryPath()))\n);\n\nserver.registerTool(\n \"pjangler_project_show\",\n {\n title: \"Show a pjangler registry project\",\n description: \"Return one project by slug from the pjangler central registry.\",\n inputSchema: z.strictObject({\n slug: PROJECT_SLUG_SCHEMA,\n registryPath: z.string().optional(),\n }),\n },\n async ({ slug, registryPath }) => {\n try {\n return asText(getProject(loadProjectRegistry(registryPath ?? projectRegistryPath()), slug));\n } catch (err) {\n return { isError: true, content: [{ type: \"text\" as const, text: err instanceof Error ? err.message : String(err) }] };\n }\n }\n);\n\nserver.registerTool(\n \"pjangler_describe_project\",\n {\n title: \"Describe a project\",\n description:\n \"Reads a repo and returns its detected type, installed pjangler subsystems, config files present, parity counts, and suggested next steps. The orientation call for an agent landing in an unfamiliar repo.\",\n inputSchema: z.strictObject({\n targetDir: z.string().optional(),\n registryPath: z.string().optional(),\n json: z.boolean().optional(),\n }),\n },\n async ({ targetDir, registryPath, json }) => {\n try {\n const description = describeProject({\n repoArg: resolveTargetDir(targetDir),\n registryPath: registryPath ?? projectRegistryPath(),\n });\n return asText(json === false ? formatProjectDescription(description) : description);\n } catch (err) {\n return { isError: true, content: [{ type: \"text\" as const, text: err instanceof Error ? err.message : String(err) }] };\n }\n }\n);\n\nserver.registerTool(\n \"pjangler_describe_recipe\",\n {\n title: \"Describe recipe\",\n description: \"Returns metadata for a specific pjangler recipe.\",\n inputSchema: z.strictObject({\n recipe: z.string(),\n }),\n },\n async ({ recipe }) => {\n const info = getRecipeInfo(recipe);\n if (!info) {\n return {\n isError: true,\n content: [{ type: \"text\" as const, text: `Recipe not found: ${recipe}` }],\n };\n }\n\n return asText({\n name: info.name,\n description: info.description,\n commands: info.commands,\n });\n }\n);\n\nserver.registerTool(\n \"pjangler_run_recipe\",\n {\n title: \"Run recipe\",\n description: \"Preview or apply a non-interactive pjangler recipe against an explicit target directory. Preview is the default; writes require apply=true.\",\n inputSchema: z.strictObject({\n recipe: z.enum(GENERIC_RECIPE_NAMES as [string, ...string[]]),\n targetDir: EXPLICIT_TARGET_DIR_SCHEMA,\n force: z.boolean().optional(),\n apply: z.boolean().optional(),\n }),\n },\n async ({ recipe, targetDir, force, apply }) => {\n try {\n const resolvedTarget = resolveTargetDir(targetDir);\n const shouldApply = apply === true;\n const context: CommandContext = {\n targetDir: resolvedTarget,\n force: force ?? false,\n dryRun: !shouldApply,\n quiet: true,\n };\n\n const result = await runRecipeWithCapture(recipe, context);\n return {\n isError: !result.success,\n ...asText({\n success: result.success,\n recipe,\n targetDir: resolvedTarget,\n apply: shouldApply,\n dryRun: !shouldApply,\n logs: result.logs,\n errors: result.errors,\n }),\n };\n } catch (err) {\n return {\n isError: true,\n content: [{ type: \"text\" as const, text: err instanceof Error ? err.message : String(err) }],\n };\n }\n }\n);\n\nserver.registerTool(\n \"pjangler_deploy_hermes_agent\",\n {\n title: \"Deploy Hermes agent\",\n description:\n \"Preview or apply a non-interactive Hermes agent deployment. Local writes require apply=true. External effects additionally require live=true, local=false, and an explicit positive opt-in for each effect. Bloodbank routing is always fleet-shared.\",\n inputSchema: z.strictObject({\n targetDir: EXPLICIT_TARGET_DIR_SCHEMA,\n targetRepo: TARGET_REPO_SCHEMA.optional(),\n role: AGENT_ROLE_SCHEMA,\n agentPurpose: z.string().optional(),\n soulTone: z.enum([\"direct\", \"playful\", \"formal\", \"terse\"]).optional(),\n modelProvider: z.string().optional(),\n modelName: z.string().optional(),\n modelBaseUrl: z.string().optional(),\n modelApiMode: z.enum([\"\", \"chat_completions\", \"codex_responses\", \"anthropic_messages\", \"bedrock_converse\", \"codex_app_server\"]).optional(),\n modelKeyEnv: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).optional(),\n local: z.boolean().optional(),\n apply: z.boolean().optional(),\n live: z.boolean().optional(),\n provisionRuntimeRepo: RUNTIME_REPO_COMPAT_SCHEMA,\n provisionTicketBoard: z.boolean().optional().describe(\"Explicitly opt in to ticket-board provisioning; requires live=true, local=false, and skipPlane!=true.\"),\n enableSystemd: z.boolean().optional().describe(\"Explicitly opt in to systemd installation/enablement; requires live=true, local=false, and skipSystemd!=true.\"),\n force: z.boolean().optional(),\n skipRuntimeRepo: RUNTIME_REPO_COMPAT_SCHEMA,\n skipPlane: z.boolean().optional(),\n skipSystemd: z.boolean().optional(),\n ticketProvider: TICKET_PROVIDER_SCHEMA.optional(),\n }),\n },\n async (input) => {\n try {\n const externalEffects = validateExternalEffectConsent(input, { requireNonLocal: true });\n const resolvedTarget = resolveTargetDir(input.targetDir);\n const local = input.local ?? true;\n const apply = input.apply === true;\n const live = input.live === true;\n let trustedCopier: TrustedCopierIdentity | undefined;\n\n if (apply) {\n const hermesBlocker = preflightExistingHermesScaffold(resolvedTarget);\n if (hermesBlocker) {\n return {\n isError: true,\n ...asText({\n success: false,\n recipe: \"hermes-agent\",\n targetDir: resolvedTarget,\n apply,\n live,\n logs: [],\n errors: [`Lifecycle preflight failed: ${hermesBlocker}`],\n }),\n };\n }\n const eligibility = preflightMcpLifecycle({\n pjanglerRoot: resolvePjanglerRoot(),\n targetDir: resolvedTarget,\n commonProject: false,\n hermes: true,\n });\n if (!eligibility.ok) {\n return {\n isError: true,\n ...asText({\n success: false,\n recipe: \"hermes-agent\",\n targetDir: resolvedTarget,\n apply,\n live,\n logs: [],\n errors: [`Lifecycle preflight failed: ${eligibility.error ?? \"unknown eligibility failure\"}`],\n }),\n };\n }\n if (!eligibility.identity) {\n return {\n isError: true,\n ...asText({\n success: false,\n recipe: \"hermes-agent\",\n targetDir: resolvedTarget,\n apply,\n live,\n logs: [],\n errors: [\"Lifecycle preflight failed: Copier attestation returned no executable identity\"],\n }),\n };\n }\n trustedCopier = eligibility.identity;\n }\n\n const context: HermesAgentContext = {\n targetDir: resolvedTarget,\n yes: true,\n quiet: true,\n local,\n live,\n targetRepo: input.targetRepo ?? basename(resolvedTarget),\n role: normalizeAgentRole(input.role),\n agentPurpose: input.agentPurpose,\n soulTone: input.soulTone,\n modelProvider: input.modelProvider,\n modelName: input.modelName,\n modelBaseUrl: input.modelBaseUrl,\n modelApiMode: input.modelApiMode,\n modelKeyEnv: input.modelKeyEnv,\n ticketProvider: input.ticketProvider as TicketProvider | undefined,\n force: input.force ?? false,\n dryRun: !apply,\n // MCP has no prompt-capable Telegram/email inputs. These steps remain\n // unreachable and therefore cannot consume JSON-RPC stdin.\n skipTelegram: true,\n skipEmail: true,\n skipPlane: !externalEffects.ticketBoard,\n skipBloodbank: true,\n skipSystemd: !externalEffects.systemd || process.platform === \"darwin\",\n trustedCopier,\n deferredExternalEffects: {\n ticketBoard: externalEffects.ticketBoard,\n systemd: externalEffects.systemd,\n owner: \"hermes\",\n },\n };\n\n const result = await runRecipeWithCapture(\"hermes-agent\", context);\n return {\n isError: !result.success,\n ...asText({\n success: result.success,\n recipe: \"hermes-agent\",\n targetDir: resolvedTarget,\n apply,\n live,\n bloodbankMode: \"fleet-shared\",\n runtimeMode: \"role-local-ignored\",\n guidance: parityGuidance(),\n context: {\n targetRepo: context.targetRepo,\n role: context.role,\n local: context.local,\n dryRun: context.dryRun,\n quiet: context.quiet,\n force: context.force,\n skipPlane: context.skipPlane,\n skipSystemd: context.skipSystemd,\n },\n logs: result.logs,\n errors: result.errors,\n }),\n };\n } catch (err) {\n return {\n isError: true,\n content: [{ type: \"text\" as const, text: err instanceof Error ? err.message : String(err) }],\n };\n }\n }\n);\n\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n", "import { homedir } from \"node:os\";\nimport { resolve } from \"node:path\";\nimport { Command } from \"../commands/Command\";\nimport type { CommandContext, InvokeResult } from \"../commands/Command\";\nimport { bold, cyan, dim, green, yellow, glyph } from \"../utils/style\";\nimport { auditCheck } from \"./types\";\nimport type {\n LifecycleAuditFinding,\n LifecycleContext,\n LifecycleMigrationResult,\n LifecycleRecipe,\n RecipeCheck,\n RecipeInitResult,\n RecipeMetadata,\n RecipePhaseOutcome,\n RecipePhaseStatus,\n} from \"./types\";\n\nexport interface AddIngredient<T extends Command = Command> {\n new (context: CommandContext): T;\n}\n\nfunction commandStatus(result: InvokeResult, dryRun: boolean): RecipePhaseStatus {\n if (result.outcome) return result.outcome;\n if (!result.success) return \"failed\";\n if (dryRun && result.filePath) return \"planned\";\n return result.filePath ? \"changed\" : \"unchanged\";\n}\n\nfunction mergeInitResults(recipeId: string, dryRun: boolean, results: readonly RecipeInitResult[]): RecipeInitResult {\n return {\n recipeId,\n ok: results.every((result) => result.ok),\n dryRun,\n changedFiles: [...new Set(results.flatMap((result) => result.changedFiles))].sort(),\n logs: results.flatMap((result) => result.logs),\n errors: results.flatMap((result) => result.errors),\n phases: results.flatMap((result) => result.phases),\n };\n}\n\n/**\n * A lifecycle recipe owns initialization, audit, and migration for one module.\n * Command messages are presentation only; lifecycle success and changed-file\n * accounting are derived exclusively from structured command/check outcomes.\n */\nexport abstract class Recipe<TInput = unknown> implements LifecycleRecipe<TInput> {\n abstract readonly metadata: RecipeMetadata;\n abstract readonly checks: readonly RecipeCheck[];\n protected readonly ingredientTypes: AddIngredient[] = [];\n private readonly compatibilityContext?: CommandContext;\n\n constructor(context?: CommandContext) {\n this.compatibilityContext = context;\n }\n\n addIngredient<T extends Command>(CommandClass: AddIngredient<T>): this {\n this.ingredientTypes.push(CommandClass);\n return this;\n }\n\n protected async invokeIngredients(ctx: LifecycleContext): Promise<RecipeInitResult> {\n const phases: RecipePhaseOutcome[] = [];\n const logs: string[] = [];\n const errors: string[] = [];\n const changedFiles: string[] = [];\n\n for (const CommandClass of this.ingredientTypes) {\n const command = new CommandClass(ctx);\n const result = await command.invoke();\n const status = commandStatus(result, Boolean(ctx.dryRun));\n const phaseChangedFiles = status === \"changed\" && result.filePath\n ? [resolve(ctx.targetDir, result.filePath)]\n : [];\n phases.push({ id: CommandClass.name, status, changedFiles: phaseChangedFiles, message: result.message || undefined });\n if (result.message) logs.push(result.message);\n changedFiles.push(...phaseChangedFiles);\n if (status === \"failed\" || status === \"cancelled\") errors.push(result.message || `${CommandClass.name} ${status}`);\n if (status === \"failed\" || status === \"cancelled\") break;\n }\n\n return {\n recipeId: this.metadata.id,\n ok: errors.length === 0,\n dryRun: Boolean(ctx.dryRun),\n changedFiles: [...new Set(changedFiles)].sort(),\n logs,\n errors,\n phases,\n };\n }\n\n /** Initialize missing/drifted state using only this recipe's owned checks. */\n protected async initializeOwnedChecks(ctx: LifecycleContext): Promise<RecipeInitResult> {\n const phases: RecipePhaseOutcome[] = [];\n const logs: string[] = [];\n const errors: string[] = [];\n const changedFiles: string[] = [];\n\n for (const check of this.checks) {\n const finding = check.audit(ctx);\n if (finding.status === \"pass\" || finding.status === \"skip\") {\n phases.push({ id: check.id, status: finding.status === \"skip\" ? \"skipped\" : \"unchanged\", changedFiles: [], message: finding.summary });\n continue;\n }\n if (!finding.fixable) {\n phases.push({ id: check.id, status: \"failed\", changedFiles: [], message: finding.summary });\n errors.push(`${check.id}: ${finding.summary}`);\n break;\n }\n const migrated = await check.migrate(ctx, finding);\n const status: RecipePhaseStatus = migrated.status === \"applied\"\n ? (ctx.dryRun ? \"planned\" : \"changed\")\n : migrated.status === \"noop\"\n ? \"unchanged\"\n : migrated.status === \"skipped\"\n ? \"skipped\"\n : \"failed\";\n const actualChanges = status === \"changed\" ? migrated.changedFiles : [];\n phases.push({ id: check.id, status, changedFiles: actualChanges, message: migrated.summary });\n logs.push(`${check.id}: ${migrated.summary}`);\n changedFiles.push(...actualChanges);\n if (status === \"failed\") {\n errors.push(`${check.id}: ${migrated.summary}`);\n break;\n }\n if (!ctx.dryRun) {\n const postcondition = check.audit(ctx);\n if (postcondition.status !== \"pass\" && postcondition.status !== \"skip\") {\n const detail = postcondition.details.length ? ` (${postcondition.details.join(\"; \")})` : \"\";\n errors.push(`${check.id}: init postcondition failed: ${postcondition.summary}${detail}`);\n phases.push({ id: `${check.id}:postcondition`, status: \"failed\", changedFiles: [], message: postcondition.summary });\n break;\n }\n }\n }\n\n return {\n recipeId: this.metadata.id,\n ok: errors.length === 0,\n dryRun: Boolean(ctx.dryRun),\n changedFiles: [...new Set(changedFiles)].sort(),\n logs,\n errors,\n phases,\n };\n }\n\n /** Every concrete recipe declares its own initialization policy. */\n abstract init(ctx: LifecycleContext, input: TInput): Promise<RecipeInitResult>;\n\n audit(ctx: LifecycleContext): LifecycleAuditFinding[] {\n return this.checks.map((check) => auditCheck(check, ctx, this.metadata.id));\n }\n\n migrate(ctx: LifecycleContext, ruleIds: readonly string[]): LifecycleMigrationResult[] {\n const selected = this.checks.filter((check) => ruleIds.includes(check.id));\n return selected.map((check) => ({ ...check.migrate(ctx, check.audit(ctx)), recipeId: this.metadata.id }));\n }\n\n /** @deprecated Compatibility alias; registry dispatch is authoritative. */\n async execute(input?: TInput): Promise<void> {\n if (!this.compatibilityContext) throw new Error(`${this.metadata.id}.execute requires a compatibility context`);\n const targetDir = resolve(this.compatibilityContext.targetDir);\n const ctx: LifecycleContext = {\n ...this.compatibilityContext,\n targetDir,\n repoRoot: targetDir,\n pjanglerRoot: resolve(new URL(\"../..\", import.meta.url).pathname),\n homeDir: homedir(),\n dryRun: Boolean(this.compatibilityContext.dryRun),\n force: Boolean(this.compatibilityContext.force),\n };\n console.log(\"\");\n console.log(` ${cyan(bold(glyph.chevron))} ${bold(`Initializing ${this.metadata.id} subsystem`)}${ctx.dryRun ? ` ${dim(glyph.dot)} ${yellow(\"dry run\")}` : \"\"}`);\n console.log(\"\");\n const result = await this.init(ctx, input as TInput);\n for (const line of result.logs) console.log(line.split(\"\\n\").map((part) => part ? ` ${part}` : part).join(\"\\n\"));\n for (const error of result.errors) console.error(error);\n if (!ctx.dryRun && result.ok) this.printNextSteps();\n if (ctx.dryRun) {\n console.log(\"\");\n console.log(` ${green(glyph.pass)} ${dim(\"Dry-run complete \u2014 no files were modified.\")}`);\n console.log(` ${dim(\"Remove --dry-run to apply changes.\")}`);\n }\n }\n\n protected abstract printNextSteps(): void;\n}\n\nexport { mergeInitResults };\n", "import { existsSync, writeFileSync, mkdirSync } from \"fs\";\nimport { join, dirname } from \"path\";\n\nexport interface InvokeResult {\n success: boolean;\n message: string;\n filePath?: string;\n /** Structured lifecycle outcome. Message text is presentation only. */\n outcome?: \"changed\" | \"unchanged\" | \"planned\" | \"skipped\" | \"failed\" | \"cancelled\";\n}\n\nexport interface CommandContext {\n targetDir: string;\n force?: boolean;\n dryRun?: boolean;\n /** Suppress presentation output when a structured caller owns stdout. */\n quiet?: boolean;\n}\n\nexport abstract class Command {\n protected context: CommandContext;\n\n constructor(context: CommandContext) {\n this.context = context;\n }\n\n abstract invoke(): Promise<InvokeResult>;\n\n /**\n * Format message with [DRY RUN] prefix if in dry-run mode\n */\n protected formatMessage(message: string): string {\n return this.context.dryRun ? `[DRY RUN] ${message}` : message;\n }\n\n protected fileExists(filePath: string): boolean {\n const fullPath = join(this.context.targetDir, filePath);\n return existsSync(fullPath);\n }\n\n protected writeFile(filePath: string, content: string): void {\n // Skip file writing in dry-run mode\n if (this.context.dryRun) {\n return;\n }\n\n const fullPath = join(this.context.targetDir, filePath);\n const dir = dirname(fullPath);\n\n mkdirSync(dir, { recursive: true });\n writeFileSync(fullPath, content);\n }\n\n protected createDirectory(dirPath: string): void {\n // Skip directory creation in dry-run mode\n if (this.context.dryRun) {\n return;\n }\n\n const fullPath = join(this.context.targetDir, dirPath);\n mkdirSync(fullPath, { recursive: true });\n }\n}\n", "import type { CommandContext } from \"../commands/Command\";\nimport type { NotebookObservationV1, NotebookPlanV1 } from \"../notebook/observation\";\n\nexport type RecipeId = string;\nexport type RuleId = string;\nexport type LifecycleStatus = \"pass\" | \"fail\" | \"warn\" | \"skip\";\n/**\n * `partial` is the honest outcome for a rule that DID apply changes (or found\n * nothing it was allowed to change) yet still does not pass its own audit --\n * e.g. a step that needs an explicit opt-in flag, or a blocker the rule\n * refuses to resolve destructively. It is the migrate-side counterpart of the\n * postcondition check `Recipe.initializeOwnedChecks` has always run, and it\n * exists so \"Migration complete\" can never be followed by a failing audit.\n */\nexport type MigrationStatus = \"applied\" | \"noop\" | \"blocked\" | \"skipped\" | \"partial\";\nexport type RecipePhaseStatus = \"changed\" | \"unchanged\" | \"planned\" | \"skipped\" | \"failed\" | \"cancelled\";\n\nexport interface LifecycleContext extends CommandContext {\n targetDir: string;\n dryRun: boolean;\n force: boolean;\n repoRoot: string;\n pjanglerRoot: string;\n homeDir: string;\n /**\n * PJAN-84: the project registry this run reads.\n *\n * Every rule that consults the registry used to fall back to\n * `projectRegistryPath()` independently, so `--registry` could not reach them.\n * `describe --registry` was the visible symptom: describe/index.ts passed the\n * override to describeIdentity and describeNotebook and then built the parity\n * context WITHOUT it, so the identity block and the notebook rules answered\n * about two different registries in one report.\n */\n registryPath?: string;\n live?: boolean;\n bmadVersionPin?: string;\n acceptRegistryMatches?: boolean;\n notebookPlan?: Readonly<NotebookPlanV1>;\n /** True only when the authoritative Registry project has a notebook binding block. */\n notebookRegistryDeclared?: boolean;\n /** Focused `pj notebook audit|migrate` opts undeclared repositories into the actionable declaration rule. */\n notebookFocusedAudit?: boolean;\n /** Exact binding projection from the Manifest snapshot used to build notebookPlan; null means absent. */\n notebookManifestBinding?: Readonly<Record<string, unknown>> | null;\n notebookObservation?: Readonly<NotebookObservationV1>;\n notebookStateRoot?: string;\n}\n\nexport interface RecipeMetadata {\n id: RecipeId;\n name: string;\n description: string;\n dependencies: readonly RecipeId[];\n commands: readonly string[];\n publicRuleIds: readonly RuleId[];\n}\n\nexport interface RecipeInitResult {\n recipeId: RecipeId;\n ok: boolean;\n dryRun: boolean;\n changedFiles: string[];\n logs: string[];\n errors: string[];\n phases: RecipePhaseOutcome[];\n [key: string]: unknown;\n}\n\nexport interface RecipePhaseOutcome {\n id: string;\n status: RecipePhaseStatus;\n changedFiles: string[];\n message?: string;\n}\n\nexport interface LifecycleAuditFinding {\n /** See LifecycleScope. Absent means \"project\". */\n scope?: LifecycleScope;\n id: RuleId;\n title: string;\n status: LifecycleStatus;\n summary: string;\n details: string[];\n fixable: boolean;\n recipeId?: RecipeId;\n}\n\nexport interface LifecycleMigrationResult {\n id: RuleId;\n title: string;\n status: MigrationStatus;\n summary: string;\n changedFiles: string[];\n details: string[];\n recipeId?: RecipeId;\n}\n\nexport interface LifecycleAuditReport {\n repo: string;\n /** Is the audited PROJECT in parity? Host-scoped findings never affect this. */\n ok: boolean;\n /** Is the MACHINE's shared state healthy? Reported separately, never gating. */\n hostOk: boolean;\n auditedAt: string;\n rules: LifecycleAuditFinding[];\n}\n\nexport interface LifecycleMigrationReport {\n repo: string;\n dryRun: boolean;\n ok: boolean;\n selectedRules: string[];\n results: LifecycleMigrationResult[];\n changedFiles: string[];\n}\n\n/**\n * PJAN-84: whose problem is this finding?\n *\n * `project` \u2014 the repository being audited can change it. A failure gates the\n * project: it is exactly what `pj audit` and the init transaction are for.\n * `host` \u2014 it is about this MACHINE ($HOME, systemd, the fleet registry, the\n * global skill projection). No amount of work in the repository can change it,\n * so failing the repository for it is a category error.\n *\n * Absent means `project`, so a rule that has never thought about scope keeps\n * gating \u2014 the safe default.\n *\n * Why this exists: `auditRecipes` counted anything but pass/skip as not-ok, and\n * `ProjectRecipe` turned a not-ok postcondition audit into a transaction error.\n * So one drifted symlink under ~/.agents could fail \u2014 and roll back \u2014 a\n * brand-new project, and every project on the machine at once. PJAN-82 fixed the\n * two rules that happened to be firing; this fixes the semantics, so the next\n * host-scoped rule cannot re-create it.\n */\nexport type LifecycleScope = \"project\" | \"host\";\n\nexport interface RecipeCheck {\n readonly id: RuleId;\n readonly title: string;\n /** Defaults to \"project\" when absent. */\n readonly scope?: LifecycleScope;\n audit(ctx: LifecycleContext): LifecycleAuditFinding;\n migrate(ctx: LifecycleContext, finding: LifecycleAuditFinding): LifecycleMigrationResult;\n}\n\n/**\n * The ONE place a check's audit is turned into a stamped finding.\n *\n * Every caller must go through this. `Recipe.audit` was the only stamper, but\n * `verifyMigration` and `migrateAll` call `checks[i].audit(ctx)` directly \u2014 so a\n * field stamped only in `Recipe.audit` would be silently absent in exactly the\n * two places that decide whether a migration succeeded.\n */\nexport function stampFinding(\n check: RecipeCheck,\n finding: LifecycleAuditFinding,\n recipeId?: string,\n): LifecycleAuditFinding {\n return {\n ...finding,\n scope: finding.scope ?? check.scope ?? \"project\",\n ...(recipeId ? { recipeId } : {}),\n };\n}\n\nexport function auditCheck(\n check: RecipeCheck,\n ctx: LifecycleContext,\n recipeId?: string,\n): LifecycleAuditFinding {\n return stampFinding(check, check.audit(ctx), recipeId);\n}\n\n/** A finding that must not gate the repository it was found in. */\nexport function isHostScoped(finding: Pick<LifecycleAuditFinding, \"scope\">): boolean {\n return finding.scope === \"host\";\n}\n\n/**\n * Does this finding mean the audited PROJECT is out of parity?\n *\n * `warn` deliberately does not. A warn that counts against ok is just a fail\n * with a different glyph, which is how `pj audit` came to exit 1 while\n * reporting zero failed rules. Migration selection is a different question and\n * still picks up fail AND warn.\n */\nexport function gatesProject(finding: Pick<LifecycleAuditFinding, \"status\" | \"scope\">): boolean {\n return finding.status === \"fail\" && !isHostScoped(finding);\n}\n\nexport interface LifecycleRecipe<TInput = unknown> {\n readonly metadata: RecipeMetadata;\n readonly checks: readonly RecipeCheck[];\n init(ctx: LifecycleContext, input: TInput): Promise<RecipeInitResult>;\n audit(ctx: LifecycleContext): LifecycleAuditFinding[];\n migrate(ctx: LifecycleContext, ruleIds: readonly RuleId[]): LifecycleMigrationResult[];\n /** Project-like orchestrators run their declared dependencies inside init. */\n readonly orchestratesDependencies?: boolean;\n}\n", "import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, readdirSync, realpathSync, renameSync, rmdirSync, symlinkSync, unlinkSync, writeFileSync, chmodSync, copyFileSync, cpSync, rmSync } from \"node:fs\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { homedir } from \"node:os\";\nimport { createHash } from \"node:crypto\";\nimport { spawnSync } from \"node:child_process\";\nimport YAML from \"yaml\";\nimport { bold, dim, green, red, yellow, gray, glyph, statusStyle, joinDot } from \"../utils/style\";\nimport { SUPPORTED_BMAD_TOOLS, SUPPORTED_CLI_ROOTS } from \"../recipes/supported-clis\";\nimport {\n PackUnavailableError,\n assertNoSymlinkComponents,\n assertRealDirectory,\n isRegularFile,\n normalizePackEntry,\n readRegularFile,\n readPackMetadata,\n safeRelativePath,\n selectPackVersion,\n validatePack,\n validatePathComponent,\n type PackManifestEntry,\n type ValidatedPack,\n} from \"./pack\";\n\n/**\n * BMAD is NOT a Skillex pack.\n *\n * pjangler used to pin a frozen `packs/bmad/<version>` in the Skillex registry\n * and project it into `.agents/skills/bmad-*` as symlinks. That was a mirror of\n * something `bmad-method` already does natively: `bmad-method install` writes\n * its skills into `.agents/skills/bmad-*` and into each `--tools` root itself,\n * per repo, versioned by `_bmad/_config/manifest.yaml`.\n *\n * Two sources of truth for the same files is a bug waiting for one of them to\n * move, and on 2026-08-18 one did: the registry dropped `packs/bmad`, and every\n * machine without a warm cache lost `pjangler project create`.\n *\n * BMAD is now owned end to end by the external `bmad-method` npm package, and\n * pjangler's BMAD rules are a wrapper around it: install it, keep it current,\n * keep its CLI projections configured. `packs[]` still exists for real Skillex\n * packs; `bmad` is no longer special to it in any way.\n */\n\nexport type RuleStatus = \"pass\" | \"fail\" | \"warn\" | \"skip\";\n\nexport interface AuditFinding {\n id: string;\n title: string;\n status: RuleStatus;\n summary: string;\n details: string[];\n fixable: boolean;\n /**\n * PJAN-84: \"project\" (the repo can fix it, and a failure gates the repo) or\n * \"host\" (this machine's shared state \u2014 reported, never gating). Absent means\n * \"project\".\n */\n scope?: \"project\" | \"host\";\n}\n\nexport interface AuditReport {\n repo: string;\n /** Is the audited PROJECT in parity? Host findings never affect this. */\n ok: boolean;\n /** Is this machine's shared state healthy? Reported separately, never gating. */\n hostOk?: boolean;\n auditedAt: string;\n rules: AuditFinding[];\n}\n\nexport interface MigrationRuleResult {\n id: string;\n title: string;\n status: \"applied\" | \"noop\" | \"blocked\" | \"skipped\" | \"partial\";\n summary: string;\n changedFiles: string[];\n details: string[];\n}\n\nexport interface MigrationReport {\n repo: string;\n dryRun: boolean;\n ok: boolean;\n selectedRules: string[];\n results: MigrationRuleResult[];\n changedFiles: string[];\n}\n\ninterface RoleMeta {\n role: string;\n roleDir: string;\n roleYamlPath: string;\n repo: string;\n agentId: string;\n profileName: string;\n displayName: string;\n purpose: string;\n botHandle: string;\n runtimeRepo: string;\n runtimeOwner: string;\n planeWorkspace: string;\n ticketProviderName: string;\n ticketProviderBoardId: string;\n ticketProviderIdentifier: string;\n bloodbankEnabled: string;\n deploymentSystemd: string;\n serviceStateGateway: string;\n serviceStateHeartbeat: string;\n legacyReconcileEnabled: string;\n legacyReconcileGraceHours: string;\n legacyReconcileAutoReview: string;\n legacyScrumGraceHours: string;\n legacyScrumAutoReview: string;\n}\n\nexport interface Context {\n repoRoot: string;\n dryRun: boolean;\n pjanglerRoot: string;\n homeDir: string;\n /** Exact BMAD package version used by an in-flight fresh-project transaction. */\n bmadVersionPin?: string;\n // PJAN-28: opt-in gate for mapping legacy committed skills into\n // .agents/skills.json. Absent/false => migrate only REPORTS the proposal.\n acceptRegistryMatches?: boolean;\n}\n\nexport interface RecipeOwnedCheck {\n id: string;\n title: string;\n /**\n * PJAN-84: \"host\" for a rule about this MACHINE's shared state, which the\n * audited repository cannot change. Absent means \"project\". See\n * LifecycleScope in src/recipes/types.ts.\n */\n scope?: \"project\" | \"host\";\n audit: (ctx: Context) => AuditFinding;\n migrate: (ctx: Context, finding: AuditFinding) => MigrationRuleResult;\n}\n\n// mise runs each hook `script`/task `run` value through `sh -c`, expanding the\n// `{{config_root}}` tera template first. If the resolved path contains a space\n// (e.g. \".../James Brennan/...\") an UNQUOTED reference word-splits and fails, so\n// every config_root path is wrapped in single quotes. Multiple commands are\n// emitted as an array of `[[hooks.enter]]` tables purely for readability and\n// stable diffs \u2014 mise 2026.7.5 executes the `enter = [ ... ]` array-of-strings\n// form correctly too, so migrating a repo off it is cosmetic, not a fix.\n// PJAN-82: every managed script is handed config_root EXPLICITLY as its\n// SUBJECT, not just as the path it is loaded from.\n//\n// A mise enter hook runs with cwd set to the directory the operator cd'd into,\n// and that is true for a PARENT config's hook too \u2014 measured on mise 2026.8.10.\n// `mise run <task>` does run at config_root, which is why reading the subject\n// from cwd looked correct for years: only the enter-hook path was wrong. The\n// consequence on this machine was that entering 33GOD/pjangler ran 33GOD's copy\n// of provision-packs.py and sync-skills.py against pjangler \u2014 force-rewriting\n// pjangler/.agents/skills.json and planting dangling links in seven sibling\n// repos. config_root locates the file; the argument locates the subject.\nconst LINK_AGENTFILES_SCRIPT = \"'{{config_root}}/.mise/scripts/link-agentfiles.sh' '{{config_root}}'\";\n// PJAN-24/PJAN-57: mise owns only a simple, quoted script invocation. The\n// managed script owns mktemp reservation, path quoting, cleanup traps, and the\n// successful-inject-before-atomic-mv contract without mise interpolating shell\n// locals such as `$temp_file`.\nconst MATERIALIZE_ENV_SCRIPT_REL = \".mise/scripts/materialize-env.sh\";\nconst OP_INJECT_SCRIPT = `'{{config_root}}/${MATERIALIZE_ENV_SCRIPT_REL}'`;\n// PACKS-CONTRACT section 7: `provision-bmad-skills.py` is retired in favour of\n// the generic `provision-packs.py`, and the mise task that ran it is renamed\n// from `skills-provision-bmad` to `skills-provision-packs`. Both legacy names\n// are still recognized so `audit` can report them and `migrate` can remove them.\nconst PROVISION_PACKS_SCRIPT_REL = \".mise/scripts/provision-packs.py\";\nconst LEGACY_PROVISION_SCRIPT_REL = \".mise/scripts/provision-bmad-skills.py\";\nconst SYNC_SKILLS_SCRIPT_REL = \".mise/scripts/sync-skills.py\";\n// PJAN-61: managed mise task names are unified on the COLON namespace form.\n// The dash-era names below are retired. This is not cosmetic \u2014 the 33GOD root\n// had already moved to colons, and the mismatch left `depends` pointing at a\n// task name that no longer existed, so `mise run skills:sync` died with\n// \"task not found\". Only the TASK names change; the `.mise/scripts/*.sh`\n// FILENAMES stay dashed, so never match a task name by bare substring.\nconst LINK_AGENTFILES_TASK = \"link:agentfiles\";\nconst SKILLS_SYNC_TASK = \"skills:sync\";\nconst PROVISION_PACKS_TASK = \"skills:provision:packs\";\nconst LEGACY_PROVISION_TASK = \"skills-provision-bmad\";\n/**\n * Retired dash-era task name -> current colon name. `migrate` renames every\n * occurrence (section header, `task =` dispatch, `depends` entry); `audit`\n * reports them. `skills-provision-bmad` is absent on purpose: its task is\n * deleted outright, not renamed, because its script is retired too.\n */\nconst RETIRED_TASK_RENAMES: ReadonlyArray<readonly [string, string]> = [\n [\"link-agentfiles\", LINK_AGENTFILES_TASK],\n [\"skills-sync\", SKILLS_SYNC_TASK],\n [\"skills-provision-packs\", PROVISION_PACKS_TASK],\n [\"hooks-sync\", \"hooks:sync\"],\n [\"hooks-check\", \"hooks:check\"],\n [\"hooks-uninstall\", \"hooks:uninstall\"],\n [\"hindsight-setup\", \"hindsight:setup\"],\n];\n\n/**\n * TOML section header for a managed task. A bare TOML key may not contain `:`,\n * so every colon-namespaced task MUST be quoted \u2014 `[tasks.\"skills:sync\"]`.\n * Emitting the bare form produces a file mise refuses to parse at all.\n */\nfunction taskHeader(name: string): string {\n return `[tasks.\"${name}\"]`;\n}\n\n/** Matches a task's section header in either the bare or the quoted TOML form. */\nfunction taskHeaderPattern(name: string): RegExp {\n const esc = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`^\\\\[tasks\\\\.(?:\"${esc}\"|${esc})\\\\]$`);\n}\nconst PROVISION_PACKS_SCRIPT =\n `python3 '{{config_root}}/${PROVISION_PACKS_SCRIPT_REL}' --root '{{config_root}}'`;\nconst LEGACY_PROVISION_BMAD_SKILLS_SCRIPT =\n `python3 '{{config_root}}/${LEGACY_PROVISION_SCRIPT_REL}'`;\nconst SYNC_SKILLS_SCRIPT =\n `python3 '{{config_root}}/${SYNC_SKILLS_SCRIPT_REL}' --scope project --root '{{config_root}}'`;\n// PACKS-CONTRACT section 7: the old schemas host 404s. It is accepted on read\n// (so an un-migrated repo still audits) but always rewritten by migrate/init.\nconst SKILLS_SCHEMA_URL = \"https://raw.githubusercontent.com/delorenj/skillex/main/skills.schema.json\";\nconst RETIRED_SKILLS_SCHEMA_URLS = [\n \"https://raw.githubusercontent.com/skillex/schemas/main/skills.schema.json\",\n];\nconst CODEGRAPH_SCRIPT =\n \"[ -f '{{config_root}}/.mise/scripts/codegraph.sh' ] && '{{config_root}}/.mise/scripts/codegraph.sh' || true\";\nconst SKILLS_REGISTRY_URL = \"https://github.com/delorenj/skillex.git\";\n// PJAN-28: legacy committed skills are moved here \u2014 never deleted \u2014 when\n// `migrate skills.project-manifest --accept-registry-matches` maps them into\n// `.agents/skills.json`. It is a SIBLING of `.agents/skills`, so the audit walk\n// (which only reads `.agents/skills`) can never see its own backups and loop.\n// Deliberately NOT added to any managed `.gitignore` block: an entry mapped to\n// `file://.../.agents/skills.bak/<name>` is the manifest's source of truth for\n// that skill, so ignoring it would break every other clone of the repo.\nconst SKILLS_BACKUP_DIRNAME = \"skills.bak\";\n// Directories inside a registry checkout that may hold a skill by bare name.\n// `all-skills/<name>` is the shorthand sync-skills.py expands a bare string\n// manifest entry into, so it is the primary and first-checked location.\nconst SKILLS_REGISTRY_SKILL_DIRS = [\"all-skills\", \"skills\"] as const;\n// PJAN-28 targets legacy NON-BMAD committed skills. Everything under the\n// `bmad-` namespace already has an owner: pinned pack names are validated as\n// symlinks by this same rule, and off-pack `bmad-*` trees (e.g. bmad-build from\n// a newer bmad-method installer writing through the .claude/skills alias) are\n// re-materialized by `bmad.scaffold` on every run. Mapping those into the\n// manifest and backing them up would be undone by the next BMAD install and\n// re-reported forever \u2014 the same drift loop the backup dir exists to avoid.\nconst BMAD_SKILL_NAME_PREFIX = \"bmad-\";\n/**\n * PJAN-82: pack names the contract forbids anyone to declare.\n *\n * PJAN-76 settled that BMAD is owned by `bmad-method install` and is never a\n * Skillex pack \"on either side\"; skillex deleted `packs/bmad` accordingly. But a\n * repo that still declared `packs: [{name: \"bmad\"}]` could not be repaired at\n * all: provisioning the declared packs runs FIRST, the pack resolves nowhere, and\n * the whole skills.project-manifest migration returned `blocked`. docsidian sat\n * on 528 dangling links behind that single dead declaration with no way through.\n *\n * A declaration the contract forbids is dropped, not obeyed \u2014 otherwise the\n * unresolvable thing gets a veto over its own removal.\n */\nconst RETIRED_PACK_NAMES: ReadonlySet<string> = new Set([\"bmad\"]);\n\nfunction retiredPackDeclarations(manifest: Record<string, unknown> | null | undefined): string[] {\n const packs = manifest?.packs;\n if (!Array.isArray(packs)) return [];\n const names: string[] = [];\n for (const entry of packs) {\n const name = typeof entry === \"string\"\n ? entry\n : (entry && typeof entry === \"object\" && typeof (entry as { name?: unknown }).name === \"string\"\n ? (entry as { name: string }).name\n : undefined);\n if (name && RETIRED_PACK_NAMES.has(name)) names.push(name);\n }\n return names;\n}\n\n/** Strip forbidden pack declarations, returning the dropped names. */\nfunction dropRetiredPackDeclarations(manifestPath: string, dryRun: boolean): string[] {\n const raw = safeReadText(manifestPath);\n if (raw === null) return [];\n let parsed: unknown;\n try { parsed = JSON.parse(raw); }\n catch { return []; }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return [];\n const manifest = parsed as Record<string, unknown>;\n const dropped = retiredPackDeclarations(manifest);\n if (!dropped.length) return [];\n manifest.packs = (manifest.packs as unknown[]).filter((entry) => {\n const name = typeof entry === \"string\"\n ? entry\n : (entry && typeof entry === \"object\" && typeof (entry as { name?: unknown }).name === \"string\"\n ? (entry as { name: string }).name\n : undefined);\n return !(name && RETIRED_PACK_NAMES.has(name));\n });\n if (!dryRun) writeText(manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`);\n return dropped;\n}\n// PACKS-CONTRACT section 6b: exactly six supported agent CLIs, project scope.\n// `.augment`, `.hermes`, `.openclaw`, `.kimi`, `.crush` and `.cursor` are\n// RETIRED \u2014 sync-skills.py never writes them again, so their topology is no\n// longer pjangler's to police (and never was pjangler's to delete).\nconst PROJECT_CLI_SKILL_DIRS = [\n \".claude/skills\",\n \".codex/skills\",\n \".gemini/skills\",\n \".copilot/skills\",\n \".opencode/skills\",\n \".kimi-code/skills\",\n] as const;\nconst CANONICAL_CLI_SKILLS_ALIAS = \"../.agents/skills\";\n\nconst HOOKS_COMMENT_HEADER = `# This block will handle the linking of\n# agent files to the main AGENTS.md file.\n#\n# TODO: Ensure this works for all levels of nesting.\n# i.e. All linked agent files MUST be siblings at\n# any given level of nesting.`;\n\n// Canonical managed enter-hook commands, always installed (space-safe).\nconst LINK_AGENTFILES_HOOK_ENTRIES = [\n LINK_AGENTFILES_SCRIPT,\n PROVISION_PACKS_SCRIPT,\n SYNC_SKILLS_SCRIPT,\n];\n\nconst LINK_AGENTFILES_WATCH_TASK_BLOCK = `[[watch_files]]\npatterns = [\"AGENTS.md\"]\ntask = \"${LINK_AGENTFILES_TASK}\"\n\n[[watch_files]]\npatterns = [\".agents/skills.json\"]\ntask = \"${SKILLS_SYNC_TASK}\"\n\n${taskHeader(LINK_AGENTFILES_TASK)}\ndescription = \"Symlink all agent files to AGENTS.md\"\nrun = ${JSON.stringify(LINK_AGENTFILES_SCRIPT)}\n\n${taskHeader(SKILLS_SYNC_TASK)}\ndescription = \"Sync skills from manifest to local CLI dirs\"\ndepends = [\"${PROVISION_PACKS_TASK}\"]\nrun = ${JSON.stringify(SYNC_SKILLS_SCRIPT)}\n\n${taskHeader(PROVISION_PACKS_TASK)}\ndescription = \"Provision every Skillex pack declared in .agents/skills.json\"\nrun = ${JSON.stringify(PROVISION_PACKS_SCRIPT)}`;\n\nconst VERSIONING_BLOCK = `# >>> mise-versioning >>> (managed block \u2014 do not edit by hand; re-run init to update)\n[tasks.\"version\"]\ndescription = \"Print the current version (vX.Y.Z)\"\nrun = \"'{{config_root}}/.mise/scripts/versioning.sh' current\"\n\n[tasks.\"version:bump\"]\ndescription = \"Bump patch version: vX.Y.Z -> vX.Y.(Z+1)\"\nalias = \"version:bump-patch\"\nrun = \"'{{config_root}}/.mise/scripts/versioning.sh' bump patch\"\n\n[tasks.\"version:bump-minor\"]\ndescription = \"Bump minor version: vX.Y.Z -> vX.(Y+1).0\"\nrun = \"'{{config_root}}/.mise/scripts/versioning.sh' bump minor\"\n\n[tasks.\"version:bump-major\"]\ndescription = \"Bump major version: vX.Y.Z -> v(X+1).0.0\"\nrun = \"'{{config_root}}/.mise/scripts/versioning.sh' bump major\"\n\n[tasks.\"version:check\"]\ndescription = \"Verify every versioned file is in parity\"\nrun = \"'{{config_root}}/.mise/scripts/versioning.sh' check\"\n\n[tasks.\"version:sync\"]\ndescription = \"Force every versioned file up to the highest version\"\nrun = \"'{{config_root}}/.mise/scripts/versioning.sh' sync\"\n# <<< mise-versioning <<<`;\n\nfunction resolvePjanglerRoot(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n while (dir !== dirname(dir)) {\n if (existsSync(join(dir, \"package.json\")) && existsSync(join(dir, \"templates\", \"commonproject\", \"copier.yml\"))) {\n return dir;\n }\n dir = dirname(dir);\n }\n throw new Error(\"Unable to resolve pjangler root\");\n}\n\nfunction normalizeNewlines(value: string): string {\n return value.replace(/\\r\\n/g, \"\\n\");\n}\n\nfunction readText(path: string): string {\n return normalizeNewlines(readFileSync(path, \"utf8\"));\n}\n\nfunction safeReadText(path: string): string | null {\n return existsSync(path) ? readText(path) : null;\n}\n\nfunction ensureParent(path: string): void {\n mkdirSync(dirname(path), { recursive: true });\n}\n\nfunction writeText(path: string, content: string): void {\n ensureParent(path);\n writeFileSync(path, content);\n}\n\nfunction tryParseJson(text: string | null): Record<string, unknown> | null {\n if (!text) return null;\n try {\n return JSON.parse(text) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\nfunction slugifyRepoName(name: string): string {\n return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"project\";\n}\n\nfunction titleCaseSlug(slug: string): string {\n return slug\n .split(/[-_]/g)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction isSymlinkTo(path: string, expectedTarget: string): boolean {\n if (!existsSync(path)) return false;\n const stat = lstatSync(path);\n if (!stat.isSymbolicLink()) return false;\n try {\n const actual = readlinkSync(path);\n return actual === expectedTarget;\n } catch {\n return false;\n }\n}\n\nfunction readSymlinkTarget(path: string): string | null {\n if (!existsSync(path)) return null;\n try {\n return readlinkSync(path);\n } catch {\n return null;\n }\n}\n\nfunction ensureSymlink(path: string, target: string, dryRun: boolean): { changed: boolean; blocked?: string } {\n if (existsSync(path)) {\n const stat = lstatSync(path);\n if (stat.isSymbolicLink()) {\n const current = readSymlinkTarget(path);\n if (current === target) return { changed: false };\n if (!dryRun) {\n unlinkSync(path);\n symlinkSync(target, path);\n }\n return { changed: true };\n }\n return { changed: false, blocked: `${relative(process.cwd(), path) || path} exists and is not a symlink` };\n }\n if (!dryRun) symlinkSync(target, path);\n return { changed: true };\n}\n\nfunction bootstrapAgentsFile(repoRoot: string, dryRun: boolean): { changedFiles: string[]; details: string[]; blocked?: string } {\n const agentsPath = join(repoRoot, \"AGENTS.md\");\n if (existsSync(agentsPath)) return { changedFiles: [], details: [] };\n\n for (const file of [\"CLAUDE.md\", \"GEMINI.md\"]) {\n const source = join(repoRoot, file);\n if (!existsSync(source)) continue;\n const stat = lstatSync(source);\n if (stat.isSymbolicLink()) continue;\n if (stat.isFile()) {\n if (!dryRun) renameSync(source, agentsPath);\n return { changedFiles: [agentsPath], details: [`Moved ${file} to AGENTS.md before wiring agent-file symlinks`] };\n }\n return { changedFiles: [], details: [], blocked: `${file} exists but is not a regular file; cannot promote to AGENTS.md` };\n }\n\n const readmePath = join(repoRoot, \"README.md\");\n if (existsSync(readmePath)) {\n const stat = lstatSync(readmePath);\n if (!stat.isFile()) return { changedFiles: [], details: [], blocked: \"README.md exists but is not a regular file; cannot copy to AGENTS.md\" };\n if (!dryRun) copyFileSync(readmePath, agentsPath);\n return { changedFiles: [agentsPath], details: [\"Copied README.md to AGENTS.md before wiring agent-file symlinks\"] };\n }\n\n return { changedFiles: [], details: [], blocked: \"AGENTS.md missing and no CLAUDE.md, GEMINI.md, or README.md source exists\" };\n}\n\nfunction yamlGet(text: string, keyPath: string): string {\n const parts = keyPath.split(\".\");\n const lines = text.split(\"\\n\");\n let start = 0;\n let indent = 0;\n for (let idx = 0; idx < parts.length; idx += 1) {\n const key = parts[idx]!;\n let found = false;\n for (let i = start; i < lines.length; i += 1) {\n const line = lines[i]!;\n if (!line.trim() || line.trim().startsWith(\"#\")) continue;\n const match = line.match(/^(\\s*)([^:#]+):\\s*(.*)$/);\n if (!match) continue;\n const currentIndent = match[1]!.length;\n const currentKey = match[2]!.trim();\n const rest = match[3]!.trim();\n if (idx > 0 && currentIndent < indent) break;\n if (currentIndent !== indent || currentKey !== key) continue;\n found = true;\n if (idx === parts.length - 1) {\n return rest.replace(/^['\"]|['\"]$/g, \"\").trim();\n }\n start = i + 1;\n indent = currentIndent + 2;\n break;\n }\n if (!found) return \"\";\n }\n return \"\";\n}\n\nfunction discoverRoles(repoRoot: string): RoleMeta[] {\n const rolesDir = join(repoRoot, \"agents\", \"hermes\");\n if (!existsSync(rolesDir)) return [];\n return readdirSync(rolesDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => {\n const roleDir = join(rolesDir, entry.name);\n const roleYamlPath = join(roleDir, \"role.yaml\");\n if (!existsSync(roleYamlPath)) return null;\n const text = readText(roleYamlPath);\n const runtimeRepoRaw = yamlGet(text, \"runtime.github_repo\");\n return {\n role: yamlGet(text, \"role\") || entry.name,\n roleDir,\n roleYamlPath,\n repo: yamlGet(text, \"repo\"),\n agentId: yamlGet(text, \"agent_id\"),\n profileName: yamlGet(text, \"profile\") || yamlGet(text, \"agent_id\"),\n displayName: yamlGet(text, \"display_name\"),\n purpose: yamlGet(text, \"purpose\"),\n botHandle: yamlGet(text, \"telegram.bot_username\"),\n runtimeRepo: runtimeRepoRaw.includes(\"/\") ? runtimeRepoRaw.split(\"/\").slice(-1)[0] ?? runtimeRepoRaw : runtimeRepoRaw,\n runtimeOwner: yamlGet(text, \"runtime.github_owner\"),\n planeWorkspace: yamlGet(text, \"ticket_provider.workspace\") || yamlGet(text, \"plane.workspace\"),\n ticketProviderName: yamlGet(text, \"ticket_provider.name\"),\n ticketProviderBoardId: yamlGet(text, \"ticket_provider.board_id\"),\n ticketProviderIdentifier: yamlGet(text, \"plane.identifier\"),\n bloodbankEnabled: yamlGet(text, \"bloodbank.enabled\"),\n deploymentSystemd: yamlGet(text, \"deployment.systemd\"),\n serviceStateGateway: yamlGet(text, \"service_state.gateway\"),\n serviceStateHeartbeat: yamlGet(text, \"service_state.heartbeat\"),\n legacyReconcileEnabled: yamlGet(text, \"reconcile.enabled\"),\n legacyReconcileGraceHours: yamlGet(text, \"reconcile.grace_hours\"),\n legacyReconcileAutoReview: yamlGet(text, \"reconcile.auto_review\"),\n legacyScrumGraceHours: yamlGet(text, \"scrum_master.grace_hours\"),\n legacyScrumAutoReview: yamlGet(text, \"scrum_master.auto_review\"),\n } satisfies RoleMeta;\n })\n .filter((value): value is RoleMeta => Boolean(value));\n}\n\nfunction registryPath(homeDir: string): string {\n return join(homeDir, \".hermes\", \"agents-registry.yaml\");\n}\n\nfunction fleetEnvPath(homeDir: string): string {\n return join(homeDir, \".hermes\", \"fleet.env\");\n}\n\n// Retired per-agent command-ingress contract. The fleet-shared Bloodbank\n// gateway owns command routing (registry `gateways.bloodbank`, routed by\n// data.target_agent_id); per-agent consumer units and checkpoint timers are\n// legacy. This constant is the ONLY place the legacy key names may appear \u2014\n// tests/fleet-shared-bloodbank-regressions.mjs enforces that scoping so the\n// legacy contract can be detected and cleaned but never provisioned again.\nconst LEGACY_SYSTEMD_KEYS = [\"consumer_unit\", \"checkpoint_timer\"] as const;\n\nfunction legacyConsumerUnitPath(homeDir: string, agentId: string): string {\n return join(homeDir, \".config\", \"systemd\", \"user\", `hermes-${agentId}-consumer.service`);\n}\n\nfunction systemctlUser(args: string[]): { ok: boolean; stdout: string; stderr: string } {\n const result = spawnSync(\"systemctl\", [\"--user\", ...args], { encoding: \"utf8\" });\n return {\n ok: result.status === 0,\n stdout: result.stdout.trim(),\n stderr: result.stderr.trim(),\n };\n}\n\nfunction relativeRepo(repoRoot: string, path: string): string {\n return relative(repoRoot, path) || \".\";\n}\n\nfunction templateScript(ctx: Context, name: string): string | undefined {\n // Shipped in the npm tarball via the package.json files allowlist (PJAN-3);\n // soft-return so a broken install blocks one finding instead of the run.\n const source = join(ctx.pjanglerRoot, \".mise\", \"scripts\", name);\n return existsSync(source) ? readText(source) : undefined;\n}\n\nfunction templateVersioningScript(ctx: Context): string | undefined {\n return templateScript(ctx, \"versioning.sh\");\n}\n\nfunction templateLinkAgentfilesScript(ctx: Context): string | undefined {\n // PJAN-82: read the CommonProject template, exactly like\n // templateMaterializeEnvScript does. This used to read pjangler's OWN\n // .mise/scripts/link-agentfiles.sh (shipped through the package.json files\n // allowlist), which made two different sources of truth for two scripts\n // sitting in the same directory. Hardening the template copy therefore\n // propagated to nobody: `pj migrate mise.config-root` compared every repo\n // against pjangler's stale copy and reported \"No changes required\" while the\n // cwd-relative version that destroys a hand-written CLAUDE.md stayed\n // installed everywhere, including in pjangler itself.\n const source = join(ctx.pjanglerRoot, \"templates\", \"commonproject\", \"template\", \".mise\", \"scripts\", \"link-agentfiles.sh\");\n return existsSync(source) ? readText(source) : templateScript(ctx, \"link-agentfiles.sh\");\n}\n\nfunction templateMaterializeEnvScript(ctx: Context): string | undefined {\n const source = join(ctx.pjanglerRoot, \"templates\", \"commonproject\", \"template\", MATERIALIZE_ENV_SCRIPT_REL);\n return existsSync(source) ? readText(source) : undefined;\n}\n\n/**\n * Resolve whether a generated mise.toml should wire in the project-scoped\n * agent-hooks + skill fan-out layer. Mirrors pjangler's `resolveAgentHooksLayer`\n * (src/project/index.ts): an explicit PJ_AGENT_HOOKS_LAYER override wins; a repo\n * that already carries the hook tree keeps it; otherwise the layer is skipped\n * when a GLOBAL install (~/.agents/hooks) is present, so sync never re-injects the\n * same hooks into the caller's shared per-user CLI configs.\n */\nfunction resolveAgentHooksLayer(ctx: Context): boolean {\n const override = process.env.PJ_AGENT_HOOKS_LAYER;\n if (override === \"0\" || override === \"false\") return false;\n if (override === \"1\" || override === \"true\") return true;\n if (existsSync(join(ctx.repoRoot, \".agents\", \"hooks\", \"sync.py\"))) return true;\n return !existsSync(join(ctx.homeDir, \".agents\", \"hooks\"));\n}\n\n/**\n * Evaluate the flat `{% if agent_hooks_layer %}...{% endif %}` conditionals in\n * mise.toml.jinja. Every Jinja statement tag occupies its own line, so we\n * evaluate line-by-line: statement lines are consumed and a block's body is\n * dropped when its condition is falsy. Unknown variables are treated as falsy so\n * an unevaluated (invalid-TOML) Jinja tag can never leak into a generated\n * mise.toml \u2014 the root cause of the `TOML parse error ... {%- if\n * agent_hooks_layer %}` crash when the naive renderer only stripped {% raw %}.\n */\nfunction evaluateMiseConditionals(template: string, agentHooksLayer: boolean): string {\n const out: string[] = [];\n let depth = 0;\n let skipDepth = 0;\n for (const line of template.split(\"\\n\")) {\n const stmt = line.trim();\n const ifMatch = /^\\{%-?\\s*if\\s+(\\w+)\\s*-?%\\}$/.exec(stmt);\n if (ifMatch) {\n depth += 1;\n const truthy = ifMatch[1] === \"agent_hooks_layer\" ? agentHooksLayer : false;\n if (skipDepth === 0 && !truthy) skipDepth = depth;\n continue;\n }\n if (/^\\{%-?\\s*endif\\s*-?%\\}$/.test(stmt)) {\n if (skipDepth === depth) skipDepth = 0;\n depth = Math.max(0, depth - 1);\n continue;\n }\n if (skipDepth === 0) out.push(line);\n }\n return out.join(\"\\n\");\n}\n\nfunction renderGeneratedProjectMiseToml(ctx: Context, template: string): string {\n const project = readProjectJson(ctx);\n const projectName = String(project?.project_name ?? basename(ctx.repoRoot) ?? \"project\");\n return evaluateMiseConditionals(template, resolveAgentHooksLayer(ctx))\n .replace(/\\{%\\s*raw\\s*%\\}([\\s\\S]*?)\\{%\\s*endraw\\s*%\\}/g, \"$1\")\n .replace(/\\{\\{\\s*project_name\\s*\\}\\}/g, projectName);\n}\n\n/**\n * Materialize `mise.toml` from the generated-project template when the repo has\n * none. Returns the resulting content, or `null` when there is nothing to\n * initialize from.\n *\n * PJAN-75: the content is RETURNED rather than left for the caller to read back\n * off disk. A dry run plans the write without performing it, so a caller that\n * re-read the path crashed with ENOENT -- which is what\n * `migrate skills.project-manifest --dry-run` did on every repo without a\n * mise.toml, surfacing as the useless \"migrate threw: ENOENT\".\n */\nfunction ensureMiseTomlFromTemplate(ctx: Context, changedFiles: string[]): string | null {\n const targetPath = join(ctx.repoRoot, \"mise.toml\");\n if (existsSync(targetPath)) return null;\n const sourcePath = join(ctx.pjanglerRoot, \"templates\", \"commonproject\", \"template\", \"mise.toml.jinja\");\n if (!existsSync(sourcePath)) return null;\n const rendered = renderGeneratedProjectMiseToml(ctx, readText(sourcePath));\n changedFiles.push(targetPath);\n if (!ctx.dryRun) writeText(targetPath, rendered);\n return rendered;\n}\n\nfunction templateCommonProjectText(ctx: Context, rel: string): string | undefined {\n const path = join(ctx.pjanglerRoot, \"templates\", \"commonproject\", \"template\", rel);\n return existsSync(path) ? readText(path) : undefined;\n}\n\ninterface SkillManifestEntry {\n name: string;\n source: string;\n}\n\nfunction validateSkillName(name: string): string {\n if (!name || name === \".\" || name === \"..\" || name.includes(\"/\") || name.includes(\"\\\\\") || basename(name) !== name) {\n throw new Error(`Unsafe skill name: ${JSON.stringify(name)}`);\n }\n return name;\n}\n\nfunction lstatIfPresent(path: string): ReturnType<typeof lstatSync> | undefined {\n try {\n return lstatSync(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw error;\n }\n}\n\nfunction isContainedBy(root: string, target: string): boolean {\n const rel = relative(root, target);\n return rel === \"\" || (rel !== \"..\" && !rel.startsWith(\"../\") && !rel.startsWith(\"..\\\\\"));\n}\n\nfunction prepareSafeProjectSkillsDirs(ctx: Context): { agentsDir: string; skillsDir: string } {\n const projectRoot = realpathSync(ctx.repoRoot);\n const agentsDir = join(projectRoot, \".agents\");\n const skillsDir = join(agentsDir, \"skills\");\n for (const path of [agentsDir, skillsDir]) {\n if (!isContainedBy(projectRoot, path)) throw new Error(`Project skills path escapes repository: ${path}`);\n const stat = lstatIfPresent(path);\n if (stat?.isSymbolicLink()) throw new Error(`Refusing symlinked project skills directory: ${path}`);\n if (stat && !stat.isDirectory()) throw new Error(`Project skills path is not a directory: ${path}`);\n }\n if (!ctx.dryRun) {\n if (!existsSync(agentsDir)) mkdirSync(agentsDir, { recursive: false });\n if (!existsSync(skillsDir)) mkdirSync(skillsDir, { recursive: false });\n for (const path of [agentsDir, skillsDir]) {\n if (lstatSync(path).isSymbolicLink() || !lstatSync(path).isDirectory()) {\n throw new Error(`Unsafe project skills directory after creation: ${path}`);\n }\n if (!isContainedBy(projectRoot, realpathSync(path))) {\n throw new Error(`Resolved project skills directory escapes repository: ${path}`);\n }\n }\n }\n return { agentsDir, skillsDir };\n}\n\nfunction projectSkillTopologyIssues(repoRoot: string): string[] {\n const issues: string[] = [];\n let projectRoot: string;\n try {\n projectRoot = realpathSync(repoRoot);\n } catch (error) {\n return [`Project root is not a readable real directory: ${error instanceof Error ? error.message : String(error)}`];\n }\n const managedSkills = join(projectRoot, \".agents\", \"skills\");\n\n for (const rel of PROJECT_CLI_SKILL_DIRS) {\n const cliDir = join(projectRoot, rel);\n const parent = dirname(cliDir);\n const parentStat = lstatIfPresent(parent);\n if (!parentStat) continue;\n if (parentStat.isSymbolicLink() || !parentStat.isDirectory()) {\n issues.push(`${rel} has an unsafe symlinked/non-directory parent`);\n continue;\n }\n if (!isContainedBy(projectRoot, realOrSelf(parent))) {\n issues.push(`${rel} parent resolves outside the project`);\n continue;\n }\n\n const stat = lstatIfPresent(cliDir);\n if (!stat) continue;\n if (stat.isSymbolicLink()) {\n let rawTarget = \"\";\n try {\n rawTarget = readlinkSync(cliDir);\n } catch {\n issues.push(`${rel} is an unreadable skills directory symlink`);\n continue;\n }\n if (rawTarget !== CANONICAL_CLI_SKILLS_ALIAS) {\n issues.push(`${rel} is an unsupported skills directory symlink`);\n continue;\n }\n const managedStat = lstatIfPresent(managedSkills);\n if (!managedStat || managedStat.isSymbolicLink() || !managedStat.isDirectory()) {\n issues.push(`${rel} canonical alias target .agents/skills is missing or unsafe`);\n continue;\n }\n try {\n if (realpathSync(cliDir) !== realpathSync(managedSkills)) {\n issues.push(`${rel} canonical alias resolves outside .agents/skills`);\n }\n } catch {\n issues.push(`${rel} canonical alias is broken`);\n }\n continue;\n }\n if (!stat.isDirectory()) {\n issues.push(`${rel} is not a directory`);\n continue;\n }\n if (!isContainedBy(projectRoot, realOrSelf(cliDir))) {\n issues.push(`${rel} resolves outside the project`);\n }\n }\n return issues;\n}\n\n// ---------------------------------------------------------------------------\n// Skillex packs (PACKS-CONTRACT sections 2, 3, 5 and 6)\n//\n// A repo declares packs in `.agents/skills.json` `packs[]`. Their members are\n// projected into `.agents/skills/<name>` as symlinks and are NOT expanded into\n// `skills[]`. Nothing is pinned implicitly: a repo that declares no packs gets\n// no pack projections.\n// ---------------------------------------------------------------------------\n\n/** Per-pack root override, e.g. `PJ_PACK_ROOT_HERMES_BASE=/tmp/pack`. */\nfunction packRootOverride(name: string): string | undefined {\n const generic = process.env[`PJ_PACK_ROOT_${name.toUpperCase().replace(/[^A-Z0-9]/g, \"_\")}`]?.trim();\n return generic ? resolve(generic) : undefined;\n}\n\n/**\n * The projection target for one pack member.\n *\n * Contract section 3b makes `<root>/<name>` WRONG for a flattened pack, so this\n * is the only place a member path may come from. Deriving it from the name\n * again anywhere else is exactly how the two engines would drift.\n */\nfunction packMemberPath(pack: ValidatedPack, name: string): string {\n const target = pack.memberPaths.get(validateSkillName(name));\n if (!target) throw new Error(`Pack ${pack.name} has no resolved path for member ${JSON.stringify(name)}`);\n return target;\n}\n\n/** Stable, order-sensitive identity of a pack's projection, for revalidation. */\nfunction packProjectionSignature(pack: ValidatedPack): string {\n return JSON.stringify(pack.members.map((name) => [name, pack.memberPaths.get(name) ?? null]));\n}\n\n/**\n * The one normalization that turns a registry URL into its registry-cache\n * directory name.\n *\n * This is a WIRE FORMAT, not an implementation detail: three independent\n * surfaces address the same directory on the same machine and must compute\n * byte-identical names, or one manifest resolves to two different checkouts \u2014\n * and one of them may be a stale, unsealed clone that gets zero integrity\n * checking. The other two surfaces are:\n *\n * - `sync-skills.py` -> `registry_cache_dir()`:\n * `re.sub(r\"[^a-zA-Z0-9]\", \"_\", registry_url)`\n * - skillex `paths.py` -> `sanitize_registry_url()`:\n * `re.sub(r\"[^a-zA-Z0-9]\", \"_\", url)`\n *\n * `sync-skills.py` is the only surface allowed to CLONE, so it owns the name on\n * disk; pjangler and skillex are read-only consumers and follow it. Every\n * non-alphanumeric byte becomes `_`, so the result is always exactly one safe\n * path component \u2014 no separator, no `.`, no `..`.\n *\n * Do not \"improve\" this here alone. `tests/registry-cache-parity-regressions`\n * fails the build if the three surfaces disagree.\n */\nexport function registryCacheDirName(registryUrl: string): string {\n const cacheName = registryUrl.replace(/[^a-zA-Z0-9]/g, \"_\");\n if (!cacheName) {\n throw new Error(`Registry URL has no usable cache directory name: ${JSON.stringify(registryUrl)}`);\n }\n return cacheName;\n}\n\n/**\n * Registry checkout roots for pack resolution, in contract order.\n *\n * An audit must NEVER clone or fetch, so an absent checkout means \"unavailable\",\n * not \"go get it\". `sync-skills.py` is the only thing allowed to clone.\n */\nfunction packRegistryRoots(ctx: Context, registryUrl: string): string[] {\n const explicit = process.env.PJ_SKILLS_REGISTRY_ROOT?.trim();\n if (explicit) return [resolve(explicit)];\n const cacheName = registryCacheDirName(registryUrl);\n return [\n join(ctx.homeDir, \".agents\", \".cache\", \"registries\", cacheName),\n join(ctx.homeDir, \"code\", \"skillex\"),\n ];\n}\n\n/**\n * THE pack root resolver (contract section 2).\n *\n * Every pack \u2014 declared in `packs[]` or supplied by pjangler itself, like the\n * implicit BMAD pin \u2014 walks this one ladder, so a given pack name resolves to a\n * single root per process. Two ladders would mean `bmad@X` could mean the sync\n * cache when declared and the developer checkout when implicit, which silently\n * breaks every identity comparison built on the root (ownership, redundancy\n * pruning, projection targets).\n */\nfunction resolvePackRoot(ctx: Context, entry: PackManifestEntry): { root: string; description: string } {\n const override = packRootOverride(entry.name);\n if (override) {\n assertRealDirectory(override, `Pack ${entry.name} root`);\n return { root: override, description: \"env override\" };\n }\n\n if (entry.source) {\n if (entry.source.startsWith(\"file:\")) {\n let local: string;\n try {\n local = resolve(fileURLToPath(entry.source));\n } catch (error) {\n throw new Error(`Pack ${entry.name} source is not a usable file URI: ${entry.source}`);\n }\n assertRealDirectory(local, `Pack ${entry.name} root`);\n return { root: local, description: entry.source };\n }\n // git/https packs live in the sync engine's clone cache. Parity never clones.\n const cached = join(ctx.homeDir, \".agents\", \".cache\", \"skills\", validatePathComponent(entry.name, \"Pack name\"));\n assertRealDirectory(cached, `Pack ${entry.name} clone cache`);\n return { root: cached, description: entry.source };\n }\n\n const registryUrl = entry.registry ?? SKILLS_REGISTRY_URL;\n const matches: RegistryPackMatch[] = [];\n let firstUnavailable: PackUnavailableError | undefined;\n\n for (const candidate of packRegistryRoots(ctx, registryUrl)) {\n const stat = lstatIfPresent(candidate);\n if (!stat || !(stat.isDirectory() || (stat.isSymbolicLink() && existsSync(candidate)))) continue;\n try {\n matches.push(resolvePackRootInRegistry(realpathSync(candidate), entry));\n } catch (error) {\n // \"This checkout does not carry the pack\" is precisely what an ordered\n // candidate list is FOR \u2014 keep walking. Anything else (a symlinked path\n // component, an escape, a `pack.toml` that is not a regular file) is\n // hostile rather than absent, and must never be masked by silently\n // falling through to a different checkout.\n if (!(error instanceof PackUnavailableError)) throw error;\n firstUnavailable ??= error;\n }\n }\n\n if (!matches.length) {\n throw firstUnavailable ?? new PackUnavailableError(`No registry checkout available for ${registryUrl}`);\n }\n // Contract order already decided `matches`; attestation only promotes within it.\n const chosen = matches.find((match) => match.attested) ?? matches[0]!;\n return { root: chosen.root, description: `${registryUrl}:${chosen.relativePath}` };\n}\n\ninterface RegistryPackMatch {\n root: string;\n relativePath: string;\n /** The root carries a `pack.toml` that positively identifies this entry. */\n attested: boolean;\n}\n\n/**\n * Does this pack root carry a `pack.toml` that positively attests `entry`?\n *\n * Contract section 3 makes `pack.toml` the AUTHORITATIVE identity and inventory\n * of a pack; a bare `packs/<name>/<version>/` directory is an unattested claim\n * resting on nothing but a directory name that anyone can create. Several\n * checkouts routinely carry the same `packs/<name>/<version>/` path while only\n * one of them holds the RENDERED pack \u2014 that is the NORMAL state while a pack is\n * being cut, because the sync cache is a clone of what has been *pushed*.\n *\n * Ranking attested above unattested is what stops `[policy] sealed = true` from\n * being silently downgraded to \"unsealed, structural checks only\" by whichever\n * checkout happens to sort first. It can only ever TIGHTEN: contract order still\n * breaks every tie, so a sealed pack in a higher-priority checkout always wins,\n * and a lower-priority checkout can never demote one (unattested is strictly the\n * lower rank). A manifest `sealed: true` is likewise unaffected \u2014 it is enforced\n * against whichever root wins, and an unsealable root simply fails.\n */\nfunction packRootAttests(root: string, entry: PackManifestEntry): boolean {\n // Throws (does NOT return false) when pack.toml exists but is a symlink, is\n // not a regular file, or does not parse \u2014 those are hard errors everywhere\n // else and must not be downgraded into \"just not attested\".\n const metadata = readPackMetadata(root);\n if (!metadata) return false;\n if (metadata.name !== entry.name) {\n throw new Error(\n `Pack ${entry.name} pack.toml declares name ${JSON.stringify(metadata.name)}`\n );\n }\n if (entry.version && metadata.version !== entry.version) {\n throw new Error(\n `Pack ${entry.name} pack.toml declares version ${JSON.stringify(metadata.version)}, manifest pins ${JSON.stringify(entry.version)}`\n );\n }\n return true;\n}\n\n/**\n * Resolve `entry` inside ONE registry checkout (contract section 2 step 2).\n *\n * Throws `PackUnavailableError` when this checkout simply does not carry the\n * pack, and a hard error for anything unsafe. Every guard runs against the root\n * that is actually returned.\n */\nfunction resolvePackRootInRegistry(registryRoot: string, entry: PackManifestEntry): RegistryPackMatch {\n let relativePath: string;\n if (entry.registryPath) {\n relativePath = safeRelativePath(entry.registryPath, `pack ${entry.name} registry_path`);\n } else {\n relativePath = `packs/${entry.name}`;\n const packDir = join(registryRoot, relativePath);\n assertNoSymlinkComponents(registryRoot, relativePath);\n assertRealDirectory(packDir, `Pack ${entry.name} directory`);\n if (entry.version) {\n relativePath = `${relativePath}/${entry.version}`;\n } else if (!isRegularFile(join(packDir, \"pack.toml\"))) {\n // The ONLY implicit choice in the contract: highest version directory.\n const selected = selectPackVersion(packDir);\n if (selected !== null) relativePath = `${relativePath}/${selected}`;\n }\n }\n\n assertNoSymlinkComponents(registryRoot, relativePath);\n const root = join(registryRoot, relativePath);\n assertRealDirectory(root, `Pack ${entry.name} root`);\n return { root, relativePath, attested: packRootAttests(root, entry) };\n}\n\ninterface ResolvedPackPlanEntry {\n entry: PackManifestEntry;\n root: string;\n pack: ValidatedPack;\n /** `packs/<name>` when the pack lives under a version directory. */\n familyRoot?: string;\n}\n\ninterface PackPlan {\n /**\n * Pack skills recorded in `skills[]`. Always empty now that nothing is\n * pinned implicitly \u2014 declared packs project into `.agents/skills` and are\n * deliberately NOT expanded into `skills[]` (PACKS-CONTRACT section 3).\n * Kept so the manifest writer keeps one shape for both.\n */\n manifestSkills: SkillManifestEntry[];\n /** Every projection to materialize in `.agents/skills`: name -> target dir. */\n projections: Map<string, string>;\n /** Roots that own a `skills[]` entry or a `.agents/skills` symlink. */\n ownershipRoots: string[];\n resolved: ResolvedPackPlanEntry[];\n /** Declared packs that resolved and validated (used for redundancy checks). */\n declared: ResolvedPackPlanEntry[];\n errors: string[];\n /** Optional packs that were unavailable and skipped (contract section 1). */\n warnings: string[];\n /**\n * Advisories from a pack that resolved fine \u2014 today, section 3b's \"this\n * container projects nothing\" and \"this container child is a symlink\". Kept\n * apart from `warnings` because those two mean different things to the audit\n * summary, and because a pack advisory must not read as a skipped pack.\n */\n packWarnings: string[];\n}\n\nfunction manifestPackEntries(manifest: Record<string, unknown> | null | undefined): {\n entries: PackManifestEntry[];\n errors: string[];\n} {\n const raw = manifest?.packs;\n if (raw === undefined || raw === null) return { entries: [], errors: [] };\n if (!Array.isArray(raw)) return { entries: [], errors: [\".agents/skills.json packs must be an array\"] };\n const entries: PackManifestEntry[] = [];\n const errors: string[] = [];\n for (const item of raw) {\n try {\n entries.push(normalizePackEntry(item));\n } catch (error) {\n errors.push(`.agents/skills.json packs[] entry is invalid: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return { entries, errors };\n}\n\n/**\n * Resolve and validate every pack this repo projects.\n *\n * Nothing here mutates anything: a plan is built (and every integrity failure\n * collected) BEFORE the caller is allowed to touch the project, which is what\n * keeps \"one unsafe or broken pack produces zero mutation\" true.\n */\nfunction buildPackPlan(ctx: Context, manifest: Record<string, unknown> | null | undefined): PackPlan {\n const plan: PackPlan = {\n manifestSkills: [],\n projections: new Map(),\n ownershipRoots: [],\n resolved: [],\n declared: [],\n errors: [],\n warnings: [],\n packWarnings: [],\n };\n\n const { entries, errors } = manifestPackEntries(manifest);\n plan.errors.push(...errors);\n // Declared packs, in array order \u2014 a later pack wins a name collision.\n for (const entry of entries) {\n try {\n const { root } = resolvePackRoot(ctx, entry);\n const pack = validatePack(root, entry);\n const familyRoot = basename(dirname(root)) === entry.name ? dirname(root) : undefined;\n const resolved: ResolvedPackPlanEntry = { entry, root, pack, familyRoot };\n plan.resolved.push(resolved);\n plan.declared.push(resolved);\n plan.ownershipRoots.push(root);\n if (familyRoot) plan.ownershipRoots.push(familyRoot);\n plan.packWarnings.push(...pack.warnings);\n for (const name of pack.members) {\n plan.projections.set(name, packMemberPath(pack, name));\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (entry.optional && error instanceof PackUnavailableError) {\n plan.warnings.push(`Optional pack ${entry.name} is unavailable and was skipped: ${message}`);\n } else {\n plan.errors.push(`Skillex pack ${entry.name} could not be resolved: ${message}`);\n }\n }\n }\n\n // PACKS-CONTRACT section 5: an explicit `skills[]` entry ALWAYS overrides a\n // pack member of the same name. Only entries that survive section 6 pruning\n // count \u2014 a redundant entry pointing INTO the pack is not an override, and the\n // implicit BMAD expansion is pjangler's own output, not a user override.\n if (plan.declared.length) {\n const managedNames = new Set(plan.manifestSkills.map((entry) => entry.name));\n for (const entry of Array.isArray(manifest?.skills) ? manifest.skills : []) {\n const name = skillManifestEntryName(entry);\n if (!name || !plan.projections.has(name)) continue;\n if (managedNames.has(name) || isRedundantDeclaredPackEntry(entry, plan)) continue;\n plan.projections.delete(name);\n }\n }\n\n return plan;\n}\n\n/**\n * Re-validate every pack the plan projected.\n *\n * Called at the mutation boundary so a pack tampered with between preflight and\n * apply is caught, and the transaction rolled back.\n */\nfunction assertPackPlanUnchanged(plan: PackPlan): void {\n for (const item of plan.resolved) {\n const again = validatePack(item.root, item.entry);\n // Names AND paths: under section 3b a member can move between containers\n // without its name changing, which would silently repoint a live symlink.\n if (packProjectionSignature(again) !== packProjectionSignature(item.pack)) {\n throw new Error(`Pack ${item.entry.name} inventory changed after preflight`);\n }\n }\n}\n\nfunction skillManifestEntryName(entry: unknown): string | undefined {\n if (typeof entry === \"string\") return entry;\n if (!entry || typeof entry !== \"object\") return undefined;\n const name = (entry as Record<string, unknown>).name;\n return typeof name === \"string\" ? name : undefined;\n}\n\nfunction manifestEntrySourcePath(entry: unknown): string | undefined {\n if (!entry || typeof entry !== \"object\") return undefined;\n const source = (entry as Record<string, unknown>).source;\n if (typeof source !== \"string\" || !source.startsWith(\"file:\")) return undefined;\n try {\n return resolve(fileURLToPath(source));\n } catch {\n return undefined;\n }\n}\n\n/**\n * A `skills[]` entry left behind by the retired Skillex `bmad` pin.\n *\n * Deliberately narrow on BOTH axes. The name must be in the `bmad-*` namespace\n * the installer owns, AND the source must point into a `packs/bmad/` tree \u2014\n * which is the shape pjangler itself used to write and the only shape that is\n * unambiguously stale, since the registry no longer carries that pack at all.\n *\n * Matching on the name alone would evict a skill the user wrote and keeps in\n * their own repo just because they named it `bmad-something`. That entry is\n * theirs, it resolves, and nothing else claims the path.\n */\nfunction isRetiredBmadPackEntry(entry: unknown): boolean {\n const name = skillManifestEntryName(entry);\n if (!name || !name.startsWith(BMAD_SKILL_NAME_PREFIX)) return false;\n const source = manifestEntrySourcePath(entry);\n return Boolean(source && /(^|\\/)packs\\/bmad\\//.test(source));\n}\n\nfunction isPackManagedManifestEntry(entry: unknown, expectedNames: Set<string>, packRoots: string[]): boolean {\n const name = skillManifestEntryName(entry);\n if (!name) return false;\n if (expectedNames.has(name)) return true;\n const sourcePath = manifestEntrySourcePath(entry);\n if (!sourcePath) return false;\n return basename(sourcePath) === name && packRoots.some((root) => isContainedBy(root, sourcePath));\n}\n\n/**\n * PACKS-CONTRACT section 6: declaring a pack REPLACES hand-expanded per-skill\n * entries for that pack's members.\n *\n * Deliberately narrow. An entry only counts as redundant when its own resolved\n * source lands inside the pack (or, for a declared member name, inside any\n * version of the same pack). An entry pointing anywhere else \u2014 a local tree, a\n * different registry, a customized copy \u2014 is the user's and is never removed.\n *\n * The family-root arm matches `inventoryNames` \u2014 under section 3b those are the\n * FLATTENED names, because that is what the pack PROVIDES and clause (b) asks\n * what a pack provides. The container names it was declared with are an\n * implementation detail of the pack's on-disk layout, and no `skills[]` entry is\n * ever named after one, so they deliberately do NOT match. Clause (a) is\n * unaffected: a leaf at `<root>/apple/apple-notes` is still contained by\n * `<root>`. With flatten off, `inventoryNames` IS the declared list, so nothing\n * about a pre-existing pack changes.\n */\nfunction isRedundantDeclaredPackEntry(entry: unknown, plan: PackPlan): boolean {\n const name = skillManifestEntryName(entry);\n if (!name) return false;\n const sourcePath = manifestEntrySourcePath(entry);\n if (!sourcePath) return false;\n for (const declared of plan.declared) {\n if (isContainedBy(declared.pack.root, sourcePath)) return true;\n if (\n declared.familyRoot &&\n declared.pack.inventoryNames.includes(name) &&\n isContainedBy(declared.familyRoot, sourcePath)\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction canonicalSkillsManifest(\n ctx: Context,\n current?: Record<string, unknown> | null,\n plan: PackPlan = buildPackPlan(ctx, current)\n): string {\n const existing = Array.isArray(current?.skills) ? current.skills : [];\n return `${JSON.stringify(\n {\n ...(current ?? {}),\n $schema: SKILLS_SCHEMA_URL,\n inherit_global: true,\n registry: SKILLS_REGISTRY_URL,\n skills: [\n // Two evictions, deliberately narrow. `isRetiredBmadPackEntry` clears the\n // leftovers from when pjangler pinned a Skillex `bmad` pack;\n // `isRedundantDeclaredPackEntry` clears hand-expanded members of a pack\n // the repo now declares. Nothing else is removed \u2014 an entry pointing at\n // a CONTAINER inside a declared pack's family, or anywhere outside it,\n // is the user's.\n ...existing.filter(\n (entry) => !isRetiredBmadPackEntry(entry) && !isRedundantDeclaredPackEntry(entry, plan)\n ),\n ...plan.manifestSkills,\n ],\n },\n null,\n 2\n )}\\n`;\n}\n\n// ---------------------------------------------------------------------------\n// PJAN-28: legacy committed skills\n//\n// Before this, `.agents/skills/` entries that were neither BMAD pack symlinks\n// nor recorded in `.agents/skills.json` were *silently skipped* by both the\n// audit walk and the migrate walk. A repo could therefore carry committed\n// skills that no manifest knew about and nothing ever said so. These helpers\n// surface that drift and, behind an explicit opt-in, map each entry into the\n// manifest.\n// ---------------------------------------------------------------------------\n\nfunction skillsBackupDir(repoRoot: string): string {\n return join(repoRoot, \".agents\", SKILLS_BACKUP_DIRNAME);\n}\n\n/**\n * Local, offline-only registry checkouts to consult for a content match.\n *\n * The \"registry\" (`SKILLS_REGISTRY_URL`) is a plain git repo \u2014 it exposes no\n * API and no index, so the only thing that can be matched against is a\n * checkout that already exists on disk. `sync-skills.py` clones it into\n * `~/.agents/.cache/registries/<sanitized-url>`; `~/code/skillex` is the\n * canonical developer checkout. This is deliberately the SAME ladder pack\n * resolution walks \u2014 a second, divergent copy is what let one pack name resolve\n * two ways. We NEVER clone or fetch here: a parity audit/migrate must not depend\n * on the network, so an absent checkout simply means \"no confident match\".\n */\nfunction skillsRegistryRoots(ctx: Context): string[] {\n return packRegistryRoots(ctx, SKILLS_REGISTRY_URL);\n}\n\nfunction availableSkillsRegistryRoots(ctx: Context): string[] {\n return skillsRegistryRoots(ctx).filter((root) =>\n SKILLS_REGISTRY_SKILL_DIRS.some((dir) => existsSync(join(root, dir)))\n );\n}\n\n/**\n * Canonical content digest for a skill entry.\n *\n * Returns `null` for anything that cannot be compared with certainty \u2014 a\n * symlink at any depth, a device/fifo, or an unreadable path. `null` always\n * means \"not a confident match\", never \"match\".\n */\nfunction digestSkillEntry(root: string): string | null {\n const hash = createHash(\"sha256\");\n try {\n const stat = lstatSync(root);\n if (stat.isSymbolicLink()) return null;\n if (stat.isFile()) {\n const content = readFileSync(root);\n hash.update(`file\\0\\0${content.length}\\0`);\n hash.update(content);\n return hash.digest(\"hex\");\n }\n if (!stat.isDirectory()) return null;\n const walk = (dir: string, rel: string): boolean => {\n for (const name of readdirSync(dir).sort()) {\n const full = join(dir, name);\n const entryRel = rel ? `${rel}/${name}` : name;\n const entryStat = lstatSync(full);\n if (entryStat.isSymbolicLink()) return false;\n if (entryStat.isDirectory()) {\n hash.update(`dir\\0${entryRel}\\0`);\n if (!walk(full, entryRel)) return false;\n } else if (entryStat.isFile()) {\n const content = readFileSync(full);\n hash.update(`file\\0${entryRel}\\0${content.length}\\0`);\n hash.update(content);\n } else {\n return false;\n }\n }\n return true;\n };\n hash.update(\"dir\\0\");\n return walk(root, \"\") ? hash.digest(\"hex\") : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Names under `.agents/skills` that no contract accounts for.\n *\n * Shared by the audit and the migration so the two can never drift. An entry is\n * \"undeclared\" when it is NOT in the BMAD namespace (see\n * BMAD_SKILL_NAME_PREFIX), NOT recorded in `.agents/skills.json`, and NOT a\n * projection of a backed-up skill (`skills-sync` re-materializes mapped entries\n * as symlinks into `.agents/skills.bak`, which must never be re-reported).\n *\n * PJAN-82: it used to report these as \"unmanaged COMMITTED skill(s)\", which is\n * a claim this function cannot make \u2014 it never consults git. On the reporting\n * machine 58 of them were gitignored generated symlinks, and the word sent the\n * reader looking for a tracking problem that did not exist. The real condition\n * is \"present in the projection, accounted for by nothing\", which since the\n * fan-out engine started reconciling is usually sediment the next sync removes\n * rather than content anyone needs to adopt.\n */\nfunction legacyCommittedSkillNames(\n skillsDir: string,\n backupDir: string,\n expectedNames: Set<string>,\n packRoots: string[],\n manifestNames: Set<string>\n): string[] {\n const stat = lstatIfPresent(skillsDir);\n if (!stat || stat.isSymbolicLink() || !stat.isDirectory()) return [];\n const names: string[] = [];\n let entries: string[];\n try {\n entries = readdirSync(skillsDir).sort();\n } catch {\n return [];\n }\n // PJAN-84: a repo's OWN authored skill is declared by its directory.\n //\n // `<repo>/skills/<name>/SKILL.md` is projected by sync-skills.py without any\n // manifest entry, because `.agents/skills.json` is generated and gitignored in\n // these repos \u2014 a hand-written entry there does not survive a fresh clone, and\n // a declaration that restates a directory's contents is a second copy of the\n // truth that drifts from the first. This is the TypeScript mirror of that rule,\n // so the audit agrees with the engine instead of demanding a duplicate.\n const repoSkillsRoot = resolve(skillsDir, \"..\", \"..\", \"skills\");\n for (const name of entries) {\n if (expectedNames.has(name) || manifestNames.has(name)) continue;\n if (name.startsWith(BMAD_SKILL_NAME_PREFIX)) continue;\n const path = join(skillsDir, name);\n let linkTarget: string | null = null;\n try {\n linkTarget = lstatSync(path).isSymbolicLink() ? resolve(dirname(path), readlinkSync(path)) : null;\n } catch {\n linkTarget = null;\n }\n if (\n linkTarget &&\n (packRoots.some((root) => isContainedBy(root, linkTarget)) || isContainedBy(backupDir, linkTarget))\n ) {\n continue;\n }\n // The projection of this repo's own `skills/<name>`, by that exact name.\n if (linkTarget && linkTarget === join(repoSkillsRoot, name) && existsSync(join(linkTarget, \"SKILL.md\"))) {\n continue;\n }\n names.push(name);\n }\n return names;\n}\n\ninterface LegacySkillPlan {\n name: string;\n registryPath?: string;\n description: string;\n}\n\n/**\n * Decide where a single unmanaged entry should be recorded.\n *\n * \"Confident\" means byte-identical: the entry's whole tree must digest to\n * exactly the same value as a registry candidate. Anything short of that \u2014\n * a customized copy, an unreadable tree, a symlink, no local checkout \u2014 keeps\n * the skill local, because a wrong registry mapping would silently swap the\n * user's customized skill for the upstream one on the next `skills-sync`.\n */\nfunction planLegacyCommittedSkill(\n skillsDir: string,\n backupDir: string,\n registryRoots: string[],\n name: string\n): LegacySkillPlan {\n const backupTarget = join(backupDir, name);\n const localDescription = (reason: string) =>\n `${name} -> file://${backupTarget} (${reason}; kept local)`;\n const digest = digestSkillEntry(join(skillsDir, name));\n if (!digest) {\n return { name, description: localDescription(\"entry is a symlink or is not byte-comparable\") };\n }\n if (!registryRoots.length) {\n return { name, description: localDescription(\"no local registry checkout to compare against\") };\n }\n for (const root of registryRoots) {\n for (const dir of SKILLS_REGISTRY_SKILL_DIRS) {\n const candidate = join(root, dir, name);\n if (!existsSync(candidate)) continue;\n if (digestSkillEntry(candidate) !== digest) continue;\n return {\n name,\n registryPath: `${dir}/${name}`,\n description: `${name} -> registry_path ${dir}/${name} (exact content match)`,\n };\n }\n }\n return { name, description: localDescription(\"no exact registry content match\") };\n}\n\n/**\n * Report (default) or apply (with `--accept-registry-matches`) the mapping of\n * every unmanaged `.agents/skills` entry into `.agents/skills.json`.\n *\n * Applying moves the original into `.agents/skills.bak/<name>` \u2014 never deletes\n * it \u2014 and records either `registry_path` (confident match) or an absolute\n * `file://` source pointing at the backup (everything else).\n */\nfunction migrateLegacyCommittedSkills(ctx: Context, changedFiles: string[]): string[] {\n const details: string[] = [];\n const agentsDir = join(ctx.repoRoot, \".agents\");\n const skillsDir = join(agentsDir, \"skills\");\n const backupDir = skillsBackupDir(ctx.repoRoot);\n const manifestPath = join(agentsDir, \"skills.json\");\n\n const rawManifest = safeReadText(manifestPath);\n const manifest = tryParseJson(rawManifest);\n if (rawManifest !== null && manifest === null) {\n // Invalid JSON: never clobber it. provisionDeclaredPacks reports the blocker.\n return details;\n }\n // An unresolvable pack blocks later in provisionDeclaredPacks; an empty pack\n // inventory here only makes this step more conservative.\n const packPlan = buildPackPlan(ctx, manifest);\n const expectedNames = new Set(packPlan.projections.keys());\n const manifestSkills = Array.isArray(manifest?.skills) ? [...manifest.skills] : [];\n const manifestNames = new Set(\n manifestSkills\n .map(skillManifestEntryName)\n .filter((name): name is string => Boolean(name))\n );\n\n const names = legacyCommittedSkillNames(skillsDir, backupDir, expectedNames, packPlan.ownershipRoots, manifestNames);\n if (!names.length) return details;\n\n const registryRoots = availableSkillsRegistryRoots(ctx);\n if (!registryRoots.length) {\n details.push(\n `No local ${SKILLS_REGISTRY_URL} checkout is available; registry matching is skipped (set PJ_SKILLS_REGISTRY_ROOT or let skills-sync clone the registry)`\n );\n }\n const plans = names.map((name) => planLegacyCommittedSkill(skillsDir, backupDir, registryRoots, name));\n\n if (!ctx.acceptRegistryMatches) {\n for (const plan of plans) details.push(`proposed mapping: ${plan.description}`);\n details.push(\n `${plans.length} legacy committed skill(s) left untouched; re-run with --accept-registry-matches to apply`\n );\n return details;\n }\n\n const applied: LegacySkillPlan[] = [];\n for (const plan of plans) {\n const from = join(skillsDir, plan.name);\n const to = join(backupDir, plan.name);\n if (lstatIfPresent(to)) {\n details.push(`skipped ${plan.name}: ${to} already exists and would be overwritten`);\n continue;\n }\n if (!changedFiles.includes(to)) changedFiles.push(to);\n if (!ctx.dryRun) {\n mkdirSync(backupDir, { recursive: true });\n renameSync(from, to);\n }\n manifestSkills.push(\n plan.registryPath\n ? { name: plan.name, registry_path: plan.registryPath }\n : { name: plan.name, source: pathToFileURL(to).href }\n );\n applied.push(plan);\n details.push(`mapped ${plan.description}`);\n }\n if (!applied.length) return details;\n\n // Emit the canonical shape rather than a plain append: provisionDeclaredPacks\n // re-orders the manifest into [non-pack..., pack...] on every run, so a naive\n // append would be rewritten on the next migrate and never reach \"noop\".\n const merged = { ...(manifest ?? {}), skills: manifestSkills };\n let nextManifest: string;\n try {\n nextManifest = canonicalSkillsManifest(ctx, merged);\n } catch {\n nextManifest = `${JSON.stringify(merged, null, 2)}\\n`;\n }\n if (nextManifest !== rawManifest) {\n if (!changedFiles.includes(manifestPath)) changedFiles.push(manifestPath);\n if (!ctx.dryRun) writeText(manifestPath, nextManifest);\n }\n return details;\n}\n\nexport interface PackProvisionHooks {\n afterPreflight?: () => void;\n createLink?: (target: string, link: string, index: number) => void;\n afterApply?: (manifestPath: string, skillsDir: string) => void;\n}\n\nfunction removeProjectEntry(path: string): void {\n const stat = lstatIfPresent(path);\n if (!stat) return;\n if (stat.isDirectory() && !stat.isSymbolicLink()) {\n rmSync(path, { recursive: true, force: true });\n return;\n }\n // Node 24 rejects rmSync(..., { recursive: false }) for directory symlinks\n // with ERR_FS_EISDIR. unlinkSync removes the link itself without touching its\n // directory target and also preserves the intended regular-file behavior.\n try {\n unlinkSync(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n}\n\nfunction normalizeExecutableTemplate(\n ctx: Context,\n target: string,\n expected: string,\n changedFiles: string[]\n): void {\n const stat = lstatIfPresent(target);\n if (stat && (!stat.isFile() || stat.isSymbolicLink())) {\n throw new Error(`Refusing non-regular managed executable target: ${target}`);\n }\n const contentChanged = !stat || safeReadText(target) !== expected;\n const modeChanged = !stat || (Number(stat.mode) & 0o111) === 0;\n if (!contentChanged && !modeChanged) return;\n if (!changedFiles.includes(target)) changedFiles.push(target);\n if (ctx.dryRun) return;\n if (contentChanged) {\n writeText(target, expected);\n }\n const beforeChmod = lstatIfPresent(target);\n if (!beforeChmod?.isFile() || beforeChmod.isSymbolicLink()) {\n throw new Error(`Refusing changed managed executable target: ${target}`);\n }\n chmodSync(target, 0o755);\n}\n\nfunction atomicWriteBuffer(path: string, content: Buffer, mode: number, temporary: string): void {\n writeFileSync(temporary, content, { flag: \"wx\" });\n chmodSync(temporary, mode);\n renameSync(temporary, path);\n}\n\n/**\n * Materialize every pack DECLARED in `.agents/skills.json` `packs[]` into\n * `.agents/skills/<name>` symlinks, and normalize the manifest around them.\n *\n * Formerly `provisionBmadSkills`, back when pjangler pinned a `bmad` pack\n * implicitly and this function's main job was projecting it. BMAD is the\n * installer's now; nothing is pinned implicitly, so this only ever handles\n * what a repo asked for by name.\n */\nexport function provisionDeclaredPacks(\n ctx: Context,\n preservedManifest?: Record<string, unknown> | null,\n hooks: PackProvisionHooks = {}\n): { ok: boolean; changedFiles: string[]; error?: string; packWarnings?: string[] } {\n // Destination topology and the manifest's own file type are security\n // boundaries. Validate them before reading packs[] or resolving any registry\n // path: a symlinked manifest must never be followed even during planning.\n let initialDirs: { agentsDir: string; skillsDir: string };\n try {\n initialDirs = prepareSafeProjectSkillsDirs({ ...ctx, dryRun: true });\n } catch (error) {\n return { ok: false, changedFiles: [], error: error instanceof Error ? error.message : String(error) };\n }\n const initialManifestPath = join(initialDirs.agentsDir, \"skills.json\");\n const initialManifestStat = lstatIfPresent(initialManifestPath);\n if (initialManifestStat?.isSymbolicLink() || (initialManifestStat && !initialManifestStat.isFile())) {\n return { ok: false, changedFiles: [], error: `Refusing unsafe skills manifest: ${initialManifestPath}` };\n }\n\n // The plan depends on `packs[]`, so the manifest is read (leniently) first.\n // A manifest that does not parse yields no packs here and is reported with\n // its proper error below, before anything is created or written.\n //\n const declaringManifest =\n preservedManifest ??\n tryParseJson(initialManifestStat ? readRegularFile(initialManifestPath).toString(\"utf8\") : null);\n const plan = buildPackPlan(ctx, declaringManifest);\n if (plan.errors.length) {\n return { ok: false, changedFiles: [], error: plan.errors.join(\"; \") };\n }\n const packSkills = plan.manifestSkills;\n hooks.afterPreflight?.();\n\n const projectRoot = realpathSync(ctx.repoRoot);\n const agentsPath = join(projectRoot, \".agents\");\n const skillsPath = join(agentsPath, \"skills\");\n const agentsExisted = Boolean(lstatIfPresent(agentsPath));\n const skillsExisted = Boolean(lstatIfPresent(skillsPath));\n let preflightDirs: { agentsDir: string; skillsDir: string };\n try {\n preflightDirs = prepareSafeProjectSkillsDirs({ ...ctx, dryRun: true });\n } catch (error) {\n return { ok: false, changedFiles: [], error: error instanceof Error ? error.message : String(error) };\n }\n const manifestPath = join(preflightDirs.agentsDir, \"skills.json\");\n const manifestStat = lstatIfPresent(manifestPath);\n if (manifestStat?.isSymbolicLink() || (manifestStat && !manifestStat.isFile())) {\n return { ok: false, changedFiles: [], error: `Refusing unsafe skills manifest: ${manifestPath}` };\n }\n const manifestBytes = manifestStat ? readRegularFile(manifestPath) : null;\n const manifestMode = manifestStat ? Number(manifestStat.mode) & 0o777 : 0o644;\n let currentManifest: Record<string, unknown> = {};\n if (manifestBytes !== null) {\n try {\n const parsed = JSON.parse(manifestBytes.toString(\"utf8\")) as unknown;\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) throw new Error(\"must contain a JSON object\");\n currentManifest = parsed as Record<string, unknown>;\n if (currentManifest.skills !== undefined && !Array.isArray(currentManifest.skills)) throw new Error(\"skills must be an array\");\n } catch (error) {\n return { ok: false, changedFiles: [], error: `Invalid existing skills manifest ${manifestPath}: ${error instanceof Error ? error.message : String(error)}` };\n }\n }\n let safeDirs: { agentsDir: string; skillsDir: string };\n try {\n safeDirs = prepareSafeProjectSkillsDirs(ctx);\n } catch (error) {\n return { ok: false, changedFiles: [], error: error instanceof Error ? error.message : String(error) };\n }\n const nextManifest = canonicalSkillsManifest(ctx, preservedManifest ?? currentManifest, plan);\n const skillsDir = safeDirs.skillsDir;\n const resolvedSkillsDir = ctx.dryRun && !existsSync(skillsDir) ? skillsDir : realpathSync(skillsDir);\n const expected = new Map(plan.projections);\n const expectedNames = new Set(expected.keys());\n const ownershipManifest = preservedManifest ?? currentManifest;\n const managedManifestNames = new Set(\n (Array.isArray(ownershipManifest.skills) ? ownershipManifest.skills : [])\n .filter((entry) => isPackManagedManifestEntry(entry, expectedNames, plan.ownershipRoots))\n .map(skillManifestEntryName)\n .filter((name): name is string => Boolean(name))\n );\n const affected = new Set<string>();\n const staleManagedNames = new Set<string>();\n const originalCorrectLinks = new Map<string, string>();\n if (existsSync(skillsDir)) {\n for (const name of readdirSync(skillsDir)) {\n validateSkillName(name);\n if (dirname(join(resolvedSkillsDir, name)) !== resolvedSkillsDir) {\n return { ok: false, changedFiles: [], error: `BMAD skill path escapes project skills directory: ${name}` };\n }\n const entryPath = join(skillsDir, name);\n let linkTargetsPack = false;\n try {\n const linkTarget =\n lstatSync(entryPath).isSymbolicLink() ? resolve(dirname(entryPath), readlinkSync(entryPath)) : null;\n linkTargetsPack = Boolean(linkTarget) && plan.ownershipRoots.some((root) => isContainedBy(root, linkTarget!));\n } catch {\n linkTargetsPack = false;\n }\n if (!expected.has(name) && !managedManifestNames.has(name) && !linkTargetsPack) continue;\n const target = expected.get(name);\n let correct = false;\n try {\n correct = Boolean(target) && lstatSync(entryPath).isSymbolicLink() && resolve(dirname(entryPath), readlinkSync(entryPath)) === target;\n } catch {\n correct = false;\n }\n if (correct) originalCorrectLinks.set(name, readlinkSync(join(skillsDir, name)));\n else {\n affected.add(name);\n if (!target) staleManagedNames.add(name);\n }\n }\n }\n for (const [name, target] of expected) {\n const link = join(resolvedSkillsDir, validateSkillName(name));\n if (dirname(link) !== resolvedSkillsDir) {\n return { ok: false, changedFiles: [], error: `BMAD skill path escapes project skills directory: ${name}` };\n }\n let correct = false;\n try {\n correct = lstatSync(link).isSymbolicLink() && resolve(dirname(link), readlinkSync(link)) === target;\n } catch {\n correct = false;\n }\n if (!correct) affected.add(name);\n }\n\n const manifestChanged = manifestBytes?.toString(\"utf8\") !== nextManifest;\n const changedFiles = [\n ...(manifestChanged ? [manifestPath] : []),\n ...(affected.size ? [skillsDir] : []),\n ];\n if (ctx.dryRun || changedFiles.length === 0) {\n try {\n assertPackPlanUnchanged(plan);\n return { ok: true, changedFiles, packWarnings: plan.packWarnings };\n } catch (error) {\n return { ok: false, changedFiles: [], error: error instanceof Error ? error.message : String(error) };\n }\n }\n\n const transaction = mkdtempSync(join(safeDirs.agentsDir, \".bmad-transaction-\"));\n const backup = join(transaction, \"entries\");\n mkdirSync(backup);\n const moved: string[] = [];\n\n const rollback = (): void => {\n const errors: string[] = [];\n try {\n for (const name of affected) {\n removeProjectEntry(join(skillsDir, validateSkillName(name)));\n }\n for (const name of originalCorrectLinks.keys()) {\n removeProjectEntry(join(skillsDir, validateSkillName(name)));\n }\n } catch (error) {\n errors.push(`remove applied projection: ${String(error)}`);\n }\n for (const name of [...moved].reverse()) {\n try {\n renameSync(join(backup, name), join(skillsDir, name));\n } catch (error) {\n errors.push(`restore ${name}: ${String(error)}`);\n }\n }\n for (const [name, rawTarget] of originalCorrectLinks) {\n try {\n symlinkSync(rawTarget, join(skillsDir, name), \"dir\");\n } catch (error) {\n errors.push(`restore ${name}: ${String(error)}`);\n }\n }\n try {\n if (manifestBytes === null) removeProjectEntry(manifestPath);\n else atomicWriteBuffer(manifestPath, manifestBytes, manifestMode, join(transaction, \"manifest.restore\"));\n } catch (error) {\n errors.push(`restore manifest: ${String(error)}`);\n }\n rmSync(transaction, { recursive: true, force: true });\n try {\n if (!skillsExisted && existsSync(skillsDir) && readdirSync(skillsDir).length === 0) rmdirSync(skillsDir);\n if (!agentsExisted && existsSync(safeDirs.agentsDir) && readdirSync(safeDirs.agentsDir).length === 0) rmdirSync(safeDirs.agentsDir);\n } catch (error) {\n errors.push(`remove created directories: ${String(error)}`);\n }\n if (errors.length) throw new Error(`BMAD rollback was incomplete: ${errors.join(\"; \")}`);\n };\n\n try {\n for (const name of affected) {\n const entry = join(skillsDir, name);\n if (lstatIfPresent(entry)) {\n renameSync(entry, join(backup, name));\n moved.push(name);\n }\n }\n let index = 0;\n for (const [name, target] of expected) {\n index += 1;\n const link = join(skillsDir, name);\n let correct = false;\n try {\n correct = lstatSync(link).isSymbolicLink() && resolve(skillsDir, readlinkSync(link)) === target;\n } catch {\n correct = false;\n }\n if (correct) continue;\n if (hooks.createLink) hooks.createLink(target, link, index);\n else symlinkSync(target, link, \"dir\");\n }\n if (manifestChanged) {\n atomicWriteBuffer(manifestPath, Buffer.from(nextManifest), manifestMode, join(transaction, \"manifest.next\"));\n }\n assertPackPlanUnchanged(plan);\n hooks.afterApply?.(manifestPath, skillsDir);\n for (const name of staleManagedNames) {\n if (lstatIfPresent(join(skillsDir, name))) {\n throw new Error(`Applied BMAD projection retained stale managed entry: ${name}`);\n }\n }\n for (const [name, target] of expected) {\n const link = join(skillsDir, name);\n let correct = false;\n try {\n correct = lstatSync(link).isSymbolicLink() && resolve(skillsDir, readlinkSync(link)) === target;\n } catch {\n correct = false;\n }\n if (!correct) throw new Error(`Applied BMAD projection link differs from plan: ${name}`);\n }\n const finalManifestStat = lstatIfPresent(manifestPath);\n if (\n !finalManifestStat || finalManifestStat.isSymbolicLink() || !finalManifestStat.isFile() ||\n (Number(finalManifestStat.mode) & 0o777) !== manifestMode ||\n readFileSync(manifestPath).toString(\"utf8\") !== nextManifest\n ) {\n throw new Error(\"Applied BMAD skills manifest differs from planned bytes or mode\");\n }\n const finalManifest = JSON.parse(readFileSync(manifestPath, \"utf8\")) as Record<string, unknown>;\n if (\n finalManifest.$schema !== SKILLS_SCHEMA_URL ||\n finalManifest.inherit_global !== true || finalManifest.registry !== SKILLS_REGISTRY_URL ||\n !Array.isArray(finalManifest.skills)\n ) {\n throw new Error(\"Applied BMAD skills manifest schema differs from plan\");\n }\n } catch (error) {\n try {\n rollback();\n } catch (rollbackError) {\n return { ok: false, changedFiles: [], error: `BMAD provisioning failed (${String(error)}); ${String(rollbackError)}` };\n }\n return { ok: false, changedFiles: [], error: error instanceof Error ? error.message : String(error) };\n }\n\n rmSync(transaction, { recursive: true });\n return { ok: true, changedFiles, packWarnings: plan.packWarnings };\n}\n\nfunction templateVersionFilesConf(ctx: Context, repoRoot: string): string {\n const packageJson = join(repoRoot, \"package.json\");\n return existsSync(packageJson)\n ? \"# mise-versioning manifest: <type> <path>\\n# types: json toml cargo csproj gradle plain gittag\\njson package.json\\ngittag .\\n\"\n : \"# mise-versioning manifest: <type> <path>\\n# types: json toml cargo csproj gradle plain gittag\\ngittag .\\n\";\n}\n\nfunction replaceOrAppendManagedBlock(text: string, startMarker: RegExp, block: string, beforePattern?: RegExp): string {\n if (startMarker.test(text)) {\n return text.replace(/# >>> mise-versioning >>>[\\s\\S]*?# <<< mise-versioning <<</, block);\n }\n if (beforePattern) {\n const match = text.match(beforePattern);\n if (match && typeof match.index === \"number\") {\n return `${text.slice(0, match.index).replace(/\\s*$/, \"\\n\\n\")}${block}\\n\\n${text.slice(match.index)}`;\n }\n }\n return `${text.replace(/\\s*$/, \"\")}\\n\\n${block}\\n`;\n}\n\nconst BASE_MISE_PATH_ENTRIES = [\".mise/scripts\", \"agents/hermes/pm\"];\n\nfunction requiredMisePathEntries(_ctx: Context): string[] {\n // mise PATH entries are directories. agents/hermes/pm already makes the\n // executable wrapper at agents/hermes/pm/hermes discoverable; adding the\n // wrapper file itself creates a false audit disagreement and an invalid PATH\n // component on every rendered PM role.\n return [...BASE_MISE_PATH_ENTRIES];\n}\n\nfunction upsertMisePath(text: string, required = BASE_MISE_PATH_ENTRIES): string {\n const render = (values: string[]) => `_.path = [${values.map((value) => JSON.stringify(value)).join(\", \")}]`;\n const envMatch = text.match(/(^|\\n)(\\[env\\][\\s\\S]*?)(?=\\n\\[[^\\]]+\\]|$)/);\n if (!envMatch || typeof envMatch.index !== \"number\") {\n return `[env]\\n${render(required)}\\n\\n${text.replace(/^\\s+/, \"\")}`;\n }\n\n const prefix = text.slice(0, envMatch.index + envMatch[1]!.length);\n const section = envMatch[2]!;\n const suffix = text.slice(envMatch.index + envMatch[1]!.length + section.length);\n const pathLine = section.match(/^_\\.path\\s*=\\s*\\[([^\\]]*)\\]\\s*$/m);\n if (!pathLine) {\n return `${prefix}${section.replace(/\\n?$/, \"\\n\")}${render(required)}${suffix}`;\n }\n\n const current = [...pathLine[1]!.matchAll(/\"([^\"]+)\"/g)].map((match) => match[1]!);\n const merged = [...current];\n for (const value of required) {\n if (!merged.includes(value)) merged.push(value);\n }\n const nextLine = render(merged);\n if (pathLine[0] === nextLine) return text;\n return `${prefix}${section.replace(pathLine[0], nextLine)}${suffix}`;\n}\n\nfunction removeTomlSection(text: string, headerPattern: RegExp, marker?: RegExp, options?: { includePrecedingComments?: boolean }): string {\n const lines = text.split(\"\\n\");\n let start = -1;\n let end = -1;\n for (let i = 0; i < lines.length; i++) {\n if (!headerPattern.test(lines[i]!)) continue;\n if (marker) {\n let hasMarker = false;\n for (let j = i + 1; j < lines.length && !/^\\[[^\\]]+\\]/.test(lines[j]!); j++) {\n if (marker.test(lines[j]!)) {\n hasMarker = true;\n break;\n }\n }\n if (!hasMarker) continue;\n }\n start = i;\n for (let j = i + 1; j < lines.length; j++) {\n if (/^\\[[^\\]]+\\]/.test(lines[j]!)) {\n end = j;\n break;\n }\n }\n if (end === -1) end = lines.length;\n break;\n }\n if (start === -1) return text;\n // Trailing comment/blank lines directly before the next header belong to that\n // next section (e.g. the `# >>> mise-versioning >>>` marker), so keep them out\n // of the removed range \u2014 otherwise re-running a migrate corrupts them.\n while (end > start + 1 && (lines[end - 1]!.trim() === \"\" || lines[end - 1]!.trim().startsWith(\"#\"))) {\n end--;\n }\n if (options?.includePrecedingComments) {\n while (start > 0 && lines[start - 1]!.trim().startsWith(\"#\")) {\n start--;\n }\n }\n const result = lines.slice(0, start).concat(lines.slice(end)).join(\"\\n\");\n return result.replace(/\\n{3,}/g, \"\\n\\n\").replace(/\\n+$/, \"\\n\");\n}\n\nfunction insertTomlBlockBeforeVersioning(text: string, block: string): string {\n const versioningIndex = text.indexOf(\"# >>> mise-versioning >>>\");\n if (versioningIndex >= 0) {\n return `${text.slice(0, versioningIndex).replace(/\\s*$/, \"\\n\\n\")}${block}\\n\\n${text.slice(versioningIndex)}`;\n }\n return `${text.replace(/\\s*$/, \"\")}\\n\\n${block}\\n`;\n}\n\nfunction insertHookBlock(text: string, block: string): string {\n const structural = /^(?:\\[\\[watch_files\\]\\]|\\[tasks(?:\\.|\\]))/m.exec(text);\n const versioningIndex = text.indexOf(\"# >>> mise-versioning >>>\");\n const candidates = [structural?.index, versioningIndex >= 0 ? versioningIndex : undefined]\n .filter((value): value is number => value !== undefined);\n if (candidates.length) {\n const index = Math.min(...candidates);\n return `${text.slice(0, index).replace(/\\s*$/, \"\\n\\n\")}${block}\\n\\n${text.slice(index)}`;\n }\n return `${text.replace(/\\s*$/, \"\")}\\n\\n${block}\\n`;\n}\n\nfunction extractTomlStrings(text: string): string[] {\n const values: string[] = [];\n const stringPattern = /\"((?:\\\\.|[^\"\\\\])*)\"|'([^']*)'/g;\n for (const match of text.matchAll(stringPattern)) {\n if (match[1] !== undefined) {\n try {\n values.push(JSON.parse(`\"${match[1]}\"`) as string);\n } catch {\n values.push(match[1]);\n }\n } else if (match[2] !== undefined) {\n values.push(match[2]);\n }\n }\n return values;\n}\n\n/**\n * Blank out TOML string literals (and any trailing comment) so structural\n * scans can count brackets without being fooled by `[`/`]` that live inside a\n * quoted value \u2014 e.g. a hook entry like `\"[ -f foo ] && foo || true\"`.\n */\nfunction stripTomlStringsAndComments(line: string): string {\n return line\n .replace(/\"(?:\\\\.|[^\"\\\\])*\"/g, '\"\"')\n .replace(/'[^']*'/g, \"''\")\n .replace(/#.*$/, \"\");\n}\n\n/** Strip quoting and the `{{config_root}}/` prefix so hook paths compare. */\nfunction normalizeOpInjectPath(raw: string): string {\n let path = raw.trim();\n if ((path.startsWith(\"'\") && path.endsWith(\"'\")) || (path.startsWith('\"') && path.endsWith('\"'))) {\n path = path.slice(1, -1);\n }\n return path.replace(/^\\{\\{config_root\\}\\}\\//, \"\").replace(/^\\.\\//, \"\");\n}\n\nconst QUOTED_OR_BARE = String.raw`(\"[^\"]*\"|'[^']*'|\\S+)`;\n\n/**\n * The file an `op inject` hook ultimately writes, normalized relative to the\n * project root \u2014 or null if the value is not an `op inject` command at all.\n *\n * Publication order matters: a hook that stages to a temp and then `mv`s is\n * defined by the `mv` destination, not by `-o`. Only the segment AFTER\n * `op inject` is considered, so the `>/dev/null` in the `command -v op` guard\n * is never mistaken for the output target.\n */\nfunction opInjectOutputTarget(value: string): string | null {\n const trimmed = value.trim();\n const start = trimmed.search(/\\bop\\s+inject\\b/);\n if (start < 0) return null;\n const tail = trimmed.slice(start);\n const mv = new RegExp(String.raw`\\bmv\\s+(?:-\\S+\\s+)*${QUOTED_OR_BARE}\\s+${QUOTED_OR_BARE}`).exec(tail);\n if (mv?.[2]) return normalizeOpInjectPath(mv[2]);\n const redirect = new RegExp(String.raw`>\\s*${QUOTED_OR_BARE}`).exec(tail);\n if (redirect?.[1]) return normalizeOpInjectPath(redirect[1]);\n const flag = new RegExp(String.raw`\\s(?:-o|--out(?:put)?)[=\\s]\\s*${QUOTED_OR_BARE}`).exec(tail);\n if (flag?.[1]) return normalizeOpInjectPath(flag[1]);\n return null;\n}\n\n/**\n * True only for a pjangler-owned dotenv materialization hook: one that writes\n * `.env` itself. That covers the canonical atomic form and both truncating\n * ancestors (v0 unguarded, v1 guarded-but-still-redirecting), all of which a\n * migrate replaces with the canonical command.\n *\n * It deliberately does NOT claim every hook that merely mentions `op inject`\n * and `.env.op`. A hook writing somewhere else \u2014 `.env.secrets` (the\n * WireMiseOpInject pattern, which is SAFER than what we install), `.env.local`,\n * `.env.staging` \u2014 belongs to the user. Claiming it is destructive, not\n * cosmetic: normalizeHookScript rewrites it to the canonical string and\n * dedupePreserve then collapses it into the managed entry, so the user's hook\n * disappears entirely. When in doubt, do not claim it.\n */\nfunction isOpInjectHookEntry(value: string): boolean {\n const trimmed = value.trim();\n if (trimmed === OP_INJECT_SCRIPT) return true;\n return opInjectOutputTarget(trimmed) === \".env\";\n}\n\n/**\n * Enter-hook values that materialize `.env` but are NOT the canonical atomic\n * command \u2014 i.e. every form that can still clobber a populated `.env`.\n *\n * The audit must test these extracted VALUES, never the raw mise.toml text: the\n * explanatory comments above the hook quote the truncating forms verbatim, so a\n * text scan would flag the very files that are already correct.\n */\nfunction truncatingOpInjectEntries(enterHooks: string[]): string[] {\n return enterHooks.filter((value) => value.trim() !== OP_INJECT_SCRIPT && isOpInjectHookEntry(value));\n}\n\nfunction isManagedHookEntry(value: string): boolean {\n const trimmed = value.trim();\n if (isOpInjectHookEntry(trimmed)) return true;\n if (trimmed === SYNC_SKILLS_SCRIPT) return true;\n if (trimmed === PROVISION_PACKS_SCRIPT) return true;\n if (trimmed === LEGACY_PROVISION_BMAD_SKILLS_SCRIPT) return true;\n if (/sync-skills(?:\\.py)?[\"']?\\s+--scope project/.test(trimmed)) return true;\n if (/provision-packs\\.py/.test(trimmed)) return true;\n if (/provision-bmad-skills\\.py/.test(trimmed)) return true;\n if (/link-project-skills-to-clis\\.sh'?\\s*$/.test(trimmed)) return true;\n if (/unlink-project-skills-from-clis\\.sh'?\\s*$/.test(trimmed)) return true;\n // link-agentfiles.sh, with or without wrapping single quotes / path prefix.\n return /link-agentfiles\\.sh'?\\s*$/.test(trimmed);\n}\n\n/**\n * Normalize a preserved hook command so pjangler-managed scripts it references\n * are single-quoted (space-safe). Unknown user commands are kept verbatim.\n *\n * `kind` is load-bearing (PJAN-24): the dotenv rewrite applies to ENTER hooks\n * only. A LEAVE hook is a teardown step, so rewriting one to the materialization\n * command turns \"clean up on exit\" into \"resolve secrets on exit\" \u2014 the exact\n * inverse of its intent.\n */\nfunction normalizeHookScript(script: string, kind: \"enter\" | \"leave\"): string {\n const trimmed = script.trim();\n if (/codegraph\\.sh/.test(trimmed)) return CODEGRAPH_SCRIPT;\n if (kind === \"enter\" && isOpInjectHookEntry(trimmed)) return OP_INJECT_SCRIPT;\n return trimmed;\n}\n\n/**\n * Determine the exclusive end line of a (possibly multi-line) TOML value that\n * begins at `start`, counting array brackets outside of string literals so a\n * `]` inside a quoted command can't be mistaken for the array close.\n */\nfunction tomlValueSpanEnd(lines: string[], start: number, limit: number): number {\n let depth = 0;\n let j = start;\n for (; j < limit; j++) {\n for (const ch of stripTomlStringsAndComments(lines[j]!)) {\n if (ch === \"[\") depth++;\n else if (ch === \"]\") depth--;\n }\n if (depth <= 0) break;\n }\n return Math.min(j, limit - 1) + 1;\n}\n\n/**\n * Remove every mise hook construct from the text \u2014 both the `[hooks]` table\n * (with `enter`/`leave` as a string or an array of strings) and any\n * `[[hooks.enter]]`/`[[hooks.leave]]` array-of-tables \u2014 and return the stripped\n * text alongside the collected enter/leave commands.\n */\ninterface HookTableRecord {\n kind: \"enter\" | \"leave\";\n script?: string;\n raw: string;\n}\n\nfunction stripHookBlocks(text: string): { text: string; enter: string[]; leave: string[]; records: HookTableRecord[] } {\n const lines = text.split(\"\\n\");\n const enter: string[] = [];\n const leave: string[] = [];\n const records: HookTableRecord[] = [];\n const drop = new Array<boolean>(lines.length).fill(false);\n const isHeader = (line: string) => /^\\[/.test(line.trim());\n\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i]!.trim();\n const tableMatch = /^\\[\\[\\s*hooks\\.(enter|leave)\\s*\\]\\]$/.exec(trimmed);\n if (tableMatch) {\n const kind = tableMatch[1] as \"enter\" | \"leave\";\n const bucket = kind === \"enter\" ? enter : leave;\n let recordScript: string | undefined;\n let j = i + 1;\n // TOML array-of-table bodies extend to the next table header. Blank lines\n // and comments are part of the current table and must never terminate the\n // range (PJAN-57: the old heuristic orphaned script under [env]).\n for (; j < lines.length && !isHeader(lines[j]!); j++) {\n // A managed-section marker starts a new logical region even though it\n // is a TOML comment rather than a table header.\n if (lines[j]!.trim().startsWith(\"# >>> mise-versioning >>>\")) break;\n const scriptMatch = /^\\s*script\\s*=\\s*(.+)$/.exec(lines[j]!);\n if (scriptMatch) {\n const value = extractTomlStrings(scriptMatch[1]!)[0];\n if (value !== undefined) {\n recordScript = value;\n bucket.push(value);\n }\n }\n }\n for (let k = i; k < j; k++) drop[k] = true;\n records.push({ kind, script: recordScript, raw: lines.slice(i, j).join(\"\\n\").replace(/\\n+$/, \"\") });\n i = j - 1;\n continue;\n }\n if (trimmed === \"[hooks]\") {\n let j = i + 1;\n let lastDrop = i; // last line index that is part of the [hooks] table proper\n while (j < lines.length && !isHeader(lines[j]!)) {\n const keyMatch = /^\\s*(enter|leave)\\s*=/.exec(lines[j]!);\n if (keyMatch) {\n const bucket = keyMatch[1] === \"enter\" ? enter : leave;\n const end = tomlValueSpanEnd(lines, j, lines.length);\n // Full-line comments are dropped before extraction: the explanatory\n // comment above the op-inject hook quotes the truncating forms\n // verbatim, and must not be read back as a hook value (PJAN-24).\n const chunk = lines.slice(j, end).filter((line) => !/^\\s*#/.test(line)).join(\"\\n\");\n for (const value of extractTomlStrings(chunk)) {\n bucket.push(value);\n records.push({ kind: keyMatch[1] as \"enter\" | \"leave\", script: value, raw: `[[hooks.${keyMatch[1]}]]\\nscript = ${JSON.stringify(value)}` });\n }\n lastDrop = end - 1;\n j = end;\n } else if (/^\\s*\\]\\s*$/.test(lines[j]!)) {\n // Orphan bare-`]` left by a prior buggy run that duplicated the array\n // close \u2014 absorb it (self-heal) rather than leaking invalid TOML.\n lastDrop = j;\n j++;\n } else {\n j++;\n }\n }\n // Drop the header through the last key value only; keep trailing\n // comment/blank lines that belong to the following section.\n for (let k = i; k <= lastDrop; k++) drop[k] = true;\n i = j - 1;\n continue;\n }\n }\n\n const kept = lines\n .filter((_, idx) => !drop[idx])\n .join(\"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .replace(/\\n+$/, \"\\n\");\n return { text: kept, enter, leave, records };\n}\n\nfunction ownedOpInjectScriptsOutsideEnter(text: string): Array<{ line: number; value: string }> {\n const findings: Array<{ line: number; value: string }> = [];\n let table = \"\";\n for (const [index, line] of text.split(\"\\n\").entries()) {\n const header = /^\\s*(\\[\\[?[^\\]]+\\]\\]?)\\s*(?:#.*)?$/.exec(line);\n if (header) {\n table = header[1]!.replace(/[\\[\\]\\s]/g, \"\");\n continue;\n }\n const script = /^\\s*script\\s*=\\s*(.+)$/.exec(line);\n if (!script || table === \"hooks.enter\") continue;\n const value = extractTomlStrings(script[1]!)[0];\n if (value !== undefined && isOpInjectHookEntry(value)) findings.push({ line: index + 1, value });\n }\n return findings;\n}\n\nfunction removeOwnedOpInjectScriptsOutsideEnter(text: string): string {\n let table = \"\";\n return text.split(\"\\n\").filter((line) => {\n const header = /^\\s*(\\[\\[?[^\\]]+\\]\\]?)\\s*(?:#.*)?$/.exec(line);\n if (header) {\n table = header[1]!.replace(/[\\[\\]\\s]/g, \"\");\n return true;\n }\n const script = /^\\s*script\\s*=\\s*(.+)$/.exec(line);\n if (!script || table === \"hooks.enter\") return true;\n const value = extractTomlStrings(script[1]!)[0];\n return value === undefined || !isOpInjectHookEntry(value);\n }).join(\"\\n\");\n}\n\nfunction renderHookTables(scripts: readonly string[], kind: \"enter\" | \"leave\"): string[] {\n return scripts.map((script) => `[[hooks.${kind}]]\\nscript = ${JSON.stringify(script)}`);\n}\n\nfunction dedupePreserve(scripts: string[]): string[] {\n const out: string[] = [];\n for (const script of scripts) {\n if (script && !out.includes(script)) out.push(script);\n }\n return out;\n}\n\nfunction isMiseCoreHookEntry(value: string): boolean {\n const trimmed = value.trim();\n if (isOpInjectHookEntry(trimmed)) return false;\n return trimmed === SYNC_SKILLS_SCRIPT\n || trimmed === PROVISION_PACKS_SCRIPT\n || trimmed === LEGACY_PROVISION_BMAD_SKILLS_SCRIPT\n || /sync-skills(?:\\.py)?[\"']?\\s+--scope project/.test(trimmed)\n || /provision-(?:packs|bmad-skills)\\.py/.test(trimmed)\n // PJAN-82: tolerate a trailing argument list.\n //\n // These patterns decide which existing hook records this owner REPLACES.\n // They were anchored to end-of-string right after the script filename, so\n // the moment the canonical form gained an explicit `'{{config_root}}'`\n // subject argument the owner stopped recognizing its OWN output: every\n // `pj migrate mise.config-root` found nothing it owned, prepended the\n // canonical block again, and left the previous copy in place as a foreign\n // record. Three runs produced three link-agentfiles enter hooks while\n // `pj audit` reported \"mise AGENTS-linking parity verified\".\n || /link-(?:project-skills-to-clis|agentfiles)\\.sh'?(?:\\s+\\S.*)?$/.test(trimmed)\n || /unlink-project-skills-from-clis\\.sh'?(?:\\s+\\S.*)?$/.test(trimmed);\n}\n\nfunction reconcileHookOwner(\n text: string,\n owns: (record: HookTableRecord) => boolean,\n canonicalScripts: readonly string[],\n header = \"\",\n): string {\n const { text: stripped, records } = stripHookBlocks(text);\n const canonicalRecords = renderHookTables(canonicalScripts, \"enter\");\n const output: string[] = [];\n let inserted = false;\n for (const record of records) {\n if (owns(record)) {\n if (!inserted) {\n output.push(...canonicalRecords);\n inserted = true;\n }\n continue;\n }\n output.push(record.raw);\n }\n if (!inserted) output.unshift(...canonicalRecords);\n\n const effectiveHeader = header || (stripped.includes(HOOKS_COMMENT_HEADER) ? HOOKS_COMMENT_HEADER : \"\");\n const withoutManagedHeader = effectiveHeader\n ? stripped.replace(HOOKS_COMMENT_HEADER, \"\").replace(/\\n{3,}/g, \"\\n\\n\")\n : stripped;\n const block = [effectiveHeader, ...output].filter(Boolean).join(\"\\n\");\n return insertHookBlock(withoutManagedHeader, block);\n}\n\nfunction upsertLinkAgentfilesHooks(text: string): string {\n return reconcileHookOwner(\n text,\n (record) => record.kind === \"enter\" && Boolean(record.script && isMiseCoreHookEntry(record.script)),\n LINK_AGENTFILES_HOOK_ENTRIES,\n HOOKS_COMMENT_HEADER,\n );\n}\n\nfunction upsertOpInjectHook(text: string): string {\n const withoutStrays = removeOwnedOpInjectScriptsOutsideEnter(text);\n return reconcileHookOwner(\n withoutStrays,\n (record) => record.kind === \"enter\" && Boolean(record.script && isOpInjectHookEntry(record.script)),\n [OP_INJECT_SCRIPT],\n );\n}\n\n/**\n * PJAN-61: rewrite retired dash-era mise task names to their colon form in\n * place \u2014 section headers, `task = \"...\"` watch dispatches, `depends` entries,\n * and `mise run <name>` invocations. Deliberately anchored to those syntactic\n * positions: a bare substring pass would also rewrite\n * `.mise/scripts/link-agentfiles.sh`, whose FILENAME is still dashed and must\n * stay that way.\n */\n/**\n * Report every retired dash-era task name still present in a mise.toml, in the\n * same three syntactic positions `renameRetiredMiseTasks` rewrites. Anything\n * this reports is fixable by that function, so audit and migrate never disagree.\n */\n/**\n * PJAN-84: a hook must name its SUBJECT, not just the script to run.\n *\n * `{{config_root}}` in a hook string locates the FILE. Nothing located the\n * file's subject, and a mise enter hook runs with cwd set to the directory the\n * operator cd'd into \u2014 including for a PARENT config's hook \u2014 so a script that\n * read its subject from cwd reshaped whichever nested repo you entered. That is\n * how 33GOD's copies of provision-packs.py and sync-skills.py came to rewrite\n * `pjangler/.agents/skills.json` and plant dangling links in seven siblings.\n *\n * The check that was here verified only that the hook string CONTAINED\n * `'{{config_root}}/.mise/scripts/link-agentfiles.sh'`, which the subject-bearing\n * form also contains \u2014 so it passed on both, and never looked at the two python\n * hooks at all. Every cwd hazard PJAN-82 fixed sat under a green audit the whole\n * time.\n */\nconst MANAGED_HOOK_SUBJECTS: ReadonlyArray<{ name: string; marker: string; subject: RegExp }> = [\n { name: \"link-agentfiles.sh\", marker: \"link-agentfiles.sh\", subject: /link-agentfiles\\.sh'?\\s+'?\\{\\{config_root\\}\\}'?/u },\n { name: \"sync-skills.py\", marker: \"sync-skills.py\", subject: /--root\\s+'?\\{\\{config_root\\}\\}'?/u },\n { name: \"provision-packs.py\", marker: \"provision-packs.py\", subject: /--root\\s+'?\\{\\{config_root\\}\\}'?/u },\n];\n\nfunction managedHookSubjectIssues(text: string): string[] {\n const issues: string[] = [];\n for (const record of stripHookBlocks(text).records) {\n if (record.kind !== \"enter\") continue;\n const script = record.script?.trim();\n if (!script) continue;\n for (const managed of MANAGED_HOOK_SUBJECTS) {\n if (!script.includes(managed.marker)) continue;\n if (managed.subject.test(script)) continue;\n issues.push(\n `hooks.enter runs ${managed.name} without handing it {{config_root}} as its subject; ` +\n \"an enter hook's cwd is the directory you cd'd into, so it would act on that repo instead\"\n );\n }\n }\n return issues;\n}\n\nfunction retiredTaskNameIssues(text: string): string[] {\n const issues: string[] = [];\n for (const [oldName, newName] of RETIRED_TASK_RENAMES) {\n const esc = oldName.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const present = new RegExp(\n `^\\\\[tasks\\\\.(?:\"${esc}\"|${esc})\\\\]|^\\\\s*task\\\\s*=\\\\s*\"${esc}\"|^\\\\s*depends\\\\s*=\\\\s*\\\\[[^\\\\]]*\"${esc}\"`,\n \"m\",\n ).test(text);\n if (present) issues.push(`mise.toml still uses the retired task name \"${oldName}\" (renamed to \"${newName}\")`);\n }\n return issues;\n}\n\nexport function renameRetiredMiseTasks(text: string): string {\n let out = text;\n for (const [oldName, newName] of RETIRED_TASK_RENAMES) {\n const esc = oldName.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n out = out.replace(new RegExp(`^\\\\[tasks\\\\.(?:\"${esc}\"|${esc})\\\\]`, \"gm\"), taskHeader(newName));\n out = out.replace(new RegExp(`^(\\\\s*task\\\\s*=\\\\s*)\"${esc}\"`, \"gm\"), `$1\"${newName}\"`);\n out = out.replace(new RegExp(`\\\\bmise run ${esc}\\\\b`, \"g\"), `mise run ${newName}`);\n }\n // `depends = [...]` holds bare task names; rewrite inside the array only.\n return out.replace(/^(\\s*depends\\s*=\\s*)(\\[[^\\]]*\\])/gm, (_whole, head: string, arr: string) => {\n let next = arr;\n for (const [oldName, newName] of RETIRED_TASK_RENAMES) {\n next = next.split(`\"${oldName}\"`).join(`\"${newName}\"`);\n }\n return head + next;\n });\n}\n\nfunction upsertLinkAgentfilesBlock(text: string, ctx: Context): string {\n const withPath = upsertMisePath(renameRetiredMiseTasks(text), requiredMisePathEntries(ctx));\n // Remove stale AGENTS-linking pieces before appending the canonical block.\n // Both the colon and the retired dash header forms are matched so a\n // half-migrated file can never end up holding two copies of the same task.\n let cleaned = removeTomlSection(withPath, taskHeaderPattern(LINK_AGENTFILES_TASK), /link-agentfiles/, { includePrecedingComments: false });\n cleaned = removeTomlSection(cleaned, /^\\[tasks\\.link-agentfiles\\]$/, /link-agentfiles/, { includePrecedingComments: false });\n cleaned = removeTomlSection(cleaned, taskHeaderPattern(SKILLS_SYNC_TASK), undefined, { includePrecedingComments: false });\n cleaned = removeTomlSection(cleaned, /^\\[tasks\\.skills-sync\\]$/, undefined, { includePrecedingComments: false });\n cleaned = removeTomlSection(cleaned, taskHeaderPattern(PROVISION_PACKS_TASK), undefined, { includePrecedingComments: false });\n cleaned = removeTomlSection(cleaned, /^\\[tasks\\.skills-provision-packs\\]$/, undefined, { includePrecedingComments: false });\n cleaned = removeTomlSection(cleaned, /^\\[tasks\\.skills-provision-bmad\\]$/, undefined, { includePrecedingComments: false });\n cleaned = removeTomlSection(cleaned, /^\\[tasks\\.link-project-skills-to-clis\\]$/, undefined, { includePrecedingComments: false });\n cleaned = removeTomlSection(cleaned, /^\\[tasks\\.unlink-project-skills-from-clis\\]$/, undefined, { includePrecedingComments: false });\n cleaned = removeTomlSection(cleaned, /^\\[tasks\\.skills-relink\\]$/, undefined, { includePrecedingComments: false });\n cleaned = removeTomlSection(cleaned, /^\\[\\[watch_files\\]\\]$/, /AGENTS\\.md/, { includePrecedingComments: false });\n cleaned = removeTomlSection(cleaned, /^\\[\\[watch_files\\]\\]$/, /\\.agents\\/skills\\.json/, { includePrecedingComments: false });\n cleaned = upsertLinkAgentfilesHooks(cleaned);\n return insertTomlBlockBeforeVersioning(cleaned, LINK_AGENTFILES_WATCH_TASK_BLOCK);\n}\n\nfunction readProjectJson(ctx: Context): Record<string, unknown> | null {\n return tryParseJson(safeReadText(join(ctx.repoRoot, \".project.json\")));\n}\n\ninterface DeclaredAgentEntry {\n agentId: string;\n role?: string;\n roleDir?: string;\n extras: Record<string, unknown>;\n}\n\nfunction readDeclaredAgents(ctx: Context): DeclaredAgentEntry[] {\n const project = readProjectJson(ctx);\n const agents = project?.agents as Record<string, unknown> | undefined;\n if (!agents || typeof agents !== \"object\") return [];\n return Object.entries(agents).map(([agentId, value]) => {\n const entry = (typeof value === \"object\" && value !== null ? (value as Record<string, unknown>) : {}) as Record<string, unknown>;\n return {\n agentId,\n role: typeof entry.role === \"string\" ? entry.role : undefined,\n roleDir: typeof entry.role_dir === \"string\" ? entry.role_dir : undefined,\n extras: Object.fromEntries(Object.entries(entry).filter(([key]) => key !== \"role\" && key !== \"role_dir\")),\n };\n });\n}\n\nfunction readRoleYamlAt(roleDir: string): { role: string; agentId: string; providerName: string; text: string } | null {\n const roleYamlPath = join(roleDir, \"role.yaml\");\n if (!existsSync(roleYamlPath)) return null;\n const text = readText(roleYamlPath);\n return {\n role: yamlGet(text, \"role\"),\n agentId: yamlGet(text, \"agent_id\"),\n providerName: yamlGet(text, \"ticket_provider.name\"),\n text,\n };\n}\n\n/**\n * True when a declared/registered agent has no `role.yaml` behind it -- i.e.\n * the role is unprovisioned or half-provisioned rather than merely drifted.\n *\n * PJAN-75: this predicate is deliberately SHARED between `sot.project-json`\n * and `hermes.registry-parity`. Those two rules used to test the same\n * condition independently and reach opposite conclusions: registry-parity\n * called it a non-fixable blocker (\"provision or restore the role, do not\n * delete its registry/declaration\") while project-json quietly deleted the\n * declaration as invalid. A single `migrate --all` therefore destroyed the\n * only repo-local record of an agent's identity AND still left the audit\n * failing, because the fleet registry entry it could not see survived.\n *\n * An empty/missing role_dir counts as unprovisioned for the same reason: there\n * is nothing on disk to recover the identity from, so the declaration is all\n * that is left of it.\n */\nfunction declaredRoleIsUnprovisioned(repoRoot: string, roleDir: string | undefined): boolean {\n if (!roleDir) return true;\n return !existsSync(join(resolve(repoRoot, roleDir), \"role.yaml\"));\n}\n\nfunction validateDeclaredAgent(ctx: Context, declared: DeclaredAgentEntry): { valid: boolean; role?: string; agentId?: string; roleDir?: string; details: string[] } {\n const details: string[] = [];\n if (!declared.roleDir) {\n details.push(`agents.${declared.agentId}.role_dir missing`);\n return { valid: false, details };\n }\n const roleDir = resolve(ctx.repoRoot, declared.roleDir);\n if (!existsSync(roleDir)) {\n details.push(`agents.${declared.agentId}.role_dir ${declared.roleDir} does not exist`);\n return { valid: false, roleDir, details };\n }\n const roleYaml = readRoleYamlAt(roleDir);\n if (!roleYaml) {\n details.push(`agents.${declared.agentId}.role_dir ${declared.roleDir} missing role.yaml`);\n return { valid: false, roleDir, details };\n }\n if (declared.role !== roleYaml.role) {\n details.push(`agents.${declared.agentId}.role should be ${roleYaml.role} (declared ${declared.role})`);\n }\n if (declared.agentId !== roleYaml.agentId) {\n details.push(`agents.${declared.agentId} should map to agent_id ${roleYaml.agentId}`);\n }\n if (roleYaml.providerName) {\n const dispatcher = join(roleDir, \".scripts\", \"lib\", \"ticket-provider.sh\");\n if (!existsSync(dispatcher)) {\n details.push(`agents.${declared.agentId} provider dispatcher ${relative(ctx.repoRoot, dispatcher)} missing`);\n }\n const provider = join(roleDir, \".scripts\", \"providers\", `${roleYaml.providerName}.sh`);\n if (!existsSync(provider)) {\n details.push(`agents.${declared.agentId} provider script ${relative(ctx.repoRoot, provider)} missing`);\n }\n }\n return { valid: details.length === 0, role: roleYaml.role, agentId: roleYaml.agentId, roleDir, details };\n}\n\nfunction boolSetting(value: unknown, fallback: boolean): boolean {\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"string\") {\n const normalized = value.trim().toLowerCase();\n if ([\"true\", \"1\", \"yes\", \"on\"].includes(normalized)) return true;\n if ([\"false\", \"0\", \"no\", \"off\"].includes(normalized)) return false;\n }\n return fallback;\n}\n\nfunction numberSetting(value: unknown, fallback: number): number {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim()) {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n return fallback;\n}\n\nfunction canonicalProjectJson(ctx: Context): Record<string, unknown> & { dropped: string[]; unprovisioned: string[] } {\n const roles = discoverRoles(ctx.repoRoot);\n const existing = readProjectJson(ctx) ?? {};\n const slug = typeof existing.project_slug === \"string\" && existing.project_slug ? existing.project_slug : slugifyRepoName(basename(ctx.repoRoot));\n const firstRole = roles[0];\n const ticketProvider = {\n type: String(((existing.ticket_provider as Record<string, unknown> | undefined)?.type ?? firstRole?.ticketProviderName ?? \"plane\") || \"plane\"),\n workspace: String(((existing.ticket_provider as Record<string, unknown> | undefined)?.workspace ?? firstRole?.planeWorkspace ?? \"\") || \"\"),\n identifier: String(((existing.ticket_provider as Record<string, unknown> | undefined)?.identifier ?? firstRole?.ticketProviderIdentifier ?? \"\") || \"\"),\n board_id: String(((existing.ticket_provider as Record<string, unknown> | undefined)?.board_id ?? firstRole?.ticketProviderBoardId ?? \"\") || \"\"),\n state: String(((existing.ticket_provider as Record<string, unknown> | undefined)?.state ?? (firstRole?.ticketProviderBoardId ? \"linked\" : \"planned\")) || \"planned\"),\n };\n if (ticketProvider.board_id && ticketProvider.state === \"planned\") ticketProvider.state = \"linked\";\n const existingAgents = (existing.agents as Record<string, { role?: string; role_dir?: string; [key: string]: unknown }> | undefined) ?? {};\n const discoveredAgents: Record<string, { role: string; role_dir: string }> = Object.fromEntries(\n roles.map((role) => [\n role.agentId || `${slug}-${role.role}`,\n {\n role: role.role,\n role_dir: relative(ctx.repoRoot, role.roleDir),\n },\n ])\n );\n const agents: Record<string, Record<string, unknown>> = Object.fromEntries(\n Object.entries(discoveredAgents).map(([agentId, discovered]) => {\n const existingAgent = existingAgents[agentId] ?? {};\n const extras = Object.fromEntries(Object.entries(existingAgent).filter(([key]) => key !== \"role\" && key !== \"role_dir\"));\n return [agentId, { role: discovered.role, role_dir: discovered.role_dir, ...extras }];\n })\n );\n const dropped: string[] = [];\n const unprovisioned: string[] = [];\n for (const [declaredAgentId, entry] of Object.entries(existingAgents)) {\n const declared: DeclaredAgentEntry = {\n agentId: declaredAgentId,\n role: typeof entry.role === \"string\" ? entry.role : undefined,\n roleDir: typeof entry.role_dir === \"string\" ? entry.role_dir : undefined,\n extras: Object.fromEntries(Object.entries(entry).filter(([key]) => key !== \"role\" && key !== \"role_dir\")),\n };\n // PJAN-75: a declaration with no role.yaml behind it is an UNPROVISIONED\n // role, not junk. role.yaml is the identity SSOT, so when it is absent the\n // declaration is the last place the agent's role, role_dir and any\n // provisioning extras still exist -- and `hermes.registry-parity` refuses\n // to prune exactly this state for exactly that reason. Preserve the entry\n // byte-for-byte and let the rule keep failing until the role is\n // provisioned or restored. Dropping it neither fixed the audit (the fleet\n // registry entry outlives .project.json) nor left anything to repair from.\n if (declaredRoleIsUnprovisioned(ctx.repoRoot, declared.roleDir)) {\n agents[declaredAgentId] = { ...entry };\n unprovisioned.push(declaredAgentId);\n continue;\n }\n const validated = validateDeclaredAgent(ctx, declared);\n if (!validated.valid || !validated.role || !validated.agentId || !validated.roleDir) {\n // role.yaml exists, so `discoverRoles` has already contributed the\n // canonical identity above and this stale key carries nothing unique.\n dropped.push(declaredAgentId);\n continue;\n }\n agents[validated.agentId] = {\n role: validated.role,\n role_dir: relative(ctx.repoRoot, validated.roleDir),\n ...declared.extras,\n };\n }\n const existingAutomation = (existing.automation as Record<string, unknown> | undefined) ?? {};\n const existingReconcile = (existingAutomation.reconcile as Record<string, unknown> | undefined) ?? {};\n const legacyEnabled = roles.find((role) => role.legacyReconcileEnabled)?.legacyReconcileEnabled;\n const legacyGrace = roles.find((role) => role.legacyReconcileGraceHours || role.legacyScrumGraceHours);\n const legacyAutoReview = roles.find((role) => role.legacyReconcileAutoReview || role.legacyScrumAutoReview);\n const automation = {\n ...existingAutomation,\n reconcile: {\n enabled: boolSetting(existingReconcile.enabled, boolSetting(legacyEnabled, false)),\n grace_hours: numberSetting(existingReconcile.grace_hours, numberSetting(legacyGrace?.legacyReconcileGraceHours || legacyGrace?.legacyScrumGraceHours, 0)),\n auto_review: boolSetting(existingReconcile.auto_review, boolSetting(legacyAutoReview?.legacyReconcileAutoReview || legacyAutoReview?.legacyScrumAutoReview, true)),\n },\n };\n return {\n project_name: String(existing.project_name ?? titleCaseSlug(slug)),\n project_description: String(existing.project_description ?? \"\"),\n project_slug: slug,\n repo_path: ctx.repoRoot,\n ticket_provider: ticketProvider,\n agents,\n automation,\n dropped,\n unprovisioned,\n };\n}\n\nfunction projectJsonFinding(ctx: Context): AuditFinding {\n const projectPath = join(ctx.repoRoot, \".project.json\");\n const planeJsonPath = join(ctx.repoRoot, \".plane.json\");\n const details: string[] = [];\n const data = readProjectJson(ctx);\n const roles = discoverRoles(ctx.repoRoot);\n if (!existsSync(projectPath)) {\n return { id: \"sot.project-json\", title: \"Canonical .project.json\", status: \"fail\", summary: \".project.json missing\", details: [], fixable: true };\n }\n if (!data) {\n return { id: \"sot.project-json\", title: \"Canonical .project.json\", status: \"fail\", summary: \".project.json is not valid JSON\", details: [], fixable: true };\n }\n for (const key of [\"project_name\", \"project_description\", \"project_slug\", \"repo_path\", \"ticket_provider\", \"agents\", \"automation\"]) {\n if (!(key in data)) details.push(`missing key: ${key}`);\n }\n if (data.repo_path !== ctx.repoRoot) details.push(`repo_path should be ${ctx.repoRoot}`);\n const agents = (data.agents as Record<string, unknown> | undefined) ?? {};\n for (const role of roles) {\n const agent = agents[role.agentId] as Record<string, unknown> | undefined;\n if (!agent) {\n details.push(`agents.${role.agentId} missing`);\n continue;\n }\n if (agent.role !== role.role) details.push(`agents.${role.agentId}.role should be ${role.role}`);\n if (agent.role_dir !== relative(ctx.repoRoot, role.roleDir)) {\n details.push(`agents.${role.agentId}.role_dir should be ${relative(ctx.repoRoot, role.roleDir)}`);\n }\n }\n // PJAN-75: split the declaration findings by whether migrate can actually\n // resolve them. An unprovisioned role is a human action (provision or\n // restore role.yaml); reporting it as fixable put the rule back in the\n // picker on every run, where the only \"fix\" available was the destructive\n // prune this rule no longer performs.\n const declaredAgents = readDeclaredAgents(ctx);\n let unprovisionedDeclarations = 0;\n for (const declared of declaredAgents) {\n const declaredDetails = validateDeclaredAgent(ctx, declared).details;\n if (declaredRoleIsUnprovisioned(ctx.repoRoot, declared.roleDir)) {\n unprovisionedDeclarations += declaredDetails.length;\n details.push(\n ...declaredDetails.map((detail) => `${detail}; provision or restore the role, do not delete its declaration`)\n );\n continue;\n }\n details.push(...declaredDetails);\n }\n const ticketProvider = (data.ticket_provider as Record<string, unknown> | undefined) ?? {};\n for (const key of [\"type\", \"workspace\", \"identifier\", \"board_id\", \"state\"]) {\n if (!(key in ticketProvider)) details.push(`ticket_provider.${key} missing`);\n }\n if (\"board_url\" in ticketProvider) details.push(\"ticket_provider.board_url should be removed; derive it from provider/workspace/board_id\");\n if (!ticketProvider.board_id && roles.some((role) => role.ticketProviderBoardId)) {\n details.push(\"ticket_provider.board_id missing even though legacy role.yaml contains a board binding\");\n }\n const automation = (data.automation as Record<string, unknown> | undefined) ?? {};\n const reconcile = (automation.reconcile as Record<string, unknown> | undefined) ?? {};\n for (const key of [\"enabled\", \"grace_hours\", \"auto_review\"]) {\n if (!(key in reconcile)) details.push(`automation.reconcile.${key} missing`);\n }\n if (existsSync(planeJsonPath)) details.push(\".plane.json should not exist once .project.json is canonical\");\n return {\n id: \"sot.project-json\",\n title: \"Canonical .project.json\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? \".project.json matches canonical parity contract\" : `${details.length} parity issue(s) detected`,\n details,\n fixable: details.length > unprovisionedDeclarations,\n };\n}\n\nfunction renderSoul(role: RoleMeta): string {\n const telegram = role.botHandle ? `@${role.botHandle}` : \"(unwired)\";\n const tone = role.role === \"pm\"\n ? \"Direct and brief. Decision-forward. No throat-clearing, no apologies, no \\\"I'll help you with that\\\" preambles.\"\n : \"Direct and brief.\";\n const roleSpecific = role.role === \"pm\"\n ? `You are the project manager. You triage incoming work, create or refine tickets, and delegate implementation. You do not ship product code. A systemd heartbeat checks runtime health; when this repo opts into reconciliation (\\`automation.reconcile.enabled\\` in repo-root \\`.project.json\\`), the same heartbeat also runs your continuous board-reconciliation pass out-of-band (\\`.scripts/sentinel.prompt.md\\`, \\`--source cron\\`), kept separate from your interactive session memory.`\n : `You operate as the ${role.role} agent for this repo.`;\n return `# ${role.displayName || role.agentId}\\n\\nYou are **${role.displayName || role.agentId}** \u2014 a Hermes agent provisioned to work inside the\\n\\`${role.repo}\\` repository.\\n\\n## Identity\\n\\n| | |\\n| --- | --- |\\n| Agent ID | \\`${role.agentId}\\` |\\n| Profile | \\`${role.profileName || role.agentId}\\` |\\n| Repo | \\`${role.repo}\\` |\\n| Role | \\`${role.role}\\` |\\n| Telegram | \\`${telegram}\\` |\\n| Purpose | ${role.purpose || `${role.role} agent for ${role.repo}`} |\\n\\n## Scope\\n\\nYou operate only within the working directory of \\`${role.repo}\\`. HERMES_HOME is the real named profile at \\`~/.hermes/profiles/${role.profileName || role.agentId}\\`; shared config/auth/skills remain linked to fleet truth while owned state lives in ignored \\`./runtime/\\`. The launcher supplies the project root through process-local \\`TERMINAL_CWD\\` and never persists it into shared config.\\n\\n## Tone\\n\\n${tone}\\n\\n## Role-specific behavior\\n\\n${roleSpecific}\\n\\n## Memory hygiene\\n\\nYour memory is stored locally at \\`./runtime/memories/\\`. Use durable memory deliberately and keep \\`memories/MEMORY.md\\` current.\\n`;\n}\n\nfunction renderHermesWrapper(role: RoleMeta, templateRoleDir: string): string {\n return readText(join(templateRoleDir, \"hermes.jinja\"))\n .replace(/\\{\\{\\s*agent_id\\s*\\}\\}/g, role.agentId);\n}\n\nfunction templateFiles(sourceDir: string, current = sourceDir): string[] {\n if (!existsSync(current)) return [];\n const files: string[] = [];\n for (const entry of readdirSync(current, { withFileTypes: true })) {\n if (entry.name === \"__pycache__\" || entry.name.endsWith(\".pyc\") || entry.name.endsWith(\".pyo\")) continue;\n const sourcePath = join(current, entry.name);\n if (entry.isDirectory()) files.push(...templateFiles(sourceDir, sourcePath));\n else if (entry.isFile()) files.push(relative(sourceDir, sourcePath));\n }\n return files.sort();\n}\n\nfunction managedHermesScaffoldRoles(ctx: Context): { roles: RoleMeta[]; blockers: string[] } {\n const discovered = discoverRoles(ctx.repoRoot);\n const declared = readDeclaredAgents(ctx)\n .filter((entry) => entry.role === \"pm\" || entry.role === \"director\");\n if (declared.length === 0) {\n const orchestrators = discovered.filter((role) => role.role === \"pm\" || role.role === \"director\");\n const blockers = orchestrators\n .filter((role) => roleBloodbankEnabled(role) === null)\n .map((role) => `${relative(ctx.repoRoot, role.roleYamlPath)} bloodbank.enabled must be the strict YAML boolean true or false`);\n return {\n roles: orchestrators.filter((role) => roleBloodbankEnabled(role) !== null),\n blockers,\n };\n }\n\n const roles: RoleMeta[] = [];\n const blockers: string[] = [];\n for (const entry of declared) {\n if (!entry.roleDir) {\n blockers.push(`agents.${entry.agentId}.role_dir missing`);\n continue;\n }\n const roleDir = resolve(ctx.repoRoot, entry.roleDir);\n if (!isContainedBy(ctx.repoRoot, roleDir)) {\n blockers.push(`agents.${entry.agentId}.role_dir resolves outside the project`);\n continue;\n }\n const role = discovered.find((candidate) => resolve(candidate.roleDir) === roleDir);\n if (!role) {\n blockers.push(`agents.${entry.agentId}.role_dir ${entry.roleDir} missing role.yaml`);\n continue;\n }\n if (role.agentId !== entry.agentId || role.role !== entry.role) {\n blockers.push(`agents.${entry.agentId} identity does not match ${entry.roleDir}/role.yaml`);\n continue;\n }\n if (roleBloodbankEnabled(role) === null) {\n blockers.push(`${entry.roleDir}/role.yaml bloodbank.enabled must be the strict YAML boolean true or false`);\n continue;\n }\n roles.push(role);\n }\n return { roles, blockers };\n}\n\nfunction renderSentinelPrompt(role: RoleMeta, templateRoleDir: string): string {\n return readText(join(templateRoleDir, \".scripts\", \"sentinel.prompt.md.jinja\"))\n .replace(/\\{\\{\\s*agent_id\\s*\\}\\}/g, role.agentId)\n .replace(/\\{\\{\\s*role\\s*\\}\\}/g, role.role)\n .replace(/\\{\\{\\s*target_repo\\s*\\}\\}/g, role.repo)\n .replace(/\\{\\{\\s*display_name\\s*\\}\\}/g, role.displayName || role.agentId)\n .replace(/\\{\\{\\s*ticket_provider\\s*\\}\\}/g, role.ticketProviderName || \"plane\");\n}\n\nfunction copyMissingRecursive(sourceDir: string, targetDir: string, changedFiles: string[], dryRun: boolean, skip?: (source: string) => boolean): void {\n if (!existsSync(sourceDir)) return;\n mkdirSync(targetDir, { recursive: true });\n for (const entry of readdirSync(sourceDir, { withFileTypes: true })) {\n const sourcePath = join(sourceDir, entry.name);\n if (skip?.(sourcePath)) continue;\n const targetPath = join(targetDir, entry.name);\n if (entry.isDirectory()) {\n copyMissingRecursive(sourcePath, targetPath, changedFiles, dryRun, skip);\n continue;\n }\n if (existsSync(targetPath)) continue;\n changedFiles.push(targetPath);\n if (!dryRun) {\n ensureParent(targetPath);\n copyFileSync(sourcePath, targetPath);\n }\n }\n}\n\nfunction runtimeSubmodulePath(repoRoot: string, role: RoleMeta): string | null {\n const rolePath = relative(repoRoot, role.roleDir).replace(/\\\\/g, \"/\");\n if (!/^agents\\/hermes\\/[^/]+$/.test(rolePath)) return null;\n return `${rolePath}/runtime`;\n}\n\nfunction submoduleSectionHasPath(section: string, targetPath: string): boolean {\n return section\n .split(/\\r?\\n/)\n .some((line) => /^\\s*path\\s*=/.test(line) && line.replace(/^\\s*path\\s*=\\s*/, \"\").trim() === targetPath);\n}\n\nfunction hasRuntimeSubmoduleMapping(repoRoot: string, role: RoleMeta): boolean {\n const gitmodulesPath = join(repoRoot, \".gitmodules\");\n const current = safeReadText(gitmodulesPath) ?? \"\";\n const sections = current.match(/^\\[submodule \"[^\"\\n]+\"\\][\\s\\S]*?(?=^\\[submodule \"|(?![\\s\\S]))/gm) ?? [];\n const targetPath = runtimeSubmodulePath(repoRoot, role);\n return Boolean(targetPath && sections.some((section) => submoduleSectionHasPath(section, targetPath)));\n}\n\nfunction removeRuntimeSubmoduleMapping(repoRoot: string, role: RoleMeta, changedFiles: string[], dryRun: boolean): string[] {\n const gitmodulesPath = join(repoRoot, \".gitmodules\");\n const current = safeReadText(gitmodulesPath) ?? \"\";\n if (!hasRuntimeSubmoduleMapping(repoRoot, role)) return [];\n const targetPath = runtimeSubmodulePath(repoRoot, role);\n if (!targetPath) return [];\n const next = current\n .replace(/^\\[submodule \"[^\"\\n]+\"\\][\\s\\S]*?(?=^\\[submodule \"|(?![\\s\\S]))/gm, (section) =>\n submoduleSectionHasPath(section, targetPath) ? \"\" : section)\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n changedFiles.push(gitmodulesPath);\n if (!dryRun) writeText(gitmodulesPath, next ? `${next}\\n` : \"\");\n return [gitmodulesPath];\n}\n\ninterface RuntimeRetirementResult {\n ok: boolean;\n details: string[];\n error?: string;\n}\n\nfunction retireRuntimeSubmodule(\n repoRoot: string,\n role: RoleMeta,\n changedFiles: string[],\n dryRun: boolean,\n): RuntimeRetirementResult {\n const runtimePath = runtimeSubmodulePath(repoRoot, role);\n if (!runtimePath) {\n return { ok: false, details: [], error: `refusing unsafe runtime path for ${role.roleDir}` };\n }\n const probe = spawnSync(\"git\", [\"ls-files\", \"--stage\", \"--\", runtimePath], {\n cwd: repoRoot,\n encoding: \"utf8\",\n });\n if (probe.status !== 0) {\n return { ok: false, details: [], error: `failed to inspect runtime index at ${runtimePath}: ${probe.stderr.trim() || `exit ${probe.status}`}` };\n }\n\n const details: string[] = [];\n if (probe.stdout.trim()) {\n details.push(`untrack ${runtimePath}`);\n if (dryRun) {\n changedFiles.push(runtimePath);\n } else {\n const removal = spawnSync(\"git\", [\"rm\", \"--cached\", \"-r\", \"-f\", \"--\", runtimePath], {\n cwd: repoRoot,\n encoding: \"utf8\",\n });\n if (removal.status !== 0) {\n return { ok: false, details, error: `failed to untrack ${runtimePath}: ${removal.stderr.trim() || `exit ${removal.status}`}` };\n }\n const verification = spawnSync(\"git\", [\"ls-files\", \"--stage\", \"--\", runtimePath], {\n cwd: repoRoot,\n encoding: \"utf8\",\n });\n if (verification.status !== 0 || verification.stdout.trim()) {\n return {\n ok: false,\n details,\n error: verification.status !== 0\n ? `failed to verify untracked runtime ${runtimePath}: ${verification.stderr.trim() || `exit ${verification.status}`}`\n : `runtime remains tracked after index-only removal: ${runtimePath}`,\n };\n }\n changedFiles.push(runtimePath);\n }\n }\n\n if (hasRuntimeSubmoduleMapping(repoRoot, role)) {\n details.push(`remove stale .gitmodules mapping for ${runtimePath}`);\n removeRuntimeSubmoduleMapping(repoRoot, role, changedFiles, dryRun);\n }\n return { ok: true, details };\n}\n\nfunction upsertRegistryEntry(role: RoleMeta, homeDir: string, changedFiles: string[], dryRun: boolean): string | null {\n const path = registryPath(homeDir);\n const current = safeReadText(path) ?? \"# Hermes agent fleet registry.\\n# One entry per provisioned agent. Managed by hermes-agent-template/.scripts/80-registry.sh.\\nschema_version: 1\\nagents: {}\\n\";\n if (current.includes(`${role.agentId}:`)) return null;\n const enabled = roleBloodbankEnabled(role);\n if (enabled === null) return null;\n const block = ` ${role.agentId}:\\n repo: ${role.repo}\\n role: ${role.role}\\n display_name: ${JSON.stringify(role.displayName || role.agentId)}\\n project_path: ${ctxEscape(role.roleDir ? dirname(dirname(dirname(role.roleDir))) : \"\")}\\n role_dir: ${ctxEscape(role.roleDir)}\\n profile_name: ${role.profileName || role.agentId}\\n telegram:\\n bot_username: ${ctxEscape(role.botHandle)}\\n plane:\\n workspace: ${ctxEscape(role.planeWorkspace)}\\n project_id: ${ctxEscape(role.ticketProviderBoardId)}\\n identifier: ${ctxEscape(role.ticketProviderIdentifier)}\\n runtime_repo: ${ctxEscape(role.runtimeRepo)}\\n bloodbank:\\n enabled: ${enabled ? \"true\" : \"false\"}\\n gateway_scope: fleet\\n target_agent_id: ${role.agentId}\\n systemd:\\n gateway_unit: hermes-${role.agentId}-gateway.service\\n heartbeat_timer: hermes-${role.agentId}-heartbeat.timer\\n`;\n const next = current.includes(\"agents: {}\") ? current.replace(\"agents: {}\", `agents:\\n${block}`) : `${current.replace(/\\s*$/, \"\\n\")}${block}`;\n changedFiles.push(path);\n if (!dryRun) writeText(path, next);\n return path;\n}\n\nfunction roleBloodbankEnabled(role: RoleMeta): boolean | null {\n if (role.bloodbankEnabled === \"\" || role.bloodbankEnabled === \"false\") return false;\n if (role.bloodbankEnabled === \"true\") return true;\n return null;\n}\n\nfunction profileMetaInheritsDefault(path: string): boolean {\n const text = safeReadText(path);\n return Boolean(\n text &&\n /^config:\\s*$/m.test(text) &&\n /^\\s+inherit_from:\\s*default\\s*$/m.test(text) &&\n /^\\s+save_mode:\\s*delta\\s*$/m.test(text)\n );\n}\n\nfunction upsertInheritedProfileMeta(path: string, changedFiles: string[], dryRun: boolean): string | null {\n const current = safeReadText(path) ?? \"\";\n const lines = current.split(\"\\n\");\n let next: string;\n const start = lines.findIndex((line) => /^config:\\s*$/.test(line));\n\n if (!current.trim()) {\n next = \"config:\\n inherit_from: default\\n save_mode: delta\\n\";\n } else if (start === -1) {\n next = `${current.replace(/\\s*$/, \"\\n\")}config:\\n inherit_from: default\\n save_mode: delta\\n`;\n } else {\n let end = start + 1;\n while (end < lines.length && !/^[^#\\s][^:]*:\\s*/.test(lines[end] ?? \"\")) end++;\n\n let hasInherit = false;\n let hasSave = false;\n for (let idx = start + 1; idx < end; idx++) {\n if (/^\\s+inherit_from:\\s*/.test(lines[idx] ?? \"\")) {\n lines[idx] = \" inherit_from: default\";\n hasInherit = true;\n } else if (/^\\s+save_mode:\\s*/.test(lines[idx] ?? \"\")) {\n lines[idx] = \" save_mode: delta\";\n hasSave = true;\n }\n }\n\n const inserts: string[] = [];\n if (!hasInherit) inserts.push(\" inherit_from: default\");\n if (!hasSave) inserts.push(\" save_mode: delta\");\n if (inserts.length) lines.splice(end, 0, ...inserts);\n next = lines.join(\"\\n\");\n if (!next.endsWith(\"\\n\")) next += \"\\n\";\n }\n\n if (next === current) return null;\n changedFiles.push(path);\n if (!dryRun) writeText(path, next);\n return path;\n}\n\nfunction ctxEscape(value: string): string {\n return JSON.stringify(value || \"\");\n}\n\nfunction checkUnit(unit: string): { enabled: boolean; active: boolean } {\n const enabled = systemctlUser([\"is-enabled\", unit]).ok;\n const active = systemctlUser([\"is-active\", unit]).ok;\n return { enabled, active };\n}\n\nfunction persistRoleServiceState(\n role: RoleMeta,\n updates: Partial<Record<\"gateway\" | \"heartbeat\", \"active\" | \"deferred\">>,\n): { changed: boolean; error?: string } {\n try {\n const stat = lstatSync(role.roleYamlPath);\n if (!stat.isFile() || stat.isSymbolicLink()) {\n return { changed: false, error: `refusing unsafe role manifest ${role.roleYamlPath}` };\n }\n const current = readFileSync(role.roleYamlPath, \"utf8\");\n const document = YAML.parseDocument(current);\n if (document.errors.length) throw document.errors[0];\n const serviceState = document.get(\"service_state\", true);\n if (serviceState !== undefined && serviceState !== null && !YAML.isMap(serviceState)) {\n return { changed: false, error: `${role.roleYamlPath} service_state must be a YAML mapping` };\n }\n for (const [leaf, value] of Object.entries(updates)) {\n document.setIn([\"service_state\", leaf], value);\n }\n const next = String(document);\n if (next === current) return { changed: false };\n\n // The declaration becomes durable only after every unit action and probe\n // succeeds. A same-directory rename atomically replaces role.yaml without\n // following a symlink or exposing a partially serialized manifest.\n const transaction = mkdtempSync(join(dirname(role.roleYamlPath), \".pjangler-role-state-\"));\n try {\n atomicWriteBuffer(\n role.roleYamlPath,\n Buffer.from(next),\n Number(stat.mode) & 0o777,\n join(transaction, \"role.yaml\"),\n );\n } finally {\n rmSync(transaction, { recursive: true, force: true });\n }\n return { changed: true };\n } catch (error) {\n return { changed: false, error: error instanceof Error ? error.message : String(error) };\n }\n}\n\nfunction reconcileHermesRoleUnits(\n ctx: Context,\n role: RoleMeta,\n changedFiles: string[],\n details: string[],\n): boolean {\n const gatewayUnit = `hermes-${role.agentId}-gateway.service`;\n const heartbeatUnit = `hermes-${role.agentId}-heartbeat.timer`;\n const gatewayDeferred = role.serviceStateGateway === \"deferred\";\n const stateUpdates: Partial<Record<\"gateway\" | \"heartbeat\", \"active\" | \"deferred\">> = {};\n if (role.serviceStateHeartbeat !== \"active\") stateUpdates.heartbeat = \"active\";\n if (!gatewayDeferred && role.serviceStateGateway !== \"active\") stateUpdates.gateway = \"active\";\n\n if (ctx.dryRun) {\n details.push(\"would run: systemctl --user daemon-reload\");\n details.push(`would run: systemctl --user enable --now ${heartbeatUnit}`);\n details.push(`would run: systemctl --user ${gatewayDeferred ? \"disable\" : \"enable\"} --now ${gatewayUnit}`);\n if (Object.keys(stateUpdates).length) {\n if (!changedFiles.includes(role.roleYamlPath)) changedFiles.push(role.roleYamlPath);\n details.push(`would atomically record verified service_state in ${relative(ctx.repoRoot, role.roleYamlPath)}`);\n }\n return true;\n }\n\n const reload = systemctlUser([\"daemon-reload\"]);\n if (!reload.ok) {\n details.push(`script failed: systemctl --user daemon-reload: ${reload.stderr || reload.stdout || \"unknown error\"}`);\n return false;\n }\n const heartbeat = systemctlUser([\"enable\", \"--now\", heartbeatUnit]);\n const gateway = systemctlUser([gatewayDeferred ? \"disable\" : \"enable\", \"--now\", gatewayUnit]);\n if (!heartbeat.ok) {\n details.push(`script failed: could not enable ${heartbeatUnit}: ${heartbeat.stderr || heartbeat.stdout || \"unknown error\"}`);\n }\n if (!gateway.ok) {\n details.push(`script failed: could not ${gatewayDeferred ? \"disable\" : \"enable\"} ${gatewayUnit}: ${gateway.stderr || gateway.stdout || \"unknown error\"}`);\n }\n if (!heartbeat.ok || !gateway.ok) return false;\n\n const heartbeatState = checkUnit(heartbeatUnit);\n const gatewayState = checkUnit(gatewayUnit);\n const heartbeatHealthy = heartbeatState.enabled && heartbeatState.active;\n const gatewayHealthy = gatewayDeferred\n ? !gatewayState.enabled && !gatewayState.active\n : gatewayState.enabled && gatewayState.active;\n if (!heartbeatHealthy) {\n details.push(`script failed: ${heartbeatUnit} did not become enabled+active after systemctl reported success`);\n }\n if (!gatewayHealthy) {\n details.push(`script failed: ${gatewayUnit} did not become ${gatewayDeferred ? \"disabled+inactive\" : \"enabled+active\"} after systemctl reported success`);\n }\n if (!heartbeatHealthy || !gatewayHealthy) return false;\n\n const persisted = persistRoleServiceState(role, stateUpdates);\n if (persisted.error) {\n details.push(`script failed: could not update ${relative(ctx.repoRoot, role.roleYamlPath)}: ${persisted.error}`);\n return false;\n }\n if (persisted.changed) {\n if (!changedFiles.includes(role.roleYamlPath)) changedFiles.push(role.roleYamlPath);\n details.push(`atomically recorded verified service_state in ${relative(ctx.repoRoot, role.roleYamlPath)}`);\n }\n details.push(`verified ${heartbeatUnit} enabled+active and ${gatewayUnit} ${gatewayDeferred ? \"disabled+inactive\" : \"enabled+active\"}`);\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// BMAD version helpers (shared by bmad.scaffold + bmad.version)\n// ---------------------------------------------------------------------------\n\nconst BMAD_NPM_PACKAGE = \"bmad-method\";\n// Installer and Skillex pack are independently pinned artifacts. Do not derive\n// either lifecycle from the other: the installer is advanced only after its\n// real multi-module configuration contract is verified.\nexport const BMAD_INSTALLER_VERSION = \"6.11.1-next.1\";\n// Legacy BMAD currency checks continue to report the moving next channel; fresh\n// bootstrap uses the exact installer pin above so mutation is reproducible.\nconst BMAD_TARGET_CHANNEL = \"next\";\nconst BMAD_DIST_TAGS_TTL_MS = 60 * 60 * 1000; // 1h \u2014 mirrors the starship BMAD indicator cache\nconst DEFAULT_BMAD_MODULES = [\"bmm\", \"bmb\", \"cis\"];\n\n// Derived from the one public six-CLI support matrix.\nconst BMAD_INSTALL_TOOLS = SUPPORTED_BMAD_TOOLS;\n\ntype ManifestBmadModuleSelection =\n | { status: \"absent\" }\n | { status: \"valid\"; modules: string[] }\n | { status: \"invalid\"; error: string };\n\nfunction manifestBmadModules(repoRoot: string): ManifestBmadModuleSelection {\n const manifestPath = join(repoRoot, \"_bmad\", \"_config\", \"manifest.yaml\");\n const raw = safeReadText(manifestPath);\n if (raw === null) return { status: \"absent\" };\n try {\n const parsed = YAML.parse(raw) as { modules?: unknown } | undefined;\n if (!Array.isArray(parsed?.modules)) {\n return { status: \"invalid\", error: `${manifestPath} must define a modules array` };\n }\n const declared: string[] = [];\n for (const entry of parsed.modules) {\n const name = typeof entry === \"string\"\n ? entry\n : entry && typeof entry === \"object\"\n ? (entry as Record<string, unknown>).name\n : undefined;\n if (typeof name !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(name)) {\n return { status: \"invalid\", error: `${manifestPath} contains an invalid module entry` };\n }\n if (name !== \"core\" && name !== \"custom\") declared.push(name);\n }\n return { status: \"valid\", modules: Array.from(new Set(declared)) };\n } catch (error) {\n return {\n status: \"invalid\",\n error: `Could not parse ${manifestPath}: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n}\n\nfunction configuredBmadModules(repoRoot: string): string[] | undefined {\n const raw = safeReadText(join(repoRoot, \"_bmad\", \"config.toml\"));\n if (raw === null) return undefined;\n const modules = [...raw.matchAll(/^\\[modules\\.([A-Za-z0-9][A-Za-z0-9_-]*)\\]\\s*$/gm)].map((match) => match[1]!);\n return Array.from(new Set(modules));\n}\n\nfunction selectedBmadModules(repoRoot: string): string[] {\n const manifest = manifestBmadModules(repoRoot);\n if (manifest.status === \"valid\") return manifest.modules;\n if (manifest.status === \"invalid\") throw new Error(manifest.error);\n return configuredBmadModules(repoRoot) ?? [...DEFAULT_BMAD_MODULES];\n}\n\nfunction requiredBmadSentinels(repoRoot: string, modules = selectedBmadModules(repoRoot)): string[] {\n return [\n join(\"core\", \"config.yaml\"),\n join(\"config.toml\"),\n join(\"_config\", \"manifest.yaml\"),\n ...modules.map((module) => join(module, \"config.yaml\")),\n ];\n}\n\nfunction canonicalBmadProjectName(repoRoot: string): string {\n const project = readProjectJson({ repoRoot } as Context);\n const declared = typeof project?.project_name === \"string\" ? project.project_name.trim() : \"\";\n return declared || basename(repoRoot);\n}\n\nfunction bmadProjectNameIssues(repoRoot: string): { paths: string[]; details: string[] } {\n const expected = canonicalBmadProjectName(repoRoot);\n const paths: string[] = [];\n const details: string[] = [];\n const configToml = join(repoRoot, \"_bmad\", \"config.toml\");\n const tomlText = safeReadText(configToml);\n const tomlMatch = tomlText?.match(/^project_name\\s*=\\s*\"((?:\\\\.|[^\"\\\\])*)\"\\s*$/m);\n let tomlName: string | undefined;\n if (tomlMatch) {\n try {\n tomlName = JSON.parse(`\"${tomlMatch[1]}\"`) as string;\n } catch {\n tomlName = undefined;\n }\n }\n if (tomlName !== expected) {\n paths.push(configToml);\n details.push(`_bmad/config.toml project_name must be ${JSON.stringify(expected)}`);\n }\n const bmadRoot = join(repoRoot, \"_bmad\");\n if (existsSync(bmadRoot)) {\n // PJAN-82: only the modules BMAD's own manifest declares.\n //\n // This used to walk every directory under _bmad/, which pulled in stale\n // module directories a long-retired installer left behind \u2014 pjangler still\n // carried _bmad/_memory and _bmad/custom from 6.0.0-alpha.23, neither of\n // which has ever had a project_name key. `bmad-method install` does not\n // touch them, so bmad.scaffold reported two unfixable issues on every\n // re-audit and its migration could only ever come back \"partial\". Scoping\n // the check to declared modules makes the rule converge, and an\n // undeclared-but-present directory is bmad.cli-roots' and the installer's\n // business, not this rule's.\n let declared: string[];\n try { declared = selectedBmadModules(repoRoot); }\n catch { declared = readdirSync(bmadRoot); }\n for (const name of new Set(declared)) {\n const configPath = join(bmadRoot, name, \"config.yaml\");\n const raw = safeReadText(configPath);\n if (raw === null) continue;\n let actual: unknown;\n try {\n actual = (YAML.parse(raw) as Record<string, unknown> | undefined)?.project_name;\n } catch {\n actual = undefined;\n }\n if (actual !== expected) {\n paths.push(configPath);\n details.push(`_bmad/${name}/config.yaml project_name must be ${JSON.stringify(expected)}`);\n }\n }\n }\n return { paths: [...new Set(paths)].sort(), details };\n}\n\n/**\n * Remove `bmad-*` skill entries left behind as SYMLINKS by the retired Skillex\n * `bmad` pin, so `bmad-method install` can write its own real directories.\n *\n * Only symlinks are removed, and only under the `bmad-` namespace. A real\n * directory there is either the installer's own output (which it overwrites in\n * place) or something a human put there, and neither is this function's to\n * delete. The pack symlinks point into a per-machine registry cache that no\n * longer even holds the pack, so leaving them shadows the installer with dead\n * links.\n */\nfunction evictLegacyBmadPackState(ctx: Context, changedFiles: string[]): string[] {\n const details: string[] = [];\n const skillDirs = [\n join(ctx.repoRoot, \".agents\", \"skills\"),\n ...SUPPORTED_CLI_ROOTS.map((root) => join(ctx.repoRoot, root, \"skills\")),\n ];\n for (const dir of skillDirs) {\n const dirStat = lstatIfPresent(dir);\n // A CLI root whose `skills` is itself the .agents/skills alias is covered\n // by the canonical directory above; following it would double-count.\n if (!dirStat || dirStat.isSymbolicLink() || !dirStat.isDirectory()) continue;\n let names: string[];\n try {\n names = readdirSync(dir);\n } catch {\n continue;\n }\n for (const name of names) {\n if (!name.startsWith(BMAD_SKILL_NAME_PREFIX)) continue;\n const path = join(dir, name);\n if (!lstatIfPresent(path)?.isSymbolicLink()) continue;\n changedFiles.push(path);\n details.push(`removed retired BMAD pack symlink ${relative(ctx.repoRoot, path)}`);\n if (!ctx.dryRun) unlinkSync(path);\n }\n }\n return details;\n}\n\ninterface BmadInstallerInvocation {\n command: string;\n prefixArgs: string[];\n}\n\nfunction bmadInstallerInvocation(version = BMAD_INSTALLER_VERSION): BmadInstallerInvocation {\n const explicit = process.env.PJ_BMAD_INSTALLER?.trim();\n if (explicit) return { command: resolve(explicit), prefixArgs: [] };\n return {\n command: \"npx\",\n prefixArgs: [\"-y\", `${BMAD_NPM_PACKAGE}@${version}`],\n };\n}\n\nfunction bmadInstallerArgs(repoRoot: string, modules = selectedBmadModules(repoRoot)): string[] {\n // bmad-method treats a missing/falsy --modules under --yes as \"installed +\n // defaults\", which can silently add bmm. The installer-supported explicit\n // no-optional-modules representation is `--modules core`; core is mandatory\n // and the installer does not add defaults when the option is truthy.\n const installerModules = modules.length ? modules.join(\",\") : \"core\";\n return [\n \"install\",\n \"--yes\",\n \"--directory\",\n repoRoot,\n \"--modules\",\n installerModules,\n \"--tools\",\n BMAD_INSTALL_TOOLS.join(\",\"),\n \"--set\",\n `core.project_name=${canonicalBmadProjectName(repoRoot)}`,\n ];\n}\n\nfunction bmadInstallDisplay(\n repoRoot: string,\n modules = selectedBmadModules(repoRoot),\n version = BMAD_INSTALLER_VERSION,\n): string {\n const invocation = bmadInstallerInvocation(version);\n return [invocation.command, ...invocation.prefixArgs, ...bmadInstallerArgs(repoRoot, modules)]\n .join(\" \")\n .replace(BMAD_INSTALL_TOOLS.join(\",\"), \"...\");\n}\n\nexport interface BmadLifecyclePreflightResult {\n ok: boolean;\n error?: string;\n}\n\n/**\n * Prove the exact fresh-project BMAD input before Copier can create a target.\n *\n * That input is now exactly one thing: the pinned `bmad-method` installer,\n * resolved from npm (or an explicit local executable) up front so a create\n * cannot fail half-way through with a scaffolded but BMAD-less directory. The\n * pack preflight that used to sit here proved a Skillex `bmad` pin that no\n * longer exists \u2014 and, once the registry dropped that pack, failed every\n * create on any machine without a warm cache.\n */\nexport function preflightBmadLifecycle(_ctx: Context): BmadLifecyclePreflightResult {\n const invocation = bmadInstallerInvocation();\n const probe = spawnSync(invocation.command, [...invocation.prefixArgs, \"--version\"], {\n encoding: \"utf8\",\n timeout: 30_000,\n });\n if (probe.status !== 0) {\n const detail = String(probe.stderr || probe.stdout || probe.error?.message || \"installer probe failed\").trim();\n return {\n ok: false,\n error: `Pinned BMAD installer ${BMAD_NPM_PACKAGE}@${BMAD_INSTALLER_VERSION} is unavailable: ${detail}`,\n };\n }\n const versionOutput = `${probe.stdout ?? \"\"}\\n${probe.stderr ?? \"\"}`;\n const reportedVersions: string[] = versionOutput.match(/\\b\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?\\b/g) ?? [];\n if (!reportedVersions.includes(BMAD_INSTALLER_VERSION)) {\n return {\n ok: false,\n error: `BMAD installer version mismatch: expected ${BMAD_INSTALLER_VERSION}, received ${versionOutput.trim() || \"no version output\"}`,\n };\n }\n return { ok: true };\n}\n\n/** Run the non-interactive BMAD installer/upgrader against `repoRoot`. */\nfunction runBmadInstall(\n repoRoot: string,\n modules = selectedBmadModules(repoRoot),\n version = BMAD_INSTALLER_VERSION,\n): { ok: boolean; error?: string } {\n const invocation = bmadInstallerInvocation(version);\n const result = spawnSync(invocation.command, [...invocation.prefixArgs, ...bmadInstallerArgs(repoRoot, modules)], { encoding: \"utf8\" });\n if (result.status !== 0) {\n return { ok: false, error: result.stderr || result.error?.message || \"Unknown error\" };\n }\n return { ok: true };\n}\n\n/** Read `installation.version` from a repo's `_bmad/_config/manifest.yaml`. */\nfunction readInstalledBmadVersion(repoRoot: string): string | undefined {\n const raw = safeReadText(join(repoRoot, \"_bmad\", \"_config\", \"manifest.yaml\"));\n if (!raw) return undefined;\n try {\n const parsed = YAML.parse(raw) as { installation?: { version?: unknown } } | undefined;\n const version = parsed?.installation?.version;\n return typeof version === \"string\" && version.trim() ? version.trim() : undefined;\n } catch {\n return undefined;\n }\n}\n\ninterface BmadDistTagsCache {\n fetchedAt: number;\n distTags: Record<string, string>;\n}\n\nfunction bmadCachePath(homeDir: string): string {\n const cacheRoot = process.env.XDG_CACHE_HOME?.trim() || join(homeDir, \".cache\");\n return join(cacheRoot, \"pjangler\", \"bmad-dist-tags.json\");\n}\n\nfunction readBmadDistTagsCache(homeDir: string): BmadDistTagsCache | undefined {\n const raw = safeReadText(bmadCachePath(homeDir));\n if (!raw) return undefined;\n try {\n const parsed = JSON.parse(raw) as BmadDistTagsCache;\n if (parsed && typeof parsed.fetchedAt === \"number\" && parsed.distTags && typeof parsed.distTags === \"object\") {\n return parsed;\n }\n } catch {\n /* fall through to undefined */\n }\n return undefined;\n}\n\nfunction fetchBmadDistTags(): Record<string, string> | undefined {\n const result = spawnSync(\"npm\", [\"view\", BMAD_NPM_PACKAGE, \"dist-tags\", \"--json\"], {\n encoding: \"utf8\",\n timeout: 8000,\n });\n if (result.status !== 0 || !result.stdout.trim()) return undefined;\n try {\n const parsed = JSON.parse(result.stdout) as unknown;\n // `npm view <pkg> dist-tags --json` returns the tags object directly on some\n // npm versions and a one-element array of it on others \u2014 normalize both.\n const obj = Array.isArray(parsed) ? parsed[0] : parsed;\n if (!obj || typeof obj !== \"object\") return undefined;\n const tags: Record<string, string> = {};\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n if (typeof value === \"string\") tags[key] = value;\n }\n return Object.keys(tags).length ? tags : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolve BMAD dist-tags, preferring a <1h cache so `pj audit` stays fast and\n * offline-tolerant. On a cache miss it queries npm and repopulates the cache; if\n * npm is unreachable it falls back to a stale cache (flagged), else `undefined`\n * so the caller degrades to a `skip` finding rather than failing the audit.\n */\nfunction resolveBmadDistTags(homeDir: string): { distTags: Record<string, string>; stale: boolean } | undefined {\n const cached = readBmadDistTagsCache(homeDir);\n if (cached && Date.now() - cached.fetchedAt < BMAD_DIST_TAGS_TTL_MS) {\n return { distTags: cached.distTags, stale: false };\n }\n\n const fetched = fetchBmadDistTags();\n if (fetched) {\n try {\n const path = bmadCachePath(homeDir);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify({ fetchedAt: Date.now(), distTags: fetched } satisfies BmadDistTagsCache, null, 2));\n } catch {\n /* cache write is best-effort */\n }\n return { distTags: fetched, stale: false };\n }\n\n if (cached) return { distTags: cached.distTags, stale: true };\n return undefined;\n}\n\n/**\n * Compare two BMAD versions (semver with an optional `-next.N` prerelease).\n * Returns <0 if a<b, 0 if equal, >0 if a>b. A prerelease sorts below its release\n * (`6.10.1-next.12` < `6.10.1`) per semver precedence rules.\n */\nfunction compareBmadVersions(a: string, b: string): number {\n const parse = (v: string): { nums: [number, number, number]; pre: string } => {\n const [core = \"0\", pre = \"\"] = v.replace(/^v/, \"\").split(\"-\", 2);\n const parts = core.split(\".\");\n const n = (i: number) => parseInt(parts[i] ?? \"0\", 10) || 0;\n return { nums: [n(0), n(1), n(2)], pre };\n };\n const pa = parse(a);\n const pb = parse(b);\n for (let i = 0; i < 3; i++) {\n if (pa.nums[i] !== pb.nums[i]) return pa.nums[i]! - pb.nums[i]!;\n }\n if (pa.pre === pb.pre) return 0;\n if (!pa.pre) return 1; // a is the release, b is a prerelease\n if (!pb.pre) return -1; // a is a prerelease, b is the release\n const ida = pa.pre.split(\".\");\n const idb = pb.pre.split(\".\");\n for (let i = 0; i < Math.max(ida.length, idb.length); i++) {\n const xa = ida[i];\n const xb = idb[i];\n if (xa === undefined) return -1;\n if (xb === undefined) return 1;\n const na = Number(xa);\n const nb = Number(xb);\n if (!Number.isNaN(na) && !Number.isNaN(nb)) {\n if (na !== nb) return na - nb;\n } else if (xa !== xb) {\n return xa < xb ? -1 : 1;\n }\n }\n return 0;\n}\n\n// \u2500\u2500 Hermes singleton-runtime contract \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// One fleet root holds the shared truth (config.yaml, auth.json, .env, skills/).\n// Each agent gets ~/.hermes/profiles/<name>/ as a REAL directory: shared entries\n// symlink up to the root, person-owned entries symlink back into the repo\n// runtime. That split is load-bearing \u2014 Hermes resolves the profile NAME from\n// the unresolved HERMES_HOME path (so the profile dir must not itself be a\n// symlink) and only offers ~/.hermes/auth.json as a shared fallback when\n// HERMES_HOME differs from the fleet root.\n// Fleet-shared, symlinked up to ~/.hermes/<entry>.\n//\n// config.yaml is deliberately NOT here. It used to be, and the symlink was\n// actively harmful: Hermes' atomic_yaml_write does os.replace, which REPLACES a\n// symlink with a regular file, so the first in-agent config write (/model,\n// onboarding, a config migration) silently detached the profile and froze it on\n// a stale copy of the base forever. Symlinking also gave a profile no way to\n// override anything, which is why several profiles were hand-forked into\n// 700-line copies instead.\n//\n// config.yaml is now GENERATED: deep_merge(~/.hermes/config.yaml, <profile>/\n// config.delta.yaml), rendered by hermes-agent-template/scripts/\n// hermes-profile-config.py. The delta is the hand-edited SSOT and is usually\n// empty (identical to base). See PROFILE_RENDER_MARKER below.\nconst SHARED_PROFILE_ENTRIES = [\".env\", \"skills\"] as const;\n\n// Header stamped into every generated profile config.yaml. Its presence is how\n// we tell \"rendered from base+delta\" apart from \"hand-forked copy that has\n// silently drifted\", which look identical on disk otherwise.\nconst PROFILE_RENDER_MARKER = \"GENERATED FILE -- DO NOT EDIT\";\n// Person-owned. SOUL.md is load-bearing: Hermes reads it from HERMES_HOME and\n// seeds the stock \"You are Hermes Agent, created by Nous Research\" default into\n// any fresh profile dir, which would silently shadow each agent's real identity.\nconst OWNED_PROFILE_ENTRIES = [\n \"memories\",\n \"sessions\",\n \"workspace\",\n \"logs\",\n \"cron\",\n \"plans\",\n \"hooks\",\n \"pairing\",\n \"audio_cache\",\n \"image_cache\",\n] as const;\nconst OWNED_PROFILE_FILES = [\"SOUL.md\", \"state.db\", \"kanban.db\"] as const;\n\ninterface SingletonLink {\n path: string;\n target: string;\n ensureTargetDir: boolean;\n}\n\ninterface SingletonPlan {\n fleetRoot: string;\n profileDir: string;\n runtimeDir: string;\n links: SingletonLink[];\n sharedSeeds: { rootPath: string; runtimePath: string }[];\n}\n\nfunction fleetHome(ctx: Context): string {\n return process.env.HERMES_FLEET_HOME || join(ctx.homeDir, \".hermes\");\n}\n\nfunction fleetBinPath(ctx: Context): string {\n const candidates = [\n process.env.HERMES_FLEET_BIN,\n join(fleetHome(ctx), \"hermes-agent\", \".venv\", \"bin\", \"hermes\"),\n join(fleetHome(ctx), \"hermes-agent\", \"venv\", \"bin\", \"hermes\"),\n join(ctx.homeDir, \".local\", \"bin\", \"hermes\"),\n ].filter(Boolean) as string[];\n return candidates.find((candidate) => existsSync(candidate)) ?? \"\";\n}\n\nfunction singletonPlan(ctx: Context, role: RoleMeta): SingletonPlan {\n const fleetRoot = fleetHome(ctx);\n const profileName = role.profileName || role.agentId;\n const profileDir = join(fleetRoot, \"profiles\", profileName);\n const runtimeDir = join(role.roleDir, \"runtime\");\n const links: SingletonLink[] = [];\n for (const entry of SHARED_PROFILE_ENTRIES) {\n links.push({ path: join(profileDir, entry), target: join(fleetRoot, entry), ensureTargetDir: entry === \"skills\" });\n }\n for (const entry of OWNED_PROFILE_ENTRIES) {\n links.push({ path: join(profileDir, entry), target: join(runtimeDir, entry), ensureTargetDir: true });\n }\n for (const entry of OWNED_PROFILE_FILES) {\n links.push({ path: join(profileDir, entry), target: join(runtimeDir, entry), ensureTargetDir: false });\n }\n const sharedSeeds = [\"config.yaml\", \"auth.json\", \".env\"].map((entry) => ({\n rootPath: join(fleetRoot, entry),\n runtimePath: join(runtimeDir, entry),\n }));\n return { fleetRoot, profileDir, runtimeDir, links, sharedSeeds };\n}\n\nfunction profileNameOf(role: RoleMeta): string {\n return role.profileName || role.agentId;\n}\n\n// The base+delta renderer ships in hermes-agent-template, which is a sibling\n// component rather than a pjangler dependency \u2014 so locate it rather than\n// vendoring a second implementation of Hermes' merge semantics.\nfunction profileRendererPath(ctx: Context): string | null {\n const candidates = [\n join(ctx.repoRoot, \"hermes-agent-template\", \"scripts\", \"hermes-profile-config.py\"),\n join(ctx.repoRoot, \"..\", \"hermes-agent-template\", \"scripts\", \"hermes-profile-config.py\"),\n join(homedir(), \"code\", \"33GOD\", \"hermes-agent-template\", \"scripts\", \"hermes-profile-config.py\"),\n join(ctx.pjanglerRoot, \"templates\", \"hermes-agent\", \"scripts\", \"hermes-profile-config.py\"),\n ];\n for (const c of candidates) {\n if (existsSync(c)) return resolve(c);\n }\n return null;\n}\n\n// Per-profile config + memory invariants that replaced the old\n// \"config.yaml is a symlink to the fleet base\" contract.\n//\n// Returns human-readable findings; empty means in parity.\nfunction profileConfigFindings(profileDir: string, profileName: string): string[] {\n const out: string[] = [];\n const cfg = join(profileDir, \"config.yaml\");\n const delta = join(profileDir, \"config.delta.yaml\");\n\n // 1. config.yaml must be a real, generated file \u2014 never a symlink (see\n // SHARED_PROFILE_ENTRIES) and never a hand-forked copy.\n if (!existsSync(cfg)) {\n out.push(`profile config missing (run hermes-profile-config.py render): ${cfg}`);\n } else if (lstatSync(cfg).isSymbolicLink()) {\n out.push(`config.yaml is a symlink \u2014 it detaches on the first Hermes write; render it instead: ${cfg}`);\n } else {\n let head = \"\";\n try {\n head = readFileSync(cfg, \"utf8\").slice(0, 800);\n } catch {\n /* unreadable is reported below via the marker check */\n }\n if (!head.includes(PROFILE_RENDER_MARKER)) {\n out.push(`config.yaml is not a rendered artifact (missing generated header) \u2014 likely a hand-forked copy that will drift: ${cfg}`);\n }\n }\n\n // 2. The delta is the hand-edited source of truth. Absent means \"no overrides\",\n // which is valid \u2014 but the FILE must exist so the profile is demonstrably\n // under inheritance rather than merely un-migrated.\n if (!existsSync(delta)) {\n out.push(`config.delta.yaml missing \u2014 profile is not under base+delta inheritance: ${delta}`);\n } else if (lstatSync(delta).isSymbolicLink()) {\n out.push(`config.delta.yaml must be a real file, not a symlink: ${delta}`);\n }\n\n // 3. Identity-memory bank must be pinned explicitly. Relying on\n // bank_id_template: agent-{profile} is unsafe: {profile} resolves through\n // get_active_profile_name(), which calls Path.resolve() on HERMES_HOME and\n // requires a lowercase id directly under profiles/. A symlinked profile dir\n // or an uppercase name silently yields the literal \"custom\", merging several\n // agents' PRIVATE memory into one shared bank.\n const memCfg = join(profileDir, \"hindsight\", \"config.json\");\n const wantBank = `agent-${profileName}`;\n if (!existsSync(memCfg)) {\n out.push(`identity-memory bank not pinned (expected bank_id \"${wantBank}\"): ${memCfg}`);\n } else {\n try {\n const parsed = JSON.parse(readFileSync(memCfg, \"utf8\")) as Record<string, unknown>;\n const got = typeof parsed.bank_id === \"string\" ? parsed.bank_id : \"\";\n if (got !== wantBank) {\n out.push(`identity-memory bank_id is ${got ? `\"${got}\"` : \"unset\"}, expected \"${wantBank}\": ${memCfg}`);\n }\n } catch {\n out.push(`identity-memory pin is unparseable JSON: ${memCfg}`);\n }\n }\n return out;\n}\n\nfunction isDanglingLink(path: string): boolean {\n try {\n return lstatSync(path).isSymbolicLink() && !existsSync(path);\n } catch {\n return false;\n }\n}\n\nfunction linkState(path: string, target: string): \"ok\" | \"missing\" | \"not-a-symlink\" | \"wrong-target\" {\n let stat;\n try {\n stat = lstatSync(path);\n } catch {\n return \"missing\";\n }\n if (!stat.isSymbolicLink()) return \"not-a-symlink\";\n try {\n return readlinkSync(path) === target ? \"ok\" : \"wrong-target\";\n } catch {\n return \"wrong-target\";\n }\n}\n\nfunction realOrSelf(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n\n// heartbeat.SERVICE (not just the .timer) also carries Environment= lines, so\n// omitting it leaves a stale HERMES_HOME and the dead HERMES_OAUTH_FILE behind.\nfunction profileUnits(role: RoleMeta): string[] {\n return [\n `hermes-${role.agentId}-gateway.service`,\n `hermes-${role.agentId}-heartbeat.service`,\n `hermes-${role.agentId}-heartbeat.timer`,\n `hermes-${role.agentId}-checkpoint.service`,\n ];\n}\n\nfunction readRegistry(registryPath: string): Record<string, unknown> | null {\n const raw = safeReadText(registryPath);\n if (raw === null) return null;\n try {\n const doc = YAML.parse(raw) as Record<string, unknown>;\n return (doc?.agents ?? {}) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\nfunction declaredAgentIds(repoRoot: string): string[] {\n return declaredAgentEntries(repoRoot).map(([agentId]) => agentId);\n}\n\nfunction declaredAgentEntries(repoRoot: string): [string, Record<string, unknown>][] {\n const raw = safeReadText(join(repoRoot, \".project.json\"));\n if (raw === null) return [];\n try {\n const doc = JSON.parse(raw) as { agents?: Record<string, unknown> };\n return Object.entries(doc.agents ?? {}).map(([agentId, entry]) => [agentId, (entry ?? {}) as Record<string, unknown>]);\n } catch {\n return [];\n }\n}\n\n// Registry entries this repo actually owns. role_dir is\n// <project>/agents/hermes/<role>, so the project root is three levels up. A\n// prefix match on repoRoot would wrongly claim nested submodule agents\n// (33GOD contains bloodbank, candystore, candybar, holocene...).\nfunction ownedRegistryEntries(\n registry: Record<string, unknown>,\n repoRoot: string,\n): [string, Record<string, unknown>][] {\n const want = realOrSelf(repoRoot);\n const owned: [string, Record<string, unknown>][] = [];\n for (const [agentId, raw] of Object.entries(registry)) {\n const entry = (raw ?? {}) as Record<string, unknown>;\n const roleDir = String(entry.role_dir ?? \"\");\n if (!roleDir) continue;\n if (realOrSelf(dirname(dirname(dirname(roleDir)))) !== want) continue;\n owned.push([agentId, entry]);\n }\n return owned;\n}\n\ninterface UnprovisionedRoleAgent {\n agentId: string;\n roleDir: string;\n sources: (\"registry\" | \".project.json\")[];\n}\n\nfunction unprovisionedRoleAgents(\n registry: Record<string, unknown>,\n repoRoot: string,\n canonical: Set<string>,\n): UnprovisionedRoleAgent[] {\n const blockers = new Map<string, { roleDir: string; sources: Set<\"registry\" | \".project.json\"> }>();\n const record = (agentId: string, roleDir: string, source: \"registry\" | \".project.json\") => {\n const current = blockers.get(agentId) ?? { roleDir, sources: new Set<\"registry\" | \".project.json\">() };\n if (!current.roleDir && roleDir) current.roleDir = roleDir;\n current.sources.add(source);\n blockers.set(agentId, current);\n };\n\n for (const [agentId, entry] of ownedRegistryEntries(registry, repoRoot)) {\n if (canonical.has(agentId)) continue;\n // The registry stores role_dir absolute; `resolve` leaves those untouched,\n // so the same repo-relative-aware predicate serves both sources.\n const roleDir = String(entry.role_dir ?? \"\");\n if (declaredRoleIsUnprovisioned(repoRoot, roleDir)) record(agentId, roleDir, \"registry\");\n }\n for (const [agentId, entry] of declaredAgentEntries(repoRoot)) {\n if (canonical.has(agentId)) continue;\n const configured = String(entry.role_dir ?? \"\");\n const roleDir = configured ? resolve(repoRoot, configured) : \"\";\n if (declaredRoleIsUnprovisioned(repoRoot, configured)) record(agentId, roleDir, \".project.json\");\n }\n\n return [...blockers.entries()].map(([agentId, value]) => ({\n agentId,\n roleDir: value.roleDir,\n sources: [...value.sources],\n }));\n}\n\n// Drop a duplicate agent id from .project.json so the next provisioning run\n// does not resurrect the registry entry we just removed.\nfunction dropDeclaredAgent(ctx: Context, agentId: string, changedFiles: string[], details: string[]): void {\n const path = join(ctx.repoRoot, \".project.json\");\n const raw = safeReadText(path);\n if (raw === null) return;\n let doc: { agents?: Record<string, unknown> };\n try {\n doc = JSON.parse(raw) as { agents?: Record<string, unknown> };\n } catch {\n return;\n }\n if (!doc.agents || !(agentId in doc.agents)) return;\n delete doc.agents[agentId];\n details.push(`drop agent \"${agentId}\" from .project.json`);\n changedFiles.push(path);\n if (!ctx.dryRun) writeText(path, `${JSON.stringify(doc, null, 2)}\\n`);\n}\n\n// The one correct right-hand side for HERMES_HOME: the named profile dir,\n// either as the canonical expression or already expanded to a literal path.\nfunction isProfileHomeExpr(assigned: string): boolean {\n const bare = assigned.replace(/^[\"']|[\"']$/g, \"\");\n return bare === \"$FLEET_HOME/profiles/$PROFILE_NAME\"\n || /^\\$\\{?HERMES_FLEET_HOME.*\\}?\\/profiles\\//.test(bare)\n || /\\/\\.hermes\\/profiles\\/[^/]+$/.test(bare);\n}\n\nfunction rewriteLauncher(text: string, profileName?: string): string {\n let next = text;\n const assigned = /^HERMES_HOME=(.*)$/m.exec(next)?.[1]?.trim();\n if (assigned !== undefined && !isProfileHomeExpr(assigned)) {\n // A bare substitution would leave $FLEET_HOME/$PROFILE_NAME undefined, and\n // these launchers run under `set -u`. Emit the definitions with it, and\n // keep the old value as RUNTIME_HOME \u2014 the provisioning guard still needs\n // the repo runtime path.\n const name = profileName ? `\\${HERMES_PROFILE_NAME:-${profileName}}` : \"${HERMES_PROFILE_NAME:-$(basename \\\"$ROLE_DIR\\\")}\";\n next = next.replace(\n /^HERMES_HOME=(.*)$/m,\n [\n `RUNTIME_HOME=$1`,\n `FLEET_HOME=\"\\${HERMES_FLEET_HOME:-$HOME/.hermes}\"`,\n `PROFILE_NAME=\"${name}\"`,\n `# Singleton-runtime contract: HERMES_HOME MUST be the named profile dir.`,\n `HERMES_HOME=\"$FLEET_HOME/profiles/$PROFILE_NAME\"`,\n ].join(\"\\n\"),\n );\n // The provisioning guard referenced HERMES_HOME when it meant the runtime.\n next = next.replace(\n /if \\[\\[ ! -d \"\\$HERMES_HOME\" \\]\\]; then\\n(\\s*)echo \"hermes: local runtime not provisioned at \\$HERMES_HOME\"/,\n 'if [[ ! -d \"$RUNTIME_HOME\" ]]; then\\n$1echo \"hermes: local runtime not provisioned at $RUNTIME_HOME\"',\n );\n }\n next = next.replace(/^HERMES_OAUTH_FILE=.*\\n/m, \"\");\n next = next.replace(/\\s*HERMES_OAUTH_FILE=\"\\$HERMES_OAUTH_FILE\"/g, \"\");\n next = next.replace(/^.*\\/home\\/delorenj\\/code\\/hermes-agent\\/\\.venv\\/bin\\/hermes.*$/m, (line) =>\n line.replace(\"/home/delorenj/code/hermes-agent/.venv/bin/hermes\", \"$HOME/.hermes/hermes-agent/.venv/bin/hermes\"),\n );\n return next;\n}\n\n// ============================================================================\n// Momo lifecycle-plane readiness profile\n// ============================================================================\n\nexport interface MomoReadinessFinding {\n section: string;\n status: RuleStatus;\n summary: string;\n details: string[];\n}\n\nexport interface MomoReadinessReport {\n ready: boolean;\n profile: \"momo-lifecycle-plane\";\n repo: string;\n live: boolean;\n auditedAt: string;\n findings: MomoReadinessFinding[];\n}\n\ninterface MomoProviderCandidate {\n path: string;\n kind: \"shell\" | \"python\" | \"unknown\";\n}\n\nfunction discoverMomoProviderCandidates(repoRoot: string): MomoProviderCandidate[] {\n const candidates: MomoProviderCandidate[] = [];\n const roleDirs: string[] = [];\n const hermesDir = join(repoRoot, \"agents\", \"hermes\");\n if (existsSync(hermesDir)) {\n for (const entry of readdirSync(hermesDir, { withFileTypes: true })) {\n if (entry.isDirectory()) roleDirs.push(join(hermesDir, entry.name));\n }\n }\n for (const roleDir of roleDirs) {\n for (const name of [\"momo\", \"provider\", \"momo-provider\"]) {\n const path = join(roleDir, name);\n if (existsSync(path)) {\n const kind = path.endsWith(\".py\") ? \"python\" : \"shell\";\n candidates.push({ path, kind });\n }\n }\n // Also accept any executable file named momo* in the role dir.\n if (existsSync(roleDir)) {\n for (const entry of readdirSync(roleDir, { withFileTypes: true })) {\n if (!entry.isFile()) continue;\n if (!entry.name.startsWith(\"momo\")) continue;\n const path = join(roleDir, entry.name);\n try {\n if (lstatSync(path).mode & 0o111) {\n const kind = entry.name.endsWith(\".py\") ? \"python\" : \"shell\";\n if (!candidates.some((c) => c.path === path)) candidates.push({ path, kind });\n }\n } catch {\n /* ignore */\n }\n }\n }\n }\n for (const rel of [\".mise/scripts/momo-provider.sh\", \".scripts/momo-provider.sh\", \"momo\"]) {\n const path = join(repoRoot, rel);\n if (existsSync(path)) {\n const kind = path.endsWith(\".py\") ? \"python\" : \"shell\";\n if (!candidates.some((c) => c.path === path)) candidates.push({ path, kind });\n }\n }\n return candidates;\n}\n\nfunction firstMomoProvider(repoRoot: string): MomoProviderCandidate | undefined {\n return discoverMomoProviderCandidates(repoRoot)[0];\n}\n\nfunction checkProviderSyntax(candidate: MomoProviderCandidate): { ok: boolean; detail?: string } {\n if (candidate.kind === \"python\") {\n const result = spawnSync(\"python3\", [\"-m\", \"py_compile\", candidate.path], { encoding: \"utf8\" });\n if (result.status !== 0) {\n return { ok: false, detail: `python3 -m py_compile failed: ${result.stderr.trim() || result.stdout.trim() || \"syntax error\"}` };\n }\n return { ok: true };\n }\n if (candidate.kind === \"shell\") {\n const result = spawnSync(\"bash\", [\"-n\", candidate.path], { encoding: \"utf8\" });\n if (result.status !== 0) {\n return { ok: false, detail: `bash -n failed: ${result.stderr.trim() || result.stdout.trim() || \"syntax error\"}` };\n }\n return { ok: true };\n }\n return { ok: true };\n}\n\nfunction runProviderLocalSmoke(repoRoot: string, candidate: MomoProviderCandidate): { ok: boolean; detail?: string } {\n const result = spawnSync(candidate.path, [\"--help\"], { cwd: repoRoot, encoding: \"utf8\" });\n if (result.status !== 0) {\n return { ok: false, detail: `${relative(repoRoot, candidate.path)} --help exited ${result.status}: ${result.stderr.trim() || result.stdout.trim()}` };\n }\n return { ok: true };\n}\n\nfunction attemptPlaneStateMapping(repoRoot: string): { ok: boolean; detail?: string } {\n const project = tryParseJson(safeReadText(join(repoRoot, \".project.json\")));\n const tp = (project?.ticket_provider as Record<string, unknown>) ?? {};\n if (!tp.board_id) return { ok: false, detail: \"ticket_provider.board_id missing; cannot map Plane states\" };\n // The live mapping is credential-bearing; a real run would query Plane here.\n // In this deterministic interface we only verify the binding is present and\n // report that the attempt was made. Returning ok:false with a stable detail\n // keeps the output deterministic when credentials are absent.\n return { ok: false, detail: `Plane state mapping attempted for board ${tp.board_id} (credentials required for full mapping)` };\n}\n\nfunction attemptNestedAdapterSmoke(repoRoot: string, candidate: MomoProviderCandidate): { ok: boolean; detail?: string } {\n const result = spawnSync(candidate.path, [\"--smoke\", \"nested\"], { cwd: repoRoot, encoding: \"utf8\" });\n if (result.status !== 0) {\n return { ok: false, detail: `${relative(repoRoot, candidate.path)} --smoke nested exited ${result.status}: ${result.stderr.trim() || result.stdout.trim()}` };\n }\n return { ok: true };\n}\n\nfunction momoLifecycleFinding(\n section: string,\n status: RuleStatus,\n summary: string,\n details: string[] = []\n): MomoReadinessFinding {\n return { section, status, summary, details };\n}\n\nfunction auditManifestRoleConsistency(repoRoot: string): MomoReadinessFinding {\n const details: string[] = [];\n const projectPath = join(repoRoot, \".project.json\");\n if (!existsSync(projectPath)) {\n return momoLifecycleFinding(\"manifest-role-consistency\", \"fail\", \".project.json missing\", [\".project.json missing\"]);\n }\n const project = tryParseJson(safeReadText(projectPath));\n if (!project) {\n return momoLifecycleFinding(\"manifest-role-consistency\", \"fail\", \".project.json is invalid JSON\", [\".project.json is invalid JSON\"]);\n }\n const agents = (project.agents as Record<string, { role?: string; role_dir?: string }> | undefined) ?? {};\n const discovered = discoverRoles(repoRoot);\n const discoveredByAgentId = new Map(discovered.map((role) => [role.agentId, role]));\n const discoveredByDir = new Map(discovered.map((role) => [role.roleDir, role]));\n\n for (const [agentId, agent] of Object.entries(agents)) {\n if (!agent.role_dir) {\n details.push(`agents.${agentId}.role_dir missing`);\n continue;\n }\n const roleDir = resolve(repoRoot, agent.role_dir);\n if (!existsSync(roleDir)) {\n details.push(`agents.${agentId}.role_dir does not exist: ${agent.role_dir}`);\n continue;\n }\n const roleYaml = join(roleDir, \"role.yaml\");\n if (!existsSync(roleYaml)) {\n details.push(`agents.${agentId} role.yaml missing at ${agent.role_dir}/role.yaml`);\n continue;\n }\n const discoveredRole = discoveredByDir.get(roleDir);\n if (!discoveredRole) {\n details.push(`agents.${agentId} role.yaml at ${agent.role_dir} could not be parsed`);\n continue;\n }\n if (discoveredRole.agentId !== agentId) {\n details.push(`agents.${agentId} role.yaml agent_id mismatch: ${discoveredRole.agentId}`);\n }\n if (discoveredRole.role !== agent.role) {\n details.push(`agents.${agentId} role.yaml role mismatch: expected ${agent.role}, got ${discoveredRole.role}`);\n }\n }\n\n for (const role of discovered) {\n if (!role.agentId) {\n details.push(`role.yaml at ${relative(repoRoot, role.roleYamlPath)} missing agent_id`);\n continue;\n }\n if (!(role.agentId in agents)) {\n details.push(`role.yaml declares unregistered agent_id: ${role.agentId}`);\n }\n }\n\n if (Object.keys(agents).length === 0) {\n details.push(\"no agents declared in .project.json\");\n }\n\n return details.length === 0\n ? momoLifecycleFinding(\"manifest-role-consistency\", \"pass\", \"manifest and role declarations are consistent\")\n : momoLifecycleFinding(\"manifest-role-consistency\", \"fail\", `${details.length} manifest/role consistency issue(s)`, details);\n}\n\nfunction hasAnyLifecycleScript(repoRoot: string): boolean {\n const patterns = [\n \".mise/scripts/lifecycle\",\n \".scripts/lifecycle\",\n \"agents/hermes/*/lifecycle\",\n \"agents/hermes/*/.scripts/lifecycle\",\n \"agents/hermes/*/.scripts/migrate\",\n \".mise/tasks/lifecycle\",\n ];\n for (const pattern of patterns) {\n if (pattern.includes(\"*\")) {\n const [prefix, suffix] = pattern.split(\"*\") as [string, string];\n const base = join(repoRoot, prefix);\n if (!existsSync(base)) continue;\n for (const entry of readdirSync(base, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const candidate = join(base, entry.name, suffix);\n if (existsSync(candidate)) return true;\n // Prefix-match the leaf, matching both the advertised pattern\n // (\"<role>/.scripts/lifecycle*\") and the non-wildcard branch below.\n // Requiring an extensionless `lifecycle` made the obvious filename\n // (lifecycle.sh) fail against a message saying it should work.\n const parent = dirname(candidate);\n const stem = basename(candidate);\n if (!existsSync(parent)) continue;\n for (const sibling of readdirSync(parent, { withFileTypes: true })) {\n if (sibling.isFile() && sibling.name.startsWith(stem)) return true;\n }\n }\n } else {\n const base = join(repoRoot, pattern);\n if (existsSync(base)) return true;\n // Also accept any file starting with the base path.\n const parent = dirname(base);\n const prefix = basename(base);\n if (existsSync(parent)) {\n for (const entry of readdirSync(parent, { withFileTypes: true })) {\n if (entry.name.startsWith(prefix)) return true;\n }\n }\n }\n }\n return false;\n}\n\nfunction auditLifecycleScripts(repoRoot: string): MomoReadinessFinding {\n if (hasAnyLifecycleScript(repoRoot)) {\n return momoLifecycleFinding(\"lifecycle-scripts\", \"pass\", \"lifecycle scripts present\");\n }\n return momoLifecycleFinding(\n \"lifecycle-scripts\",\n \"fail\",\n \"lifecycle scripts missing\",\n [\"expected one of: .mise/scripts/lifecycle*, .scripts/lifecycle*, agents/hermes/<role>/lifecycle*, agents/hermes/<role>/.scripts/lifecycle*\"]\n );\n}\n\nfunction hasAnySentinelScript(repoRoot: string): boolean {\n const patterns = [\n \"agents/hermes/*/.scripts/checkpoint.sh\",\n \"agents/hermes/*/.scripts/heartbeat.sh\",\n \"agents/hermes/*/.scripts/sentinel\",\n \"agents/hermes/*/sentinel.prompt.md\",\n \".scripts/sentinel\",\n ];\n for (const pattern of patterns) {\n if (pattern.includes(\"*\")) {\n const [prefix, suffix] = pattern.split(\"*\") as [string, string];\n const base = join(repoRoot, prefix);\n if (!existsSync(base)) continue;\n for (const entry of readdirSync(base, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const candidate = join(base, entry.name, suffix);\n if (existsSync(candidate)) return true;\n // Prefix-match the leaf, matching both the advertised pattern\n // (\"<role>/.scripts/lifecycle*\") and the non-wildcard branch below.\n // Requiring an extensionless `lifecycle` made the obvious filename\n // (lifecycle.sh) fail against a message saying it should work.\n const parent = dirname(candidate);\n const stem = basename(candidate);\n if (!existsSync(parent)) continue;\n for (const sibling of readdirSync(parent, { withFileTypes: true })) {\n if (sibling.isFile() && sibling.name.startsWith(stem)) return true;\n }\n }\n } else {\n const base = join(repoRoot, pattern);\n if (existsSync(base)) return true;\n const parent = dirname(base);\n const prefix = basename(base);\n if (existsSync(parent)) {\n for (const entry of readdirSync(parent, { withFileTypes: true })) {\n if (entry.name.startsWith(prefix)) return true;\n }\n }\n }\n }\n return false;\n}\n\nfunction auditSentinelScripts(repoRoot: string): MomoReadinessFinding {\n if (hasAnySentinelScript(repoRoot)) {\n return momoLifecycleFinding(\"sentinel-scripts\", \"pass\", \"sentinel scripts present\");\n }\n return momoLifecycleFinding(\n \"sentinel-scripts\",\n \"fail\",\n \"sentinel scripts missing\",\n [\"expected one of: agents/hermes/<role>/.scripts/{checkpoint.sh,heartbeat.sh,sentinel*}, agents/hermes/<role>/sentinel.prompt.md, .scripts/sentinel*\"]\n );\n}\n\nfunction auditExecutableProvider(repoRoot: string): MomoReadinessFinding {\n const candidates = discoverMomoProviderCandidates(repoRoot);\n if (candidates.length === 0) {\n return momoLifecycleFinding(\n \"executable-provider\",\n \"fail\",\n \"executable provider dispatcher missing\",\n [\"expected an executable agents/hermes/<role>/momo, agents/hermes/<role>/provider, or project-level momo-provider script\"]\n );\n }\n const details = candidates.map((c) => relative(repoRoot, c.path));\n return momoLifecycleFinding(\"executable-provider\", \"pass\", `${candidates.length} provider dispatcher candidate(s)`, details);\n}\n\nfunction auditProviderSyntax(repoRoot: string): MomoReadinessFinding {\n const candidate = firstMomoProvider(repoRoot);\n if (!candidate) {\n return momoLifecycleFinding(\"provider-syntax\", \"skip\", \"no provider dispatcher to validate\");\n }\n const syntax = checkProviderSyntax(candidate);\n if (!syntax.ok) {\n return momoLifecycleFinding(\"provider-syntax\", \"fail\", `${relative(repoRoot, candidate.path)} has syntax errors`, [syntax.detail ?? \"syntax check failed\"]);\n }\n return momoLifecycleFinding(\"provider-syntax\", \"pass\", `${relative(repoRoot, candidate.path)} syntax OK`);\n}\n\nfunction auditPlaneBinding(repoRoot: string): MomoReadinessFinding {\n const details: string[] = [];\n const project = tryParseJson(safeReadText(join(repoRoot, \".project.json\")));\n const tp = (project?.ticket_provider as Record<string, unknown>) ?? {};\n for (const key of [\"type\", \"workspace\", \"identifier\", \"board_id\"]) {\n if (!tp[key]) details.push(`ticket_provider.${key} missing`);\n }\n const discovered = discoverRoles(repoRoot);\n for (const role of discovered) {\n if (!role.ticketProviderBoardId && !role.ticketProviderIdentifier) {\n details.push(`${relative(repoRoot, role.roleYamlPath)} missing ticket_provider/plane binding`);\n }\n }\n if (details.length === 0) {\n return momoLifecycleFinding(\"plane-binding\", \"pass\", \"Plane ticket provider binding present\");\n }\n return momoLifecycleFinding(\"plane-binding\", \"fail\", `${details.length} Plane binding issue(s)`, details);\n}\n\nfunction auditPlaneStateMapping(repoRoot: string, live: boolean): MomoReadinessFinding {\n if (!live) {\n return momoLifecycleFinding(\"plane-state-mapping\", \"skip\", \"live check skipped (pass --live)\", [\"requires --live\"]);\n }\n const result = attemptPlaneStateMapping(repoRoot);\n if (!result.ok) {\n return momoLifecycleFinding(\"plane-state-mapping\", \"warn\", \"Plane state mapping attempted but incomplete\", [result.detail ?? \"incomplete\"]);\n }\n return momoLifecycleFinding(\"plane-state-mapping\", \"pass\", \"Plane state mapping verified\");\n}\n\nfunction auditRootAdapterSmoke(repoRoot: string): MomoReadinessFinding {\n const candidate = firstMomoProvider(repoRoot);\n if (!candidate) {\n return momoLifecycleFinding(\"root-adapter-smoke\", \"skip\", \"no provider dispatcher to smoke-test\");\n }\n const smoke = runProviderLocalSmoke(repoRoot, candidate);\n if (!smoke.ok) {\n return momoLifecycleFinding(\"root-adapter-smoke\", \"fail\", \"root adapter smoke test failed\", [smoke.detail ?? \"unknown error\"]);\n }\n return momoLifecycleFinding(\"root-adapter-smoke\", \"pass\", \"root adapter smoke test passed\");\n}\n\nfunction auditNestedAdapterSmoke(repoRoot: string, live: boolean): MomoReadinessFinding {\n const candidate = firstMomoProvider(repoRoot);\n if (!candidate) {\n return momoLifecycleFinding(\"nested-adapter-smoke\", \"skip\", \"no provider dispatcher to smoke-test\");\n }\n if (!live) {\n return momoLifecycleFinding(\"nested-adapter-smoke\", \"skip\", \"live check skipped (pass --live)\", [\"requires --live\"]);\n }\n const smoke = attemptNestedAdapterSmoke(repoRoot, candidate);\n if (!smoke.ok) {\n return momoLifecycleFinding(\"nested-adapter-smoke\", \"warn\", \"nested adapter smoke attempted but incomplete\", [smoke.detail ?? \"unknown error\"]);\n }\n return momoLifecycleFinding(\"nested-adapter-smoke\", \"pass\", \"nested adapter smoke test passed\");\n}\n\nfunction runMomoLifecyclePlaneAudit(repoRoot: string, live = false): MomoReadinessReport {\n const findings: MomoReadinessFinding[] = [\n auditManifestRoleConsistency(repoRoot),\n auditLifecycleScripts(repoRoot),\n auditSentinelScripts(repoRoot),\n auditExecutableProvider(repoRoot),\n auditProviderSyntax(repoRoot),\n auditPlaneBinding(repoRoot),\n auditPlaneStateMapping(repoRoot, live),\n auditRootAdapterSmoke(repoRoot),\n auditNestedAdapterSmoke(repoRoot, live),\n ];\n const ready = findings.every((f) => f.status === \"pass\" || f.status === \"skip\");\n return {\n ready,\n profile: \"momo-lifecycle-plane\",\n repo: resolve(repoRoot),\n live,\n auditedAt: new Date().toISOString(),\n findings,\n };\n}\n\nexport function runMomoReadinessAudit(repoRoot?: string, live = false): MomoReadinessReport {\n return runMomoLifecyclePlaneAudit(resolve(repoRoot ?? process.cwd()), live);\n}\n\nexport function formatMomoReadinessReport(report: MomoReadinessReport): string {\n const sectionWidth = report.findings.reduce((max, f) => Math.max(max, f.section.length), 0);\n const overall = report.ready\n ? `${green(glyph.pass)} ${bold(\"Momo readiness: ready\")}`\n : `${red(glyph.fail)} ${bold(\"Momo readiness: not ready\")}`;\n const lines = [\"\", ` ${overall} ${dim(glyph.dot)} ${dim(report.profile)}`, ` ${dim(report.repo)} ${dim(glyph.dot)} ${dim(report.auditedAt)}`, \"\"];\n for (const finding of report.findings) {\n const style = statusStyle(finding.status);\n lines.push(` ${style.color(style.glyph)} ${style.color(finding.section.padEnd(sectionWidth))} ${finding.summary}`);\n for (const detail of finding.details) lines.push(` ${dim(glyph.arrow)} ${dim(detail)}`);\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\ninterface OpReferenceOccurrence {\n line: number;\n value: string;\n commentOnly: boolean;\n}\n\nfunction isValidOpReference(value: string): boolean {\n if (!value.startsWith(\"op://\") || /[\\[\\]{}<>]/.test(value)) return false;\n const withoutScheme = value.slice(\"op://\".length);\n const fragmentIndex = withoutScheme.indexOf(\"#\");\n if (fragmentIndex >= 0) return false;\n const queryIndex = withoutScheme.indexOf(\"?\");\n const pathPart = queryIndex >= 0 ? withoutScheme.slice(0, queryIndex) : withoutScheme;\n const queryPart = queryIndex >= 0 ? withoutScheme.slice(queryIndex + 1) : \"\";\n const parts = pathPart.split(\"/\");\n if (parts.length < 3 || parts.length > 4 || parts.some((part) => !part)) return false;\n try {\n for (const part of parts) decodeURIComponent(part);\n } catch {\n return false;\n }\n if (queryIndex >= 0 && !/^attribute=[A-Za-z0-9._~-]+$/.test(queryPart)) return false;\n return true;\n}\n\n/**\n * PJAN-84: a 1Password item name may contain a space, and `op` accepts it.\n *\n * Verified against the real CLI: `op inject` resolves\n * `T=op://DeLoSecrets/DeLoHQ Bot/token` bare, double-quoted, and single-quoted.\n * Percent-encoding is NOT accepted \u2014 `%20` is decoded and then split, so the\n * encoded form fails where the literal space works.\n *\n * The scanner below was whitespace-delimited, so it read that value as\n * `op://DeLoSecrets/DeLoHQ`, counted two segments, and reported \"Malformed\n * active op:// reference(s)\". holocene's env migration was blocked on a\n * reference that resolves correctly, and the message told the operator to\n * repair a file that was already right.\n *\n * An assignment's value is therefore taken whole: everything after the first\n * `=`, trimmed, with matching surrounding quotes removed. A trailing\n * space-hash comment is stripped only from an UNQUOTED value, which is the\n * dotenv convention; a `#` still inside the reference after that remains\n * invalid, as before. References appearing in prose or mid-line keep the old\n * whitespace-delimited scan, because there is no value boundary to use.\n */\nfunction assignmentOpReference(line: string): string | null {\n const separator = line.indexOf(\"=\");\n if (separator < 0) return null;\n const key = line.slice(0, separator).trim().replace(/^export\\s+/u, \"\");\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key)) return null;\n let value = line.slice(separator + 1).trim();\n const quoted = (value.startsWith('\"') && value.endsWith('\"') && value.length > 1)\n || (value.startsWith(\"'\") && value.endsWith(\"'\") && value.length > 1);\n if (quoted) value = value.slice(1, -1);\n else value = value.replace(/\\s+#.*$/u, \"\").trim();\n return value.startsWith(\"op://\") ? value : null;\n}\n\nfunction malformedOpReferences(text: string): OpReferenceOccurrence[] {\n const occurrences: OpReferenceOccurrence[] = [];\n const lines = text.split(\"\\n\");\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]!;\n const commentOnly = line.trimStart().startsWith(\"#\");\n const assigned = commentOnly ? null : assignmentOpReference(line);\n if (assigned !== null) {\n if (!isValidOpReference(assigned)) occurrences.push({ line: index + 1, value: assigned, commentOnly: false });\n continue;\n }\n for (const match of line.matchAll(/op:\\/\\/[^\\s\"'`]+/g)) {\n const value = match[0];\n if (!isValidOpReference(value)) {\n occurrences.push({ line: index + 1, value, commentOnly });\n }\n }\n }\n return occurrences;\n}\n\nfunction removeMalformedCommentOpReferences(text: string): { text: string; changed: boolean } {\n let changed = false;\n const lines = text.split(\"\\n\").map((line) => {\n if (!line.trimStart().startsWith(\"#\")) return line;\n return line.replace(/op:\\/\\/[^\\s\"'`]+/g, (value) => {\n if (isValidOpReference(value)) return value;\n changed = true;\n return \"<invalid 1Password reference removed by pjangler>\";\n });\n });\n return { text: lines.join(\"\\n\"), changed };\n}\n\nconst UNSUPPORTED_BMAD_ROOTS = {\n \".agent\": \"antigravity\",\n \".adal\": \"adal\",\n \".bob\": \"bob\",\n \".cline\": \"cline\",\n \".codebuddy\": \"codebuddy\",\n \".codewhale\": \"codewhale\",\n \".cortex\": \"cortex\",\n \".cursor\": \"cursor\",\n \".factory\": \"droid\",\n \".firebender\": \"firebender\",\n \".iflow\": \"iflow\",\n \".junie\": \"junie\",\n \".kiro\": \"kiro\",\n \".kode\": \"kode\",\n \".neovate\": \"neovate\",\n \".ona\": \"ona\",\n \".qoder\": \"qoder\",\n \".qwen\": \"qwen\",\n \".trae\": \"trae\",\n \".zcode\": \"zcode\",\n \".zencoder\": \"zencoder\",\n} as const;\n\nfunction parseCsvRows(text: string): string[][] {\n const rows: string[][] = [];\n let row: string[] = [];\n let field = \"\";\n let quoted = false;\n for (let index = 0; index < text.length; index++) {\n const char = text[index]!;\n if (quoted) {\n if (char === '\"' && text[index + 1] === '\"') {\n field += '\"';\n index++;\n } else if (char === '\"') {\n quoted = false;\n } else {\n field += char;\n }\n } else if (char === '\"') {\n quoted = true;\n } else if (char === \",\") {\n row.push(field);\n field = \"\";\n } else if (char === \"\\n\") {\n row.push(field.replace(/\\r$/, \"\"));\n rows.push(row);\n row = [];\n field = \"\";\n } else {\n field += char;\n }\n }\n if (field || row.length) {\n row.push(field.replace(/\\r$/, \"\"));\n rows.push(row);\n }\n return rows;\n}\n\nfunction csvObjects(text: string): Record<string, string>[] {\n const [headers, ...rows] = parseCsvRows(text);\n if (!headers?.length) return [];\n return rows\n .filter((row) => row.some(Boolean))\n .map((row) => Object.fromEntries(headers.map((header, index) => [header, row[index] ?? \"\"])));\n}\n\nfunction installedBmadTools(repoRoot: string): Set<string> {\n const raw = safeReadText(join(repoRoot, \"_bmad\", \"_config\", \"manifest.yaml\"));\n if (!raw) return new Set();\n try {\n const parsed = YAML.parse(raw) as { ides?: unknown } | undefined;\n return new Set(Array.isArray(parsed?.ides) ? parsed.ides.filter((entry): entry is string => typeof entry === \"string\") : []);\n } catch {\n return new Set();\n }\n}\n\n/**\n * Reconstruct the installer-owned CLI inventory from BMAD's own durable\n * metadata. skill-manifest.csv maps a projected skill id to its source tree;\n * files-manifest.csv records the SHA-256 of every file in that tree.\n */\nfunction bmadCliProjectionInventory(repoRoot: string): { files: Map<string, string>; error?: string } {\n const filesText = safeReadText(join(repoRoot, \"_bmad\", \"_config\", \"files-manifest.csv\"));\n const skillsText = safeReadText(join(repoRoot, \"_bmad\", \"_config\", \"skill-manifest.csv\"));\n if (!filesText || !skillsText) return { files: new Map(), error: \"BMAD files/skill manifests are missing\" };\n const fileHashes = new Map<string, string>();\n for (const row of csvObjects(filesText)) {\n const hash = row.hash ?? \"\";\n if (row.path && /^[a-f0-9]{64}$/i.test(hash)) fileHashes.set(row.path.replace(/^_bmad\\//, \"\"), hash.toLowerCase());\n }\n const projected = new Map<string, string>();\n for (const row of csvObjects(skillsText)) {\n const canonicalId = row.canonicalId ?? \"\";\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(canonicalId)) continue;\n const skillPath = (row.path ?? \"\").replace(/^_bmad\\//, \"\");\n if (!skillPath.endsWith(\"/SKILL.md\")) continue;\n const sourceRoot = dirname(skillPath);\n for (const [sourcePath, hash] of fileHashes) {\n if (sourcePath !== `${sourceRoot}/SKILL.md` && !sourcePath.startsWith(`${sourceRoot}/`)) continue;\n const suffix = relative(sourceRoot, sourcePath);\n if (!suffix || suffix.startsWith(\"..\")) continue;\n projected.set(join(\"skills\", canonicalId, suffix), hash);\n }\n }\n return projected.size ? { files: projected } : { files: projected, error: \"BMAD manifests contain no projected skill inventory\" };\n}\n\nfunction inventoryFilesUnder(root: string, current = root): { files: string[]; unsafe: string[] } {\n if (!existsSync(current)) return { files: [], unsafe: [] };\n const stat = lstatSync(current);\n const rel = relative(root, current) || \".\";\n if (stat.isSymbolicLink()) return { files: [], unsafe: [rel] };\n if (stat.isFile()) return { files: [relative(root, current)], unsafe: [] };\n if (!stat.isDirectory()) return { files: [], unsafe: [rel] };\n const result = { files: [] as string[], unsafe: [] as string[] };\n for (const name of readdirSync(current)) {\n const child = inventoryFilesUnder(root, join(current, name));\n result.files.push(...child.files);\n result.unsafe.push(...child.unsafe);\n }\n return result;\n}\n\nfunction unsupportedRootAttestation(repoRoot: string, rootName: keyof typeof UNSUPPORTED_BMAD_ROOTS): { safe: boolean; reason: string } {\n const root = join(repoRoot, rootName);\n const stat = lstatSync(root);\n if (!stat.isDirectory() || stat.isSymbolicLink()) return { safe: false, reason: `${rootName} is not a regular generated directory` };\n const installerTool = UNSUPPORTED_BMAD_ROOTS[rootName];\n if (!installedBmadTools(repoRoot).has(installerTool)) {\n return { safe: false, reason: `BMAD installer metadata does not declare tool ${installerTool}` };\n }\n const inventory = bmadCliProjectionInventory(repoRoot);\n if (inventory.error) return { safe: false, reason: inventory.error };\n const walked = inventoryFilesUnder(root);\n if (walked.unsafe.length) return { safe: false, reason: `${rootName}/${walked.unsafe[0]} is a symlink or non-regular entry` };\n if (!walked.files.length) return { safe: false, reason: `${rootName} has no installer-owned files` };\n for (const rel of walked.files) {\n const expectedHash = inventory.files.get(rel);\n if (!expectedHash) return { safe: false, reason: `${rootName}/${rel} is outside the BMAD generated inventory` };\n const actualHash = createHash(\"sha256\").update(readFileSync(join(root, rel))).digest(\"hex\");\n if (actualHash !== expectedHash) return { safe: false, reason: `${rootName}/${rel} was locally modified after generation` };\n }\n return { safe: true, reason: `${walked.files.length} file(s) match BMAD installer inventory and hashes` };\n}\n\n/**\n * PJAN-84: template scripts that are OPTIONAL but must not drift.\n *\n * Four of the six CommonProject scripts have a byte-parity owner\n * (link-agentfiles.sh here, materialize-env.sh in secrets.env-op,\n * provision-packs.py and sync-skills.py in skills.project-manifest). These two\n * had none, so a repo could carry a months-old copy and nothing noticed.\n *\n * They are optional by design and stay so: the template guards the codegraph\n * hook with `[ -f ... ] && ... || true`, and hindsight-setup.sh backs a task\n * nobody has to run. pjangler itself carries neither. Demanding their presence\n * would contradict that guard \u2014 so the rule is \"if it is here, it matches\", and\n * absence is silence.\n */\nconst OPTIONAL_TEMPLATE_SCRIPTS = [\n \".mise/scripts/codegraph.sh\",\n \".mise/scripts/hindsight-setup.sh\",\n] as const;\n\nfunction optionalTemplateScriptIssues(ctx: Context): string[] {\n const issues: string[] = [];\n for (const rel of OPTIONAL_TEMPLATE_SCRIPTS) {\n const path = join(ctx.repoRoot, rel);\n if (!existsSync(path)) continue;\n const expected = templateCommonProjectText(ctx, rel);\n if (expected === undefined) continue;\n if (safeReadText(path) !== expected) issues.push(`${rel} is present but has drifted from the shipped template`);\n }\n return issues;\n}\n\nfunction refreshOptionalTemplateScripts(ctx: Context): string[] {\n const changed: string[] = [];\n for (const rel of OPTIONAL_TEMPLATE_SCRIPTS) {\n const path = join(ctx.repoRoot, rel);\n if (!existsSync(path)) continue;\n const expected = templateCommonProjectText(ctx, rel);\n if (expected === undefined || safeReadText(path) === expected) continue;\n changed.push(path);\n if (!ctx.dryRun) {\n writeText(path, expected);\n chmodSync(path, 0o755);\n }\n }\n return changed;\n}\n\nexport function createMiseChecks(): RecipeOwnedCheck[] {\nreturn [\n {\n id: \"mise.config-root\",\n title: \"mise config_root + AGENTS link hooks\",\n audit: (ctx) => {\n const misePath = join(ctx.repoRoot, \"mise.toml\");\n if (!existsSync(misePath)) {\n return { id: \"mise.config-root\", title: \"mise config_root + AGENTS link hooks\", status: \"fail\", summary: \"mise.toml missing\", details: [], fixable: true };\n }\n const text = readText(misePath);\n const details: string[] = [];\n const linkAgentfilesPath = join(ctx.repoRoot, \".mise\", \"scripts\", \"link-agentfiles.sh\");\n if (!existsSync(linkAgentfilesPath)) details.push(\".mise/scripts/link-agentfiles.sh missing\");\n const pathValues = [...(text.match(/^_\\.path\\s*=\\s*\\[([^\\]]*)\\]/m)?.[1] ?? \"\").matchAll(/\"([^\"]+)\"/g)].map((match) => match[1]);\n const missingPathValues = requiredMisePathEntries(ctx).filter((value) => !pathValues.includes(value));\n if (missingPathValues.length) details.push(`[env]._.path should include ${missingPathValues.join(\", \")}`);\n if (!text.includes(\"'{{config_root}}/.mise/scripts/link-agentfiles.sh'\")) details.push(\"link-agentfiles hook must use single-quoted {{config_root}} guard\");\n details.push(...managedHookSubjectIssues(text));\n details.push(...optionalTemplateScriptIssues(ctx));\n if (!text.includes(\"patterns = [\\\"AGENTS.md\\\"]\")) details.push(\"watch_files must monitor AGENTS.md\");\n if (!text.includes(`task = \"${LINK_AGENTFILES_TASK}\"`)) details.push(`watch_files must dispatch the ${LINK_AGENTFILES_TASK} task`);\n details.push(...retiredTaskNameIssues(text));\n return {\n id: \"mise.config-root\",\n title: \"mise config_root + AGENTS link hooks\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? \"mise AGENTS-linking parity verified\" : `${details.length} issue(s) detected in mise AGENTS-linking contract`,\n details,\n fixable: true,\n };\n },\n migrate: (ctx, finding) => {\n const path = join(ctx.repoRoot, \"mise.toml\");\n const changedFiles: string[] = [];\n const details: string[] = [];\n if (!existsSync(path)) {\n if (ensureMiseTomlFromTemplate(ctx, changedFiles) === null) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: \"mise.toml missing and no generated-project mise template available to initialize from\", changedFiles, details: [] };\n }\n details.push(\"Initialized mise.toml from generated-project template\");\n if (ctx.dryRun) {\n return { id: finding.id, title: finding.title, status: \"applied\", summary: \"Would initialize mise.toml from generated-project template\", changedFiles, details };\n }\n }\n let text = readText(path);\n const next = upsertLinkAgentfilesBlock(text, ctx);\n if (next !== text) {\n if (!changedFiles.includes(path)) changedFiles.push(path);\n if (!ctx.dryRun) writeText(path, next);\n text = next;\n }\n const linkAgentfilesPath = join(ctx.repoRoot, \".mise\", \"scripts\", \"link-agentfiles.sh\");\n const expectedScript = templateLinkAgentfilesScript(ctx);\n if (expectedScript === undefined) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: \"pjangler install is missing .mise/scripts/link-agentfiles.sh \u2014 update @delorenj/pjangler (broken package)\", changedFiles, details: [] };\n }\n changedFiles.push(...refreshOptionalTemplateScripts(ctx));\n if (safeReadText(linkAgentfilesPath) !== expectedScript) {\n changedFiles.push(linkAgentfilesPath);\n if (!ctx.dryRun) {\n writeText(linkAgentfilesPath, expectedScript);\n chmodSync(linkAgentfilesPath, 0o755);\n }\n }\n return {\n id: finding.id,\n title: finding.title,\n status: changedFiles.length ? \"applied\" : \"noop\",\n summary: changedFiles.length ? \"Updated mise AGENTS-linking contract\" : \"No changes required\",\n changedFiles,\n details: changedFiles.length ? [`Normalized hooks/watch_files/tasks.\"${LINK_AGENTFILES_TASK}\" block and script`] : [],\n };\n },\n },\n {\n id: \"mise.versioning\",\n title: \"managed mise versioning block\",\n audit: (ctx) => {\n const details: string[] = [];\n const misePath = join(ctx.repoRoot, \"mise.toml\");\n const versioningPath = join(ctx.repoRoot, \".mise\", \"scripts\", \"versioning.sh\");\n const manifestPath = join(ctx.repoRoot, \".mise\", \"version-files.conf\");\n const text = safeReadText(misePath);\n if (!text?.includes(\"# >>> mise-versioning >>>\")) details.push(\"mise versioning managed block missing\");\n if (!existsSync(versioningPath)) details.push(\".mise/scripts/versioning.sh missing\");\n if (!existsSync(manifestPath)) details.push(\".mise/version-files.conf missing\");\n return {\n id: \"mise.versioning\",\n title: \"managed mise versioning block\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? \"mise versioning parity verified\" : `${details.length} versioning issue(s) detected`,\n details,\n fixable: true,\n };\n },\n migrate: (ctx, finding) => {\n const changedFiles: string[] = [];\n const details: string[] = [];\n const misePath = join(ctx.repoRoot, \"mise.toml\");\n if (!existsSync(misePath)) {\n if (ensureMiseTomlFromTemplate(ctx, changedFiles) === null) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: \"mise.toml missing and no generated-project mise template available to initialize from\", changedFiles, details: [] };\n }\n details.push(\"Initialized mise.toml from generated-project template\");\n if (ctx.dryRun) {\n return { id: finding.id, title: finding.title, status: \"applied\", summary: \"Would initialize mise.toml from generated-project template\", changedFiles, details };\n }\n }\n const currentMise = readText(misePath);\n let cleanedMise = currentMise;\n if (!currentMise.includes(\"# >>> mise-versioning >>>\")) {\n const taskNames = [\"version\", \"version:bump\", \"version:bump-patch\", \"version:bump-minor\", \"version:bump-major\", \"version:check\", \"version:sync\"];\n for (const taskName of taskNames) {\n const escaped = taskName.replace(/:/g, \"\\\\:\");\n const headerPattern = new RegExp(`^\\\\[tasks\\\\.(?:\"${escaped}\"|'${escaped}'|${escaped})\\\\]$`);\n cleanedMise = removeTomlSection(cleanedMise, headerPattern);\n }\n }\n const nextMise = replaceOrAppendManagedBlock(cleanedMise, /# >>> mise-versioning >>>/, VERSIONING_BLOCK, /^\\[tasks\\.build\\]/m);\n if (nextMise !== currentMise) {\n if (!changedFiles.includes(misePath)) changedFiles.push(misePath);\n if (!ctx.dryRun) writeText(misePath, nextMise);\n }\n const versioningPath = join(ctx.repoRoot, \".mise\", \"scripts\", \"versioning.sh\");\n const expectedScript = templateVersioningScript(ctx);\n if (expectedScript === undefined) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: \"pjangler install is missing .mise/scripts/versioning.sh \u2014 update @delorenj/pjangler (broken package)\", changedFiles, details: [] };\n }\n if (safeReadText(versioningPath) !== expectedScript) {\n changedFiles.push(versioningPath);\n if (!ctx.dryRun) {\n writeText(versioningPath, expectedScript);\n chmodSync(versioningPath, 0o755);\n }\n }\n const manifestPath = join(ctx.repoRoot, \".mise\", \"version-files.conf\");\n const expectedManifest = templateVersionFilesConf(ctx, ctx.repoRoot);\n if (safeReadText(manifestPath) !== expectedManifest) {\n changedFiles.push(manifestPath);\n if (!ctx.dryRun) writeText(manifestPath, expectedManifest);\n }\n return {\n id: finding.id,\n title: finding.title,\n status: changedFiles.length ? \"applied\" : \"noop\",\n summary: changedFiles.length ? \"Versioning block/script/manifest normalized\" : \"No changes required\",\n changedFiles,\n details: [],\n };\n },\n },\n];\n}\n\nexport function createAgentHooksChecks(): RecipeOwnedCheck[] {\nreturn [\n {\n id: \"skills.project-manifest\",\n title: \"Skillex project skills manifest\",\n audit: (ctx) => {\n const details: string[] = [];\n const manifestPath = join(ctx.repoRoot, \".agents\", \"skills.json\");\n const legacyDir = join(ctx.repoRoot, \".agents\", \"skills\");\n const localExamplePath = join(ctx.repoRoot, \".agents\", \"local.example.json\");\n const misePath = join(ctx.repoRoot, \"mise.toml\");\n let fixable = true;\n\n const manifest = tryParseJson(safeReadText(manifestPath));\n // PACKS-CONTRACT: `packs[]` members are projected as symlinks and are NOT\n // required to appear in `skills[]`. Nothing is expanded into `skills[]`\n // any more \u2014 BMAD, the last thing that was, is now the installer's.\n const plan = buildPackPlan(ctx, manifest);\n if (plan.errors.length) {\n details.push(...plan.errors);\n fixable = false;\n }\n // PACKS-CONTRACT section 1: an `optional: true` pack that is missing WARNS,\n // it does not fail. Section 3b adds a second advisory class: a declared\n // container that projects nothing, or a symlinked container child that was\n // skipped. Both belong in the canonical summary, never in `details` \u2014\n // a detail is a FAILURE here, and neither of these is one.\n const packAdvisories = [\n ...(plan.warnings.length ? [`${plan.warnings.length} optional pack(s) skipped`] : []),\n ...plan.packWarnings,\n ];\n const expectedByName = new Map(plan.projections);\n const expectedNames = new Set(expectedByName.keys());\n\n if (!manifest) {\n details.push(\".agents/skills.json missing or invalid JSON\");\n } else {\n if (manifest.inherit_global !== true) details.push(\".agents/skills.json should set inherit_global: true\");\n if (manifest.registry !== SKILLS_REGISTRY_URL) details.push(`.agents/skills.json should set registry to ${SKILLS_REGISTRY_URL}`);\n if (typeof manifest.$schema === \"string\" && RETIRED_SKILLS_SCHEMA_URLS.includes(manifest.$schema)) {\n details.push(`.agents/skills.json $schema still points at the retired ${manifest.$schema}; it should be ${SKILLS_SCHEMA_URL}`);\n } else if (manifest.$schema !== SKILLS_SCHEMA_URL) {\n details.push(`.agents/skills.json should set $schema to ${SKILLS_SCHEMA_URL}`);\n }\n if (!Array.isArray(manifest.skills)) {\n details.push(\".agents/skills.json should define a skills array\");\n } else {\n // An entry pointing into a `packs/bmad/` tree is a leftover from the\n // retired Skillex pin: bmad-method writes those same skills into\n // .agents/skills itself, and the registry no longer carries the pack\n // at all, so the entry resolves nowhere and fights the installer.\n const bmadEntries = manifest.skills\n .filter((entry) => isRetiredBmadPackEntry(entry))\n .map(skillManifestEntryName)\n .filter((name): name is string => Boolean(name));\n const retiredPacks = retiredPackDeclarations(manifest);\n if (retiredPacks.length) {\n details.push(\n `.agents/skills.json declares retired pack(s) that bmad-method owns and Skillex no longer carries: ${retiredPacks.join(\", \")}`,\n );\n }\n if (bmadEntries.length) {\n details.push(\n `.agents/skills.json declares ${bmadEntries.length} bmad-* skill(s) that bmad-method owns and should drop them: ${bmadEntries.join(\", \")}`\n );\n }\n // PACKS-CONTRACT section 6: declaring a pack replaces hand-expanded\n // per-skill entries for that pack's members.\n const redundant = manifest.skills\n .filter((entry) => isRedundantDeclaredPackEntry(entry, plan))\n .map(skillManifestEntryName)\n .filter((name): name is string => Boolean(name));\n if (redundant.length) {\n details.push(\n `.agents/skills.json skills[] duplicates ${redundant.length} declared pack member(s) and should drop them: ${redundant.join(\", \")}`\n );\n }\n }\n }\n\n const invalidBmadLinkNames = new Set<string>();\n if (existsSync(legacyDir)) {\n for (const name of readdirSync(legacyDir)) {\n const expected = expectedByName.get(name);\n const path = join(legacyDir, name);\n let linkTargetsPack = false;\n try {\n const linkTarget = lstatSync(path).isSymbolicLink() ? resolve(dirname(path), readlinkSync(path)) : null;\n linkTargetsPack = Boolean(linkTarget) && plan.ownershipRoots.some((root) => isContainedBy(root, linkTarget!));\n } catch {\n linkTargetsPack = false;\n }\n if (!expected && !linkTargetsPack) continue;\n try {\n if (!expected || !lstatSync(path).isSymbolicLink() || resolve(dirname(path), readlinkSync(path)) !== expected) invalidBmadLinkNames.add(name);\n } catch {\n invalidBmadLinkNames.add(name);\n }\n }\n for (const [name, expected] of expectedByName) {\n const path = join(legacyDir, name);\n try {\n if (!lstatSync(path).isSymbolicLink() || resolve(dirname(path), readlinkSync(path)) !== expected) invalidBmadLinkNames.add(name);\n } catch {\n invalidBmadLinkNames.add(name);\n }\n }\n } else {\n for (const name of expectedByName.keys()) invalidBmadLinkNames.add(name);\n }\n if (invalidBmadLinkNames.size > 0) {\n details.push(`${invalidBmadLinkNames.size} managed pack skill path(s) should be symlinks into their declared Skillex pack`);\n }\n\n // PJAN-28: the walk above deliberately skips everything that is not a\n // pinned pack name or a pack symlink. That used to mean legacy committed\n // skills were silently ignored; enumerate them instead.\n const manifestNames = new Set(\n (Array.isArray(manifest?.skills) ? manifest.skills : [])\n .map(skillManifestEntryName)\n .filter((name): name is string => Boolean(name))\n );\n const unmanagedSkillNames = legacyCommittedSkillNames(\n legacyDir,\n skillsBackupDir(ctx.repoRoot),\n expectedNames,\n plan.ownershipRoots,\n manifestNames\n );\n for (const name of unmanagedSkillNames) {\n details.push(`.agents/skills/${name} is present in the projection but declared by nothing`);\n }\n if (unmanagedSkillNames.length) {\n details.push(\n `Run \\`pj migrate skills.project-manifest --accept-registry-matches\\` to map ${unmanagedSkillNames.length} undeclared skill entr(ies) into the manifest`\n );\n }\n\n for (const rel of [\".mise/scripts/link-project-skills-to-clis.sh\", \".mise/scripts/unlink-project-skills-from-clis.sh\"]) {\n if (existsSync(join(ctx.repoRoot, rel))) details.push(`${rel} is a legacy symlink-era script and should be removed`);\n }\n\n const localExample = tryParseJson(safeReadText(localExamplePath));\n if (localExample && Object.prototype.hasOwnProperty.call(localExample, \"skills\")) {\n details.push(\".agents/local.example.json still documents legacy skills overrides; drop the skills section\");\n }\n\n // PACKS-CONTRACT section 7: the BMAD-only provisioner is retired.\n if (existsSync(join(ctx.repoRoot, LEGACY_PROVISION_SCRIPT_REL))) {\n details.push(`${LEGACY_PROVISION_SCRIPT_REL} is the retired BMAD-only provisioner and should be replaced by ${PROVISION_PACKS_SCRIPT_REL}`);\n }\n\n const mise = safeReadText(misePath);\n if (!mise?.includes(SYNC_SKILLS_SCRIPT)) details.push(\"mise.toml should run the shipped project-local sync-skills.py engine via config_root\");\n if (!mise?.includes(PROVISION_PACKS_SCRIPT)) details.push(\"mise.toml should provision declared Skillex packs before syncing skills\");\n if (mise?.includes(SYNC_SKILLS_SCRIPT) && mise.includes(PROVISION_PACKS_SCRIPT) && mise.indexOf(PROVISION_PACKS_SCRIPT) > mise.indexOf(SYNC_SKILLS_SCRIPT)) {\n details.push(\"mise.toml should run the pack provisioner before project skill sync\");\n }\n if (mise?.includes(LEGACY_PROVISION_TASK) || mise?.includes(\"provision-bmad-skills.py\")) {\n details.push(`mise.toml still references the retired ${LEGACY_PROVISION_TASK} task/provision-bmad-skills.py script`);\n }\n if (mise?.includes('script = \"sync-skills.py --scope project\"') || mise?.includes('run = \"sync-skills.py --scope project\"')) {\n details.push(\"mise.toml still invokes the missing bare sync-skills.py executable\");\n }\n if (!mise?.includes('patterns = [\".agents/skills.json\"]')) details.push(\"mise.toml should watch .agents/skills.json\");\n if (!mise?.includes(taskHeader(SKILLS_SYNC_TASK))) details.push(`mise.toml should define a ${SKILLS_SYNC_TASK} task`);\n if (!mise?.includes(`depends = [\"${PROVISION_PACKS_TASK}\"]`)) details.push(`${SKILLS_SYNC_TASK} task should depend on ${PROVISION_PACKS_TASK}`);\n if (mise) details.push(...retiredTaskNameIssues(mise));\n for (const [rel, label] of [\n [PROVISION_PACKS_SCRIPT_REL, \"Skillex pack provisioning script\"],\n [SYNC_SKILLS_SCRIPT_REL, \"Project-local skills sync engine\"],\n ] as const) {\n const target = join(ctx.repoRoot, rel);\n const expected = templateCommonProjectText(ctx, rel);\n const stat = lstatIfPresent(target);\n if (!stat || !stat.isFile() || stat.isSymbolicLink()) {\n details.push(`${label} is missing or unsafe`);\n if (stat) fixable = false;\n } else {\n if (expected === undefined || safeReadText(target) !== expected) details.push(`${label} differs from the shipped template`);\n if ((Number(stat.mode) & 0o111) === 0) details.push(`${label} is not executable`);\n }\n }\n const topologyIssues = projectSkillTopologyIssues(ctx.repoRoot);\n if (topologyIssues.length) {\n details.push(...topologyIssues.map((issue) => `CLI skill topology: ${issue}`));\n fixable = false;\n }\n if (mise?.includes(\"link-project-skills-to-clis.sh\") || mise?.includes(\"unlink-project-skills-from-clis.sh\") || mise?.includes(\"[tasks.skills-relink]\")) {\n details.push(\"mise.toml still contains legacy skill-link wiring\");\n }\n\n return {\n id: \"skills.project-manifest\",\n title: \"Skillex project skills manifest\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary:\n details.length === 0\n ? `Skillex skills manifest parity verified${\n packAdvisories.length ? ` (${packAdvisories.join(\"; \")})` : \"\"\n }`\n : `${details.length} Skillex migration issue(s) detected${\n unmanagedSkillNames.length\n ? ` (${unmanagedSkillNames.length} undeclared skill entr(ies): ${unmanagedSkillNames.join(\", \")})`\n : \"\"\n }`,\n details,\n fixable,\n };\n },\n migrate: (ctx, finding) => {\n const changedFiles: string[] = [];\n const details: string[] = [];\n const manifestPath = join(ctx.repoRoot, \".agents\", \"skills.json\");\n const localExamplePath = join(ctx.repoRoot, \".agents\", \"local.example.json\");\n const misePath = join(ctx.repoRoot, \"mise.toml\");\n const provisionScriptPath = join(ctx.repoRoot, PROVISION_PACKS_SCRIPT_REL);\n const legacyProvisionScriptPath = join(ctx.repoRoot, LEGACY_PROVISION_SCRIPT_REL);\n const syncScriptPath = join(ctx.repoRoot, SYNC_SKILLS_SCRIPT_REL);\n const expectedProvisionScript = templateCommonProjectText(ctx, PROVISION_PACKS_SCRIPT_REL);\n const expectedSyncScript = templateCommonProjectText(ctx, SYNC_SKILLS_SCRIPT_REL);\n\n const topologyIssues = projectSkillTopologyIssues(ctx.repoRoot);\n if (topologyIssues.length) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"Unsafe project CLI skill topology must be repaired manually\",\n changedFiles,\n details: topologyIssues,\n };\n }\n\n if (!expectedProvisionScript || !expectedSyncScript) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"pjangler install is missing a shipped skills executable\",\n changedFiles,\n details: [\n ...(!expectedProvisionScript ? [`Missing Skillex pack provisioning script template (${PROVISION_PACKS_SCRIPT_REL})`] : []),\n ...(!expectedSyncScript ? [\"Missing project-local skills sync engine template\"] : []),\n ],\n };\n }\n const unsafeScriptTargets = [provisionScriptPath, syncScriptPath].filter((path) => {\n const stat = lstatIfPresent(path);\n return Boolean(stat && (!stat.isFile() || stat.isSymbolicLink()));\n });\n if (unsafeScriptTargets.length) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"Refusing non-regular managed skills executable target\",\n changedFiles,\n details: unsafeScriptTargets.map((path) => `${path} must be removed or repaired manually`),\n };\n }\n\n // Drop forbidden declarations before provisioning: otherwise an\n // unresolvable pack blocks the very migration that would remove it.\n const droppedPacks = dropRetiredPackDeclarations(manifestPath, Boolean(ctx.dryRun));\n if (droppedPacks.length) {\n if (!ctx.dryRun) changedFiles.push(manifestPath);\n details.push(`dropped retired pack declaration(s) bmad-method owns: ${droppedPacks.join(\", \")}`);\n }\n\n const provisioned = provisionDeclaredPacks(ctx);\n if (!provisioned.ok) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"A declared Skillex pack is unavailable or untrusted\",\n changedFiles,\n details: [provisioned.error ?? \"Unknown Skillex pack error\"],\n };\n }\n changedFiles.push(...provisioned.changedFiles);\n if (provisioned.changedFiles.includes(manifestPath)) details.push(\"Normalized .agents/skills.json against the declared Skillex packs\");\n // Section 3b advisories: a declared container that projected nothing must\n // be reported, not silently dropped. It is not a failure, so it only ever\n // annotates the result.\n details.push(...(provisioned.packWarnings ?? []));\n\n // PJAN-28: runs after the BMAD projection so nothing is mutated ahead of\n // the pack blocker above. provisionDeclaredPacks never touches unmanaged\n // entries, and it preserves every non-pack-managed manifest entry, so\n // appending here is stable in both directions.\n details.push(...migrateLegacyCommittedSkills(ctx, changedFiles));\n\n // Retired scripts. `provision-bmad-skills.py` (PACKS-CONTRACT section 7)\n // is removed only after `provision-packs.py` has been written below, so a\n // failure part-way through never leaves a repo with neither provisioner.\n for (const rel of [\".mise/scripts/link-project-skills-to-clis.sh\", \".mise/scripts/unlink-project-skills-from-clis.sh\"]) {\n const path = join(ctx.repoRoot, rel);\n if (existsSync(path)) {\n changedFiles.push(path);\n if (!ctx.dryRun) unlinkSync(path);\n }\n }\n\n const templateLocalExample = templateCommonProjectText(ctx, \".agents/local.example.json\");\n const currentLocalExample = safeReadText(localExamplePath);\n if (templateLocalExample && currentLocalExample && currentLocalExample !== templateLocalExample) {\n changedFiles.push(localExamplePath);\n if (!ctx.dryRun) writeText(localExamplePath, templateLocalExample);\n }\n\n normalizeExecutableTemplate(ctx, provisionScriptPath, expectedProvisionScript, changedFiles);\n\n normalizeExecutableTemplate(ctx, syncScriptPath, expectedSyncScript, changedFiles);\n\n // Only now that provision-packs.py exists is the retired one dropped.\n const legacyProvisionStat = lstatIfPresent(legacyProvisionScriptPath);\n if (legacyProvisionStat) {\n if (legacyProvisionStat.isDirectory() && !legacyProvisionStat.isSymbolicLink()) {\n details.push(`${LEGACY_PROVISION_SCRIPT_REL} is a directory and must be removed manually`);\n } else {\n changedFiles.push(legacyProvisionScriptPath);\n details.push(`Removed the retired ${LEGACY_PROVISION_SCRIPT_REL}`);\n if (!ctx.dryRun) unlinkSync(legacyProvisionScriptPath);\n }\n }\n\n let currentMise = safeReadText(misePath);\n if (currentMise === null) {\n const initialized = ensureMiseTomlFromTemplate(ctx, changedFiles);\n if (initialized === null) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: \"mise.toml missing and no generated-project mise template available to initialize from\", changedFiles, details };\n }\n details.push(\"Initialized mise.toml from generated-project template\");\n currentMise = initialized;\n }\n const nextMise = upsertLinkAgentfilesBlock(currentMise, ctx);\n if (nextMise !== currentMise) {\n if (!changedFiles.includes(misePath)) changedFiles.push(misePath);\n if (!ctx.dryRun) writeText(misePath, nextMise);\n }\n\n return {\n id: finding.id,\n title: finding.title,\n status: changedFiles.length ? \"applied\" : \"noop\",\n summary: changedFiles.length ? \"Skillex skills manifest contract normalized\" : \"No changes required\",\n changedFiles,\n details,\n };\n },\n },\n {\n id: \"sot.agent-symlinks\",\n title: \"AGENTS/CLAUDE/GEMINI symlink contract\",\n audit: (ctx) => {\n const agentsPath = join(ctx.repoRoot, \"AGENTS.md\");\n if (!existsSync(agentsPath)) {\n const fallbackSources = [\"CLAUDE.md\", \"GEMINI.md\", \"README.md\"].filter((file) => existsSync(join(ctx.repoRoot, file)));\n if (fallbackSources.length === 0) {\n return { id: \"sot.agent-symlinks\", title: \"AGENTS/CLAUDE/GEMINI symlink contract\", status: \"skip\", summary: \"AGENTS.md missing; symlink contract not applicable\", details: [], fixable: false };\n }\n return {\n id: \"sot.agent-symlinks\",\n title: \"AGENTS/CLAUDE/GEMINI symlink contract\",\n status: \"fail\",\n summary: \"AGENTS.md missing but can be derived from existing project documentation\",\n details: [`AGENTS.md can be created from ${fallbackSources[0]}`],\n fixable: true,\n };\n }\n const details: string[] = [];\n for (const file of [\"CLAUDE.md\", \"GEMINI.md\"]) {\n const full = join(ctx.repoRoot, file);\n const target = readSymlinkTarget(full);\n if (target !== \"AGENTS.md\") details.push(`${file} should be a symlink to AGENTS.md`);\n }\n return {\n id: \"sot.agent-symlinks\",\n title: \"AGENTS/CLAUDE/GEMINI symlink contract\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? \"Agent documentation symlinks are in parity\" : `${details.length} symlink issue(s) detected`,\n details,\n fixable: true,\n };\n },\n migrate: (ctx, finding) => {\n const changedFiles: string[] = [];\n const details: string[] = [];\n const blockedDetails: string[] = [];\n const bootstrap = bootstrapAgentsFile(ctx.repoRoot, ctx.dryRun);\n changedFiles.push(...bootstrap.changedFiles);\n details.push(...bootstrap.details);\n if (bootstrap.blocked) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: \"AGENTS.md missing; cannot derive canonical agent file\", changedFiles, details: [bootstrap.blocked] };\n }\n for (const file of [\"CLAUDE.md\", \"GEMINI.md\"]) {\n const full = join(ctx.repoRoot, file);\n const result = ensureSymlink(full, \"AGENTS.md\", ctx.dryRun);\n if (result.blocked) blockedDetails.push(result.blocked);\n if (result.changed) changedFiles.push(full);\n }\n return {\n id: finding.id,\n title: finding.title,\n status: blockedDetails.length ? \"blocked\" : changedFiles.length ? \"applied\" : \"noop\",\n summary: blockedDetails.length ? \"One or more files could not be replaced safely\" : changedFiles.length ? \"Symlink contract repaired\" : \"No changes required\",\n changedFiles,\n details: [...details, ...blockedDetails],\n };\n },\n },\n];\n}\n\nfunction createProjectJsonChecks(): RecipeOwnedCheck[] {\nreturn [\n {\n id: \"sot.project-json\",\n title: \"Canonical .project.json\",\n audit: projectJsonFinding,\n migrate: (ctx, finding) => {\n const changedFiles: string[] = [];\n const blockedDetails: string[] = [];\n const droppedDetails: string[] = [];\n const path = join(ctx.repoRoot, \".project.json\");\n const existing = readProjectJson(ctx) ?? {};\n const canonical = canonicalProjectJson(ctx);\n const preservedDetails: string[] = [];\n for (const agentId of canonical.unprovisioned) {\n const roleDir = ((existing.agents as Record<string, Record<string, unknown>> | undefined)?.[agentId]?.role_dir);\n preservedDetails.push(\n `preserved unprovisioned declared agent: ${agentId}${typeof roleDir === \"string\" && roleDir ? ` (${roleDir} has no role.yaml)` : \" (no role_dir)\"}; provision or restore the role, do not delete its declaration`\n );\n }\n for (const agentId of canonical.dropped) {\n const entry = (existing.agents as Record<string, unknown> | undefined)?.[agentId];\n const entryRecord = typeof entry === \"object\" && entry !== null ? (entry as Record<string, unknown>) : undefined;\n const declared: DeclaredAgentEntry = {\n agentId,\n role: typeof entryRecord?.role === \"string\" ? entryRecord.role : undefined,\n roleDir: typeof entryRecord?.role_dir === \"string\" ? entryRecord.role_dir : undefined,\n extras: {},\n };\n const validation = validateDeclaredAgent(ctx, declared);\n const reason = validation.details.join(\"; \") || \"invalid\";\n droppedDetails.push(`dropped invalid declared agent: ${agentId} (${reason})`);\n }\n // Merge: canonical keys win, but preserve any extra keys the user added\n const { dropped: _dropped, unprovisioned: _unprovisioned, ...canonicalJson } = canonical;\n const merged = { ...existing, ...canonicalJson };\n const expected = `${JSON.stringify(merged, null, 2)}\\n`;\n if (safeReadText(path) !== expected) {\n changedFiles.push(path);\n if (!ctx.dryRun) writeText(path, expected);\n }\n const planeJson = join(ctx.repoRoot, \".plane.json\");\n if (existsSync(planeJson)) {\n const backup = `${planeJson}.migrated-backup`;\n if (existsSync(backup)) {\n blockedDetails.push(`cannot back up .plane.json because ${relative(ctx.repoRoot, backup)} already exists`);\n } else {\n changedFiles.push(backup);\n if (!ctx.dryRun) renameSync(planeJson, backup);\n }\n }\n const details = [...droppedDetails, ...preservedDetails, ...blockedDetails];\n return {\n id: finding.id,\n title: finding.title,\n status: blockedDetails.length ? \"blocked\" : (changedFiles.length || droppedDetails.length) ? \"applied\" : \"noop\",\n summary: blockedDetails.length\n ? \"Project SOT partially blocked\"\n : (changedFiles.length || droppedDetails.length)\n ? `Canonical .project.json written; dropped ${droppedDetails.length} invalid declared agent(s)`\n : \"No changes required\",\n changedFiles,\n details,\n };\n },\n },\n];\n}\n\nexport function createMiseOpInjectChecks(): RecipeOwnedCheck[] {\nreturn [\n {\n id: \"secrets.env-op\",\n title: \".env.op + gitignore secrets contract\",\n audit: (ctx) => {\n const details: string[] = [];\n let envOpNeedsHands = false;\n const envOpPath = join(ctx.repoRoot, \".env.op\");\n const envOpExists = existsSync(envOpPath);\n const envOp = envOpExists ? readText(envOpPath) : undefined;\n const gitignore = safeReadText(join(ctx.repoRoot, \".gitignore\"));\n if (!envOpExists) {\n details.push(\".env.op missing\");\n } else if (!envOp?.trim()) {\n details.push(\".env.op is empty or whitespace-only\");\n } else {\n const malformed = malformedOpReferences(envOp);\n if (malformed.length) {\n details.push(`.env.op has malformed op:// reference(s) on line(s): ${Array.from(new Set(malformed.map((entry) => entry.line))).join(\", \")}`);\n }\n const invalidLines = envOp\n .split(\"\\n\")\n .map((line, index) => ({ line: line.trim(), number: index + 1 }))\n .filter(({ line }) => line && !line.startsWith(\"#\") && line.includes(\"=\"))\n .filter(({ line }) => {\n const value = line.slice(line.indexOf(\"=\") + 1).trim();\n const quotedLiteral = /^\"[^\"\\r\\n]*\"$/.test(value) || /^'[^'\\r\\n]*'$/.test(value);\n return !value.startsWith(\"op://\") && !/^https?:\\/\\//.test(value) && !/^[A-Za-z0-9_.:-]+$/.test(value) && !quotedLiteral;\n });\n if (invalidLines.length) details.push(`.env.op has non-reference values that do not look like safe literals on line(s): ${invalidLines.map((entry) => entry.number).join(\", \")}`);\n }\n if (!gitignore?.includes(\".env\\n\") && !gitignore?.includes(\".env\\r\\n\")) details.push(\".gitignore should ignore .env\");\n if (!gitignore?.includes(\".env.*\")) details.push(\".gitignore should ignore .env.*\");\n if (!gitignore?.includes(\"!.env.op\")) details.push(\".gitignore should unignore .env.op\");\n const misePath = join(ctx.repoRoot, \"mise.toml\");\n const miseText = safeReadText(misePath);\n if (!miseText) {\n details.push(\"mise.toml missing for .env materialization hook\");\n } else {\n const enterHookValues = stripHookBlocks(miseText).enter;\n const truncating = truncatingOpInjectEntries(enterHookValues);\n if (truncating.length) details.push(`hooks.enter has ${truncating.length} unsafe legacy .env op-inject hook(s)`);\n const canonicalCount = enterHookValues.filter((value) => value.trim() === OP_INJECT_SCRIPT).length;\n if (canonicalCount !== 1) details.push(`hooks.enter must contain exactly one managed materialize-env hook (found ${canonicalCount})`);\n const strayOwned = ownedOpInjectScriptsOutsideEnter(miseText);\n if (strayOwned.length) details.push(`owned .env materialization appears outside [[hooks.enter]] on line(s): ${strayOwned.map((entry) => entry.line).join(\", \")}`);\n }\n const materializePath = join(ctx.repoRoot, MATERIALIZE_ENV_SCRIPT_REL);\n const expectedMaterializer = templateMaterializeEnvScript(ctx);\n if (!expectedMaterializer) {\n details.push(\"pjangler package is missing the managed materialize-env.sh source\");\n } else if (safeReadText(materializePath) !== expectedMaterializer) {\n details.push(`${MATERIALIZE_ENV_SCRIPT_REL} missing or drifted`);\n } else if ((lstatSync(materializePath).mode & 0o111) === 0) {\n details.push(`${MATERIALIZE_ENV_SCRIPT_REL} is not executable`);\n }\n return {\n id: \"secrets.env-op\",\n title: \".env.op + gitignore secrets contract\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? \"Secret reference file and ignore rules are in parity\" : `${details.length} env parity issue(s) detected`,\n details,\n fixable: true,\n };\n },\n migrate: (ctx, finding) => {\n const changedFiles: string[] = [];\n const details: string[] = [];\n let envOpNeedsHands = false;\n const envOpPath = join(ctx.repoRoot, \".env.op\");\n const canonicalEnvOpPath = join(ctx.pjanglerRoot, \"templates\", \"commonproject\", \"template\", \".env.op\");\n if (!existsSync(canonicalEnvOpPath)) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: \"pjangler package is missing the neutral .env.op template\", changedFiles: [], details: [] };\n }\n const canonicalEnvOp = readText(canonicalEnvOpPath);\n if (!existsSync(envOpPath) || !readText(envOpPath).trim()) {\n changedFiles.push(envOpPath);\n if (!ctx.dryRun) writeText(envOpPath, canonicalEnvOp);\n } else {\n const current = readText(envOpPath);\n const activeMalformed = malformedOpReferences(current).filter((entry) => !entry.commentOnly);\n const invalidActive = current\n .split(\"\\n\")\n .map((line, index) => ({ line: line.trim(), number: index + 1 }))\n .filter(({ line }) => line && !line.startsWith(\"#\") && line.includes(\"=\"))\n .filter(({ line }) => {\n const value = line.slice(line.indexOf(\"=\") + 1).trim();\n const quotedLiteral = /^\"[^\"\\r\\n]*\"$/.test(value) || /^'[^'\\r\\n]*'$/.test(value);\n return !value.startsWith(\"op://\") && !/^https?:\\/\\//.test(value) && !/^[A-Za-z0-9_.:-]+$/.test(value) && !quotedLiteral;\n });\n if (activeMalformed.length || invalidActive.length) {\n // PJAN-84: report the .env.op content, but do not let it veto the\n // repairs that have nothing to do with it.\n //\n // This used to `return blocked` here, which skipped the .gitignore\n // block, the mise.toml op-inject hook, and the materialize-env.sh\n // install \u2014 three fixes that never touch .env.op's contents. A repo\n // whose .env.op holds a deliberately inline local-only value (one\n // KeepyMoney file says so in a comment: \"Local-only creds (threat\n // model: none)\") could therefore never get its enter hook repaired,\n // and the cwd-relative `op inject -i .env.op > .env` hook that drops a\n // stray .env into any subdirectory you jump into stayed forever.\n //\n // Same shape as the retired `bmad` pack declaration that blocked the\n // migration which would have removed it: an unresolvable thing must\n // never get a veto over everything around it.\n envOpNeedsHands = true;\n details.push(...(activeMalformed.length ? [`Malformed active op:// reference(s) remain on line(s) ${Array.from(new Set(activeMalformed.map((entry) => entry.line))).join(\", \")}; repair them manually without replacing valid user references`] : []));\n details.push(...(invalidActive.length ? [`Unsafe active value(s) remain on line(s) ${invalidActive.map((entry) => entry.number).join(\", \")}; repair them manually`] : []));\n } else {\n const repaired = removeMalformedCommentOpReferences(current);\n // A comment-only file is an intentional opt-out. Preserve it exactly\n // unless malformed examples in comments need conservative cleanup.\n const next = repaired.text;\n if (next !== current) {\n changedFiles.push(envOpPath);\n if (!ctx.dryRun) writeText(envOpPath, next);\n }\n }\n }\n const gitignorePath = join(ctx.repoRoot, \".gitignore\");\n const gitignore = safeReadText(gitignorePath) ?? \"\";\n // `.env.*` also covers the `.env.inject.XXXXXX` staging file the atomic\n // op-inject enter hook creates in the project dir (PJAN-24).\n const requiredBlock = `# Secrets \u2014 .env is materialized from .env.op by \\`op inject\\` on mise enter,\\n# staged through a mktemp file and moved into place only on success.\\n# NEVER commit it. .env.op holds only 1Password references or safe literals and IS committed.\\n.env\\n.env.*\\n!.env.op\\n`;\n if (!gitignore.includes(\"!.env.op\") || !gitignore.includes(\".env.*\")) {\n changedFiles.push(gitignorePath);\n if (!ctx.dryRun) writeText(gitignorePath, `${gitignore.replace(/\\s*$/, \"\")}${gitignore.trim() ? \"\\n\\n\" : \"\"}${requiredBlock}`);\n }\n const misePath = join(ctx.repoRoot, \"mise.toml\");\n let currentMise = safeReadText(misePath);\n if (currentMise === null) {\n const initialized = ensureMiseTomlFromTemplate(ctx, changedFiles);\n if (initialized === null) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: \"mise.toml missing and the packaged template is unavailable\", changedFiles: [], details: [] };\n }\n // Previously guarded by `if (existsSync(misePath))`, which a dry run\n // never satisfies -- so the op-inject hook silently vanished from the\n // preview of a repo that had no mise.toml yet.\n currentMise = initialized;\n }\n const nextOpInjectMise = upsertOpInjectHook(currentMise);\n if (nextOpInjectMise !== currentMise) {\n if (!changedFiles.includes(misePath)) changedFiles.push(misePath);\n if (!ctx.dryRun) writeText(misePath, nextOpInjectMise);\n }\n const materializePath = join(ctx.repoRoot, MATERIALIZE_ENV_SCRIPT_REL);\n const expectedMaterializer = templateMaterializeEnvScript(ctx);\n if (!expectedMaterializer) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: \"pjangler package is missing materialize-env.sh\", changedFiles: [], details: [] };\n }\n if (safeReadText(materializePath) !== expectedMaterializer || (existsSync(materializePath) && (lstatSync(materializePath).mode & 0o111) === 0)) {\n changedFiles.push(materializePath);\n if (!ctx.dryRun) {\n writeText(materializePath, expectedMaterializer);\n chmodSync(materializePath, 0o755);\n }\n }\n const uniqueChangedFiles = [...new Set(changedFiles)].sort();\n if (envOpNeedsHands) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: uniqueChangedFiles.length\n ? \"Repaired the mise contract; .env.op content still needs hands\"\n : \"Manual .env.op cleanup still required\",\n changedFiles: uniqueChangedFiles,\n details,\n };\n }\n return {\n id: finding.id,\n title: finding.title,\n status: uniqueChangedFiles.length ? \"applied\" : \"noop\",\n summary: uniqueChangedFiles.length ? \"Reconciled the canonical .env materialization contract\" : \"No changes required\",\n changedFiles: uniqueChangedFiles,\n details,\n };\n },\n },\n];\n}\n\nfunction createProjectProvenanceChecks(): RecipeOwnedCheck[] {\nreturn [\n {\n id: \"provenance.copier\",\n title: \".copier-answers.yml provenance + drift report\",\n audit: (ctx) => {\n const details: string[] = [];\n const path = join(ctx.repoRoot, \".copier-answers.yml\");\n const text = safeReadText(path);\n const project = readProjectJson(ctx);\n if (!text) {\n details.push(\".copier-answers.yml missing\");\n } else {\n if (!text.startsWith(\"# Changes here will be overwritten by Copier; NEVER EDIT MANUALLY\")) details.push(\"missing Copier overwrite warning header\");\n if (!text.includes(\"_src_path:\")) details.push(\"_src_path missing\");\n if (project?.project_name) {\n const nameMatch = text.match(/project_name:\\s*(.+)/);\n if (!nameMatch || nameMatch[1]?.trim() !== String(project.project_name)) details.push(\"project_name drift between .copier-answers.yml and .project.json\");\n }\n if (project?.project_description) {\n const descMatch = text.match(/project_description:\\s*([\\s\\S]*?)(?=\\n\\w|$)/);\n const yamlDesc = descMatch?.[1]?.replace(/\\n\\s+/g, \" \").trim() ?? \"\";\n if (yamlDesc !== String(project.project_description)) details.push(\"project_description drift between .copier-answers.yml and .project.json\");\n }\n }\n return {\n id: \"provenance.copier\",\n title: \".copier-answers.yml provenance + drift report\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? \"Copier provenance is in parity\" : `${details.length} provenance issue(s) detected`,\n details,\n fixable: true,\n };\n },\n migrate: (ctx, finding) => {\n const changedFiles: string[] = [];\n const project = canonicalProjectJson(ctx);\n const text = `# Changes here will be overwritten by Copier; NEVER EDIT MANUALLY\\n_src_path: ${join(ctx.pjanglerRoot, \"templates\", \"commonproject\")}\\nproject_description: ${String(project.project_description)}\\nproject_name: ${String(project.project_name)}\\nticket_provider: ${String(((project.ticket_provider as Record<string, unknown>)?.type ?? \"plane\"))}\\n`;\n const path = join(ctx.repoRoot, \".copier-answers.yml\");\n if (safeReadText(path) !== text) {\n changedFiles.push(path);\n if (!ctx.dryRun) writeText(path, text);\n }\n return {\n id: finding.id,\n title: finding.title,\n status: changedFiles.length ? \"applied\" : \"noop\",\n summary: changedFiles.length ? \"Copier provenance file refreshed\" : \"No changes required\",\n changedFiles,\n details: [],\n };\n },\n },\n];\n}\n\nfunction supportedCliProjectionIssues(repoRoot: string): string[] {\n const issues: string[] = [];\n const managedSkills = join(repoRoot, \".agents\", \"skills\");\n for (const rootName of SUPPORTED_CLI_ROOTS) {\n const root = join(repoRoot, rootName);\n const rootStat = lstatIfPresent(root);\n if (!rootStat) {\n issues.push(`${rootName} missing`);\n continue;\n }\n if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {\n issues.push(`${rootName} must be a real configuration directory`);\n continue;\n }\n const skills = join(root, \"skills\");\n const skillsStat = lstatIfPresent(skills);\n if (!skillsStat) {\n issues.push(`${rootName}/skills missing`);\n continue;\n }\n let projectedSkills = skills;\n if (skillsStat.isSymbolicLink()) {\n let rawTarget = \"\";\n try {\n rawTarget = readlinkSync(skills);\n } catch {\n issues.push(`${rootName}/skills is an unreadable symlink`);\n continue;\n }\n if (rawTarget !== CANONICAL_CLI_SKILLS_ALIAS) {\n issues.push(`${rootName}/skills must target ${CANONICAL_CLI_SKILLS_ALIAS}`);\n continue;\n }\n const targetStat = lstatIfPresent(managedSkills);\n if (!targetStat || targetStat.isSymbolicLink() || !targetStat.isDirectory()) {\n issues.push(`${rootName}/skills alias target .agents/skills is missing or unsafe`);\n continue;\n }\n try {\n if (realpathSync(skills) !== realpathSync(managedSkills)) {\n issues.push(`${rootName}/skills resolves outside .agents/skills`);\n continue;\n }\n } catch {\n issues.push(`${rootName}/skills alias is broken`);\n continue;\n }\n projectedSkills = managedSkills;\n } else if (!skillsStat.isDirectory()) {\n issues.push(`${rootName}/skills is not a directory`);\n continue;\n }\n const hasGeneratedSkill = existsSync(projectedSkills) && readdirSync(projectedSkills).some((name) => {\n const skillFile = join(projectedSkills, name, \"SKILL.md\");\n return existsSync(skillFile) && lstatSync(skillFile).isFile();\n });\n if (!hasGeneratedSkill) issues.push(`${rootName}/skills contains no BMAD skill configuration`);\n }\n return issues;\n}\n\n/**\n * Each CLI root holds hand-owned configuration (settings, commands) that IS\n * durable project state, and a generated `skills/` projection that is not.\n *\n * The un-ignore lines keep the configuration tracked. The trailing re-ignore\n * lines \u2014 last match wins in gitignore \u2014 drop the skill projections back out,\n * because `bmad-method install` rewrites all of them on every run and version\n * bump. Committing them means ~76 skills duplicated across seven locations,\n * re-churned on every upgrade, when `_bmad/_config/manifest.yaml` already pins\n * the version that reproduces them exactly.\n *\n * PJAN-82: the re-ignore patterns carry NO trailing slash on purpose. A\n * trailing slash matches a directory only, and the projection is not always a\n * directory: `bmad-method install` writes a real directory into .claude,\n * .codex and .opencode, while `sync-skills.py` projects .gemini, .copilot and\n * .kimi-code as a SYMLINK to ../.agents/skills. `.gemini/skills/` therefore\n * never matched the symlink, `!.gemini/**` won instead, and `git add -A`\n * happily staged three generated skill projections as tracked symlinks.\n */\nconst SUPPORTED_CLI_GITIGNORE_BLOCK = `# Generated CLI configurations are durable project state...\n${SUPPORTED_CLI_ROOTS.flatMap((root) => [`!${root}/`, `!${root}/**`]).join(\"\\n\")}\n# ...but their skill projections are regenerated by \\`bmad-method install\\` and\n# \\`mise run skills:sync\\`, so they stay out of the tree. No trailing slash:\n# some CLIs get a real directory here and some get a symlink.\n/.agents/skills\n${SUPPORTED_CLI_ROOTS.map((root) => `${root}/skills`).join(\"\\n\")}`;\n\nfunction supportedCliGitignoreIssues(repoRoot: string): string[] {\n const lines = (safeReadText(join(repoRoot, \".gitignore\")) ?? \"\").split(/\\r?\\n/);\n return [\n ...SUPPORTED_CLI_ROOTS.flatMap((root) => [\n ...(!lines.includes(`!${root}/`) ? [`.gitignore must unignore ${root}/`] : []),\n ...(!lines.includes(`!${root}/**`) ? [`.gitignore must unignore ${root}/**`] : []),\n // Accept either form so an existing repo is not churned, but only the\n // slashless pattern actually covers a symlinked projection.\n ...(!lines.includes(`${root}/skills`) ? [`.gitignore must re-ignore the generated ${root}/skills (no trailing slash \u2014 the projection may be a symlink)`] : []),\n ]),\n ...(!lines.includes(\"/.agents/skills\") ? [\".gitignore must ignore the generated /.agents/skills\"] : []),\n ];\n}\n\nfunction ensureSupportedCliGitignore(ctx: Context): string[] {\n if (!supportedCliGitignoreIssues(ctx.repoRoot).length) return [];\n const path = join(ctx.repoRoot, \".gitignore\");\n const current = safeReadText(path) ?? \"\";\n const next = `${current.replace(/\\s*$/, \"\")}${current.trim() ? \"\\n\\n\" : \"\"}${SUPPORTED_CLI_GITIGNORE_BLOCK}\\n`;\n if (!ctx.dryRun) writeText(path, next);\n return [path];\n}\n\nfunction ensureSupportedCliProjections(ctx: Context): { changedFiles: string[]; blockers: string[] } {\n const changedFiles: string[] = [];\n const blockers: string[] = [];\n const managedSkills = join(ctx.repoRoot, \".agents\", \"skills\");\n const managedStat = lstatIfPresent(managedSkills);\n if (!managedStat || managedStat.isSymbolicLink() || !managedStat.isDirectory()) {\n return { changedFiles, blockers: [\".agents/skills must be a real BMAD-generated directory before CLI projections can be created\"] };\n }\n for (const rootName of SUPPORTED_CLI_ROOTS) {\n const root = join(ctx.repoRoot, rootName);\n const rootStat = lstatIfPresent(root);\n if (rootStat && (rootStat.isSymbolicLink() || !rootStat.isDirectory())) {\n blockers.push(`${rootName} is not a real configuration directory`);\n continue;\n }\n if (!rootStat) {\n changedFiles.push(root);\n if (!ctx.dryRun) mkdirSync(root, { recursive: false });\n }\n const skills = join(root, \"skills\");\n const skillsStat = lstatIfPresent(skills);\n if (!skillsStat) {\n changedFiles.push(skills);\n if (!ctx.dryRun) symlinkSync(CANONICAL_CLI_SKILLS_ALIAS, skills, \"dir\");\n continue;\n }\n if (skillsStat.isSymbolicLink()) {\n try {\n if (readlinkSync(skills) !== CANONICAL_CLI_SKILLS_ALIAS || realpathSync(skills) !== realpathSync(managedSkills)) {\n blockers.push(`${rootName}/skills is not the managed .agents/skills alias`);\n }\n } catch {\n blockers.push(`${rootName}/skills is an unreadable or broken symlink`);\n }\n } else if (!skillsStat.isDirectory()) {\n blockers.push(`${rootName}/skills is not a directory`);\n }\n }\n return { changedFiles: [...new Set(changedFiles)].sort(), blockers };\n}\n\nexport function createBmadChecks(): RecipeOwnedCheck[] {\nreturn [\n {\n id: \"bmad.scaffold\",\n title: \"BMAD modules/docs scaffold\",\n audit: (ctx) => {\n const manifestSelection = manifestBmadModules(ctx.repoRoot);\n if (manifestSelection.status === \"invalid\") {\n return {\n id: \"bmad.scaffold\",\n title: \"BMAD modules/docs scaffold\",\n status: \"fail\",\n summary: \"BMAD module manifest is invalid; refusing fallback module selection\",\n details: [manifestSelection.error],\n fixable: false,\n };\n }\n const targetRoot = join(ctx.repoRoot, \"_bmad\");\n const selectedModules = manifestSelection.status === \"valid\"\n ? manifestSelection.modules\n : configuredBmadModules(ctx.repoRoot) ?? [...DEFAULT_BMAD_MODULES];\n const sentinels = requiredBmadSentinels(ctx.repoRoot, selectedModules);\n const missing = sentinels.filter((file) => !existsSync(join(targetRoot, file)));\n const projectNameIssues = bmadProjectNameIssues(ctx.repoRoot);\n const details = [\n ...missing.map((file) => `_bmad/${file}`),\n ...projectNameIssues.details,\n ];\n return {\n id: \"bmad.scaffold\",\n title: \"BMAD modules/docs scaffold\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? \"BMAD scaffold and project identity parity verified\" : `${details.length} BMAD scaffold issue(s) detected`,\n details,\n fixable: true,\n };\n },\n migrate: (ctx, finding) => {\n const changedFiles: string[] = [];\n const manifestSelection = manifestBmadModules(ctx.repoRoot);\n if (manifestSelection.status === \"invalid\") {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"BMAD module manifest is invalid; refusing fallback module selection\",\n changedFiles,\n details: [manifestSelection.error],\n };\n }\n const selectedModules = manifestSelection.status === \"valid\"\n ? manifestSelection.modules\n : configuredBmadModules(ctx.repoRoot) ?? [...DEFAULT_BMAD_MODULES];\n if (ctx.dryRun) {\n const sentinels = requiredBmadSentinels(ctx.repoRoot, selectedModules);\n changedFiles.push(...sentinels\n .map((file) => join(ctx.repoRoot, \"_bmad\", file))\n .filter((path) => !existsSync(path)));\n changedFiles.push(...bmadProjectNameIssues(ctx.repoRoot).paths);\n return {\n id: finding.id,\n title: finding.title,\n status: changedFiles.length ? \"applied\" : \"noop\",\n summary: changedFiles.length ? \"Would run non-interactive bmad-method install\" : \"No changes required\",\n changedFiles,\n details: [\n `Would run: ${bmadInstallDisplay(ctx.repoRoot, selectedModules)}`,\n ],\n };\n }\n\n const expectedChangedPaths = [\n ...requiredBmadSentinels(ctx.repoRoot, selectedModules)\n .map((file) => join(ctx.repoRoot, \"_bmad\", file))\n .filter((path) => !existsSync(path)),\n ...bmadProjectNameIssues(ctx.repoRoot).paths,\n ];\n // Clear retired pack symlinks first: they point into a registry cache\n // that no longer holds the pack, and the installer must be able to write\n // real directories at those names.\n const evicted = evictLegacyBmadPackState(ctx, changedFiles);\n const install = runBmadInstall(ctx.repoRoot, selectedModules);\n if (!install.ok) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: `Failed to run bmad-method install`,\n changedFiles: [],\n details: [...evicted, install.error ?? \"Unknown error\"],\n };\n }\n\n changedFiles.push(...expectedChangedPaths.filter(existsSync));\n\n return {\n id: finding.id,\n title: finding.title,\n status: changedFiles.length ? \"applied\" : \"noop\",\n summary: changedFiles.length ? \"Installed BMAD scaffold via bmad-method\" : \"No changes required\",\n changedFiles,\n details: evicted,\n };\n },\n },\n {\n id: \"bmad.version\",\n title: \"BMAD version currency\",\n audit: (ctx) => {\n const installed = readInstalledBmadVersion(ctx.repoRoot);\n if (!installed) {\n // Absence / unreadable manifest is bmad.scaffold's concern, not ours.\n return {\n id: \"bmad.version\",\n title: \"BMAD version currency\",\n status: \"skip\",\n summary: existsSync(join(ctx.repoRoot, \"_bmad\"))\n ? \"BMAD installed but version manifest unreadable\"\n : \"No BMAD install present\",\n details: [],\n fixable: false,\n };\n }\n\n const pinned = ctx.bmadVersionPin?.trim();\n const resolved = pinned ? undefined : resolveBmadDistTags(ctx.homeDir);\n const available = pinned ?? resolved?.distTags?.[BMAD_TARGET_CHANNEL];\n if (!available) {\n return {\n id: \"bmad.version\",\n title: \"BMAD version currency\",\n status: \"skip\",\n summary: `BMAD ${installed} installed; latest ${BMAD_TARGET_CHANNEL} version unknown (npm unreachable)`,\n details: [`Could not resolve ${BMAD_NPM_PACKAGE}@${BMAD_TARGET_CHANNEL} from npm`],\n fixable: false,\n };\n }\n\n const targetLabel = pinned ? `pinned ${available}` : `${BMAD_TARGET_CHANNEL} ${available}`;\n const staleNote = resolved?.stale ? ` ${glyph.dot} cached` : \"\";\n const comparison = compareBmadVersions(installed, available);\n if (pinned ? comparison === 0 : comparison >= 0) {\n return {\n id: \"bmad.version\",\n title: \"BMAD version currency\",\n status: \"pass\",\n summary: `BMAD ${installed} is current (${targetLabel})${staleNote}`,\n details: [],\n fixable: false,\n };\n }\n\n const pinnedMismatch = Boolean(pinned && comparison !== 0);\n const stable = resolved?.distTags.latest;\n // PJAN-82: being behind a MOVING prerelease channel is news, not a defect.\n //\n // The target channel is `next`, which advances every few days\n // (6.11.1-next.1 -> next.27 inside a week). Reporting that as `warn` made\n // every repository on the machine permanently non-parity, because\n // auditRecipes counts anything but pass/skip as not-ok and ProjectRecipe\n // turns a not-ok postcondition audit into a transaction error \u2014 so a\n // brand-new project was \"broken\" the moment upstream cut a prerelease, and\n // `migrate --all` would reinstall BMAD everywhere to chase it. A real\n // currency defect is measured against a floor that does not move: the\n // published stable release, or an explicit transaction pin.\n if (!pinned && !stable) {\n // No published stable tag resolved, so there is no non-moving floor to\n // measure currency against. Say so instead of guessing in either\n // direction.\n return {\n id: \"bmad.version\",\n title: \"BMAD version currency\",\n status: \"skip\",\n summary: `BMAD ${installed} installed; stable currency floor unknown (${BMAD_NPM_PACKAGE} latest unresolved)`,\n details: [`installed: ${installed}`, `available: ${available} (${BMAD_NPM_PACKAGE}@${BMAD_TARGET_CHANNEL})`],\n fixable: false,\n };\n }\n const behindStable = !pinned && stable ? compareBmadVersions(installed, stable) < 0 : false;\n if (!pinned && !behindStable) {\n return {\n id: \"bmad.version\",\n title: \"BMAD version currency\",\n status: \"pass\",\n summary: `BMAD ${installed} is at or ahead of stable ${stable ?? \"unknown\"}; ${targetLabel} available${staleNote}`,\n details: [\n `installed: ${installed}`,\n `available: ${available} (${BMAD_NPM_PACKAGE}@${BMAD_TARGET_CHANNEL})`,\n stable ? `stable latest: ${stable}` : \"\",\n \"run `pj migrate bmad.version` to take the prerelease\",\n ].filter(Boolean),\n fixable: false,\n };\n }\n return {\n id: \"bmad.version\",\n title: \"BMAD version currency\",\n status: pinnedMismatch ? \"fail\" : \"warn\",\n summary: pinnedMismatch\n ? `BMAD ${installed} does not match ${targetLabel}`\n : `BMAD ${installed} is behind stable ${stable} \u2014 upgrade available`,\n details: [\n `installed: ${installed}`,\n pinned ? `required transaction pin: ${available}` : `available: ${available} (${BMAD_NPM_PACKAGE}@${BMAD_TARGET_CHANNEL})`,\n !pinned && stable ? `stable latest: ${stable}` : \"\",\n \"run `pj migrate bmad.version` to upgrade\",\n ].filter(Boolean),\n fixable: true,\n };\n },\n migrate: (ctx, finding) => {\n // PJAN-82: recompute rather than trusting the finding's status.\n //\n // The audit now passes when the only drift is against the moving `next`\n // prerelease channel, so gating on `status === \"warn\"` would make an\n // explicit `pj migrate bmad.version` a silent no-op. `migrate --all`\n // still skips this rule, because it only selects fail/warn findings.\n if (finding.status === \"skip\") {\n return { id: finding.id, title: finding.title, status: \"noop\", summary: finding.summary, changedFiles: [], details: [] };\n }\n {\n const current = readInstalledBmadVersion(ctx.repoRoot);\n const target = ctx.bmadVersionPin?.trim() ?? resolveBmadDistTags(ctx.homeDir)?.distTags?.[BMAD_TARGET_CHANNEL];\n if (!current || !target || compareBmadVersions(current, target) === 0) {\n return { id: finding.id, title: finding.title, status: \"noop\", summary: \"BMAD already current\", changedFiles: [], details: [] };\n }\n }\n\n const installed = readInstalledBmadVersion(ctx.repoRoot);\n const available = ctx.bmadVersionPin?.trim() ?? resolveBmadDistTags(ctx.homeDir)?.distTags?.[BMAD_TARGET_CHANNEL];\n const manifestPath = join(ctx.repoRoot, \"_bmad\", \"_config\", \"manifest.yaml\");\n const manifestSelection = manifestBmadModules(ctx.repoRoot);\n if (manifestSelection.status === \"invalid\") {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"BMAD module manifest is invalid; refusing fallback module selection\",\n changedFiles: [],\n details: [manifestSelection.error],\n };\n }\n const selectedModules = manifestSelection.status === \"valid\"\n ? manifestSelection.modules\n : configuredBmadModules(ctx.repoRoot) ?? [...DEFAULT_BMAD_MODULES];\n\n if (ctx.dryRun) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"applied\",\n summary: `Would upgrade BMAD ${installed ?? \"?\"} -> ${available ?? BMAD_TARGET_CHANNEL}`,\n changedFiles: [manifestPath],\n details: [\n `Would run: ${bmadInstallDisplay(ctx.repoRoot, selectedModules, available ?? BMAD_TARGET_CHANNEL)}`,\n ],\n };\n }\n\n const install = runBmadInstall(ctx.repoRoot, selectedModules, available ?? BMAD_TARGET_CHANNEL);\n if (!install.ok) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"Failed to upgrade BMAD via installer\",\n changedFiles: [],\n details: [install.error ?? \"Unknown error\"],\n };\n }\n const evictedChanges: string[] = [];\n const evicted = evictLegacyBmadPackState(ctx, evictedChanges);\n\n const nowInstalled = readInstalledBmadVersion(ctx.repoRoot);\n const upgraded = Boolean(nowInstalled && installed && compareBmadVersions(nowInstalled, installed) > 0);\n const changed = Array.from(new Set([\n ...(upgraded ? [manifestPath] : []),\n ...evictedChanges,\n ]));\n return {\n id: finding.id,\n title: finding.title,\n status: changed.length ? \"applied\" : \"noop\",\n summary: upgraded ? `Upgraded BMAD ${installed} -> ${nowInstalled}` : `BMAD reinstalled (${nowInstalled ?? \"?\"})`,\n changedFiles: changed,\n details: evicted,\n };\n },\n },\n {\n id: \"bmad.cli-roots\",\n title: \"Supported BMAD CLI projection roots\",\n audit: (ctx) => {\n const unsupportedNames = Object.keys(UNSUPPORTED_BMAD_ROOTS) as (keyof typeof UNSUPPORTED_BMAD_ROOTS)[];\n const present = unsupportedNames.filter((name) => existsSync(join(ctx.repoRoot, name)));\n const attestations = present.map((name) => ({ name, ...unsupportedRootAttestation(ctx.repoRoot, name) }));\n const supportedIssues = supportedCliProjectionIssues(ctx.repoRoot);\n const details = [\n ...supportedIssues,\n ...supportedCliGitignoreIssues(ctx.repoRoot),\n ...attestations.map((entry) => `${entry.name}: ${entry.safe ? \"generated and safely removable\" : `ambiguous/user-owned \u2014 ${entry.reason}`}`),\n ];\n return {\n id: \"bmad.cli-roots\",\n title: \"Supported BMAD CLI projection roots\",\n status: details.length ? \"fail\" : \"pass\",\n summary: details.length\n ? `${supportedIssues.length} supported projection issue(s); ${present.length} unsupported root(s)`\n : \"All six supported CLI projections are configured and no unsupported roots are present\",\n details,\n fixable: attestations.every((entry) => entry.safe),\n };\n },\n migrate: (ctx, finding) => {\n const unsupportedNames = Object.keys(UNSUPPORTED_BMAD_ROOTS) as (keyof typeof UNSUPPORTED_BMAD_ROOTS)[];\n const present = unsupportedNames.filter((name) => existsSync(join(ctx.repoRoot, name)));\n const attestations = present.map((name) => ({ name, ...unsupportedRootAttestation(ctx.repoRoot, name) }));\n const blocked = attestations.filter((entry) => !entry.safe);\n if (blocked.length) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"Refusing to remove ambiguous or user-owned CLI projection roots\",\n changedFiles: [],\n details: blocked.map((entry) => `${entry.name}: ${entry.reason}`),\n };\n }\n const projectionResult = ensureSupportedCliProjections(ctx);\n if (projectionResult.blockers.length) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"Supported CLI projections contain unsafe or user-owned conflicts\",\n changedFiles: [],\n details: projectionResult.blockers,\n };\n }\n const gitignoreChanges = ensureSupportedCliGitignore(ctx);\n const removedRoots = attestations.map((entry) => join(ctx.repoRoot, entry.name));\n if (!ctx.dryRun) for (const path of removedRoots) rmSync(path, { recursive: true, force: true });\n const changedFiles = [...new Set([...projectionResult.changedFiles, ...gitignoreChanges, ...removedRoots])].sort();\n return {\n id: finding.id,\n title: finding.title,\n status: changedFiles.length ? \"applied\" : \"noop\",\n summary: changedFiles.length\n ? `Reconciled six supported projections and removed ${removedRoots.length} attested unsupported root(s)`\n : \"No changes required\",\n changedFiles,\n details: attestations.map((entry) => `${entry.name}: ${entry.reason}`),\n };\n },\n },\n];\n}\n\nexport function createHermesChecks(): RecipeOwnedCheck[] {\nreturn [\n {\n id: \"hermes.pm-scaffold\",\n title: \"Hermes orchestrator scaffold parity\",\n audit: (ctx) => {\n const selection = managedHermesScaffoldRoles(ctx);\n if (selection.roles.length === 0 && selection.blockers.length === 0) {\n return { id: \"hermes.pm-scaffold\", title: \"Hermes orchestrator scaffold parity\", status: \"skip\", summary: \"No provisioned pm or director role present\", details: [], fixable: false };\n }\n const details: string[] = [...selection.blockers];\n const templateRoleDir = join(ctx.pjanglerRoot, \"templates\", \"hermes-agent\", \"template\");\n const managedScripts = templateFiles(join(templateRoleDir, \".scripts\"))\n .filter((rel) => rel !== \"sentinel.prompt.md.jinja\");\n for (const role of selection.roles) {\n const prefix = role.agentId || role.role;\n for (const rel of [\"role.yaml\", \"SOUL.md\", \".runtime-scaffold/README.md\", \"runtime/memories/MEMORY.md\"]) {\n if (!existsSync(join(role.roleDir, rel))) details.push(`${prefix}: missing ${relative(ctx.repoRoot, join(role.roleDir, rel))}`);\n }\n const wrapper = join(role.roleDir, \"hermes\");\n const expectedWrapper = renderHermesWrapper(role, templateRoleDir);\n if (!existsSync(wrapper)) details.push(`${prefix}: missing ${relative(ctx.repoRoot, wrapper)}`);\n else if (safeReadText(wrapper) !== expectedWrapper) details.push(`${prefix}: stale ${relative(ctx.repoRoot, wrapper)}`);\n const expectedIgnore = readText(join(templateRoleDir, \".gitignore.jinja\")).replace(/\\{\\{\\s*role\\s*\\}\\}/g, role.role);\n const ignorePath = join(role.roleDir, \".gitignore\");\n if (!existsSync(ignorePath)) details.push(`${prefix}: missing ${relative(ctx.repoRoot, ignorePath)}`);\n else if (safeReadText(ignorePath) !== expectedIgnore) details.push(`${prefix}: stale ${relative(ctx.repoRoot, ignorePath)}`);\n for (const rel of managedScripts) {\n const source = join(templateRoleDir, \".scripts\", rel);\n const target = join(role.roleDir, \".scripts\", rel);\n if (!existsSync(target)) details.push(`${prefix}: missing ${relative(ctx.repoRoot, target)}`);\n else if (safeReadText(target) !== readText(source)) details.push(`${prefix}: stale ${relative(ctx.repoRoot, target)}`);\n }\n const promptPath = join(role.roleDir, \".scripts\", \"sentinel.prompt.md\");\n if (!existsSync(promptPath)) details.push(`${prefix}: missing ${relative(ctx.repoRoot, promptPath)}`);\n else if (safeReadText(promptPath) !== renderSentinelPrompt(role, templateRoleDir)) details.push(`${prefix}: stale ${relative(ctx.repoRoot, promptPath)}`);\n if (hasRuntimeSubmoduleMapping(ctx.repoRoot, role)) details.push(`${prefix}: .gitmodules contains retired ${role.role} runtime submodule mapping`);\n if (!profileMetaInheritsDefault(join(role.roleDir, \"runtime\", \"profile.yaml\"))) details.push(`${prefix}: runtime/profile.yaml missing inherited default config metadata`);\n const registry = safeReadText(registryPath(ctx.homeDir));\n if (!registry?.includes(`${role.agentId}:`)) details.push(`fleet registry missing ${role.agentId}`);\n }\n return {\n id: \"hermes.pm-scaffold\",\n title: \"Hermes orchestrator scaffold parity\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? `${selection.roles.length} orchestrator scaffold(s) verified` : `${details.length} orchestrator scaffold issue(s) detected`,\n details,\n fixable: selection.blockers.length === 0,\n };\n },\n migrate: (ctx, finding) => {\n const selection = managedHermesScaffoldRoles(ctx);\n const changedFiles: string[] = [];\n const details: string[] = [];\n if (selection.blockers.length > 0) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: \"Provisioned orchestrator manifest is invalid\", changedFiles, details: selection.blockers };\n }\n if (selection.roles.length === 0) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: \"No provisioned pm or director role present\", changedFiles, details: [] };\n }\n const templateRoleDir = join(ctx.pjanglerRoot, \"templates\", \"hermes-agent\", \"template\");\n const managedScripts = templateFiles(join(templateRoleDir, \".scripts\"))\n .filter((rel) => rel !== \"sentinel.prompt.md.jinja\");\n for (const role of selection.roles) {\n const retirement = retireRuntimeSubmodule(ctx.repoRoot, role, changedFiles, ctx.dryRun);\n details.push(...retirement.details);\n if (!retirement.ok) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: `Failed to retire ${role.role} runtime submodule metadata safely`, changedFiles, details: [retirement.error ?? \"unknown runtime retirement failure\"] };\n }\n if (!existsSync(join(role.roleDir, \"SOUL.md\"))) writeIfDifferent(join(role.roleDir, \"SOUL.md\"), renderSoul(role), ctx.dryRun, changedFiles);\n writeIfDifferent(join(role.roleDir, \"hermes\"), renderHermesWrapper(role, templateRoleDir), ctx.dryRun, changedFiles, 0o755);\n writeIfDifferent(join(role.roleDir, \".gitignore\"), readText(join(templateRoleDir, \".gitignore.jinja\")).replace(/\\{\\{\\s*role\\s*\\}\\}/g, role.role), ctx.dryRun, changedFiles);\n copyMissingRecursive(join(templateRoleDir, \".runtime-scaffold\"), join(role.roleDir, \".runtime-scaffold\"), changedFiles, ctx.dryRun);\n copyMissingRecursive(join(templateRoleDir, \".runtime-scaffold\"), join(role.roleDir, \"runtime\"), changedFiles, ctx.dryRun);\n for (const rel of managedScripts) {\n const source = join(templateRoleDir, \".scripts\", rel);\n const executable = (lstatSync(source).mode & 0o111) !== 0;\n writeIfDifferent(join(role.roleDir, \".scripts\", rel), readText(source), ctx.dryRun, changedFiles, executable ? 0o755 : undefined);\n }\n writeIfDifferent(join(role.roleDir, \".scripts\", \"sentinel.prompt.md\"), renderSentinelPrompt(role, templateRoleDir), ctx.dryRun, changedFiles);\n const profileMetaUpdated = upsertInheritedProfileMeta(join(role.roleDir, \"runtime\", \"profile.yaml\"), changedFiles, ctx.dryRun);\n if (profileMetaUpdated) details.push(`updated ${profileMetaUpdated}`);\n const registryUpdated = upsertRegistryEntry(role, ctx.homeDir, changedFiles, ctx.dryRun);\n if (registryUpdated) details.push(`updated ${registryUpdated}`);\n }\n return {\n id: finding.id,\n title: finding.title,\n status: changedFiles.length ? \"applied\" : \"noop\",\n summary: changedFiles.length ? `${selection.roles.length} orchestrator scaffold(s) normalized` : \"No changes required\",\n changedFiles,\n details,\n };\n },\n },\n {\n id: \"hermes.untracked-runtimes\",\n title: \"Hermes agent runtimes untracked + gitignored\",\n audit: (ctx) => {\n const roles = discoverRoles(ctx.repoRoot);\n if (roles.length === 0) {\n return {\n id: \"hermes.untracked-runtimes\",\n title: \"Hermes agent runtimes untracked + gitignored\",\n status: \"skip\",\n summary: \"No Hermes roles present\",\n details: [],\n fixable: false,\n };\n }\n const details: string[] = [];\n for (const role of roles) {\n const roleRelDir = relative(ctx.repoRoot, role.roleDir);\n const runtimeRelPath = join(roleRelDir, \"runtime\");\n\n // 1. Check if tracked in git\n const lsResult = spawnSync(\"git\", [\"ls-files\", \"--stage\", runtimeRelPath], {\n cwd: ctx.repoRoot,\n encoding: \"utf8\",\n });\n if (lsResult.status === 0 && lsResult.stdout.trim().length > 0) {\n details.push(`submodule runtime is tracked in Git index at ${runtimeRelPath}`);\n }\n\n if (hasRuntimeSubmoduleMapping(ctx.repoRoot, role)) {\n details.push(`stale .gitmodules mapping exists for ${runtimeRelPath}`);\n }\n\n // 2. Check if .gitignore ignores runtime/\n const gitignorePath = join(role.roleDir, \".gitignore\");\n if (existsSync(gitignorePath)) {\n const content = safeReadText(gitignorePath) ?? \"\";\n const lines = content.split(/\\r?\\n/).map((line) => line.trim());\n if (!lines.includes(\"runtime/\") && !lines.includes(\"runtime\")) {\n details.push(`.gitignore missing runtime/ ignore entry in ${relative(ctx.repoRoot, gitignorePath)}`);\n }\n } else {\n details.push(`.gitignore is missing in ${relative(ctx.repoRoot, gitignorePath)}`);\n }\n }\n\n return {\n id: \"hermes.untracked-runtimes\",\n title: \"Hermes agent runtimes untracked + gitignored\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? \"All Hermes agent runtimes are untracked and gitignored\" : `${details.length} issue(s) with untracked/ignored runtimes detected`,\n details,\n fixable: true,\n };\n },\n migrate: (ctx, finding) => {\n const roles = discoverRoles(ctx.repoRoot);\n const changedFiles: string[] = [];\n const details: string[] = [];\n\n for (const role of roles) {\n const retirement = retireRuntimeSubmodule(ctx.repoRoot, role, changedFiles, ctx.dryRun);\n details.push(...retirement.details);\n if (!retirement.ok) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"Failed to retire Hermes runtime submodule metadata safely\",\n changedFiles,\n details: [retirement.error ?? \"unknown runtime retirement failure\"],\n };\n }\n\n // Update .gitignore only after index removal is verified and the stale\n // mapping has been retired.\n const gitignorePath = join(role.roleDir, \".gitignore\");\n let content = \"\";\n let isIgnored = false;\n if (existsSync(gitignorePath)) {\n content = safeReadText(gitignorePath) ?? \"\";\n const lines = content.split(/\\r?\\n/).map((line) => line.trim());\n isIgnored = lines.includes(\"runtime/\") || lines.includes(\"runtime\");\n }\n\n if (!isIgnored) {\n details.push(`ignore runtime/ in ${relative(ctx.repoRoot, gitignorePath)}`);\n changedFiles.push(gitignorePath);\n if (!ctx.dryRun) {\n if (content && !content.endsWith(\"\\n\")) {\n content += \"\\n\";\n }\n content += \"runtime/\\n\";\n writeText(gitignorePath, content);\n }\n }\n }\n\n return {\n id: finding.id,\n title: finding.title,\n status: changedFiles.length ? \"applied\" : \"noop\",\n summary: changedFiles.length ? \"Hermes agent runtimes made untracked and ignored\" : \"No changes required\",\n changedFiles,\n details,\n };\n },\n },\n {\n id: \"systemd.sentinel\",\n title: \"Hermes systemd/sentinel units enabled + active\",\n // PJAN-84: host-scoped \u2014 systemd --user units on this machine.\n scope: \"host\",\n audit: (ctx) => {\n const roles = discoverRoles(ctx.repoRoot);\n if (!roles.length) {\n return { id: \"systemd.sentinel\", title: \"Hermes systemd/sentinel units enabled + active\", status: \"skip\", summary: \"No Hermes roles present\", details: [], fixable: false };\n }\n const requiredRoles = roles.filter((role) => role.deploymentSystemd !== \"deferred\");\n if (!requiredRoles.length) {\n return { id: \"systemd.sentinel\", title: \"Hermes systemd/sentinel units enabled + active\", status: \"pass\", summary: \"systemd is intentionally deferred for every local-only Hermes role\", details: [], fixable: false };\n }\n const probe = systemctlUser([\"is-system-running\"]);\n if (!probe.ok && !/running|degraded|starting|maintenance/.test(`${probe.stdout} ${probe.stderr}`)) {\n const sysDir = join(ctx.homeDir, \".config\", \"systemd\", \"user\");\n const details: string[] = [];\n for (const role of requiredRoles) {\n const gateway = role.serviceStateGateway || \"active\";\n const heartbeat = role.serviceStateHeartbeat || \"active\";\n for (const unit of [`hermes-${role.agentId}-gateway.service`, `hermes-${role.agentId}-heartbeat.timer`]) {\n if (!existsSync(join(sysDir, unit))) details.push(`${unit} should be installed`);\n }\n if (heartbeat !== \"installed\") details.push(`${role.agentId} heartbeat should record installed while systemd --user is unavailable (got ${heartbeat})`);\n if (gateway !== \"installed\" && gateway !== \"deferred\") details.push(`${role.agentId} gateway should record installed or deferred while systemd --user is unavailable (got ${gateway})`);\n }\n return {\n id: \"systemd.sentinel\",\n title: \"Hermes systemd/sentinel units enabled + active\",\n status: details.length ? \"warn\" : \"pass\",\n summary: details.length ? \"systemd --user unavailable and installed-state metadata is incomplete\" : \"Hermes units are installed; activation is deferred because systemd --user is unavailable\",\n details,\n fixable: false,\n };\n }\n const details: string[] = [];\n const sysDir = join(ctx.homeDir, \".config\", \"systemd\", \"user\");\n for (const role of requiredRoles) {\n const gatewayUnit = `hermes-${role.agentId}-gateway.service`;\n const heartbeatUnit = `hermes-${role.agentId}-heartbeat.timer`;\n const gatewayState = role.serviceStateGateway || \"active\";\n const heartbeatState = role.serviceStateHeartbeat || \"active\";\n for (const unit of [gatewayUnit, heartbeatUnit]) {\n if (!existsSync(join(sysDir, unit))) details.push(`${unit} should be installed`);\n }\n const heartbeat = checkUnit(heartbeatUnit);\n if (heartbeatState !== \"active\" || !heartbeat.enabled || !heartbeat.active) {\n details.push(`${heartbeatUnit} should be enabled+active (manifest: ${heartbeatState || \"missing\"})`);\n }\n const gateway = checkUnit(gatewayUnit);\n if (gatewayState === \"deferred\") {\n if (gateway.enabled || gateway.active) details.push(`${gatewayUnit} is deferred and should be disabled+inactive`);\n } else if (gatewayState !== \"active\" || !gateway.enabled || !gateway.active) {\n details.push(`${gatewayUnit} should be enabled+active (manifest: ${gatewayState || \"missing\"})`);\n }\n }\n return {\n id: \"systemd.sentinel\",\n title: \"Hermes systemd/sentinel units enabled + active\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? \"Hermes user units match each role's declared service state\" : `${details.length} systemd parity issue(s) detected`,\n details,\n fixable: true,\n };\n },\n migrate: (ctx, finding) => {\n const roles = discoverRoles(ctx.repoRoot).filter((role) => role.deploymentSystemd !== \"deferred\");\n const changedFiles: string[] = [];\n const details: string[] = [];\n if (!roles.length) {\n return { id: finding.id, title: finding.title, status: \"skipped\", summary: \"systemd is intentionally deferred for local-only Hermes roles\", changedFiles, details };\n }\n const probe = systemctlUser([\"is-system-running\"]);\n if (!probe.ok && !/running|degraded|starting|maintenance/.test(`${probe.stdout} ${probe.stderr}`)) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: \"systemd --user unavailable on this host\", changedFiles, details };\n }\n for (const role of roles) {\n const sysDir = join(ctx.homeDir, \".config\", \"systemd\", \"user\");\n const units = [`hermes-${role.agentId}-gateway.service`, `hermes-${role.agentId}-heartbeat.timer`];\n const allUnitsPresent = units.every((unit) => existsSync(join(sysDir, unit)));\n // Existing units can still point at the checkout's former location.\n // In that case enabling them again preserves the stale ExecStart path,\n // so regenerate them from the role's current provisioning script.\n const unitsStale = units.some((unit) => {\n const text = safeReadText(join(sysDir, unit));\n if (text === null) return true;\n return text.includes(\"/agents/hermes/\") && !text.includes(role.roleDir);\n });\n const manifestNeedsReconcile = [role.serviceStateGateway, role.serviceStateHeartbeat]\n .some((state) => state === \"pending\" || state === \"error\");\n if (allUnitsPresent && !unitsStale && !manifestNeedsReconcile) {\n reconcileHermesRoleUnits(ctx, role, changedFiles, details);\n continue;\n }\n let regenerated = false;\n for (const script of [join(role.roleDir, \".scripts\", \"70-systemd.sh\")]) {\n if (!existsSync(script)) {\n details.push(`script failed: missing ${script}`);\n continue;\n }\n if (ctx.dryRun) {\n details.push(`would run: FORCE_SYSTEMD=1 bash ${script}`);\n } else {\n const result = spawnSync(\"bash\", [script], {\n cwd: role.roleDir,\n encoding: \"utf8\",\n env: { ...process.env, FORCE_SYSTEMD: \"1\" },\n });\n if (result.status !== 0) {\n details.push(`script failed: ${script}: ${result.stderr.trim() || result.stdout.trim()}`);\n } else {\n regenerated = true;\n details.push(`regenerated systemd units for ${role.agentId} from ${role.roleDir}`);\n }\n }\n }\n if (ctx.dryRun) continue;\n if (regenerated) {\n const refreshed = discoverRoles(ctx.repoRoot).find((candidate) => candidate.agentId === role.agentId);\n if (!refreshed) {\n details.push(`script failed: regenerated role ${role.agentId} could not be rediscovered`);\n } else {\n reconcileHermesRoleUnits(ctx, refreshed, changedFiles, details);\n }\n }\n }\n return {\n id: finding.id,\n title: finding.title,\n status: details.some((detail) => detail.includes(\"failed:\")) ? \"blocked\" : details.length ? (ctx.dryRun ? \"skipped\" : \"applied\") : \"noop\",\n summary: details.length ? (ctx.dryRun ? \"Planned systemd remediation commands\" : \"Reconciled and verified systemd service state\") : \"No changes required\",\n changedFiles,\n details,\n };\n },\n },\n {\n id: \"hermes.runtime-singleton\",\n title: \"Hermes singleton runtime (shared config/auth, per-agent memory)\",\n audit: (ctx) => {\n const roles = discoverRoles(ctx.repoRoot);\n if (!roles.length) {\n return { id: \"hermes.runtime-singleton\", title: \"Hermes singleton runtime (shared config/auth, per-agent memory)\", status: \"skip\", summary: \"No Hermes roles present\", details: [], fixable: false };\n }\n const details: string[] = [];\n for (const role of roles) {\n const plan = singletonPlan(ctx, role);\n if (!existsSync(plan.fleetRoot)) {\n details.push(`fleet root missing at ${plan.fleetRoot}`);\n continue;\n }\n // The profile entry must be a REAL directory. If it is a symlink,\n // get_active_profile_name() resolves through it, escapes the profiles\n // root, and reports \"custom\" instead of the profile name.\n if (!existsSync(plan.profileDir)) {\n details.push(`profile dir missing: ${plan.profileDir}`);\n } else if (lstatSync(plan.profileDir).isSymbolicLink()) {\n details.push(`profile dir is a symlink (must be a real dir): ${plan.profileDir}`);\n }\n for (const link of plan.links) {\n const state = linkState(link.path, link.target);\n if (state !== \"ok\") details.push(`${state}: ${link.path} -> ${link.target}`);\n }\n details.push(...profileConfigFindings(plan.profileDir, profileNameOf(role)));\n }\n return {\n id: \"hermes.runtime-singleton\",\n title: \"Hermes singleton runtime (shared config/auth, per-agent memory)\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? \"Singleton runtime contract satisfied\" : `${details.length} singleton-runtime issue(s) detected`,\n details,\n fixable: true,\n };\n },\n migrate: (ctx, finding) => {\n const roles = discoverRoles(ctx.repoRoot);\n const changedFiles: string[] = [];\n const details: string[] = [];\n for (const role of roles) {\n const plan = singletonPlan(ctx, role);\n if (!existsSync(plan.fleetRoot)) {\n details.push(`blocked: fleet root missing at ${plan.fleetRoot}`);\n continue;\n }\n // Seed the shared singletons from the richest existing runtime copy so a\n // first migration never lands agents on an empty config.\n for (const shared of plan.sharedSeeds) {\n if (existsSync(shared.rootPath)) continue;\n const donor = existsSync(shared.runtimePath) ? shared.runtimePath : null;\n if (!donor) continue;\n details.push(`seed fleet ${basename(shared.rootPath)} from ${donor}`);\n changedFiles.push(shared.rootPath);\n if (!ctx.dryRun) copyFileSync(donor, shared.rootPath);\n }\n // Replace a symlinked profile entry with a real directory.\n if (existsSync(plan.profileDir) && lstatSync(plan.profileDir).isSymbolicLink()) {\n details.push(`convert profile symlink to real dir: ${plan.profileDir}`);\n changedFiles.push(plan.profileDir);\n if (!ctx.dryRun) unlinkSync(plan.profileDir);\n }\n if (!existsSync(plan.profileDir)) {\n details.push(`create profile dir: ${plan.profileDir}`);\n changedFiles.push(plan.profileDir);\n if (!ctx.dryRun) mkdirSync(plan.profileDir, { recursive: true });\n }\n for (const link of plan.links) {\n const state = linkState(link.path, link.target);\n if (state === \"ok\") continue;\n // Person-owned targets must exist before linking or the agent starts\n // against a dangling path and silently recreates empty state.\n if (link.ensureTargetDir && !existsSync(link.target) && !ctx.dryRun) {\n mkdirSync(link.target, { recursive: true });\n }\n details.push(`link ${link.path} -> ${link.target}`);\n changedFiles.push(link.path);\n if (ctx.dryRun) continue;\n if (existsSync(link.path) || isDanglingLink(link.path)) {\n const lst = lstatSync(link.path);\n if (lst.isSymbolicLink()) {\n unlinkSync(link.path);\n } else {\n // Never discard real user data: park it beside the profile.\n const parked = `${link.path}.pre-singleton`;\n renameSync(link.path, parked);\n details.push(`parked pre-existing ${link.path} at ${parked}`);\n }\n }\n ensureParent(link.path);\n symlinkSync(link.target, link.path);\n }\n // Render config.yaml from base+delta and pin the identity-memory bank.\n // This deliberately does NOT symlink config.yaml (see\n // SHARED_PROFILE_ENTRIES): the renderer owns that file now.\n const profileName = profileNameOf(role);\n if (profileConfigFindings(plan.profileDir, profileName).length) {\n const renderer = profileRendererPath(ctx);\n if (!renderer) {\n details.push(`blocked: profile renderer not found (expected hermes-agent-template/scripts/hermes-profile-config.py); cannot render ${plan.profileDir}/config.yaml`);\n } else {\n details.push(`render config.yaml + pin memory bank for ${profileName}`);\n changedFiles.push(join(plan.profileDir, \"config.yaml\"), join(plan.profileDir, \"config.delta.yaml\"));\n if (!ctx.dryRun) {\n for (const args of [[\"init\", \"--profile\", profileName], [\"memory-pin\", \"--profile\", profileName]]) {\n const res = spawnSync(\"python3\", [renderer, ...args], { encoding: \"utf8\" });\n if (res.status !== 0) {\n details.push(`blocked: ${basename(renderer)} ${args[0]} failed for ${profileName}: ${(res.stderr || res.stdout || \"\").trim().split(\"\\n\").slice(-2).join(\" \")}`);\n }\n }\n }\n }\n }\n }\n return {\n id: finding.id,\n title: finding.title,\n status: details.some((d) => d.startsWith(\"blocked:\")) ? \"blocked\" : changedFiles.length ? (ctx.dryRun ? \"skipped\" : \"applied\") : \"noop\",\n // PJAN-75: the summary has to follow the status. The blocked branch was\n // missing here, so a run that stopped on a missing profile renderer\n // still reported \"Singleton runtime wired\" -- and that string is what\n // surfaced as the recipe's ERROR message, telling the operator the\n // exact opposite of what happened.\n summary: details.some((d) => d.startsWith(\"blocked:\"))\n ? \"Singleton-runtime wiring blocked\"\n : changedFiles.length ? (ctx.dryRun ? \"Planned singleton-runtime wiring\" : \"Singleton runtime wired\") : \"No changes required\",\n changedFiles,\n details,\n };\n },\n },\n {\n // Fleet-base invariants. Every profile inherits ~/.hermes/config.yaml by\n // generation, so a defect here is a defect in EVERY agent at once \u2014 and each\n // of these has already shipped silently: no error, no log, just an agent\n // quietly missing a capability.\n id: \"hermes.fleet-config\",\n title: \"Fleet base config carries the capabilities every agent inherits\",\n // PJAN-84: host-scoped \u2014 $HOME/.hermes/fleet.env, shared by every agent.\n scope: \"host\",\n audit: (ctx) => {\n const roles = discoverRoles(ctx.repoRoot);\n if (!roles.length) {\n return { id: \"hermes.fleet-config\", title: \"Fleet base config carries the capabilities every agent inherits\", status: \"skip\", summary: \"No Hermes roles present\", details: [], fixable: false };\n }\n const base = join(fleetHome(ctx), \"config.yaml\");\n const details: string[] = [];\n let cfg: any = null;\n if (!existsSync(base)) {\n details.push(`fleet base config missing: ${base}`);\n } else {\n try {\n cfg = YAML.parse(readFileSync(base, \"utf8\")) ?? {};\n } catch (err) {\n details.push(`fleet base config is unparseable YAML: ${base} (${(err as Error).message})`);\n }\n }\n\n if (cfg) {\n // TTS provider must be the REGISTRY KEY, not the product name. \"voxxy\"\n // is the service (swappable engines: voxcpm/vibevoice/elevenlabs); the\n // Hermes plugin registers as \"vox\". An unknown provider does not error \u2014\n // Hermes falls back to a built-in (ElevenLabs when the key is set, else\n // Edge) and you simply hear the wrong voice. Regressed twice.\n const ttsProvider = cfg?.tts?.provider;\n if (ttsProvider && ttsProvider !== \"vox\") {\n details.push(`tts.provider is \"${ttsProvider}\" \u2014 must be \"vox\" (registry key). \"voxxy\" is the service name and matches no registered provider, so TTS silently falls back to a built-in.`);\n }\n\n // Bloodbank lifecycle hooks. These lived on 3 of 36 profiles once, so 33\n // agents emitted no events at all while appearing healthy.\n const hooks = cfg?.hooks;\n const REQUIRED_HOOKS = [\"on_session_start\", \"on_session_end\", \"pre_tool_call\", \"post_tool_call\"];\n if (!hooks || typeof hooks !== \"object\") {\n details.push(`no hooks: block in the fleet base \u2014 every agent publishes zero Bloodbank lifecycle events: ${base}`);\n } else {\n const missing = REQUIRED_HOOKS.filter((h) => !hooks[h]);\n if (missing.length) details.push(`fleet base hooks missing event(s): ${missing.join(\", \")}`);\n const serialized = JSON.stringify(hooks);\n if (!serialized.includes(\"hooks/bloodbank/publish.py\")) {\n details.push(`fleet base hooks do not call the canonical publisher (~/.agents/hooks/bloodbank/publish.py --client hermes)`);\n }\n }\n\n // Memory: the provider can be configured and still be muzzled. Tool\n // injection is gated by agent.disabled_toolsets while auto recall/retain\n // keeps running underneath, so \"memory works\" and \"the agent can use\n // memory\" are different questions.\n const provider = cfg?.memory?.provider;\n if (!provider) {\n details.push(`memory.provider is unset in the fleet base \u2014 agents get no external memory`);\n }\n const disabled: unknown = cfg?.agent?.disabled_toolsets;\n if (Array.isArray(disabled) && disabled.includes(\"memory\")) {\n details.push(`agent.disabled_toolsets contains \"memory\" \u2014 memory tools are suppressed fleet-wide even though memory.provider is set (auto recall/retain still runs, which masks it)`);\n }\n\n // Skills reach agents only through external_dirs; a profile that\n // inherits an empty list silently has no skills at all.\n const dirs: unknown = cfg?.skills?.external_dirs;\n if (!Array.isArray(dirs) || dirs.length === 0) {\n details.push(`skills.external_dirs is empty in the fleet base \u2014 no agent can see any shared skill`);\n }\n }\n\n return {\n id: \"hermes.fleet-config\",\n title: \"Fleet base config carries the capabilities every agent inherits\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? \"Fleet base config invariants satisfied\" : `${details.length} fleet-base config issue(s) detected`,\n details,\n // Deliberately not auto-fixable: these are fleet-wide values whose\n // correct setting is an operator decision, and a wrong guess would\n // change behavior for every agent simultaneously.\n fixable: false,\n };\n },\n // The audit above is `fixable: false`, so `migrate --all` never selects\n // this rule -- but naming it explicitly must still produce an answer. It\n // shipped with no migrate at all, which the registry surfaced as\n // \"migrate threw: check.migrate is not a function\": true, but useless.\n migrate: (ctx, finding) => ({\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"Fleet base config is operator-owned; pjangler will not guess fleet-wide values\",\n changedFiles: [],\n details: finding.details.length\n ? [...finding.details, `Edit ${join(ctx.homeDir, \".hermes\", \"config.yaml\")} directly, then re-run audit`]\n : [`Edit ${join(ctx.homeDir, \".hermes\", \"config.yaml\")} directly, then re-run audit`],\n }),\n },\n {\n id: \"hermes.profile-wiring\",\n title: \"Launcher + systemd HERMES_HOME points at the named profile\",\n // PJAN-84: host-scoped \u2014 $HOME/.hermes/profiles and the launcher's HERMES_HOME.\n scope: \"host\",\n audit: (ctx) => {\n const roles = discoverRoles(ctx.repoRoot);\n if (!roles.length) {\n return { id: \"hermes.profile-wiring\", title: \"Launcher + systemd HERMES_HOME points at the named profile\", status: \"skip\", summary: \"No Hermes roles present\", details: [], fixable: false };\n }\n const details: string[] = [];\n for (const role of roles) {\n const plan = singletonPlan(ctx, role);\n const launcher = join(role.roleDir, \"hermes\");\n const text = safeReadText(launcher);\n if (text === null) {\n details.push(`launcher missing: ${relative(ctx.repoRoot, launcher)}`);\n } else {\n // Match the ASSIGNMENT, not one known-bad spelling of it. Earlier\n // revisions only tested for `HERMES_HOME=\"$RUNTIME_HOME\"`, so every\n // launcher still carrying the older `HERMES_HOME=\"$ROLE_DIR/runtime\"`\n // form \u2014 which is what the fleet template emitted \u2014 passed this audit\n // while running split-brain against its own systemd unit.\n const assigned = /^HERMES_HOME=(.*)$/m.exec(text)?.[1]?.trim();\n if (assigned !== undefined && !isProfileHomeExpr(assigned)) {\n details.push(`launcher sets HERMES_HOME=${assigned} instead of the named profile dir (disables shared auth + profile identity): ${relative(ctx.repoRoot, launcher)}`);\n }\n if (/HERMES_OAUTH_FILE/.test(text)) {\n details.push(`launcher exports HERMES_OAUTH_FILE, which Hermes does not implement (dead config): ${relative(ctx.repoRoot, launcher)}`);\n }\n }\n for (const unit of profileUnits(role)) {\n const unitPath = join(ctx.homeDir, \".config\", \"systemd\", \"user\", unit);\n const unitText = safeReadText(unitPath);\n if (unitText === null) continue;\n const current = /^Environment=HERMES_HOME=(.*)$/m.exec(unitText)?.[1]?.trim();\n if (current && current !== plan.profileDir) {\n details.push(`${unit} HERMES_HOME=${current} (expected ${plan.profileDir})`);\n }\n if (/^Environment=HERMES_OAUTH_FILE=/m.test(unitText)) {\n details.push(`${unit} sets HERMES_OAUTH_FILE (dead config)`);\n }\n }\n }\n return {\n id: \"hermes.profile-wiring\",\n title: \"Launcher + systemd HERMES_HOME points at the named profile\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? \"HERMES_HOME wiring is in parity\" : `${details.length} HERMES_HOME wiring issue(s) detected`,\n details,\n fixable: true,\n };\n },\n migrate: (ctx, finding) => {\n const roles = discoverRoles(ctx.repoRoot);\n const changedFiles: string[] = [];\n const details: string[] = [];\n let unitsTouched = false;\n for (const role of roles) {\n const plan = singletonPlan(ctx, role);\n const launcher = join(role.roleDir, \"hermes\");\n const text = safeReadText(launcher);\n if (text !== null) {\n const before = /^HERMES_HOME=(.*)$/m.exec(text)?.[1]?.trim();\n const rewritten = rewriteLauncher(text, role.profileName || role.agentId);\n if (rewritten !== text) {\n // Say which change actually happened \u2014 the previous single message\n // claimed a HERMES_HOME rewrite even when only the dead\n // HERMES_OAUTH_FILE export was stripped.\n const rel = relative(ctx.repoRoot, launcher);\n if (before !== undefined && !isProfileHomeExpr(before)) {\n details.push(`rewrite launcher HERMES_HOME ${before} -> ${plan.profileDir}: ${rel}`);\n }\n if (/HERMES_OAUTH_FILE/.test(text)) {\n details.push(`strip dead HERMES_OAUTH_FILE export: ${rel}`);\n }\n writeIfDifferent(launcher, rewritten, ctx.dryRun, changedFiles, 0o755);\n }\n }\n for (const unit of profileUnits(role)) {\n const unitPath = join(ctx.homeDir, \".config\", \"systemd\", \"user\", unit);\n const unitText = safeReadText(unitPath);\n if (unitText === null) continue;\n let next = unitText.replace(/^Environment=HERMES_HOME=.*$/m, `Environment=HERMES_HOME=${plan.profileDir}`);\n next = next.replace(/^Environment=HERMES_OAUTH_FILE=.*\\n/m, \"\");\n if (next !== unitText) {\n details.push(`repoint ${unit} HERMES_HOME -> ${plan.profileDir}`);\n writeIfDifferent(unitPath, next, ctx.dryRun, changedFiles);\n unitsTouched = true;\n }\n }\n }\n if (unitsTouched && !ctx.dryRun) {\n systemctlUser([\"daemon-reload\"]);\n details.push(\"systemctl --user daemon-reload (restart units to pick up the new HERMES_HOME)\");\n }\n return {\n id: finding.id,\n title: finding.title,\n status: changedFiles.length ? (ctx.dryRun ? \"skipped\" : \"applied\") : \"noop\",\n summary: changedFiles.length ? (ctx.dryRun ? \"Planned HERMES_HOME rewiring\" : \"HERMES_HOME rewired to named profiles\") : \"No changes required\",\n changedFiles,\n details,\n };\n },\n },\n {\n id: \"hermes.registry-parity\",\n title: \"Fleet registry matches .project.json (no duplicate or stale agents)\",\n // PJAN-84: host-scoped \u2014 $HOME/.hermes/agents-registry.yaml.\n scope: \"host\",\n audit: (ctx) => {\n const roles = discoverRoles(ctx.repoRoot);\n const details: string[] = [];\n let malformedRoleGate = false;\n const registryPath = join(ctx.homeDir, \".hermes\", \"agents-registry.yaml\");\n const registry = readRegistry(registryPath);\n if (!registry) {\n if (!roles.length && declaredAgentIds(ctx.repoRoot).length === 0) {\n return { id: \"hermes.registry-parity\", title: \"Fleet registry matches .project.json (no duplicate or stale agents)\", status: \"skip\", summary: \"No Hermes roles or declared agents present\", details: [], fixable: false };\n }\n return { id: \"hermes.registry-parity\", title: \"Fleet registry matches .project.json (no duplicate or stale agents)\", status: \"warn\", summary: `registry unreadable at ${registryPath}`, details: [], fixable: false };\n }\n // role.yaml is the identity SSOT. discoverRoles() only walks this repo's\n // own agents/hermes/*, so nested submodule agents are correctly excluded --\n // a naive role_dir.startsWith(repoRoot) would swallow them and propose\n // deleting perfectly good sibling agents.\n const canonical = new Set(roles.map((role) => role.agentId).filter(Boolean));\n const owned = ownedRegistryEntries(registry, ctx.repoRoot);\n const unprovisioned = unprovisionedRoleAgents(registry, ctx.repoRoot, canonical);\n if (unprovisioned.length) {\n return {\n id: \"hermes.registry-parity\",\n title: \"Fleet registry matches .project.json (no duplicate or stale agents)\",\n status: \"fail\",\n summary: `${unprovisioned.length} unprovisioned Hermes role blocker(s) detected`,\n details: unprovisioned.map(({ agentId, roleDir, sources }) =>\n `agent \"${agentId}\" (${sources.join(\" + \")}) has no role.yaml${roleDir ? ` at ${roleDir}` : \"\"}; provision or restore the role, do not delete its registry/declaration`\n ),\n fixable: false,\n };\n }\n if (canonical.size === 0) {\n return { id: \"hermes.registry-parity\", title: \"Fleet registry matches .project.json (no duplicate or stale agents)\", status: \"skip\", summary: \"No Hermes roles, declarations, or registry entries present\", details: [], fixable: false };\n }\n // With at least one provisioned role, stale sibling identities can be\n // compared safely against role.yaml. The empty-role case returned above\n // as a truthful non-fixable blocker and never enters destructive repair.\n for (const [agentId, entry] of owned) {\n const roleDir = String((entry as Record<string, unknown>)?.role_dir ?? \"\");\n if (!canonical.has(agentId)) {\n details.push(`stale/duplicate registry agent \"${agentId}\" for ${roleDir} (role.yaml declares ${[...canonical].join(\", \")})`);\n }\n }\n for (const extra of declaredAgentIds(ctx.repoRoot).filter((id) => !canonical.has(id))) {\n details.push(`.project.json declares agent \"${extra}\" that no role.yaml claims`);\n }\n for (const role of roles) {\n const expectedBloodbankEnabled = roleBloodbankEnabled(role);\n if (expectedBloodbankEnabled === null) {\n details.push(`${relative(ctx.repoRoot, role.roleYamlPath)} bloodbank.enabled must be the strict YAML boolean true or false`);\n malformedRoleGate = true;\n }\n const entry = registry[role.agentId] as Record<string, unknown> | undefined;\n if (!entry) {\n details.push(`registry is missing an entry for ${role.agentId}`);\n continue;\n }\n const entryRoleDir = String(entry.role_dir ?? \"\");\n if (entryRoleDir && realOrSelf(entryRoleDir) !== realOrSelf(role.roleDir)) {\n details.push(`registry role_dir for ${role.agentId} is ${entryRoleDir} (expected ${role.roleDir})`);\n }\n const bin = String((entry.hermes as Record<string, unknown> | undefined)?.bin ?? \"\");\n if (bin && !existsSync(bin)) {\n details.push(`registry hermes.bin for ${role.agentId} does not exist: ${bin}`);\n }\n // Fleet-bloodbank standard: one shared gateway owns command ingress.\n // Every agent entry advertises fleet routing; none carries the retired\n // per-agent consumer/checkpoint contract in the registry or on disk.\n const bloodbank = (entry.bloodbank ?? {}) as Record<string, unknown>;\n if (typeof bloodbank.enabled !== \"boolean\") {\n details.push(`registry entry for ${role.agentId} bloodbank.enabled must be a strict boolean`);\n } else if (expectedBloodbankEnabled !== null && bloodbank.enabled !== expectedBloodbankEnabled) {\n details.push(`registry entry for ${role.agentId} bloodbank.enabled must match explicit role value ${expectedBloodbankEnabled}`);\n }\n if (bloodbank.gateway_scope !== \"fleet\" || bloodbank.target_agent_id !== role.agentId) {\n details.push(`registry entry for ${role.agentId} must advertise bloodbank { gateway_scope: fleet, target_agent_id: ${role.agentId} }`);\n }\n const systemd = (entry.systemd ?? {}) as Record<string, unknown>;\n for (const key of LEGACY_SYSTEMD_KEYS) {\n if (systemd[key] !== undefined) {\n details.push(`registry entry for ${role.agentId} carries retired systemd.${key}; the fleet-shared Bloodbank gateway owns command ingress`);\n }\n }\n const legacyUnit = legacyConsumerUnitPath(ctx.homeDir, role.agentId);\n if (existsSync(legacyUnit)) {\n details.push(`retired per-agent consumer unit still on disk: ${legacyUnit}`);\n }\n }\n return {\n id: \"hermes.registry-parity\",\n title: \"Fleet registry matches .project.json (no duplicate or stale agents)\",\n status: details.length === 0 ? \"pass\" : \"fail\",\n summary: details.length === 0 ? \"Fleet registry is in parity\" : `${details.length} registry parity issue(s) detected`,\n details,\n fixable: !malformedRoleGate,\n };\n },\n migrate: (ctx, finding) => {\n const changedFiles: string[] = [];\n const details: string[] = [];\n const registryPath = join(ctx.homeDir, \".hermes\", \"agents-registry.yaml\");\n let raw = safeReadText(registryPath);\n if (raw === null) {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: `registry unreadable at ${registryPath}`, changedFiles, details };\n }\n const roles = discoverRoles(ctx.repoRoot);\n const malformedRoleGates = roles.filter((role) => roleBloodbankEnabled(role) === null);\n if (malformedRoleGates.length > 0) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"Registry parity is blocked by malformed role Bloodbank gates\",\n changedFiles,\n details: malformedRoleGates.map((role) =>\n `${relative(ctx.repoRoot, role.roleYamlPath)} bloodbank.enabled must be the strict YAML boolean true or false`\n ),\n };\n }\n const missingRoles = roles.filter((role) => !raw!.includes(`${role.agentId}:`));\n for (const role of missingRoles) {\n const updated = upsertRegistryEntry(role, ctx.homeDir, changedFiles, ctx.dryRun);\n if (updated) details.push(`add missing fleet registry entry for ${role.agentId}`);\n if (!ctx.dryRun) raw = safeReadText(registryPath) ?? raw;\n }\n if (ctx.dryRun && missingRoles.length) {\n return { id: finding.id, title: finding.title, status: \"skipped\", summary: \"Planned missing fleet registry entries\", changedFiles: [...new Set(changedFiles)], details };\n }\n let doc: Record<string, unknown>;\n try {\n doc = YAML.parse(raw) as Record<string, unknown>;\n } catch {\n return { id: finding.id, title: finding.title, status: \"blocked\", summary: \"registry is not valid YAML\", changedFiles, details };\n }\n const agents = (doc?.agents ?? {}) as Record<string, Record<string, unknown>>;\n const canonical = new Set(roles.map((role) => role.agentId).filter(Boolean));\n const unprovisioned = unprovisionedRoleAgents(agents, ctx.repoRoot, canonical);\n if (unprovisioned.length) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"Registry parity is blocked by an unprovisioned Hermes role\",\n changedFiles,\n details: unprovisioned.map(({ agentId, roleDir, sources }) =>\n `blocked: \"${agentId}\" (${sources.join(\" + \")}) has no role.yaml${roleDir ? ` at ${roleDir}` : \"\"}; provision or restore the role without pruning registry/declaration state`\n ),\n };\n }\n const fleetBin = fleetBinPath(ctx);\n let dirty = false;\n\n if (canonical.size === 0) {\n // Unprovisioned repo: report, never delete. Losing these entries costs\n // the Plane binding and unit names that provisioning cannot rebuild.\n for (const [agentId] of ownedRegistryEntries(agents, ctx.repoRoot)) {\n details.push(`blocked: \"${agentId}\" has no role.yaml; provision the role instead of pruning the registry`);\n }\n for (const agentId of declaredAgentIds(ctx.repoRoot)) {\n if (!details.some((detail) => detail.includes(`\"${agentId}\"`))) {\n details.push(`blocked: \"${agentId}\" is declared but has no role.yaml; provision or restore the role`);\n }\n }\n if (details.length) {\n return {\n id: finding.id,\n title: finding.title,\n status: \"blocked\",\n summary: \"Registry parity is blocked by an unprovisioned Hermes role\",\n changedFiles,\n details,\n };\n }\n }\n // A moved checkout is deliberately invisible to ownedRegistryEntries(),\n // because that helper scopes ownership using the registry's role_dir.\n // role.yaml gives us a safer canonical identity: repair the matching\n // agent by id first, then let normal ownership-scoped cleanup proceed.\n for (const role of roles) {\n const entry = agents[role.agentId] as Record<string, unknown> | undefined;\n if (!entry) continue;\n const entryRoleDir = String(entry.role_dir ?? \"\");\n if (entryRoleDir && realOrSelf(entryRoleDir) !== realOrSelf(role.roleDir)) {\n details.push(`repoint ${role.agentId} role_dir -> ${role.roleDir}`);\n entry.role_dir = role.roleDir;\n entry.project_path = ctx.repoRoot;\n dirty = true;\n }\n // Converge on the fleet-bloodbank standard: advertise fleet routing,\n // drop the retired per-agent consumer/checkpoint contract, and remove\n // any leftover consumer unit file from disk.\n const bloodbank = (entry.bloodbank ?? {}) as Record<string, unknown>;\n const expectedBloodbankEnabled = roleBloodbankEnabled(role) ?? false;\n if (bloodbank.enabled !== expectedBloodbankEnabled || bloodbank.gateway_scope !== \"fleet\" || bloodbank.target_agent_id !== role.agentId) {\n details.push(`normalize fleet bloodbank routing for ${role.agentId} with enabled=${expectedBloodbankEnabled}`);\n entry.bloodbank = { ...bloodbank, enabled: expectedBloodbankEnabled, gateway_scope: \"fleet\", target_agent_id: role.agentId };\n dirty = true;\n }\n const systemd = entry.systemd as Record<string, unknown> | undefined;\n if (systemd) {\n for (const key of LEGACY_SYSTEMD_KEYS) {\n if (systemd[key] !== undefined) {\n details.push(`drop retired systemd.${key} from ${role.agentId}`);\n delete systemd[key];\n dirty = true;\n }\n }\n }\n const legacyUnit = legacyConsumerUnitPath(ctx.homeDir, role.agentId);\n if (existsSync(legacyUnit)) {\n if (ctx.dryRun) {\n details.push(`would remove retired consumer unit ${legacyUnit}`);\n } else {\n systemctlUser([\"disable\", \"--now\", basename(legacyUnit)]);\n rmSync(legacyUnit, { force: true });\n systemctlUser([\"daemon-reload\"]);\n systemctlUser([\"reset-failed\"]);\n details.push(`removed retired consumer unit ${legacyUnit}`);\n }\n changedFiles.push(legacyUnit);\n }\n }\n for (const [agentId, entry] of ownedRegistryEntries(agents, ctx.repoRoot)) {\n // Only ids this repo's own role.yaml files claim survive. Scoping is by\n // derived project root, so nested submodule agents are never touched.\n if (canonical.size > 0 && !canonical.has(agentId)) {\n details.push(`drop stale/duplicate registry agent \"${agentId}\"`);\n delete agents[agentId];\n dropDeclaredAgent(ctx, agentId, changedFiles, details);\n dirty = true;\n continue;\n }\n const hermes = (entry.hermes ?? {}) as Record<string, unknown>;\n if (fleetBin && String(hermes.bin ?? \"\") !== fleetBin && !existsSync(String(hermes.bin ?? \"\"))) {\n details.push(`repoint ${agentId} hermes.bin -> ${fleetBin}`);\n hermes.bin = fleetBin;\n entry.hermes = hermes;\n dirty = true;\n }\n // HERMES_OAUTH_FILE is documented but unimplemented; drop the pointer so\n // the registry stops advertising a sharing mechanism that does nothing.\n if (hermes.oauth_file) {\n details.push(`drop dead hermes.oauth_file from ${agentId}`);\n delete hermes.oauth_file;\n dirty = true;\n }\n }\n\n // Once role.yaml establishes the canonical identity, stale declarations\n // can be retired alongside duplicate registry entries.\n if (canonical.size > 0) {\n for (const extra of declaredAgentIds(ctx.repoRoot).filter((id) => !canonical.has(id))) {\n dropDeclaredAgent(ctx, extra, changedFiles, details);\n }\n }\n\n if (dirty) {\n changedFiles.push(registryPath);\n if (!ctx.dryRun) {\n doc.agents = agents;\n writeText(registryPath, YAML.stringify(doc));\n }\n }\n return {\n id: finding.id,\n title: finding.title,\n status: changedFiles.length ? (ctx.dryRun ? \"skipped\" : \"applied\") : \"noop\",\n summary: changedFiles.length ? (ctx.dryRun ? \"Planned registry repair\" : \"Fleet registry repaired\") : \"No changes required\",\n changedFiles,\n details,\n };\n },\n },\n];\n}\n\nfunction createProjectMomoChecks(): RecipeOwnedCheck[] {\nreturn [\n {\n id: \"momo-lifecycle-plane\",\n title: \"Momo lifecycle-plane readiness profile\",\n audit: () => ({\n id: \"momo-lifecycle-plane\",\n title: \"Momo lifecycle-plane readiness profile\",\n status: \"skip\" as const,\n summary: \"Momo readiness is an audit-only profile; use audit --profile momo-lifecycle-plane\",\n details: [],\n fixable: false,\n }),\n migrate: (ctx, finding) => ({\n id: finding.id,\n title: finding.title,\n status: \"skipped\" as const,\n summary: \"report-only profile; migration is intentionally skipped\",\n changedFiles: [],\n details: [\"Momo lifecycle-plane readiness checks are credential-bearing and are performed only by `audit --profile momo-lifecycle-plane`\"],\n }),\n },\n];\n}\n\nexport function createProjectChecks(): RecipeOwnedCheck[] {\n return [\n ...createProjectJsonChecks(),\n ...createProjectProvenanceChecks(),\n ...createProjectMomoChecks(),\n ];\n}\n\nfunction writeIfDifferent(path: string, content: string, dryRun: boolean, changedFiles: string[], mode?: number): void {\n const normalized = content.endsWith(\"\\n\") ? content : `${content}\\n`;\n if (safeReadText(path) === normalized) return;\n changedFiles.push(path);\n if (!dryRun) {\n writeText(path, normalized);\n if (mode) chmodSync(path, mode);\n }\n}\n\nfunction prettyTimestamp(iso: string): string {\n // 2026-07-07T09:59:00.989Z -> 2026-07-07 09:59:00 UTC\n const match = /^(\\d{4}-\\d{2}-\\d{2})T(\\d{2}:\\d{2}:\\d{2})/.exec(iso);\n return match ? `${match[1]} ${match[2]} UTC` : iso;\n}\n\nexport function formatAuditReport(report: AuditReport): string {\n const counts: Record<string, number> = {};\n for (const rule of report.rules) counts[rule.status] = (counts[rule.status] ?? 0) + 1;\n const idWidth = report.rules.reduce((width, rule) => Math.max(width, rule.id.length), 0);\n\n const tally: string[] = [];\n if (counts.pass) tally.push(green(`${counts.pass} passed`));\n if (counts.fail) tally.push(red(`${counts.fail} failed`));\n if (counts.warn) tally.push(yellow(`${counts.warn} warning${counts.warn === 1 ? \"\" : \"s\"}`));\n if (counts.skip) tally.push(gray(`${counts.skip} skipped`));\n\n const overall = report.ok\n ? `${green(glyph.pass)} ${bold(\"Parity audit passed\")}`\n : `${red(glyph.fail)} ${bold(\"Parity audit failed\")}`;\n\n const lines = [\"\"];\n lines.push(` ${overall}${tally.length ? ` ${dim(glyph.dot)} ${joinDot(tally)}` : \"\"}`);\n lines.push(` ${dim(report.repo)} ${dim(glyph.dot)} ${dim(prettyTimestamp(report.auditedAt))}`);\n // PJAN-84: a host finding no longer fails the repo, so it has to be visible on\n // its own line \u2014 otherwise \"Parity audit passed\" would be the only thing an\n // operator reads while their machine's shared state is broken.\n const hostTrouble = report.rules.filter((rule) => rule.scope === \"host\" && (rule.status === \"fail\" || rule.status === \"warn\"));\n if (hostTrouble.length) {\n lines.push(\"\");\n lines.push(` ${yellow(glyph.warn)} ${bold(\"This machine needs attention\")} ${dim(glyph.dot)} ${dim(\"not this project \u2014 these cannot be fixed from here\")}`);\n for (const rule of hostTrouble) lines.push(` ${dim(glyph.arrow)} ${rule.id}: ${rule.summary}`);\n }\n lines.push(\"\");\n for (const rule of report.rules) {\n const style = statusStyle(rule.status);\n lines.push(` ${style.color(style.glyph)} ${style.color(rule.id.padEnd(idWidth))} ${rule.summary}`);\n for (const detail of rule.details) lines.push(` ${dim(glyph.arrow)} ${dim(detail)}`);\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\nexport function formatMigrationReport(report: MigrationReport): string {\n const idWidth = report.results.reduce((width, result) => Math.max(width, result.id.length), 0);\n const blocked = report.results.filter((result) => result.status === \"blocked\").length;\n const partial = report.results.filter((result) => result.status === \"partial\").length;\n\n // PJAN-75: \"Migration complete\" is now a claim the run has verified, so the\n // not-ok case has to say WHICH kind of unfinished it is. A blocker means the\n // rule refused to act; a partial means it acted and still did not reach\n // parity, which is the state that used to be reported as success.\n const overall = report.ok\n ? `${green(glyph.pass)} ${bold(report.dryRun ? \"Migration preview complete\" : \"Migration complete\")}`\n : blocked\n ? `${red(glyph.fail)} ${bold(\"Migration finished with blockers\")}`\n : `${yellow(glyph.warn)} ${bold(`Migration incomplete ${glyph.dot} ${partial} rule${partial === 1 ? \"\" : \"s\"} still failing`)}`;\n\n const lines = [\"\"];\n lines.push(` ${overall}${report.dryRun ? ` ${dim(glyph.dot)} ${yellow(\"dry run\")}` : \"\"}`);\n lines.push(` ${dim(report.repo)}`);\n if (report.selectedRules.length) lines.push(` ${dim(`rules: ${report.selectedRules.join(\", \")}`)}`);\n lines.push(\"\");\n for (const result of report.results) {\n const style = statusStyle(result.status);\n lines.push(` ${style.color(style.glyph)} ${style.color(result.id.padEnd(idWidth))} ${result.summary} ${dim(`[${style.label}]`)}`);\n for (const detail of result.details) lines.push(` ${dim(glyph.arrow)} ${dim(detail)}`);\n for (const file of result.changedFiles) lines.push(` ${green(glyph.add)} ${file}`);\n }\n if (report.changedFiles.length) {\n lines.push(\"\");\n lines.push(` ${bold(`Changed files (${report.changedFiles.length})`)}`);\n for (const file of report.changedFiles) lines.push(` ${green(glyph.add)} ${file}`);\n }\n const unresolved = partial + blocked;\n if (unresolved) {\n lines.push(\"\");\n lines.push(` ${dim(`Run \\`pjangler audit\\` for the full detail on the ${unresolved} rule${unresolved === 1 ? \"\" : \"s\"} still failing.`)}`);\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Interactive rule picker presentation\n//\n// Presentation only: this never decides *which* rules are offered or in what\n// order \u2014 the caller owns that. It just turns an already-selected list of\n// findings into the label/hint pairs @clack's multiselect renders.\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** One row of the interactive rule picker, in @clack `Option` shape. */\nexport interface RulePickerChoice {\n value: string;\n label: string;\n hint?: string;\n}\n\nexport interface RulePicker {\n message: string;\n options: RulePickerChoice[];\n}\n\n/**\n * Widest hint the picker will emit before eliding, and the widest title column\n * it will pad to. Both are caps, not targets: rule titles run from ~20 to ~70\n * characters, and padding every row out to the longest one turns a short list\n * into a field of whitespace and pushes rows past any sane terminal width.\n * Titles longer than the cap are never truncated \u2014 that row just goes ragged.\n */\nconst RULE_HINT_WIDTH = 72;\nconst RULE_TITLE_COLUMN = 44;\n\n/**\n * Row-width budget. @clack never wraps, so an over-long row is the terminal's\n * problem \u2014 we keep rows near a comfortable width instead. Fixed rather than\n * read from `process.stdout.columns`: the picker only ever runs on a TTY, but a\n * deterministic layout is worth more than a responsive one here (it keeps the\n * rendering reproducible in tests and identical across operators' terminals).\n */\nconst RULE_ROW_TARGET = 116;\nconst RULE_HINT_MIN = 28;\n/** @clack's own gutter + checkbox prefix (\"\u2502 \u25FC \"), plus our \" (...)\" wrapper. */\nconst RULE_ROW_CHROME = 7;\n\nfunction elide(value: string, width: number): string {\n const flat = value.replace(/\\s+/g, \" \").trim();\n return flat.length <= width ? flat : `${flat.slice(0, Math.max(1, width - 1)).trimEnd()}\u2026`;\n}\n\n/**\n * Fold a finding's summary + details into ONE bounded line. @clack renders a\n * hint only for the focused row and for already-selected rows, so this is the\n * progressive-disclosure layer: enough context to decide, never enough to bury\n * the list. `pjangler audit` stays the full-detail surface, which is why the\n * header points at it.\n *\n * Detail policy: a lone detail IS the whole story, so it is shown inline; two\n * or more collapse to a count. Every failing rule is pre-selected, so inlining\n * detail text unconditionally would put a paragraph on nearly every row \u2014 the\n * exact wall of text this ticket removes.\n *\n * Deliberately un-colored: @clack wraps hints in its own dim(), and nesting our\n * SGR codes inside that renders inconsistently across terminals.\n */\nfunction ruleHint(rule: AuditFinding, budget: number): string | undefined {\n const summary = rule.summary.replace(/\\s+/g, \" \").trim();\n const fragments: string[] = [];\n if (summary) fragments.push(summary);\n if (rule.details.length === 1) {\n fragments.push(`${glyph.arrow} ${rule.details[0]}`);\n } else if (rule.details.length > 1) {\n fragments.push(`${glyph.arrow} ${rule.details.length} details`);\n }\n const hint = elide(fragments.join(` ${glyph.dot} `), budget);\n return hint || undefined;\n}\n\n/**\n * Compose the interactive rule picker.\n *\n * Row anatomy \u2014 the human sentence leads so the list is scannable, the rule id\n * stays visible (dim, in a column) because the operator still needs it for\n * `pjangler migrate <rule-id>`, and status drives both icon and color so a\n * failing rule is obvious. The icon carries the distinction on its own, so a\n * NO_COLOR / non-TTY terminal (where `src/utils/style` degrades every color\n * helper to identity) loses no information:\n *\n * \u2716 Canonical .project.json sot.project-json (1 parity issue \u2026)\n * \u2714 managed mise versioning block mise.versioning\n */\nexport function formatRulePicker(rules: AuditFinding[]): RulePicker {\n const titleColumn = Math.min(\n RULE_TITLE_COLUMN,\n rules.reduce((width, rule) => Math.max(width, rule.title.length), 0),\n );\n\n const options = rules.map((rule) => {\n const style = statusStyle(rule.status);\n // Pad OUTSIDE the color run, so a row never carries styled trailing space.\n const pad = \" \".repeat(Math.max(0, titleColumn - rule.title.length));\n const headline =\n rule.status === \"fail\"\n ? bold(style.color(rule.title))\n : rule.status === \"warn\"\n ? style.color(rule.title)\n : rule.status === \"skip\"\n ? dim(rule.title)\n : rule.title;\n\n // Give the hint whatever row budget the label did not spend, so a long\n // title costs detail rather than overflowing the terminal.\n const labelWidth = 2 + rule.title.length + pad.length + 2 + rule.id.length;\n const budget = Math.min(RULE_HINT_WIDTH, Math.max(RULE_HINT_MIN, RULE_ROW_TARGET - RULE_ROW_CHROME - labelWidth));\n\n return {\n value: rule.id,\n label: `${style.color(style.glyph)} ${headline}${pad} ${dim(rule.id)}`,\n hint: ruleHint(rule, budget),\n };\n });\n\n return { message: formatRulePickerMessage(rules), options };\n}\n\n/**\n * Header line: a status tally so the operator knows what they're looking at\n * before scanning, plus a pointer to the full-detail surface. @clack already\n * prints its own \"press space to select, enter to submit\" instructions, so we\n * do not repeat them. Single line by construction \u2014 a newline here would break\n * @clack's frame.\n */\nfunction formatRulePickerMessage(rules: AuditFinding[]): string {\n const counts: Record<string, number> = {};\n for (const rule of rules) counts[rule.status] = (counts[rule.status] ?? 0) + 1;\n\n const fragments: string[] = [];\n if (counts.fail) fragments.push(red(`${counts.fail} failing`));\n if (counts.warn) fragments.push(yellow(`${counts.warn} warning${counts.warn === 1 ? \"\" : \"s\"}`));\n if (counts.pass) fragments.push(green(`${counts.pass} passing`));\n if (counts.skip) fragments.push(gray(`${counts.skip} skipped`));\n fragments.push(dim(\"`pjangler audit` for full detail\"));\n\n return `Select parity rules to apply ${joinDot(fragments)}`;\n}\n", "export interface SupportedCli {\n id: \"claude\" | \"codex\" | \"gemini\" | \"copilot\" | \"opencode\" | \"kimi\";\n name: \"Claude\" | \"Codex\" | \"Gemini\" | \"Copilot\" | \"OpenCode\" | \"Kimi\";\n bmadTool: \"claude-code\" | \"codex\" | \"gemini\" | \"github-copilot\" | \"opencode\" | \"kimi-code\";\n projectRoot: \".claude\" | \".codex\" | \".gemini\" | \".copilot\" | \".opencode\" | \".kimi-code\";\n skillsRoot: string;\n}\n\n/** The complete, ordered CLI projection policy. No other CLI is generated. */\nexport const SUPPORTED_CLIS: readonly SupportedCli[] = Object.freeze([\n { id: \"claude\", name: \"Claude\", bmadTool: \"claude-code\", projectRoot: \".claude\", skillsRoot: \".claude/skills\" },\n { id: \"codex\", name: \"Codex\", bmadTool: \"codex\", projectRoot: \".codex\", skillsRoot: \".codex/skills\" },\n { id: \"gemini\", name: \"Gemini\", bmadTool: \"gemini\", projectRoot: \".gemini\", skillsRoot: \".gemini/skills\" },\n { id: \"copilot\", name: \"Copilot\", bmadTool: \"github-copilot\", projectRoot: \".copilot\", skillsRoot: \".copilot/skills\" },\n { id: \"opencode\", name: \"OpenCode\", bmadTool: \"opencode\", projectRoot: \".opencode\", skillsRoot: \".opencode/skills\" },\n { id: \"kimi\", name: \"Kimi\", bmadTool: \"kimi-code\", projectRoot: \".kimi-code\", skillsRoot: \".kimi-code/skills\" },\n]);\n\nexport const SUPPORTED_BMAD_TOOLS = SUPPORTED_CLIS.map((cli) => cli.bmadTool);\nexport const SUPPORTED_CLI_ROOTS = SUPPORTED_CLIS.map((cli) => cli.projectRoot);\n", "import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readdirSync } from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { basename, join, relative, resolve, sep } from \"node:path\";\n\n/**\n * Generic Skillex pack validator (PACKS-CONTRACT sections 3, 3b and 4).\n *\n * This module used to hard-code one trusted BMAD release. It is now pack-agnostic:\n * every layout that exists in the registry has to work \u2014\n *\n * packs/<name>/pack.toml flat, unversioned, may declare ZERO skills\n * packs/<name>/<skill dirs> flat, no pack.toml at all\n * packs/<name>/<version>/pack.toml versioned\n * packs/<name>/<version>/ + stray root files stray non-payload files are IGNORED\n * packs/<name>/<container>/.../<skill dirs> NESTED, projected FLAT (3b)\n *\n * The nested layout is opt-in (`[policy] flatten` or a manifest `flatten`) and\n * exists because upstream Hermes models the container level as a real, named\n * grouping with its own DESCRIPTION.md, resolved by the depth-agnostic\n * `agent/skill_utils.py::iter_skill_index_files` (see `agent/prompt_builder.py`\n * lines 1670 and 1718). Upstream nests three deep in places, so the expansion\n * here is a DESCENT, not a fixed one-level step. The pack mirrors upstream\n * verbatim; the mismatch with the five container-less CLIs is resolved here, at\n * PROJECTION time, never by rewriting the pack on disk.\n *\n * Everything the hardened BMAD validator did is preserved, just generalized:\n * * every read goes through O_NOFOLLOW, so a symlink can never be read as a file\n * * the pack root and every declared skill directory must be a REAL directory\n * * a pack payload may contain only regular files and real directories\n * * `SHA256SUMS` paths must be safe relative paths, no duplicates\n * * a sealed pack may not contain unauthenticated (empty) payload directories\n * * skill names are exactly one safe path component\n *\n * The one deliberate relaxation, required by contract section 4 rule 3: a\n * `SHA256SUMS` that covers files which are NOT payload (`README.md` is the live\n * example, in `packs/bmad/6.10.1-next.31`) is LEGAL. Those files are still\n * verified \u2014 they simply may not be absent. Files that are neither payload nor\n * listed (`.claude/`, `_bmad/`, `mise.toml`, a stray guard script) are ignored.\n */\n\n/** The pack, or a declared member of it, is simply not installed here. */\nexport class PackUnavailableError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PackUnavailableError\";\n }\n}\n\n/** A normalized `packs[]` manifest entry (contract section 1). */\nexport interface PackManifestEntry {\n name: string;\n version?: string;\n source?: string;\n registry?: string;\n registryPath?: string;\n include?: string[];\n exclude?: string[];\n optional: boolean;\n /** Manifest-level seal. May only TIGHTEN what `[policy] sealed` declares. */\n sealed: boolean;\n /**\n * Manifest-level `flatten` (contract section 3b). ORs with `[policy] flatten`;\n * layout is a property of the pack, so `pack.toml` is the natural home and this\n * exists for packs that ship no `pack.toml` at all.\n */\n flatten: boolean;\n}\n\n/**\n * One projected skill of a pack (contract section 3b).\n *\n * `path` is what makes flattening work end to end: a member is no longer\n * necessarily `<root>/<name>`, so every consumer that needs a filesystem target\n * must take it from here rather than re-deriving it from the name.\n */\nexport interface PackMember {\n /** Projected skill name \u2014 the LEAF directory's basename. */\n name: string;\n /** `/`-separated path relative to the pack root. Equals `name` when flat. */\n path: string;\n /** The DECLARED inventory entry this member came from (`name` when flat). */\n declaredEntry: string;\n}\n\nexport interface ValidatedPack {\n name: string;\n version?: string;\n root: string;\n /**\n * Raw DECLARED inventory, BEFORE include/exclude and BEFORE section 3b\n * expansion. This \u2014 not the flattened inventory \u2014 is the sealed payload basis\n * (contract section 4), because declaring a container already covers its\n * leaves recursively.\n */\n declared: string[];\n /** Section 3b inventory (expanded when flattened), BEFORE include/exclude. */\n inventory: PackMember[];\n /** `inventory` names \u2014 what a hand-expanded `skills[]` entry would be called. */\n inventoryNames: string[];\n /** Inventory after include then exclude. */\n members: string[];\n /** Member name -> ABSOLUTE leaf directory. The only source of member paths. */\n memberPaths: Map<string, string>;\n /** Section 3b expansion was enabled for this pack. */\n flatten: boolean;\n /** Non-fatal advisories (a container that projects nothing, a skipped symlink). */\n warnings: string[];\n sealed: boolean;\n /** Payload files excluding `pack.toml` itself. */\n payloadFiles: number;\n}\n\nexport interface PackMetadata {\n name?: string;\n version?: string;\n /** `[freeform].skills`; absent section means an empty inventory, never \"glob\". */\n skills: string[];\n /** `[policy] sealed = true`. `immutable = true` alone does NOT imply sealed. */\n sealed: boolean;\n /** `[policy] flatten = true` (contract section 3b). */\n flatten: boolean;\n /** `[source].payload_files`, when declared as an integer. */\n payloadFiles?: number;\n}\n\n/**\n * The canonical identifier shape the contract mandates for pack and skill names\n * (section 1): lowercase alphanumerics and dashes, no leading or trailing dash.\n */\nexport const CANONICAL_NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;\n\n/**\n * Canonical pack identifier shape. Enforced as advisory only so packs that\n * predate the convention stay resolvable; the hard requirement \u2014 exactly one\n * safe path component \u2014 is enforced by `validatePathComponent`.\n */\nexport const PACK_NAME_PATTERN = CANONICAL_NAME_PATTERN;\n\n// ---------------------------------------------------------------------------\n// Filesystem primitives (all symlink-hostile)\n// ---------------------------------------------------------------------------\n\nfunction sha256(content: Buffer): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\n/** Read a regular file, refusing to follow a symlink at the final component. */\nexport function readRegularFile(path: string): Buffer {\n const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);\n try {\n if (!fstatSync(fd).isFile()) throw new Error(`Pack entry is not a regular file: ${path}`);\n return readFileSync(fd);\n } finally {\n closeSync(fd);\n }\n}\n\nexport function hashRegularFile(path: string): string {\n return sha256(readRegularFile(path));\n}\n\nexport function isRegularFile(path: string): boolean {\n try {\n const stat = lstatSync(path);\n return stat.isFile() && !stat.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\n/** A real directory: present, not a symlink, actually a directory. */\nexport function assertRealDirectory(path: string, label: string): string {\n let stat: ReturnType<typeof lstatSync>;\n try {\n stat = lstatSync(path);\n } catch {\n throw new PackUnavailableError(`${label} is not present: ${path}`);\n }\n if (stat.isSymbolicLink() || !stat.isDirectory()) {\n throw new Error(`${label} must be a real directory: ${path}`);\n }\n return path;\n}\n\n/** No component of `relativePath` under `root` may be a symlink. */\nexport function assertNoSymlinkComponents(root: string, relativePath: string): string {\n let current = root;\n for (const part of relativePath.split(\"/\")) {\n if (!part) continue;\n current = join(current, part);\n let stat: ReturnType<typeof lstatSync>;\n try {\n stat = lstatSync(current);\n } catch {\n throw new PackUnavailableError(`Pack path is not present: ${current}`);\n }\n if (stat.isSymbolicLink()) throw new Error(`Refusing symlinked pack path component: ${current}`);\n }\n return current;\n}\n\n// ---------------------------------------------------------------------------\n// Name / path validation\n// ---------------------------------------------------------------------------\n\n/** Exactly one safe path component. */\nexport function validatePathComponent(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !value) throw new Error(`${label} must be a non-empty string`);\n if (value === \".\" || value === \"..\" || value.includes(\"/\") || value.includes(\"\\\\\") || basename(value) !== value) {\n throw new Error(`${label} must be one path component: ${JSON.stringify(value)}`);\n }\n return value;\n}\n\n/** A safe, `/`-separated, strictly relative path with no `.`/`..`/empty segments. */\nexport function safeRelativePath(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !value) throw new Error(`${label} must be a non-empty string`);\n if (value.includes(\"\\\\\") || value.startsWith(\"/\")) throw new Error(`Unsafe ${label}: ${JSON.stringify(value)}`);\n const parts = value.split(\"/\");\n if (parts.some((part) => part === \"\" || part === \".\" || part === \"..\")) {\n throw new Error(`Unsafe ${label}: ${JSON.stringify(value)}`);\n }\n return parts.join(\"/\");\n}\n\n// ---------------------------------------------------------------------------\n// Manifest entry normalization (contract section 1)\n// ---------------------------------------------------------------------------\n\nfunction optionalStringArray(value: unknown, label: string): string[] | undefined {\n if (value === undefined || value === null) return undefined;\n if (!Array.isArray(value)) throw new Error(`${label} must be an array of skill names`);\n return value.map((item) => validatePathComponent(item, `${label} entry`));\n}\n\nfunction optionalBoolean(value: unknown, label: string): boolean {\n if (value === undefined || value === null) return false;\n if (typeof value !== \"boolean\") throw new Error(`${label} must be a boolean`);\n return value;\n}\n\n/** String shorthand (`\"hermes-base\"`, `\"hermes-base@0.18.2\"`) or object form -> validated object. */\nexport function normalizePackEntry(raw: unknown): PackManifestEntry {\n let source: Record<string, unknown>;\n if (typeof raw === \"string\") {\n const trimmed = raw.trim();\n const at = trimmed.indexOf(\"@\");\n source = at >= 0 ? { name: trimmed.slice(0, at), version: trimmed.slice(at + 1) } : { name: trimmed };\n } else if (raw && typeof raw === \"object\" && !Array.isArray(raw)) {\n source = raw as Record<string, unknown>;\n } else {\n throw new Error(`Pack entry must be a string or object: ${JSON.stringify(raw)}`);\n }\n\n const name = validatePathComponent(source.name, \"Pack name\");\n const entry: PackManifestEntry = {\n name,\n optional: optionalBoolean(source.optional, `Pack ${name} optional`),\n sealed: optionalBoolean(source.sealed, `Pack ${name} sealed`),\n flatten: optionalBoolean(source.flatten, `Pack ${name} flatten`),\n };\n if (source.version !== undefined && source.version !== null) {\n entry.version = validatePathComponent(source.version, `Pack ${name} version`);\n }\n if (source.source !== undefined && source.source !== null) {\n if (typeof source.source !== \"string\") throw new Error(`Pack ${name} source must be a string`);\n entry.source = source.source;\n }\n if (source.registry !== undefined && source.registry !== null) {\n if (typeof source.registry !== \"string\") throw new Error(`Pack ${name} registry must be a string`);\n entry.registry = source.registry;\n }\n if (source.registry_path !== undefined && source.registry_path !== null) {\n entry.registryPath = safeRelativePath(source.registry_path, `pack ${name} registry_path`);\n }\n if (entry.source && entry.registryPath) {\n throw new Error(`Pack ${name} may not set both \\`source\\` and \\`registry_path\\``);\n }\n entry.include = optionalStringArray(source.include, `Pack ${name} include`);\n entry.exclude = optionalStringArray(source.exclude, `Pack ${name} exclude`);\n return entry;\n}\n\n// ---------------------------------------------------------------------------\n// Version ordering (contract section 2 step 2)\n// ---------------------------------------------------------------------------\n\ntype VersionSegment = [number, number, string];\n\nfunction versionSegments(text: string): VersionSegment[] {\n return text\n .split(/[._]/)\n .filter(Boolean)\n .map((chunk): VersionSegment => (/^\\d+$/.test(chunk) ? [0, Number.parseInt(chunk, 10), \"\"] : [1, 0, chunk]));\n}\n\nfunction compareSegments(a: VersionSegment[], b: VersionSegment[]): number {\n const length = Math.max(a.length, b.length);\n for (let index = 0; index < length; index += 1) {\n const left = a[index];\n const right = b[index];\n if (!left) return -1;\n if (!right) return 1;\n if (left[0] !== right[0]) return left[0] - right[0];\n if (left[1] !== right[1]) return left[1] - right[1];\n if (left[2] !== right[2]) return left[2] < right[2] ? -1 : 1;\n }\n return 0;\n}\n\n/** PEP440/semver-ish ordering: numeric-segment aware, prereleases sort BELOW the release. */\nexport function compareVersions(a: string, b: string): number {\n const splitAt = (value: string): [string, string, boolean] => {\n const index = value.indexOf(\"-\");\n return index < 0 ? [value, \"\", false] : [value.slice(0, index), value.slice(index + 1), true];\n };\n const [aRelease, aPre, aHasPre] = splitAt(a);\n const [bRelease, bPre, bHasPre] = splitAt(b);\n const release = compareSegments(versionSegments(aRelease), versionSegments(bRelease));\n if (release !== 0) return release;\n const aRank = aHasPre ? 0 : 1;\n const bRank = bHasPre ? 0 : 1;\n if (aRank !== bRank) return aRank - bRank;\n return compareSegments(versionSegments(aPre), versionSegments(bPre));\n}\n\n/**\n * Highest version subdirectory of `packs/<name>/`, or `null` when this is not a\n * pure \"only subdirectories\" version layout (i.e. it is a flat pack).\n *\n * \"Only subdirectories\" is necessary but NOT sufficient. A `pack.toml`-less\n * `packs/<name>/` whose children are REAL directories that each hold a regular\n * `SKILL.md` satisfies that test and is emphatically not a version layout \u2014 it is\n * a flat pack, and section 3's glob inventory applies instead. The discriminator\n * is what those children ARE: a child holding a regular `SKILL.md` is a skill, so\n * its parent cannot be a version root. Contrast `packs/bmad/`, also `pack.toml`-less\n * and also all real directories, but whose children (e.g. `6.10.1-next.31/`) hold\n * no top-level `SKILL.md` \u2014 that IS a version layout.\n *\n * Do not cite a retired BMAD version in this docblock: `bmad-version-surface`\n * regressions scan source for it and will fail the suite.\n *\n * `packs/Kurzgesagt/` is NOT an example of this: its twelve children are all\n * symlinks, so it is disqualified one check earlier by the `isSymbolicLink()` test\n * below and never reaches the `SKILL.md` test. (Earlier revisions of this comment\n * cited it as \"twelve skill directories\"; that was wrong.)\n */\nexport function selectPackVersion(packDir: string): string | null {\n const versions: string[] = [];\n for (const name of readdirSync(packDir).sort()) {\n if (name.startsWith(\".\")) continue;\n const stat = lstatSync(join(packDir, name));\n // A symlink or a stray file means this is not a version-directory layout.\n if (stat.isSymbolicLink() || !stat.isDirectory()) return null;\n if (isRegularFile(join(packDir, name, \"SKILL.md\"))) return null;\n versions.push(name);\n }\n if (!versions.length) return null;\n return versions.reduce((best, candidate) => (compareVersions(candidate, best) > 0 ? candidate : best));\n}\n\n// ---------------------------------------------------------------------------\n// Minimal TOML reader\n//\n// pack.toml is machine-rendered and only a handful of keys are load-bearing, so\n// this reads exactly the subset those files use: table headers, quoted/literal\n// strings, integers, booleans, and (possibly multi-line) arrays of strings.\n// Anything it cannot interpret is retained as an unsupported sentinel rather\n// than guessed at. Load-bearing keys such as `[freeform].skills` can therefore\n// fail closed instead of silently becoming an empty inventory.\n// ---------------------------------------------------------------------------\n\ntype TomlValue = string | number | boolean | string[] | null;\n\nfunction stripTomlComment(line: string): string {\n let out = \"\";\n let quote: string | null = null;\n for (let index = 0; index < line.length; index += 1) {\n const ch = line[index]!;\n if (quote) {\n if (ch === \"\\\\\" && quote === '\"') {\n out += ch + (line[index + 1] ?? \"\");\n index += 1;\n continue;\n }\n if (ch === quote) quote = null;\n out += ch;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n quote = ch;\n out += ch;\n continue;\n }\n if (ch === \"#\") break;\n out += ch;\n }\n return out;\n}\n\nfunction bracketDepth(text: string): number {\n let depth = 0;\n let quote: string | null = null;\n for (let index = 0; index < text.length; index += 1) {\n const ch = text[index]!;\n if (quote) {\n if (ch === \"\\\\\" && quote === '\"') index += 1;\n else if (ch === quote) quote = null;\n continue;\n }\n if (ch === '\"' || ch === \"'\") quote = ch;\n else if (ch === \"[\") depth += 1;\n else if (ch === \"]\") depth -= 1;\n }\n return depth;\n}\n\nfunction unescapeBasicString(value: string): string {\n return value.replace(/\\\\(u[0-9a-fA-F]{4}|.)/g, (match, escape: string) => {\n if (escape.startsWith(\"u\")) return String.fromCharCode(Number.parseInt(escape.slice(1), 16));\n switch (escape) {\n case \"n\": return \"\\n\";\n case \"t\": return \"\\t\";\n case \"r\": return \"\\r\";\n case \"\\\\\": return \"\\\\\";\n case '\"': return '\"';\n default: return escape;\n }\n });\n}\n\nfunction parseTomlStringArray(body: string, label: string): string[] {\n const items: string[] = [];\n const pattern = /\"((?:[^\"\\\\]|\\\\.)*)\"|'([^']*)'/g;\n let remainder = \"\";\n let cursor = 0;\n let match: RegExpExecArray | null;\n while ((match = pattern.exec(body))) {\n remainder += body.slice(cursor, match.index);\n cursor = match.index + match[0].length;\n items.push(match[1] !== undefined ? unescapeBasicString(match[1]) : match[2]!);\n }\n remainder += body.slice(cursor);\n if (/[^\\s[\\],]/.test(remainder)) {\n throw new Error(`${label} must be an array of strings`);\n }\n return items;\n}\n\nfunction parseTomlScalar(raw: string): TomlValue | undefined {\n const value = raw.trim();\n if (!value) return undefined;\n if (value.startsWith('\"')) {\n const match = value.match(/^\"((?:[^\"\\\\]|\\\\.)*)\"/);\n return match ? unescapeBasicString(match[1]!) : undefined;\n }\n if (value.startsWith(\"'\")) {\n const match = value.match(/^'([^']*)'/);\n return match ? match[1]! : undefined;\n }\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n if (/^[+-]?[0-9][0-9_]*$/.test(value)) return Number.parseInt(value.replace(/_/g, \"\"), 10);\n return undefined;\n}\n\n/** Parse the supported TOML subset into `table name -> key -> value`. */\nexport function parseTomlTables(content: string): Map<string, Map<string, TomlValue>> {\n const tables = new Map<string, Map<string, TomlValue>>();\n const tableFor = (name: string): Map<string, TomlValue> => {\n let table = tables.get(name);\n if (!table) {\n table = new Map<string, TomlValue>();\n tables.set(name, table);\n }\n return table;\n };\n let current = tableFor(\"\");\n\n const lines = content.split(\"\\n\");\n for (let index = 0; index < lines.length; index += 1) {\n const line = stripTomlComment(lines[index]!).trim();\n if (!line) continue;\n\n const header = line.match(/^\\[\\[?\\s*([^[\\]]+?)\\s*\\]\\]?$/);\n if (header) {\n current = tableFor(header[1]!);\n continue;\n }\n\n const assignment = line.match(/^(\"(?:[^\"\\\\]|\\\\.)*\"|'[^']*'|[A-Za-z0-9_.-]+)\\s*=\\s*(.*)$/);\n if (!assignment) continue;\n let key = assignment[1]!;\n if (key.startsWith('\"')) key = unescapeBasicString(key.slice(1, -1));\n else if (key.startsWith(\"'\")) key = key.slice(1, -1);\n const raw = assignment[2]!;\n\n // Multi-line basic/literal strings: skip to the closing delimiter so the\n // lines inside can never be mistaken for further key assignments.\n const multiline = raw.match(/^(\"\"\"|''')/);\n if (multiline) {\n const delimiter = multiline[1]!;\n if (raw.slice(3).includes(delimiter)) continue;\n for (index += 1; index < lines.length; index += 1) {\n if (lines[index]!.includes(delimiter)) break;\n }\n continue;\n }\n\n if (raw.startsWith(\"[\")) {\n let body = raw;\n let depth = bracketDepth(raw);\n let cursor = index;\n while (depth > 0 && cursor + 1 < lines.length) {\n cursor += 1;\n const chunk = stripTomlComment(lines[cursor]!);\n body += `\\n${chunk}`;\n depth += bracketDepth(chunk);\n }\n if (depth > 0) throw new Error(`Unterminated TOML array for key ${JSON.stringify(key)}`);\n index = cursor;\n current.set(key, parseTomlStringArray(body, `${JSON.stringify(key)}`));\n continue;\n }\n\n const scalar = parseTomlScalar(raw);\n current.set(key, scalar ?? null);\n }\n return tables;\n}\n\n// ---------------------------------------------------------------------------\n// pack.toml\n// ---------------------------------------------------------------------------\n\n/** `null` when the pack has no `pack.toml` at all (a legal, unsealed layout). */\nexport function readPackMetadata(root: string): PackMetadata | null {\n const path = join(root, \"pack.toml\");\n const stat = (() => {\n try {\n return lstatSync(path);\n } catch {\n return undefined;\n }\n })();\n if (!stat) return null;\n if (stat.isSymbolicLink() || !stat.isFile()) throw new Error(`Pack metadata is not a regular file: ${path}`);\n\n let tables: Map<string, Map<string, TomlValue>>;\n try {\n tables = parseTomlTables(readRegularFile(path).toString(\"utf8\"));\n } catch (error) {\n throw new Error(`Pack metadata at ${path} does not parse: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n const pack = tables.get(\"pack\");\n const freeform = tables.get(\"freeform\");\n const policy = tables.get(\"policy\");\n const sourceTable = tables.get(\"source\");\n\n const declared = freeform?.get(\"skills\");\n if (declared !== undefined && !Array.isArray(declared)) {\n throw new Error(`Pack metadata at ${path} [freeform].skills must be an array of strings`);\n }\n const payloadFiles = sourceTable?.get(\"payload_files\");\n const name = pack?.get(\"name\");\n const version = pack?.get(\"version\");\n\n return {\n name: typeof name === \"string\" ? name : undefined,\n version: typeof version === \"string\" ? version : undefined,\n skills: Array.isArray(declared) ? [...declared] : [],\n // `immutable = true` alone deliberately does NOT imply sealed.\n sealed: policy?.get(\"sealed\") === true,\n flatten: policy?.get(\"flatten\") === true,\n payloadFiles: typeof payloadFiles === \"number\" ? payloadFiles : undefined,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Inventory (contract sections 3 and 3b)\n// ---------------------------------------------------------------------------\n\n/** `flatten` is enabled by the pack's `[policy]` OR by the manifest entry. */\nexport function packFlattenEnabled(\n metadata: PackMetadata | null,\n entry: Pick<PackManifestEntry, \"flatten\">\n): boolean {\n return entry.flatten === true || metadata?.flatten === true;\n}\n\n/**\n * Every skill reachable under a CONTAINER, at ANY depth (contract section 3b).\n *\n * The descent rule is the whole of the expansion: descend while a node is a\n * container; a node holding a regular `SKILL.md` IS a skill and is never\n * descended into. That mirrors upstream `agent/skill_utils.py`'s\n * `iter_skill_index_files`, which is a depth-agnostic `os.walk`, and it is why\n * `hermes-base`'s `mlops/evaluation/lm-evaluation-harness` IS a member:\n * `mlops/evaluation` carries only a `DESCRIPTION.md`, so it is another container\n * and the walk continues through it.\n *\n * Stopping at the first `SKILL.md` on each branch is also what keeps a skill's\n * own `references/`/`scripts/`/`assets/`/`templates/` subtree from contributing a\n * second member \u2014 the same reason upstream prunes `SKILL_SUPPORT_DIRS` only under\n * a directory that already has a `SKILL.md`.\n *\n * Skip rules match section 3's glob exactly, at every level: `.`/`_` prefixes are\n * ignored, non-directories are ignored, and a symlink is skipped (never followed)\n * and reported. Since symlinks are never followed the descent cannot cycle.\n *\n * `symlinked` entries are reported as `/`-separated paths relative to the\n * container, so a skipped grandchild is still identifiable.\n */\nfunction packContainerLeaves(containerDir: string): {\n /** `/`-separated leaf paths relative to `containerDir`, sorted by walk order. */\n leaves: string[];\n symlinked: string[];\n} {\n const leaves: string[] = [];\n const symlinked: string[] = [];\n const visit = (directory: string, prefix: string): void => {\n let children: string[];\n try {\n children = readdirSync(directory).sort();\n } catch {\n return;\n }\n for (const child of children) {\n if (child.startsWith(\".\") || child.startsWith(\"_\")) continue;\n const childPath = join(directory, child);\n const relativePath = prefix ? `${prefix}/${child}` : child;\n let stat: ReturnType<typeof lstatSync>;\n try {\n stat = lstatSync(childPath);\n } catch {\n continue;\n }\n if (stat.isSymbolicLink()) {\n symlinked.push(relativePath);\n continue;\n }\n if (!stat.isDirectory()) continue;\n // A symlinked SKILL.md is not a regular file, so the leaf is skipped too.\n if (isRegularFile(join(childPath, \"SKILL.md\"))) {\n leaves.push(relativePath);\n continue;\n }\n // Still a container: keep descending.\n visit(childPath, relativePath);\n }\n };\n visit(containerDir, \"\");\n return { leaves, symlinked };\n}\n\n/**\n * True when a skill is reachable anywhere under `directory`.\n *\n * The discriminator between \"a CONTAINER of skills\" and \"an ordinary directory\n * that happens to sit in the pack root\" (`docs/`, `assets/`, ...). Used on the\n * section 3 GLOB path, where a container has to be recognized without a\n * `pack.toml` to declare it.\n *\n * Written in terms of `packContainerLeaves` so the glob's notion of \"container\"\n * can never drift from what the expansion actually reaches \u2014 a directory that\n * qualifies here always contributes at least one member, and one that does not\n * qualify could never have contributed any.\n */\nfunction hasFlattenableChildren(directory: string): boolean {\n return packContainerLeaves(directory).leaves.length > 0;\n}\n\n/**\n * Expand the declared inventory per contract section 3b.\n *\n * With `flatten` off this is the identity map, which is what keeps every\n * existing pack byte-for-byte unchanged: no released `bmad` pack declares\n * `[policy] flatten`, so each takes the early return below and never sees a\n * single new filesystem read.\n *\n * (Do not name a specific BMAD version here: `bmad-version-surface` regressions\n * scan source for retired version literals and will fail the suite.)\n */\nexport function expandPackInventory(\n root: string,\n declared: string[],\n entry: Pick<PackManifestEntry, \"name\">,\n flatten: boolean\n): { inventory: PackMember[]; warnings: string[] } {\n if (!flatten) {\n return {\n inventory: declared.map((name) => ({ name, path: name, declaredEntry: name })),\n warnings: [],\n };\n }\n\n const inventory: PackMember[] = [];\n const warnings: string[] = [];\n const origin = new Map<string, string>();\n /**\n * Project one leaf. Returns true when it was actually claimed.\n *\n * `declaredAsIs` marks the one case where the name was NOT lifted off the\n * filesystem: a declared entry that is already a skill keeps the author's\n * string, exactly as it would without flatten. It defaults to false so the\n * canonical gate is the fail-safe direction for any future call site.\n */\n const claim = (member: PackMember, declaredAsIs = false): boolean => {\n if (!declaredAsIs && !CANONICAL_NAME_PATTERN.test(member.name)) {\n // Contract 3b. Flatten is the ONLY place a projected skill name is lifted\n // straight off the filesystem \u2014 without it a pack.toml pack projects\n // exactly the strings its author typed into `[freeform].skills`.\n // `validatePathComponent` only asks for one safe path component, which\n // happily admits `-rf`, `--help`, `*`, and names carrying newlines or\n // tabs; those become argv- and glob-hostile symlink names in all six CLI\n // skill directories. Skipped rather than thrown so one odd upstream\n // directory cannot brick a whole pack. JSON.stringify keeps control\n // characters escaped in the warning itself.\n warnings.push(\n `Pack ${entry.name} leaf ${JSON.stringify(member.name)} at ${member.path} is not a canonical skill name (${CANONICAL_NAME_PATTERN.source}); skipping`\n );\n return false;\n }\n validatePathComponent(member.name, `Pack ${entry.name} skill name`);\n const previous = origin.get(member.name);\n if (previous !== undefined) {\n // Ambiguous pack: two leaves would project onto one CLI destination, and\n // which one won would depend on inventory order. Refuse rather than\n // silently pick. (ACROSS packs this is fine \u2014 section 5 precedence\n // decides \u2014 but within ONE pack there is no rule to apply.)\n throw new Error(\n `Pack ${entry.name} flattens to a duplicate skill name ${JSON.stringify(member.name)}: ${join(root, previous)} and ${join(root, member.path)}`\n );\n }\n origin.set(member.name, member.path);\n inventory.push(member);\n return true;\n };\n\n for (const declaredEntry of declared) {\n const declaredDir = join(root, declaredEntry);\n // Defence in depth: `packPayload` has already asserted this, but\n // `expandPackInventory` is exported and must be safe standalone.\n assertRealDirectory(declaredDir, `Pack skill ${declaredEntry}`);\n // Entry HAS a regular SKILL.md -> it IS a skill, taken as-is.\n if (isRegularFile(join(declaredDir, \"SKILL.md\"))) {\n // The name is the author's declared string, not a filesystem basename.\n claim({ name: declaredEntry, path: declaredEntry, declaredEntry }, true);\n continue;\n }\n // Entry has NO SKILL.md -> it is a CONTAINER. Descend it to ANY depth: the\n // walk stops on each branch at the first directory that carries a SKILL.md,\n // so a container of containers (hermes-base's `mlops/`) resolves the same way\n // upstream's depth-agnostic `iter_skill_index_files` does.\n const { leaves, symlinked } = packContainerLeaves(declaredDir);\n // Section 4 is STRICTER than 3b's \"skip a symlink with a warning\": a symlink\n // anywhere under a DECLARED entry is a payload violation, and `packPayload`\n // has already thrown on it by the time `validatePack` gets here. This arm\n // therefore only ever runs for a direct caller that did not walk the payload\n // first; dropping it would make such a caller silently lose a member.\n for (const child of symlinked) {\n warnings.push(`Pack ${entry.name} member ${declaredEntry}/${child} is a symlink; skipping`);\n }\n let contributed = 0;\n for (const leafPath of leaves) {\n // The NAME is the leaf's basename; the PATH may be any number of segments\n // deep. Nothing downstream may re-derive one from the other.\n if (claim({ name: basename(leafPath), path: `${declaredEntry}/${leafPath}`, declaredEntry })) {\n contributed += 1;\n }\n }\n if (contributed === 0) {\n // A container whose ENTIRE subtree yields no PROJECTABLE skill \u2014 either it\n // holds none at all, or every leaf it holds was rejected by the\n // canonical-name gate. Never silently dropped \u2014 contract section 3b.\n warnings.push(\n `Pack ${entry.name} declared entry ${JSON.stringify(declaredEntry)} is a container that contributes no skills`\n );\n }\n }\n return { inventory, warnings };\n}\n\nexport function packDeclaredSkills(\n root: string,\n metadata: PackMetadata | null,\n entry: Pick<PackManifestEntry, \"name\" | \"version\">,\n flatten = false\n): string[] {\n if (metadata) {\n if (metadata.name !== entry.name) {\n throw new Error(`Pack ${entry.name} pack.toml declares name ${JSON.stringify(metadata.name ?? null)}`);\n }\n if (entry.version && metadata.version !== entry.version) {\n throw new Error(\n `Pack ${entry.name} pack.toml declares version ${JSON.stringify(metadata.version ?? null)}, manifest pins ${JSON.stringify(entry.version)}`\n );\n }\n const declared = metadata.skills.map((name) => validatePathComponent(name, `Pack ${entry.name} skill name`));\n if (new Set(declared).size !== declared.length) {\n throw new Error(`Pack ${entry.name} pack.toml declares duplicate skills`);\n }\n return declared;\n }\n\n const declared: string[] = [];\n for (const name of readdirSync(root).sort()) {\n if (name.startsWith(\".\") || name.startsWith(\"_\")) continue;\n const stat = lstatSync(join(root, name));\n // A symlinked child is never a pack member; it is skipped, not followed.\n if (stat.isSymbolicLink() || !stat.isDirectory()) continue;\n if (!isRegularFile(join(root, name, \"SKILL.md\"))) {\n // A `pack.toml`-less pack has no declared list to expand, so section 3b's\n // container level has to be admitted by the glob itself or the manifest\n // `flatten` flag \u2014 which section 3b says exists precisely for packs with\n // no `pack.toml` \u2014 could never do anything. A container qualifies on the\n // same descent test section 3b expands it with, so the glob admits exactly\n // the directories that go on to contribute at least one member.\n if (!flatten || !hasFlattenableChildren(join(root, name))) continue;\n }\n declared.push(validatePathComponent(name, `Pack ${entry.name} skill name`));\n }\n return declared;\n}\n\n// ---------------------------------------------------------------------------\n// Payload + sealed verification (contract section 4)\n// ---------------------------------------------------------------------------\n\nfunction walkPackSubtree(\n root: string,\n relativeRoot: string,\n files: Map<string, string>,\n directories: Set<string>\n): void {\n const visit = (directory: string): void => {\n for (const name of readdirSync(directory).sort()) {\n const path = join(directory, name);\n const key = relative(root, path).split(sep).join(\"/\");\n const stat = lstatSync(path);\n if (stat.isSymbolicLink()) throw new Error(`Pack payload may not contain symlinks: ${path}`);\n if (stat.isDirectory()) {\n directories.add(key);\n visit(path);\n } else if (stat.isFile()) {\n files.set(key, hashRegularFile(path));\n } else {\n throw new Error(`Pack payload may contain only regular files and directories: ${path}`);\n }\n }\n };\n directories.add(relativeRoot);\n visit(join(root, relativeRoot));\n}\n\n/**\n * payload = `pack.toml` + every file recursively under each DECLARED skill dir.\n *\n * UNCHANGED by section 3b: a container is a declared entry, and walking it\n * recursively already covers every leaf underneath it. That is why a flattened\n * pack seals and verifies with no change to section 4 at all.\n *\n * The one thing `flatten` moves is WHERE the `SKILL.md` requirement is enforced.\n * With flatten off, a declared entry must be a skill, so its missing `SKILL.md`\n * is reported here (and, inside a seal, becomes an integrity failure). With\n * flatten on, a declared entry legitimately may be a container, so the\n * requirement moves to `expandPackInventory`, which finds members BY their\n * `SKILL.md`. Declaring a container must never raise `SKILL_MD_MISSING`.\n */\nexport function packPayload(\n root: string,\n metadata: PackMetadata | null,\n declared: string[],\n flatten = false\n): { files: Map<string, string>; directories: Set<string> } {\n const files = new Map<string, string>();\n const directories = new Set<string>();\n if (metadata) files.set(\"pack.toml\", hashRegularFile(join(root, \"pack.toml\")));\n for (const name of declared) {\n const skillDir = join(root, name);\n assertRealDirectory(skillDir, `Pack skill ${name}`);\n if (!flatten && !isRegularFile(join(skillDir, \"SKILL.md\"))) {\n throw new PackUnavailableError(`Pack skill ${name} is missing a regular SKILL.md: ${skillDir}`);\n }\n walkPackSubtree(root, name, files, directories);\n }\n return { files, directories };\n}\n\nexport function parsePackChecksums(root: string): Map<string, string> {\n const raw = readRegularFile(join(root, \"SHA256SUMS\")).toString(\"utf8\");\n const expected = new Map<string, string>();\n for (const line of raw.split(\"\\n\")) {\n if (!line) continue;\n const match = line.match(/^([0-9a-f]{64}) (.+)$/);\n if (!match) throw new Error(`Invalid SHA256SUMS entry in ${root}: ${line}`);\n const path = safeRelativePath(match[2]!, \"checksum path\");\n if (expected.has(path)) throw new Error(`Duplicate SHA256SUMS entry in ${root}: ${path}`);\n expected.set(path, match[1]!);\n }\n return expected;\n}\n\nfunction verifySealedPack(root: string, files: Map<string, string>, directories: Set<string>): void {\n const expected = parsePackChecksums(root);\n\n // Rule 2: every payload file is covered, with a matching digest.\n const missing = [...files.keys()].filter((path) => !expected.has(path)).sort();\n if (missing.length) {\n throw new Error(`Pack payload at ${root} is not covered by SHA256SUMS: ${JSON.stringify(missing.slice(0, 5))}`);\n }\n for (const [path, digest] of files) {\n if (expected.get(path) !== digest) throw new Error(`Pack digest mismatch at ${root}: ${path}`);\n }\n\n // Rule 3: covered-but-not-payload files (README.md, ...) are still verified.\n // They are legal; they simply may not be absent.\n for (const path of [...expected.keys()].sort()) {\n if (files.has(path)) continue;\n const digest = expected.get(path)!;\n let actual: string;\n try {\n assertNoSymlinkComponents(root, path);\n actual = hashRegularFile(join(root, path));\n } catch (error) {\n if (error instanceof PackUnavailableError) {\n throw new Error(`SHA256SUMS at ${root} references a missing path: ${path}`);\n }\n throw error;\n }\n if (actual !== digest) throw new Error(`Pack digest mismatch at ${root}: ${path}`);\n }\n\n // A payload directory holding no authenticated file is unauthenticated: it is\n // not covered by any checksum, so it could be planted without detection.\n const covered = new Set<string>();\n for (const path of files.keys()) {\n const parts = path.split(\"/\");\n for (let index = 1; index < parts.length; index += 1) covered.add(parts.slice(0, index).join(\"/\"));\n }\n const unauthenticated = [...directories].filter((directory) => !covered.has(directory)).sort();\n if (unauthenticated.length) {\n throw new Error(\n `Pack at ${root} contains unauthenticated empty directories: ${JSON.stringify(unauthenticated.slice(0, 5))}`\n );\n }\n}\n\n/**\n * Validate a pack root against a (normalized) manifest entry.\n *\n * Sealed packs get full checksum verification; unsealed packs get structural\n * validation only \u2014 real pack root, parsable pack.toml, every declared skill\n * present with a regular SKILL.md, no symlinks and nothing but regular files\n * inside the payload.\n */\nexport function validatePack(packRoot: string, entry: PackManifestEntry): ValidatedPack {\n const root = resolve(packRoot);\n assertRealDirectory(root, `Pack ${entry.name} root`);\n\n const metadata = readPackMetadata(root);\n const flatten = packFlattenEnabled(metadata, entry);\n const declared = packDeclaredSkills(root, metadata, entry, flatten);\n // The manifest may only TIGHTEN: `sealed: false` cannot disable a sealed pack.\n const sealed = entry.sealed === true || metadata?.sealed === true;\n\n const { files, directories } = packPayload(root, metadata, declared, flatten);\n if (metadata?.payloadFiles !== undefined) {\n const actual = [...files.keys()].filter((path) => path !== \"pack.toml\").length;\n if (actual !== metadata.payloadFiles) {\n throw new Error(`Pack at ${root} declares ${metadata.payloadFiles} payload files but has ${actual}`);\n }\n }\n if (sealed) {\n if (!isRegularFile(join(root, \"SHA256SUMS\"))) throw new Error(`Sealed pack at ${root} has no regular SHA256SUMS`);\n verifySealedPack(root, files, directories);\n }\n\n // Expansion runs AFTER integrity verification so a tampered pack can never be\n // enumerated, and so a flattening error can never mask a digest mismatch.\n const { inventory, warnings } = expandPackInventory(root, declared, entry, flatten);\n\n // Contract section 3b: include/exclude apply to the FINAL flattened names.\n let members = inventory;\n if (entry.include) {\n const wanted = new Set(entry.include);\n members = members.filter((member) => wanted.has(member.name));\n }\n if (entry.exclude?.length) {\n const unwanted = new Set(entry.exclude);\n members = members.filter((member) => !unwanted.has(member.name));\n }\n\n const memberPaths = new Map<string, string>();\n for (const member of members) {\n // Every segment was validated as one safe path component on the way in.\n memberPaths.set(member.name, join(root, ...member.path.split(\"/\")));\n }\n\n return {\n name: entry.name,\n version: entry.version,\n root,\n declared,\n inventory,\n inventoryNames: inventory.map((member) => member.name),\n members: members.map((member) => member.name),\n memberPaths,\n flatten,\n warnings,\n sealed,\n payloadFiles: [...files.keys()].filter((path) => path !== \"pack.toml\").length,\n };\n}\n", "import { Recipe } from \"./Recipe\";\nimport type { CommandContext } from \"../commands/Command\";\nimport { createAgentHooksChecks } from \"../parity/rules\";\nimport type { LifecycleContext, RecipeInitResult, RecipeMetadata } from \"./types\";\n\n/**\n * Retrofit an existing repo with the project-scoped agent-hooks + skill manifest\n * layer (Claude/Codex/Kimi/Hermes hooks + sync-skills manifest via mise enter/leave).\n * New projects get this from the CommonProject template directly; this recipe is\n * for repos created before the template carried it.\n */\nexport class AgentHooksRecipe extends Recipe {\n readonly checks = createAgentHooksChecks();\n readonly metadata: RecipeMetadata = {\n id: \"agent-hooks\",\n name: \"agent-hooks\",\n description: \"Project-scoped agent hooks and six-CLI skill topology\",\n dependencies: [\"mise\"],\n commands: [\"CopyAgentHooksTree\", \"WireMiseAgentHooks\"],\n publicRuleIds: this.checks.map((check) => check.id),\n };\n\n constructor(context?: CommandContext) {\n super(context);\n }\n\n override init(ctx: LifecycleContext, _input: unknown): Promise<RecipeInitResult> {\n return this.initializeOwnedChecks(ctx);\n }\n\n protected printNextSteps(): void {\n console.log(\"\uD83E\uDE9D Agent-hooks layer installed!\");\n console.log(\" Next steps:\");\n console.log(\" 1. mise run skills:sync # sync .agents/skills.json into local CLI dirs\");\n console.log(\" 2. mise run hooks:sync # generate .claude/settings.json + inject codex/kimi/hermes\");\n console.log(\" 3. git add .claude/settings.json .agents/hooks .agents/skills.json && commit (codex/kimi/hermes are per-dev)\");\n console.log(\" 4. mise run hindsight:setup # set HINDSIGHT_OP_KEY_REF to your 1Password item first\");\n console.log(\" 5. Optional per-dev hook opt-out: copy .agents/local.example.json -> .agents/local.json\");\n }\n}\n", "import type { CommandContext } from \"../commands/Command\";\nimport { createBmadChecks } from \"../parity/rules\";\nimport { Recipe } from \"./Recipe\";\nimport type { LifecycleContext, RecipeInitResult, RecipeMetadata } from \"./types\";\n\n/** Owns BMAD installation, version currency, and supported CLI projections. */\nexport class BmadRecipe extends Recipe {\n readonly checks = createBmadChecks();\n readonly metadata: RecipeMetadata = {\n id: \"bmad\",\n name: \"bmad\",\n description: \"BMAD methodology and six supported CLI projections\",\n dependencies: [\"agent-hooks\"],\n commands: [],\n publicRuleIds: this.checks.map((check) => check.id),\n };\n\n constructor(context?: CommandContext) {\n super(context);\n }\n\n override init(ctx: LifecycleContext, _input: unknown): Promise<RecipeInitResult> {\n return this.initializeOwnedChecks(ctx);\n }\n\n protected printNextSteps(): void {\n console.log(\"BMAD lifecycle initialized for the six supported CLIs.\");\n }\n}\n", "import { Command, type InvokeResult, type CommandContext } from \"./Command\";\n\nexport class AddDockerfile extends Command {\n async invoke(): Promise<InvokeResult> {\n const filePath = \"Dockerfile\";\n \n if (this.fileExists(filePath) && !this.context.force) {\n return {\n success: false,\n message: this.formatMessage(\"\u26A0\uFE0F Dockerfile already exists\"),\n filePath\n };\n }\n\n const content = `FROM node:20-alpine\n\nWORKDIR /app\n\nCOPY package.json bun.lockb ./\nRUN bun install\n\nCOPY . .\n\nRUN bun run build\n\nEXPOSE 3000\n\nCMD [\"bun\", \"run\", \"start\"]\n`;\n\n this.writeFile(filePath, content);\n return {\n success: true,\n message: this.formatMessage(this.context.dryRun ? \"Would create Dockerfile\" : \"\u2705 Created Dockerfile\"),\n filePath\n };\n }\n}", "import { Command, type InvokeResult, type CommandContext } from \"./Command\";\n\nexport class AddDockerCompose extends Command {\n async invoke(): Promise<InvokeResult> {\n const filePath = \"docker-compose.yml\";\n \n if (this.fileExists(filePath) && !this.context.force) {\n return {\n success: false,\n message: this.formatMessage(\"\u26A0\uFE0F docker-compose.yml already exists\"),\n filePath\n };\n }\n\n const content = `version: '3.8'\n\nservices:\n app:\n build: .\n ports:\n - \"3000:3000\"\n environment:\n - NODE_ENV=production\n volumes:\n - ./logs:/app/logs\n restart: unless-stopped\n\n redis:\n image: redis:7-alpine\n ports:\n - \"6379:6379\"\n volumes:\n - redis_data:/data\n restart: unless-stopped\n\nvolumes:\n redis_data:\n`;\n\n this.writeFile(filePath, content);\n return {\n success: true,\n message: this.formatMessage(this.context.dryRun ? \"Would create docker-compose.yml\" : \"\u2705 Created docker-compose.yml\"),\n filePath\n };\n }\n}", "import type { InvokeResult } from \"./Command\";\nimport { Command } from \"./Command\";\n\nexport class AddDockerignore extends Command {\n async invoke(): Promise<InvokeResult> {\n const filePath = \".dockerignore\";\n\n if (this.fileExists(filePath) && !this.context.force) {\n return {\n success: false,\n message: this.formatMessage(\"\u26A0\uFE0F .dockerignore already exists\"),\n filePath\n };\n }\n\n const content = `node_modules\nnpm-debug.log\ndist\nbuild\n.env\n.git\n*.md\n`;\n\n this.writeFile(filePath, content);\n return {\n success: true,\n message: this.formatMessage(this.context.dryRun ? \"Would create .dockerignore\" : \"\u2705 Created .dockerignore\"),\n filePath\n };\n }\n}\n", "import { Recipe } from \"./Recipe\";\nimport { AddDockerfile } from \"../commands/AddDockerfile\";\nimport { AddDockerCompose } from \"../commands/AddDockerCompose\";\nimport { AddDockerignore } from \"../commands/AddDockerignore\";\nimport type { CommandContext } from \"../commands/Command\";\nimport type { LifecycleContext, RecipeCheck, RecipeInitResult, RecipeMetadata } from \"./types\";\n\nexport class DockerRecipe extends Recipe {\n // PJAN-84: deliberately no checks, and this is the reason.\n //\n // An audit rule here would have to answer \"did pjangler install this?\", and\n // the recipe records no provenance \u2014 nothing distinguishes the Dockerfile\n // `pj add docker` wrote from one the operator wrote by hand. Requiring all\n // three artifacts whenever any of them is present would flag every repo with\n // a hand-written Dockerfile and no compose file, which is most of them.\n //\n // So the honest state is what `describe` already reports: the subsystem's\n // presence comes from marker files and its parity reads \"unchecked\". A rule\n // that produced false positives would be worse than no rule. Give this checks\n // when the recipe starts recording what it wrote \u2014 not before.\n readonly checks: readonly RecipeCheck[] = [];\n readonly metadata: RecipeMetadata = {\n id: \"docker\",\n name: \"docker\",\n description: \"Docker containerization setup\",\n dependencies: [],\n commands: [\"AddDockerfile\", \"AddDockerCompose\", \"AddDockerignore\"],\n publicRuleIds: [],\n };\n\n constructor(context?: CommandContext) {\n super(context);\n this\n .addIngredient(AddDockerfile)\n .addIngredient(AddDockerCompose)\n .addIngredient(AddDockerignore);\n }\n\n override init(ctx: LifecycleContext, _input: unknown): Promise<RecipeInitResult> {\n return this.invokeIngredients(ctx);\n }\n\n protected printNextSteps(): void {\n console.log(\"\uD83C\uDF89 Docker subsystem initialized successfully!\");\n console.log(\" Next steps:\");\n console.log(\" 1. docker-compose up -d\");\n console.log(\" 2. docker-compose logs -f\");\n }\n}\n", "import { homedir, platform } from \"node:os\";\nimport {\n existsSync,\n lstatSync,\n mkdirSync,\n readFileSync,\n realpathSync,\n renameSync,\n rmSync,\n writeFileSync,\n type Stats,\n} from \"node:fs\";\nimport { spawnSync } from \"node:child_process\";\nimport { basename, join, dirname } from \"node:path\";\nimport { Command, type InvokeResult } from \"../Command\";\nimport type { HermesAgentContext } from \"./types\";\n\nconst HERMES_GIT_URL = \"https://github.com/delorenj/hermes-agent.git\";\nconst HERMES_GIT_REF = \"main\";\nconst HERMES_GIT_SHA = \"0408fec7a153e6c32c064acd2b8053917f1525f1\";\n\ntype ConfigSchema = ReadonlyArray<{\n section: string;\n values: ReadonlyArray<readonly [key: string, value: string]>;\n}>;\n\n/** Resolve the one host-global config consumed by the pinned Copier template. */\nexport function resolveTemplateConfigPath(): string {\n const fromEnv = process.env.HERMES_TEMPLATE_CONFIG;\n if (fromEnv && fromEnv.trim()) return fromEnv.trim();\n const xdg = process.env.XDG_CONFIG_HOME?.trim();\n const base = xdg && xdg.length ? xdg : join(homedir(), \".config\");\n return join(base, \"hermes-agent-template\", \"config.toml\");\n}\n\nfunction quote(value: string): string {\n return JSON.stringify(value);\n}\n\nfunction detectHermesInstall(home: string): { bin: string; repo: string } {\n const releaseRoot = join(home, \".local\", \"share\", \"hermes-agent\", \"releases\", HERMES_GIT_SHA);\n const devRoot = join(home, \"code\", \"hermes-agent\");\n const candidates = [\n join(releaseRoot, \".venv\", \"bin\", \"hermes\"),\n join(home, \".local\", \"bin\", \"hermes\"),\n join(devRoot, \"venv\", \"bin\", \"hermes\"),\n join(devRoot, \".venv\", \"bin\", \"hermes\"),\n ];\n const bin = candidates.find((candidate) => existsSync(candidate)) ?? candidates[0]!;\n try {\n const resolved = realpathSync(bin);\n const environment = dirname(dirname(resolved));\n if ([\"venv\", \".venv\"].includes(environment.split(\"/\").at(-1) ?? \"\")) {\n return { bin, repo: dirname(environment) };\n }\n } catch {\n // A not-yet-installed pinned release is still the canonical bootstrap guess.\n }\n return { bin, repo: bin.startsWith(devRoot) ? devRoot : releaseRoot };\n}\n\nfunction hostSchema(): ConfigSchema {\n const home = homedir();\n const hermes = detectHermesInstall(home);\n return [\n {\n section: \"fleet\",\n values: [\n [\"hermes_bin\", quote(hermes.bin)],\n [\"hermes_repo\", quote(hermes.repo)],\n [\"pjangler_bin\", quote(\"pj\")],\n [\"hermes_git_url\", quote(HERMES_GIT_URL)],\n [\"hermes_git_ref\", quote(HERMES_GIT_REF)],\n [\"hermes_git_sha\", quote(HERMES_GIT_SHA)],\n [\"runtime_scaffold_dir\", quote(join(home, \"code\", \"hermes-agent-template\", \"runtime-scaffold\"))],\n [\"fleet_env\", quote(\"~/.hermes/fleet.env\")],\n [\"registry_file\", quote(\"~/.hermes/agents-registry.yaml\")],\n [\"oauth_file\", quote(\"~/.hermes/auth.json\")],\n [\"codex_home\", quote(\"~/.codex\")],\n [\"canonical_skills_dir\", quote(join(home, \".agents\", \"skills\"))],\n [\"vox_plugin_name\", quote(\"vox\")],\n [\"vox_plugin_dir\", quote(join(home, \"code\", \"voxxy\", \"plugins\", \"tts\", \"vox\"))],\n [\"vox_voice\", quote(\"carlin\")],\n [\"vox_url\", quote(\"https://vox.delo.sh\")],\n [\"onepassword_vault\", quote(\"DeLoSecrets\")],\n [\"onepassword_item_prefix\", quote(\"hermes-agent\")],\n [\n \"symlinked_runtime_skills\",\n `[${[\n \"delonet-conventions\",\n \"delonet-dotenv\",\n \"hermes-pm-template-maintenance\",\n \"hindsight\",\n \"33god-projects\",\n \"subagent-driven-development\",\n ].map(quote).join(\", \")}]`,\n ],\n ],\n },\n { section: \"github\", values: [[\"runtime_repo_owner\", quote(\"\")]] },\n {\n section: \"plane\",\n values: [\n [\"base\", quote(\"https://plane.delo.sh\")],\n [\"workspace\", quote(\"33god\")],\n ],\n },\n ];\n}\n\n/** Render the current, pinned template schema with host-derived path values. */\nexport function renderHostConfig(): string {\n const sections = hostSchema()\n .map(({ section, values }) => `[${section}]\\n${values.map(([key, value]) => `${key} = ${value}`).join(\"\\n\")}`)\n .join(\"\\n\\n\");\n return `# hermes-agent-template \u2014 host configuration\\n# Bootstrapped by \\`pj config bootstrap\\` for $HOME=${homedir()} (platform=${platform()}).\\n# Existing values and additional keys are preserved by \\`--force\\`; it only adds\\n# fields missing from the schema pinned in this pjangler release.\\n# Resolution precedence: env var > ~/.hermes/fleet.env > this file > fallback.\\n\\n${sections}\\n`;\n}\n\nexport interface TomlTableHeader {\n kind: \"table\" | \"array-table\";\n path: string[];\n headerStart: number;\n bodyStart: number;\n bodyEnd: number;\n}\n\ntype MultilineString = \"basic\" | \"literal\" | undefined;\n\nfunction isEscaped(value: string, index: number): boolean {\n let slashes = 0;\n for (let cursor = index - 1; cursor >= 0 && value[cursor] === \"\\\\\"; cursor -= 1) slashes += 1;\n return slashes % 2 === 1;\n}\n\n/** Track TOML multiline strings so header-looking payload lines stay payload. */\nfunction scanMultilineState(line: string, initial: MultilineString): MultilineString {\n let state = initial;\n let string: \"basic\" | \"literal\" | undefined;\n for (let index = 0; index < line.length;) {\n if (state) {\n const marker = state === \"basic\" ? '\\\"\\\"\\\"' : \"'''\";\n const close = line.indexOf(marker, index);\n if (close === -1) return state;\n if (state === \"basic\" && isEscaped(line, close)) {\n index = close + marker.length;\n continue;\n }\n state = undefined;\n index = close + marker.length;\n continue;\n }\n if (string === \"basic\") {\n if (line[index] === '\\\"' && !isEscaped(line, index)) string = undefined;\n index += 1;\n continue;\n }\n if (string === \"literal\") {\n if (line[index] === \"'\") string = undefined;\n index += 1;\n continue;\n }\n if (line[index] === \"#\") break;\n if (line.startsWith('\\\"\\\"\\\"', index)) {\n state = \"basic\";\n index += 3;\n continue;\n }\n if (line.startsWith(\"'''\", index)) {\n state = \"literal\";\n index += 3;\n continue;\n }\n if (line[index] === '\\\"') string = \"basic\";\n else if (line[index] === \"'\") string = \"literal\";\n index += 1;\n }\n return state;\n}\n\nfunction parseBasicKey(raw: string): string | undefined {\n try {\n const parsed = JSON.parse(raw) as unknown;\n return typeof parsed === \"string\" ? parsed : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Parse a TOML dotted key, including quoted segments, without losing spelling. */\nfunction parseDottedKey(raw: string): string[] | undefined {\n const path: string[] = [];\n let cursor = 0;\n const whitespace = () => {\n while (cursor < raw.length && /[ \\t]/.test(raw[cursor]!)) cursor += 1;\n };\n whitespace();\n while (cursor < raw.length) {\n let key: string | undefined;\n if (raw[cursor] === '\\\"') {\n const start = cursor;\n cursor += 1;\n while (cursor < raw.length) {\n if (raw[cursor] === '\\\"' && !isEscaped(raw, cursor)) {\n cursor += 1;\n key = parseBasicKey(raw.slice(start, cursor));\n break;\n }\n cursor += 1;\n }\n } else if (raw[cursor] === \"'\") {\n const end = raw.indexOf(\"'\", cursor + 1);\n if (end !== -1) {\n key = raw.slice(cursor + 1, end);\n cursor = end + 1;\n }\n } else {\n const match = raw.slice(cursor).match(/^[A-Za-z0-9_-]+/);\n if (match) {\n key = match[0];\n cursor += match[0].length;\n }\n }\n if (key === undefined) return undefined;\n path.push(key);\n whitespace();\n if (cursor === raw.length) return path;\n if (raw[cursor] !== \".\") return undefined;\n cursor += 1;\n whitespace();\n if (cursor === raw.length) return undefined;\n }\n return path.length ? path : undefined;\n}\n\nfunction parseHeaderLine(line: string): Pick<TomlTableHeader, \"kind\" | \"path\"> | undefined {\n const text = line.trimStart();\n if (!text.startsWith(\"[\")) return undefined;\n const kind: TomlTableHeader[\"kind\"] = text.startsWith(\"[[\") ? \"array-table\" : \"table\";\n const openLength = kind === \"array-table\" ? 2 : 1;\n const close = kind === \"array-table\" ? \"]]\" : \"]\";\n let string: \"basic\" | \"literal\" | undefined;\n let closeAt = -1;\n for (let cursor = openLength; cursor < text.length; cursor += 1) {\n if (string === \"basic\") {\n if (text[cursor] === '\\\"' && !isEscaped(text, cursor)) string = undefined;\n continue;\n }\n if (string === \"literal\") {\n if (text[cursor] === \"'\") string = undefined;\n continue;\n }\n if (text[cursor] === '\\\"') {\n string = \"basic\";\n continue;\n }\n if (text[cursor] === \"'\") {\n string = \"literal\";\n continue;\n }\n if (text.startsWith(close, cursor)) {\n closeAt = cursor;\n break;\n }\n }\n if (closeAt === -1) return undefined;\n const tail = text.slice(closeAt + close.length);\n if (!/^[ \\t]*(?:#.*)?$/.test(tail)) return undefined;\n const path = parseDottedKey(text.slice(openLength, closeAt));\n return path ? { kind, path } : undefined;\n}\n\n/**\n * Parse table spans while preserving the original document byte-for-byte.\n * Every table owns content only until the next normal OR array-table header.\n */\nexport function parseTomlTableHeaders(source: string): TomlTableHeader[] {\n const parsed: Array<Omit<TomlTableHeader, \"bodyEnd\">> = [];\n let offset = 0;\n let multiline: MultilineString;\n for (const match of source.matchAll(/[^\\r\\n]*(?:\\r\\n|\\n|\\r|$)/g)) {\n const segment = match[0];\n if (!segment) break;\n const line = segment.replace(/(?:\\r\\n|\\n|\\r)$/, \"\");\n if (!multiline) {\n const header = parseHeaderLine(line);\n if (header) {\n parsed.push({\n ...header,\n headerStart: offset,\n bodyStart: offset + segment.length,\n });\n }\n }\n multiline = scanMultilineState(line, multiline);\n offset += segment.length;\n }\n return parsed.map((header, index) => ({\n ...header,\n bodyEnd: parsed[index + 1]?.headerStart ?? source.length,\n }));\n}\n\nfunction ownedBareKeys(source: string, table: TomlTableHeader): Set<string> {\n const keys = new Set<string>();\n let multiline: MultilineString;\n const body = source.slice(table.bodyStart, table.bodyEnd);\n for (const match of body.matchAll(/[^\\r\\n]*(?:\\r\\n|\\n|\\r|$)/g)) {\n const segment = match[0];\n if (!segment) break;\n const line = segment.replace(/(?:\\r\\n|\\n|\\r)$/, \"\");\n if (!multiline) {\n const assignment = line.match(/^\\s*((?:\"(?:\\\\.|[^\"\\\\])*\"|'[^']*'|[A-Za-z0-9_-]+))\\s*=/);\n if (assignment) {\n const path = parseDottedKey(assignment[1]!);\n if (path?.length === 1) keys.add(path[0]!);\n }\n }\n multiline = scanMultilineState(line, multiline);\n }\n return keys;\n}\n\nconst TOMLLIB_VALIDATE = String.raw`\nimport sys\n\ntry:\n import tomllib\nexcept Exception as exc:\n sys.stderr.write(\"TOMLLIB_UNAVAILABLE:\" + repr(exc))\n raise SystemExit(2)\n\ntry:\n source = sys.stdin.buffer.read().decode(\"utf-8\", errors=\"strict\")\n tomllib.loads(source)\nexcept (UnicodeDecodeError, tomllib.TOMLDecodeError) as exc:\n sys.stderr.write(\"TOML_INVALID:\" + exc.__class__.__name__ + \": \" + str(exc))\n raise SystemExit(1)\n`;\n\nconst TOMLLIB_VALIDATION_TIMEOUT_MS = 5_000;\n\n/**\n * Python's isolated mode ignores PYTHON* settings itself. Removing them from\n * the child environment as well keeps project/operator configuration from even\n * reaching the validator process and makes that boundary independently\n * auditable.\n */\nfunction isolatedPythonEnvironment(): NodeJS.ProcessEnv {\n return Object.fromEntries(\n Object.entries(process.env).filter(([name]) => !name.toUpperCase().startsWith(\"PYTHON\")),\n );\n}\n\n\n/**\n * Validate the exact bytes with the Python tomllib consumer used by Hermes.\n *\n * Validation is REQUIRED, not best effort. This command exists only to write a\n * file whose sole consumer is `tomllib.load()` inside the template's shell\n * library, and that consumer swallows every parse failure and silently returns\n * the caller's default (_lib.sh `config_get`). A config we could not validate\n * is therefore not a small risk: it degrades every later lookup -- hermes_bin,\n * plane workspace, item prefixes -- to a default, with no error anywhere.\n *\n * Requiring python3 costs no portability either. Every provisioning script in\n * the template drives python3 heredocs, and the config is unreadable without\n * tomllib, so a host that cannot run the validator cannot run Hermes at all.\n */\nfunction validateTomlBytes(source: Buffer, label: string): void {\n const validation = spawnSync(\"python3\", [\"-I\", \"-S\", \"-c\", TOMLLIB_VALIDATE], {\n input: source,\n encoding: \"utf8\",\n env: isolatedPythonEnvironment(),\n maxBuffer: 1024 * 1024,\n timeout: TOMLLIB_VALIDATION_TIMEOUT_MS,\n killSignal: \"SIGKILL\",\n });\n if (validation.error) {\n const code = (validation.error as NodeJS.ErrnoException).code;\n if (code === \"ETIMEDOUT\") {\n throw new Error(`${label} validation timed out after ${TOMLLIB_VALIDATION_TIMEOUT_MS}ms`);\n }\n throw new Error(\n code === \"ENOENT\"\n ? `${label} cannot be validated: python3 with tomllib is required but was not found`\n : `${label} validation failed to start: ${validation.error.message}`,\n );\n }\n if (validation.status === 2 || validation.stderr.startsWith(\"TOMLLIB_UNAVAILABLE:\")) {\n throw new Error(\n `${label} cannot be validated: python3 with tomllib is required (${validation.stderr.replace(/^TOMLLIB_UNAVAILABLE:/, \"\")})`,\n );\n }\n if (validation.status !== 0) {\n const detail = validation.stderr.replace(/^TOML_INVALID:/, \"\").trim() || `python3 exited ${validation.status ?? \"without a status\"}`;\n throw new Error(`${label} is not valid TOML 1.0 for Python tomllib: ${detail}`);\n }\n}\n\nfunction assertValidToml(source: string, label: string): void {\n validateTomlBytes(Buffer.from(source, \"utf8\"), label);\n}\n\n/**\n * Add missing pinned-schema fields without replacing operator values, comments,\n * unknown keys, or richer sections. This is intentionally a small TOML-aware\n * merge rather than a parse/stringify round trip, which would erase comments.\n *\n * The input is BYTES, deliberately, and the parameter type is the enforcement.\n * `readFileSync(path, \"utf8\")` replaces an invalid UTF-8 sequence with U+FFFD,\n * which is a perfectly valid TOML string character -- so a config the deployed\n * Python `tomllib` consumer cannot even decode would validate here and then be\n * rewritten with those replacement characters, silently destroying operator\n * bytes that Hermes itself would have refused to read. Validation runs on the\n * exact bytes, and the decode that follows is proved lossless before merging.\n */\nexport function mergeHostConfig(existingBytes: Buffer): string {\n validateTomlBytes(existingBytes, \"Existing Hermes template config\");\n const existing = existingBytes.toString(\"utf8\");\n if (!Buffer.from(existing, \"utf8\").equals(existingBytes)) {\n // Defense in depth. The validator above decodes with errors=\"strict\", so\n // non-UTF-8 bytes never reach this line today; keeping the check makes the\n // lossless-decode invariant local and provable at the point that depends\n // on it, instead of an assumption about another function's Python.\n throw new Error(\"Existing Hermes template config is not valid UTF-8\");\n }\n let merged = existing;\n for (const { section, values } of hostSchema()) {\n const tables = parseTomlTableHeaders(merged);\n const matching = tables.filter((table) => table.kind === \"table\" && table.path.length === 1 && table.path[0] === section);\n if (matching.length > 1) {\n throw new Error(`Cannot merge [${section}]: config contains duplicate table headers`);\n }\n const table = matching[0];\n if (!table) {\n const incompatible = tables.find((candidate) => candidate.path[0] === section);\n if (incompatible) {\n throw new Error(`Cannot merge [${section}]: config defines ${incompatible.kind === \"array-table\" ? \"an array table\" : \"a child table\"} at [${incompatible.path.join(\".\")}] without an owning [${section}] table`);\n }\n const prefix = merged.length === 0 ? \"\" : merged.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n merged += `${prefix}[${section}]\\n${values.map(([key, value]) => `${key} = ${value}`).join(\"\\n\")}\\n`;\n continue;\n }\n const existingKeys = ownedBareKeys(merged, table);\n const missing = values.filter(([key]) => !existingKeys.has(key));\n if (!missing.length) continue;\n const body = merged.slice(table.bodyStart, table.bodyEnd);\n const addition = `${body.length === 0 || body.endsWith(\"\\n\") ? \"\" : \"\\n\"}${missing.map(([key, value]) => `${key} = ${value}`).join(\"\\n\")}\\n`;\n merged = `${merged.slice(0, table.bodyEnd)}${addition}${merged.slice(table.bodyEnd)}`;\n }\n // Text preservation is valuable only while the result remains real TOML.\n // Dotted-key and inline-table ownership forms cannot always be extended by\n // inserting a conventional table/key assignment. Fail before the caller\n // touches disk rather than accepting a corrupt but superficially merged file.\n assertValidToml(merged, \"Merged Hermes template config\");\n return merged;\n}\n\n/**\n * Snapshot of an operator-owned regular config. The identity and content hash\n * are checked again immediately before rename so a concurrent writer cannot be\n * silently overwritten by an additive bootstrap prepared from stale bytes.\n */\n\nfunction describePathType(stats: Stats): string {\n if (stats.isSymbolicLink()) return \"symbolic link\";\n if (stats.isDirectory()) return \"directory\";\n if (stats.isFIFO()) return \"FIFO\";\n if (stats.isSocket()) return \"socket\";\n if (stats.isCharacterDevice()) return \"character device\";\n if (stats.isBlockDevice()) return \"block device\";\n return \"non-regular file\";\n}\n\n/** lstat is the first operation on the config leaf, including the no-force path. */\nfunction inspectConfigPath(path: string): Stats | undefined {\n let stats: Stats;\n try {\n stats = lstatSync(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw error;\n }\n if (!stats.isFile() || stats.isSymbolicLink()) {\n throw new Error(`Unsafe Hermes template config path ${path}: expected a regular file, found ${describePathType(stats)}`);\n }\n return stats;\n}\n\n/**\n * Write the config through a same-directory temp file and one rename.\n *\n * rename(2) within a directory is atomic, so a reader sees either the old file\n * or the complete new one -- never a half-written config. That is the whole of\n * the durability requirement here: this command runs once per `pj hermes-agent`\n * / `pj config bootstrap`, sequentially, in a single process. There is no\n * concurrent writer to defend against, and inventing one cost this file 1,500\n * lines of lock/CAS/crash-recovery machinery that could wedge the command with\n * a leftover transaction directory. Do not reintroduce it: if a genuine\n * multi-writer requirement ever appears, add it with a failing test that\n * demonstrates the race first.\n */\nfunction installConfig(path: string, next: string, previous: Stats | undefined): void {\n const dir = dirname(path);\n mkdirSync(dir, { recursive: true });\n const tmp = join(dir, `.${basename(path)}.pjangler-${process.pid}.tmp`);\n try {\n writeFileSync(tmp, next, { mode: previous ? previous.mode & 0o777 : 0o600 });\n renameSync(tmp, path);\n } catch (error) {\n try {\n rmSync(tmp, { force: true });\n } catch {\n /* the rename already failed; a leftover temp file is not worth masking it */\n }\n throw error;\n }\n}\n\nexport class EnsureTemplateConfig extends Command {\n async invoke(): Promise<InvokeResult> {\n const ctx = this.context as HermesAgentContext;\n if (ctx.deferredExternalEffects && !ctx.applyingDeferredHostEffects) {\n return {\n success: true,\n outcome: \"unchanged\",\n message: \"Hermes host config deferred until rendered lifecycle eligibility passes\",\n };\n }\n\n const force = ctx.forceConfig === true || process.env.PJANGLER_FORCE_CONFIG === \"1\";\n const path = resolveTemplateConfigPath();\n\n let stats: Stats | undefined;\n try {\n stats = inspectConfigPath(path);\n } catch (error) {\n return {\n success: false,\n outcome: \"failed\",\n message: `Failed to inspect ${path}: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n const exists = stats !== undefined;\n if (exists && !force) {\n if (!ctx.quiet) console.log(`\u2713 Config present: ${path}`);\n return { success: true, outcome: \"unchanged\", message: `Config present: ${path}` };\n }\n\n let next = renderHostConfig();\n let current = \"\";\n try {\n if (exists) {\n // Bytes, not a lossy \"utf8\" decode: mergeHostConfig validates the\n // exact file the Python consumer would read and proves the decode is\n // lossless before this command is allowed to rewrite anything.\n const bytes = readFileSync(path);\n next = mergeHostConfig(bytes);\n current = bytes.toString(\"utf8\");\n } else {\n assertValidToml(next, \"Rendered Hermes template config\");\n }\n } catch (error) {\n return {\n success: false,\n outcome: \"failed\",\n message: `Failed to prepare ${path}; no changes were applied: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n\n if (exists && next === current) {\n return { success: true, outcome: \"unchanged\", message: `Config schema already current: ${path}` };\n }\n\n if (ctx.dryRun) {\n if (!ctx.quiet) console.log(`[DRY RUN] Would ${exists ? \"merge missing schema fields into\" : \"create\"} config: ${path}`);\n return {\n success: true,\n outcome: \"planned\",\n filePath: path,\n message: `[DRY RUN] Would ${exists ? \"merge missing schema fields into\" : \"create\"} config: ${path}`,\n };\n }\n\n try {\n installConfig(path, next, stats);\n } catch (error) {\n return {\n success: false,\n outcome: \"failed\",\n message: `Failed to write ${path}: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n\n if (!ctx.quiet) {\n console.log(`\u2713 ${exists ? \"Updated\" : \"Bootstrapped\"} config: ${path}`);\n if (!exists) console.log(\" Review [github].runtime_repo_owner + [plane] + [bloodbank] before a cloud provision.\");\n }\n return {\n success: true,\n outcome: \"changed\",\n filePath: path,\n message: `${exists ? \"Updated\" : \"Bootstrapped\"} config without replacing existing values: ${path}`,\n };\n }\n}\n", "import { basename, join } from \"node:path\";\nimport { readFileSync } from \"node:fs\";\nimport * as p from \"@clack/prompts\";\nimport { Command, type InvokeResult } from \"../Command\";\nimport type { HermesAgentContext, TicketProvider } from \"./types\";\nimport { deriveAgentId, deriveProfileName } from \"./types\";\n\n/**\n * Synergy with CommonProject: if this repo was bootstrapped by the base\n * template, its board provider already lives in .project.json. Read it so the\n * recipe defaults to the SAME provider the repo's board was created in, rather\n * than blindly defaulting to plane.\n */\nfunction detectTicketProvider(targetDir: string): TicketProvider | undefined {\n try {\n const t = JSON.parse(readFileSync(join(targetDir, \".project.json\"), \"utf8\"))\n ?.ticket_provider?.type;\n return t === \"plane\" || t === \"trello\" ? t : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * First step of the hermes-agent recipe.\n *\n * A Hermes agent is, by design, always a single PM per repo named `<repo>-pm`\n * (see the unified single-PM fleet model). There is therefore nothing to\n * choose: repo, role, board, purpose, tone, and model all have one correct\n * default. This command applies those defaults unconditionally and \u2014 in\n * interactive mode \u2014 asks exactly ONE question: whether to wire the Telegram\n * bot now. The compatibility `--email` flag is rejected by the next effect-free\n * validation step because the pinned template has no email provisioner.\n *\n * Any field pre-supplied via a CLI flag (or by the MCP layer) is preserved;\n * we only fill in what's missing. Downstream commands read the mutated context.\n */\nexport class PromptForAgentConfig extends Command {\n async invoke(): Promise<InvokeResult> {\n const ctx = this.context as HermesAgentContext;\n\n // Default target_repo from the current working dir. Lowercase so the value\n // is a valid Hermes profile name, Telegram handle prefix, and systemd unit\n // slug \u2014 all of which reject uppercase.\n const defaultRepo = basename(ctx.targetDir).toLowerCase();\n\n // --- Defaults for everything (the PM-only, one-agent-per-repo model) ---\n ctx.targetRepo = (ctx.targetRepo ?? defaultRepo).toLowerCase();\n ctx.role ??= \"pm\"; // PM-only fleet: no other roles are offered.\n ctx.agentPurpose ??= `${ctx.role} agent for ${ctx.targetRepo}`;\n ctx.soulTone ??= \"direct\";\n ctx.modelProvider ??= \"\"; // inherit shared default profile\n ctx.modelName ??= \"\"; // inherit shared default profile\n ctx.modelBaseUrl ??= \"\"; // inherit shared default profile\n ctx.modelApiMode ??= \"\"; // inherit shared default profile\n ctx.modelKeyEnv ??= \"\"; // no profile-scoped credential override\n // Board provider: honor an explicit flag, else inherit the repo's existing\n // .project.json provider, else plane.\n ctx.ticketProvider ??= detectTicketProvider(ctx.targetDir) ?? \"plane\";\n // The default remains skipped; explicit --email is rejected before effects.\n ctx.skipEmail ??= true;\n\n ctx.agentId = deriveAgentId(ctx.targetRepo!, ctx.role!);\n ctx.profileName = deriveProfileName(ctx.targetRepo!, ctx.role!);\n\n if (ctx.quiet && !ctx.yes) {\n return {\n success: false,\n outcome: \"failed\",\n message: \"Quiet Hermes execution must also set yes=true; interactive prompts are unavailable to structured callers\",\n };\n }\n\n // --- Non-interactive: also skip the one human-input step (Telegram) ---\n if (ctx.yes) {\n ctx.skipTelegram ??= true;\n return {\n success: true,\n message: this.formatMessage(\n `\u2713 Non-interactive mode \u2014 using defaults (repo=${ctx.targetRepo}, role=${ctx.role}, profile=${ctx.profileName})`\n ),\n };\n }\n\n // --- Interactive: the ONE and ONLY question is the Telegram wire-up ---\n p.intro(\"\u2695 hermes-agent \u00B7 provision the PM agent for this repo\");\n p.log.info(\n `agent ${ctx.agentId} \u00B7 board ${ctx.ticketProvider} \u00B7 tone ${ctx.soulTone}`\n );\n\n if (ctx.skipTelegram === undefined) {\n const botHandle = `${ctx.targetRepo!.replace(/-/g, \"_\")}_${ctx.role}_bot`;\n const wire = await p.confirm({\n message: `Wire up the Telegram bot (@${botHandle}) now?`,\n initialValue: true,\n });\n if (p.isCancel(wire)) return this.cancelled();\n ctx.skipTelegram = !wire;\n }\n\n return {\n success: true,\n message: this.formatMessage(\n `\u2713 Collected agent config (agent_id=${ctx.agentId}, profile=${ctx.profileName})`\n ),\n };\n }\n\n private cancelled(): InvokeResult {\n p.cancel(\"Aborted by user.\");\n return { success: false, message: \"Aborted by user.\" };\n }\n}\n", "import type { CommandContext } from \"../Command\";\nimport type { TrustedCopierIdentity } from \"../../lifecycle/preflight\";\n\n/**\n * Context for the hermes-agent recipe. Extends the base CommandContext with\n * the answers collected by PromptForAgentConfig (or supplied via CLI flags).\n *\n * Convention: PromptForAgentConfig mutates `context` in place with these\n * fields populated before downstream commands run.\n */\nexport interface HermesAgentContext extends CommandContext {\n // --- collected/provided ---\n targetRepo?: string; // basename($PWD) by default\n role?: string; // \"pm\" by default\n agentPurpose?: string;\n soulTone?: \"direct\" | \"playful\" | \"formal\" | \"terse\";\n modelProvider?: string;\n modelName?: string;\n modelBaseUrl?: string;\n modelApiMode?: string;\n modelKeyEnv?: string;\n ticketProvider?: TicketProvider; // \"plane\" by default \u2014 board lives here\n\n // --- behavior toggles ---\n yes?: boolean; // non-interactive; accept all defaults\n local?: boolean; // local-only: defer Plane/systemd; runtime remains role-local\n live?: boolean; // explicit external-effect authority (still requires per-effect opt-ins)\n forceConfig?: boolean; // add missing pinned-schema fields to the host config\n skipTelegram?: boolean;\n skipEmail?: boolean;\n skipSystemd?: boolean;\n skipBloodbank?: boolean;\n skipPlane?: boolean;\n\n // MCP apply paths render and prove local lifecycle state first. The selected\n // external scripts run only from the owning recipe/project transaction after\n // that eligibility audit, then a read-only postcondition audit verifies the\n // result. CLI callers that omit this block retain their existing sequencing.\n deferredExternalEffects?: {\n ticketBoard: boolean;\n systemd: boolean;\n owner: \"hermes\" | \"project\";\n };\n // MCP provisioning defers host-global config/profile/fleet writes until the\n // freshly rendered repo-local projection has passed its structural\n // eligibility gate. This private flag is set only while that deferred host\n // phase is actually being applied.\n applyingDeferredHostEffects?: boolean;\n // MCP apply resolves and attests Copier before any mutation. The render\n // command revalidates this identity and invokes its canonical absolute path;\n // it must never resolve PATH a second time.\n trustedCopier?: TrustedCopierIdentity;\n\n // --- derived after copier runs ---\n agentId?: string; // <targetRepo>-<role>\n profileName?: string; // named Hermes profile, conventionally <targetRepo>-<role>\n roleDir?: string; // <projectRoot>/agents/hermes/<role>\n runtimeRepo?: string; // legacy compatibility metadata; runtime is role-local\n\n // --- final presentation (set only by HermesAgentRecipe) ---\n deploymentOutcome?: \"planned\" | \"verified\" | \"verified-deferred\" | \"failed\";\n deploymentDeferrals?: string[];\n deploymentPostconditions?: string[];\n}\n\nexport const HERMES_AGENT_TEMPLATE = \"gh:delorenj/hermes-agent-template\";\n\nexport const SOUL_TONES = [\"direct\", \"playful\", \"formal\", \"terse\"] as const;\n\n// NOTE: the fleet is PM-only (one `<repo>-pm` agent per repo), so the recipe no\n// longer offers a role selection. `role` defaults to \"pm\" and is overridable\n// only via the `--role` flag / MCP input for programmatic/edge use. The copier\n// template still accepts a `role` value, so other roles remain reachable\n// out-of-band \u2014 they're just not part of the interactive flow.\n\nexport type TicketProvider = \"plane\" | \"trello\";\n\nexport const TICKET_PROVIDERS = [\n { value: \"plane\", label: \"Plane\", hint: \"self-hosted at plane.delo.sh (default)\" },\n { value: \"trello\", label: \"Trello\", hint: \"board = project\" },\n] as const;\n\nexport function deriveAgentId(repo: string, role: string): string {\n return `${repo}-${role}`.toLowerCase();\n}\n\nexport function deriveProfileName(repo: string, role: string): string {\n return deriveAgentId(repo, role);\n}\n", "import { lstatSync, readdirSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { Command, type InvokeResult } from \"../Command\";\nimport { normalizeAgentRole, resolveContainedPath } from \"../../project/index\";\nimport type { HermesAgentContext } from \"./types\";\n\nexport const EMAIL_UNSUPPORTED_MESSAGE =\n \"Email provisioning is unavailable: the pinned Hermes template has no supported email provisioner. Omit --email; no files or external state were changed.\";\n\nconst HARMLESS_ROLE_PLACEHOLDERS = new Set([\".gitkeep\", \".DS_Store\", \"Thumbs.db\"]);\n\n/**\n * Find pre-existing role content that requires explicit overwrite consent.\n * Empty directories and inert, single-link regular placeholder/OS metadata\n * files are harmless. Ignored runtime state, links, special files, and every\n * template-shaped file are not.\n */\nexport function existingRoleDirectoryBlockers(roleDir: string): string[] {\n let root;\n try {\n root = lstatSync(roleDir);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw error;\n }\n if (!root.isDirectory() || root.isSymbolicLink()) return [\"<target is not a real directory>\"];\n\n const blockers: string[] = [];\n const visit = (directory: string): void => {\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n const path = join(directory, entry.name);\n // Do not trust a placeholder-looking name or Dirent type: lstat the leaf\n // without following it so sockets/FIFOs/devices, symlinks, and hardlinks\n // can never be treated as inert metadata.\n const stats = lstatSync(path);\n if (stats.isDirectory() && !stats.isSymbolicLink()) {\n visit(path);\n } else if (\n !HARMLESS_ROLE_PLACEHOLDERS.has(entry.name) ||\n !stats.isFile() ||\n stats.isSymbolicLink() ||\n stats.nlink !== 1\n ) {\n blockers.push(relative(roleDir, path));\n }\n }\n };\n visit(roleDir);\n return blockers.sort();\n}\n\nexport function existingRoleRefusal(roleDir: string): string | undefined {\n const blockers = existingRoleDirectoryBlockers(roleDir);\n if (!blockers.length) return undefined;\n const sample = blockers.slice(0, 3).join(\", \");\n const remainder = blockers.length > 3 ? ` and ${blockers.length - 3} more` : \"\";\n return `Hermes target directory is not empty at ${roleDir} (found ${sample}${remainder}); non-interactive mode will not render into it. Re-run with --force to re-render explicitly.`;\n}\n\n/**\n * Effect-free CLI/recipe option validation.\n *\n * This command deliberately runs before host config bootstrap or Copier. Flags\n * that cannot be honored must fail without leaving a half-started deployment.\n */\nexport class ValidateHermesOptions extends Command {\n async invoke(): Promise<InvokeResult> {\n const ctx = this.context as HermesAgentContext;\n\n if (ctx.skipEmail === false) {\n return { success: false, outcome: \"failed\", message: EMAIL_UNSUPPORTED_MESSAGE };\n }\n\n const role = normalizeAgentRole(ctx.role ?? \"pm\");\n const roleDir = resolveContainedPath(\n ctx.targetDir,\n join(ctx.targetDir, \"agents\", \"hermes\", role),\n \"Hermes role directory\",\n );\n const refusal = (ctx.yes || ctx.quiet) && !ctx.force ? existingRoleRefusal(roleDir) : undefined;\n if (refusal) {\n return {\n success: false,\n outcome: \"failed\",\n message: refusal,\n };\n }\n\n return { success: true, outcome: \"unchanged\", message: \"\" };\n }\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { homedir } from \"node:os\";\nimport { join, dirname, relative } from \"node:path\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport * as p from \"@clack/prompts\";\nimport YAML from \"yaml\";\nimport { Command, type InvokeResult } from \"../Command\";\nimport { HERMES_AGENT_TEMPLATE, deriveAgentId, deriveProfileName, type HermesAgentContext } from \"./types\";\nimport { normalizeAgentRole, resolveContainedPath } from \"../../project/index\";\nimport { verifyTrustedCopierIdentity } from \"../../lifecycle/preflight\";\nimport { existingRoleRefusal } from \"./ValidateHermesOptions\";\n\nconst TICKET_PROVIDER_CREDENTIAL_KEYS = new Set([\n \"PLANE_API_KEY\",\n \"TRELLO_KEY\",\n \"TRELLO_TOKEN\",\n \"LINEAR_API_KEY\",\n]);\n\nconst INTERACTIVE_CHANNEL_CREDENTIAL_KEYS = new Set([\n \"TELEGRAM_BOT_TOKEN\",\n \"SLACK_BOT_TOKEN\",\n \"SLACK_APP_TOKEN\",\n \"CF_EMAIL_ROUTING_TOKEN\",\n]);\n\nexport function scrubTicketProviderCredentials(env: NodeJS.ProcessEnv): void {\n for (const key of Object.keys(env)) {\n if (TICKET_PROVIDER_CREDENTIAL_KEYS.has(key) || /^PLANE_[A-Z0-9_]+_API_KEY$/.test(key)) {\n delete env[key];\n }\n }\n}\n\nexport function scrubInteractiveChannelCredentials(env: NodeJS.ProcessEnv): void {\n for (const key of INTERACTIVE_CHANNEL_CREDENTIAL_KEYS) delete env[key];\n // MCP has no positive Slack grant. Remove ambient opt-in switches as well as\n // credentials so the non-interactive child cannot be armed indirectly.\n delete env.ENABLE_SLACK;\n delete env.WIRE_SLACK;\n}\n\nfunction registerRenderedAgent(ctx: HermesAgentContext, roleDir: string, role: string): void {\n const manifestPath = join(ctx.targetDir, \".project.json\");\n if (!existsSync(manifestPath) || !ctx.targetRepo) return;\n\n const current = readFileSync(manifestPath, \"utf8\");\n const parsed = JSON.parse(current) as unknown;\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(`${manifestPath} must contain a JSON object`);\n }\n const manifest = parsed as Record<string, unknown>;\n const rawAgents = manifest.agents;\n if (rawAgents !== undefined && (!rawAgents || typeof rawAgents !== \"object\" || Array.isArray(rawAgents))) {\n throw new Error(`${manifestPath} agents must contain a JSON object`);\n }\n const agents = (rawAgents ?? {}) as Record<string, unknown>;\n const agentId = ctx.agentId ?? deriveAgentId(ctx.targetRepo, role);\n Object.defineProperty(agents, agentId, {\n value: {\n role,\n role_dir: relative(ctx.targetDir, roleDir),\n provisioning_state: \"provisioned\",\n },\n configurable: true,\n enumerable: true,\n writable: true,\n });\n manifest.agents = agents;\n const next = `${JSON.stringify(manifest, null, 2)}\\n`;\n if (next !== current) writeFileSync(manifestPath, next, \"utf8\");\n}\n\n/**\n * Resolve a vendored copier template that ships with pjangler as a git\n * submodule under templates/<name>/. Walks up from this module's directory so\n * it works both when run from source (src/commands/hermes/) and from a repo\n * checkout. Returns undefined when not found (e.g. a bundled single-file\n * install), letting callers fall back to ~/code or the published gh: template.\n */\nfunction resolveVendoredTemplate(name: string): string | undefined {\n let dir: string;\n try {\n dir = dirname(fileURLToPath(import.meta.url));\n } catch {\n return undefined;\n }\n for (let i = 0; i < 8; i++) {\n const candidate = join(dir, \"templates\", name);\n if (existsSync(join(candidate, \"copier.yml\"))) return candidate;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return undefined;\n}\n\n/**\n * Invokes Copier against the pinned vendored template (with explicit fallbacks)\n * and the collected --data flags. Telegram and email steps are always skipped\n * in the template process; the recipe handles Telegram afterward and rejects\n * unsupported email requests before reaching this command.\n *\n * Honors dryRun: prints what would run, doesn't execute copier.\n */\nexport class RunCopierTemplate extends Command {\n async invoke(): Promise<InvokeResult> {\n const ctx = this.context as HermesAgentContext;\n const {\n targetRepo,\n role,\n agentPurpose,\n soulTone,\n modelProvider,\n modelName,\n modelBaseUrl,\n modelApiMode,\n modelKeyEnv,\n } = ctx;\n const ticketProvider = ctx.ticketProvider ?? \"plane\";\n const profileName =\n ctx.profileName ?? (targetRepo && role ? deriveProfileName(targetRepo, role) : undefined);\n\n if (!targetRepo || !role) {\n return {\n success: false,\n message: \"PromptForAgentConfig must run before RunCopierTemplate (targetRepo/role unset)\",\n };\n }\n\n const safeRole = normalizeAgentRole(role);\n ctx.role = safeRole;\n const roleDir = resolveContainedPath(\n ctx.targetDir,\n join(ctx.targetDir, \"agents\", \"hermes\", safeRole),\n \"Hermes role directory\",\n );\n ctx.roleDir = roleDir;\n const nonInteractiveRefusal = (ctx.yes || ctx.quiet) && !ctx.force\n ? existingRoleRefusal(roleDir)\n : undefined;\n if (nonInteractiveRefusal) {\n return { success: false, outcome: \"failed\", message: nonInteractiveRefusal };\n }\n const trustedCopierRequired = Boolean(ctx.deferredExternalEffects && !ctx.dryRun);\n if (trustedCopierRequired && !ctx.trustedCopier) {\n return {\n success: false,\n outcome: \"failed\",\n message: \"MCP Hermes apply requires a preflight-attested Copier identity\",\n };\n }\n // Interactive CLI callers retain their historical PATH behavior. MCP\n // apply has an identity and therefore must not execute `which` or resolve\n // PATH again after the handler's read-only preflight.\n if (!ctx.trustedCopier) {\n const which = spawnSync(\"which\", [\"copier\"], { encoding: \"utf8\" });\n if (which.status !== 0) {\n return {\n success: false,\n outcome: \"failed\",\n message:\n \"\u2717 copier not found on PATH. Install with: `uv tool install copier` or `pip install copier`\",\n };\n }\n }\n\n // Idempotency: non-interactive mode never turns consent to defaults into\n // consent to overwrite an existing role. ValidateHermesOptions normally\n // rejects this before config bootstrap; retain the guard here for direct\n // command callers and only prompt interactive callers.\n if (existsSync(join(roleDir, \"role.yaml\")) && !ctx.force) {\n if (!ctx.yes && !ctx.quiet) {\n const proceed = await p.confirm({\n message: `${safeRole}/role.yaml already exists \u2014 re-render with --overwrite?`,\n initialValue: false,\n });\n if (p.isCancel(proceed) || !proceed) {\n return {\n success: false,\n outcome: \"cancelled\",\n message: `Skipped: ${roleDir} already provisioned (use --force to re-render)`,\n };\n }\n ctx.force = true;\n }\n }\n\n // Set every lifecycle gate explicitly so template subprocess behavior is\n // independent of inherited operator environment.\n const env: NodeJS.ProcessEnv = {\n ...process.env,\n SKIP_TELEGRAM: \"1\",\n SKIP_EMAIL: \"1\",\n SKIP_SLACK: ctx.deferredExternalEffects ? \"1\" : \"0\",\n // Fresh project targets do not have their own .git directory until the\n // project transaction's final phase. Pin scripts to the caller-resolved\n // root so they can never climb into an enclosing checkout.\n PJANGLER_PROJECT_ROOT: ctx.targetDir,\n // Config, fleet env/profile, and registry are host-global state. MCP\n // renders repo-local files first and executes those scripts only after a\n // structural lifecycle gate has accepted the render.\n SKIP_HOST_STATE: ctx.deferredExternalEffects ? \"1\" : \"0\",\n // The legacy script/env name now owns only ignored role-local runtime\n // setup. Structured transactions defer it until rendered eligibility;\n // ordinary CLI deploys always run it and no flag can create a remote repo.\n SKIP_RUNTIME_REPO: ctx.deferredExternalEffects ? \"1\" : \"0\",\n SKIP_PLANE: ctx.deferredExternalEffects ? \"1\" : ctx.skipPlane ? \"1\" : \"0\",\n SKIP_BLOODBANK: \"1\",\n SKIP_SYSTEMD: ctx.deferredExternalEffects ? \"1\" : ctx.skipSystemd ? \"1\" : \"0\",\n };\n if (ctx.deferredExternalEffects) scrubInteractiveChannelCredentials(env);\n if (ctx.deferredExternalEffects || ctx.skipPlane) scrubTicketProviderCredentials(env);\n if (ctx.trustedCopier) {\n // The attested UV interpreter must resolve packages from its own venv;\n // ambient Python path injection would otherwise bypass package hashes.\n delete env.PYTHONHOME;\n delete env.PYTHONPATH;\n env.PYTHONNOUSERSITE = \"1\";\n env.PYTHONSAFEPATH = \"1\";\n }\n\n // Prefer a local template checkout (if present) so fixes propagate\n // immediately without waiting for a GitHub push. Resolve against $HOME so\n // this works on any operator's machine (e.g. a friend's Mac), not just the\n // box this was authored on. PJANGLER_HERMES_TEMPLATE overrides; otherwise\n // fall back to the published gh: template.\n // Resolution order: explicit env override \u2192 vendored submodule (the\n // version-locked default) \u2192 a ~/code dev checkout \u2192 the published gh:\n // template. PJANGLER_HERMES_TEMPLATE stays the escape hatch for pointing at\n // a live ~/code checkout during template development.\n const LOCAL_TEMPLATE = join(homedir(), \"code\", \"hermes-agent-template\");\n const vendored = resolveVendoredTemplate(\"hermes-agent\");\n const templateSrc =\n process.env.PJANGLER_HERMES_TEMPLATE ||\n vendored ||\n (existsSync(join(LOCAL_TEMPLATE, \"copier.yml\")) ? LOCAL_TEMPLATE : HERMES_AGENT_TEMPLATE);\n\n const args = [\n \"copy\",\n templateSrc,\n roleDir,\n \"--data\", `target_repo=${targetRepo}`,\n \"--data\", `role=${safeRole}`,\n \"--data\", `agent_purpose=${agentPurpose ?? \"\"}`,\n \"--data\", `model_provider=${modelProvider ?? \"\"}`,\n \"--data\", `model_name=${modelName ?? \"\"}`,\n \"--data\", `model_base_url=${modelBaseUrl ?? \"\"}`,\n \"--data\", `model_api_mode=${modelApiMode ?? \"\"}`,\n \"--data\", `model_key_env=${modelKeyEnv ?? \"\"}`,\n \"--data\", `profile_name=${profileName ?? \"\"}`,\n \"--data\", `soul_tone=${soulTone ?? \"direct\"}`,\n \"--data\", `ticket_provider=${ticketProvider}`,\n \"--trust\",\n \"--vcs-ref=HEAD\",\n ];\n if (ctx.yes || ctx.quiet) args.push(\"--defaults\");\n if (ctx.force) args.push(\"--overwrite\");\n\n if (ctx.dryRun) {\n return {\n success: true,\n outcome: \"planned\",\n filePath: roleDir,\n message: this.formatMessage(`Would run: ${ctx.trustedCopier?.executable ?? \"copier\"} ${args.join(\" \")}`),\n };\n }\n\n // Revalidate at the last effect-free boundary. A launcher, interpreter,\n // receipt, RECORD, metadata, or package replacement after MCP preflight is\n // rejected before mkdir, config, provider, systemd, or any subprocess.\n if (ctx.trustedCopier) {\n const verified = verifyTrustedCopierIdentity(ctx.trustedCopier);\n if (!verified.ok) {\n return {\n success: false,\n outcome: \"failed\",\n message: `Copier provenance revalidation failed: ${verified.error ?? \"unknown identity failure\"}`,\n };\n }\n }\n\n // Ensure agents/hermes/ parent exists so copier doesn't have to create it\n // (copier handles this fine, but creating it ourselves lets us catch\n // permission issues earlier).\n mkdirSync(join(ctx.targetDir, \"agents\", \"hermes\"), { recursive: true });\n\n const spinner = ctx.quiet ? undefined : p.spinner();\n spinner?.start(`Running copier copy (target: agents/hermes/${safeRole})`);\n const copierExecutable = ctx.trustedCopier?.executable ?? \"copier\";\n const result = spawnSync(copierExecutable, args, ctx.quiet\n ? { encoding: \"utf8\", env, cwd: ctx.targetDir }\n : { stdio: \"inherit\", env, cwd: ctx.targetDir });\n spinner?.stop(result.status === 0 ? \"\u2713 copier run complete\" : \"\u2717 copier failed\");\n\n if (result.status !== 0) {\n return {\n success: false,\n outcome: \"failed\",\n message: `copier exited with status ${result.status}.${ctx.quiet && String(result.stderr ?? \"\").trim() ? ` ${String(result.stderr).trim()}` : \" Check the output above; re-run with the same flags after fixing.\"}`,\n };\n }\n\n const roleManifest = join(roleDir, \"role.yaml\");\n try {\n const current = readFileSync(roleManifest, \"utf8\");\n const document = YAML.parseDocument(current);\n if (document.errors.length) throw document.errors[0];\n document.setIn([\"deployment\", \"local_only\"], ctx.deferredExternalEffects ? true : Boolean(ctx.local));\n document.setIn([\"deployment\", \"systemd\"], ctx.deferredExternalEffects ? \"deferred\" : ctx.skipSystemd ? \"deferred\" : \"required\");\n const next = String(document);\n if (next !== current) writeFileSync(roleManifest, next, \"utf8\");\n registerRenderedAgent(ctx, roleDir, safeRole);\n } catch (error) {\n return {\n success: false,\n outcome: \"failed\",\n message: `Failed to record Hermes deployment mode in ${roleManifest}: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n\n return {\n success: true,\n outcome: \"changed\",\n message: `Rendered Hermes role at ${roleDir}; lifecycle postconditions are pending`,\n };\n }\n}\n", "import { existsSync, readFileSync, writeFileSync, readdirSync } from \"fs\";\nimport { join } from \"path\";\nimport { spawnSync } from \"node:child_process\";\nimport { Command, type InvokeResult } from \"../Command\";\n\nfunction sectionHasPath(section: string, targetPath: string): boolean {\n return section\n .split(/\\r?\\n/)\n .some((line) => /^\\s*path\\s*=/.test(line) && line.replace(/^\\s*path\\s*=\\s*/, \"\").trim() === targetPath);\n}\n\nfunction removeSubmodulePath(content: string, targetPath: string): string {\n return content\n .replace(/^\\[submodule \"[^\"\\n]+\"\\][\\s\\S]*?(?=^\\[submodule \"|(?![\\s\\S]))/gm, (section) =>\n sectionHasPath(section, targetPath) ? \"\" : section)\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n}\n\nexport class UntrackHermesRuntimes extends Command {\n async invoke(): Promise<InvokeResult> {\n const targetDir = this.context.targetDir;\n const rolesDir = join(targetDir, \"agents\", \"hermes\");\n if (!existsSync(rolesDir)) {\n return {\n success: true,\n message: \"No Hermes agents found (no agents/hermes directory).\",\n };\n }\n\n const roles = readdirSync(rolesDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name);\n\n if (roles.length === 0) {\n return {\n success: true,\n message: \"No Hermes agents found.\",\n };\n }\n\n let modifiedAny = false;\n const details: string[] = [];\n\n for (const role of roles) {\n const roleDir = join(\"agents\", \"hermes\", role);\n const runtimePath = join(roleDir, \"runtime\");\n const gitignorePath = join(roleDir, \".gitignore\");\n const gitmodulesPath = join(targetDir, \".gitmodules\");\n\n // 1. Check if runtime is tracked in git\n let isTracked = false;\n const lsResult = spawnSync(\"git\", [\"ls-files\", \"--stage\", \"--\", runtimePath], {\n cwd: targetDir,\n encoding: \"utf8\",\n });\n if (lsResult.status !== 0) {\n return {\n success: false,\n message: `\u2717 Failed to inspect runtime index at ${runtimePath}: ${lsResult.stderr.trim() || `exit ${lsResult.status}`}`,\n };\n }\n if (lsResult.status === 0 && lsResult.stdout.trim().length > 0) {\n isTracked = true;\n }\n\n let hasStaleMapping = false;\n let gitmodulesContent = \"\";\n if (existsSync(gitmodulesPath)) {\n gitmodulesContent = readFileSync(gitmodulesPath, \"utf8\");\n const sections = gitmodulesContent.match(/^\\[submodule \"[^\"\\n]+\"\\][\\s\\S]*?(?=^\\[submodule \"|(?![\\s\\S]))/gm) ?? [];\n hasStaleMapping = sections.some((section) => sectionHasPath(section, runtimePath));\n }\n\n // 2. Check if .gitignore ignores runtime/\n let isIgnored = false;\n const fullGitignorePath = join(targetDir, gitignorePath);\n if (existsSync(fullGitignorePath)) {\n const content = readFileSync(fullGitignorePath, \"utf8\");\n const lines = content.split(/\\r?\\n/).map((line) => line.trim());\n isIgnored = lines.includes(\"runtime/\") || lines.includes(\"runtime\");\n }\n\n if (isTracked || hasStaleMapping || !isIgnored) {\n modifiedAny = true;\n\n if (isTracked) {\n details.push(`untrack agents/hermes/${role}/runtime`);\n if (!this.context.dryRun) {\n const rmResult = spawnSync(\"git\", [\"rm\", \"--cached\", \"-r\", \"-f\", \"--\", runtimePath], {\n cwd: targetDir,\n encoding: \"utf8\",\n });\n if (rmResult.status !== 0) {\n return {\n success: false,\n message: `\u2717 Failed to untrack ${runtimePath}: ${rmResult.stderr.trim() || `exit ${rmResult.status}`}`,\n };\n }\n const verifyResult = spawnSync(\"git\", [\"ls-files\", \"--stage\", \"--\", runtimePath], {\n cwd: targetDir,\n encoding: \"utf8\",\n });\n if (verifyResult.status !== 0 || verifyResult.stdout.trim()) {\n return {\n success: false,\n message: verifyResult.status !== 0\n ? `\u2717 Failed to verify untracked runtime ${runtimePath}: ${verifyResult.stderr.trim() || `exit ${verifyResult.status}`}`\n : `\u2717 Runtime remains tracked after index-only removal: ${runtimePath}`,\n };\n }\n }\n }\n\n if (hasStaleMapping) {\n details.push(`remove stale .gitmodules mapping for ${runtimePath}`);\n if (!this.context.dryRun) {\n const next = removeSubmodulePath(gitmodulesContent, runtimePath);\n writeFileSync(gitmodulesPath, next ? `${next}\\n` : \"\", \"utf8\");\n }\n }\n\n if (!isIgnored) {\n details.push(`ignore runtime/ in agents/hermes/${role}/.gitignore`);\n if (!this.context.dryRun) {\n let content = \"\";\n if (existsSync(fullGitignorePath)) {\n content = readFileSync(fullGitignorePath, \"utf8\");\n }\n if (content && !content.endsWith(\"\\n\")) {\n content += \"\\n\";\n }\n content += \"runtime/\\n\";\n writeFileSync(fullGitignorePath, content, \"utf8\");\n }\n }\n }\n }\n\n if (!modifiedAny) {\n return {\n success: true,\n message: \"\u2705 All Hermes agent runtimes are already untracked and gitignored.\",\n };\n }\n\n const actionText = this.context.dryRun ? \"Would make\" : \"Made\";\n return {\n success: true,\n message: `${actionText} Hermes agent runtimes untracked and gitignored:\\n${details.map(d => ` - ${d}`).join(\"\\n\")}`,\n };\n }\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { join } from \"node:path\";\nimport { existsSync, unlinkSync } from \"node:fs\";\nimport * as p from \"@clack/prompts\";\nimport { Command, type InvokeResult } from \"../Command\";\nimport type { HermesAgentContext } from \"./types\";\n\n/**\n * BotFather token wire-up for a per-(repo, role) Hermes bot.\n *\n * Token resolution order:\n * 1. $TELEGRAM_BOT_TOKEN\n * 2. op://DeLoSecrets/<vaultTitle>/token\n * 3. BotFather walkthrough + clack secret prompt, then offer to persist\n * back to 1Password so future runs skip the prompt entirely.\n *\n * The vault item is per-bot (Telegram-Hermes-<repo>-<role>) because each\n * bot has its own token \u2014 unlike WireEmail's shared CF account credential.\n */\nexport class WireTelegram extends Command {\n async invoke(): Promise<InvokeResult> {\n const ctx = this.context as HermesAgentContext;\n if (ctx.skipTelegram) {\n return { success: true, message: \"\u2192 Telegram wire-up skipped\" };\n }\n if (ctx.quiet) {\n return {\n success: false,\n outcome: \"failed\",\n message: \"Telegram wiring is interactive and unavailable during quiet/non-interactive Hermes execution\",\n };\n }\n if (ctx.dryRun) {\n return { success: true, message: this.formatMessage(\"Would run BotFather token capture\") };\n }\n\n const { targetRepo, role, roleDir } = ctx;\n if (!targetRepo || !role || !roleDir) {\n return { success: false, message: \"Cannot wire telegram: missing target_repo/role/roleDir\" };\n }\n\n const botHandle = `${targetRepo.toLowerCase().replace(/-/g, \"_\")}_${role.toLowerCase()}_bot`;\n const displayName = `${cap(targetRepo)} ${role.length <= 3 ? role.toUpperCase() : cap(role)}`;\n const vaultTitle = `Telegram-Hermes-${targetRepo.toLowerCase()}-${role.toLowerCase()}`;\n const vaultRef = `op://DeLoSecrets/${vaultTitle}/token`;\n\n let token = process.env.TELEGRAM_BOT_TOKEN;\n let source: \"env\" | \"op\" | \"prompt\" | null = token ? \"env\" : null;\n\n if (!token) {\n const tryOp = spawnSync(\"op\", [\"read\", vaultRef], { encoding: \"utf8\" });\n if (tryOp.status === 0) {\n token = tryOp.stdout.trim();\n source = \"op\";\n p.log.info(`\u2713 Telegram token loaded from ${vaultRef}`);\n }\n }\n\n if (!token) {\n p.log.step(\"BotFather steps\");\n p.log.info(\n [\n \" 1. Open Telegram, message @BotFather\",\n \" 2. /newbot\",\n ` 3. Display name: ${displayName}`,\n ` 4. Username: ${botHandle} (must end in _bot)`,\n \" 5. Copy the HTTP API token from the reply.\",\n \" 6. /setjoingroups Disable\",\n \" 7. /setprivacy Disable\",\n ].join(\"\\n\")\n );\n\n const tokenAnswer = await p.password({\n message: `Paste the bot token for @${botHandle}`,\n mask: \"\u2022\",\n validate: (v) => {\n const s = String(v ?? \"\").trim();\n if (!s) return \"required\";\n if (!/^[0-9]+:.+/.test(s)) return \"expected '<digits>:<secret>' shape\";\n },\n });\n if (p.isCancel(tokenAnswer)) {\n return { success: true, message: \"\u2192 Telegram skipped (no token). Re-run later.\" };\n }\n token = String(tokenAnswer).trim();\n source = \"prompt\";\n\n const persist = await p.confirm({\n message: `Save to ${vaultRef} for next time?`,\n initialValue: true,\n });\n if (!p.isCancel(persist) && persist) {\n const create = spawnSync(\n \"op\",\n [\n \"item\",\n \"create\",\n \"--category=API Credential\",\n \"--vault=DeLoSecrets\",\n `--title=${vaultTitle}`,\n `token=${token}`,\n `bot_handle=${botHandle}`,\n ],\n { stdio: \"inherit\" }\n );\n if (create.status !== 0) {\n p.log.warn(\"Could not store in 1Password \u2014 token is still set for this run.\");\n }\n }\n }\n\n const allowedAnswer = await p.text({\n message: \"Your Telegram user id (allow-list for this bot)\",\n placeholder: process.env.TELEGRAM_ALLOWED_USERS ?? \"\",\n initialValue: process.env.TELEGRAM_ALLOWED_USERS ?? \"\",\n validate: (v) =>\n /^[0-9](?:[0-9,]*[0-9])?$/.test(String(v).trim()) ? undefined : \"comma-separated numeric ids\",\n });\n if (p.isCancel(allowedAnswer)) {\n return { success: false, message: \"\u2717 Aborted; Telegram step deferred.\" };\n }\n\n const script = join(roleDir, \".scripts\", \"30-telegram.sh\");\n if (!existsSync(script)) {\n return {\n success: false,\n message: `\u2717 ${script} not found. Did Copier finish rendering the Hermes role?`,\n };\n }\n\n const marker = join(roleDir, \".scripts\", \".done-30-telegram\");\n if (existsSync(marker)) unlinkSync(marker);\n\n const spinner = p.spinner();\n spinner.start(\"Verifying token + wiring profile\");\n const result = spawnSync(\"bash\", [script], {\n stdio: \"inherit\",\n env: {\n ...process.env,\n // Interactive wiring is an explicit host-state operation: it writes the\n // profile. Set the gate rather than inheriting whatever a deferred MCP\n // render left in the environment, which would silently no-op this run.\n SKIP_HOST_STATE: \"0\",\n SKIP_TELEGRAM: \"0\",\n TELEGRAM_BOT_TOKEN: token,\n TELEGRAM_ALLOWED_USERS: String(allowedAnswer).trim(),\n },\n cwd: roleDir,\n });\n spinner.stop(result.status === 0 ? \"\u2713 Telegram wired\" : \"\u2717 Telegram step failed\");\n\n if (result.status !== 0) {\n return { success: false, message: \"Telegram wire-up failed. See output above.\" };\n }\n\n const sourceLabel = source === \"env\" ? \" (token: env)\" : source === \"op\" ? \" (token: op)\" : \"\";\n return { success: true, message: `\u2713 Telegram: @${botHandle} ready${sourceLabel}` };\n }\n}\n\nfunction cap(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n", "import { Command, type InvokeResult } from \"../Command\";\nimport type { HermesAgentContext } from \"./types\";\nimport { EMAIL_UNSUPPORTED_MESSAGE } from \"./ValidateHermesOptions\";\n\n/**\n * Compatibility guard for the retired `--email` surface.\n *\n * The pinned template exposes no email script or stable email provisioning\n * contract. Failing closed is safer than discovering that after Copier and\n * host provisioning have already mutated state. ValidateHermesOptions normally\n * catches this before all effects; this command is a defense-in-depth guard for\n * direct command callers.\n */\nexport class WireEmail extends Command {\n async invoke(): Promise<InvokeResult> {\n const ctx = this.context as HermesAgentContext;\n if (ctx.skipEmail !== false) {\n return { success: true, outcome: \"skipped\", message: \"\" };\n }\n return { success: false, outcome: \"failed\", message: EMAIL_UNSUPPORTED_MESSAGE };\n }\n}\n", "import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport YAML from \"yaml\";\nimport { Command, type InvokeResult } from \"../Command\";\nimport type { HermesAgentContext } from \"./types\";\n\ninterface DurableServiceState {\n gateway: string;\n heartbeat: string;\n}\n\nfunction readServiceState(roleDir: string | undefined): DurableServiceState {\n if (!roleDir || !existsSync(join(roleDir, \"role.yaml\"))) return { gateway: \"planned\", heartbeat: \"planned\" };\n try {\n const role = YAML.parse(readFileSync(join(roleDir, \"role.yaml\"), \"utf8\")) as {\n service_state?: { gateway?: unknown; heartbeat?: unknown };\n } | null;\n return {\n gateway: typeof role?.service_state?.gateway === \"string\" ? role.service_state.gateway : \"unknown\",\n heartbeat: typeof role?.service_state?.heartbeat === \"string\" ? role.service_state.heartbeat : \"unknown\",\n };\n } catch {\n return { gateway: \"unknown\", heartbeat: \"unknown\" };\n }\n}\n\n/** Render only claims established by the recipe's final postcondition phase. */\nexport function renderHermesSummary(ctx: HermesAgentContext): string {\n const outcome = ctx.deploymentOutcome ?? (ctx.dryRun ? \"planned\" : \"failed\");\n const service = readServiceState(ctx.roleDir);\n const deferrals = [...new Set(ctx.deploymentDeferrals ?? [])];\n const title = outcome === \"planned\"\n ? \"Hermes deployment plan (no changes applied)\"\n : outcome === \"verified-deferred\"\n ? \"Hermes deployment healthy with deferred capabilities\"\n : outcome === \"verified\"\n ? \"Hermes deployment verified\"\n : \"Hermes deployment not verified\";\n const lines = [\n title,\n `agent_id: ${ctx.agentId ?? \"planned\"}`,\n `role_dir: ${ctx.roleDir ?? join(ctx.targetDir, \"agents\", \"hermes\", ctx.role ?? \"pm\")}`,\n `runtime: local role runtime (${join(ctx.roleDir ?? join(ctx.targetDir, \"agents\", \"hermes\", ctx.role ?? \"pm\"), \"runtime\")})`,\n `heartbeat: ${service.heartbeat}`,\n `gateway: ${service.gateway}`,\n ];\n if (deferrals.length) lines.push(`deferred: ${deferrals.join(\", \")}`);\n for (const assertion of ctx.deploymentPostconditions ?? []) lines.push(`verified: ${assertion}`);\n if (outcome === \"planned\") lines.push(\"Apply by rerunning without --dry-run.\");\n return lines.join(\"\\n\");\n}\n\nexport class PrintHermesSummary extends Command {\n async invoke(): Promise<InvokeResult> {\n const ctx = this.context as HermesAgentContext;\n return { success: ctx.deploymentOutcome !== \"failed\", outcome: \"unchanged\", message: renderHermesSummary(ctx) };\n }\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport YAML from \"yaml\";\nimport { Command, type InvokeResult } from \"../Command\";\nimport type { HermesAgentContext } from \"./types\";\nimport { scrubInteractiveChannelCredentials, scrubTicketProviderCredentials } from \"./RunCopierTemplate\";\n\n/**\n * Execute explicitly granted Hermes external phases after local lifecycle\n * eligibility has passed. Output is always captured: this command is reached\n * only through structured MCP transactions, whose stdout belongs to JSON-RPC.\n */\nexport class ApplyDeferredExternalEffects extends Command {\n async invoke(): Promise<InvokeResult> {\n const ctx = this.context as HermesAgentContext;\n const selected = ctx.deferredExternalEffects;\n if (!selected || (!selected.ticketBoard && !selected.systemd)) {\n return { success: true, outcome: \"unchanged\", message: \"Hermes external effects not selected\" };\n }\n if (!ctx.roleDir) {\n return { success: false, outcome: \"failed\", message: \"Hermes roleDir is unavailable for deferred external effects\" };\n }\n\n const env: NodeJS.ProcessEnv = {\n ...process.env,\n PJANGLER_PROJECT_ROOT: ctx.targetDir,\n SKIP_HOST_STATE: \"0\",\n SKIP_TELEGRAM: \"1\",\n SKIP_EMAIL: \"1\",\n SKIP_SLACK: \"1\",\n SKIP_BLOODBANK: \"1\",\n // Role-local runtime is already converged by ApplyDeferredHostEffects.\n // External consent can never dispatch the retired GitHub runtime model.\n SKIP_RUNTIME_REPO: \"1\",\n SKIP_PLANE: selected.ticketBoard ? \"0\" : \"1\",\n SKIP_SYSTEMD: selected.systemd ? \"0\" : \"1\",\n };\n scrubInteractiveChannelCredentials(env);\n if (!selected.ticketBoard) scrubTicketProviderCredentials(env);\n\n const roleManifest = join(ctx.roleDir, \"role.yaml\");\n const scripts = [\n ...(selected.ticketBoard ? [\"42-ticket-provider.sh\"] : []),\n ...(selected.systemd ? [\"70-systemd.sh\"] : []),\n // Refresh fleet metadata after a board binding or systemd state\n // changes. 80-registry.sh is idempotent and performs no provider call.\n \"80-registry.sh\",\n ];\n const logs: string[] = [];\n for (const script of scripts) {\n const path = join(ctx.roleDir, \".scripts\", script);\n if (!existsSync(path)) {\n return { success: false, outcome: \"failed\", message: `Deferred Hermes script is missing: ${path}` };\n }\n const result = spawnSync(path, [], { cwd: ctx.roleDir, env, encoding: \"utf8\" });\n if (String(result.stdout ?? \"\").trim()) logs.push(String(result.stdout).trim());\n if (String(result.stderr ?? \"\").trim()) logs.push(String(result.stderr).trim());\n if (result.error || result.status !== 0) {\n const detail = result.error?.message ?? logs.at(-1) ?? `status ${result.status ?? \"unknown\"}`;\n return { success: false, outcome: \"failed\", message: `${script} failed: ${detail}` };\n }\n }\n\n // The local render deliberately records every external phase as deferred,\n // allowing lifecycle eligibility to be proved without probing systemd or\n // implying cloud authority. Persist the granted/applied deployment state\n // only after every selected effect has completed successfully; a failed\n // child must leave the durable manifest truthfully deferred.\n try {\n const current = readFileSync(roleManifest, \"utf8\");\n const document = YAML.parseDocument(current);\n if (document.errors.length) throw document.errors[0];\n document.setIn([\"deployment\", \"local_only\"], Boolean(ctx.local));\n document.setIn([\"deployment\", \"systemd\"], selected.systemd ? \"required\" : \"deferred\");\n const next = String(document);\n if (next !== current) writeFileSync(roleManifest, next, \"utf8\");\n } catch (error) {\n return {\n success: false,\n outcome: \"failed\",\n message: `Failed to record applied Hermes deployment metadata: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n return {\n success: true,\n outcome: \"changed\",\n message: `Applied deferred Hermes external effects: ${scripts.join(\", \")}${logs.length ? `\\n${logs.join(\"\\n\")}` : \"\"}`,\n };\n }\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { Command, type InvokeResult } from \"../Command\";\nimport { EnsureTemplateConfig } from \"./EnsureTemplateConfig\";\nimport { scrubInteractiveChannelCredentials, scrubTicketProviderCredentials } from \"./RunCopierTemplate\";\nimport type { HermesAgentContext } from \"./types\";\n\n/**\n * Apply host-global Hermes state only after the rendered repo projection has\n * passed its read-only lifecycle eligibility gate. Output is always captured:\n * this phase is used by structured MCP transactions whose stdout is JSON-RPC.\n */\nexport class ApplyDeferredHostEffects extends Command {\n async invoke(): Promise<InvokeResult> {\n const ctx = this.context as HermesAgentContext;\n if (!ctx.deferredExternalEffects) {\n return { success: true, outcome: \"unchanged\", message: \"Hermes host effects use template sequencing\" };\n }\n if (!ctx.roleDir) {\n return { success: false, outcome: \"failed\", message: \"Hermes roleDir is unavailable for deferred host effects\" };\n }\n\n let config: InvokeResult;\n ctx.applyingDeferredHostEffects = true;\n try {\n config = await new EnsureTemplateConfig(ctx).invoke();\n } finally {\n ctx.applyingDeferredHostEffects = false;\n }\n if (!config.success) return config;\n\n const env: NodeJS.ProcessEnv = {\n ...process.env,\n PJANGLER_PROJECT_ROOT: ctx.targetDir,\n SKIP_HOST_STATE: \"0\",\n SKIP_TELEGRAM: \"1\",\n SKIP_EMAIL: \"1\",\n SKIP_SLACK: \"1\",\n SKIP_BLOODBANK: \"1\",\n // The legacy name controls role-local runtime/profile convergence only.\n // It is a required host/local phase, never a GitHub repository effect.\n SKIP_RUNTIME_REPO: \"0\",\n SKIP_PLANE: \"1\",\n SKIP_SYSTEMD: \"1\",\n };\n // Config/profile/fleet setup never needs board credentials. Do not expose\n // ambient provider authority to these child processes even when a later,\n // separately gated provider phase was positively selected.\n scrubTicketProviderCredentials(env);\n scrubInteractiveChannelCredentials(env);\n\n const scripts = [\"01-config.sh\", \"05-fleet-env.sh\", \"10-hermes-profile.sh\", \"20-runtime-repo.sh\"];\n const logs: string[] = [];\n for (const script of scripts) {\n const path = join(ctx.roleDir, \".scripts\", script);\n if (!existsSync(path)) {\n return { success: false, outcome: \"failed\", message: `Deferred Hermes host script is missing: ${path}` };\n }\n const result = spawnSync(path, [], { cwd: ctx.roleDir, env, encoding: \"utf8\" });\n if (String(result.stdout ?? \"\").trim()) logs.push(String(result.stdout).trim());\n if (String(result.stderr ?? \"\").trim()) logs.push(String(result.stderr).trim());\n if (result.error || result.status !== 0) {\n const detail = result.error?.message ?? logs.at(-1) ?? `status ${result.status ?? \"unknown\"}`;\n return { success: false, outcome: \"failed\", message: `${script} failed: ${detail}` };\n }\n }\n return {\n success: true,\n outcome: \"changed\",\n message: `Applied deferred Hermes host effects: ${scripts.join(\", \")}${logs.length ? `\\n${logs.join(\"\\n\")}` : \"\"}`,\n };\n }\n}\n", "import { Recipe, mergeInitResults } from \"./Recipe\";\nimport { EnsureTemplateConfig } from \"../commands/hermes/EnsureTemplateConfig\";\nimport { PromptForAgentConfig } from \"../commands/hermes/PromptForAgentConfig\";\nimport { ValidateHermesOptions } from \"../commands/hermes/ValidateHermesOptions\";\nimport { RunCopierTemplate } from \"../commands/hermes/RunCopierTemplate\";\nimport { UntrackHermesRuntimes } from \"../commands/hermes/UntrackHermesRuntimes\";\nimport { WireTelegram } from \"../commands/hermes/WireTelegram\";\nimport { WireEmail } from \"../commands/hermes/WireEmail\";\nimport { PrintHermesSummary } from \"../commands/hermes/PrintHermesSummary\";\nimport { ApplyDeferredExternalEffects } from \"../commands/hermes/ApplyDeferredExternalEffects\";\nimport { ApplyDeferredHostEffects } from \"../commands/hermes/ApplyDeferredHostEffects\";\nimport type { HermesAgentContext } from \"../commands/hermes/types\";\nimport { createHermesChecks, createMiseChecks, createProjectChecks } from \"../parity/rules\";\nimport type { LifecycleContext, RecipeInitResult, RecipeMetadata, RecipePhaseOutcome, RecipePhaseStatus } from \"./types\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport YAML from \"yaml\";\nimport { changedTreePaths, snapshotTree } from \"../utils/tree-diff\";\nimport { preflightRenderedHermes } from \"../lifecycle/preflight\";\n\nfunction deploymentDeferrals(ctx: HermesAgentContext): string[] {\n const deferred: string[] = [];\n if (ctx.local || ctx.skipPlane) deferred.push(\"ticket-board provisioning\");\n if (ctx.local || ctx.skipSystemd) deferred.push(\"systemd service activation\");\n const projectManifest = join(ctx.targetDir, \".project.json\");\n if (!ctx.skipPlane && existsSync(projectManifest)) {\n try {\n const project = JSON.parse(readFileSync(projectManifest, \"utf8\")) as {\n ticket_provider?: { state?: unknown };\n };\n const state = project.ticket_provider?.state;\n if (typeof state === \"string\" && state !== \"linked\") deferred.push(`ticket board (${state})`);\n } catch {\n deferred.push(\"ticket board state unreadable\");\n }\n }\n const rolePath = ctx.roleDir ? join(ctx.roleDir, \"role.yaml\") : \"\";\n if (rolePath && existsSync(rolePath)) {\n try {\n const role = YAML.parse(readFileSync(rolePath, \"utf8\")) as {\n service_state?: { gateway?: unknown; heartbeat?: unknown };\n } | null;\n const gateway = role?.service_state?.gateway;\n const heartbeat = role?.service_state?.heartbeat;\n if (typeof gateway === \"string\" && gateway !== \"active\") deferred.push(`gateway (${gateway})`);\n if (typeof heartbeat === \"string\" && heartbeat !== \"active\") deferred.push(`heartbeat (${heartbeat})`);\n } catch {\n deferred.push(\"service state unreadable\");\n }\n } else if (!ctx.dryRun) {\n deferred.push(\"role service state unavailable\");\n }\n return [...new Set(deferred)];\n}\n\nasync function summaryResult(ctx: LifecycleContext): Promise<RecipeInitResult> {\n const summary = await new PrintHermesSummary(ctx).invoke();\n return {\n recipeId: \"hermes-agent\",\n ok: summary.success,\n dryRun: Boolean(ctx.dryRun),\n changedFiles: [],\n logs: summary.message ? [summary.message] : [],\n errors: summary.success ? [] : [summary.message || \"Hermes summary could not be rendered\"],\n phases: [{\n id: \"hermes.summary\",\n status: summary.success ? \"unchanged\" : \"failed\",\n changedFiles: [],\n message: summary.message || undefined,\n }],\n };\n}\n\n/**\n * Recipe that provisions a Hermes agent role into the current project repo.\n *\n * Chain (each command mutates the shared context):\n * 1. PromptForAgentConfig \u2014 collect/default effect-free inputs\n * 2. ValidateHermesOptions \u2014 reject unsupported or destructive modes\n * 3. EnsureTemplateConfig \u2014 bootstrap/merge the pinned host config schema\n * 4. RunCopierTemplate \u2014 render the pinned vendored Copier template\n * 5. UntrackHermesRuntimes \u2014 keep runtime state out of the repository\n * 6. WireTelegram \u2014 BotFather token capture (skippable)\n * 7. WireEmail \u2014 defense-in-depth unsupported-option guard\n *\n * PrintHermesSummary is deliberately not an ingredient. It runs only after\n * the final postcondition audit, so presentation can never outrun reality.\n *\n * We deliberately swallow the base Recipe's \"\u2713/\u26A0\uFE0F created file\" line \u2014 our\n * commands print their own rich status via @clack/prompts, and we don't want\n * doubled output.\n */\nexport class HermesAgentRecipe extends Recipe {\n readonly checks = createHermesChecks();\n readonly metadata: RecipeMetadata = {\n id: \"hermes-agent\",\n name: \"hermes-agent\",\n description: \"Add and reconcile a Hermes agent role\",\n dependencies: [],\n commands: [\n \"PromptForAgentConfig\",\n \"ValidateHermesOptions\",\n \"EnsureTemplateConfig\",\n \"RunCopierTemplate\",\n \"UntrackHermesRuntimes\",\n \"WireTelegram\",\n \"WireEmail\",\n \"PrintHermesSummary (postconditions only)\",\n ],\n publicRuleIds: this.checks.map((check) => check.id),\n };\n\n /** Hermes sequencing is fatal/cancel short-circuiting under registry init. */\n override async init(ctx: LifecycleContext, _input: unknown): Promise<RecipeInitResult> {\n const phases: RecipePhaseOutcome[] = [];\n const logs: string[] = [];\n const errors: string[] = [];\n const changedFiles: string[] = [];\n\n // Resolve constructors lazily at dispatch time. The bundled CLI also\n // imports EnsureTemplateConfig directly for `config bootstrap`; capturing\n // that binding while the singleton catalog is being evaluated would store\n // `undefined` before the command module finishes initializing.\n const ingredients = [\n PromptForAgentConfig,\n ValidateHermesOptions,\n EnsureTemplateConfig,\n RunCopierTemplate,\n UntrackHermesRuntimes,\n WireTelegram,\n WireEmail,\n ] as const;\n for (const [ingredientIndex, CommandClass] of ingredients.entries()) {\n if (typeof CommandClass !== \"function\") {\n throw new TypeError(`Hermes ingredient ${ingredientIndex} is not constructable`);\n }\n const before = ctx.dryRun ? undefined : snapshotTree(ctx.targetDir);\n const result = await new CommandClass(ctx).invoke();\n const observedChanges = before ? changedTreePaths(ctx.targetDir, before, snapshotTree(ctx.targetDir)) : [];\n let status: RecipePhaseStatus = result.outcome ?? (result.success\n ? (ctx.dryRun && result.filePath ? \"planned\" : result.filePath ? \"changed\" : \"unchanged\")\n : \"failed\");\n if (result.success && !ctx.dryRun && observedChanges.length) status = \"changed\";\n const declaredChanges = status === \"changed\" && result.filePath ? [resolve(ctx.targetDir, result.filePath)] : [];\n const actualChanges = [...new Set([...observedChanges, ...declaredChanges])].sort();\n phases.push({ id: CommandClass.name, status, changedFiles: actualChanges, message: result.message || undefined });\n changedFiles.push(...actualChanges);\n if (result.message) logs.push(result.message);\n if (status === \"failed\" || status === \"cancelled\") {\n errors.push(result.message || `${CommandClass.name} ${status}`);\n break;\n }\n\n // Copier's trusted, version-locked inputs were attested before launch.\n // Validate its repo-local projection before any deferred config/profile/\n // fleet effect runs, so a structural lifecycle failure cannot first be\n // discovered after host state has changed.\n if (!ctx.dryRun && CommandClass === RunCopierTemplate && (ctx as HermesAgentContext).deferredExternalEffects) {\n const hermesContext = ctx as HermesAgentContext;\n const eligibility = hermesContext.roleDir\n && hermesContext.targetRepo\n && hermesContext.role\n && hermesContext.agentId\n ? preflightRenderedHermes({\n pjanglerRoot: ctx.pjanglerRoot,\n targetDir: ctx.targetDir,\n roleDir: hermesContext.roleDir,\n targetRepo: hermesContext.targetRepo,\n role: hermesContext.role,\n agentId: hermesContext.agentId,\n })\n : { ok: false, error: \"Hermes render did not establish role identity\" };\n phases.push({\n id: \"hermes.rendered-eligibility\",\n status: eligibility.ok ? \"unchanged\" : \"failed\",\n changedFiles: [],\n message: eligibility.ok ? \"Rendered Hermes lifecycle eligibility passed\" : eligibility.error,\n });\n if (!eligibility.ok) {\n errors.push(`hermes.rendered-eligibility: ${eligibility.error ?? \"unknown eligibility failure\"}`);\n break;\n }\n\n const beforeHost = snapshotTree(ctx.targetDir);\n const host = await new ApplyDeferredHostEffects(ctx).invoke();\n const hostChanges = changedTreePaths(ctx.targetDir, beforeHost, snapshotTree(ctx.targetDir));\n phases.push({\n id: \"hermes.host-effects\",\n status: host.success ? (hostChanges.length ? \"changed\" : \"unchanged\") : \"failed\",\n changedFiles: host.success ? hostChanges : [],\n message: host.message || undefined,\n });\n changedFiles.push(...hostChanges);\n if (host.message) logs.push(host.message);\n if (!host.success) {\n errors.push(host.message || \"Deferred Hermes host effects failed\");\n break;\n }\n }\n }\n\n const commandResult: RecipeInitResult = {\n recipeId: this.metadata.id,\n ok: errors.length === 0,\n dryRun: Boolean(ctx.dryRun),\n changedFiles: [...new Set(changedFiles)].sort(),\n logs,\n errors,\n phases,\n };\n if (!commandResult.ok) return commandResult;\n const lifecycle = await this.initializeOwnedChecks(ctx);\n const localResult = mergeInitResults(this.metadata.id, Boolean(ctx.dryRun), [commandResult, lifecycle]);\n if (!localResult.ok) return localResult;\n\n const hermesContext = ctx as HermesAgentContext;\n if (ctx.dryRun) {\n hermesContext.deploymentOutcome = \"planned\";\n hermesContext.deploymentDeferrals = deploymentDeferrals(hermesContext);\n hermesContext.deploymentPostconditions = [\"dry-run made no repository or host changes\"];\n return mergeInitResults(this.metadata.id, true, [localResult, await summaryResult(ctx)]);\n }\n\n const selected = hermesContext.deferredExternalEffects;\n // The Project recipe owns external dispatch and the whole-project audit for\n // MCP project transactions. It is the only caller that returns before this\n // recipe's final direct-command presentation.\n if (selected?.owner === \"project\" || (ctx.quiet && !selected)) return localResult;\n\n let appliedResult = localResult;\n if (selected?.owner === \"hermes\" && (selected.ticketBoard || selected.systemd)) {\n const beforeExternal = snapshotTree(ctx.targetDir);\n const external = await new ApplyDeferredExternalEffects(ctx).invoke();\n const externalChanges = changedTreePaths(ctx.targetDir, beforeExternal, snapshotTree(ctx.targetDir));\n const externalResult: RecipeInitResult = {\n recipeId: this.metadata.id,\n ok: external.success,\n dryRun: false,\n changedFiles: externalChanges,\n logs: external.message ? [external.message] : [],\n errors: external.success ? [] : [external.message || \"Deferred Hermes external effects failed\"],\n phases: [{\n id: \"hermes.external-effects\",\n status: external.success ? \"changed\" : \"failed\",\n changedFiles: external.success ? externalChanges : [],\n message: external.message || undefined,\n }],\n };\n appliedResult = mergeInitResults(this.metadata.id, false, [localResult, externalResult]);\n if (!externalResult.ok) return appliedResult;\n }\n\n // Copier exit zero is not deployment success. Re-audit every Hermes-owned\n // invariant plus the two project contracts this command changes/depends on.\n const crossChecks = [\n ...createMiseChecks().filter((check) => check.id === \"mise.config-root\"),\n ...createProjectChecks().filter((check) => check.id === \"sot.project-json\"),\n ];\n const findings = [\n ...this.audit(ctx),\n ...crossChecks.map((check) => check.audit(ctx)),\n ].filter((finding) => finding.status !== \"pass\" && finding.status !== \"skip\");\n const verification: RecipeInitResult = {\n recipeId: this.metadata.id,\n ok: findings.length === 0,\n dryRun: false,\n changedFiles: [],\n logs: [],\n errors: findings.map((finding) => `${finding.id}: ${finding.summary}`),\n phases: [{\n id: \"hermes.postcondition-audit\",\n status: findings.length ? \"failed\" : \"unchanged\",\n changedFiles: [],\n message: findings.length ? \"Hermes postcondition audit failed\" : \"Hermes postcondition audit passed\",\n }],\n };\n const verifiedResult = mergeInitResults(this.metadata.id, false, [appliedResult, verification]);\n if (!verification.ok) {\n hermesContext.deploymentOutcome = \"failed\";\n return verifiedResult;\n }\n\n hermesContext.deploymentDeferrals = deploymentDeferrals(hermesContext);\n hermesContext.deploymentOutcome = hermesContext.deploymentDeferrals.length ? \"verified-deferred\" : \"verified\";\n hermesContext.deploymentPostconditions = [\n \"Hermes lifecycle audit passed\",\n \"mise PATH and canonical project manifest passed\",\n ];\n return mergeInitResults(this.metadata.id, false, [verifiedResult, await summaryResult(ctx)]);\n }\n\n protected printNextSteps(): void {\n // PrintHermesSummary handles this via the recipe chain.\n }\n}\n", "import { Recipe } from \"./Recipe\";\nimport type { CommandContext } from \"../commands/Command\";\nimport { createMiseOpInjectChecks } from \"../parity/rules\";\nimport type { RecipeMetadata } from \"./types\";\nimport type { LifecycleContext, RecipeInitResult } from \"./types\";\n\nexport class MiseOpInjectRecipe extends Recipe {\n readonly checks = createMiseOpInjectChecks();\n readonly metadata: RecipeMetadata = {\n id: \"mise-op-inject\",\n name: \"mise-op-inject\",\n description: \"Canonical .env.op to .env materialization lifecycle\",\n dependencies: [],\n commands: [\"WireMiseOpInject\"],\n publicRuleIds: this.checks.map((check) => check.id),\n };\n\n constructor(context?: CommandContext) {\n super(context);\n }\n\n override init(ctx: LifecycleContext, _input: unknown): Promise<RecipeInitResult> {\n return this.initializeOwnedChecks(ctx);\n }\n\n protected printNextSteps(): void {\n console.log(\"\uD83C\uDF89 Wired up .env.op 1Password resolution via mise!\");\n console.log(\" Next steps:\");\n console.log(\" 1. Create .env.op with your op:// secret references\");\n console.log(\" 2. Re-enter the project to run the managed materialization hook\");\n }\n}\n", "import { Recipe } from \"./Recipe\";\nimport type { CommandContext } from \"../commands/Command\";\nimport { createMiseChecks } from \"../parity/rules\";\nimport type { LifecycleContext, RecipeInitResult, RecipeMetadata } from \"./types\";\n\nexport class MiseRecipe extends Recipe {\n readonly checks = createMiseChecks();\n readonly metadata: RecipeMetadata = {\n id: \"mise\",\n name: \"mise\",\n description: \"Mise task runner and environment setup\",\n dependencies: [\"mise-op-inject\"],\n commands: [\"AddMiseToml\", \"AddDotenv\", \"AddMiseTasksStructure\", \"AddMiseBaseToml\", \"AddMiseBaseScript\", \"AddMiseCodegraphScript\", \"AddMiseCodegraphWireScript\"],\n publicRuleIds: this.checks.map((check) => check.id),\n };\n\n constructor(context?: CommandContext) {\n super(context);\n }\n\n override init(ctx: LifecycleContext, _input: unknown): Promise<RecipeInitResult> {\n return this.initializeOwnedChecks(ctx);\n }\n\n protected printNextSteps(): void {\n console.log(\"\uD83C\uDF89 Mise subsystem initialized successfully!\");\n console.log(\" Next steps:\");\n console.log(\" 1. mise install\");\n console.log(\" 2. mise run dev\");\n }\n}\n", "import { Command, type InvokeResult, type CommandContext } from \"../commands/Command\";\n\nexport class AddPackageJson extends Command {\n async invoke(): Promise<InvokeResult> {\n const filePath = \"package.json\";\n \n if (this.fileExists(filePath) && !this.context.force) {\n return {\n success: false,\n message: \"\u26A0\uFE0F package.json already exists\",\n filePath\n };\n }\n\n const content = `{\n \"name\": \"my-project\",\n \"version\": \"1.0.0\",\n \"description\": \"A new project\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"start\": \"node index.js\",\n \"dev\": \"node --watch index.js\",\n \"test\": \"echo \\\\\"Error: no test specified\\\\\" && exit 1\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"ISC\"\n}\n`;\n\n this.writeFile(filePath, content);\n return {\n success: true,\n message: \"\u2705 Created package.json\",\n filePath\n };\n }\n}\n\nexport class AddReadme extends Command {\n async invoke(): Promise<InvokeResult> {\n const filePath = \"README.md\";\n \n if (this.fileExists(filePath) && !this.context.force) {\n return {\n success: false,\n message: \"\u26A0\uFE0F README.md already exists\",\n filePath\n };\n }\n\n const content = `# My Project\n\nA new project initialized with pjangler.\n\n## Getting Started\n\n1. Install dependencies: \\`mise install\\`\n2. Start development: \\`mise run dev\\`\n\n## Project Structure\n\n- \\`mise.toml\\` - Environment configuration\n- \\`.mise/tasks/\\` - Task definitions\n- \\`src/\\` - Source code\n`;\n\n this.writeFile(filePath, content);\n return {\n success: true,\n message: \"\u2705 Created README.md\",\n filePath\n };\n }\n}\n\nexport class AddSrcDirectory extends Command {\n async invoke(): Promise<InvokeResult> {\n this.createDirectory(\"src\");\n \n const indexJsPath = \"src/index.js\";\n const content = `console.log(\"Hello, World!\");\n`;\n\n this.writeFile(indexJsPath, content);\n \n return {\n success: true,\n message: \"\u2705 Created src/ directory with index.js\",\n filePath: \"src/index.js\"\n };\n }\n}", "import { Recipe } from \"./Recipe\";\nimport { AddPackageJson, AddReadme, AddSrcDirectory } from \"../commands/NodeCommands\";\nimport type { CommandContext } from \"../commands/Command\";\nimport type { LifecycleContext, RecipeCheck, RecipeInitResult, RecipeMetadata } from \"./types\";\n\nexport class NodeRecipe extends Recipe {\n // PJAN-84: deliberately no checks, and this is the reason.\n //\n // An audit rule here would have to answer \"did pjangler install this?\", and\n // the recipe records no provenance \u2014 nothing distinguishes the package.json\n // `pj add node` wrote from the one npm wrote. Requiring README.md and\n // src/ wherever a package.json exists would flag every library, every\n // monorepo package, and every repo that keeps its sources elsewhere.\n //\n // So the honest state is what `describe` already reports: the subsystem's\n // presence comes from marker files and its parity reads \"unchecked\". A rule\n // that produced false positives would be worse than no rule. Give this checks\n // when the recipe starts recording what it wrote \u2014 not before.\n readonly checks: readonly RecipeCheck[] = [];\n readonly metadata: RecipeMetadata = {\n id: \"node\",\n name: \"node\",\n description: \"Node.js project template\",\n dependencies: [],\n commands: [\"NodeCommands\"],\n publicRuleIds: [],\n };\n\n constructor(context?: CommandContext) {\n super(context);\n this\n .addIngredient(AddPackageJson)\n .addIngredient(AddReadme)\n .addIngredient(AddSrcDirectory);\n }\n\n override init(ctx: LifecycleContext, _input: unknown): Promise<RecipeInitResult> {\n return this.invokeIngredients(ctx);\n }\n\n protected printNextSteps(): void {\n console.log(\"\uD83C\uDF89 Node.js project initialized successfully!\");\n console.log(\" Next steps:\");\n console.log(\" 1. mise install\");\n console.log(\" 2. mise run dev\");\n }\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { existsSync, lstatSync, readFileSync, rmSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, relative as relativePath, resolve } from \"node:path\";\nimport {\n createSafeRecord,\n executeProjectInitPlan,\n normalizeAgentRole,\n providerAssignsIdentifiers,\n type ProjectAgentRecord,\n type ProjectInitExecutionOptions,\n type ProjectInitExecutionResult,\n type ProjectInitPlan,\n type ProjectManifest,\n type ProjectTicketProvider,\n} from \"../project/index\";\nimport {\n BMAD_INSTALLER_VERSION,\n createProjectChecks,\n preflightBmadLifecycle,\n type AuditReport,\n type BmadLifecyclePreflightResult,\n type MigrationReport,\n} from \"../parity/rules\";\nimport { Recipe } from \"./Recipe\";\nimport type { RecipeRegistry } from \"./registry\";\nimport { gatesProject } from \"./types\";\nimport type {\n LifecycleContext,\n RecipeInitResult,\n RecipeMetadata,\n RecipePhaseOutcome,\n} from \"./types\";\nimport type { HermesAgentContext } from \"../commands/hermes/types\";\nimport { ApplyDeferredExternalEffects } from \"../commands/hermes/ApplyDeferredExternalEffects\";\nimport { changedTreePaths, snapshotTree } from \"../utils/tree-diff\";\nimport type { TrustedCopierIdentity } from \"../lifecycle/preflight\";\nimport type { NotebookPlanV1 } from \"../notebook/observation\";\nimport { NotebookRecipe } from \"./NotebookRecipe\";\n\nexport interface ProjectRecipeInput {\n plan: ProjectInitPlan;\n mode: \"create\" | \"sync\";\n selectedRuleIds?: readonly string[];\n selectedOperations?: readonly string[];\n agentContext?: Partial<HermesAgentContext>;\n quiet?: boolean;\n trustedCopier?: TrustedCopierIdentity;\n requireTrustedCopier?: boolean;\n}\n\nexport interface ProjectRecipeResult extends RecipeInitResult {\n plan: ProjectInitPlan;\n mode: \"create\" | \"sync\";\n audit?: AuditReport;\n migrationReport?: MigrationReport;\n selectedOperations: readonly string[];\n selectedParityRules: readonly string[];\n agentResult?: RecipeInitResult;\n}\n\nexport interface ProjectRecipeRuntime {\n executePlan(plan: ProjectInitPlan, options?: ProjectInitExecutionOptions): Promise<ProjectInitExecutionResult>;\n preflightBmad(ctx: LifecycleContext): BmadLifecyclePreflightResult;\n runGit(\n cwd: string,\n args: readonly string[],\n options?: { env?: NodeJS.ProcessEnv },\n ): { status: number | null; stdout: string; stderr: string; error?: Error };\n}\n\nconst BOOTSTRAP_GIT_IDENTITY: NodeJS.ProcessEnv = {\n GIT_AUTHOR_NAME: \"Pjangler Lifecycle\",\n GIT_AUTHOR_EMAIL: \"pjangler@localhost.invalid\",\n GIT_COMMITTER_NAME: \"Pjangler Lifecycle\",\n GIT_COMMITTER_EMAIL: \"pjangler@localhost.invalid\",\n};\n\nconst PRODUCTION_RUNTIME: ProjectRecipeRuntime = {\n executePlan: executeProjectInitPlan,\n preflightBmad: preflightBmadLifecycle,\n runGit(cwd, args, options) {\n const result = spawnSync(\"git\", [...args], {\n cwd,\n encoding: \"utf8\",\n env: options?.env ? { ...process.env, ...options.env } : process.env,\n });\n return {\n status: result.status,\n stdout: result.stdout ?? \"\",\n stderr: result.stderr ?? \"\",\n error: result.error,\n };\n },\n};\n\n/**\n * PJAN-84: prove the path being deleted is the path that was created.\n *\n * The rollback was `rmSync(targetDir, {recursive: true, force: true})` on the\n * sole evidence that `existsSync(targetDir)` had been false at the start. Node's\n * recursive remove does not FOLLOW a symlink at the leaf, but it does traverse\n * symlinked PARENT components \u2014 so if any ancestor of the target became a\n * symlink during the transaction, the delete lands somewhere nobody named. Every\n * other place in this codebase that touches an unproved path checks this first\n * (src/notebook/hooks.ts, src/parity/pack.ts); the one operation that deletes a\n * whole directory tree did not.\n *\n * Returns null when the path is safe to remove, or the reason it is not.\n */\nexport function unsafeToRemove(targetDir: string): string | null {\n const absolute = resolve(targetDir);\n let cursor = absolute;\n const seen = new Set<string>();\n while (!seen.has(cursor)) {\n seen.add(cursor);\n try {\n const stat = lstatSync(cursor);\n if (stat.isSymbolicLink()) {\n return cursor === absolute\n ? `${absolute} is a symlink; removing it would leave the tree it points at orphaned`\n : `${cursor} is a symlink on the path to ${absolute}; a recursive remove would traverse it`;\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n return `${cursor} could not be inspected: ${error instanceof Error ? error.message : String(error)}`;\n }\n }\n const parent = dirname(cursor);\n if (parent === cursor) break;\n cursor = parent;\n }\n return null;\n}\n\nfunction publicAudit(report: ReturnType<RecipeRegistry[\"auditRecipes\"]>): AuditReport {\n return {\n ...report,\n rules: report.rules.map(({ recipeId: _recipeId, ...finding }) => finding),\n } as AuditReport;\n}\n\nfunction publicMigration(report: Awaited<ReturnType<RecipeRegistry[\"migrateRules\"]>>): MigrationReport {\n return {\n ...report,\n results: report.results.map(({ recipeId: _recipeId, ...result }) => result),\n } as MigrationReport;\n}\n\nfunction hasGitRepository(runtime: ProjectRecipeRuntime, targetDir: string): boolean {\n if (!existsSync(join(targetDir, \".git\"))) return false;\n return runtime.runGit(targetDir, [\"rev-parse\", \"--is-inside-work-tree\"]).status === 0;\n}\n\n/**\n * The repo-local manifest is authoritative for state discovered while running\n * the project transaction (most notably Hermes role directories). Project the\n * canonical result back into the pending central-registry write so persisting\n * the registry last cannot reintroduce pre-provisioning state on the next run.\n */\nfunction refreshPlanFromCanonicalManifest(plan: ProjectInitPlan): void {\n const manifestPath = join(plan.project.repo_path, \".project.json\");\n const manifest = JSON.parse(readFileSync(manifestPath, \"utf8\")) as ProjectManifest;\n if (!manifest || typeof manifest !== \"object\" || Array.isArray(manifest)) {\n throw new Error(`${manifestPath} must contain a JSON object`);\n }\n\n const agents = createSafeRecord<ProjectAgentRecord>();\n for (const [agentId, entry] of Object.entries(manifest.agents ?? {})) {\n const rawRole = typeof entry?.role === \"string\" ? entry.role : \"\";\n if (!rawRole.trim()) throw new Error(`${manifestPath} agents.${agentId}.role is missing`);\n const role = normalizeAgentRole(rawRole);\n if (Object.hasOwn(agents, role)) throw new Error(`${manifestPath} declares more than one ${role} agent`);\n agents[role] = {\n role,\n role_dir: entry.role_dir,\n provisioning_state: entry.provisioning_state ?? \"provisioned\",\n };\n }\n const manifestTicket = manifest.ticket_provider;\n if (!manifestTicket || typeof manifestTicket !== \"object\") {\n throw new Error(`${manifestPath} ticket_provider is missing`);\n }\n const manifestIdentifier = String(manifestTicket.identifier ?? \"\");\n const manifestBoardId = String(manifestTicket.board_id ?? \"\");\n const manifestType = String(manifestTicket.type ?? \"\");\n // `.project.json` is authoritative for the BINDING, and the adapter that\n // wrote it stamps `board_confirmed_at` at the instant the provider handed the\n // board back \u2014 so board-binding provenance travels with the binding.\n // IDENTIFIER provenance does not: the manifest cannot say where a key came\n // from beyond what it was told, so keep what the registry already knows when\n // the manifest agrees, and otherwise degrade to \"proposed\" until\n // `pj project identity` re-reads the truth.\n const recorded = plan.project.ticket_provider;\n const carriesProvenance =\n (recorded?.identifier ?? \"\") === manifestIdentifier && (recorded?.board_id ?? \"\") === manifestBoardId;\n const identifierSource = (carriesProvenance ? recorded?.identifier_source : undefined) ?? \"proposed\";\n const manifestConfirmedAt =\n typeof manifestTicket.board_confirmed_at === \"string\" ? manifestTicket.board_confirmed_at.trim() : \"\";\n const boardConfirmedAt =\n manifestConfirmedAt || ((recorded?.board_id ?? \"\") === manifestBoardId ? recorded?.board_confirmed_at ?? \"\" : \"\");\n // Plane names its own boards; Trello does not. A link needs a confirmed\n // board from either, and a provider-sourced key only from the former.\n const keyIsProven = !providerAssignsIdentifiers(manifestType) || identifierSource === \"provider\";\n const manifestState = typeof manifestTicket.state === \"string\" ? manifestTicket.state : undefined;\n const ticketProvider: ProjectTicketProvider = {\n type: manifestType,\n workspace: String(manifestTicket.workspace ?? \"\"),\n identifier: manifestIdentifier,\n identifier_source: identifierSource,\n ...(carriesProvenance && identifierSource === \"provider\" && recorded?.identifier_fetched_at\n ? { identifier_fetched_at: recorded.identifier_fetched_at }\n : {}),\n board_id: manifestBoardId,\n ...(boardConfirmedAt ? { board_confirmed_at: boardConfirmedAt } : {}),\n state:\n manifestState === \"skipped\"\n ? \"skipped\"\n : manifestBoardId && boardConfirmedAt && keyIsProven\n ? \"linked\"\n : \"planned\",\n };\n\n plan.manifest = manifest;\n plan.project.agents = agents;\n plan.project.ticket_provider = ticketProvider;\n for (const action of plan.actions) {\n if (action.kind === \"project.write-manifest\") action.manifest = manifest;\n if (action.kind === \"registry.upsert\") action.project = plan.project;\n }\n}\n\n/**\n * Project-level transaction boundary shared by CLI and MCP.\n *\n * It executes the selected plan, initializes declared lifecycle dependencies\n * only for a fresh scaffold, applies only explicitly selected sync migrations,\n * proves eligibility, initializes Git and local registry state, then runs the\n * provider/systemd tail followed only by read-only postcondition verification.\n * No implicit migrate-all repair phase exists.\n */\nexport class ProjectRecipe extends Recipe<ProjectRecipeInput | ProjectInitPlan> {\n readonly orchestratesDependencies = true;\n readonly checks = createProjectChecks();\n readonly metadata: RecipeMetadata = {\n id: \"project\",\n name: \"project\",\n description: \"CommonProject plan, lifecycle composition, audit, and Git boundary\",\n dependencies: [\"mise\", \"agent-hooks\", \"bmad\", \"notebook\"],\n commands: [],\n publicRuleIds: this.checks.map((check) => check.id),\n };\n\n private registry?: RecipeRegistry;\n\n constructor(private readonly runtime: ProjectRecipeRuntime = PRODUCTION_RUNTIME) {\n super();\n }\n\n attachRegistry(registry: RecipeRegistry): void {\n this.registry = registry;\n }\n\n private async runNotebookLifecycle(plan: ProjectInitPlan, mode: \"create\" | \"sync\", ctx: LifecycleContext): Promise<NotebookPlanV1> {\n if (!this.registry) throw new Error(\"ProjectRecipe is not attached to a RecipeRegistry\");\n const result = await this.registry.initRecipe(\"notebook\", ctx, { plan, mode });\n if (!result.ok || !result.notebookPlan) throw new Error(result.errors.join(\"; \") || \"Notebook lifecycle planning failed\");\n return result.notebookPlan as NotebookPlanV1;\n }\n\n override async init(ctx: LifecycleContext, input: ProjectRecipeInput | ProjectInitPlan): Promise<ProjectRecipeResult> {\n if (!this.registry) throw new Error(\"ProjectRecipe is not attached to a RecipeRegistry\");\n const normalized: ProjectRecipeInput = \"plan\" in input\n ? input\n : {\n plan: input,\n mode: input.actions.some((action) => action.kind === \"copier.copy.commonproject\") ? \"create\" : \"sync\",\n };\n const { plan, mode } = normalized;\n const targetDir = plan.project.repo_path;\n const phases: RecipePhaseOutcome[] = [];\n const logs: string[] = [];\n const errors: string[] = [];\n const changedFiles: string[] = [];\n const targetExistedAtStart = existsSync(targetDir);\n const transactionContext: LifecycleContext = {\n ...ctx,\n targetDir,\n repoRoot: targetDir,\n bmadVersionPin: mode === \"create\" ? BMAD_INSTALLER_VERSION : ctx.bmadVersionPin,\n };\n let agentResult: RecipeInitResult | undefined;\n let provisionedAgentContext: (LifecycleContext & HermesAgentContext) | undefined;\n let migrationReport: MigrationReport | undefined;\n let audit: AuditReport | undefined;\n let notebookPlan: NotebookPlanV1 | undefined;\n let notebookRecipeForCommit: NotebookRecipe | undefined;\n let notebookJournals: Parameters<NotebookRecipe[\"commitExternal\"]>[0] = [];\n let externalDispatchStarted = false;\n let rollbackEligible = true;\n let registryFinalizerEligible = false;\n\n try {\n if (mode === \"create\") {\n const preflight = this.runtime.preflightBmad(transactionContext);\n phases.push({\n id: \"project.preflight:bmad\",\n status: preflight.ok ? \"unchanged\" : \"failed\",\n changedFiles: [],\n message: preflight.ok ? \"Pinned BMAD installer and sealed pack are available\" : preflight.error,\n });\n if (!preflight.ok) errors.push(`BMAD preflight failed: ${preflight.error ?? \"unknown error\"}`);\n }\n\n const registryActions = plan.actions.filter((action) => action.kind === \"registry.upsert\");\n const externalPlanActions = plan.actions.filter((action) => action.kind === \"ticket-provider.create-or-link\");\n const filesystemPlan: ProjectInitPlan = {\n ...plan,\n actions: plan.actions.filter((action) =>\n action.kind !== \"registry.upsert\"\n && action.kind !== \"hermes.provision-agent\"\n && action.kind !== \"ticket-provider.create-or-link\"),\n };\n const planBlocked = errors.length > 0;\n const executed = !planBlocked && filesystemPlan.actions.length\n ? await this.runtime.executePlan(filesystemPlan, {\n trustedCopier: normalized.trustedCopier,\n requireTrustedCopier: normalized.requireTrustedCopier,\n })\n : { ok: !planBlocked, plan: filesystemPlan, logs: [], errors: [], changedFiles: [] };\n logs.push(...executed.logs);\n errors.push(...executed.errors);\n changedFiles.push(...executed.changedFiles);\n phases.push({\n id: \"project.plan\",\n status: planBlocked ? \"skipped\" : executed.ok ? (executed.changedFiles.length ? \"changed\" : \"unchanged\") : \"failed\",\n changedFiles: executed.ok ? executed.changedFiles : [],\n message: planBlocked ? \"Project plan skipped after failed preflight\" : executed.ok ? \"Project plan executed\" : executed.errors.join(\"; \"),\n });\n\n if (errors.length === 0 && executed.ok && mode === \"create\") {\n const dependencyResult = await this.registry.initDependencies(this.metadata.id, transactionContext, normalized, [\"notebook\"]);\n logs.push(...dependencyResult.logs);\n errors.push(...dependencyResult.errors);\n changedFiles.push(...dependencyResult.changedFiles);\n phases.push(...dependencyResult.phases);\n }\n\n if (errors.length === 0 && executed.ok) {\n try {\n notebookPlan = await this.runNotebookLifecycle(plan, mode, transactionContext);\n phases.push({\n id: \"notebook.plan\",\n status: notebookPlan.remote_effect === \"reconcile\" ? \"planned\" : \"skipped\",\n changedFiles: [],\n message: notebookPlan.reason,\n });\n } catch (error) {\n errors.push(`notebook lifecycle planning failed: ${error instanceof Error ? error.message : String(error)}`);\n phases.push({ id: \"notebook.plan\", status: \"failed\", changedFiles: [], message: errors.at(-1) });\n }\n }\n\n if (errors.length === 0 && notebookPlan) {\n const notebookRecipe = this.registry.get(\"notebook\");\n if (!(notebookRecipe instanceof NotebookRecipe)) throw new Error(\"Registered notebook recipe is not the singleton NotebookRecipe\");\n const localNotebook = await notebookRecipe.applyLocal(transactionContext, plan, notebookPlan);\n logs.push(...localNotebook.logs);\n errors.push(...localNotebook.errors);\n changedFiles.push(...localNotebook.changedFiles);\n phases.push(...localNotebook.phases);\n }\n\n const agentAction = plan.actions.find((action) => action.kind === \"hermes.provision-agent\" && action.enabled);\n if (errors.length === 0 && agentAction?.kind === \"hermes.provision-agent\") {\n const agentContext: HermesAgentContext = {\n targetRepo: agentAction.targetRepo,\n role: agentAction.role,\n agentPurpose: `${agentAction.role} agent for ${agentAction.targetRepo}`,\n ticketProvider: plan.project.ticket_provider.type as \"plane\" | \"trello\",\n local: agentAction.local,\n force: Boolean(ctx.force),\n skipTelegram: true,\n skipEmail: true,\n skipPlane: agentAction.context.skipPlane,\n skipBloodbank: agentAction.context.skipBloodbank,\n skipSystemd: agentAction.context.skipSystemd,\n ...(normalized.agentContext ?? {}),\n targetDir,\n yes: true,\n // Structured callers own stdout and prompt input. Do not allow a\n // nested context object to weaken the transaction's quiet contract.\n quiet: normalized.quiet ?? ctx.quiet ?? false,\n dryRun: false,\n };\n provisionedAgentContext = { ...transactionContext, ...agentContext, targetDir, repoRoot: targetDir };\n agentResult = await this.registry.initRecipe(\n \"hermes-agent\",\n provisionedAgentContext,\n agentContext,\n );\n logs.push(...agentResult.logs);\n errors.push(...agentResult.errors);\n changedFiles.push(...agentResult.changedFiles);\n phases.push(...agentResult.phases);\n }\n\n // A fresh scaffold and an agent-provisioning action both create state\n // governed by this recipe. Close only ProjectRecipe's own checks here;\n // existing syncs without such an action still require explicitly selected\n // migrations and never receive an implicit migrate-all repair pass.\n if (errors.length === 0 && (mode === \"create\" || agentResult)) {\n const projectLifecycle = await this.initializeOwnedChecks(transactionContext);\n logs.push(...projectLifecycle.logs);\n errors.push(...projectLifecycle.errors);\n changedFiles.push(...projectLifecycle.changedFiles);\n phases.push(...projectLifecycle.phases);\n if (projectLifecycle.ok) {\n try {\n refreshPlanFromCanonicalManifest(plan);\n } catch (error) {\n errors.push(`project manifest refresh failed: ${error instanceof Error ? error.message : String(error)}`);\n phases.push({\n id: \"project.manifest-refresh\",\n status: \"failed\",\n changedFiles: [],\n message: errors.at(-1),\n });\n }\n }\n }\n\n if (errors.length === 0 && normalized.selectedRuleIds?.length) {\n migrationReport = publicMigration(await this.registry.migrateRules(\n { ...transactionContext, dryRun: false },\n normalized.selectedRuleIds,\n ));\n changedFiles.push(...migrationReport.changedFiles);\n phases.push(...migrationReport.results.map((result) => ({\n id: result.id,\n status: result.status === \"applied\" ? \"changed\" : result.status === \"noop\" ? \"unchanged\" : result.status === \"skipped\" ? \"skipped\" : \"failed\",\n // A `partial` failed, but its writes really happened, so they stay\n // accounted for rather than vanishing from the transaction record.\n changedFiles: result.status === \"applied\" || result.status === \"partial\" ? result.changedFiles : [],\n message: result.summary,\n } as RecipePhaseOutcome)));\n errors.push(...migrationReport.results\n .filter((result) => result.status === \"blocked\" || result.status === \"partial\")\n .map((result) => `${result.id}: ${result.summary}`));\n }\n\n const eligibilityAudit = errors.length === 0\n ? publicAudit(this.registry.auditRecipes({ ...transactionContext, dryRun: true }))\n : undefined;\n audit = eligibilityAudit;\n if (eligibilityAudit && !eligibilityAudit.ok) {\n errors.push(...eligibilityAudit.rules\n // PJAN-84: only a PROJECT-scoped failure is this transaction's problem.\n // A host finding \u2014 a drifted ~/.agents symlink, a systemd unit, the\n // fleet registry \u2014 cannot be fixed by the repo being created, and\n // failing here used to delete it (see the rollback guard below).\n .filter((finding) => gatesProject(finding))\n .map((finding) => `${finding.id}: ${finding.summary}`));\n }\n phases.push({\n id: \"project.audit:eligibility\",\n status: eligibilityAudit?.ok ? \"unchanged\" : \"failed\",\n changedFiles: [],\n message: eligibilityAudit?.ok\n ? \"Lifecycle eligibility audit passed before external effects\"\n : \"Lifecycle eligibility audit failed or was skipped; external effects remain disabled\",\n });\n\n // Complete every ordinary local operation that can fail before entering\n // the explicitly granted external tail. External scripts may persist\n // their own returned identifiers, but no new lifecycle mutation follows\n // them; only the postcondition audit below remains.\n if (errors.length === 0 && mode === \"create\") {\n if (hasGitRepository(this.runtime, targetDir)) {\n phases.push({ id: \"project.git\", status: \"unchanged\", changedFiles: [], message: \"Git repository already initialized\" });\n } else {\n const gitPath = join(targetDir, \".git\");\n for (const { args, label, options } of [\n { args: [\"init\", \"--initial-branch=main\"], label: \"git init\" },\n { args: [\"add\", \"-A\"], label: \"git add\" },\n {\n args: [\"commit\", \"--no-gpg-sign\", \"-m\", \"chore: initialize project\"],\n label: \"git commit\",\n options: { env: BOOTSTRAP_GIT_IDENTITY },\n },\n ] as const) {\n const result = this.runtime.runGit(targetDir, args, options);\n if (result.status !== 0) {\n errors.push(`${label} failed: ${(result.stderr || result.stdout || result.error?.message || \"unknown error\").trim()}`);\n phases.push({ id: `project.git:${label}`, status: \"failed\", changedFiles: changedFiles.includes(gitPath) ? [gitPath] : [], message: errors.at(-1) });\n break;\n }\n if (label === \"git init\" && existsSync(gitPath)) changedFiles.push(gitPath);\n logs.push(`${label}: ok`);\n }\n if (errors.length === 0) {\n const repositoryReady = hasGitRepository(this.runtime, targetDir);\n const headReady = repositoryReady && this.runtime.runGit(targetDir, [\"rev-parse\", \"--verify\", \"HEAD\"]).status === 0;\n if (!headReady) {\n errors.push(\"git postcondition failed: repository or initial commit is missing\");\n phases.push({ id: \"project.git:postcondition\", status: \"failed\", changedFiles: existsSync(gitPath) ? [gitPath] : [], message: errors.at(-1) });\n } else {\n if (!changedFiles.includes(gitPath)) changedFiles.push(gitPath);\n phases.push({ id: \"project.git\", status: \"changed\", changedFiles: [gitPath], message: \"Git repository initialized and committed\" });\n }\n }\n }\n }\n registryFinalizerEligible = errors.length === 0;\n\n if (errors.length === 0 && externalPlanActions.length) {\n // Any enabled provider action crosses an adapter boundary, including a\n // link/reconcile of an already-known board. Latch before handing the\n // action to the adapter so fresh-target rollback can never delete local\n // recovery evidence after external dispatch might have started.\n const dispatching = externalPlanActions.some((action) => action.kind === \"ticket-provider.create-or-link\" && action.enabled);\n if (dispatching) {\n externalDispatchStarted = true;\n rollbackEligible = false;\n }\n const externalPlan: ProjectInitPlan = {\n ...plan,\n actions: externalPlanActions,\n };\n const external = await this.runtime.executePlan(externalPlan);\n logs.push(...external.logs);\n errors.push(...external.errors);\n changedFiles.push(...external.changedFiles);\n phases.push({\n id: \"project.external:ticket-provider\",\n status: external.ok ? (external.changedFiles.length ? \"changed\" : \"unchanged\") : \"failed\",\n changedFiles: external.ok ? external.changedFiles : [],\n message: external.ok ? \"Deferred ticket-provider phase completed\" : external.errors.join(\"; \"),\n });\n }\n\n\n if (errors.length === 0 && notebookPlan?.remote_effect === \"reconcile\") {\n if (!ctx.live) {\n phases.push({ id: \"project.external:notebook\", status: \"skipped\", changedFiles: [], message: \"Notebook remote reconciliation requires --live\" });\n } else {\n externalDispatchStarted = true;\n rollbackEligible = false;\n const notebookRecipe = this.registry.get(\"notebook\");\n if (!(notebookRecipe instanceof NotebookRecipe)) throw new Error(\"Registered notebook recipe is not the singleton NotebookRecipe\");\n try {\n const applied = await notebookRecipe.applyExternal(plan, notebookPlan);\n notebookRecipeForCommit = notebookRecipe;\n notebookJournals = applied.data.journals ?? [];\n logs.push(`notebook: reconciled ${applied.data.notebook_id} with Overview ${applied.data.overview_note_id}`);\n const manifestActions = plan.actions.filter((action) => action.kind === \"project.write-manifest\");\n const projected = manifestActions.length\n ? await this.runtime.executePlan({ ...plan, actions: manifestActions })\n : { ok: true, logs: [], errors: [], changedFiles: [] };\n logs.push(...projected.logs);\n errors.push(...projected.errors);\n changedFiles.push(...projected.changedFiles);\n if (projected.ok) {\n notebookPlan = notebookRecipe.refreshPlan(plan, notebookPlan);\n transactionContext.notebookPlan = notebookPlan;\n const projectedNotebook = (plan.manifest as ProjectManifest & { notebook?: { binding?: Record<string, unknown> } }).notebook;\n transactionContext.notebookManifestBinding = projectedNotebook?.binding\n ? Object.freeze({ ...projectedNotebook.binding })\n : null;\n transactionContext.notebookObservation = Object.freeze(await notebookRecipe.observeExternal(plan, notebookPlan));\n const candidateAudit = publicAudit(this.registry.auditRecipes(transactionContext, [\"notebook\"]));\n if (!candidateAudit.ok) errors.push(...candidateAudit.rules.filter((item) => item.status === \"fail\" || item.status === \"warn\").map((item) => `${item.id}: ${item.summary}`));\n }\n phases.push({\n id: \"project.external:notebook\",\n status: errors.length === 0 ? (projected.changedFiles.length ? \"changed\" : \"unchanged\") : \"failed\",\n changedFiles: errors.length === 0 ? projected.changedFiles : [],\n message: errors.length === 0 ? \"Notebook and stable Overview reconciled and observation-audited\" : errors.at(-1),\n });\n } catch (error) {\n errors.push(`notebook external effect failed: ${error instanceof Error ? error.message : String(error)}`);\n phases.push({ id: \"project.external:notebook\", status: \"failed\", changedFiles: [], message: errors.at(-1) });\n }\n }\n }\n\n const deferred = provisionedAgentContext?.deferredExternalEffects;\n if (errors.length === 0 && deferred?.owner === \"project\" && (deferred.ticketBoard || deferred.systemd)) {\n externalDispatchStarted = true;\n rollbackEligible = false;\n const beforeExternal = snapshotTree(targetDir);\n const external = await new ApplyDeferredExternalEffects(provisionedAgentContext!).invoke();\n const externalChanges = changedTreePaths(targetDir, beforeExternal, snapshotTree(targetDir));\n logs.push(...(external.message ? [external.message] : []));\n if (!external.success) errors.push(external.message || \"Deferred Hermes external effects failed\");\n changedFiles.push(...externalChanges);\n phases.push({\n id: \"project.external:hermes\",\n status: external.success ? \"changed\" : \"failed\",\n changedFiles: external.success ? externalChanges : [],\n message: external.message || undefined,\n });\n }\n\n if (registryFinalizerEligible && (externalPlanActions.length || notebookPlan || deferred)) {\n try {\n refreshPlanFromCanonicalManifest(plan);\n } catch (error) {\n errors.push(`project manifest refresh after external effects failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n // One Registry-only finalizer is the last mutation. It persists linked\n // successes and planned/blocked recovery even when an external effect\n // failed, then no lifecycle writer runs again in this transaction.\n if (registryFinalizerEligible && registryActions.length) {\n rollbackEligible = false;\n const registryPlan: ProjectInitPlan = { ...plan, actions: registryActions };\n const persisted = await this.runtime.executePlan(registryPlan);\n logs.push(...persisted.logs);\n errors.push(...persisted.errors);\n changedFiles.push(...persisted.changedFiles);\n phases.push({\n id: \"project.registry:finalizer\",\n status: persisted.ok ? (persisted.changedFiles.length ? \"changed\" : \"unchanged\") : \"failed\",\n changedFiles: persisted.ok ? persisted.changedFiles : [],\n message: persisted.ok ? \"Project Registry persisted as the final mutation\" : persisted.errors.join(\"; \"),\n });\n if (errors.length === 0 && persisted.ok && notebookRecipeForCommit && notebookJournals.length) {\n try { notebookRecipeForCommit.commitExternal(notebookJournals); }\n catch (error) { errors.push(`notebook ownership journal finalization failed: ${error instanceof Error ? error.message : String(error)}`); }\n }\n }\n\n audit = errors.length === 0\n ? publicAudit(this.registry.auditRecipes({ ...transactionContext, dryRun: true }))\n : audit;\n if (errors.length === 0 && audit && !audit.ok) {\n errors.push(...audit.rules\n // PJAN-84: only a PROJECT-scoped failure is this transaction's problem.\n // A host finding \u2014 a drifted ~/.agents symlink, a systemd unit, the\n // fleet registry \u2014 cannot be fixed by the repo being created, and\n // failing here used to delete it (see the rollback guard below).\n .filter((finding) => gatesProject(finding))\n .map((finding) => `${finding.id}: ${finding.summary}`));\n }\n phases.push({\n id: \"project.audit\",\n status: errors.length === 0 && audit?.ok ? \"unchanged\" : \"failed\",\n changedFiles: [],\n message: errors.length === 0 && audit?.ok\n ? \"Lifecycle postcondition audit passed\"\n : \"Lifecycle postcondition audit failed or was skipped\",\n });\n\n } catch (error) {\n errors.push(`project transaction failed: ${error instanceof Error ? error.message : String(error)}`);\n phases.push({\n id: \"project.transaction\",\n status: \"failed\",\n changedFiles: [],\n message: errors.at(-1),\n });\n }\n\n // `externalDispatchStarted` and `rollbackEligible` were assigned together\n // everywhere except the registry finalizer, so this conjunction always\n // reduced to `rollbackEligible` \u2014 two names for one fact. Because the latch\n // had no single meaning, nothing forced the notebook and Hermes HOST writes\n // earlier in this method to answer \"does this need to latch?\", and a failure\n // after them deleted the project while leaving that host state behind.\n if (errors.length > 0 && mode === \"create\" && !targetExistedAtStart && rollbackEligible && existsSync(targetDir)) {\n const unsafe = unsafeToRemove(targetDir);\n if (unsafe) {\n // Refusing leaves the target in place and says why. That is strictly\n // better than deleting through a symlink: the operator can inspect it,\n // and `pj init` over an existing directory is a supported path.\n errors.push(`fresh-target rollback refused: ${unsafe}`);\n phases.push({\n id: \"project.rollback\",\n status: \"failed\",\n changedFiles: [],\n message: errors.at(-1),\n });\n } else try {\n rmSync(targetDir, { recursive: true, force: true });\n // Report what survived rather than erasing the record.\n //\n // This used to be `changedFiles.length = 0`, which claimed the\n // transaction had changed nothing \u2014 while every write it made OUTSIDE\n // the target was still on disk. A run that installed a global skill\n // link and rewrote ~/.claude/settings.json reported `changedFiles: []`\n // and deleted the only thing that referenced them.\n const insideTarget = (path: string) => {\n const relative = relativePath(resolve(targetDir), resolve(path));\n return relative === \"\" || (!relative.startsWith(\"..\") && !isAbsolute(relative));\n };\n const orphaned = [...new Set(changedFiles.filter((path) => !insideTarget(path)))].sort();\n changedFiles.length = 0;\n changedFiles.push(...orphaned);\n logs.push(`Rolled back newly-created target: ${targetDir}`);\n for (const path of orphaned) logs.push(` not undone (outside the target): ${path}`);\n phases.push({\n id: \"project.rollback\",\n status: \"changed\",\n changedFiles: orphaned,\n message: orphaned.length\n ? `Removed the newly-created target; ${orphaned.length} change(s) outside it were NOT undone`\n : \"Removed the newly-created target after transaction failure\",\n });\n } catch (error) {\n errors.push(`fresh-target rollback failed: ${error instanceof Error ? error.message : String(error)}`);\n phases.push({\n id: \"project.rollback\",\n status: \"failed\",\n changedFiles: [],\n message: errors.at(-1),\n });\n }\n }\n\n return {\n recipeId: this.metadata.id,\n ok: errors.length === 0 && Boolean(audit?.ok),\n dryRun: Boolean(ctx.dryRun),\n changedFiles: [...new Set(changedFiles)].sort(),\n logs,\n errors,\n phases,\n plan,\n mode,\n audit,\n selectedOperations: normalized.selectedOperations ?? [],\n selectedParityRules: normalized.selectedRuleIds ?? [],\n migrationReport,\n agentResult,\n };\n }\n\n protected printNextSteps(): void {\n // Project init surfaces format the structured result themselves.\n }\n}\n", "import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { loadProjectRegistry, type ProjectInitPlan, type ProjectManifest, type ProjectRecord } from \"../project/index\";\nimport { createNotebookChecks, NOTEBOOK_RULE_IDS } from \"../notebook/checks\";\nimport { resolveEffectiveNotebookConfig, type ResolvedNotebookProjectV1 } from \"../notebook/config\";\nimport { NotebookModule } from \"../notebook/module\";\nimport { notebookStateRoot } from \"../notebook/state\";\nimport { commitReconciledRemoteMutation, type RemoteMutationJournalV1 } from \"../notebook/remote-mutation-journal\";\nimport type { NotebookPlanV1 } from \"../notebook/observation\";\nimport { prepareNotebookObservationResolved, type NotebookObservationV1 } from \"../notebook/observation\";\nimport type { ProjectNotebookBindingV1, ProjectNotebookConfigV1 } from \"../notebook/types\";\nimport { Recipe } from \"./Recipe\";\nimport type { LifecycleContext, RecipeInitResult, RecipeMetadata } from \"./types\";\n\nexport interface NotebookRecipeInput {\n plan: ProjectInitPlan;\n mode: \"create\" | \"sync\";\n}\n\nexport interface NotebookRecipeResult extends RecipeInitResult {\n notebookPlan: NotebookPlanV1;\n}\n\nexport interface NotebookDryRunProjectionV1 {\n plan: NotebookPlanV1;\n phases: Array<{\n id: \"configuration\" | \"binding-projection\" | \"skill\" | \"managed-hooks\" | \"overview-note\" | \"live-action\";\n scope: \"local\" | \"live\";\n status: \"proposed\" | \"requires-live\" | \"blocked-not-configured\" | \"skip\";\n summary: string;\n }>;\n}\n\nfunction integrationEnvironment(module: NotebookModule, ctx: LifecycleContext): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = { ...module.environment, HOME: ctx.homeDir };\n if (module.environment.HOME !== ctx.homeDir) {\n env.XDG_DATA_HOME = join(ctx.homeDir, \".local\", \"share\");\n env.XDG_STATE_HOME = join(ctx.homeDir, \".local\", \"state\");\n env.PJ_PROJECT_NOTEBOOK_CLAUDE_SETTINGS = join(ctx.homeDir, \".claude\", \"settings.json\");\n }\n return env;\n}\n\nfunction resolvedForPlan(plan: ProjectInitPlan): ResolvedNotebookProjectV1 {\n const manifestPath = join(plan.project.repo_path, \".project.json\");\n let manifest = plan.manifest;\n if (existsSync(manifestPath)) {\n const parsed = JSON.parse(readFileSync(manifestPath, \"utf8\")) as unknown;\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) throw new Error(`${manifestPath} must contain a JSON object`);\n manifest = parsed as ProjectManifest;\n }\n return {\n registry: loadProjectRegistry(plan.registryPath),\n project: plan.project,\n manifest,\n registry_path: plan.registryPath,\n };\n}\n\nexport function planNotebookForProjectInit(plan: ProjectInitPlan, mode: \"create\" | \"sync\"): NotebookPlanV1 {\n const resolved = resolvedForPlan(plan);\n const config = resolveEffectiveNotebookConfig(resolved);\n return Object.freeze({\n schema_version: 1,\n project_slug: config.project_slug,\n repo_path: config.repo_path,\n mode,\n config,\n remote_effect: config.policy.enabled && Boolean(config.base_url) ? \"reconcile\" : \"none\",\n reason: !config.policy.enabled ? \"disabled by project policy\" : config.base_url ? \"configured stable identity requires reconciliation\" : \"no safe global endpoint configured\",\n });\n}\n\nexport function projectNotebookDryRunProjection(plan: ProjectInitPlan, mode: \"create\" | \"sync\"): NotebookDryRunProjectionV1 {\n const notebookPlan = planNotebookForProjectInit(plan, mode);\n const enabled = notebookPlan.config.policy.enabled && notebookPlan.config.binding.state !== \"disabled\";\n const liveStatus = !enabled ? \"skip\" as const\n : !notebookPlan.config.base_url ? \"blocked-not-configured\" as const\n : plan.live ? \"proposed\" as const : \"requires-live\" as const;\n return {\n plan: notebookPlan,\n phases: [\n { id: \"configuration\", scope: \"local\", status: enabled ? \"proposed\" : \"skip\", summary: `Effective Project Notebook policy; SessionStart=${notebookPlan.config.policy.session_start_enabled} SessionEnd capture=${notebookPlan.config.policy.session_capture_enabled}` },\n { id: \"binding-projection\", scope: \"local\", status: enabled ? \"proposed\" : \"skip\", summary: `Registry/Manifest binding ${notebookPlan.config.binding.state} for ${notebookPlan.config.binding.notebook_name ?? notebookPlan.config.project_slug}` },\n { id: \"skill\", scope: \"local\", status: enabled ? \"proposed\" : \"skip\", summary: \"Verify the digest-pinned global Project Notebook skill\" },\n { id: \"managed-hooks\", scope: \"local\", status: enabled ? \"proposed\" : \"skip\", summary: \"Project true SessionStart and SessionEnd Managed Hooks without enabling repository capture policy\" },\n { id: \"overview-note\", scope: \"live\", status: liveStatus, summary: \"Reconcile the stable Overview Note ID and exact OverviewDescriptor\" },\n { id: \"live-action\", scope: \"live\", status: liveStatus, summary: \"Create, adopt, or rename the marker-owned Companion Notebook; remote mutation requires --live\" },\n ],\n };\n}\n\nfunction setBinding(plan: ProjectInitPlan, binding: ProjectNotebookBindingV1): void {\n const currentProject = plan.project.notebook;\n plan.project.notebook = { ...(currentProject ?? { state: \"planned\" }), ...binding };\n const currentManifest = (plan.manifest as ProjectManifest & { notebook?: ProjectNotebookConfigV1 }).notebook;\n (plan.manifest as ProjectManifest & { notebook: ProjectNotebookConfigV1 }).notebook = {\n ...(currentManifest ?? {}),\n binding: { ...(currentManifest?.binding ?? {}), ...binding },\n };\n for (const action of plan.actions) {\n if (action.kind === \"project.write-manifest\") action.manifest = plan.manifest;\n if (action.kind === \"registry.upsert\") action.project = plan.project;\n }\n}\n\nexport class NotebookRecipe extends Recipe<NotebookRecipeInput> {\n readonly checks = createNotebookChecks();\n readonly metadata: RecipeMetadata = {\n id: \"notebook\",\n name: \"notebook\",\n description: \"Project Notebook lifecycle, binding, hooks, and capture state\",\n dependencies: [],\n commands: [],\n publicRuleIds: NOTEBOOK_RULE_IDS,\n };\n\n constructor(readonly module = new NotebookModule()) { super(); }\n\n override async init(ctx: LifecycleContext, input: NotebookRecipeInput): Promise<NotebookRecipeResult> {\n const resolved = resolvedForPlan(input.plan);\n const notebookPlan = planNotebookForProjectInit(input.plan, input.mode);\n ctx.notebookPlan = notebookPlan;\n ctx.notebookRegistryDeclared = Boolean(resolved.project.notebook && typeof resolved.project.notebook === \"object\");\n const manifestNotebook = (resolved.manifest as ProjectManifest & { notebook?: ProjectNotebookConfigV1 }).notebook;\n ctx.notebookManifestBinding = manifestNotebook?.binding\n ? Object.freeze({ ...manifestNotebook.binding })\n : null;\n ctx.notebookStateRoot = this.module.stateRoot;\n return {\n recipeId: this.metadata.id,\n ok: true,\n dryRun: Boolean(ctx.dryRun),\n changedFiles: [],\n logs: [`notebook: ${notebookPlan.reason}`],\n errors: [],\n phases: [{ id: \"notebook.plan\", status: notebookPlan.remote_effect === \"reconcile\" ? \"planned\" : \"skipped\", changedFiles: [], message: notebookPlan.reason }],\n notebookPlan,\n };\n }\n\n async applyLocal(ctx: LifecycleContext, plan: ProjectInitPlan, notebookPlan: NotebookPlanV1): Promise<RecipeInitResult> {\n if (!plan.apply || ctx.dryRun || !notebookPlan.config.policy.enabled || notebookPlan.config.binding.state === \"disabled\") {\n return { recipeId: this.metadata.id, ok: true, dryRun: Boolean(ctx.dryRun), changedFiles: [], logs: [\"notebook: local skill/hooks skipped\"], errors: [], phases: [{ id: \"notebook.local\", status: \"skipped\", changedFiles: [], message: \"Notebook is disabled or this is a plan-only invocation\" }] };\n }\n // PJAN-82: do not mutate the operator's GLOBAL agent configuration on behalf\n // of a notebook that cannot do anything.\n //\n // remote_effect is \"none\" exactly when no endpoint is configured, and the\n // adjacent phases said so out loud:\n // notebook.plan skipped | no safe global endpoint configured\n // notebook.local changed | Canonical Project Notebook skill and hooks verified\n // The guard only consulted policy/binding, and the default policy is\n // enabled, so every `pj init` on this machine installed a global skill link\n // and rewrote ~/.claude/settings.json for a feature it had just declared\n // inert \u2014 which is what made a global-state defect reachable from 100% of\n // invocations. `pj notebook migrate --apply` still projects it on request.\n if (notebookPlan.remote_effect === \"none\") {\n const message = `Notebook has no configured endpoint (${notebookPlan.reason}); global skill and hook projection deferred to \\`pj notebook migrate --apply\\``;\n return { recipeId: this.metadata.id, ok: true, dryRun: false, changedFiles: [], logs: [`notebook: ${message}`], errors: [], phases: [{ id: \"notebook.local\", status: \"skipped\", changedFiles: [], message }] };\n }\n try {\n const env = integrationEnvironment(this.module, ctx);\n ctx.notebookStateRoot = notebookStateRoot(env);\n const applied = this.module.installIntegration(env);\n ctx.notebookObservation = Object.freeze(await prepareNotebookObservationResolved(this.module, resolvedForPlan(plan), notebookPlan.config, true, env));\n // PJAN-82: the global skill projection lives on the machine, not in this\n // repository. When it is owned elsewhere PJ\u00E1ngler leaves it alone and says\n // so; it must never be a reason to fail (and therefore roll back) the\n // project transaction that merely observed it.\n if (applied.blocked) {\n const advisory = `notebook: global skill projection left untouched \u2014 ${applied.blocked.summary}`;\n return {\n recipeId: this.metadata.id,\n ok: true,\n dryRun: false,\n changedFiles: applied.changedFiles,\n logs: [advisory, ...applied.blocked.details.map((detail) => `notebook: ${detail}`), `notebook: repair with ${applied.blocked.repair}`],\n errors: [],\n phases: [{ id: \"notebook.local\", status: \"skipped\", changedFiles: applied.changedFiles, message: advisory }],\n };\n }\n return {\n recipeId: this.metadata.id,\n ok: true,\n dryRun: false,\n changedFiles: applied.changedFiles,\n logs: [\"notebook: canonical skill and true SessionStart/SessionEnd hooks projected\"],\n errors: [],\n phases: [{ id: \"notebook.local\", status: applied.changedFiles.length ? \"changed\" : \"unchanged\", changedFiles: applied.changedFiles, message: \"Canonical Project Notebook skill and hooks verified\" }],\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { recipeId: this.metadata.id, ok: false, dryRun: false, changedFiles: [], logs: [], errors: [message], phases: [{ id: \"notebook.local\", status: \"failed\", changedFiles: [], message }] };\n }\n }\n\n async applyExternal(plan: ProjectInitPlan, notebookPlan: NotebookPlanV1): Promise<{ changedFiles: string[]; data: { created: boolean; adopted: boolean; notebook_id: string; overview_note_id: string; journals: RemoteMutationJournalV1[] } }> {\n if (notebookPlan.remote_effect !== \"reconcile\") return { changedFiles: [], data: { created: false, adopted: false, notebook_id: notebookPlan.config.binding.notebook_id ?? \"\", overview_note_id: notebookPlan.config.binding.overview_note_id ?? \"\", journals: [] } };\n const provisioned = await this.module.provisionResolved(resolvedForPlan(plan), notebookPlan.config);\n setBinding(plan, provisioned.binding);\n return { changedFiles: [], data: { ...provisioned.data, journals: provisioned.journals ?? [] } };\n }\n\n commitExternal(journals: RemoteMutationJournalV1[]): void {\n for (const journal of journals) commitReconciledRemoteMutation(this.module.stateRoot, journal);\n }\n\n refreshPlan(plan: ProjectInitPlan, notebookPlan: NotebookPlanV1): NotebookPlanV1 {\n const resolved = resolvedForPlan(plan);\n return Object.freeze({ ...notebookPlan, config: resolveEffectiveNotebookConfig(resolved) });\n }\n\n async observeExternal(plan: ProjectInitPlan, notebookPlan: NotebookPlanV1): Promise<NotebookObservationV1> {\n const resolved = resolvedForPlan(plan);\n // applyExternal mutates the in-memory plan and then projects the linked\n // binding into the Manifest. The immutable planning snapshot is now stale;\n // candidate proof must resolve the linked IDs from that updated state.\n return prepareNotebookObservationResolved(this.module, resolved, resolveEffectiveNotebookConfig(resolved), false);\n }\n\n protected printNextSteps(): void { /* Project and notebook CLI render structured next actions. */ }\n}\n", "import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { LifecycleAuditFinding, LifecycleContext, LifecycleMigrationResult, RecipeCheck } from \"../recipes/types\";\nimport { loadEffectiveNotebookConfig } from \"./config\";\nimport { canonicalJson } from \"./notes\";\nimport { normalizeNotebookError } from \"./output\";\nimport { captureAdmissionSummary, currentRetentionPressure, listCaptureReceipts, notebookStateRoot, pruneNotebookState } from \"./state\";\nimport type { NotebookObservationV1 } from \"./observation\";\n\nexport const NOTEBOOK_RULE_IDS = [\n \"notebook.configuration\",\n \"notebook.binding\",\n \"notebook.remote-notebook\",\n \"notebook.overview-note\",\n \"notebook.skill-installed\",\n \"notebook.hooks-projected\",\n \"notebook.capture-receipts\",\n] as const;\n\nfunction finding(id: string, title: string, status: LifecycleAuditFinding[\"status\"], summary: string, details: string[] = [], fixable = false): LifecycleAuditFinding {\n return { id, title, status, summary, details, fixable };\n}\n\nfunction result(check: LifecycleAuditFinding, status: LifecycleMigrationResult[\"status\"], summary: string, changedFiles: string[] = [], details: string[] = []): LifecycleMigrationResult {\n return { id: check.id, title: check.title, status, summary, changedFiles, details };\n}\n\nfunction manifestNotebook(repo: string): Record<string, unknown> | null {\n const path = join(repo, \".project.json\");\n if (!existsSync(path)) return null;\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as unknown;\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n const notebook = (parsed as Record<string, unknown>).notebook;\n return notebook && typeof notebook === \"object\" && !Array.isArray(notebook) ? notebook as Record<string, unknown> : null;\n } catch { return null; }\n}\n\nfunction enabled(ctx: LifecycleContext): boolean {\n if (ctx.notebookRegistryDeclared === false) return false;\n if (ctx.notebookPlan || manifestNotebook(ctx.repoRoot)) return true;\n try { return loadEffectiveNotebookConfig(ctx.repoRoot).binding.state !== \"disabled\"; }\n catch { return false; }\n}\n\nfunction registryDeclared(ctx: LifecycleContext): boolean {\n if (ctx.notebookRegistryDeclared !== undefined) return ctx.notebookRegistryDeclared;\n return enabled(ctx);\n}\n\nfunction resolvedConfig(ctx: LifecycleContext) {\n // PJAN-84: honour the run's registry. Falling back to projectRegistryPath()\n // here is what made `describe --registry` report notebook findings about the\n // DEFAULT registry while its identity block described the override.\n return ctx.notebookPlan?.config\n ?? (ctx.registryPath\n ? loadEffectiveNotebookConfig(ctx.repoRoot, ctx.registryPath)\n : loadEffectiveNotebookConfig(ctx.repoRoot));\n}\n\nfunction bindingProjection(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const raw = value as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n for (const key of [\"state\", \"notebook_id\", \"notebook_name\", \"overview_note_id\", \"blocked_reason\"] as const) {\n if (raw[key] !== undefined) result[key] = raw[key];\n }\n return result;\n}\n\nfunction manifestBinding(repo: string): Record<string, unknown> | null {\n const notebook = manifestNotebook(repo);\n return notebook ? bindingProjection(notebook.binding) : null;\n}\n\nfunction observation(ctx: LifecycleContext): Readonly<NotebookObservationV1> | undefined {\n return ctx.notebookObservation;\n}\n\nclass NotebookCheck implements RecipeCheck {\n constructor(\n readonly id: string,\n readonly title: string,\n private readonly auditFn: (ctx: LifecycleContext) => LifecycleAuditFinding,\n private readonly migrateFn?: (ctx: LifecycleContext, finding: LifecycleAuditFinding) => LifecycleMigrationResult,\n /** PJAN-84: \"host\" for the two rules about $HOME. Absent means \"project\". */\n readonly scope?: \"project\" | \"host\",\n ) {}\n audit(ctx: LifecycleContext): LifecycleAuditFinding { return this.auditFn(ctx); }\n migrate(ctx: LifecycleContext, current: LifecycleAuditFinding): LifecycleMigrationResult {\n return this.migrateFn?.(ctx, current) ?? result(current, \"blocked\", `${this.id} requires an explicit owned migration path`);\n }\n}\n\nfunction configurationAudit(ctx: LifecycleContext): LifecycleAuditFinding {\n if (!registryDeclared(ctx)) {\n if (!ctx.notebookFocusedAudit) return finding(\n \"notebook.configuration\",\n \"Notebook configuration\",\n \"skip\",\n \"Project Notebook is not declared; use the focused pj notebook audit surface to opt in\",\n );\n return finding(\n \"notebook.configuration\",\n \"Notebook configuration\",\n \"warn\",\n \"This registered repository has no authoritative Project Notebook declaration\",\n [\n `Run pj notebook migrate ${ctx.repoRoot} --apply to create a planned Registry binding and Manifest policy`,\n \"The declaration keeps SessionStart and SessionEnd capture disabled until explicitly enabled per project\",\n ],\n true,\n );\n }\n if (!enabled(ctx)) return finding(\"notebook.configuration\", \"Notebook configuration\", \"skip\", \"Project Notebook is not declared for this repository\");\n try {\n const config = resolvedConfig(ctx);\n if (!config.policy.enabled) return finding(\"notebook.configuration\", \"Notebook configuration\", \"skip\", \"Project Notebook is explicitly disabled\");\n if (!config.base_url) return finding(\"notebook.configuration\", \"Notebook configuration\", \"pass\", \"Project Notebook policy is valid; remote work remains planned until an endpoint is configured\", [\"Set Registry notebook.base_url to HTTPS or loopback HTTP before remote work\"], false);\n return finding(\"notebook.configuration\", \"Notebook configuration\", \"pass\", \"Notebook endpoint, auth name, policy, and finite limits are valid\");\n } catch (error) {\n return finding(\"notebook.configuration\", \"Notebook configuration\", \"fail\", normalizeNotebookError(error).message);\n }\n}\n\nfunction bindingAudit(ctx: LifecycleContext): LifecycleAuditFinding {\n if (!enabled(ctx)) return finding(\"notebook.binding\", \"Notebook binding\", \"skip\", \"Project Notebook is not declared for this repository\");\n const config = (() => { try { return resolvedConfig(ctx); } catch { return undefined; } })();\n if (!config) return finding(\"notebook.binding\", \"Notebook binding\", \"fail\", \"Notebook binding could not be resolved\");\n if (config.binding.state === \"disabled\") return finding(\"notebook.binding\", \"Notebook binding\", \"skip\", \"Project Notebook binding is disabled\");\n if (config.binding.state === \"linked\" && (!config.binding.notebook_id || !config.binding.overview_note_id)) {\n return finding(\"notebook.binding\", \"Notebook binding\", \"fail\", \"Linked binding is missing its notebook or Overview stable ID\", [], true);\n }\n const projected = ctx.notebookManifestBinding !== undefined\n ? bindingProjection(ctx.notebookManifestBinding)\n : manifestBinding(ctx.repoRoot);\n const authoritative = bindingProjection(config.binding);\n if (!projected || canonicalJson(projected) !== canonicalJson(authoritative)) {\n return finding(\n \"notebook.binding\",\n \"Notebook binding\",\n \"fail\",\n \"Manifest Notebook binding projection has drifted from the authoritative Project Registry binding\",\n [\"Run pj notebook migrate --apply to project Registry binding into .project.json\"],\n true,\n );\n }\n return finding(\"notebook.binding\", \"Notebook binding\", \"pass\", config.binding.state === \"linked\" ? \"Registry binding has stable notebook and Overview IDs\" : \"Planned binding is valid recovery state\");\n}\n\nfunction remoteAudit(ctx: LifecycleContext): LifecycleAuditFinding {\n if (!enabled(ctx)) return finding(\"notebook.remote-notebook\", \"Remote notebook\", \"skip\", \"Project Notebook is not declared for this repository\");\n const journals = (() => {\n try { return admission(ctx).unresolvedJournals.filter((item) => item.kind === \"notebook.create\"); }\n catch { return []; }\n })();\n if (journals.length) {\n return finding(\"notebook.remote-notebook\", \"Remote notebook\", \"warn\", \"Unresolved notebook-create journal requires marker reconciliation and durable Registry ownership\", journalDetails(journals), true);\n }\n const observed = observation(ctx);\n if (!observed || observed.notebook_check.status === \"skip\") return finding(\"notebook.remote-notebook\", \"Remote notebook\", \"skip\", \"Remote notebook was not observed; no hidden network request was made\");\n if (observed.notebook_check.status === \"pass\" && observed.notebook) return finding(\"notebook.remote-notebook\", \"Remote notebook\", \"pass\", \"Stable notebook ID, marker, name, and archive state were observed exactly\");\n return finding(\n \"notebook.remote-notebook\",\n \"Remote notebook\",\n \"fail\",\n observed.error?.message ?? \"Remote notebook is missing, ambiguous, unavailable, or metadata-drifted\",\n observed.notebook_check.drift.map((item) => `${item.path}: ${item.reason}`),\n true,\n );\n}\n\nfunction overviewAudit(ctx: LifecycleContext): LifecycleAuditFinding {\n if (!enabled(ctx)) return finding(\"notebook.overview-note\", \"Overview note\", \"skip\", \"Project Notebook is not declared for this repository\");\n const config = (() => { try { return resolvedConfig(ctx); } catch { return undefined; } })();\n const logicalId = config ? `overview:v1:${config.project_slug}` : null;\n const journals = (() => {\n try { return admission(ctx).unresolvedJournals.filter((item) => item.kind === \"note.create\" && item.logical_marker === logicalId); }\n catch { return []; }\n })();\n if (journals.length) {\n return finding(\"notebook.overview-note\", \"Overview note\", \"warn\", \"Unresolved Overview-create journal requires stable-ID reconciliation and durable binding ownership\", journalDetails(journals), true);\n }\n const observed = observation(ctx);\n if (!observed || observed.remote_check === \"skip\") return finding(\"notebook.overview-note\", \"Overview note\", \"skip\", \"Overview was not observed; no hidden network request was made\");\n if (observed.overview?.present && observed.overview.member && observed.overview.envelope_owned && observed.overview.drift.length === 0) return finding(\"notebook.overview-note\", \"Overview note\", \"pass\", \"Bound Overview membership, project ownership, logical ID, and descriptor freshness were proved\");\n return finding(\"notebook.overview-note\", \"Overview note\", \"fail\", \"Overview is missing, foreign, or drifted\", observed.overview?.drift.map((item) => `${item.path}: ${item.reason}`) ?? [], true);\n}\n\n/**\n * PJAN-82: a host-owned skill projection is not a repository defect.\n *\n * `~/.agents/skills` belongs to the machine, not to the repo being audited. When\n * it is owned elsewhere (a Skillex fanout that has drifted, or a deliberately\n * customized path) no amount of work in this repository can change it, so\n * reporting `fail` made every project on the machine fail at once \u2014 and, because\n * `auditRecipes` treats anything that is not pass/skip as not-ok and\n * `ProjectRecipe` turns a not-ok postcondition audit into a transaction error,\n * that host state was enough to fail (and roll back) a brand-new project.\n * These are reported as `skip` carrying the exact drift and the repair command.\n */\nfunction hostBlockFinding(id: string, title: string, block: NonNullable<NotebookObservationV1[\"skill_host_block\"]>): LifecycleAuditFinding {\n return finding(id, title, \"skip\", `Host skill projection is owned outside PJ\u00E1ngler: ${block.summary}`, [...block.details, `Repair: ${block.repair}`], false);\n}\n\nfunction skillAudit(ctx: LifecycleContext): LifecycleAuditFinding {\n if (!enabled(ctx)) return finding(\"notebook.skill-installed\", \"Project Notebook skill\", \"skip\", \"Project Notebook is not declared for this repository\");\n const observed = observation(ctx);\n if (observed?.skill_installed === true) return finding(\"notebook.skill-installed\", \"Project Notebook skill\", \"pass\", \"Digest-verified Project Notebook skill is installed\");\n if (observed?.skill_host_block) return hostBlockFinding(\"notebook.skill-installed\", \"Project Notebook skill\", observed.skill_host_block);\n if (observed?.skill_installed === false) return finding(\"notebook.skill-installed\", \"Project Notebook skill\", \"fail\", \"Digest-verified Project Notebook skill is not installed\", [\"Run pj notebook migrate --apply\"], true);\n return finding(\"notebook.skill-installed\", \"Project Notebook skill\", \"skip\", \"Skill installation was not observed; no global path was read\", [], true);\n}\n\nfunction hooksAudit(ctx: LifecycleContext): LifecycleAuditFinding {\n if (!enabled(ctx)) return finding(\"notebook.hooks-projected\", \"Project Notebook hooks\", \"skip\", \"Project Notebook is not declared for this repository\");\n const observed = observation(ctx);\n if (observed?.hooks_projected === true) return finding(\"notebook.hooks-projected\", \"Project Notebook hooks\", \"pass\", \"True SessionStart and SessionEnd hook entries are projected once\");\n if (observed?.skill_host_block) return hostBlockFinding(\"notebook.hooks-projected\", \"Project Notebook hooks\", observed.skill_host_block);\n if (observed?.hooks_projected === false) return finding(\"notebook.hooks-projected\", \"Project Notebook hooks\", \"fail\", \"Canonical true-boundary hooks are missing, duplicated, or drifted\", [\"Run pj notebook migrate --apply\"], true);\n return finding(\"notebook.hooks-projected\", \"Project Notebook hooks\", \"skip\", \"Hook projection was not observed; no global settings file was read\", [], true);\n}\n\nfunction stateRoot(ctx: LifecycleContext): string {\n return ctx.notebookStateRoot ?? notebookStateRoot({ HOME: ctx.homeDir });\n}\n\nfunction admission(ctx: LifecycleContext) {\n const config = resolvedConfig(ctx);\n return captureAdmissionSummary(stateRoot(ctx), config.project_slug, config.limits);\n}\n\nfunction journalDetails(journals: ReturnType<typeof admission>[\"unresolvedJournals\"]): string[] {\n return journals.map((item) => `${item.operation_id}: ${item.result_category}; ${item.next_action}; run pj notebook audit --json, then retry the originating action once`);\n}\n\nfunction captureAudit(ctx: LifecycleContext): LifecycleAuditFinding {\n if (!enabled(ctx)) return finding(\"notebook.capture-receipts\", \"Capture receipts\", \"skip\", \"Project Notebook is not declared for this repository\");\n try {\n const config = resolvedConfig(ctx);\n const summary = captureAdmissionSummary(stateRoot(ctx), config.project_slug, config.limits);\n if (summary.unmeasurable_entry_count) return finding(\"notebook.capture-receipts\", \"Capture receipts\", \"fail\", \"Capture state-integrity prevents exact admission proof\", summary.integrity_entries.map((item) => `${item.entry_id}: ${item.reason}`), true);\n const overviewLogicalId = `overview:v1:${config.project_slug}`;\n const actionJournals = summary.unresolvedJournals.filter((item) => item.kind === \"note.create\" && item.logical_marker !== overviewLogicalId);\n if (actionJournals.length) {\n const succeeded = new Map(listCaptureReceipts(stateRoot(ctx), config.project_slug, config.limits, \"succeeded\").map((receipt) => [receipt.session_key, receipt]));\n const recoverable = actionJournals.filter((journal) => {\n const receipt = journal.session_key ? succeeded.get(journal.session_key) : undefined;\n if (!receipt || journal.state !== \"reconciled\" || journal.binding_id !== config.binding.notebook_id || journal.candidate_ids.length !== 1) return false;\n const index = receipt.note_logical_ids.indexOf(journal.logical_marker);\n return index >= 0 && receipt.remote_note_ids[index] === journal.candidate_ids[0];\n });\n return finding(\n \"notebook.capture-receipts\",\n \"Capture receipts\",\n \"warn\",\n recoverable.length\n ? \"Receipt-proven reconciled capture journals can be finalized locally; other session, document, or user-note journals still require explicit originating-action recovery\"\n : \"Unresolved session, document, or user-note mutations require explicit originating-action recovery; retention cleanup cannot resolve them\",\n [\n ...journalDetails(actionJournals),\n ...(recoverable.length ? [`Run pj notebook migrate ${config.repo_path} --apply to finalize ${recoverable.length} receipt-proven journal(s) without remote work`] : []),\n ],\n recoverable.length > 0,\n );\n }\n const pressure = currentRetentionPressure(summary);\n if (pressure.length) return finding(\"notebook.capture-receipts\", \"Capture receipts\", \"warn\", \"Current unresolved capture usage is under retention pressure\", pressure.map((item) => item.session_key ? `${item.reason}: ${item.session_key}` : item.reason), false);\n return finding(\"notebook.capture-receipts\", \"Capture receipts\", \"pass\", \"Capture receipts are measurable; unresolved work is preserved and within admission caps\", summary.active_refusals.map((item) => `capture-refused-history: ${item.session_key}`));\n } catch (error) {\n return finding(\"notebook.capture-receipts\", \"Capture receipts\", \"fail\", normalizeNotebookError(error).message);\n }\n}\n\nexport function createNotebookChecks(): readonly RecipeCheck[] {\n return [\n new NotebookCheck(\"notebook.configuration\", \"Notebook configuration\", configurationAudit),\n new NotebookCheck(\"notebook.binding\", \"Notebook binding\", bindingAudit),\n new NotebookCheck(\"notebook.remote-notebook\", \"Remote notebook\", remoteAudit),\n new NotebookCheck(\"notebook.overview-note\", \"Overview note\", overviewAudit),\n // PJAN-84: host-scoped. These describe $HOME/.agents/skills and\n // $HOME/.claude/settings.json \u2014 the machine's shared agent configuration.\n // No work in the audited repository can change either, and reporting them as\n // the repository's failure is what let one drifted symlink fail (and roll\n // back) a brand-new project, and every project on the box at once.\n new NotebookCheck(\"notebook.skill-installed\", \"Project Notebook skill\", skillAudit, undefined, \"host\"),\n new NotebookCheck(\"notebook.hooks-projected\", \"Project Notebook hooks\", hooksAudit, undefined, \"host\"),\n new NotebookCheck(\"notebook.capture-receipts\", \"Capture receipts\", captureAudit, (ctx, current) => {\n if (ctx.dryRun) return result(current, \"applied\", \"Would expire only elapsed succeeded receipts and elapsed unreferenced receiptless state\");\n try {\n const config = resolvedConfig(ctx);\n const removed = pruneNotebookState(stateRoot(ctx), config.project_slug, config.limits);\n return result(current, removed.length ? \"applied\" : \"noop\", removed.length ? \"Expired only eligible owned capture state\" : \"No eligible capture state required cleanup\", removed);\n } catch (error) {\n return result(current, \"blocked\", normalizeNotebookError(error).message);\n }\n }),\n ];\n}\n", "import { randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { isPgRegistryEnabled, PgRegistryStore, pgRegistryConfigFromEnv, projectRegistryPath, resolvePjanglerRoot, type ProjectRegistry } from \"../project/index\";\nimport type { RegistryStore } from \"../project/RegistryStore\";\nimport {\n loadEffectiveNotebookConfig,\n notebookDisplayName,\n persistProjectNotebookDeclaration,\n persistProjectNotebookBinding,\n requireRemoteNotebookConfig,\n resolveEffectiveNotebookConfig,\n resolveNotebookProject,\n resolveNotebookProjectBySlug,\n type ResolvedNotebookProjectV1,\n} from \"./config\";\nimport { OpenNotebookClient } from \"./open-notebook-client\";\nimport {\n canonicalJson,\n noteDetail,\n noteSummary,\n parseNoteEnvelope,\n searchNotesLocally,\n userNoteLogicalId,\n withNoteEnvelope,\n} from \"./notes\";\nimport { compileOverviewArtifact, compileOverviewDescriptor, overviewDescriptorDrift, renderOverviewContent } from \"./overview\";\nimport { reconcileManagedNote, reconcileProjectNotebook } from \"./reconcile\";\nimport {\n commitReconciledRemoteMutation,\n findActiveRemoteMutation,\n listRemoteMutationJournals,\n mutationInputDigest,\n remoteMutationJournalPath,\n type RemoteMutationJournalV1,\n} from \"./remote-mutation-journal\";\nimport { captureAdmissionSummary, notebookStateRoot, publicCaptureAdmissionSummary } from \"./state\";\nimport { authorizeCaptureRetry, listCaptureReceipts, pruneNotebookState, receiptSummary } from \"./state\";\nimport { validateCommittedGitRef } from \"./git-evidence\";\nimport { prepareNotebookObservation } from \"./observation\";\nimport { createNotebookChecks } from \"./checks\";\nimport { homedir } from \"node:os\";\nimport { installProjectNotebookIntegration, repairProjectNotebookSkillProjection, type ProjectNotebookHostBlockV1, type ProjectNotebookSkillRepairV1 } from \"./hooks\";\nimport {\n NOTEBOOK_POLICY_VERSION,\n NOTEBOOK_SCHEMA_VERSION,\n NotebookError,\n type CaptureAdmissionSummaryV1,\n type EffectiveNotebookConfigV1,\n type NoteDetailV1,\n type NoteSummaryV1,\n type NotebookFindingV1,\n type NotebookHealth,\n type OpenNotebookNotebookV1,\n type OpenNotebookNoteV1,\n type PjanglerNoteEnvelopeV1,\n type ProjectNotebookBindingV1,\n} from \"./types\";\n\nexport interface NotebookModuleOptions {\n registryPath?: string;\n stateRoot?: string;\n env?: NodeJS.ProcessEnv;\n fetch?: typeof globalThis.fetch;\n clientFactory?: (config: EffectiveNotebookConfigV1) => OpenNotebookClient;\n registryStore?: Pick<RegistryStore, \"save\">;\n}\n\ninterface ModuleContext {\n resolved: ResolvedNotebookProjectV1;\n config: EffectiveNotebookConfigV1;\n client?: OpenNotebookClient;\n}\n\ninterface PageCursorV1 {\n schema_version: 1;\n notebook_id: string;\n updated_at: string;\n id: string;\n}\n\nfunction decodeCursor(cursor: string): PageCursorV1 {\n try {\n const value = JSON.parse(Buffer.from(cursor, \"base64url\").toString(\"utf8\")) as unknown;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"shape\");\n const item = value as Partial<PageCursorV1>;\n if (item.schema_version !== 1 || !item.notebook_id || typeof item.updated_at !== \"string\" || typeof item.id !== \"string\") throw new Error(\"shape\");\n return item as PageCursorV1;\n } catch {\n throw new NotebookError(\"INVALID_INPUT\", \"Malformed or incompatible notebook cursor\");\n }\n}\n\nfunction encodeCursor(value: PageCursorV1): string {\n return Buffer.from(canonicalJson(value), \"utf8\").toString(\"base64url\");\n}\n\nfunction sortedNotes(notes: readonly OpenNotebookNoteV1[]): OpenNotebookNoteV1[] {\n const timestamp = (value: string | null): number => {\n const parsed = Date.parse(value ?? \"\");\n return Number.isFinite(parsed) ? parsed : Number.NEGATIVE_INFINITY;\n };\n return [...notes].sort((a, b) =>\n timestamp(b.updated_at) - timestamp(a.updated_at)\n || a.id.localeCompare(b.id, \"en\"));\n}\n\nfunction bindingNotebook(config: EffectiveNotebookConfigV1): { notebookId: string; overviewId?: string } {\n if (config.binding.state !== \"linked\" || !config.binding.notebook_id) throw new NotebookError(\"NOT_CONFIGURED\", \"Project Notebook binding is not linked\");\n return { notebookId: config.binding.notebook_id, overviewId: config.binding.overview_note_id };\n}\n\nfunction ensureText(value: string, label: string, maxBytes: number): string {\n if (!value.trim()) throw new NotebookError(\"INVALID_INPUT\", `${label} must not be empty`);\n if (Buffer.byteLength(value, \"utf8\") > maxBytes) throw new NotebookError(\"INVALID_INPUT\", `${label} exceeds the configured ceiling`);\n return value;\n}\n\nfunction ensureTitle(value: string, label = \"Note title\"): string {\n ensureText(value, label, 4_096);\n if (/[\\u0000-\\u001f\\u007f]/u.test(value)) throw new NotebookError(\"INVALID_INPUT\", `${label} must not contain control characters`);\n return value;\n}\n\nfunction ensureFinalNoteContent(value: string, maxBytes: number): string {\n if (Buffer.byteLength(value, \"utf8\") > maxBytes) throw new NotebookError(\"INVALID_INPUT\", \"Final managed note content including its ownership envelope exceeds the configured ceiling\");\n return value;\n}\n\nfunction getScoped(notes: readonly OpenNotebookNoteV1[], noteId: string): OpenNotebookNoteV1 {\n const note = notes.find((item) => item.id === noteId);\n if (!note) throw new NotebookError(\"NOT_FOUND\", `Note is not a proven member of this project notebook: ${noteId}`);\n return note;\n}\n\nexport class NotebookModule {\n readonly registryPath: string;\n readonly stateRoot: string;\n readonly environment: NodeJS.ProcessEnv;\n private readonly fetch?: typeof globalThis.fetch;\n private readonly clientFactory?: (config: EffectiveNotebookConfigV1) => OpenNotebookClient;\n private readonly registryStore?: Pick<RegistryStore, \"save\">;\n\n constructor(options: NotebookModuleOptions = {}) {\n this.registryPath = options.registryPath ?? projectRegistryPath(options.env);\n this.stateRoot = options.stateRoot ?? notebookStateRoot(options.env);\n this.environment = options.env ?? process.env;\n this.fetch = options.fetch;\n this.clientFactory = options.clientFactory;\n this.registryStore = options.registryStore;\n }\n\n installIntegration(env: NodeJS.ProcessEnv = this.environment): { changedFiles: string[]; blocked?: ProjectNotebookHostBlockV1 } {\n const installed = installProjectNotebookIntegration({ env });\n const home = env.HOME!;\n return {\n changedFiles: [\n ...(installed.skill.installed ? [installed.skill.path] : []),\n ...(installed.hooksChanged ? [resolve(env.PJ_PROJECT_NOTEBOOK_CLAUDE_SETTINGS ?? `${home}/.claude/settings.json`)] : []),\n ],\n ...(installed.blocked ? { blocked: installed.blocked } : {}),\n };\n }\n\n /** PJAN-82: reconcile a drifted canonical Skillex projection from the pinned export. */\n repairSkillProjection(apply: boolean, env: NodeJS.ProcessEnv = this.environment): ProjectNotebookSkillRepairV1 {\n return repairProjectNotebookSkillProjection({ env, apply });\n }\n\n repairBindingProjection(repo = process.cwd()): string[] {\n const ctx = this.context(repo, false);\n return persistProjectNotebookBinding(ctx.resolved, ctx.config.binding);\n }\n\n async declareNotebook(repo = process.cwd()): Promise<string[]> {\n const resolved = resolveNotebookProject(repo, this.registryPath);\n const changed = persistProjectNotebookDeclaration(resolved);\n await this.persistPostgresMirror(resolved.registry);\n return changed;\n }\n\n clientForConfig(config: EffectiveNotebookConfigV1, deadlineMonotonicMs?: number): OpenNotebookClient {\n requireRemoteNotebookConfig(config);\n return this.clientFactory?.(config) ?? new OpenNotebookClient(config, { fetch: this.fetch, env: this.environment, deadlineMonotonicMs });\n }\n\n context(repo = process.cwd(), remote = false): ModuleContext {\n const resolved = resolveNotebookProject(repo, this.registryPath);\n const config = resolveEffectiveNotebookConfig(resolved);\n if (!remote) return { resolved, config };\n requireRemoteNotebookConfig(config);\n const client = this.clientForConfig(config);\n return { resolved, config, client };\n }\n\n contextBySlug(projectSlug: string, remote = false): ModuleContext {\n const registry = resolveNotebookProjectBySlug(projectSlug, this.registryPath);\n const config = resolveEffectiveNotebookConfig(registry);\n if (!remote) return { resolved: registry, config };\n requireRemoteNotebookConfig(config);\n const client = this.clientForConfig(config);\n return { resolved: registry, config, client };\n }\n\n async status(repo = process.cwd(), localOnly = false): Promise<{\n config: EffectiveNotebookConfigV1;\n health: NotebookHealth;\n data: {\n policy: EffectiveNotebookConfigV1[\"policy\"];\n configuration_provenance: EffectiveNotebookConfigV1[\"configuration_provenance\"];\n remote_check: \"pass\" | \"fail\" | \"skip\";\n unresolved_receipt_count: number | null;\n unresolved_receipt_bytes: number | null;\n receipt_caps: { max_count: number; max_bytes: number };\n capture_admission: CaptureAdmissionSummaryV1;\n findings: NotebookFindingV1[];\n };\n }> {\n const audited = await this.audit(repo, localOnly);\n const admission = audited.data.capture_admission;\n const findings = audited.data.rules.filter((rule) => rule.status === \"fail\" || rule.status === \"warn\");\n return {\n config: audited.config,\n health: audited.health,\n data: {\n policy: audited.config.policy,\n configuration_provenance: audited.config.configuration_provenance,\n remote_check: audited.data.remote_check,\n unresolved_receipt_count: admission.unresolved_count,\n unresolved_receipt_bytes: admission.unresolved_bytes,\n receipt_caps: admission.receipt_caps,\n capture_admission: admission,\n findings,\n },\n };\n }\n\n async create(repo = process.cwd(), live = false): Promise<{ config: EffectiveNotebookConfigV1; health: NotebookHealth; data: { created: boolean; adopted: boolean; notebook_id: string; overview_note_id: string }; changedFiles: string[] }> {\n if (!live) throw new NotebookError(\"INVALID_INPUT\", \"notebook create requires --live\");\n const ctx = this.context(repo, true);\n const provisioned = await this.provisionResolved(ctx.resolved, ctx.config);\n const changedFiles = persistProjectNotebookBinding(ctx.resolved, provisioned.binding);\n await this.persistPostgresMirror(ctx.resolved.registry);\n for (const journal of provisioned.journals) commitReconciledRemoteMutation(this.stateRoot, journal);\n const config = loadEffectiveNotebookConfig(repo, this.registryPath);\n return { config, health: \"healthy\", data: provisioned.data, changedFiles };\n }\n\n private async persistPostgresMirror(registry: ProjectRegistry): Promise<void> {\n if (!this.registryStore && !isPgRegistryEnabled(this.environment)) return;\n let owned: PgRegistryStore | undefined;\n const store = this.registryStore ?? (owned = new PgRegistryStore(pgRegistryConfigFromEnv(this.environment)));\n try {\n await store.save(registry);\n } catch (error) {\n throw new NotebookError(\"SERVICE_UNAVAILABLE\", \"PostgreSQL Registry dual-write failed after YAML authority was durably preserved\", true, {}, { cause: error });\n } finally {\n await owned?.close();\n }\n }\n\n async provisionResolved(resolved: ResolvedNotebookProjectV1, config = resolveEffectiveNotebookConfig(resolved)): Promise<{\n binding: ProjectNotebookBindingV1;\n data: { created: boolean; adopted: boolean; notebook_id: string; overview_note_id: string };\n journals: RemoteMutationJournalV1[];\n }> {\n requireRemoteNotebookConfig(config);\n const client = this.clientForConfig(config);\n const reconciled = await reconcileProjectNotebook({\n stateRoot: this.stateRoot,\n projectSlug: config.project_slug,\n name: notebookDisplayName(resolved),\n description: resolved.project.description,\n client,\n });\n const compiledOverview = compileOverviewArtifact({ config, projectName: resolved.project.name, purpose: resolved.project.description });\n const overviewContent = renderOverviewContent({ config, descriptor: compiledOverview.descriptor, referenceContents: compiledOverview.reference_contents });\n const overview = await reconcileManagedNote({\n stateRoot: this.stateRoot,\n projectSlug: config.project_slug,\n notebookId: reconciled.notebook.id,\n logicalId: `overview:v1:${config.project_slug}`,\n title: \"Project Overview\",\n content: overviewContent,\n client,\n });\n const binding: ProjectNotebookBindingV1 = {\n ...config.binding,\n state: \"linked\",\n notebook_id: reconciled.notebook.id,\n notebook_name: reconciled.notebook.name,\n overview_note_id: overview.note.id,\n blocked_reason: undefined,\n };\n return {\n binding,\n data: {\n created: reconciled.created || overview.created,\n adopted: reconciled.adopted || overview.adopted,\n notebook_id: reconciled.notebook.id,\n overview_note_id: overview.note.id,\n },\n journals: [reconciled.journal, overview.journal],\n };\n }\n\n private async scoped(repo: string, deadlineMonotonicMs?: number): Promise<{ ctx: ModuleContext & { client: OpenNotebookClient }; notes: OpenNotebookNoteV1[]; notebookId: string }> {\n const local = this.context(repo, false);\n requireRemoteNotebookConfig(local.config);\n const ctx = { ...local, client: this.clientForConfig(local.config, deadlineMonotonicMs) } as ModuleContext & { client: OpenNotebookClient };\n const { notebookId } = bindingNotebook(ctx.config);\n const notes = await ctx.client.listNotes(notebookId);\n return { ctx, notes, notebookId };\n }\n\n async listNotes(repo = process.cwd(), limit = 50, cursor?: string): Promise<{ config: EffectiveNotebookConfigV1; data: { items: NoteSummaryV1[]; next_cursor: string | null } }> {\n const { ctx, notes, notebookId } = await this.scoped(repo);\n if (!Number.isSafeInteger(limit) || limit < 1 || limit > ctx.config.limits.list_max_items) throw new NotebookError(\"INVALID_INPUT\", \"Note list limit is outside configured bounds\");\n const ordered = sortedNotes(notes);\n let start = 0;\n if (cursor) {\n const decoded = decodeCursor(cursor);\n if (decoded.notebook_id !== notebookId) throw new NotebookError(\"INVALID_INPUT\", \"Notebook cursor belongs to a different binding\");\n const index = ordered.findIndex((item) => item.id === decoded.id && (item.updated_at ?? \"\") === decoded.updated_at);\n if (index < 0) throw new NotebookError(\"INVALID_INPUT\", \"Notebook cursor is stale or invalid\");\n start = index + 1;\n }\n const page = ordered.slice(start, start + limit);\n const last = page.at(-1);\n const nextCursor = start + page.length < ordered.length && last\n ? encodeCursor({ schema_version: 1, notebook_id: notebookId, updated_at: last.updated_at ?? \"\", id: last.id })\n : null;\n return { config: ctx.config, data: { items: page.map((item) => noteSummary(item, ctx.config.limits.excerpt_max_chars)), next_cursor: nextCursor } };\n }\n\n async addNote(repo: string, title: string, text: string): Promise<{ config: EffectiveNotebookConfigV1; data: { note: NoteDetailV1 } }> {\n const ctx = this.context(repo, true) as ModuleContext & { client: OpenNotebookClient };\n const { notebookId } = bindingNotebook(ctx.config);\n ensureTitle(title);\n ensureText(text, \"Note text\", ctx.config.limits.note_max_bytes);\n const operationDigest = mutationInputDigest({ kind: \"user-note\", notebook_id: notebookId, title, text });\n const active = findActiveRemoteMutation(this.stateRoot, ctx.config.project_slug, \"note.create\", operationDigest);\n if (active && active.logical_marker !== userNoteLogicalId(active.operation_id)) {\n throw new NotebookError(\"CONFLICT\", \"Active user-note mutation journal has an invalid operation-bound logical identity\");\n }\n const operationId = active?.operation_id ?? randomUUID();\n const logicalId = userNoteLogicalId(operationId);\n const envelope: PjanglerNoteEnvelopeV1 = {\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n project_slug: ctx.config.project_slug,\n kind: \"user-note\",\n logical_id: logicalId,\n policy_version: NOTEBOOK_POLICY_VERSION,\n };\n const content = ensureFinalNoteContent(withNoteEnvelope(envelope, text), ctx.config.limits.note_max_bytes);\n const result = await reconcileManagedNote({ stateRoot: this.stateRoot, projectSlug: ctx.config.project_slug, notebookId, logicalId, title, content, client: ctx.client, inputDigest: operationDigest, operationId });\n commitReconciledRemoteMutation(this.stateRoot, result.journal);\n return { config: ctx.config, data: { note: noteDetail(result.note, ctx.config.limits.note_max_bytes) } };\n }\n\n async getNote(repo: string, noteId: string): Promise<{ config: EffectiveNotebookConfigV1; data: { note: NoteDetailV1 } }> {\n const { ctx, notes, notebookId } = await this.scoped(repo);\n return { config: ctx.config, data: { note: noteDetail(getScoped(notes, noteId), ctx.config.limits.note_max_bytes) } };\n }\n\n async updateNote(repo: string, noteId: string, input: { title?: string; text: string }): Promise<{ config: EffectiveNotebookConfigV1; data: { note: NoteDetailV1 } }> {\n const { ctx, notes, notebookId } = await this.scoped(repo);\n const current = getScoped(notes, noteId);\n const parsed = parseNoteEnvelope(current.content);\n if (parsed?.envelope.project_slug !== undefined && parsed.envelope.project_slug !== ctx.config.project_slug) throw new NotebookError(\"CROSS_PROJECT\", \"Managed note envelope belongs to a different project\");\n if (parsed?.envelope.kind === \"overview\") throw new NotebookError(\"CONFLICT\", \"Use pj notebook overview --set-file to update the stable Overview note\");\n if (parsed && parsed.envelope.kind !== \"user-note\") throw new NotebookError(\"CONFLICT\", \"Derived document and session-capture notes must be regenerated from their evidence boundary\");\n ensureText(input.text, \"Note text\", ctx.config.limits.note_max_bytes);\n if (input.title !== undefined) ensureTitle(input.title);\n const content = ensureFinalNoteContent(parsed ? withNoteEnvelope(parsed.envelope, input.text) : input.text, ctx.config.limits.note_max_bytes);\n const updated = await ctx.client.updateOwnedNote(notebookId, noteId, { ...(input.title ? { title: input.title } : {}), content });\n return { config: ctx.config, data: { note: noteDetail(updated, ctx.config.limits.note_max_bytes) } };\n }\n\n async deleteNote(repo: string, noteId: string, confirmed: boolean): Promise<{ config: EffectiveNotebookConfigV1; data: { deleted_id: string } }> {\n if (!confirmed) throw new NotebookError(\"INVALID_INPUT\", \"Note deletion requires confirmation or --yes\");\n const { ctx, notes, notebookId } = await this.scoped(repo);\n const note = getScoped(notes, noteId);\n const parsed = parseNoteEnvelope(note.content);\n if (parsed && parsed.envelope.project_slug !== ctx.config.project_slug) throw new NotebookError(\"CROSS_PROJECT\", \"Managed note envelope belongs to a different project\");\n if (noteId === ctx.config.binding.overview_note_id || parsed?.envelope.kind === \"overview\") throw new NotebookError(\"CONFLICT\", \"The stable Project Overview note cannot be deleted\");\n await ctx.client.deleteOwnedNote(notebookId, noteId);\n return { config: ctx.config, data: { deleted_id: noteId } };\n }\n\n async searchNotes(repo: string, query: string, limit = 20): Promise<{ config: EffectiveNotebookConfigV1; data: ReturnType<typeof searchNotesLocally> }> {\n const { ctx, notes } = await this.scoped(repo);\n if (limit > ctx.config.limits.list_max_items) throw new NotebookError(\"INVALID_INPUT\", \"Search limit exceeds the configured ceiling\");\n return { config: ctx.config, data: searchNotesLocally(notes, query, limit, ctx.config.limits.excerpt_max_chars) };\n }\n\n async overview(repo: string, setText?: string, deadlineMonotonicMs?: number): Promise<{ config: EffectiveNotebookConfigV1; data: { note: NoteDetailV1; updated: boolean; drift: Array<{ path: string; reason: string }> } }> {\n const { ctx, notes, notebookId } = await this.scoped(repo, deadlineMonotonicMs);\n const overviewId = ctx.config.binding.overview_note_id;\n if (!overviewId) throw new NotebookError(\"NOT_CONFIGURED\", \"Overview note ID is not bound\");\n const current = getScoped(notes, overviewId);\n const parsed = parseNoteEnvelope(current.content);\n if (!parsed || parsed.envelope.kind !== \"overview\") throw new NotebookError(\"DRIFT_DETECTED\", \"Bound Overview note has no valid Overview envelope\");\n if (parsed.envelope.project_slug !== ctx.config.project_slug) throw new NotebookError(\"CROSS_PROJECT\", \"Bound Overview envelope belongs to a different project\");\n if (parsed.envelope.logical_id !== `overview:v1:${ctx.config.project_slug}`) throw new NotebookError(\"DRIFT_DETECTED\", \"Bound Overview logical identity does not match this project\");\n const descriptor = compileOverviewDescriptor({ config: ctx.config, projectName: ctx.resolved.project.name, purpose: ctx.resolved.project.description });\n const drift = overviewDescriptorDrift(parsed.envelope.overview_descriptor, descriptor);\n if (setText === undefined) return { config: ctx.config, data: { note: noteDetail(current, ctx.config.limits.note_max_bytes), updated: false, drift } };\n ensureText(setText, \"Overview text\", ctx.config.limits.note_max_bytes);\n const envelope: PjanglerNoteEnvelopeV1 = { ...parsed.envelope, overview_descriptor: descriptor, policy_version: NOTEBOOK_POLICY_VERSION };\n const content = ensureFinalNoteContent(withNoteEnvelope(envelope, setText), ctx.config.limits.note_max_bytes);\n const updated = await ctx.client.updateOwnedNote(notebookId, overviewId, { content });\n return { config: ctx.config, data: { note: noteDetail(updated, ctx.config.limits.note_max_bytes), updated: true, drift: [] } };\n }\n\n async audit(repo = process.cwd(), localOnly = false): Promise<{ config: EffectiveNotebookConfigV1; health: NotebookHealth; data: { rules: NotebookFindingV1[]; audited_at: string; remote_check: \"pass\" | \"fail\" | \"skip\"; capture_admission: CaptureAdmissionSummaryV1 } }> {\n const local = this.context(repo, false);\n const observed = await prepareNotebookObservation(this, repo, localOnly);\n const checks = createNotebookChecks();\n const lifecycle = {\n targetDir: local.config.repo_path,\n repoRoot: local.config.repo_path,\n pjanglerRoot: resolvePjanglerRoot(),\n homeDir: this.environment.HOME || homedir(),\n notebookStateRoot: this.stateRoot,\n notebookRegistryDeclared: Boolean(local.resolved.project.notebook && typeof local.resolved.project.notebook === \"object\"),\n notebookFocusedAudit: true,\n dryRun: true,\n force: false,\n notebookObservation: Object.freeze(observed),\n notebookPlan: Object.freeze({\n schema_version: 1 as const,\n project_slug: local.config.project_slug,\n repo_path: local.config.repo_path,\n mode: \"sync\" as const,\n config: local.config,\n remote_effect: \"none\" as const,\n reason: \"focused notebook audit\",\n }),\n };\n const rules = checks.map((check) => check.audit(lifecycle));\n const admission = publicCaptureAdmissionSummary(captureAdmissionSummary(this.stateRoot, local.config.project_slug, local.config.limits));\n return {\n config: local.config,\n health: observed.health,\n data: { rules, audited_at: new Date().toISOString(), remote_check: observed.remote_check, capture_admission: admission },\n };\n }\n\n pruneCaptureState(repo = process.cwd()): string[] {\n const ctx = this.context(repo, false);\n return pruneNotebookState(this.stateRoot, ctx.config.project_slug, ctx.config.limits);\n }\n\n recoverCaptureJournals(repo = process.cwd()): string[] {\n const ctx = this.context(repo, false);\n const receipts = listCaptureReceipts(this.stateRoot, ctx.config.project_slug, ctx.config.limits, \"succeeded\");\n const recovered: string[] = [];\n // Loading capture here avoids a module initialization cycle while keeping\n // migration a local, receipt-proofed operation with no remote calls.\n for (const receipt of receipts) {\n const ownership = new Map(receipt.note_logical_ids.map((logicalId, index) => [logicalId, receipt.remote_note_ids[index]]));\n const bindingId = ctx.config.binding.state === \"linked\" ? ctx.config.binding.notebook_id : undefined;\n if (!bindingId) continue;\n const journals = listRemoteMutationJournals(this.stateRoot, ctx.config.project_slug);\n for (const journal of journals) {\n if (journal.kind !== \"note.create\" || journal.session_key !== receipt.session_key || journal.state !== \"reconciled\"\n || journal.binding_id !== bindingId || journal.candidate_ids.length !== 1\n || ownership.get(journal.logical_marker) !== journal.candidate_ids[0]) continue;\n commitReconciledRemoteMutation(this.stateRoot, journal);\n recovered.push(remoteMutationJournalPath(this.stateRoot, ctx.config.project_slug, journal.operation_id));\n }\n }\n return [...new Set(recovered)].sort();\n }\n\n captureList(repo = process.cwd(), state?: string): { config: EffectiveNotebookConfigV1; data: { items: ReturnType<typeof receiptSummary>[]; next_cursor: null } } {\n const ctx = this.context(repo, false);\n return { config: ctx.config, data: { items: listCaptureReceipts(this.stateRoot, ctx.config.project_slug, ctx.config.limits, state), next_cursor: null } };\n }\n\n async captureRetry(repo: string, receiptId: string, baseline?: string): Promise<{ config: EffectiveNotebookConfigV1; data: { receipt: ReturnType<typeof receiptSummary> } }> {\n const ctx = this.context(repo, false);\n const queued = authorizeCaptureRetry({\n root: this.stateRoot,\n projectSlug: ctx.config.project_slug,\n receiptId,\n limits: ctx.config.limits,\n baseline,\n validateBaseline: (gitRef) => validateCommittedGitRef(ctx.config.repo_path, gitRef),\n });\n const { runCaptureWorker } = await import(\"./capture\");\n const completed = await runCaptureWorker(this, ctx.config.project_slug, queued.receipt_id);\n return { config: ctx.config, data: { receipt: receiptSummary(completed.receipt) } };\n }\n}\n", "import { spawnSync } from \"node:child_process\";\nimport { realpathSync } from \"node:fs\";\nimport { relative, resolve, sep } from \"node:path\";\nimport { encodeNoteEnvelope, overviewLogicalId, sha256Hex } from \"./notes\";\nimport { readSafeEvidenceText } from \"./git-evidence\";\nimport {\n NOTEBOOK_POLICY_VERSION,\n NOTEBOOK_SCHEMA_VERSION,\n NotebookError,\n type EffectiveNotebookConfigV1,\n type OverviewDescriptorV1,\n type OverviewReferenceV1,\n type PjanglerNoteEnvelopeV1,\n} from \"./types\";\n\nconst DEFAULT_OVERVIEW_REFERENCES = [\".project.json\", \"README.md\", \"AGENTS.md\", \"CLAUDE.md\", \"docs/architecture.md\"];\n\nfunction git(repo: string, args: string[], timeout: number): { ok: boolean; stdout: string } {\n const result = spawnSync(\"git\", args, { cwd: repo, encoding: \"utf8\", maxBuffer: 1024 * 1024, timeout, shell: false });\n return { ok: result.status === 0, stdout: result.stdout?.trim() ?? \"\" };\n}\n\nfunction normalizedReference(repo: string, value: string): string {\n if (!value || value.includes(\"\\0\") || value.startsWith(\"/\") || value.split(/[\\\\/]/u).includes(\"..\")) throw new NotebookError(\"INVALID_INPUT\", `Overview reference is not a contained relative path: ${value}`);\n const root = realpathSync(repo);\n const candidate = resolve(root, value);\n const rel = relative(root, candidate).split(sep).join(\"/\");\n if (!rel || rel === \"..\" || rel.startsWith(\"../\")) throw new NotebookError(\"INVALID_INPUT\", `Overview reference escapes the repository: ${value}`);\n return rel.normalize(\"NFC\");\n}\n\nfunction compileReference(config: EffectiveNotebookConfigV1, path: string): { reference: OverviewReferenceV1; content?: string } {\n const tracked = git(config.repo_path, [\"ls-files\", \"--error-unmatch\", \"--\", path], config.limits.overall_timeout_ms);\n if (!tracked.ok) return { reference: { path, status: \"missing\", reason: \"not-tracked\" } };\n const evidence = readSafeEvidenceText(config.repo_path, path, config.limits.source_file_max_bytes);\n if (evidence.status !== \"present\") return { reference: { path, status: \"missing\", reason: evidence.reason } };\n const revision = git(config.repo_path, [\"rev-parse\", `HEAD:${path}`], config.limits.overall_timeout_ms);\n return {\n reference: {\n path,\n status: \"present\",\n git_revision: revision.ok ? revision.stdout : \"working-tree-only\",\n content_sha256: evidence.content_sha256,\n },\n content: evidence.content,\n };\n}\n\nexport interface CompiledOverviewArtifactV1 {\n descriptor: OverviewDescriptorV1;\n reference_contents: Readonly<Record<string, string>>;\n}\n\nexport function compileOverviewArtifact(input: {\n config: EffectiveNotebookConfigV1;\n projectName: string;\n purpose?: string;\n}): CompiledOverviewArtifactV1 {\n const configured = input.config.policy.overview_references;\n const candidates = configured ?? DEFAULT_OVERVIEW_REFERENCES;\n const normalized = [...new Set(candidates.map((path) => normalizedReference(input.config.repo_path, path)))];\n const compiled = normalized.map((path) => compileReference(input.config, path));\n const selected = configured ? compiled : compiled.filter((item) => item.reference.status === \"present\");\n return {\n descriptor: {\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n project_slug: input.config.project_slug,\n project_name: input.projectName,\n purpose: input.purpose?.trim() || \"Purpose not yet documented\",\n references: selected.map((item) => item.reference),\n compiler_policy_version: NOTEBOOK_POLICY_VERSION,\n },\n reference_contents: Object.fromEntries(selected.flatMap((item) => item.content === undefined ? [] : [[item.reference.path, item.content]])),\n };\n}\n\nexport function compileOverviewDescriptor(input: {\n config: EffectiveNotebookConfigV1;\n projectName: string;\n purpose?: string;\n}): OverviewDescriptorV1 {\n return compileOverviewArtifact(input).descriptor;\n}\n\nexport function overviewDescriptorDrift(stored: OverviewDescriptorV1 | undefined, current: OverviewDescriptorV1): Array<{ path: string; reason: string }> {\n if (!stored) return [{ path: \"overview\", reason: \"missing-descriptor\" }];\n const drift: Array<{ path: string; reason: string }> = [];\n if (stored.project_slug !== current.project_slug || stored.project_name !== current.project_name || stored.purpose !== current.purpose || stored.compiler_policy_version !== current.compiler_policy_version) {\n drift.push({ path: \"overview\", reason: \"descriptor-metadata-changed\" });\n }\n const oldByPath = new Map(stored.references.map((item) => [item.path, item]));\n const currentPaths = new Set(current.references.map((item) => item.path));\n for (const reference of current.references) {\n const old = oldByPath.get(reference.path);\n if (!old) drift.push({ path: reference.path, reason: \"reference-added\" });\n else if (old.status !== reference.status || old.git_revision !== reference.git_revision || old.content_sha256 !== reference.content_sha256 || old.reason !== reference.reason) {\n drift.push({ path: reference.path, reason: \"reference-changed\" });\n }\n }\n for (const old of stored.references) if (!currentPaths.has(old.path)) drift.push({ path: old.path, reason: \"reference-removed\" });\n return drift.slice(0, 100);\n}\n\nexport function renderOverviewContent(input: { config: EffectiveNotebookConfigV1; descriptor: OverviewDescriptorV1; referenceContents: Readonly<Record<string, string>> }): string {\n const sections = [\n `# ${input.descriptor.project_name}`,\n \"\",\n input.descriptor.purpose,\n ];\n for (const reference of input.descriptor.references) {\n sections.push(\"\", `## ${reference.path}`);\n if (reference.status === \"missing\") {\n sections.push(`[${reference.reason ?? \"missing\"}]`);\n continue;\n }\n const content = input.referenceContents[reference.path];\n if (content === undefined || sha256Hex(content) !== reference.content_sha256) {\n sections.push(\"[reference content unavailable or changed during compilation]\");\n continue;\n }\n sections.push(content);\n }\n let body = sections.join(\"\\n\");\n if (Array.from(body).length > input.config.policy.overview_max_chars) {\n const suffix = \"\\n\\n[Overview truncated by project-notebook.v1 policy]\";\n const keep = Math.max(0, input.config.policy.overview_max_chars - Array.from(suffix).length);\n body = `${Array.from(body).slice(0, keep).join(\"\")}${suffix}`;\n }\n const envelope: PjanglerNoteEnvelopeV1 = {\n schema_version: NOTEBOOK_SCHEMA_VERSION,\n project_slug: input.config.project_slug,\n kind: \"overview\",\n logical_id: overviewLogicalId(input.config.project_slug),\n policy_version: NOTEBOOK_POLICY_VERSION,\n overview_descriptor: input.descriptor,\n };\n const marker = `${encodeNoteEnvelope(envelope)}\\n`;\n const available = input.config.limits.note_max_bytes - Buffer.byteLength(marker, \"utf8\");\n if (available <= 0) throw new NotebookError(\"INVALID_INPUT\", \"Overview ownership descriptor alone exceeds the configured note ceiling\");\n if (Buffer.byteLength(body, \"utf8\") > available) {\n const suffix = \"\\n\\n[Overview truncated by project-notebook.v1 byte policy]\";\n const budget = Math.max(0, available - Buffer.byteLength(suffix, \"utf8\"));\n let used = 0;\n const points: string[] = [];\n for (const point of body) {\n const bytes = Buffer.byteLength(point, \"utf8\");\n if (used + bytes > budget) break;\n points.push(point);\n used += bytes;\n }\n body = `${points.join(\"\")}${suffix}`;\n }\n return `${marker}${body}`;\n}\n", "import { parseNoteEnvelope } from \"./notes\";\nimport { compileOverviewDescriptor, overviewDescriptorDrift } from \"./overview\";\nimport type { NotebookModule } from \"./module\";\nimport type {\n EffectiveNotebookConfigV1,\n NotebookErrorCode,\n NotebookHealth,\n OpenNotebookNotebookV1,\n OpenNotebookNoteV1,\n} from \"./types\";\nimport { normalizeNotebookError } from \"./output\";\nimport { projectNotebookMarker } from \"./reconcile\";\nimport { notebookDisplayName, type ResolvedNotebookProjectV1 } from \"./config\";\nimport { inspectProjectNotebookIntegration, type ProjectNotebookHostBlockV1 } from \"./hooks\";\n\nexport interface NotebookObservationV1 {\n schema_version: 1;\n fetched_at: string;\n project_slug: string;\n binding_used: EffectiveNotebookConfigV1[\"binding\"];\n remote_check: \"pass\" | \"fail\" | \"skip\";\n health: NotebookHealth;\n auth_mode: EffectiveNotebookConfigV1[\"auth\"][\"mode\"];\n base_url_configured: boolean;\n notebook_check: {\n status: \"pass\" | \"fail\" | \"skip\";\n drift: Array<{ path: string; reason: string }>;\n };\n notebook: OpenNotebookNotebookV1 | null;\n scoped_notes: Array<Pick<OpenNotebookNoteV1, \"id\" | \"title\" | \"note_type\" | \"created_at\" | \"updated_at\"> & { envelope_logical_id: string | null }>;\n overview: { present: boolean; member: boolean; envelope_owned: boolean; drift: Array<{ path: string; reason: string }> } | null;\n error: { code: NotebookErrorCode; retryable: boolean; message: string } | null;\n skill_installed?: boolean | null;\n hooks_projected?: boolean | null;\n /**\n * PJAN-82: the host skill projection is owned outside PJ\u00E1ngler and was left\n * untouched. Audits report this as a machine-scoped advisory instead of\n * failing the repository for something the repository cannot fix.\n */\n skill_host_block?: ProjectNotebookHostBlockV1 | null;\n}\n\nexport interface NotebookPlanV1 {\n schema_version: 1;\n project_slug: string;\n repo_path: string;\n mode: \"create\" | \"sync\";\n config: EffectiveNotebookConfigV1;\n remote_effect: \"none\" | \"reconcile\";\n reason: string;\n}\n\nexport async function prepareNotebookObservation(module: NotebookModule, repo: string, localOnly = false): Promise<NotebookObservationV1> {\n const local = module.context(repo, false);\n return prepareNotebookObservationResolved(module, local.resolved, local.config, localOnly);\n}\n\nexport async function prepareNotebookObservationResolved(module: NotebookModule, resolved: ResolvedNotebookProjectV1, config: EffectiveNotebookConfigV1, localOnly = false, integrationEnv: NodeJS.ProcessEnv = module.environment): Promise<NotebookObservationV1> {\n const local = { resolved, config };\n const integration = inspectProjectNotebookIntegration(integrationEnv);\n const base = {\n schema_version: 1 as const,\n fetched_at: new Date().toISOString(),\n project_slug: local.config.project_slug,\n binding_used: { ...local.config.binding },\n auth_mode: local.config.auth.mode,\n base_url_configured: Boolean(local.config.base_url),\n skill_installed: integration.skill_installed,\n hooks_projected: integration.hooks_projected,\n skill_host_block: integration.blocked ?? null,\n };\n if (localOnly || !local.config.base_url) {\n return {\n ...base,\n remote_check: \"skip\",\n health: localOnly ? null : \"unconfigured\",\n notebook_check: { status: \"skip\", drift: [] },\n notebook: null,\n scoped_notes: [],\n overview: null,\n error: null,\n };\n }\n let notebookCheck: NotebookObservationV1[\"notebook_check\"] | null = null;\n let observedNotebook: OpenNotebookNotebookV1 | null = null;\n try {\n const client = module.clientForConfig(local.config);\n const notebooks = await client.listNotebooks();\n const id = local.config.binding.notebook_id;\n const notebook = id ? notebooks.find((item) => item.id === id) ?? null : null;\n const marker = projectNotebookMarker(local.config.project_slug);\n const markerCandidates = notebooks.filter((item) => item.description?.split(/\\r?\\n/u)[0] === marker);\n const notebookDrift: Array<{ path: string; reason: string }> = [];\n if (!id) notebookDrift.push({ path: \"binding.notebook_id\", reason: \"missing\" });\n if (!notebook) notebookDrift.push({ path: \"notebook\", reason: \"bound-id-not-found\" });\n if (markerCandidates.length === 0) notebookDrift.push({ path: \"notebook.marker\", reason: \"missing\" });\n else if (markerCandidates.length > 1) notebookDrift.push({ path: \"notebook.marker\", reason: `ambiguous:${markerCandidates.length}` });\n if (notebook && notebook.description?.split(/\\r?\\n/u)[0] !== marker) notebookDrift.push({ path: \"notebook.marker\", reason: \"bound-notebook-mismatch\" });\n if (notebook && notebook.name !== notebookDisplayName(local.resolved)) notebookDrift.push({ path: \"notebook.name\", reason: \"mismatch\" });\n if (notebook?.archived === true) notebookDrift.push({ path: \"notebook.archived\", reason: \"archived\" });\n notebookCheck = {\n status: notebookDrift.length === 0 ? \"pass\" : \"fail\",\n drift: notebookDrift,\n };\n observedNotebook = notebook;\n if (!notebook) {\n return { ...base, remote_check: \"fail\", health: local.config.binding.state === \"planned\" ? \"blocked\" : \"drifted\", notebook_check: notebookCheck, notebook: null, scoped_notes: [], overview: null, error: null };\n }\n const notes = await client.listNotes(notebook.id);\n const overviewId = local.config.binding.overview_note_id;\n const overviewNote = overviewId ? notes.find((item) => item.id === overviewId) : undefined;\n let overview: NotebookObservationV1[\"overview\"] = null;\n if (overviewId) {\n const parsed = overviewNote ? parseNoteEnvelope(overviewNote.content) : null;\n const current = compileOverviewDescriptor({ config: local.config, projectName: local.resolved.project.name, purpose: local.resolved.project.description });\n overview = {\n present: Boolean(overviewNote),\n member: Boolean(overviewNote),\n envelope_owned: Boolean(parsed && parsed.envelope.kind === \"overview\" && parsed.envelope.project_slug === local.config.project_slug && parsed.envelope.logical_id === `overview:v1:${local.config.project_slug}`),\n drift: parsed?.envelope.kind === \"overview\" ? overviewDescriptorDrift(parsed.envelope.overview_descriptor, current) : [{ path: \"overview\", reason: \"invalid-envelope\" }],\n };\n }\n const healthy = notebookCheck.status === \"pass\" && Boolean(overview?.present) && Boolean(overview?.envelope_owned) && overview!.drift.length === 0;\n return {\n ...base,\n remote_check: healthy ? \"pass\" : \"fail\",\n health: healthy ? \"healthy\" : \"drifted\",\n notebook_check: notebookCheck,\n notebook,\n scoped_notes: notes.map((note) => ({\n id: note.id,\n title: note.title,\n note_type: note.note_type,\n created_at: note.created_at,\n updated_at: note.updated_at,\n envelope_logical_id: parseNoteEnvelope(note.content)?.envelope.logical_id ?? null,\n })),\n overview,\n error: null,\n };\n } catch (error) {\n const normalized = normalizeNotebookError(error);\n return {\n ...base,\n remote_check: \"fail\",\n health: \"unavailable\",\n notebook_check: notebookCheck ?? { status: \"fail\", drift: [{ path: \"remote\", reason: `unavailable:${normalized.code}` }] },\n notebook: observedNotebook,\n scoped_notes: [],\n overview: null,\n error: { code: normalized.code, retryable: normalized.retryable, message: normalized.message.slice(0, 512) },\n };\n }\n}\n", "import { spawn, spawnSync } from \"node:child_process\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { chmodSync, closeSync, constants, copyFileSync, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { PJANGLER_VERSION } from \"../utils/version\";\nimport { captureGitSnapshot } from \"./git-evidence\";\nimport { sha256Hex } from \"./notes\";\nimport type { NotebookModule } from \"./module\";\nimport {\n admitCaptureReceipt,\n createOverviewClaim,\n createSessionBaseline,\n deriveSessionKey,\n readOverviewClaim,\n readSessionBaseline,\n} from \"./state\";\nimport { NOTEBOOK_POLICY_VERSION, NotebookError } from \"./types\";\n\nexport interface ClaudeSessionHookPayloadV1 {\n session_id?: unknown;\n cwd?: unknown;\n hook_event_name?: unknown;\n client_name?: unknown;\n source?: unknown;\n [key: string]: unknown;\n}\n\nexport interface NotebookHookResultV1 {\n exitCode: 0;\n stdout: string;\n stderr: string;\n outcome: \"captured\" | \"deduplicated\" | \"retention-pressure\" | \"state-integrity\" | \"primed\" | \"skipped\" | \"failed-open\";\n receiptId?: string;\n}\n\nexport interface NotebookHookRuntime {\n spawnWorker(receiptId: string, projectSlug: string): void;\n now(): Date;\n}\n\nexport function captureWorkerEnvironment(\n source: NodeJS.ProcessEnv,\n projectSlug: string,\n): NodeJS.ProcessEnv {\n const result: NodeJS.ProcessEnv = {\n PATH: \"/usr/bin:/bin\",\n PJ_NOTEBOOK_WORKER_PROJECT_SLUG: projectSlug,\n };\n for (const name of [\n \"HOME\",\n \"XDG_CONFIG_HOME\",\n \"XDG_STATE_HOME\",\n \"XDG_DATA_HOME\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n \"TZ\",\n \"OPEN_NOTEBOOK_PASSWORD\",\n ] as const) {\n const value = source[name];\n if (typeof value === \"string\" && value.length > 0) result[name] = value;\n }\n const registryPath = source.PJ_PROJECT_REGISTRY;\n if (typeof registryPath === \"string\" && isAbsolute(registryPath) && !registryPath.includes(\"\\0\") && Buffer.byteLength(registryPath, \"utf8\") <= 4_096) {\n result.PJ_PROJECT_REGISTRY = resolve(registryPath);\n }\n return result;\n}\n\nconst DEFAULT_RUNTIME: NotebookHookRuntime = {\n now: () => new Date(),\n spawnWorker(receiptId, projectSlug) {\n const entry = process.argv[1];\n if (!entry) return;\n const child = spawn(process.execPath, [entry, \"notebook\", \"worker\", \"capture\", \"--receipt-id\", receiptId], {\n detached: true,\n stdio: \"ignore\",\n env: captureWorkerEnvironment(process.env, projectSlug),\n });\n child.unref();\n },\n};\n\ninterface SkillExportManifestV1 {\n schema_version: 1;\n skill: \"project-notebook\";\n files: Array<{ path: string; sha256: string; mode: \"0644\" | \"0755\" }>;\n}\n\nfunction bundledSkillCandidates(): string[] {\n const candidates: string[] = [];\n let cursor = dirname(fileURLToPath(import.meta.url));\n for (let depth = 0; depth < 8; depth++) {\n candidates.push(join(cursor, \"dist\", \"assets\", \"project-notebook-skill\"), join(cursor, \"assets\", \"project-notebook-skill\"));\n const parent = dirname(cursor);\n if (parent === cursor) break;\n cursor = parent;\n }\n return [...new Set(candidates.map((candidate) => resolve(candidate)))];\n}\n\nfunction safeSkillRelativePath(value: string): boolean {\n if (!value || value.startsWith(\"/\") || value.includes(\"\\0\")) return false;\n const parts = value.split(\"/\");\n if (parts.some((part) => !part || part === \".\" || part === \"..\" || part === \".git\" || part === \"node_modules\" || part === \"__pycache__\")) return false;\n const leaf = parts.at(-1)!.toLowerCase();\n return !(/\\.(?:bak(?:-.+)?|orig|pid|sock|log|db-wal|db-shm)$/u.test(leaf) || leaf.endsWith(\"~\") || leaf === \".env\" || leaf.startsWith(\".env.\"));\n}\n\nfunction assertOwnedSkillTree(source: string): void {\n assertNoSymlinkComponents(source);\n const uid = typeof process.getuid === \"function\" ? process.getuid() : undefined;\n const walk = (directory: string) => {\n const directoryStat = lstatSync(directory);\n if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill source contains a non-directory component\");\n if (uid !== undefined && directoryStat.uid !== uid) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill source is not owned by the current user\");\n if (directoryStat.mode & 0o7002) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill source has unsafe directory mode bits\");\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n const path = join(directory, entry.name);\n const stat = lstatSync(path);\n if (stat.isSymbolicLink()) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill source contains a symlink\");\n if (entry.isDirectory()) walk(path);\n else if (!entry.isFile()) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill source contains a non-regular entry\");\n else {\n if (uid !== undefined && stat.uid !== uid) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill file is not owned by the current user\");\n if (stat.mode & 0o7002) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill file has unsafe mode bits\");\n }\n }\n };\n walk(source);\n}\n\nfunction enumerateSkillPayload(source: string): SkillExportManifestV1[\"files\"] {\n const result: SkillExportManifestV1[\"files\"] = [];\n const walk = (directory: string) => {\n for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name, \"en\"))) {\n const path = join(directory, entry.name);\n const rel = relative(source, path).split(sep).join(\"/\");\n // PJAN-84: `.source.yaml` is Skillex's provenance metadata about its own\n // extracted copy, rewritten on every re-sync. It is generated, like the\n // manifest and the checksums, and must not participate in the digest.\n if (!rel.includes(\"/\") && (rel === \"export-manifest.json\" || rel === \"SHA256SUMS\" || rel === \".source.yaml\")) continue;\n if (!safeSkillRelativePath(rel)) throw new NotebookError(\"CONFLICT\", `Project Notebook skill export path is unsafe: ${rel}`);\n const stat = lstatSync(path);\n if (stat.isSymbolicLink()) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill export contains a symlink\");\n if (entry.isDirectory()) walk(path);\n else if (entry.isFile()) {\n const expectedMode = rel.endsWith(\".sh\") || rel.startsWith(\"scripts/\") ? \"0755\" : \"0644\";\n result.push({ path: rel, sha256: createHash(\"sha256\").update(readFileSync(path)).digest(\"hex\"), mode: expectedMode });\n } else throw new NotebookError(\"CONFLICT\", \"Project Notebook skill export contains a non-regular entry\");\n }\n };\n walk(source);\n return result.sort((a, b) => a.path.localeCompare(b.path, \"en\"));\n}\n\nfunction parsePackedManifest(source: string): SkillExportManifestV1 | null {\n const manifestPath = join(source, \"export-manifest.json\");\n if (!existsSync(manifestPath)) return null;\n const value = JSON.parse(readFileSync(manifestPath, \"utf8\")) as unknown;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill export manifest is invalid\");\n const manifest = value as Partial<SkillExportManifestV1>;\n if (manifest.schema_version !== 1 || manifest.skill !== \"project-notebook\" || !Array.isArray(manifest.files)) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill export manifest is incompatible\");\n const paths = new Set<string>();\n for (const entry of manifest.files) {\n if (!entry || typeof entry.path !== \"string\" || !/^[a-f0-9]{64}$/u.test(entry.sha256) || !/^(?:0644|0755)$/u.test(entry.mode)) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill export entry is invalid\");\n if (!safeSkillRelativePath(entry.path) || paths.has(entry.path)) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill export path is unsafe or duplicated\");\n paths.add(entry.path);\n const path = join(source, ...entry.path.split(\"/\"));\n const stat = lstatSync(path);\n if (!stat.isFile() || stat.isSymbolicLink()) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill export contains a non-regular entry\");\n const actual = createHash(\"sha256\").update(readFileSync(path)).digest(\"hex\");\n if (actual !== entry.sha256) throw new NotebookError(\"CONFLICT\", `Project Notebook skill digest mismatch: ${entry.path}`);\n const actualMode = stat.mode & 0o777;\n const executable = entry.mode === \"0755\";\n // npm may apply the caller's cooperative umask and unpack 0644/0755 as\n // 0664/0775. The manifest mode is the exact installed-payload mode; source\n // verification accepts only that harmless group-write delta, requires the\n // owner executable bit when declared, and still rejects world/special bits\n // through assertOwnedSkillTree().\n if ((executable && (actualMode & 0o100) === 0) || (!executable && (actualMode & 0o111) !== 0)\n || (actualMode & ~((executable ? 0o755 : 0o644) | 0o020)) !== 0) {\n throw new NotebookError(\"CONFLICT\", `Project Notebook skill mode mismatch: ${entry.path}`);\n }\n }\n const actualPaths = enumerateSkillPayload(source).map((entry) => entry.path);\n if (JSON.stringify(actualPaths) !== JSON.stringify(manifest.files.map((entry) => entry.path))) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill manifest does not exactly enumerate its payload\");\n const sums = `${manifest.files.map((entry) => `${entry.sha256} ${entry.path}`).join(\"\\n\")}\\n`;\n if (!existsSync(join(source, \"SHA256SUMS\")) || readFileSync(join(source, \"SHA256SUMS\"), \"utf8\") !== sums) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill SHA256SUMS is missing or stale\");\n return manifest as SkillExportManifestV1;\n}\n\nfunction expectedPackedSkill(): { source: string; manifest: SkillExportManifestV1; digest: string } {\n for (const candidate of bundledSkillCandidates()) {\n if (!existsSync(join(candidate, \"export-manifest.json\"))) continue;\n assertOwnedSkillTree(candidate);\n const manifest = parsePackedManifest(candidate);\n if (!manifest) continue;\n const digest = createHash(\"sha256\").update(JSON.stringify(manifest)).digest(\"hex\");\n return { source: candidate, manifest, digest };\n }\n throw new NotebookError(\"NOT_CONFIGURED\", \"PJ\u00E1ngler package has no verified Project Notebook skill export\");\n}\n\nfunction isCanonicalSkillexProjectionPath(path: string): boolean {\n return resolve(path).split(sep).join(\"/\").endsWith(\"/all-skills/project-notebook\");\n}\n\nfunction isVerifiedCanonicalSkillexProjection(path: string): boolean {\n if (!isCanonicalSkillexProjectionPath(path)) return false;\n try { verifyProjectNotebookSkillExport(path); return true; }\n catch { return false; }\n}\n\n/**\n * PJAN-82: name the files that actually differ.\n *\n * `verifyProjectNotebookSkillExport` only ever said \"does not match the\n * package-pinned export digest\", which is unactionable: the operator is told a\n * tree of eleven files is wrong and nothing about which one. A single\n * uncommitted edit to one hook script in the Skillex working copy is what took\n * `pj init` down, and the only way to find it was to hand-diff the trees.\n */\nexport function describeProjectNotebookSkillDrift(source: string): string[] {\n let expected;\n try { expected = expectedPackedSkill(); }\n catch { return [\"the PJ\u00E1ngler package carries no verified Project Notebook export to compare against\"]; }\n let actual: SkillExportManifestV1[\"files\"];\n try {\n const absolute = resolve(source);\n const packed = parsePackedManifest(absolute);\n actual = packed?.files ?? enumerateSkillPayload(absolute);\n } catch (error) {\n return [boundedDiagnostic(error)];\n }\n const pinned = new Map(expected.manifest.files.map((entry) => [entry.path, entry]));\n const present = new Map(actual.map((entry) => [entry.path, entry]));\n const drift: string[] = [];\n for (const entry of actual) {\n const match = pinned.get(entry.path);\n if (!match) { drift.push(`${entry.path}: not part of the pinned export`); continue; }\n if (match.sha256 !== entry.sha256) drift.push(`${entry.path}: content differs from the pinned export`);\n else if (match.mode !== entry.mode) drift.push(`${entry.path}: mode ${entry.mode} differs from pinned ${match.mode}`);\n }\n for (const entry of expected.manifest.files) {\n if (!present.has(entry.path)) drift.push(`${entry.path}: missing from the projection`);\n }\n return drift.length ? drift.slice(0, 20) : [\"no per-file drift detected; the export enumeration itself differs\"];\n}\n\nexport function verifyProjectNotebookSkillExport(source: string): SkillExportManifestV1 {\n const absolute = resolve(source);\n assertOwnedSkillTree(absolute);\n const packed = parsePackedManifest(absolute);\n const actual = packed ?? { schema_version: 1 as const, skill: \"project-notebook\" as const, files: enumerateSkillPayload(absolute) };\n const expected = expectedPackedSkill();\n if (absolute !== expected.source && JSON.stringify(actual.files) !== JSON.stringify(expected.manifest.files)) {\n throw new NotebookError(\"CONFLICT\", \"Configured Project Notebook skill does not match the package-pinned export digest\");\n }\n return actual;\n}\n\nexport function resolveProjectNotebookSkillSource(env: NodeJS.ProcessEnv = process.env): string | null {\n if (env.PJ_PROJECT_NOTEBOOK_SKILL_ROOT) {\n const explicit = resolve(env.PJ_PROJECT_NOTEBOOK_SKILL_ROOT);\n if (!existsSync(join(explicit, \"SKILL.md\"))) throw new NotebookError(\"NOT_CONFIGURED\", \"Configured Project Notebook skill source is unavailable\");\n verifyProjectNotebookSkillExport(explicit);\n return explicit;\n }\n if (env.PJ_SKILLS_REGISTRY_ROOT) {\n const canonical = resolve(env.PJ_SKILLS_REGISTRY_ROOT, \"all-skills\", \"project-notebook\");\n if (existsSync(join(canonical, \"SKILL.md\"))) {\n verifyProjectNotebookSkillExport(canonical);\n return canonical;\n }\n }\n try { return expectedPackedSkill().source; }\n catch { return null; }\n}\n\n/**\n * PJAN-82: the reason PJ\u00E1ngler will not touch the host skill projection.\n *\n * This is an advisory about the operator's machine, never a project defect.\n * `repair` is the exact command that clears it.\n */\nexport interface ProjectNotebookHostBlockV1 {\n code: \"projection-drift\" | \"projection-foreign\" | \"skills-root-unsupported\";\n summary: string;\n details: string[];\n repair: string;\n /** The canonical Skillex projection directory, when one was identified and is repairable. */\n repairable_source?: string;\n}\n\ntype SkillsRootProbe =\n | { state: \"absent\" }\n | { state: \"plain\" }\n | { state: \"adopted\"; source: string }\n | { state: \"declined\"; block: ProjectNotebookHostBlockV1 };\n\nconst REPAIR_COMMAND = \"pj notebook skill --apply\";\n\n/**\n * PJAN-82: probe, do not enforce.\n *\n * This used to throw `CONFLICT \"Existing skills root is not a verified\n * canonical Skillex projection\"` for every non-adoptable host topology. That\n * exception travelled all the way up through `NotebookRecipe.applyLocal` into\n * `ProjectRecipe`'s error list and tripped the fresh-target rollback, so one\n * uncommitted edit in a Skillex working copy `rm -rf`'d a brand-new project\n * that had already been fully rendered. Adoption is opportunistic: declining to\n * adopt must read as \"leave the host alone\", not \"destroy the work\".\n */\nfunction probeCanonicalSkillexRootProjection(skillsRoot: string, link: string): SkillsRootProbe {\n let rootLink;\n try { rootLink = lstatSync(skillsRoot); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { state: \"absent\" };\n throw error;\n }\n if (!rootLink.isSymbolicLink()) return { state: \"plain\" };\n\n const decline = (code: ProjectNotebookHostBlockV1[\"code\"], summary: string, details: string[] = []): SkillsRootProbe =>\n ({ state: \"declined\", block: { code, summary, details, repair: REPAIR_COMMAND } });\n\n try {\n // Only the exact user-owned Skillex fanout topology may cross this\n // otherwise strict no-symlink boundary. Nothing is created or replaced\n // through the link: the existing projection is authenticated and kept.\n assertNoSymlinkComponents(dirname(skillsRoot));\n const uid = typeof process.getuid === \"function\" ? process.getuid() : undefined;\n if (uid !== undefined && rootLink.uid !== uid) throw new Error(\"owner\");\n\n const globalRoot = realpathSync(skillsRoot);\n assertNoSymlinkComponents(globalRoot);\n const globalStat = lstatSync(globalRoot);\n if (!globalStat.isDirectory() || globalStat.isSymbolicLink()) throw new Error(\"root-type\");\n if (uid !== undefined && globalStat.uid !== uid) throw new Error(\"root-owner\");\n if (globalStat.mode & 0o7002) throw new Error(\"root-mode\");\n const skillSetsRoot = dirname(globalRoot);\n if (basename(globalRoot) !== \"global\" || basename(skillSetsRoot) !== \"skill-sets\") throw new Error(\"layout\");\n\n const checkoutRoot = dirname(skillSetsRoot);\n const expectedSource = join(checkoutRoot, \"all-skills\", \"project-notebook\");\n const linkStat = lstatSync(link);\n if (!linkStat.isSymbolicLink()) throw new Error(\"projection-type\");\n if (uid !== undefined && linkStat.uid !== uid) throw new Error(\"projection-owner\");\n const projectedSource = realpathSync(link);\n if (projectedSource !== realpathSync(expectedSource)) throw new Error(\"projection-target\");\n if (!isVerifiedCanonicalSkillexProjection(projectedSource)) {\n return {\n state: \"declined\",\n block: {\n code: \"projection-drift\",\n summary: `Canonical Skillex projection of project-notebook has drifted from the version-pinned export at ${projectedSource}`,\n details: describeProjectNotebookSkillDrift(projectedSource),\n repair: REPAIR_COMMAND,\n repairable_source: projectedSource,\n },\n };\n }\n return { state: \"adopted\", source: projectedSource };\n } catch (error) {\n if (error instanceof NotebookError) {\n return decline(\"projection-drift\", error.message, describeProjectNotebookSkillDrift(link));\n }\n return decline(\n \"skills-root-unsupported\",\n `${skillsRoot} is a symlink but not the supported Skillex fanout topology (<checkout>/skill-sets/global with project-notebook projected from <checkout>/all-skills)`,\n [`probe rejected at: ${error instanceof Error ? error.message : String(error)}`],\n );\n }\n}\n\nexport interface ProjectNotebookSkillInstallV1 {\n installed: boolean;\n path: string;\n digest: string;\n /** Set when the host projection is owned elsewhere and was deliberately left untouched. */\n blocked?: ProjectNotebookHostBlockV1;\n}\n\nexport function installPackagedProjectNotebookSkill(input: { source?: string; env?: NodeJS.ProcessEnv } = {}): ProjectNotebookSkillInstallV1 {\n const env = input.env ?? process.env;\n const source = input.source ?? resolveProjectNotebookSkillSource(env);\n if (!source) throw new NotebookError(\"NOT_CONFIGURED\", \"Project Notebook skill source is unavailable\");\n const manifest = verifyProjectNotebookSkillExport(source);\n const digest = createHash(\"sha256\").update(JSON.stringify(manifest)).digest(\"hex\");\n const home = env.HOME;\n if (!home || !resolve(home).startsWith(\"/\")) throw new NotebookError(\"NOT_CONFIGURED\", \"A trusted HOME is required to install the Project Notebook skill\");\n const skillsRoot = join(home, \".agents\", \"skills\");\n const link = join(skillsRoot, \"project-notebook\");\n const probe = probeCanonicalSkillexRootProjection(skillsRoot, link);\n if (probe.state === \"adopted\") return { installed: false, path: link, digest };\n // A symlinked skills root PJ\u00E1ngler cannot authenticate is never written\n // through: the fall-through below would `mkdir` and no-symlink-assert the\n // root, which cannot succeed for a symlink. Report and leave it alone.\n if (probe.state === \"declined\") return { installed: false, path: link, digest, blocked: probe.block };\n const dataRoot = resolve(env.XDG_DATA_HOME || join(home, \".local\", \"share\"), \"pjangler\", \"skills\", \"project-notebook\");\n const payload = join(dataRoot, `${PJANGLER_VERSION}-${digest}`);\n assertNoSymlinkComponents(dirname(dataRoot), true);\n mkdirSync(dataRoot, { recursive: true, mode: 0o700 });\n assertNoSymlinkComponents(dataRoot);\n const dataStat = lstatSync(dataRoot);\n if (!dataStat.isDirectory() || dataStat.isSymbolicLink() || (typeof process.getuid === \"function\" && dataStat.uid !== process.getuid())) throw new NotebookError(\"CONFLICT\", \"Project Notebook skill data root is not a current-user directory\");\n chmodSync(dataRoot, 0o700);\n if (!existsSync(payload)) {\n const staging = join(dataRoot, `.staging-${randomUUID()}`);\n mkdirSync(staging, { recursive: false, mode: 0o700 });\n try {\n for (const entry of manifest.files) {\n const destination = join(staging, ...entry.path.split(\"/\"));\n mkdirSync(dirname(destination), { recursive: true, mode: 0o755 });\n copyFileSync(join(source, ...entry.path.split(\"/\")), destination);\n const mode = entry.mode === \"0755\" ? 0o755 : 0o644;\n chmodSync(destination, mode);\n const fd = openSync(destination, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));\n try {\n const current = fstatSync(fd);\n if (!current.isFile()) throw new NotebookError(\"CONFLICT\", `Installed skill entry is not regular: ${entry.path}`);\n fsyncSync(fd);\n } finally { closeSync(fd); }\n }\n writeFileSync(join(staging, \"export-manifest.json\"), `${JSON.stringify(manifest, null, 2)}\\n`, { mode: 0o644, flag: \"wx\" });\n writeFileSync(join(staging, \"SHA256SUMS\"), `${manifest.files.map((entry) => `${entry.sha256} ${entry.path}`).join(\"\\n\")}\\n`, { mode: 0o644, flag: \"wx\" });\n verifyProjectNotebookSkillExport(staging);\n renameSync(staging, payload);\n } finally {\n if (existsSync(staging)) rmSync(staging, { recursive: true, force: true });\n }\n } else {\n const stat = lstatSync(payload);\n if (!stat.isDirectory() || stat.isSymbolicLink()) throw new NotebookError(\"CONFLICT\", \"Installed Project Notebook payload is not a real directory\");\n verifyProjectNotebookSkillExport(payload);\n }\n assertNoSymlinkComponents(skillsRoot, true);\n mkdirSync(skillsRoot, { recursive: true, mode: 0o700 });\n assertNoSymlinkComponents(skillsRoot);\n let linkExists = existsSync(link);\n if (!linkExists) {\n try { lstatSync(link); linkExists = true; } catch { /* absent */ }\n }\n if (linkExists) {\n // PJAN-82: refusing to replace a foreign path is correct. Throwing about it\n // is not \u2014 the safety property is \"do not write\", and that is satisfied by\n // returning. A customized global skill path is an operator decision, not a\n // reason to fail the project transaction that happened to observe it.\n const foreign = (details: string[]): ProjectNotebookSkillInstallV1 => ({\n installed: false,\n path: link,\n digest,\n blocked: {\n code: \"projection-foreign\",\n summary: `${link} is customized or foreign; PJ\u00E1ngler will not replace it`,\n details,\n repair: REPAIR_COMMAND,\n },\n });\n const stat = lstatSync(link);\n if (!stat.isSymbolicLink()) return foreign([\"the path is a real file or directory, not a PJ\u00E1ngler-owned link\"]);\n const target = realpathSync(link);\n if (target !== realpathSync(payload) && !isVerifiedCanonicalSkillexProjection(target)) {\n return foreign(isCanonicalSkillexProjectionPath(target)\n ? describeProjectNotebookSkillDrift(target)\n : [`the link targets ${target}, which is neither the pinned payload nor a canonical Skillex projection`]);\n }\n try { verifyProjectNotebookSkillExport(target); }\n catch { return foreign(describeProjectNotebookSkillDrift(target)); }\n return { installed: false, path: link, digest };\n }\n symlinkSync(payload, link, \"dir\");\n collectSupersededPayloads(dataRoot, [payload, link]);\n return { installed: true, path: link, digest };\n}\n\n/**\n * PJAN-84: collect superseded payloads.\n *\n * Each re-pin materializes an immutable `<version>-<digest>` directory under the\n * XDG data root and nothing ever removed the previous one, so the store grew by\n * a full copy of the skill on every PJangler release and every content change.\n *\n * Exactly one payload can be in use: the hook command is the fixed path\n * `$HOME/.agents/skills/project-notebook`, a single link. So anything that is\n * neither the payload just written nor the target of that link is unreachable.\n * Deliberately narrow: only direct children of the data root whose names match\n * the `<version>-<64 hex>` shape are considered, a staging directory in flight is\n * skipped, and a failure to remove one is swallowed \u2014 reclaiming disk must never\n * be able to fail an install.\n */\nfunction collectSupersededPayloads(dataRoot: string, keep: readonly string[]): string[] {\n const kept = new Set<string>();\n for (const path of keep) {\n try { kept.add(realpathSync(path)); }\n catch { /* absent or unreadable: nothing to keep */ }\n }\n const removed: string[] = [];\n let entries: string[];\n try { entries = readdirSync(dataRoot); }\n catch { return removed; }\n for (const name of entries) {\n if (!/^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?-[0-9a-f]{64}$/u.test(name)) continue;\n const candidate = join(dataRoot, name);\n try {\n const stat = lstatSync(candidate);\n if (!stat.isDirectory() || stat.isSymbolicLink()) continue;\n if (kept.has(realpathSync(candidate))) continue;\n rmSync(candidate, { recursive: true, force: true });\n removed.push(candidate);\n } catch { /* leave anything that resists inspection or removal */ }\n }\n return removed;\n}\n\nexport interface ProjectNotebookSkillRepairV1 {\n status: \"clean\" | \"planned\" | \"repaired\" | \"blocked\";\n summary: string;\n source: string | null;\n drift: string[];\n changed_files: string[];\n}\n\n/**\n * PJAN-82: repair a drifted canonical Skillex projection from the pinned export.\n *\n * PJ\u00E1ngler owns these bytes: `dist/assets/project-notebook-skill` is tracked in\n * this repository and `<skillex>/all-skills/project-notebook` carries a\n * `.source.yaml` recording itself as an extraction of it. So the projection is\n * downstream, and reconciling it means writing PJ\u00E1ngler's pinned content back\n * over the local edit \u2014 not adopting the local edit.\n *\n * Only the exact manifest payload is written, and only into a path proved to be\n * the canonical projection through the same topology probe the installer uses.\n * Files not in the manifest are removed because their presence is itself the\n * drift; anything that is not a regular file blocks the repair rather than\n * being deleted.\n */\nexport function repairProjectNotebookSkillProjection(input: { env?: NodeJS.ProcessEnv; apply?: boolean } = {}): ProjectNotebookSkillRepairV1 {\n const env = input.env ?? process.env;\n const home = env.HOME;\n if (!home || !resolve(home).startsWith(\"/\")) throw new NotebookError(\"NOT_CONFIGURED\", \"A trusted HOME is required to repair the Project Notebook skill projection\");\n const skillsRoot = join(home, \".agents\", \"skills\");\n const link = join(skillsRoot, \"project-notebook\");\n const probe = probeCanonicalSkillexRootProjection(skillsRoot, link);\n if (probe.state === \"adopted\") return { status: \"clean\", summary: \"Canonical Skillex projection already matches the version-pinned export\", source: probe.source, drift: [], changed_files: [] };\n if (probe.state !== \"declined\") {\n return { status: \"clean\", summary: \"No canonical Skillex projection is in use; the version-pinned payload is installed directly\", source: null, drift: [], changed_files: [] };\n }\n const source = probe.block.repairable_source;\n if (!source) return { status: \"blocked\", summary: probe.block.summary, source: null, drift: probe.block.details, changed_files: [] };\n\n const expected = expectedPackedSkill();\n const wanted = new Set(expected.manifest.files.map((entry) => entry.path));\n assertOwnedSkillTree(source);\n const present: string[] = [];\n const walk = (directory: string) => {\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n const path = join(directory, entry.name);\n const rel = relative(source, path).split(sep).join(\"/\");\n if (entry.isDirectory()) { walk(path); continue; }\n if (!entry.isFile()) throw new NotebookError(\"CONFLICT\", `Refusing to repair a projection containing a non-regular entry: ${rel}`);\n // PJAN-84: `.source.yaml` is Skillex's provenance metadata about its own\n // extracted copy, rewritten on every re-sync. It is generated, like the\n // manifest and the checksums, and must not participate in the digest.\n if (!rel.includes(\"/\") && (rel === \"export-manifest.json\" || rel === \"SHA256SUMS\" || rel === \".source.yaml\")) continue;\n present.push(rel);\n }\n };\n walk(source);\n const stale = present.filter((rel) => !wanted.has(rel)).sort();\n const changed = expected.manifest.files\n .filter((entry) => {\n const path = join(source, ...entry.path.split(\"/\"));\n if (!existsSync(path)) return true;\n const stat = lstatSync(path);\n if (!stat.isFile()) return true;\n if (createHash(\"sha256\").update(readFileSync(path)).digest(\"hex\") !== entry.sha256) return true;\n const mode = stat.mode & 0o777;\n const executable = entry.mode === \"0755\";\n return (executable && (mode & 0o100) === 0) || (!executable && (mode & 0o111) !== 0);\n })\n .map((entry) => entry.path);\n\n const affected = [...new Set([...changed, ...stale])].sort();\n if (!affected.length) {\n return { status: \"blocked\", summary: `${source} does not verify against the pinned export, but no per-file difference was found`, source, drift: probe.block.details, changed_files: [] };\n }\n if (!input.apply) {\n return {\n status: \"planned\",\n summary: `Would restore ${affected.length} file(s) in ${source} from the version-pinned export`,\n source,\n drift: probe.block.details,\n changed_files: affected.map((rel) => join(source, ...rel.split(\"/\"))),\n };\n }\n for (const rel of stale) rmSync(join(source, ...rel.split(\"/\")), { force: true });\n for (const rel of changed) {\n const destination = join(source, ...rel.split(\"/\"));\n const entry = expected.manifest.files.find((item) => item.path === rel)!;\n mkdirSync(dirname(destination), { recursive: true, mode: 0o755 });\n copyFileSync(join(expected.source, ...rel.split(\"/\")), destination);\n chmodSync(destination, entry.mode === \"0755\" ? 0o755 : 0o644);\n }\n verifyProjectNotebookSkillExport(source);\n return {\n status: \"repaired\",\n summary: `Restored ${affected.length} file(s) in ${source} from the version-pinned export; commit the change in the Skillex checkout`,\n source,\n drift: probe.block.details,\n changed_files: affected.map((rel) => join(source, ...rel.split(\"/\"))),\n };\n}\n\nexport interface ProjectNotebookHookCheckV1 {\n ok: boolean;\n findings: Array<{ kind: string; event: string; message: string }>;\n}\n\nexport interface ProjectNotebookIntegrationObservationV1 {\n skill_installed: boolean;\n hooks_projected: boolean;\n details: string[];\n /**\n * PJAN-82: set when the global skill projection is owned outside PJ\u00E1ngler.\n * Audits must report this as a host advisory, never as a defect of the\n * repository being audited \u2014 the repository cannot fix it and must not be\n * failed for it.\n */\n blocked?: ProjectNotebookHostBlockV1;\n}\n\nexport function inspectProjectNotebookIntegration(env: NodeJS.ProcessEnv = process.env): ProjectNotebookIntegrationObservationV1 {\n const home = env.HOME;\n if (!home) return { skill_installed: false, hooks_projected: false, details: [\"HOME is unavailable\"] };\n const skillsRoot = join(home, \".agents\", \"skills\");\n const link = join(skillsRoot, \"project-notebook\");\n try {\n const expected = expectedPackedSkill();\n const dataRoot = resolve(env.XDG_DATA_HOME || join(home, \".local\", \"share\"), \"pjangler\", \"skills\", \"project-notebook\");\n const expectedPayload = join(dataRoot, `${PJANGLER_VERSION}-${expected.digest}`);\n const probe = probeCanonicalSkillexRootProjection(skillsRoot, link);\n if (probe.state === \"declined\") return { skill_installed: false, hooks_projected: false, details: probe.block.details, blocked: probe.block };\n const stat = lstatSync(link);\n if (!stat.isSymbolicLink()) {\n return {\n skill_installed: false,\n hooks_projected: false,\n details: [\"Project Notebook skill path is not an owned link\"],\n blocked: { code: \"projection-foreign\", summary: `${link} is not a PJ\u00E1ngler-owned link`, details: [\"the path is a real file or directory\"], repair: REPAIR_COMMAND },\n };\n }\n const source = realpathSync(link);\n const packedPayloadMatches = existsSync(expectedPayload) && source === realpathSync(expectedPayload);\n if (!packedPayloadMatches && !isVerifiedCanonicalSkillexProjection(source)) {\n const details = isCanonicalSkillexProjectionPath(source)\n ? describeProjectNotebookSkillDrift(source)\n : [`the link targets ${source}, which is neither the version-pinned payload nor a canonical Skillex projection`];\n return {\n skill_installed: false,\n hooks_projected: false,\n details,\n blocked: {\n code: isCanonicalSkillexProjectionPath(source) ? \"projection-drift\" : \"projection-foreign\",\n summary: `Project Notebook skill link targets a foreign or stale payload: ${source}`,\n details,\n repair: REPAIR_COMMAND,\n },\n };\n }\n verifyProjectNotebookSkillExport(source);\n const hooks = checkProjectNotebookHooks({ source, env });\n return {\n skill_installed: true,\n hooks_projected: hooks.ok,\n details: hooks.findings.map((finding) => `${finding.kind}:${finding.event}:${finding.message}`).slice(0, 20),\n };\n } catch (error) {\n return { skill_installed: false, hooks_projected: false, details: [boundedDiagnostic(error)] };\n }\n}\n\nfunction projectorArguments(source: string, command: \"check\" | \"install\", input: { target: string; stateHome?: string }): string[] {\n const script = join(source, \"scripts\", \"project-hooks.py\");\n const args = [script, command, \"--master\", join(source, \"hooks\", \"hooks.master.json\"), \"--fragment\", join(source, \"hooks\", \"claude.settings.json\"), \"--target\", input.target];\n if (command === \"check\") args.push(\"--json\");\n else if (input.stateHome) args.push(\"--state-home\", input.stateHome);\n return args;\n}\n\nfunction projectorEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const result: NodeJS.ProcessEnv = {\n PATH: \"/usr/bin:/bin\",\n LANG: \"C.UTF-8\",\n LC_ALL: \"C.UTF-8\",\n };\n if (env.HOME) result.HOME = env.HOME;\n if (env.XDG_STATE_HOME) result.XDG_STATE_HOME = env.XDG_STATE_HOME;\n return result;\n}\n\nexport function checkProjectNotebookHooks(input: { source?: string; env?: NodeJS.ProcessEnv; target?: string } = {}): ProjectNotebookHookCheckV1 {\n const env = input.env ?? process.env;\n const source = input.source ?? resolveProjectNotebookSkillSource(env);\n if (!source) throw new NotebookError(\"NOT_CONFIGURED\", \"Project Notebook skill source is unavailable; reinstall or rebuild PJangler\");\n verifyProjectNotebookSkillExport(source);\n const home = env.HOME;\n if (!home) throw new NotebookError(\"NOT_CONFIGURED\", \"HOME is required to check Project Notebook hooks\");\n const target = resolve(input.target ?? env.PJ_PROJECT_NOTEBOOK_CLAUDE_SETTINGS ?? join(home, \".claude\", \"settings.json\"));\n const result = spawnSync(\"/usr/bin/python3\", [\"-I\", ...projectorArguments(source, \"check\", { target })], { encoding: \"utf8\", env: projectorEnvironment(env), timeout: 5_000, maxBuffer: 1_048_576 });\n if (result.status !== 0 && result.status !== 1) throw new NotebookError(\"CONFLICT\", (result.stderr || \"Project Notebook projector check failed\").trim().slice(0, 512));\n try {\n const parsed = JSON.parse(result.stdout) as ProjectNotebookHookCheckV1;\n if (typeof parsed.ok !== \"boolean\" || !Array.isArray(parsed.findings)) throw new Error(\"shape\");\n return parsed;\n } catch {\n throw new NotebookError(\"INTERNAL_ERROR\", \"Project Notebook projector returned invalid check JSON\");\n }\n}\n\nexport function installProjectNotebookIntegration(input: { source?: string; env?: NodeJS.ProcessEnv; target?: string } = {}): { skill: ProjectNotebookSkillInstallV1; hooksChanged: boolean; blocked?: ProjectNotebookHostBlockV1 } {\n const env = input.env ?? process.env;\n const skill = installPackagedProjectNotebookSkill({ source: input.source, env });\n // The projected hook command is the fixed path $HOME/.agents/skills/\n // project-notebook/hooks/session-*.sh (see EVENT_WRAPPERS in the projector),\n // so projecting hooks while that path is unverified would arm a SessionStart\n // command pointing at content PJ\u00E1ngler has not authenticated. Report and stop.\n if (skill.blocked) return { skill, hooksChanged: false, blocked: skill.blocked };\n const source = realpathSync(skill.path);\n const home = env.HOME;\n if (!home) throw new NotebookError(\"NOT_CONFIGURED\", \"HOME is required to install Project Notebook hooks\");\n const target = resolve(input.target ?? env.PJ_PROJECT_NOTEBOOK_CLAUDE_SETTINGS ?? join(home, \".claude\", \"settings.json\"));\n const stateHome = resolve(env.XDG_STATE_HOME || join(home, \".local\", \"state\"));\n const result = spawnSync(\"/usr/bin/python3\", [\"-I\", ...projectorArguments(source, \"install\", { target, stateHome })], { encoding: \"utf8\", env: projectorEnvironment(env), timeout: 5_000, maxBuffer: 1_048_576 });\n if (result.status !== 0) {\n if (skill.installed) {\n try {\n const stat = lstatSync(skill.path);\n if (stat.isSymbolicLink() && realpathSync(skill.path) === source) unlinkSync(skill.path);\n } catch { /* preserve the projector error and never remove an unproved path */ }\n }\n throw new NotebookError(\"CONFLICT\", (result.stderr || \"Project Notebook hook installation failed\").trim().slice(0, 512));\n }\n return { skill, hooksChanged: /\\bchanged\\b/u.test(result.stdout) };\n}\n\nfunction boundedDiagnostic(value: unknown, max = 512): string {\n const message = value instanceof NotebookError\n ? value.message\n : \"Project Notebook encountered an unexpected internal error\";\n return message.replace(/[\\u0000-\\u001f\\u007f]/gu, \" \").replace(/\\s+/gu, \" \").slice(0, max);\n}\n\nfunction parsePayload(value: string, maxBytes: number): ClaudeSessionHookPayloadV1 {\n if (Buffer.byteLength(value, \"utf8\") > maxBytes) throw new NotebookError(\"INVALID_INPUT\", \"Hook payload exceeds its configured ceiling\");\n let parsed: unknown;\n try { parsed = JSON.parse(value) as unknown; }\n catch { throw new NotebookError(\"INVALID_INPUT\", \"Hook payload must be valid JSON\"); }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) throw new NotebookError(\"INVALID_INPUT\", \"Hook payload must be a JSON object\");\n return parsed as ClaudeSessionHookPayloadV1;\n}\n\nexport function readBoundedHookStdin(maxBytes: number, fd = 0): string {\n const chunks: Buffer[] = [];\n let total = 0;\n while (true) {\n const chunk = Buffer.allocUnsafe(Math.min(8_192, maxBytes + 1 - total));\n const count = readSync(fd, chunk, 0, chunk.length, null);\n if (count === 0) break;\n total += count;\n if (total > maxBytes) throw new NotebookError(\"INVALID_INPUT\", \"Hook stdin exceeds its configured ceiling\");\n chunks.push(chunk.subarray(0, count));\n }\n try { return new TextDecoder(\"utf-8\", { fatal: true }).decode(Buffer.concat(chunks, total)); }\n catch { throw new NotebookError(\"INVALID_INPUT\", \"Hook stdin must be valid UTF-8\"); }\n}\n\nfunction assertNoSymlinkComponents(path: string, allowMissing = false): void {\n const absolute = resolve(path);\n const root = parse(absolute).root;\n let cursor = root;\n for (const component of absolute.slice(root.length).split(sep).filter(Boolean)) {\n cursor = join(cursor, component);\n let stat;\n try { stat = lstatSync(cursor); }\n catch (error) {\n if (allowMissing && (error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw error;\n }\n if (stat.isSymbolicLink()) throw new NotebookError(\"INVALID_INPUT\", \"Hook payload path contains a symlink component\");\n }\n}\n\nexport function readHookPayload(input: { payloadFile?: string; stateRoot: string; maxBytes: number; stdin?: string }): { payload: ClaudeSessionHookPayloadV1; bytes: number } {\n if (!input.payloadFile) {\n const value = input.stdin ?? readBoundedHookStdin(input.maxBytes);\n return { payload: parsePayload(value, input.maxBytes), bytes: Buffer.byteLength(value, \"utf8\") };\n }\n const root = resolve(input.stateRoot);\n const path = resolve(input.payloadFile);\n const rel = relative(root, path);\n if (rel === \"..\" || rel.startsWith(`..${sep}`) || rel.startsWith(sep)) throw new NotebookError(\"INVALID_INPUT\", \"Hook payload file is outside Notebook XDG state\");\n assertNoSymlinkComponents(root);\n assertNoSymlinkComponents(path);\n const before = lstatSync(path);\n if (!before.isFile() || before.isSymbolicLink() || (before.mode & 0o777) !== 0o600 || before.nlink !== 1) throw new NotebookError(\"INVALID_INPUT\", \"Hook payload file must be a contained mode-0600 regular file\");\n if (typeof process.getuid === \"function\" && before.uid !== process.getuid()) throw new NotebookError(\"INVALID_INPUT\", \"Hook payload file must be owned by the current user\");\n if (before.size > input.maxBytes) throw new NotebookError(\"INVALID_INPUT\", \"Hook payload file exceeds its configured ceiling\");\n const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));\n try {\n const opened = fstatSync(fd);\n if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) throw new NotebookError(\"INVALID_INPUT\", \"Hook payload file changed while opening\");\n const value = readBoundedHookStdin(input.maxBytes, fd);\n return { payload: parsePayload(value, input.maxBytes), bytes: Buffer.byteLength(value, \"utf8\") };\n } finally { closeSync(fd); }\n}\n\nfunction identity(payload: ClaudeSessionHookPayloadV1): { sessionId: string; repo: string; client: string } | null {\n const sessionId = typeof payload.session_id === \"string\" ? payload.session_id.trim() : \"\";\n const repo = typeof payload.cwd === \"string\" ? payload.cwd.trim() : \"\";\n const client = typeof payload.client_name === \"string\" ? payload.client_name.trim().toLowerCase() : \"claude-code\";\n if (!sessionId || !repo) return null;\n if (client !== \"claude\" && client !== \"claude-code\") return null;\n return { sessionId, repo, client: \"claude-code\" };\n}\n\nfunction eventAllowed(payload: ClaudeSessionHookPayloadV1, expected: \"SessionStart\" | \"SessionEnd\"): boolean {\n if (payload.hook_event_name === undefined) return true;\n return payload.hook_event_name === expected;\n}\n\nfunction truncateCodePoints(value: string, max: number): { text: string; truncated: boolean } {\n const points = Array.from(value);\n if (points.length <= max) return { text: value, truncated: false };\n return { text: points.slice(0, max).join(\"\"), truncated: true };\n}\n\nexport async function runSessionStartHook(module: NotebookModule, payload: ClaudeSessionHookPayloadV1, runtime: NotebookHookRuntime = DEFAULT_RUNTIME): Promise<NotebookHookResultV1> {\n const hookStarted = performance.now();\n try {\n if (!eventAllowed(payload, \"SessionStart\")) return { exitCode: 0, stdout: \"\", stderr: \"project-notebook: unsupported non-SessionStart event skipped\", outcome: \"skipped\" };\n const id = identity(payload);\n if (!id) return { exitCode: 0, stdout: \"\", stderr: \"project-notebook: missing or unsupported session identity; skipped\", outcome: \"skipped\" };\n const ctx = module.context(id.repo, false);\n if (ctx.config.binding.state !== \"linked\" || (!ctx.config.policy.session_start_enabled && !ctx.config.policy.session_capture_enabled)) return { exitCode: 0, stdout: \"\", stderr: \"\", outcome: \"skipped\" };\n const budget = ctx.config.limits.hook_session_start_timeout_ms;\n const safetyMargin = Math.min(50, Math.max(1, Math.floor(budget * 0.05)));\n const deadline = hookStarted + Math.max(1, budget - safetyMargin);\n const sessionKey = deriveSessionKey(ctx.config.project_slug, id.client, id.sessionId);\n let baseline = readSessionBaseline(module.stateRoot, ctx.config.project_slug, sessionKey, ctx.config.limits);\n if (!baseline) {\n const snapshot = captureGitSnapshot(ctx.config.repo_path, ctx.config, deadline);\n baseline = createSessionBaseline(module.stateRoot, {\n limits: ctx.config.limits,\n session_key: sessionKey,\n project_slug: ctx.config.project_slug,\n client: id.client,\n created_at: runtime.now().toISOString(),\n repo_path: ctx.config.repo_path,\n git_head: snapshot.head,\n git_status_digest: snapshot.status_digest,\n policy_version: NOTEBOOK_POLICY_VERSION,\n tracked_path_digests: snapshot.tracked_path_digests,\n pre_dirty_paths: snapshot.dirty_paths,\n complete: snapshot.complete,\n incomplete_reasons: snapshot.reasons,\n }).baseline;\n } else if (runtime.now().getTime() >= Date.parse(baseline.created_at) + ctx.config.limits.receiptless_session_retention_seconds * 1_000) {\n return { exitCode: 0, stdout: \"\", stderr: \"project-notebook: SessionStart resume is older than the receiptless baseline grace; skipped without inventing a new boundary\", outcome: \"failed-open\" };\n }\n if (performance.now() >= deadline) return { exitCode: 0, stdout: \"\", stderr: \"project-notebook: SessionStart budget exhausted after recording an incomplete baseline; failed open\", outcome: \"failed-open\" };\n if (!ctx.config.policy.session_start_enabled || ctx.config.binding.state !== \"linked\") return { exitCode: 0, stdout: \"\", stderr: \"\", outcome: \"primed\" };\n if (readOverviewClaim(module.stateRoot, ctx.config.project_slug, sessionKey)) return { exitCode: 0, stdout: \"\", stderr: \"\", outcome: \"primed\" };\n try {\n const overview = await module.overview(id.repo, undefined, deadline);\n const stale = overview.data.drift.length > 0;\n const warning = stale\n ? `PROJECT NOTEBOOK OVERVIEW DRIFT\\n${overview.data.drift.map((item) => `${item.path}: ${item.reason}`).join(\"\\n\")}\\n\\n[Stored Overview is stale]\\n`\n : \"\";\n const bounded = truncateCodePoints(overview.data.note.content, ctx.config.policy.overview_max_chars);\n const content = `PROJECT NOTEBOOK\\n${warning}${bounded.text}${bounded.truncated ? \"\\n[Project Notebook Overview truncated]\" : \"\"}\\n`;\n const claim = createOverviewClaim(module.stateRoot, {\n session_key: sessionKey,\n project_slug: ctx.config.project_slug,\n created_at: runtime.now().toISOString(),\n overview_note_id: overview.data.note.id,\n content_sha256: sha256Hex(content),\n });\n return claim.created\n ? { exitCode: 0, stdout: content, stderr: \"\", outcome: \"primed\" }\n : { exitCode: 0, stdout: \"\", stderr: \"\", outcome: \"primed\" };\n } catch (error) {\n return { exitCode: 0, stdout: \"\", stderr: `project-notebook: Overview unavailable: ${boundedDiagnostic(error)}`, outcome: \"failed-open\" };\n }\n } catch (error) {\n return { exitCode: 0, stdout: \"\", stderr: `project-notebook: SessionStart failed open: ${boundedDiagnostic(error)}`, outcome: \"failed-open\" };\n }\n}\n\nexport function runSessionCloseHook(module: NotebookModule, payload: ClaudeSessionHookPayloadV1, runtime: NotebookHookRuntime = DEFAULT_RUNTIME): NotebookHookResultV1 {\n const started = Date.now();\n try {\n if (!eventAllowed(payload, \"SessionEnd\")) return { exitCode: 0, stdout: \"\", stderr: \"project-notebook: unsupported non-SessionEnd event skipped\", outcome: \"skipped\" };\n const id = identity(payload);\n if (!id) return { exitCode: 0, stdout: \"\", stderr: \"project-notebook: missing or unsupported session identity; skipped\", outcome: \"skipped\" };\n const ctx = module.context(id.repo, false);\n if (ctx.config.binding.state !== \"linked\" || !ctx.config.policy.session_capture_enabled) return { exitCode: 0, stdout: \"\", stderr: \"\", outcome: \"skipped\" };\n const sessionKey = deriveSessionKey(ctx.config.project_slug, id.client, id.sessionId);\n const admission = admitCaptureReceipt({\n root: module.stateRoot,\n projectSlug: ctx.config.project_slug,\n repoPath: ctx.config.repo_path,\n sessionKey,\n endRevision: null,\n endStatusDigest: null,\n limits: ctx.config.limits,\n now: runtime.now(),\n });\n if (admission.outcome === \"state-integrity\") return { exitCode: 0, stdout: \"\", stderr: admission.diagnostic.slice(0, 2_048), outcome: \"state-integrity\" };\n if (admission.outcome === \"retention-pressure\") return { exitCode: 0, stdout: \"\", stderr: admission.diagnostic.slice(0, 2_048), outcome: \"retention-pressure\" };\n if (admission.outcome === \"deduplicated\") return { exitCode: 0, stdout: \"\", stderr: \"\", outcome: \"deduplicated\", receiptId: admission.receipt.receipt_id };\n runtime.spawnWorker(admission.receipt.receipt_id, ctx.config.project_slug);\n const elapsed = Date.now() - started;\n return {\n exitCode: 0,\n stdout: \"\",\n stderr: elapsed > ctx.config.limits.hook_session_end_timeout_ms ? \"project-notebook: capture was durably queued but foreground budget was exceeded\" : \"\",\n outcome: \"captured\",\n receiptId: admission.receipt.receipt_id,\n };\n } catch (error) {\n return { exitCode: 0, stdout: \"\", stderr: `project-notebook: SessionEnd failed open: ${boundedDiagnostic(error)}`, outcome: \"failed-open\" };\n }\n}\n", "import { auditCheck, gatesProject, isHostScoped } from \"./types\";\nimport type {\n LifecycleAuditFinding,\n LifecycleAuditReport,\n LifecycleContext,\n LifecycleMigrationReport,\n LifecycleMigrationResult,\n LifecycleRecipe,\n RecipeId,\n RecipeInitResult,\n RecipeMetadata,\n RuleId,\n} from \"./types\";\n\n/**\n * The sole lifecycle dispatch and ownership boundary.\n *\n * Registration is deliberately strict: recipe ids and public rule ids are\n * globally unique, dependencies must exist, and the dependency graph must be\n * acyclic. Ordering is stable: registration order for audit, dependencies-first\n * for init, requested order for selected migrations.\n */\nexport class RecipeRegistry {\n private readonly recipes = new Map<RecipeId, LifecycleRecipe>();\n private readonly ruleOwners = new Map<RuleId, { recipe: LifecycleRecipe; checkIndex: number }>();\n private validated = false;\n\n constructor(recipes: readonly LifecycleRecipe[] = []) {\n for (const recipe of recipes) this.register(recipe);\n if (recipes.length) this.validate();\n }\n\n register(recipe: LifecycleRecipe): this {\n if (this.recipes.has(recipe.metadata.id)) throw new Error(`Duplicate recipe id: ${recipe.metadata.id}`);\n const seenLocal = new Set<string>();\n for (let index = 0; index < recipe.checks.length; index++) {\n const check = recipe.checks[index]!;\n if (seenLocal.has(check.id) || this.ruleOwners.has(check.id)) throw new Error(`Duplicate parity rule id: ${check.id}`);\n seenLocal.add(check.id);\n this.ruleOwners.set(check.id, { recipe, checkIndex: index });\n }\n const declared = [...recipe.metadata.publicRuleIds];\n const actual = recipe.checks.map((check) => check.id);\n if (JSON.stringify(declared) !== JSON.stringify(actual)) {\n throw new Error(`Recipe ${recipe.metadata.id} publicRuleIds do not match its checks`);\n }\n this.recipes.set(recipe.metadata.id, recipe);\n const registryAware = recipe as LifecycleRecipe & { attachRegistry?: (registry: RecipeRegistry) => void };\n registryAware.attachRegistry?.(this);\n this.validated = false;\n return this;\n }\n\n validate(): void {\n for (const recipe of this.recipes.values()) {\n for (const dependency of recipe.metadata.dependencies) {\n if (!this.recipes.has(dependency)) throw new Error(`Unknown dependency ${dependency} for recipe ${recipe.metadata.id}`);\n }\n }\n const visiting = new Set<string>();\n const visited = new Set<string>();\n const visit = (id: string, path: string[]) => {\n if (visiting.has(id)) throw new Error(`Recipe dependency cycle: ${[...path, id].join(\" -> \")}`);\n if (visited.has(id)) return;\n visiting.add(id);\n const recipe = this.recipes.get(id)!;\n for (const dependency of recipe.metadata.dependencies) visit(dependency, [...path, id]);\n visiting.delete(id);\n visited.add(id);\n };\n for (const id of this.recipes.keys()) visit(id, []);\n this.validated = true;\n }\n\n private ensureValid(): void {\n if (!this.validated) this.validate();\n }\n\n list(): readonly RecipeMetadata[] {\n this.ensureValid();\n return [...this.recipes.values()].map((recipe) => recipe.metadata);\n }\n\n get(recipeId: RecipeId): LifecycleRecipe | undefined {\n return this.recipes.get(recipeId);\n }\n\n ownerOf(ruleId: RuleId): { recipe: LifecycleRecipe; check: LifecycleRecipe[\"checks\"][number] } | undefined {\n const owner = this.ruleOwners.get(ruleId);\n if (!owner) return undefined;\n return { recipe: owner.recipe, check: owner.recipe.checks[owner.checkIndex]! };\n }\n\n resolveOrder(recipeId: RecipeId): LifecycleRecipe[] {\n this.ensureValid();\n if (!this.recipes.has(recipeId)) throw new Error(`Unknown recipe: ${recipeId}`);\n const ordered: LifecycleRecipe[] = [];\n const seen = new Set<string>();\n const visit = (id: string) => {\n if (seen.has(id)) return;\n const recipe = this.recipes.get(id)!;\n for (const dependency of recipe.metadata.dependencies) visit(dependency);\n seen.add(id);\n ordered.push(recipe);\n };\n visit(recipeId);\n return ordered;\n }\n\n resolveDependencies(recipeId: RecipeId): LifecycleRecipe[] {\n return this.resolveOrder(recipeId).filter((recipe) => recipe.metadata.id !== recipeId);\n }\n\n private aggregateInit(recipeId: RecipeId, ctx: LifecycleContext, results: readonly RecipeInitResult[]): RecipeInitResult {\n const selected = results.at(-1) ?? {\n recipeId,\n ok: true,\n dryRun: Boolean(ctx.dryRun),\n changedFiles: [],\n logs: [],\n errors: [],\n phases: [],\n };\n return {\n ...selected,\n recipeId,\n ok: results.every((result) => result.ok),\n changedFiles: [...new Set(results.flatMap((result) => result.changedFiles))].sort(),\n logs: results.flatMap((result) => result.logs),\n errors: results.flatMap((result) => result.errors),\n phases: results.flatMap((result) => result.phases),\n dependencyResults: results.slice(0, -1),\n };\n }\n\n async initDependencies<TInput>(recipeId: RecipeId, ctx: LifecycleContext, input: TInput, excludeRecipeIds: readonly RecipeId[] = []): Promise<RecipeInitResult> {\n const results: RecipeInitResult[] = [];\n for (const dependency of this.resolveDependencies(recipeId)) {\n if (excludeRecipeIds.includes(dependency.metadata.id)) continue;\n const result = await dependency.init(ctx, input);\n results.push(result);\n if (!result.ok) break;\n }\n return this.aggregateInit(recipeId, ctx, results);\n }\n\n async initRecipe<TInput>(recipeId: RecipeId, ctx: LifecycleContext, input: TInput): Promise<RecipeInitResult> {\n this.ensureValid();\n const selected = this.recipes.get(recipeId);\n if (!selected) throw new Error(`Unknown recipe: ${recipeId}`);\n if (selected.orchestratesDependencies) return selected.init(ctx, input);\n\n const results: RecipeInitResult[] = [];\n for (const recipe of this.resolveOrder(recipeId)) {\n const result = await recipe.init(ctx, input);\n results.push(result);\n if (!result.ok) break;\n }\n return this.aggregateInit(recipeId, ctx, results);\n }\n\n auditRecipes(ctx: LifecycleContext, recipeIds?: readonly RecipeId[]): LifecycleAuditReport {\n this.ensureValid();\n const selected = recipeIds ? recipeIds.map((id) => {\n const recipe = this.recipes.get(id);\n if (!recipe) throw new Error(`Unknown recipe: ${id}`);\n return recipe;\n }) : [...this.recipes.values()];\n const rules = selected.flatMap((recipe) => recipe.audit(ctx).map((finding) => ({ ...finding, recipeId: finding.recipeId ?? recipe.metadata.id })));\n return {\n repo: ctx.repoRoot,\n // PJAN-84: `ok` answers \"is the audited PROJECT in parity?\".\n //\n // It used to be `every(pass || skip)`, which made two unrelated claims:\n // that a `warn` is a failure, and that a HOST condition is the\n // repository's failure. The first is why `pj audit` exited 1 while\n // reporting zero failed rules; the second is why a drifted symlink under\n // ~/.agents could fail \u2014 and roll back \u2014 a brand-new project, and every\n // project on the machine at once.\n //\n // Host findings are still reported, and `hostOk` says whether any of them\n // needs attention, so nothing is hidden \u2014 it just no longer gates a repo\n // that cannot fix it.\n ok: rules.every((rule) => !gatesProject(rule)),\n hostOk: rules.every((rule) => !isHostScoped(rule) || rule.status === \"pass\" || rule.status === \"skip\"),\n auditedAt: new Date().toISOString(),\n rules,\n };\n }\n\n /**\n * PJAN-75: re-audit a rule that has just been migrated and demote a claimed\n * success that did not actually reach parity.\n *\n * Without this, `migrate` reports whatever each rule chooses to report about\n * itself, and a rule that applies SOME of its changes still shows a green\n * `[applied]`. That is how `migrate` came to print \"Migration complete\"\n * immediately followed by a failing `audit` on the very same rules -- the\n * two commands were answering different questions and only `audit` was\n * answering the one the operator asked.\n *\n * Only `applied` and `noop` are re-checked. `blocked` and `skipped` already\n * say the work did not happen, and a dry run has nothing to verify because\n * nothing was written.\n */\n private verifyMigration(ctx: LifecycleContext, result: LifecycleMigrationResult): LifecycleMigrationResult {\n if (ctx.dryRun) return result;\n if (result.status !== \"applied\" && result.status !== \"noop\") return result;\n const owner = this.ruleOwners.get(result.id);\n if (!owner) return result;\n let postcondition;\n try {\n postcondition = auditCheck(owner.recipe.checks[owner.checkIndex]!, ctx);\n } catch (err) {\n return {\n ...result,\n status: \"partial\",\n summary: `${result.summary} (postcondition audit threw)`,\n details: [...result.details, `postcondition audit threw: ${err instanceof Error ? err.message : String(err)}`],\n };\n }\n if (postcondition.status === \"pass\" || postcondition.status === \"skip\") return result;\n return {\n ...result,\n status: \"partial\",\n // The audit's own summary is the authoritative account of what is still\n // wrong, so it replaces the migrate summary rather than appending to it.\n summary: postcondition.summary,\n details: [\n ...result.details,\n `still failing after migrate: ${postcondition.summary}`,\n ...postcondition.details,\n ],\n };\n }\n\n migrateRules(ctx: LifecycleContext, ruleIds: readonly RuleId[]): LifecycleMigrationReport {\n this.ensureValid();\n const unknown = ruleIds.filter((id) => !this.ruleOwners.has(id));\n if (unknown.length) throw new Error(`Unknown parity rules: ${unknown.join(\", \")}`);\n // PJAN-84: verify AFTER every selected rule has run, not inside the loop.\n //\n // verifyMigration used to be applied per result as it was produced, so rule\n // N's postcondition was read before rules N+1..M had run. A rule that a\n // LATER rule repaired was therefore still reported `partial`, and since\n // `partial` counts against `ok`, `migrate --all` exited 1 describing a repo\n // that was in parity by the time the run ended. Observed on pjangler:\n // bmad.cli-roots reported \"3 supported projection issue(s)\" that\n // bmad.scaffold's BMAD reinstall had already resolved.\n //\n // PJAN-75's property is untouched: a claimed success must still be supported\n // by the rule's own audit. Only WHEN that audit is read changes.\n const raw: LifecycleMigrationResult[] = [];\n for (const id of ruleIds) {\n const owner = this.ruleOwners.get(id)!;\n try {\n const migrated = owner.recipe.migrate(ctx, [id]);\n raw.push(...migrated.map((result) => ({\n ...result,\n recipeId: result.recipeId ?? owner.recipe.metadata.id,\n })));\n } catch (err) {\n const check = owner.recipe.checks[owner.checkIndex]!;\n raw.push({\n id,\n recipeId: owner.recipe.metadata.id,\n title: check.title,\n status: \"blocked\",\n summary: `migrate threw: ${err instanceof Error ? err.message : String(err)}`,\n changedFiles: [],\n details: [],\n });\n }\n }\n const results = raw.map((result) => this.verifyMigration(ctx, result));\n return {\n repo: ctx.repoRoot,\n dryRun: Boolean(ctx.dryRun),\n // `partial` counts against ok for the same reason `blocked` does: the\n // repo is not in parity, so the command must not exit 0.\n ok: results.every((result) => result.status !== \"blocked\" && result.status !== \"partial\"),\n selectedRules: [...ruleIds],\n results,\n changedFiles: [...new Set(results.flatMap((result) => result.changedFiles))].sort(),\n };\n }\n\n /**\n * PJAN-75: `migrate --all` accounts for every failing rule, including the\n * ones it is not allowed to touch.\n *\n * Non-fixable failures were silently excluded from the report entirely, so a\n * repo whose only problem was an operator-owned rule -- an unprovisioned\n * Hermes role, a fleet-wide config value -- got \"Migration complete\", an\n * empty result list and exit 0, immediately followed by a failing `audit`.\n * They are re-checked AFTER the migrations run, because a rule this pass was\n * not allowed to fix may still have been fixed as a side effect of one it\n * was.\n */\n migrateAll(ctx: LifecycleContext): LifecycleMigrationReport {\n const audit = this.auditRecipes(ctx);\n const failing = audit.rules.filter((rule) => rule.status === \"fail\" || rule.status === \"warn\");\n const report = this.migrateRules(ctx, failing.filter((rule) => rule.fixable).map((rule) => rule.id));\n\n const manual: LifecycleMigrationResult[] = [];\n for (const rule of failing.filter((candidate) => !candidate.fixable)) {\n const owner = this.ruleOwners.get(rule.id);\n let current = rule;\n if (owner) {\n try {\n current = auditCheck(owner.recipe.checks[owner.checkIndex]!, ctx, rule.recipeId);\n } catch {\n // Keep the pre-migration finding rather than dropping the rule.\n }\n }\n if (current.status === \"pass\" || current.status === \"skip\") continue;\n manual.push({\n id: current.id,\n recipeId: current.recipeId,\n title: current.title,\n status: \"blocked\",\n summary: current.summary,\n changedFiles: [],\n details: [...current.details, \"not auto-fixable: this rule needs an operator decision or action\"],\n });\n }\n if (!manual.length) return report;\n return { ...report, ok: false, results: [...report.results, ...manual] };\n }\n\n listRuleIds(): readonly RuleId[] {\n this.ensureValid();\n return [...this.recipes.values()].flatMap((recipe) => recipe.checks.map((check) => check.id));\n }\n}\n\nexport function metadata(input: Omit<RecipeMetadata, \"publicRuleIds\">, checks: readonly { id: string }[]): RecipeMetadata {\n return { ...input, publicRuleIds: checks.map((check) => check.id) };\n}\n", "import { AgentHooksRecipe } from \"./AgentHooksRecipe\";\nimport { BmadRecipe } from \"./BmadRecipe\";\nimport { DockerRecipe } from \"./DockerRecipe\";\nimport { HermesAgentRecipe } from \"./HermesAgentRecipe\";\nimport { MiseOpInjectRecipe } from \"./MiseOpInjectRecipe\";\nimport { MiseRecipe } from \"./MiseRecipe\";\nimport { NodeRecipe } from \"./NodeRecipe\";\nimport { ProjectRecipe } from \"./ProjectRecipe\";\nimport { NotebookRecipe } from \"./NotebookRecipe\";\nimport { RecipeRegistry } from \"./registry\";\n\n/** The single production lifecycle registry instance. */\nexport const recipeRegistry = new RecipeRegistry([\n new MiseOpInjectRecipe(),\n new MiseRecipe(),\n new AgentHooksRecipe(),\n new BmadRecipe(),\n new DockerRecipe(),\n new NodeRecipe(),\n new HermesAgentRecipe(),\n new NotebookRecipe(),\n new ProjectRecipe(),\n]);\n", "import { homedir } from \"node:os\";\nimport { join, dirname } from \"node:path\";\nimport { existsSync, cpSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport type { InvokeResult } from \"./Command\";\nimport { Command } from \"./Command\";\nimport { resolveAgentHooksLayer } from \"../project/index\";\n\n/** Shared skip result when a global ~/.agents/hooks install makes the project-scoped\n * layer redundant. Overridable with PJ_AGENT_HOOKS_LAYER=1. */\nconst AGENT_HOOKS_SKIP_MESSAGE =\n \"\u21B7 agent-hooks layer skipped: global ~/.agents/hooks detected (these hooks already run globally).\\n\" +\n \" Set PJ_AGENT_HOOKS_LAYER=1 to install the project-scoped layer anyway.\";\n\n/**\n * Resolve the CommonProject copier template root (which vendors the generic\n * agent-hooks tree under template/.agents/hooks). Walks up from this module's\n * directory so it works both from source (src/commands/) and from the bundled\n * ESM dist (dist/index.js) \u2014 the npm package ships templates/ at its root. Falls\n * back to an env override and the canonical ~/code/pjangler checkout.\n */\nfunction resolveTemplateRoot(): string {\n const candidates: string[] = [];\n if (process.env.PJANGLER_COMMONPROJECT_TEMPLATE) {\n candidates.push(process.env.PJANGLER_COMMONPROJECT_TEMPLATE);\n }\n try {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 8; i++) {\n candidates.push(join(dir, \"templates\", \"commonproject\", \"template\"));\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n } catch {\n /* import.meta.url unavailable \u2014 rely on the other candidates */\n }\n candidates.push(join(homedir(), \"code\", \"pjangler\", \"templates\", \"commonproject\", \"template\"));\n\n for (const c of candidates) {\n if (existsSync(join(c, \".agents\", \"hooks\", \"hooks.master.json\"))) return c;\n }\n throw new Error(\n \"Could not locate the CommonProject template. Set PJANGLER_COMMONPROJECT_TEMPLATE to <repo>/templates/commonproject/template.\"\n );\n}\n\n/**\n * Copy the generic project-scoped agent-hooks tree (hooks SSOT + sync engine +\n * hindsight scripts + hermes adapter + skills manifest + hindsight-setup +\n * local.example.json) from the CommonProject template into the target repo.\n * Files are already project-agnostic (bank = repo basename, op ref is a\n * placeholder), so no rendering is needed.\n */\nexport class CopyAgentHooksTree extends Command {\n async invoke(): Promise<InvokeResult> {\n if (!resolveAgentHooksLayer()) {\n return { success: true, message: this.formatMessage(AGENT_HOOKS_SKIP_MESSAGE) };\n }\n let templateRoot: string;\n try {\n templateRoot = resolveTemplateRoot();\n } catch (e) {\n return { success: false, message: `\u26A0\uFE0F ${(e as Error).message}` };\n }\n\n // relative path -> whether it's a directory (copied recursively)\n const items: Array<{ rel: string; dir: boolean }> = [\n { rel: \".agents/hooks\", dir: true },\n { rel: \".agents/skills.json\", dir: false },\n { rel: \".agents/local.example.json\", dir: false },\n { rel: \".mise/scripts/hindsight-setup.sh\", dir: false },\n ];\n\n const created: string[] = [];\n const skipped: string[] = [];\n for (const { rel, dir } of items) {\n const src = join(templateRoot, rel);\n const dest = join(this.context.targetDir, rel);\n if (!existsSync(src)) continue;\n if (existsSync(dest) && !this.context.force) {\n skipped.push(rel);\n continue;\n }\n if (!this.context.dryRun) {\n mkdirSync(dirname(dest), { recursive: true });\n cpSync(src, dest, { recursive: dir, force: true }); // preserves mode (exec bits)\n }\n created.push(rel);\n }\n\n const verb = this.context.dryRun ? \"Would copy\" : \"Copied\";\n const tail = skipped.length ? ` (${skipped.length} already present \u2014 use --force to overwrite)` : \"\";\n return {\n success: created.length > 0,\n message: this.formatMessage(`\u2705 ${verb} ${created.length} agent-hooks path(s)${tail}`),\n };\n }\n}\n\n/**\n * Merge the agent-hooks wiring into an existing mise.toml: extend\n * [hooks].enter/leave and append the watch_files + tasks. Idempotent (guarded by\n * a sentinel marker). For the canonical CommonProject layout it edits in place;\n * if it can't find a [hooks].enter array to extend, it appends the tasks and\n * prints the exact enter/leave lines to add by hand (never corrupts the file).\n */\nexport class WireMiseAgentHooks extends Command {\n private static MARKER = \"# pjangler:agent-hooks\";\n private static CR = \"{{config_root}}\"; // mise's own runtime var \u2014 emitted literally\n\n async invoke(): Promise<InvokeResult> {\n if (!resolveAgentHooksLayer()) {\n return { success: true, message: this.formatMessage(AGENT_HOOKS_SKIP_MESSAGE) };\n }\n const misePath = join(this.context.targetDir, \"mise.toml\");\n\n if (!existsSync(misePath)) {\n return {\n success: false,\n message: \"\u26A0\uFE0F No mise.toml found \u2014 run `pjangler init mise` first, then re-run.\",\n };\n }\n let content = readFileSync(misePath, \"utf8\");\n if (content.includes(WireMiseAgentHooks.MARKER)) {\n return { success: true, message: this.formatMessage(\"\u2713 mise.toml already wired for agent-hooks\") };\n }\n\n const cr = WireMiseAgentHooks.CR;\n const enterAdds = [` \"sync-skills.py --scope project\",`, ` \"${cr}/.agents/hooks/sync.py --install --quiet\",`].join(\"\\n\");\n const leaveBlock = [\n \"leave = [\",\n ` \"${cr}/.agents/hooks/sync.py --uninstall --quiet\",`,\n \"]\",\n ].join(\"\\n\");\n\n let wiredHooks = false;\n // Insert our enter lines before the closing ] of an existing `enter = [ ... ]`.\n const enterRe = /(enter\\s*=\\s*\\[[\\s\\S]*?)(\\n[ \\t]*\\])/;\n if (enterRe.test(content)) {\n content = content.replace(enterRe, (_m, head, close) => {\n const sep = /[,[]\\s*$/.test(head) ? \"\" : \",\"; // add a comma only if needed\n return `${head}${sep}\\n${enterAdds}${close}`;\n });\n // Ensure a leave array too: extend it, or add one right after the enter close.\n const leaveRe = /(leave\\s*=\\s*\\[[\\s\\S]*?)(\\n[ \\t]*\\])/;\n if (leaveRe.test(content)) {\n content = content.replace(leaveRe, (_m, head, close) => {\n const sep = /[,[]\\s*$/.test(head) ? \"\" : \",\";\n return `${head}${sep}\\n \"${cr}/.agents/hooks/sync.py --uninstall --quiet\",${close}`;\n });\n } else {\n content = content.replace(enterRe, (m) => `${m}\\n${leaveBlock}`);\n }\n wiredHooks = true;\n }\n\n const appended = [\n \"\",\n WireMiseAgentHooks.MARKER + \" (generated \u2014 see .agents/hooks/README.md)\",\n // PJAN-61: task names use the colon namespace form. A colon is not legal\n // in a BARE toml key, so every header here MUST stay quoted.\n \"[[watch_files]]\",\n 'patterns = [\".agents/skills.json\"]',\n 'task = \"skills:sync\"',\n \"\",\n '[tasks.\"skills:sync\"]',\n 'description = \"Sync skills from manifest to local CLI dirs\"',\n 'run = \"sync-skills.py --scope project\"',\n \"\",\n \"[[watch_files]]\",\n 'patterns = [\".agents/hooks/hooks.master.json\"]',\n 'task = \"hooks:sync\"',\n \"\",\n '[tasks.\"hooks:sync\"]',\n 'description = \"Fan out hooks.master.json to each agent CLI (claude/codex/kimi/hermes)\"',\n `run = \"${cr}/.agents/hooks/sync.py --install\"`,\n \"\",\n '[tasks.\"hooks:check\"]',\n 'description = \"Drift gate: verify generated hook configs match hooks.master.json\"',\n `run = \"${cr}/.agents/hooks/sync.py --check\"`,\n \"\",\n '[tasks.\"hooks:uninstall\"]',\n 'description = \"Remove per-user agent-hook injections (codex/kimi/hermes)\"',\n `run = \"${cr}/.agents/hooks/sync.py --uninstall\"`,\n \"\",\n '[tasks.\"hindsight:setup\"]',\n 'description = \"Provision this dev\\'s shared project Hindsight key from 1Password into .env\"',\n `run = \"${cr}/.mise/scripts/hindsight-setup.sh\"`,\n \"\",\n WireMiseAgentHooks.MARKER + \":end\",\n \"\",\n ].join(\"\\n\");\n content = content.replace(/\\n*$/, \"\\n\") + appended;\n\n if (!this.context.dryRun) writeFileSync(misePath, content);\n\n if (wiredHooks) {\n return { success: true, message: this.formatMessage(\"\u2705 Wired mise.toml ([hooks] enter/leave + tasks)\") };\n }\n return {\n success: true,\n message: this.formatMessage(\n \"\u2705 Added agent-hooks tasks to mise.toml.\\n\" +\n \" \u26A0\uFE0F Could not find a [hooks].enter array to extend \u2014 add these to your [hooks] block manually:\\n\" +\n ` enter += \"sync-skills.py --scope project\", \"${cr}/.agents/hooks/sync.py --install --quiet\"\\n` +\n ` leave += \"${cr}/.agents/hooks/sync.py --uninstall --quiet\"`\n ),\n };\n }\n}\n", "import { Command, type InvokeResult, type CommandContext } from \"./Command\";\n\nexport class AddMiseToml extends Command {\n async invoke(): Promise<InvokeResult> {\n const filePath = \"mise.toml\";\n \n if (this.fileExists(filePath) && !this.context.force) {\n return {\n success: false,\n message: this.formatMessage(\"\u26A0\uFE0F mise.toml already exists\"),\n filePath\n };\n }\n\n const content = `# Mise configuration\n[tools]\npython = \"3.11\"\nnode = \"20\"\n\n[env]\nNODE_ENV = \"development\"\n`;\n\n this.writeFile(filePath, content);\n return {\n success: true,\n message: this.formatMessage(this.context.dryRun ? \"Would create mise.toml\" : \"\u2705 Created mise.toml\"),\n filePath\n };\n }\n}", "import type { InvokeResult } from \"./Command\";\nimport { Command } from \"./Command\";\n\nexport class AddMiseBaseToml extends Command {\n async invoke(): Promise<InvokeResult> {\n const filePath = \".mise/tasks/base.toml\";\n\n if (this.fileExists(filePath) && !this.context.force) {\n return {\n success: false,\n message: this.formatMessage(\"\u26A0\uFE0F .mise/tasks/base.toml already exists\"),\n filePath\n };\n }\n\n const content = `# Base tasks configuration\n[tasks.setup]\nrun = \"python scripts/base.py\"\ndescription = \"Setup base environment\"\n\n[tasks.clean]\nrun = \"rm -rf node_modules dist build\"\ndescription = \"Clean build artifacts\"\n\n[tasks.dev]\nrun = \"mise run setup\"\ndescription = \"Initialize development environment\"\n`;\n\n this.writeFile(filePath, content);\n return {\n success: true,\n message: this.formatMessage(this.context.dryRun ? \"Would create .mise/tasks/base.toml\" : \"\u2705 Created .mise/tasks/base.toml\"),\n filePath\n };\n }\n}", "import type { InvokeResult } from \"./Command\";\nimport { Command } from \"./Command\";\n\nexport class AddMiseTasksStructure extends Command {\n async invoke(): Promise<InvokeResult> {\n this.createDirectory(\".mise/tasks/scripts\");\n\n return {\n success: true,\n message: this.formatMessage(this.context.dryRun ? \"Would create .mise directory structure\" : \"\u2705 Created .mise directory structure\"),\n filePath: \".mise/tasks/scripts\"\n };\n }\n}", "import type { InvokeResult } from \"./Command\";\nimport { Command } from \"./Command\";\n\nexport class AddMiseBaseScript extends Command {\n async invoke(): Promise<InvokeResult> {\n const filePath = \".mise/tasks/scripts/base.py\";\n\n if (this.fileExists(filePath) && !this.context.force) {\n return {\n success: false,\n message: this.formatMessage(\"\u26A0\uFE0F .mise/tasks/scripts/base.py already exists\"),\n filePath\n };\n }\n\n const content = `#!/usr/bin/env python3\n\"\"\"Base setup script\"\"\"\nimport os\nimport sys\nfrom pathlib import Path\n\ndef main():\n print(\"\uD83D\uDD27 Setting up base environment...\")\n\n dirs_to_create = [\"logs\", \"temp\", \"data\"]\n for dir_name in dirs_to_create:\n Path(dir_name).mkdir(exist_ok=True)\n print(f\" Created {dir_name}/ directory\")\n\n print(\" Base environment setup complete!\")\n print(\" Run 'mise run dev' to start development\")\n\nif __name__ == \"__main__\":\n main()\n`;\n\n this.writeFile(filePath, content);\n return {\n success: true,\n message: this.formatMessage(this.context.dryRun ? \"Would create .mise/tasks/scripts/base.py\" : \"\u2705 Created .mise/tasks/scripts/base.py\"),\n filePath\n };\n }\n}", "import { chmodSync } from \"fs\";\nimport { join } from \"path\";\nimport type { InvokeResult } from \"./Command\";\nimport { Command } from \"./Command\";\n\nexport class AddMiseCodegraphScript extends Command {\n async invoke(): Promise<InvokeResult> {\n const filePath = \".mise/scripts/codegraph.sh\";\n\n if (this.fileExists(filePath) && !this.context.force) {\n return {\n success: false,\n message: this.formatMessage(\"\u26A0\uFE0F .mise/scripts/codegraph.sh already exists\"),\n filePath\n };\n }\n\n const content = `#!/usr/bin/env bash\n# Auto-generated by pjangler\n\nREPO_ROOT=\"$(pwd)\"\nPROJECT_NAME=\"$(basename \"$REPO_ROOT\")\"\nCONTAINER_NAME=\"codegraph-mcp-$PROJECT_NAME\"\nCACHE_DIR=\"$REPO_ROOT/.codegraph\"\n\n# Deterministically generate a port based on the repository path\nPORT=$(echo -n \"$REPO_ROOT\" | md5sum | awk '{print $1}' | tr -d 'a-f' | cut -c1-4)\n# Ensure port is > 1024\nPORT=$(( (PORT % 60000) + 1025 ))\n\nif ! docker ps --format '{{.Names}}' | grep -q \"^$CONTAINER_NAME$\"; then\n echo \"\uD83D\uDE80 Starting CodeGraph MCP Server on port $PORT...\"\n\n # Ensure the container isn't lingering in a stopped state\n docker rm -f \"$CONTAINER_NAME\" >/dev/null 2>&1 || true\n\n # Run the true Colby McHenry CodeGraph Docker image\n # which we built locally as colbymchenry-codegraph-mcp:latest\n docker run -d \\\\\n --name \"$CONTAINER_NAME\" \\\\\n --restart unless-stopped \\\\\n -p \"$PORT:8045\" \\\\\n -v \"$REPO_ROOT:/repo\" \\\\\n colbymchenry-codegraph-mcp:latest >/dev/null\n\n echo \"\u2705 CodeGraph MCP running in background. SSE URL: http://localhost:$PORT/sse\"\nfi\n\n# Run init inside the container to ensure the index is bootstrapped.\n# We run this using the standard codegraph CLI inside the container\ndocker exec \"$CONTAINER_NAME\" codegraph init -i /repo >/dev/null 2>&1 || true\n\n# Wire up the MCP server to local agents\nWIRE_SCRIPT=\"$(dirname \"$0\")/codegraph-wire.sh\"\nif [ -x \"$WIRE_SCRIPT\" ]; then\n \"$WIRE_SCRIPT\"\nfi\n`;\n\n this.writeFile(filePath, content);\n\n if (!this.context.dryRun) {\n chmodSync(join(this.context.targetDir, filePath), 0o755);\n }\n\n return {\n success: true,\n message: this.formatMessage(this.context.dryRun ? \"Would create .mise/scripts/codegraph.sh\" : \"\u2705 Created .mise/scripts/codegraph.sh\"),\n filePath\n };\n }\n}\n", "import { Command, type InvokeResult, type CommandContext } from \"./Command\";\n\nexport class AddDotenv extends Command {\n async invoke(): Promise<InvokeResult> {\n const filePath = \".env\";\n \n if (this.fileExists(filePath) && !this.context.force) {\n return {\n success: false,\n message: this.formatMessage(\"\u26A0\uFE0F .env already exists\"),\n filePath\n };\n }\n\n const content = `# Environment variables\nDATABASE_URL=\"\"\nAPI_KEY=\"\"\nSECRET_KEY=\"\"\n`;\n\n this.writeFile(filePath, content);\n return {\n success: true,\n message: this.formatMessage(this.context.dryRun ? \"Would create .env\" : \"\u2705 Created .env\"),\n filePath\n };\n }\n}", "import { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { recipeRegistry } from \"../recipes/catalog\";\nimport type { LifecycleContext } from \"../recipes/types\";\nimport type { AuditReport, MigrationReport } from \"./rules\";\n\nexport {\n formatAuditReport,\n formatMigrationReport,\n formatMomoReadinessReport,\n formatRulePicker,\n provisionDeclaredPacks,\n registryCacheDirName,\n runMomoReadinessAudit,\n} from \"./rules\";\nexport type {\n AuditFinding,\n AuditReport,\n PackProvisionHooks,\n Context,\n MigrationReport,\n MigrationRuleResult,\n MomoReadinessFinding,\n MomoReadinessReport,\n RulePicker,\n RulePickerChoice,\n RuleStatus,\n} from \"./rules\";\nexport { recipeRegistry };\n\nfunction resolvePjanglerRoot(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n while (dir !== dirname(dir)) {\n if (existsSync(join(dir, \"package.json\")) && existsSync(join(dir, \"templates\", \"commonproject\", \"copier.yml\"))) return dir;\n dir = dirname(dir);\n }\n return resolve(process.cwd());\n}\n\nexport function lifecycleContext(\n repoArg: string | undefined,\n dryRun: boolean,\n acceptRegistryMatches = false,\n overrides: Partial<LifecycleContext> = {},\n): LifecycleContext {\n const repoRoot = resolve(repoArg ?? process.cwd());\n return {\n ...overrides,\n targetDir: repoRoot,\n repoRoot,\n dryRun: overrides.dryRun ?? dryRun,\n force: overrides.force ?? false,\n pjanglerRoot: overrides.pjanglerRoot ?? resolvePjanglerRoot(),\n homeDir: overrides.homeDir ?? homedir(),\n acceptRegistryMatches: overrides.acceptRegistryMatches ?? acceptRegistryMatches,\n };\n}\n\nexport function getParityRuleIds(): string[] {\n return [...recipeRegistry.listRuleIds()];\n}\n\nfunction publicAudit(report: ReturnType<typeof recipeRegistry.auditRecipes>): AuditReport {\n return {\n ...report,\n rules: report.rules.map(({ recipeId: _recipeId, ...finding }) => finding),\n } as AuditReport;\n}\n\nfunction publicMigration(report: ReturnType<typeof recipeRegistry.migrateRules>): MigrationReport {\n return {\n ...report,\n results: report.results.map(({ recipeId: _recipeId, ...result }) => result),\n } as MigrationReport;\n}\n\nexport function runAudit(repoArg?: string, registryPath?: string): AuditReport {\n // PJAN-84: the registry the caller asked for reaches the rules. Without this,\n // `pj audit` had no --registry at all and every registry-reading rule fell\n // back to projectRegistryPath() independently, so auditing a project outside\n // the default registry produced findings about a project the registry had\n // never heard of.\n return publicAudit(recipeRegistry.auditRecipes(lifecycleContext(repoArg, true, false, registryPath ? { registryPath } : {})));\n}\n\nexport function runMigrationForRules(\n ruleIds: string[],\n repoArg: string | undefined,\n dryRun: boolean,\n acceptRegistryMatches = false,\n registryPath?: string,\n): MigrationReport {\n return publicMigration(recipeRegistry.migrateRules(\n lifecycleContext(repoArg, dryRun, acceptRegistryMatches, registryPath ? { registryPath } : {}),\n ruleIds,\n ));\n}\n\nexport function runMigration(\n selector: string | undefined,\n repoArg: string | undefined,\n dryRun: boolean,\n all: boolean,\n acceptRegistryMatches = false,\n registryPath?: string,\n): MigrationReport {\n const ctx = lifecycleContext(repoArg, dryRun, acceptRegistryMatches, registryPath ? { registryPath } : {});\n return publicMigration(all\n ? recipeRegistry.migrateAll(ctx)\n : recipeRegistry.migrateRules(ctx, selector ? [selector] : []));\n}\n", "import type { InvokeResult } from \"./Command\";\nimport { Command } from \"./Command\";\nimport { runMigrationForRules } from \"../parity/index\";\n\n/**\n * Compatibility command for the canonical `.env.op` -> `.env` lifecycle.\n *\n * The lifecycle registry owns the implementation. This command remains public\n * for one compatibility window and delegates to the two owned parity rules\n * instead of maintaining the retired `.env.secrets` contract.\n */\nexport class WireMiseOpInject extends Command {\n async invoke(): Promise<InvokeResult> {\n const report = runMigrationForRules(\n [\"mise.config-root\", \"secrets.env-op\"],\n this.context.targetDir,\n Boolean(this.context.dryRun)\n );\n const blocked = report.results.filter((result) => result.status === \"blocked\");\n return {\n success: blocked.length === 0,\n outcome: blocked.length\n ? \"failed\"\n : report.changedFiles.length\n ? (this.context.dryRun ? \"planned\" : \"changed\")\n : \"unchanged\",\n message: blocked.length\n ? `\u2717 op-inject lifecycle blocked: ${blocked.map((result) => `${result.id}: ${result.summary}`).join(\"; \")}`\n : this.formatMessage(\n `${this.context.dryRun ? \"Would wire\" : \"\u2713 Wired\"} atomic .env materialization from .env.op`\n ),\n filePath: report.changedFiles[0],\n };\n }\n}\n", "/**\n * Recipe and Command registry for pjangler CLI\n * Provides centralized access to available recipes and commands\n */\n\nimport type { CommandContext } from \"../commands/Command\";\nimport type { LifecycleRecipe } from \"../recipes/types\";\nimport { recipeRegistry } from \"../recipes/catalog\";\nimport { Command as Cmd } from \"../commands/Command\";\n\n// Import all commands\nimport { CopyAgentHooksTree, WireMiseAgentHooks } from \"../commands/AgentHooksCommands\";\nimport { AddDockerfile } from \"../commands/AddDockerfile\";\nimport { AddDockerCompose } from \"../commands/AddDockerCompose\";\nimport { AddDockerignore } from \"../commands/AddDockerignore\";\nimport { AddMiseToml } from \"../commands/AddMiseToml\";\nimport { AddMiseBaseToml } from \"../commands/AddMiseBaseToml\";\nimport { AddMiseTasksStructure } from \"../commands/AddMiseTasksStructure\";\nimport { AddMiseBaseScript } from \"../commands/AddMiseBaseScript\";\nimport { AddMiseCodegraphScript } from \"../commands/AddMiseCodegraphScript\";\nimport { AddDotenv } from \"../commands/AddDotenv\";\nimport { WireMiseOpInject } from \"../commands/WireMiseOpInject\";\n\nexport interface RecipeInfo {\n name: string;\n description: string;\n instance: LifecycleRecipe;\n commands: string[];\n}\n\nexport interface CommandInfo {\n name: string;\n description: string;\n group: string;\n class: new (context: CommandContext) => Cmd;\n}\n\n/**\n * Registry of all available recipes\n */\nconst LEGACY_PUBLIC_RECIPE_IDS = [\"mise\", \"docker\", \"node\", \"hermes-agent\", \"agent-hooks\", \"mise-op-inject\"] as const;\n\n/** Read-only compatibility facade over the exact production recipe instances. */\nexport const RECIPE_REGISTRY: Readonly<Record<string, RecipeInfo>> = Object.freeze(Object.fromEntries(\n LEGACY_PUBLIC_RECIPE_IDS.map((id) => {\n const instance = recipeRegistry.get(id);\n if (!instance) throw new Error(`Production recipe registry is missing ${id}`);\n return [id, Object.freeze({\n name: instance.metadata.name,\n description: instance.metadata.description,\n instance,\n commands: [...instance.metadata.commands],\n })];\n }),\n));\n\n/**\n * Registry of all available commands\n */\nexport const COMMAND_REGISTRY: Record<string, CommandInfo> = {\n CopyAgentHooksTree: {\n name: \"CopyAgentHooksTree\",\n description: \"Copy the generic agent-hooks tree (hooks SSOT + sync engine + scripts) from the CommonProject template\",\n group: \"agent-hooks\",\n class: CopyAgentHooksTree\n },\n WireMiseAgentHooks: {\n name: \"WireMiseAgentHooks\",\n description: \"Merge agent-hooks enter/leave + tasks into an existing mise.toml (idempotent)\",\n group: \"agent-hooks\",\n class: WireMiseAgentHooks\n },\n AddDockerfile: {\n name: \"AddDockerfile\",\n description: \"Create Dockerfile for containerization\",\n group: \"docker\",\n class: AddDockerfile\n },\n AddDockerCompose: {\n name: \"AddDockerCompose\",\n description: \"Create docker-compose.yml for multi-service setup\",\n group: \"docker\",\n class: AddDockerCompose\n },\n AddDockerignore: {\n name: \"AddDockerignore\",\n description: \"Create .dockerignore file\",\n group: \"docker\",\n class: AddDockerignore\n },\n AddMiseToml: {\n name: \"AddMiseToml\",\n description: \"Create mise.toml for version management\",\n group: \"mise\",\n class: AddMiseToml\n },\n AddMiseBaseToml: {\n name: \"AddMiseBaseToml\",\n description: \"Create base mise configuration\",\n group: \"mise\",\n class: AddMiseBaseToml\n },\n AddMiseTasksStructure: {\n name: \"AddMiseTasksStructure\",\n description: \"Create .mise/tasks directory structure\",\n group: \"mise\",\n class: AddMiseTasksStructure\n },\n AddMiseBaseScript: {\n name: \"AddMiseBaseScript\",\n description: \"Create base mise task scripts\",\n group: \"mise\",\n class: AddMiseBaseScript\n },\n AddMiseCodegraphScript: {\n name: \"AddMiseCodegraphScript\",\n description: \"Create .mise/scripts/codegraph.sh enter hook\",\n group: \"mise\",\n class: AddMiseCodegraphScript\n },\n AddDotenv: {\n name: \"AddDotenv\",\n description: \"Create .env.example file\",\n group: \"environment\",\n class: AddDotenv\n },\n WireMiseOpInject: {\n name: \"WireMiseOpInject\",\n description: \"Wire up op-inject script to mise.toml for 1Password secret resolution\",\n group: \"mise\",\n class: WireMiseOpInject\n }\n};\n\n/**\n * Get all available recipe names\n */\nexport function getRecipeNames(): string[] {\n return Object.keys(RECIPE_REGISTRY);\n}\n\n/**\n * Get recipe info by name\n */\nexport function getRecipeInfo(name: string): RecipeInfo | null {\n return RECIPE_REGISTRY[name] || null;\n}\n\n/**\n * Get all available command names\n */\nexport function getCommandNames(): string[] {\n return Object.keys(COMMAND_REGISTRY);\n}\n\n/**\n * Get command info by name\n */\nexport function getCommandInfo(name: string): CommandInfo | null {\n return COMMAND_REGISTRY[name] || null;\n}\n\n/**\n * Get commands grouped by category\n */\nexport function getCommandsByGroup(): Record<string, CommandInfo[]> {\n const grouped: Record<string, CommandInfo[]> = {};\n\n for (const cmdInfo of Object.values(COMMAND_REGISTRY)) {\n if (!grouped[cmdInfo.group]) {\n grouped[cmdInfo.group] = [];\n }\n grouped[cmdInfo.group]!.push(cmdInfo);\n }\n\n return grouped;\n}\n\n/**\n * Create recipe instance by name\n */\nexport function createRecipe(name: string, context: CommandContext): LifecycleRecipe | null {\n void context;\n const info = getRecipeInfo(name);\n if (!info) return null;\n return info.instance;\n}\n", "// `pjangler describe` \u2014 read a repo and report what it actually is.\n//\n// This is the AI-context surface: an agent (or a human) lands in an unfamiliar\n// repo, runs one command, and learns the project type, which pjangler\n// subsystems are installed, which config files exist, and what is worth doing\n// next. Everything here is derived from the repo on disk plus the live\n// production recipe registry \u2014 nothing is hardcoded per-project and nothing is\n// inferred from prose.\n//\n// Two independent signals are deliberately kept apart:\n//\n// presence \u2014 does the subsystem's marker file/dir exist? (is it installed?)\n// parity \u2014 do the recipe's own audit rules pass? (is it correct?)\n//\n// They are not the same question. A parity rule fails both when a subsystem is\n// missing and when it is present but drifted, so collapsing the two would make\n// `describe` claim \"broken\" where the truth is \"never installed\".\n\nimport { existsSync, readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { recipeRegistry, lifecycleContext } from \"../parity/index\";\nimport type { LifecycleAuditFinding, LifecycleStatus } from \"../recipes/types\";\nimport {\n loadProjectRegistry,\n projectRegistryPath,\n type ProjectRecord,\n} from \"../project/index\";\nimport { computeRepoActivity, gitLine, isGitRepo, type RepoActivity } from \"./activity\";\nimport { loadEffectiveNotebookConfig } from \"../notebook/config\";\nimport { captureAdmissionSummary, notebookStateRoot } from \"../notebook/state\";\nimport type { CaptureAdmissionSummaryV1, NotebookBindingState } from \"../notebook/types\";\nimport {\n bold,\n cyan,\n dim,\n gray,\n glyph,\n green,\n red,\n terminalWidth,\n truncateVisible,\n visibleWidth,\n wrapVisible,\n yellow,\n} from \"../utils/style\";\n\n/** Headline answer to \"is this subsystem in this repo?\". */\nexport type SubsystemStatus = \"installed\" | \"drifted\" | \"absent\";\n\n/** Answer to \"do this subsystem's own parity rules pass?\". */\nexport type ParityHealth = \"ok\" | \"drift\" | \"unchecked\";\n\nexport interface DescribeRule {\n id: string;\n title: string;\n status: LifecycleStatus;\n summary: string;\n fixable: boolean;\n}\n\nexport interface DescribeSubsystem {\n id: string;\n name: string;\n description: string;\n status: SubsystemStatus;\n parity: ParityHealth;\n /** Repo-relative marker paths that prove presence. */\n evidence: string[];\n rules: DescribeRule[];\n}\n\nexport interface DescribeConfigFile {\n path: string;\n purpose: string;\n /** Owning subsystem id, or \"-\" when the file belongs to no pjangler recipe. */\n subsystem: string;\n}\n\nexport interface DescribeNextStep {\n title: string;\n reason: string;\n source: \"lifecycle\" | \"registry\" | \"parity\" | \"agents\";\n command?: string;\n /** Parity rule ids this step covers, when it stands in for more than one. */\n rules?: string[];\n /** One line per covered finding. Kept structured \u2014 rule summaries contain\n * their own punctuation, so a joined string cannot be split back apart. */\n details?: string[];\n}\n\nexport interface DescribeGit {\n isRepo: boolean;\n branch?: string;\n head?: string;\n remote?: string;\n /** Count of porcelain entries; 0 means clean. */\n dirtyFiles?: number;\n}\n\nexport interface DescribeDriftNote {\n note: string;\n /** Only set when a command actually resolves this drift. Field-value\n * disagreements have no auto-fix, and claiming one would send the reader\n * to a command that cannot see the problem. */\n command?: string;\n}\n\nexport interface DescribeAgent {\n name: string;\n role: string;\n provisioningState: string;\n roleDir?: string;\n}\n\nexport interface DescribeIdentity {\n /** A `.project.json` manifest exists at the repo root. */\n manifest: boolean;\n /** The repo is present in the pjangler central registry. */\n registered: boolean;\n registryPath: string;\n slug?: string;\n name?: string;\n description?: string;\n // No `status` here on purpose. The registry carries one, but it reads\n // \"planned\" for every project ever registered \u2014 a repo in the registry is by\n // definition past planning \u2014 so it was a field that never varied and never\n // informed. `ProjectDescription.activity` answers the question it pretended\n // to, and answers it from git rather than from a value nobody updates.\n ticketProvider?: {\n type: string;\n workspace?: string;\n identifier?: string;\n boardId?: string;\n state?: string;\n };\n agents: DescribeAgent[];\n /** Disagreements between the manifest and the central registry. */\n drift: DescribeDriftNote[];\n}\n\nexport interface DescribeType {\n primaryLanguage?: string;\n languages: string[];\n /** What the repo *is* \u2014 cli, mcp-server, copier-template, 33god-project\u2026 */\n roles: string[];\n /** `<signal> (<file that proved it>)` lines backing the fields above. */\n evidence: string[];\n}\n\nexport interface ProjectDescription {\n repo: string;\n describedAt: string;\n git: DescribeGit;\n /** When work last happened here, across every branch, worktree, and edit. */\n activity: RepoActivity;\n type: DescribeType;\n identity: DescribeIdentity;\n notebook: {\n declared: boolean;\n bindingState: NotebookBindingState | null;\n notebookId: string | null;\n overviewNoteId: string | null;\n health: null;\n remoteCheck: \"skip\";\n captureAdmission: CaptureAdmissionSummaryV1 | null;\n };\n subsystems: DescribeSubsystem[];\n configFiles: DescribeConfigFile[];\n nextSteps: DescribeNextStep[];\n parity: {\n ok: boolean;\n counts: Record<LifecycleStatus, number>;\n };\n}\n\nexport interface DescribeInput {\n repoArg?: string;\n registryPath?: string;\n /** Injected clock, so relative ages are deterministic under test. */\n now?: Date;\n}\n\n// ---------------------------------------------------------------------------\n// Detection tables\n// ---------------------------------------------------------------------------\n\n/**\n * Marker paths that prove a subsystem is installed, keyed by production recipe\n * id. Recipes carry no presence probe of their own \u2014 their checks answer\n * conformance, not existence \u2014 so presence lives here, next to the recipe ids\n * it mirrors. A recipe with no entry reports `absent` until one is added.\n */\nconst SUBSYSTEM_MARKERS: Record<string, readonly string[]> = {\n \"mise-op-inject\": [\".env.op\"],\n mise: [\"mise.toml\", \".mise.toml\", \".mise/config.toml\"],\n \"agent-hooks\": [\".agents/skills.json\", \".agents/hooks\"],\n bmad: [\"_bmad\"],\n docker: [\"Dockerfile\", \"docker-compose.yml\", \"docker-compose.yaml\", \"compose.yml\", \"compose.yaml\"],\n node: [\"package.json\"],\n \"hermes-agent\": [\"agents/hermes\"],\n project: [\".project.json\"],\n};\n\ninterface LanguageMarker {\n file: string;\n language: string;\n}\n\nconst LANGUAGE_MARKERS: readonly LanguageMarker[] = [\n { file: \"package.json\", language: \"javascript\" },\n { file: \"pyproject.toml\", language: \"python\" },\n { file: \"setup.py\", language: \"python\" },\n { file: \"requirements.txt\", language: \"python\" },\n { file: \"Cargo.toml\", language: \"rust\" },\n { file: \"go.mod\", language: \"go\" },\n { file: \"pom.xml\", language: \"jvm\" },\n { file: \"build.gradle\", language: \"jvm\" },\n { file: \"build.gradle.kts\", language: \"jvm\" },\n { file: \"Gemfile\", language: \"ruby\" },\n { file: \"composer.json\", language: \"php\" },\n];\n\ninterface ConfigFileSpec {\n path: string;\n purpose: string;\n subsystem: string;\n}\n\n/**\n * Config files worth reporting, with the subsystem that owns each. Only paths\n * that exist are emitted, so this stays a lookup table rather than a claim.\n */\nconst CONFIG_FILES: readonly ConfigFileSpec[] = [\n { path: \".project.json\", purpose: \"33GOD project manifest (board binding, agents)\", subsystem: \"project\" },\n { path: \".copier-answers.yml\", purpose: \"CommonProject render provenance\", subsystem: \"project\" },\n { path: \"copier.yml\", purpose: \"Copier template definition\", subsystem: \"-\" },\n { path: \"mise.toml\", purpose: \"Task runner, env, and enter/leave hooks\", subsystem: \"mise\" },\n { path: \".mise/tasks\", purpose: \"File-based mise tasks\", subsystem: \"mise\" },\n { path: \".mise/scripts\", purpose: \"Repo tooling on PATH\", subsystem: \"mise\" },\n { path: \".env.op\", purpose: \"1Password secret references (materialized to .env)\", subsystem: \"mise-op-inject\" },\n { path: \".env.example\", purpose: \"Documented environment contract\", subsystem: \"mise-op-inject\" },\n { path: \".agents/skills.json\", purpose: \"Skillex skill/pack manifest\", subsystem: \"agent-hooks\" },\n { path: \".agents/hooks\", purpose: \"Project-scoped agent hooks SSOT\", subsystem: \"agent-hooks\" },\n { path: \".claude/settings.json\", purpose: \"Generated Claude Code hook config\", subsystem: \"agent-hooks\" },\n { path: \"_bmad\", purpose: \"BMAD methodology install\", subsystem: \"bmad\" },\n { path: \"_bmad-output\", purpose: \"BMAD work products\", subsystem: \"bmad\" },\n { path: \"AGENTS.md\", purpose: \"Agent instruction SSOT\", subsystem: \"-\" },\n { path: \"agents/hermes\", purpose: \"Hermes agent roles for this repo\", subsystem: \"hermes-agent\" },\n { path: \"Dockerfile\", purpose: \"Container image definition\", subsystem: \"docker\" },\n { path: \"docker-compose.yml\", purpose: \"Local service composition\", subsystem: \"docker\" },\n { path: \"package.json\", purpose: \"Node package manifest\", subsystem: \"node\" },\n { path: \"tsconfig.json\", purpose: \"TypeScript compiler config\", subsystem: \"node\" },\n { path: \"pyproject.toml\", purpose: \"Python package manifest\", subsystem: \"-\" },\n { path: \"Cargo.toml\", purpose: \"Rust package manifest\", subsystem: \"-\" },\n { path: \"go.mod\", purpose: \"Go module definition\", subsystem: \"-\" },\n { path: \".gitignore\", purpose: \"Ignore rules\", subsystem: \"-\" },\n { path: \".github/workflows\", purpose: \"GitHub Actions CI\", subsystem: \"-\" },\n];\n\n// ---------------------------------------------------------------------------\n// Probes\n// ---------------------------------------------------------------------------\n\nfunction readJson(path: string): Record<string, unknown> | undefined {\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as unknown;\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction describeGit(repo: string, activity: RepoActivity): DescribeGit {\n if (!isGitRepo(repo)) return { isRepo: false };\n // The activity scan already counted dirty files; re-running `git status`\n // here would be a second scan of the same working tree for the same number.\n return {\n isRepo: true,\n branch: gitLine(repo, [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]),\n head: gitLine(repo, [\"rev-parse\", \"--short\", \"HEAD\"]),\n remote: gitLine(repo, [\"remote\", \"get-url\", \"origin\"]),\n dirtyFiles: activity.scanned.dirtyFiles,\n };\n}\n\nfunction describeType(repo: string): DescribeType {\n const languages: string[] = [];\n const roles: string[] = [];\n const evidence: string[] = [];\n\n const note = (signal: string, file: string) => evidence.push(`${signal} (${file})`);\n\n for (const marker of LANGUAGE_MARKERS) {\n if (!existsSync(join(repo, marker.file))) continue;\n if (!languages.includes(marker.language)) {\n languages.push(marker.language);\n note(marker.language, marker.file);\n }\n }\n\n // Shallow scan only: .NET projects put the manifest at the repo root, and a\n // deep walk would make `describe` pay for the whole tree.\n try {\n const dotnet = readdirSync(repo).find((entry) => entry.endsWith(\".csproj\") || entry.endsWith(\".sln\"));\n if (dotnet && !languages.includes(\"dotnet\")) {\n languages.push(\"dotnet\");\n note(\"dotnet\", dotnet);\n }\n } catch {\n // Unreadable repo root: languages stay as detected so far.\n }\n\n const pkg = readJson(join(repo, \"package.json\"));\n if (pkg) {\n if (existsSync(join(repo, \"tsconfig.json\"))) {\n const index = languages.indexOf(\"javascript\");\n if (index >= 0) languages.splice(index, 1);\n if (!languages.includes(\"typescript\")) {\n languages.unshift(\"typescript\");\n note(\"typescript\", \"tsconfig.json\");\n }\n }\n if (pkg.bin) {\n roles.push(\"cli\");\n note(\"cli\", \"package.json#bin\");\n }\n if (pkg.workspaces) {\n roles.push(\"monorepo\");\n note(\"monorepo\", \"package.json#workspaces\");\n }\n const dependencies = {\n ...(pkg.dependencies as Record<string, string> | undefined),\n ...(pkg.devDependencies as Record<string, string> | undefined),\n };\n if (Object.keys(dependencies).some((name) => name.startsWith(\"@modelcontextprotocol/\"))) {\n roles.push(\"mcp-server\");\n note(\"mcp-server\", \"package.json#@modelcontextprotocol\");\n }\n }\n\n const roleMarkers: readonly (readonly [string, string])[] = [\n [\"copier-template\", \"copier.yml\"],\n [\"container-image\", \"Dockerfile\"],\n [\"compose-stack\", \"docker-compose.yml\"],\n [\"33god-project\", \".project.json\"],\n [\"bmad-project\", \"_bmad\"],\n [\"hermes-fleet-host\", \"agents/hermes\"],\n ];\n for (const [role, marker] of roleMarkers) {\n if (!existsSync(join(repo, marker))) continue;\n roles.push(role);\n note(role, marker);\n }\n\n return { primaryLanguage: languages[0], languages, roles, evidence };\n}\n\nfunction describeIdentity(repo: string, registryPath: string): DescribeIdentity {\n const manifestPath = join(repo, \".project.json\");\n const manifest = readJson(manifestPath);\n const drift: DescribeDriftNote[] = [];\n\n let record: ProjectRecord | undefined;\n let registryReadable = true;\n try {\n const registry = loadProjectRegistry(registryPath);\n const slug = typeof manifest?.project_slug === \"string\" ? manifest.project_slug : undefined;\n const resolved = resolve(repo);\n record = (slug ? registry.projects[slug] : undefined)\n ?? Object.values(registry.projects).find((project) => resolve(project.repo_path) === resolved);\n } catch (err) {\n registryReadable = false;\n drift.push({ note: `registry unreadable: ${err instanceof Error ? err.message : String(err)}` });\n }\n\n if (manifest && !record && registryReadable) {\n drift.push({ note: \".project.json exists but this repo is not in the pjangler registry\" });\n }\n if (record && !manifest) {\n drift.push({ note: `registered as ${record.slug} but .project.json is missing`, command: \"pjangler project doctor\" });\n }\n if (record && resolve(record.repo_path) !== resolve(repo)) {\n drift.push({ note: `registry repo_path points elsewhere: ${record.repo_path}`, command: \"pjangler project doctor\" });\n }\n\n // `.project.json` is the single source of truth for the board binding, so the\n // manifest wins and any registry disagreement is reported as drift rather\n // than silently overriding what the repo declares about its own board.\n const manifestProvider = manifest?.ticket_provider as Record<string, unknown> | undefined;\n const provider = manifestProvider\n ? {\n type: String(manifestProvider.type ?? \"\"),\n workspace: manifestProvider.workspace as string | undefined,\n identifier: manifestProvider.identifier as string | undefined,\n board_id: manifestProvider.board_id as string | undefined,\n state: manifestProvider.state as string | undefined,\n }\n : record?.ticket_provider;\n\n if (manifestProvider && record) {\n const fields = [\n [\"type\", provider?.type, record.ticket_provider.type],\n [\"workspace\", provider?.workspace, record.ticket_provider.workspace],\n [\"identifier\", provider?.identifier, record.ticket_provider.identifier],\n [\"board_id\", provider?.board_id, record.ticket_provider.board_id],\n ] as const;\n for (const [field, fromManifest, fromRegistry] of fields) {\n if ((fromManifest ?? \"\") === (fromRegistry ?? \"\")) continue;\n // No command here on purpose: `project doctor` checks paths and manifest\n // presence, not field values, so it would report this as healthy.\n drift.push({\n note: `ticket_provider.${field} differs: .project.json has \"${fromManifest ?? \"\"}\", registry has \"${fromRegistry ?? \"\"}\" \u2014 the manifest is the source of truth, so the registry record needs re-syncing`,\n });\n }\n }\n\n const manifestAgents = (manifest?.agents ?? {}) as Record<string, Record<string, unknown>>;\n const agents: DescribeAgent[] = record\n ? Object.entries(record.agents).map(([name, agent]) => ({\n name,\n role: agent.role,\n provisioningState: agent.provisioning_state,\n roleDir: agent.role_dir,\n }))\n : Object.entries(manifestAgents).map(([name, agent]) => ({\n name,\n role: String(agent?.role ?? \"unknown\"),\n provisioningState: String(agent?.provisioning_state ?? \"unknown\"),\n roleDir: agent?.role_dir as string | undefined,\n }));\n\n return {\n manifest: Boolean(manifest),\n registered: Boolean(record),\n registryPath,\n slug: record?.slug ?? (manifest?.project_slug as string | undefined),\n name: record?.name ?? (manifest?.project_name as string | undefined),\n description: record?.description ?? (manifest?.project_description as string | undefined),\n ticketProvider: provider\n ? {\n type: provider.type,\n workspace: provider.workspace,\n identifier: provider.identifier,\n boardId: provider.board_id,\n state: provider.state,\n }\n : undefined,\n agents,\n drift,\n };\n}\n\nfunction describeSubsystems(repo: string, findings: readonly LifecycleAuditFinding[]): DescribeSubsystem[] {\n const byRecipe = new Map<string, LifecycleAuditFinding[]>();\n for (const finding of findings) {\n if (!finding.recipeId) continue;\n const bucket = byRecipe.get(finding.recipeId) ?? [];\n bucket.push(finding);\n byRecipe.set(finding.recipeId, bucket);\n }\n\n return recipeRegistry.list().map((metadata) => {\n const markers = SUBSYSTEM_MARKERS[metadata.id] ?? [];\n const evidence = metadata.id === \"notebook\"\n ? (() => {\n try {\n const manifest = JSON.parse(readFileSync(join(repo, \".project.json\"), \"utf8\")) as Record<string, unknown>;\n return manifest.notebook && typeof manifest.notebook === \"object\" ? [\".project.json#notebook\"] : [];\n } catch { return []; }\n })()\n : markers.filter((marker) => existsSync(join(repo, marker)));\n const rules = (byRecipe.get(metadata.id) ?? []).map((finding) => ({\n id: finding.id,\n title: finding.title,\n status: finding.status,\n summary: finding.summary,\n fixable: finding.fixable,\n }));\n\n // \"skip\" means the rule did not apply here, so it votes neither way.\n const graded = rules.filter((rule) => rule.status !== \"skip\");\n const parity: ParityHealth = graded.length === 0\n ? \"unchecked\"\n : graded.every((rule) => rule.status === \"pass\")\n ? \"ok\"\n : \"drift\";\n\n const present = evidence.length > 0;\n const status: SubsystemStatus = !present ? \"absent\" : parity === \"drift\" ? \"drifted\" : \"installed\";\n\n return { id: metadata.id, name: metadata.name, description: metadata.description, status, parity, evidence, rules };\n });\n}\n\nfunction describeNotebook(repo: string, registryPath: string): ProjectDescription[\"notebook\"] {\n try {\n const registry = loadProjectRegistry(registryPath);\n const project = Object.values(registry.projects).find((entry) => resolve(entry.repo_path) === resolve(repo));\n const manifest = existsSync(join(repo, \".project.json\")) ? JSON.parse(readFileSync(join(repo, \".project.json\"), \"utf8\")) as Record<string, unknown> : undefined;\n const declared = Boolean(project?.notebook || (manifest?.notebook && typeof manifest.notebook === \"object\"));\n if (!declared) return { declared: false, bindingState: null, notebookId: null, overviewNoteId: null, health: null, remoteCheck: \"skip\", captureAdmission: null };\n const config = loadEffectiveNotebookConfig(repo, registryPath);\n return {\n declared: true,\n bindingState: config.binding.state,\n notebookId: config.binding.notebook_id ?? null,\n overviewNoteId: config.binding.overview_note_id ?? null,\n health: null,\n remoteCheck: \"skip\",\n captureAdmission: captureAdmissionSummary(notebookStateRoot(), config.project_slug, config.limits),\n };\n } catch {\n return { declared: true, bindingState: null, notebookId: null, overviewNoteId: null, health: null, remoteCheck: \"skip\", captureAdmission: null };\n }\n}\n\nfunction describeConfigFiles(repo: string): DescribeConfigFile[] {\n return CONFIG_FILES\n .filter((spec) => existsSync(join(repo, spec.path)))\n .map((spec) => ({ path: spec.path, purpose: spec.purpose, subsystem: spec.subsystem }));\n}\n\nfunction describeNextSteps(\n description: Omit<ProjectDescription, \"nextSteps\">,\n findings: readonly LifecycleAuditFinding[],\n): DescribeNextStep[] {\n const steps: DescribeNextStep[] = [];\n\n if (!description.git.isRepo) {\n steps.push({\n title: \"Initialize a git repository\",\n reason: \"pjangler lifecycle operations and parity rules assume a git work tree\",\n source: \"lifecycle\",\n command: \"git init\",\n });\n }\n\n if (!description.identity.manifest) {\n steps.push({\n title: \"Register this repo as a 33GOD project\",\n reason: \"no .project.json \u2014 the board binding and agent roster have nowhere to live\",\n source: \"lifecycle\",\n command: \"pjangler init --apply\",\n });\n } else if (!description.identity.registered) {\n steps.push({\n title: \"Add this project to the pjangler registry\",\n reason: \".project.json exists but the central registry has no entry for this repo\",\n source: \"registry\",\n command: `pjangler project init ${description.identity.name ?? \"\"} --target-dir . --apply`.replace(/\\s+/g, \" \"),\n });\n }\n\n for (const entry of description.identity.drift) {\n if (entry.note.startsWith(\".project.json exists but\")) continue; // already emitted above\n steps.push({\n title: \"Reconcile project registry drift\",\n reason: entry.note,\n source: \"registry\",\n ...(entry.command ? { command: entry.command } : {}),\n });\n }\n\n // Fixable drift collapses into one step because `migrate --all` selects\n // exactly this set (every fixable fail/warn rule) in one pass. Listing them\n // one-per-line would bury the handful of findings that actually need hands.\n const failing = findings.filter((finding) => finding.status === \"fail\" || finding.status === \"warn\");\n const fixable = failing.filter((finding) => finding.fixable);\n if (fixable.length === 1) {\n const only = fixable[0]!;\n steps.push({\n title: `Fix ${only.id}`,\n reason: only.summary,\n source: \"parity\",\n command: `pjangler migrate ${only.id}`,\n rules: [only.id],\n });\n } else if (fixable.length > 1) {\n steps.push({\n title: `Apply ${fixable.length} parity migrations`,\n reason: `${fixable.length} fixable parity rules are failing; migrate --all selects exactly this set`,\n source: \"parity\",\n command: \"pjangler migrate --all\",\n rules: fixable.map((finding) => finding.id),\n details: fixable.map((finding) => `${finding.id}: ${finding.summary}`),\n });\n }\n\n for (const finding of failing) {\n if (finding.fixable) continue;\n steps.push({\n title: `Resolve ${finding.id} manually`,\n reason: `${finding.summary} \u2014 no migration recipe, this one needs hands`,\n source: \"parity\",\n rules: [finding.id],\n });\n }\n\n for (const agent of description.identity.agents) {\n if (agent.provisioningState === \"provisioned\") continue;\n steps.push({\n title: `Provision the ${agent.role} agent`,\n reason: `${agent.name} is ${agent.provisioningState}, not provisioned`,\n source: \"agents\",\n command: `pjangler hermes-agent --role ${agent.role}`,\n });\n }\n\n return steps;\n}\n\n// ---------------------------------------------------------------------------\n// Entry point\n// ---------------------------------------------------------------------------\n\n/** Read a repo and produce its full machine-readable description. */\nexport function describeProject(input: DescribeInput = {}): ProjectDescription {\n const repo = resolve(input.repoArg ?? process.cwd());\n if (!existsSync(repo)) throw new Error(`Path does not exist: ${repo}`);\n if (!statSync(repo).isDirectory()) throw new Error(`Not a directory: ${repo}`);\n\n const registryPath = input.registryPath ?? projectRegistryPath();\n const report = recipeRegistry.auditRecipes(lifecycleContext(repo, true, false, { registryPath }));\n const findings = report.rules;\n\n const counts: Record<LifecycleStatus, number> = { pass: 0, fail: 0, warn: 0, skip: 0 };\n for (const finding of findings) counts[finding.status] += 1;\n\n const activity = computeRepoActivity(repo, { now: input.now });\n const partial = {\n repo,\n describedAt: report.auditedAt,\n git: describeGit(repo, activity),\n activity,\n type: describeType(repo),\n identity: describeIdentity(repo, registryPath),\n notebook: describeNotebook(repo, registryPath),\n subsystems: describeSubsystems(repo, findings),\n configFiles: describeConfigFiles(repo),\n parity: { ok: report.ok, counts },\n };\n\n return { ...partial, nextSteps: describeNextSteps(partial, findings) };\n}\n\n// ---------------------------------------------------------------------------\n// Presentation\n//\n// Laid out like a `gh` subcommand: a header that answers \"what am I looking\n// at\" in three lines, then labelled sections with an aligned key column. No box\n// drawing \u2014 alignment, weight and color carry the structure, which survives\n// NO_COLOR and a narrow terminal in a way ASCII frames do not.\n//\n// `renderDescribe` takes width as a PARAMETER and never reads process.stdout,\n// so the same renderer serves the terminal, the MCP transport, and tests\n// without any of them disagreeing about how wide the world is.\n// ---------------------------------------------------------------------------\n\nconst MIN_WIDTH = 60;\nconst MAX_WIDTH = 120;\n\n/** Label column for the header key/value block. */\nconst LABEL = 11;\n\nconst SUBSYSTEM_STYLE: Record<SubsystemStatus, { glyph: string; color: (value: string | number) => string }> = {\n installed: { glyph: glyph.pass, color: green },\n drifted: { glyph: glyph.warn, color: yellow },\n absent: { glyph: glyph.skip, color: gray },\n};\n\nexport interface RenderOptions {\n /** Visible columns to lay out within. Clamped to a readable range. */\n width?: number;\n /** Home directory to abbreviate as `~` in paths. */\n home?: string;\n}\n\n/** `~/code/x` instead of `/home/someone/code/x` \u2014 shorter and less noisy. */\nfunction shortenPath(path: string, home?: string): string {\n const base = home ?? process.env.HOME;\n return base && path.startsWith(`${base}/`) ? `~${path.slice(base.length)}` : path;\n}\n\nfunction section(title: string, count?: string): string {\n return `${bold(title)}${count ? ` ${dim(count)}` : \"\"}`;\n}\n\nfunction field(label: string, value: string): string {\n return ` ${dim(padEndRaw(label, LABEL))}${value}`;\n}\n\n/** Pad the RAW label before it is colored \u2014 see the note in utils/style. */\nfunction padEndRaw(value: string, width: number): string {\n return value.padEnd(width);\n}\n\n/**\n * Render the report as lines.\n *\n * Returns an array rather than a string so the interactive layer can splice in\n * its own footer without re-parsing text it just produced.\n */\nexport function renderDescribe(description: ProjectDescription, options: RenderOptions = {}): string[] {\n const width = Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, options.width ?? 100));\n const { identity, type, git, activity } = description;\n const lines: string[] = [\"\"];\n\n // --- Header ---------------------------------------------------------------\n const title = identity.name ?? description.repo.split(\"/\").pop() ?? description.repo;\n const badge = identity.ticketProvider?.identifier ? ` ${cyan(identity.ticketProvider.identifier)}` : \"\";\n const pulse = activity.updatedUnix\n ? `${activity.active ? green(\"\u25CF\") : yellow(\"\u25CB\")} ${activity.active ? green(activity.relative) : yellow(activity.relative)}`\n : dim(`${glyph.skip} never`);\n const left = ` ${bold(title)}${badge}`;\n const gap = Math.max(2, width - visibleWidth(left) - visibleWidth(pulse) - 2);\n lines.push(`${left}${\" \".repeat(gap)}${pulse}`);\n if (identity.description) lines.push(` ${dim(truncateVisible(identity.description, width - 4))}`);\n lines.push(` ${dim(truncateVisible(shortenPath(description.repo, options.home), width - 4))}`);\n lines.push(\"\");\n\n // --- Facts ----------------------------------------------------------------\n const typeFacts = [type.primaryLanguage, ...type.roles].filter(Boolean) as string[];\n lines.push(field(\"type\", typeFacts.length\n ? typeFacts.map((fact) => cyan(fact)).join(dim(\" \u00B7 \"))\n : dim(\"undetermined \u2014 no language or role markers found\")));\n\n if (activity.source) {\n lines.push(field(\"updated\", `${activity.relative} ${dim(`${glyph.dot} ${activity.source.label}`)}`));\n }\n\n if (identity.ticketProvider) {\n const provider = identity.ticketProvider;\n const board = [provider.type, provider.workspace, provider.identifier].filter(Boolean).join(\"/\");\n lines.push(field(\"board\", `${cyan(board)}${provider.state ? ` ${dim(provider.state)}` : \"\"}`));\n }\n\n if (git.isRepo) {\n const facts = [cyan(git.branch ?? \"?\")];\n if (git.head) facts.push(dim(git.head));\n facts.push(git.dirtyFiles ? yellow(`${git.dirtyFiles} uncommitted`) : green(\"clean\"));\n lines.push(field(\"git\", facts.join(dim(\" \u00B7 \"))));\n if (git.remote) lines.push(field(\"remote\", dim(truncateVisible(git.remote, width - LABEL - 4))));\n } else {\n lines.push(field(\"git\", yellow(\"not a git repository\")));\n }\n\n const registryNote = identity.registered ? green(\"registered\") : yellow(\"not registered\");\n // Clamp like the `remote` row above: a registry outside $HOME (a --registry\n // override, a deep TMPDIR) is an unbounded string and blew straight past the\n // layout width.\n const registryPath = shortenPath(identity.registryPath, options.home);\n const registryRoom = Math.max(10, width - LABEL - visibleWidth(registryNote) - 6);\n lines.push(field(\"registry\", `${registryNote} ${dim(truncateVisible(registryPath, registryRoom))}`));\n if (description.notebook.declared) {\n const state = description.notebook.bindingState ?? \"invalid\";\n const capture = description.notebook.captureAdmission;\n const usage = capture ? ` \u00B7 unresolved ${capture.unresolved_count ?? \"unknown\"}/${capture.receipt_caps.max_count}` : \"\";\n lines.push(field(\"notebook\", `${cyan(state)}${dim(`${usage} \u00B7 remote not observed`)}`));\n }\n\n for (const agent of identity.agents) {\n const state = agent.provisioningState === \"provisioned\"\n ? green(agent.provisioningState)\n : yellow(agent.provisioningState);\n lines.push(field(\"agent\", `${cyan(agent.name)} ${dim(agent.role)} ${state}`));\n }\n\n for (const entry of identity.drift) {\n lines.push(\"\");\n for (const [index, wrapped] of wrapVisible(entry.note, width - 6).entries()) {\n lines.push(index === 0 ? ` ${yellow(glyph.warn)} ${wrapped}` : ` ${dim(wrapped)}`);\n }\n }\n lines.push(\"\");\n\n // --- Subsystems -----------------------------------------------------------\n const present = description.subsystems.filter((subsystem) => subsystem.status !== \"absent\");\n lines.push(section(\"Subsystems\", `${present.length}/${description.subsystems.length} installed`));\n const nameWidth = description.subsystems.reduce((max, subsystem) => Math.max(max, subsystem.name.length), 0);\n for (const subsystem of description.subsystems) {\n const style = SUBSYSTEM_STYLE[subsystem.status];\n const failing = subsystem.rules.filter((rule) => rule.status === \"fail\" || rule.status === \"warn\");\n const detail = subsystem.status === \"absent\"\n ? dim(subsystem.description)\n : failing.length\n ? yellow(failing.map((rule) => rule.id).join(\", \"))\n : dim(subsystem.evidence.join(\", \") || subsystem.description);\n const head = ` ${style.color(style.glyph)} ${style.color(padEndRaw(subsystem.name, nameWidth))}`;\n lines.push(`${head} ${truncateVisible(detail, Math.max(10, width - nameWidth - 8))}`);\n }\n lines.push(\"\");\n\n // --- Config ---------------------------------------------------------------\n lines.push(section(\"Config\", `${description.configFiles.length} file${description.configFiles.length === 1 ? \"\" : \"s\"}`));\n if (!description.configFiles.length) lines.push(` ${dim(\"(none found)\")}`);\n const pathWidth = description.configFiles.reduce((max, file) => Math.max(max, file.path.length), 0);\n for (const file of description.configFiles) {\n const purpose = truncateVisible(file.purpose, Math.max(10, width - pathWidth - 6));\n lines.push(` ${cyan(padEndRaw(file.path, pathWidth))} ${dim(purpose)}`);\n }\n lines.push(\"\");\n\n // --- Parity ---------------------------------------------------------------\n const { counts } = description.parity;\n lines.push(`${section(\"Parity\")} ${[\n counts.pass ? green(`${counts.pass} passed`) : dim(\"0 passed\"),\n counts.fail ? red(`${counts.fail} failed`) : dim(\"0 failed\"),\n counts.warn ? yellow(`${counts.warn} warning${counts.warn === 1 ? \"\" : \"s\"}`) : dim(\"0 warnings\"),\n dim(`${counts.skip} skipped`),\n ].join(dim(\" \u00B7 \"))}`);\n lines.push(\"\");\n\n // --- Next steps -----------------------------------------------------------\n lines.push(section(\"Next steps\", String(description.nextSteps.length)));\n if (!description.nextSteps.length) {\n lines.push(` ${green(glyph.pass)} ${dim(\"Nothing pending \u2014 parity is clean and the project is fully registered.\")}`);\n }\n for (const [index, step] of description.nextSteps.entries()) {\n lines.push(` ${cyan(String(index + 1).padStart(2))} ${bold(step.title)}`);\n const body = step.details?.length ? step.details : [step.reason];\n for (const entry of body) {\n for (const [wrapIndex, wrapped] of wrapVisible(entry, width - 8).entries()) {\n lines.push(` ${wrapIndex === 0 && step.details?.length ? dim(`${glyph.dot} `) : \" \"}${dim(wrapped)}`);\n }\n }\n if (step.command) lines.push(` ${dim(glyph.pointer)} ${cyan(step.command)}`);\n }\n lines.push(\"\");\n\n return lines;\n}\n\n/** Render the report as the human-facing `pjangler describe` output. */\nexport function formatProjectDescription(description: ProjectDescription, options: RenderOptions = {}): string {\n return renderDescribe(description, { width: options.width ?? terminalWidth(), home: options.home }).join(\"\\n\");\n}\n", "// Repo activity \u2014 \"when was work last done here?\"\n//\n// This replaces the `status` field, which claimed `planned` for 22 of the 27\n// registered projects \u2014 pjangler itself among them, on a day it had commits.\n// A repo in the registry is by definition past planning, so the field never\n// varied and never informed.\n//\n// Activity is temporal instead of categorical, and COMPUTED instead of stored.\n// A stored status goes stale the moment someone commits, which is exactly how\n// the old one ended up wrong everywhere; deriving it from git at read time\n// means it cannot drift, and no cron has to walk every project to keep it\n// fresh. (The registry's own `updated_at` is not a substitute: it records the\n// last registry write, not the last piece of work.)\n//\n// \"Work\" deliberately spans more than the checked-out branch:\n//\n// refs every local branch, remote-tracking branch, and tag\n// worktrees every linked worktree's HEAD, which catches detached HEADs\n// whose commits are on no ref at all\n// uncommitted changes in the working tree that are not committed yet\n//\n// That breadth is not theoretical. Across the live registry, the newest work\n// in several projects (deckard, intelliforia, slowburns) lives in a worktree,\n// so a naive `git log -1` on the checked-out branch reports them as stale.\n//\n// Honesty note: remote-tracking refs reflect the last fetch, not the live\n// remote. Asking the network would mean a round trip per project, which is\n// unacceptable on a shell prompt. The winning source is always reported, so a\n// reader can see whether the answer came from local or remote state.\n//\n// Structure: the parsing is pure and the IO is a thin driver, in two flavours\n// (sync for one repo, async for scanning the whole registry concurrently).\n// The tricky part is the parsing, and keeping it pure means it is unit\n// testable without constructing a repo for every edge case.\n\nimport { spawn, spawnSync } from \"node:child_process\";\nimport { statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/** A repo counts as active when the newest work is within this window. */\nexport const ACTIVE_WINDOW_SECONDS = 24 * 60 * 60;\n\n/** Stop stat-ing dirty files past this many; the newest mtime converges fast. */\nconst MAX_DIRTY_STATS = 500;\n\nexport type ActivityKind = \"ref\" | \"worktree\" | \"uncommitted\";\n\nexport interface ActivitySource {\n kind: ActivityKind;\n /** Human label for the winning source: \"main\", \"origin/feat/x\", \"3 files\". */\n label: string;\n unix: number;\n}\n\nexport interface RepoActivity {\n /** ISO-8601 of the newest work, or null when the repo has no history. */\n updated: string | null;\n updatedUnix: number | null;\n /** \"3 hours ago\" \u2014 or \"never\" when nothing has happened yet. */\n relative: string;\n /** Compact form for space-constrained surfaces like a shell prompt: \"3h\". */\n compact: string;\n /** Newest work is within ACTIVE_WINDOW_SECONDS. */\n active: boolean;\n source: ActivitySource | null;\n scanned: { refs: number; worktrees: number; dirtyFiles: number };\n}\n\nexport interface ActivityOptions {\n /** Injected clock. Tests pass a fixed instant; production passes nothing. */\n now?: Date;\n}\n\n// ---------------------------------------------------------------------------\n// git plumbing\n// ---------------------------------------------------------------------------\n\nconst GIT_TIMEOUT_MS = 5_000;\nconst GIT_MAX_BUFFER = 16 * 1024 * 1024;\n\n/** Run a git subcommand in `repo`. Returns raw stdout, or undefined on failure. */\nexport function git(repo: string, args: string[]): string | undefined {\n const result = spawnSync(\"git\", [\"-C\", repo, ...args], {\n encoding: \"utf8\",\n timeout: GIT_TIMEOUT_MS,\n maxBuffer: GIT_MAX_BUFFER,\n });\n if (result.status !== 0 || typeof result.stdout !== \"string\") return undefined;\n return result.stdout;\n}\n\n/** Async twin of `git`, so a registry scan can run repos concurrently. */\nexport function gitAsync(repo: string, args: string[]): Promise<string | undefined> {\n return new Promise((resolve) => {\n const child = spawn(\"git\", [\"-C\", repo, ...args], { stdio: [\"ignore\", \"pipe\", \"ignore\"] });\n let out = \"\";\n let size = 0;\n let settled = false;\n const finish = (value: string | undefined) => {\n if (settled) return;\n settled = true;\n resolve(value);\n };\n const timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n finish(undefined);\n }, GIT_TIMEOUT_MS);\n timer.unref?.();\n\n child.stdout.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => {\n size += chunk.length;\n if (size > GIT_MAX_BUFFER) {\n child.kill(\"SIGKILL\");\n finish(undefined);\n return;\n }\n out += chunk;\n });\n child.on(\"error\", () => {\n clearTimeout(timer);\n finish(undefined);\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n finish(code === 0 ? out : undefined);\n });\n });\n}\n\nfunction trimmed(raw: string | undefined): string | undefined {\n if (raw === undefined) return undefined;\n const value = raw.trim();\n return value === \"\" ? undefined : value;\n}\n\n/** Run a git subcommand and trim; undefined for failure or empty output. */\nexport function gitLine(repo: string, args: string[]): string | undefined {\n return trimmed(git(repo, args));\n}\n\nexport function isGitRepo(repo: string): boolean {\n return gitLine(repo, [\"rev-parse\", \"--is-inside-work-tree\"]) === \"true\";\n}\n\n// ---------------------------------------------------------------------------\n// Relative time\n// ---------------------------------------------------------------------------\n\nconst MINUTE = 60;\nconst HOUR = 60 * MINUTE;\nconst DAY = 24 * HOUR;\nconst WEEK = 7 * DAY;\nconst MONTH = 30 * DAY;\nconst YEAR = 365 * DAY;\n\nfunction plural(count: number, unit: string): string {\n return `${count} ${unit}${count === 1 ? \"\" : \"s\"} ago`;\n}\n\n/**\n * Human relative age. Deterministic and clock-injected so it is testable \u2014 no\n * \"about a minute\" fuzz, because a tool reporting staleness should be precise\n * about which bucket it chose.\n */\nexport function formatRelativeAge(deltaSeconds: number): string {\n const delta = Math.max(0, Math.floor(deltaSeconds));\n if (delta < MINUTE) return \"just now\";\n if (delta < HOUR) return plural(Math.floor(delta / MINUTE), \"minute\");\n if (delta < DAY) return plural(Math.floor(delta / HOUR), \"hour\");\n if (delta < WEEK) return plural(Math.floor(delta / DAY), \"day\");\n if (delta < MONTH) return plural(Math.floor(delta / WEEK), \"week\");\n if (delta < YEAR) return plural(Math.floor(delta / MONTH), \"month\");\n return plural(Math.floor(delta / YEAR), \"year\");\n}\n\n/** Same ladder, one or two characters wide, for prompts: \"now\", \"5m\", \"3d\". */\nexport function formatCompactAge(deltaSeconds: number): string {\n const delta = Math.max(0, Math.floor(deltaSeconds));\n if (delta < MINUTE) return \"now\";\n if (delta < HOUR) return `${Math.floor(delta / MINUTE)}m`;\n if (delta < DAY) return `${Math.floor(delta / HOUR)}h`;\n if (delta < WEEK) return `${Math.floor(delta / DAY)}d`;\n if (delta < MONTH) return `${Math.floor(delta / WEEK)}w`;\n if (delta < YEAR) return `${Math.floor(delta / MONTH)}mo`;\n return `${Math.floor(delta / YEAR)}y`;\n}\n\n// ---------------------------------------------------------------------------\n// Commands (pure) \u2014 what to ask git\n// ---------------------------------------------------------------------------\n\nexport const REF_ARGS = [\n \"for-each-ref\",\n \"--sort=-committerdate\",\n \"--format=%(committerdate:unix)%09%(refname:short)\",\n \"refs/heads\",\n \"refs/remotes\",\n \"refs/tags\",\n];\n\nexport const WORKTREE_ARGS = [\"worktree\", \"list\", \"--porcelain\"];\n\n/**\n * `--porcelain -z` is deliberate: the non-`-z` form C-quotes paths containing\n * spaces or unicode, and un-quoting that correctly is a parser nobody should\n * write. NUL separation sidesteps it.\n *\n * `--ignore-submodules=dirty` is also deliberate, on both cost and correctness\n * grounds. Cost: without it `git status` recurses into every submodule working\n * tree \u2014 measured at 100ms on the 33GOD superproject versus under a\n * millisecond with it, which alone would rule out the shell-prompt path.\n * Correctness: a submodule is its own repo with its own registry entry and its\n * own activity, so edits inside it are that project's work, not the\n * superproject's. Committed submodule POINTER moves still count, because those\n * genuinely are changes to this repo.\n */\nexport const STATUS_ARGS = [\"status\", \"--porcelain\", \"-z\", \"--ignore-submodules=dirty\"];\n\n// ---------------------------------------------------------------------------\n// Parsers (pure) \u2014 what git said\n// ---------------------------------------------------------------------------\n\nexport interface WorktreeEntry {\n path: string;\n sha: string;\n detached: boolean;\n}\n\n/** Newest ref plus the total ref count, from one sorted ref walk. */\nexport function parseRefs(raw: string | undefined): { source?: ActivitySource; count: number } {\n if (raw === undefined) return { count: 0 };\n const lines = raw.split(\"\\n\").filter((line) => line.trim() !== \"\");\n if (!lines.length) return { count: 0 };\n\n const [stamp, name] = lines[0]!.split(\"\\t\");\n const unix = Number(stamp);\n if (!Number.isFinite(unix) || unix <= 0) return { count: lines.length };\n return { source: { kind: \"ref\", label: name ?? \"(unnamed ref)\", unix }, count: lines.length };\n}\n\nexport function parseWorktrees(raw: string | undefined): WorktreeEntry[] {\n if (raw === undefined) return [];\n const entries: WorktreeEntry[] = [];\n let current: { path?: string; sha?: string; detached: boolean } = { detached: false };\n const flush = () => {\n if (current.path && current.sha) entries.push({ path: current.path, sha: current.sha, detached: current.detached });\n current = { detached: false };\n };\n for (const line of raw.split(\"\\n\")) {\n if (line.startsWith(\"worktree \")) {\n flush();\n current.path = line.slice(\"worktree \".length);\n } else if (line.startsWith(\"HEAD \")) {\n current.sha = line.slice(\"HEAD \".length).trim();\n } else if (line === \"detached\") {\n current.detached = true;\n }\n }\n flush();\n return entries;\n}\n\n/** Pick the newest worktree HEAD out of a `git show -s --format=%ct %H` batch. */\nexport function parseWorktreeStamps(raw: string | undefined, entries: readonly WorktreeEntry[]): ActivitySource | undefined {\n if (raw === undefined) return undefined;\n let best: ActivitySource | undefined;\n for (const line of raw.split(\"\\n\")) {\n const [stamp, sha] = line.trim().split(\" \");\n const unix = Number(stamp);\n if (!Number.isFinite(unix) || unix <= 0 || !sha) continue;\n if (best && unix <= best.unix) continue;\n const owner = entries.find((entry) => entry.sha === sha);\n const name = owner ? basenameOf(owner.path) : sha.slice(0, 7);\n best = { kind: \"worktree\", label: owner?.detached ? `${name} (detached)` : name, unix };\n }\n return best;\n}\n\n/**\n * Paths from `git status --porcelain -z`. Every entry is \"XY <path>\"; renames\n * and copies are followed by a bare origin path with no status prefix, which\n * is consumed rather than treated as a second change.\n */\nexport function parseStatusPaths(raw: string | undefined): string[] {\n if (raw === undefined) return [];\n const parts = raw.split(\"\\0\").filter((part) => part !== \"\");\n const paths: string[] = [];\n for (let index = 0; index < parts.length; index++) {\n const entry = parts[index]!;\n if (entry.length < 4 || entry[2] !== \" \") continue;\n paths.push(entry.slice(3));\n if (entry[0] === \"R\" || entry[0] === \"C\") index += 1;\n }\n return paths;\n}\n\nfunction basenameOf(path: string): string {\n const parts = path.split(\"/\").filter(Boolean);\n return parts[parts.length - 1] ?? path;\n}\n\n/**\n * Newest mtime among uncommitted paths. This is what makes \"active\" true while\n * you are mid-edit and have not committed yet \u2014 the case a commit-only signal\n * misses entirely.\n */\nexport function uncommittedSource(repo: string, paths: readonly string[]): ActivitySource | undefined {\n if (!paths.length) return undefined;\n let newest = 0;\n for (const path of paths.slice(0, MAX_DIRTY_STATS)) {\n try {\n const mtime = Math.floor(statSync(join(repo, path)).mtimeMs / 1000);\n if (mtime > newest) newest = mtime;\n } catch {\n // Deleted (or unreadable) paths have no mtime to contribute.\n }\n }\n if (newest <= 0) return undefined;\n const label = paths.length === 1 ? \"1 uncommitted file\" : `${paths.length} uncommitted files`;\n return { kind: \"uncommitted\", label, unix: newest };\n}\n\n// ---------------------------------------------------------------------------\n// Assembly (pure)\n// ---------------------------------------------------------------------------\n\nconst NO_ACTIVITY: RepoActivity = {\n updated: null,\n updatedUnix: null,\n relative: \"never\",\n compact: \"\u2014\",\n active: false,\n source: null,\n scanned: { refs: 0, worktrees: 0, dirtyFiles: 0 },\n};\n\n/** Empty activity, for a path that is not a git repo at all. */\nexport function emptyActivity(): RepoActivity {\n return { ...NO_ACTIVITY, scanned: { refs: 0, worktrees: 0, dirtyFiles: 0 } };\n}\n\n/**\n * Ties break toward immediacy (uncommitted > worktree > ref): when a commit\n * and a working-tree edit share a second, the edit is the later event.\n */\nexport function assembleActivity(\n candidates: readonly (ActivitySource | undefined)[],\n scanned: RepoActivity[\"scanned\"],\n now?: Date,\n): RepoActivity {\n let winner: ActivitySource | null = null;\n for (const candidate of candidates) {\n if (!candidate) continue;\n if (!winner || candidate.unix >= winner.unix) winner = candidate;\n }\n if (!winner) return { ...NO_ACTIVITY, scanned };\n\n const nowUnix = Math.floor((now?.getTime() ?? Date.now()) / 1000);\n const delta = nowUnix - winner.unix;\n return {\n updated: new Date(winner.unix * 1000).toISOString(),\n updatedUnix: winner.unix,\n relative: formatRelativeAge(delta),\n compact: formatCompactAge(delta),\n active: delta < ACTIVE_WINDOW_SECONDS,\n source: winner,\n scanned,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Drivers\n// ---------------------------------------------------------------------------\n\n/**\n * Newest work across every branch, worktree, and uncommitted change.\n *\n * There is deliberately no \"fast, less accurate\" variant. The three probes\n * together measure ~8ms of git, and the ~5ms a ref-only shortcut would save\n * comes at the cost of missing detached worktrees entirely \u2014 a repo whose work\n * happens in a detached worktree would report months of staleness. That is the\n * exact coverage this function exists to provide, so it is not optional.\n */\nexport function computeRepoActivity(repo: string, options: ActivityOptions = {}): RepoActivity {\n if (!isGitRepo(repo)) return emptyActivity();\n\n const refs = parseRefs(git(repo, REF_ARGS));\n const worktrees = parseWorktrees(git(repo, WORKTREE_ARGS));\n const shas = [...new Set(worktrees.map((entry) => entry.sha))];\n const worktreeSource = shas.length\n ? parseWorktreeStamps(git(repo, [\"show\", \"-s\", \"--format=%ct %H\", ...shas]), worktrees)\n : undefined;\n const paths = parseStatusPaths(git(repo, STATUS_ARGS));\n\n return assembleActivity(\n [refs.source, worktreeSource, uncommittedSource(repo, paths)],\n { refs: refs.count, worktrees: worktrees.length, dirtyFiles: paths.length },\n options.now,\n );\n}\n\n/** Async twin of `computeRepoActivity`, for concurrent registry scans. */\nexport async function computeRepoActivityAsync(repo: string, options: ActivityOptions = {}): Promise<RepoActivity> {\n if (trimmed(await gitAsync(repo, [\"rev-parse\", \"--is-inside-work-tree\"])) !== \"true\") return emptyActivity();\n\n const [refRaw, worktreeRaw, statusRaw] = await Promise.all([\n gitAsync(repo, REF_ARGS),\n gitAsync(repo, WORKTREE_ARGS),\n gitAsync(repo, STATUS_ARGS),\n ]);\n\n const refs = parseRefs(refRaw);\n const worktrees = parseWorktrees(worktreeRaw);\n const shas = [...new Set(worktrees.map((entry) => entry.sha))];\n const worktreeSource = shas.length\n ? parseWorktreeStamps(await gitAsync(repo, [\"show\", \"-s\", \"--format=%ct %H\", ...shas]), worktrees)\n : undefined;\n const paths = parseStatusPaths(statusRaw);\n\n return assembleActivity(\n [refs.source, worktreeSource, uncommittedSource(repo, paths)],\n { refs: refs.count, worktrees: worktrees.length, dirtyFiles: paths.length },\n options.now,\n );\n}\n\n/**\n * Activity for many repos at once, keyed by the path passed in.\n *\n * Scanning the live registry serially costs ~450ms across 27 projects, which\n * is a visible stall on `project list`; a bounded pool brings that down to\n * roughly the cost of the slowest repo.\n */\nexport async function computeRepoActivityBatch(\n repos: readonly string[],\n options: ActivityOptions & { concurrency?: number } = {},\n): Promise<Map<string, RepoActivity>> {\n const results = new Map<string, RepoActivity>();\n const unique = [...new Set(repos)];\n const limit = Math.max(1, options.concurrency ?? 8);\n let cursor = 0;\n\n const worker = async (): Promise<void> => {\n while (cursor < unique.length) {\n const repo = unique[cursor++]!;\n try {\n results.set(repo, await computeRepoActivityAsync(repo, options));\n } catch {\n results.set(repo, emptyActivity());\n }\n }\n };\n\n await Promise.all(Array.from({ length: Math.min(limit, unique.length) }, worker));\n return results;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;AAUA,SAAS,cAAuB;AAE9B,MAAI,cAAc,OAAO,IAAI,aAAa,GAAI,QAAO;AACrD,QAAM,QAAQ,IAAI;AAClB,MAAI,UAAU,OAAO,UAAU,QAAS,QAAO;AAC/C,MAAI,UAAU,UAAa,UAAU,GAAI,QAAO;AAChD,MAAI,IAAI,SAAS,OAAQ,QAAO;AAChC,SAAO,QAAQ,QAAQ,OAAO,KAAK;AACrC;AAOA,SAAS,IAAI,MAAc,OAAyB;AAClD,QAAM,SAAS,QAAQ,IAAI;AAC3B,QAAM,SAAS,QAAQ,KAAK;AAC5B,SAAO,CAAC,UAAW,eAAe,GAAG,MAAM,GAAG,KAAK,GAAG,MAAM,KAAK,OAAO,KAAK;AAC/E;AAkDO,SAAS,YAAY,QAA6B;AACvD,SAAO,cAAc,MAAM,KAAK,EAAE,OAAO,MAAM,KAAK,OAAO,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ACf,QAAQ,QAAQ;AAAA,YAChB,OAAO,QAAQ;AAAA,YACf,OAAO,QAAQ;AAAA,YACf,WAAW,QAAQ;AAAA,YACnB,aAAa,QAAQ;AAAA,UACvB;AAAA,UACA,MAAMA,QAAO;AAAA,UACb,QAAQA,QAAO;AAAA,QACjB,CAAC;AAAA,MACH;AAAA,IACF,SAAS,KAAK;AACZ,aAAO;AAAA,QACL,SAAS;AAAA,QACT,SAAS,CAAC,EAAE,MAAM,QAAiB,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAE,CAAC;AAAA,MAC7F;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAM,YAAY,IAAI,qBAAqB;AAC3C,MAAM,OAAO,QAAQ,SAAS;",
6
+ "names": ["fallback", "text", "createHash", "existsSync", "lstatSync", "readFileSync", "readdirSync", "readlinkSync", "join", "relative", "createHash", "constants", "existsSync", "lstatSync", "readFileSync", "readdirSync", "realpathSync", "basename", "join", "relative", "resolve", "YAML", "env", "sha256", "text", "result", "env", "p", "readFileSync", "dirname", "join", "fileURLToPath", "spawnSync", "chmodSync", "closeSync", "copyFileSync", "existsSync", "lstatSync", "mkdirSync", "mkdtempSync", "openSync", "readFileSync", "realpathSync", "renameSync", "rmSync", "statSync", "unlinkSync", "writeFileSync", "homedir", "tmpdir", "basename", "delimiter", "dirname", "isAbsolute", "join", "relative", "resolve", "sep", "fileURLToPath", "YAML", "env", "text", "quote", "result", "boardUrl", "resolveAgentHooksLayer", "registryPath", "field", "isIP", "closeSync", "existsSync", "fchmodSync", "fsyncSync", "lstatSync", "openSync", "readFileSync", "realpathSync", "renameSync", "writeFileSync", "dirname", "resolve", "isRecord", "project", "fallback", "result", "env", "manifestNotebook", "current", "createHash", "randomUUID", "result", "timestamp", "createHash", "randomUUID", "closeSync", "constants", "existsSync", "fchmodSync", "fstatSync", "fsyncSync", "lstatSync", "mkdirSync", "openSync", "readdirSync", "renameSync", "unlinkSync", "writeFileSync", "homedir", "basename", "dirname", "join", "relative", "resolve", "sep", "env", "fsyncDirectory", "text", "result", "isRecord", "boundedString", "spawnSync", "closeSync", "constants", "fstatSync", "lstatSync", "openSync", "readSync", "realpathSync", "join", "relative", "resolve", "sep", "result", "relativePath", "randomUUID", "join", "candidates", "candidate", "owned", "spawnSync", "isAbsolute", "truncateUtf8", "result", "bindingId", "existsSync", "statSync", "basename", "dirname", "join", "resolve", "fileURLToPath", "finding", "result", "finding", "existsSync", "lstatSync", "mkdirSync", "readFileSync", "readdirSync", "writeFileSync", "basename", "dirname", "join", "relative", "resolve", "homedir", "createHash", "join", "resolve", "relativePath", "join", "trimmed", "text", "quote", "delimiter", "declared", "resolve", "readFileSync", "existsSync", "mkdirSync", "dirname", "writeFileSync", "text", "existsSync", "lstatSync", "relative", "join", "text", "readdirSync", "join", "result", "join", "existsSync", "basename", "lstatSync", "relative", "mkdirSync", "dirname", "resolve", "relativePath", "createHash", "readFileSync", "readdirSync", "writeFileSync", "text", "section", "result", "trimmed", "text", "trimmed", "trimmed", "text", "join", "existsSync", "resolve", "relative", "fallback", "basename", "readdirSync", "blockers", "mkdirSync", "section", "enabled", "dirname", "lstatSync", "readFileSync", "result", "writeFileSync", "parse", "homedir", "registryPath", "text", "field", "join", "dirname", "relative", "existsSync", "lstatSync", "result", "readdirSync", "createHash", "readFileSync", "finding", "resolve", "canonicalJson", "mkdirSync", "sysDir", "details", "basename", "registryPath", "homedir", "existsSync", "lstatSync", "mkdirSync", "readFileSync", "realpathSync", "renameSync", "rmSync", "writeFileSync", "spawnSync", "basename", "join", "dirname", "join", "homedir", "existsSync", "realpathSync", "dirname", "section", "text", "spawnSync", "table", "lstatSync", "mkdirSync", "basename", "writeFileSync", "renameSync", "rmSync", "readFileSync", "basename", "join", "readFileSync", "readFileSync", "join", "basename", "lstatSync", "readdirSync", "join", "relative", "lstatSync", "readdirSync", "join", "relative", "spawnSync", "homedir", "join", "dirname", "relative", "existsSync", "mkdirSync", "readFileSync", "writeFileSync", "fileURLToPath", "p", "YAML", "env", "join", "existsSync", "readFileSync", "relative", "writeFileSync", "dirname", "fileURLToPath", "spawnSync", "homedir", "mkdirSync", "spinner", "result", "YAML", "existsSync", "readFileSync", "writeFileSync", "readdirSync", "join", "spawnSync", "section", "join", "existsSync", "readdirSync", "spawnSync", "readFileSync", "writeFileSync", "spawnSync", "join", "existsSync", "unlinkSync", "p", "spawnSync", "join", "existsSync", "unlinkSync", "spinner", "result", "existsSync", "readFileSync", "join", "YAML", "existsSync", "join", "YAML", "readFileSync", "spawnSync", "existsSync", "readFileSync", "writeFileSync", "join", "YAML", "env", "join", "existsSync", "result", "spawnSync", "readFileSync", "YAML", "writeFileSync", "spawnSync", "existsSync", "join", "env", "join", "existsSync", "result", "spawnSync", "existsSync", "readFileSync", "join", "resolve", "YAML", "result", "hermesContext", "finding", "spawnSync", "existsSync", "lstatSync", "readFileSync", "rmSync", "dirname", "isAbsolute", "join", "resolve", "existsSync", "readFileSync", "join", "existsSync", "readFileSync", "join", "result", "overviewLogicalId", "randomUUID", "resolve", "spawnSync", "realpathSync", "relative", "resolve", "sep", "git", "result", "spawnSync", "createHash", "randomUUID", "chmodSync", "closeSync", "constants", "copyFileSync", "existsSync", "fstatSync", "fsyncSync", "lstatSync", "mkdirSync", "openSync", "readFileSync", "readSync", "readdirSync", "realpathSync", "renameSync", "rmSync", "symlinkSync", "unlinkSync", "writeFileSync", "basename", "dirname", "isAbsolute", "join", "parse", "relative", "resolve", "sep", "fileURLToPath", "dirname", "fileURLToPath", "join", "resolve", "assertNoSymlinkComponents", "lstatSync", "readdirSync", "result", "relative", "sep", "createHash", "readFileSync", "existsSync", "env", "realpathSync", "basename", "mkdirSync", "chmodSync", "randomUUID", "copyFileSync", "openSync", "constants", "fstatSync", "fsyncSync", "closeSync", "writeFileSync", "renameSync", "rmSync", "symlinkSync", "finding", "spawnSync", "unlinkSync", "assertNoSymlinkComponents", "resolve", "parse", "sep", "join", "lstatSync", "homedir", "timestamp", "env", "resolve", "admission", "text", "randomUUID", "result", "homedir", "bindingId", "runCaptureWorker", "env", "join", "existsSync", "readFileSync", "manifestNotebook", "env", "result", "spawnSync", "resolve", "lstatSync", "dirname", "finding", "existsSync", "join", "readFileSync", "rmSync", "relative", "isAbsolute", "result", "finding", "homedir", "join", "dirname", "existsSync", "cpSync", "mkdirSync", "readFileSync", "writeFileSync", "fileURLToPath", "dirname", "fileURLToPath", "join", "homedir", "existsSync", "resolveAgentHooksLayer", "mkdirSync", "cpSync", "readFileSync", "sep", "writeFileSync", "chmodSync", "join", "chmodSync", "join", "existsSync", "homedir", "dirname", "join", "resolve", "fileURLToPath", "resolvePjanglerRoot", "dirname", "fileURLToPath", "existsSync", "join", "resolve", "homedir", "publicAudit", "finding", "publicMigration", "result", "registryPath", "result", "existsSync", "readFileSync", "readdirSync", "statSync", "join", "resolve", "spawn", "spawnSync", "statSync", "join", "git", "result", "git", "statSync", "join", "readFileSync", "existsSync", "join", "readdirSync", "registryPath", "resolve", "field", "finding", "statSync", "git", "resolve", "existsSync", "statSync", "resolvePjanglerRoot", "dirname", "fileURLToPath", "join", "finding", "result", "registryPath", "basename"]
7
+ }