@mmnto/cli 2.1.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/commands/doctor-parity-fetch.d.ts +93 -2
  2. package/dist/commands/doctor-parity-fetch.d.ts.map +1 -1
  3. package/dist/commands/doctor-parity-fetch.js +332 -11
  4. package/dist/commands/doctor-parity-fetch.js.map +1 -1
  5. package/dist/commands/doctor-parity-fetch.test.d.ts +6 -0
  6. package/dist/commands/doctor-parity-fetch.test.d.ts.map +1 -1
  7. package/dist/commands/doctor-parity-fetch.test.js +405 -1
  8. package/dist/commands/doctor-parity-fetch.test.js.map +1 -1
  9. package/dist/commands/doctor-parity.d.ts.map +1 -1
  10. package/dist/commands/doctor-parity.js +27 -1
  11. package/dist/commands/doctor-parity.js.map +1 -1
  12. package/dist/commands/doctor-parity.test.js +67 -0
  13. package/dist/commands/doctor-parity.test.js.map +1 -1
  14. package/dist/commands/eject-gate-needle.test.d.ts +2 -0
  15. package/dist/commands/eject-gate-needle.test.d.ts.map +1 -0
  16. package/dist/commands/eject-gate-needle.test.js +48 -0
  17. package/dist/commands/eject-gate-needle.test.js.map +1 -0
  18. package/dist/commands/eject.d.ts +10 -0
  19. package/dist/commands/eject.d.ts.map +1 -1
  20. package/dist/commands/eject.js +67 -12
  21. package/dist/commands/eject.js.map +1 -1
  22. package/dist/commands/eject.test.js +113 -0
  23. package/dist/commands/eject.test.js.map +1 -1
  24. package/dist/commands/gate-install.d.ts +55 -5
  25. package/dist/commands/gate-install.d.ts.map +1 -1
  26. package/dist/commands/gate-install.js +47 -34
  27. package/dist/commands/gate-install.js.map +1 -1
  28. package/dist/commands/gate-install.test.js +514 -56
  29. package/dist/commands/gate-install.test.js.map +1 -1
  30. package/dist/commands/gate.d.ts +24 -9
  31. package/dist/commands/gate.d.ts.map +1 -1
  32. package/dist/commands/gate.js +50 -18
  33. package/dist/commands/gate.js.map +1 -1
  34. package/dist/commands/gate.test.js +74 -3
  35. package/dist/commands/gate.test.js.map +1 -1
  36. package/dist/commands/host-hooks.d.ts +8 -2
  37. package/dist/commands/host-hooks.d.ts.map +1 -1
  38. package/dist/commands/host-hooks.js.map +1 -1
  39. package/dist/commands/init-templates.d.ts +4 -4
  40. package/dist/commands/init-templates.d.ts.map +1 -1
  41. package/dist/commands/init-templates.js +243 -63
  42. package/dist/commands/init-templates.js.map +1 -1
  43. package/dist/commands/init.d.ts.map +1 -1
  44. package/dist/commands/init.js +35 -17
  45. package/dist/commands/init.js.map +1 -1
  46. package/dist/commands/init.test.js +10 -0
  47. package/dist/commands/init.test.js.map +1 -1
  48. package/dist/commands/session-context-journal-select.test.d.ts +2 -0
  49. package/dist/commands/session-context-journal-select.test.d.ts.map +1 -0
  50. package/dist/commands/session-context-journal-select.test.js +95 -0
  51. package/dist/commands/session-context-journal-select.test.js.map +1 -0
  52. package/dist/commands/sync-labels-forms.test.d.ts +33 -0
  53. package/dist/commands/sync-labels-forms.test.d.ts.map +1 -0
  54. package/dist/commands/sync-labels-forms.test.js +325 -0
  55. package/dist/commands/sync-labels-forms.test.js.map +1 -0
  56. package/dist/index.js +2 -2
  57. package/dist/index.js.map +1 -1
  58. package/package.json +2 -2
@@ -1,11 +1,11 @@
1
1
  import type { IngestTarget } from '@mmnto/totem';
2
2
  import type { ConfigFormat, EmbeddingTier } from './init-detect.js';
3
- export declare const REFLEX_VERSION = 14;
3
+ export declare const REFLEX_VERSION = 15;
4
4
  export declare const REFLEX_START = "<!-- totem:reflexes:start -->";
5
5
  export declare const REFLEX_END = "<!-- totem:reflexes:end -->";
6
6
  export declare const REFLEX_VERSION_RE: RegExp;
7
7
  export declare const LEGACY_SENTINEL = "## Totem AI Integration (Auto-Generated)";
8
- export declare const AI_PROMPT_BLOCK = "\n<!-- totem:reflexes:start -->\n<!-- totem:reflexes:version:14 -->\n\n## Totem AI Integration (Auto-Generated)\nYou have access to the Totem MCP for long-term project memory. You MUST operate with the following reflexes:\n\n### Memory Reflexes\n1. **BLOCKING \u2014 Pull Before Coding:** Before writing or modifying code that touches more than one file, you MUST call `search_knowledge` with a query describing what you're about to change. This is not optional. The vector DB contains traps, edge cases, and architectural constraints that prevent rework. Skip this and you risk repeating a mistake that's already been solved.\n2. **Pull Before Planning:** Before writing specs, architecture, or fixing complex bugs, use `search_knowledge` to retrieve domain constraints and past traps.\n3. **Pull on Session Start:** At the beginning of every session, call `search_knowledge` with a broad query about the current task or area of work. The vector DB is your institutional memory \u2014 use it before relying on your own context window.\n4. **Proactive Anchoring (The 3 Triggers):** You must autonomously call `add_lesson` when any of the following occur \u2014 do NOT wait for the user to ask:\n - **The Trap Trigger:** If you spend >2 turns fixing a bug caused by a framework quirk, unexpected API response, or edge case. (Anchor the symptom + fix).\n - **The Pivot Trigger:** If the user introduces a new architectural pattern or deprecates an old one. (Anchor the rule).\n - **The Handoff Trigger:** At the end of a session or when wrapping up a complex feature, extract the non-obvious lessons learned and anchor them.\n5. **Tool Preference (MCP over CLI):** Always prioritize using dedicated MCP tools (e.g., GitHub, Supabase, Vercel) over executing generic shell commands (like `gh issue view` or `curl`). MCP tools provide structured, un-truncated data optimized for your context window. Only fall back to bash execution if an MCP tool is unavailable or fails.\n\nLessons are automatically re-indexed in the background after each `add_lesson` call \u2014 no manual sync needed.\n\n### Memory Classification\nWhen deciding where to store information or rules, use this decision tree:\n- If forgetting this causes a mistake on an UNRELATED task (Core Safety): Store in your root agent memory file (e.g., CLAUDE.md or GEMINI.md).\n- If it's a stable, project-wide workflow rule: Store in project config (e.g., CLAUDE.md).\n- If it's a stable syntax/style pattern: Store in the project's styleguide or linter rules.\n- If it's domain knowledge, an edge case, or a past trap: You MUST use the Totem `add_lesson` tool to anchor it into the project's LanceDB.\n\n### Workflow Orchestrator Rituals\n[FOR LOCAL CLI/TERMINAL AGENTS ONLY] Do not attempt to run these commands if you are a headless bot or operating in a cloud PR environment (e.g., Gemini Code Assist on GitHub).\nTotem provides CLI commands that map to your development lifecycle. Use them at these moments:\n1. **Start of Session:** The SessionStart hook automatically runs `totem describe` to emit the project-orientation banner (project, tier, rule/lesson counts, targets, hooks). For richer derived project state (recent merged PRs, current branch + uncommitted files, latest strategy journal pointer, package versions, rule/lesson counts), call the MCP `describe_project` tool \u2014 the derived view replaces the retired `docs/active_work.md` convention (state is observed, not declared). For a freshness check (manifest staleness, shield drift, review state), run `totem status`. Run `totem triage` if you need to pick a new task. On a seat without the SessionStart hook (a cold start, or a vehicle that doesn't run hooks), run `totem orient` to derive in-flight and parked project state from primitives.\n2. **Before Implementation:** Run `totem spec <issue-url-or-topic>` to retrieve related context (lessons, specs, code) before writing code. Treat any generated plan as one retrieval input, never the contract \u2014 derive the actual design from primary sources (the issue, the code, project doctrine). Under the strict hook tier \u2014 which AI agents get automatically \u2014 this is REQUIRED, not optional: the pre-commit hook blocks until the checkout carries an ANCHORED `totem spec` run artifact, and prints the evidence it found. ANCHORED means the run was grounded on an ISSUE, or on a hand-authored design record bound with `totem spec --from <record>` \u2014 and that its SUBJECT carries the shape the command promises: for an issue run, every required heading with a non-empty body (or, when your project overrides the spec system prompt, just one heading with a body \u2014 a custom prompt is not held to the built-in skeleton); for a bound record, at least one heading with a body in the RECORD's own bytes, re-read from disk at commit time. A free-text topic run is NOT evidence (that is the confabulation surface the rule exists for), and neither is an artifact written before this rule \u2014 re-run it anchored. A response served from the cache writes no artifact, so add `--fresh` when the gate says there is nothing new (mmnto-ai/totem#2690, mmnto-ai/totem#2700). Under the same strict tier the pre-push hook additionally blocks a legs-owed push \u2014 a diff touching the paths in `hooks.legsOwed.globs` (doctrine, public copy, `.changeset/**` and the contract classes your project declares) \u2014 until the checkout carries a fresh leg deposit for its head, written with `totem legs deposit --sha HEAD --from <findings.json>` once the leg returns, and the gate prints the evidence it found (mmnto-ai/totem#2698). That legs gate can also be armed on its own, at any tier, with `hooks.legsOwed.enforce: 'block'` \u2014 a standard-tier install then refuses a legs-owed push too, and the gate's line names the key (mmnto-ai/totem#2771).\n3. **Before Push:** Run `totem lint` \u2014 the deterministic enforcement floor (zero LLM, ~2s). **Before PR:** `totem review` runs supplementary AI lanes over the diff (~18s) \u2014 advisory sensors, not a merge gate; known limits are disclosed in the run output (LLM window truncation on large diffs; non-code files skipped). Your team's own review discipline decides what constitutes the review of record.\n4. **End of Session:** Run `totem handoff` to generate a snapshot for the next agent session with current progress and open threads.\n5. **Managed hooks self-repair:** `totem init` distributes `.totem/prepare.cjs` and wires `package.json` `prepare` to it only when no `prepare` script exists. The wrapper runs `totem hook install` on every `pnpm install`, drift-repairing the managed Claude/Gemini hooks \u2014 no manual re-install needed.\n\n### Cloud / PR Review Bots\n[FOR CLOUD BOTS ONLY \u2014 e.g., Gemini Code Assist, GitHub Copilot PR Review]\nYou do NOT have access to the local CLI. Instead, use the Totem MCP tools directly:\n1. **Before reviewing a PR:** Call `search_knowledge` with queries about the files and patterns being changed to check for known traps and architectural constraints.\n2. **Before suggesting changes:** Call `search_knowledge` to verify your suggestion aligns with established project patterns and past lessons.\n3. **When you spot a recurring issue:** Call `add_lesson` to persist the trap so future reviews catch it automatically.\n\n### Context Management Guardrail\nYou must be highly defensive of your own context window \u2014 and you are the ONLY party holding the denominator (your model's window size and current occupancy); no Totem tool can measure it for you. Large Totem tool responses may carry a self-closing `<size-disclosure ... />` line stating that payload's measured size and cumulative session totals \u2014 a measurement, never a risk claim. Weigh it against your own occupancy and escalate to the user only when the pressure is genuinely material, suggesting `totem handoff` to capture mid-task state before clearing the chat. If you receive a `<totem_system_warning>` tag in a tool response (e.g. index staleness or degraded retrieval), read it silently and act on it or surface it naturally. Do NOT echo raw XML tags to the user.\n<!-- totem:reflexes:end -->\n";
8
+ export declare const AI_PROMPT_BLOCK = "\n<!-- totem:reflexes:start -->\n<!-- totem:reflexes:version:15 -->\n\n## Totem AI Integration (Auto-Generated)\nYou have access to the Totem MCP for long-term project memory. You MUST operate with the following reflexes:\n\n### Memory Reflexes\n1. **BLOCKING \u2014 Pull Before Coding:** Before writing or modifying code that touches more than one file, you MUST call `search_knowledge` with a query describing what you're about to change. This is not optional. The vector DB contains traps, edge cases, and architectural constraints that prevent rework. Skip this and you risk repeating a mistake that's already been solved.\n2. **Pull Before Planning:** Before writing specs, architecture, or fixing complex bugs, use `search_knowledge` to retrieve domain constraints and past traps.\n3. **Pull on Session Start:** At the beginning of every session, call `search_knowledge` with a broad query about the current task or area of work. The vector DB is your institutional memory \u2014 use it before relying on your own context window.\n4. **Proactive Anchoring (The 3 Triggers):** You must autonomously call `add_lesson` when any of the following occur \u2014 do NOT wait for the user to ask:\n - **The Trap Trigger:** If you spend >2 turns fixing a bug caused by a framework quirk, unexpected API response, or edge case. (Anchor the symptom + fix).\n - **The Pivot Trigger:** If the user introduces a new architectural pattern or deprecates an old one. (Anchor the rule).\n - **The Handoff Trigger:** At the end of a session or when wrapping up a complex feature, extract the non-obvious lessons learned and anchor them.\n5. **Tool Preference (MCP over CLI):** Always prioritize using dedicated MCP tools (e.g., GitHub, Supabase, Vercel) over executing generic shell commands (like `gh issue view` or `curl`). MCP tools provide structured, un-truncated data optimized for your context window. Only fall back to bash execution if an MCP tool is unavailable or fails.\n\nLessons are automatically re-indexed in the background after each `add_lesson` call \u2014 no manual sync needed.\n\n### Memory Classification\nWhen deciding where to store information or rules, use this decision tree:\n- If forgetting this causes a mistake on an UNRELATED task (Core Safety): Store in your root agent memory file (e.g., CLAUDE.md or GEMINI.md).\n- If it's a stable, project-wide workflow rule: Store in project config (e.g., CLAUDE.md).\n- If it's a stable syntax/style pattern: Store in the project's styleguide or linter rules.\n- If it's domain knowledge, an edge case, or a past trap: You MUST use the Totem `add_lesson` tool to anchor it into the project's LanceDB.\n\n### Workflow Orchestrator Rituals\n[FOR LOCAL CLI/TERMINAL AGENTS ONLY] Do not attempt to run these commands if you are a headless bot or operating in a cloud PR environment (e.g., Gemini Code Assist on GitHub).\nTotem provides CLI commands that map to your development lifecycle. Use them at these moments:\n1. **Start of Session:** The SessionStart hook automatically runs `totem describe` to emit the project-orientation banner (project, tier, rule/lesson counts, targets, hooks). For richer derived project state (recent merged PRs, current branch + uncommitted files, latest strategy journal pointer, package versions, rule/lesson counts), call the MCP `describe_project` tool \u2014 the derived view replaces the retired `docs/active_work.md` convention (state is observed, not declared). For a freshness check (manifest staleness, shield drift, review state), run `totem status`. Run `totem triage` if you need to pick a new task. On a seat without the SessionStart hook (a cold start, or a vehicle that doesn't run hooks), run `totem orient` to derive in-flight and parked project state from primitives.\n2. **Before Implementation:** Run `totem spec <issue-url-or-topic>` to retrieve related context (lessons, specs, code) before writing code. Treat any generated plan as one retrieval input, never the contract \u2014 derive the actual design from primary sources (the issue, the code, project doctrine). Under the strict hook tier \u2014 which AI agents get automatically \u2014 this is REQUIRED, not optional: the pre-commit hook blocks until the checkout carries an ANCHORED `totem spec` run artifact, and prints the evidence it found. ANCHORED means the run was grounded on an ISSUE, or on a hand-authored design record bound with `totem spec --from <record>` \u2014 and that its SUBJECT carries the shape the command promises: for an issue run, every required heading with a non-empty body (or, when your project overrides the spec system prompt, just one heading with a body \u2014 a custom prompt is not held to the built-in skeleton); for a bound record, at least one heading with a body in the RECORD's own bytes, re-read from disk at commit time. A free-text topic run is NOT evidence (that is the confabulation surface the rule exists for), and neither is an artifact written before this rule \u2014 re-run it anchored. A response served from the cache writes no artifact, so add `--fresh` when the gate says there is nothing new (mmnto-ai/totem#2690, mmnto-ai/totem#2700). Under the same strict tier the pre-push hook additionally blocks a legs-owed push \u2014 a diff touching the paths in `hooks.legsOwed.globs` (doctrine, public copy, `.changeset/**` and the contract classes your project declares) \u2014 until the checkout carries a fresh leg deposit for its head, written with `totem legs deposit --sha HEAD --from <findings.json>` once the leg returns, and the gate prints the evidence it found (mmnto-ai/totem#2698). That legs gate can also be armed on its own, at any tier, with `hooks.legsOwed.enforce: 'block'` \u2014 a standard-tier install then refuses a legs-owed push too, and the gate's line names the key (mmnto-ai/totem#2771).\n3. **Before Push:** Run `totem lint` \u2014 the deterministic enforcement floor (zero LLM, ~2s). **Before PR:** `totem review` runs supplementary AI lanes over the diff (~18s) \u2014 advisory sensors, not a merge gate; known limits are disclosed in the run output (LLM window truncation on large diffs; non-code files skipped). Your team's own review discipline decides what constitutes the review of record.\n4. **End of Session:** Run `totem handoff` to generate a snapshot for the next agent session with current progress and open threads.\n5. **Managed hooks self-repair:** `totem init` distributes `.totem/prepare.cjs` and wires `package.json` `prepare` to it only when no `prepare` script exists. The wrapper runs `totem hook install` on every `pnpm install`, drift-repairing the managed Claude/Gemini hooks \u2014 no manual re-install needed.\n6. **Action gates (PreToolUse):** a gate installed with `totem gate install <event>` is evaluated by the repo-local `@mmnto/cli` first and by a `totem` on PATH when that is absent; an applicable gate that neither can evaluate fails closed and its message names the exits. A `Bash|PowerShell`-matched gate applies to a fresh clone's bootstrap commands (install, build), so bootstrap such a clone from a terminal outside the harness when no `totem` is on PATH (mmnto-ai/totem#2799, mmnto-ai/totem#2822).\n\n### Cloud / PR Review Bots\n[FOR CLOUD BOTS ONLY \u2014 e.g., Gemini Code Assist, GitHub Copilot PR Review]\nYou do NOT have access to the local CLI. Instead, use the Totem MCP tools directly:\n1. **Before reviewing a PR:** Call `search_knowledge` with queries about the files and patterns being changed to check for known traps and architectural constraints.\n2. **Before suggesting changes:** Call `search_knowledge` to verify your suggestion aligns with established project patterns and past lessons.\n3. **When you spot a recurring issue:** Call `add_lesson` to persist the trap so future reviews catch it automatically.\n\n### Context Management Guardrail\nYou must be highly defensive of your own context window \u2014 and you are the ONLY party holding the denominator (your model's window size and current occupancy); no Totem tool can measure it for you. Large Totem tool responses may carry a self-closing `<size-disclosure ... />` line stating that payload's measured size and cumulative session totals \u2014 a measurement, never a risk claim. Weigh it against your own occupancy and escalate to the user only when the pressure is genuinely material, suggesting `totem handoff` to capture mid-task state before clearing the chat. If you receive a `<totem_system_warning>` tag in a tool response (e.g. index staleness or degraded retrieval), read it silently and act on it or surface it naturally. Do NOT echo raw XML tags to the user.\n<!-- totem:reflexes:end -->\n";
9
9
  export declare const TOTEM_FILE_MARKER = "// [totem] auto-generated";
10
10
  /**
11
11
  * The end marker that CLOSES every managed whole-file session hook template
@@ -73,7 +73,7 @@ export declare const CLAUDE_PREWRITESHIELD_ENTRY: {
73
73
  command: string;
74
74
  }[];
75
75
  };
76
- export declare const CLAUDE_SESSION_START = "// [totem] auto-generated \u2014 Claude Code SessionStart hook\n// Runs `@mmnto/cli describe` at the start of every Claude Code session.\n// Mirrors `.gemini/hooks/SessionStart.cjs`. `.cjs` extension because\n// package.json may have \"type\": \"module\" \u2014 Claude Code execs hooks via\n// plain `node`, which would otherwise treat `.js` as ESM.\n//\n// A.3.a: mints a session UUID, persists to .totem/ledger/.session-id,\n// and appends a `session_start` event to .totem/ledger/events.ndjson\n// BEFORE running `totem describe`. Subsequent MCP calls within the\n// session correlate via session_id (ADR-029 \u00A7 Session Heuristic).\n// Fire-and-forget: any ledger failure must NOT block the briefing.\nconst { spawnSync } = require('child_process');\nconst { existsSync, mkdirSync, writeFileSync, appendFileSync } = require('fs');\nconst { randomUUID } = require('crypto');\nconst { join } = require('path');\n\n// \u2500\u2500\u2500 A.3.a: mint session ID + log session_start event \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Hoisted so the selection-manifest row below (mmnto-ai/totem#2468) can carry\n// the same session UUID as its join key.\nlet mintedSessionId = null;\ntry {\n const ledgerDir = join(process.cwd(), '.totem', 'ledger');\n mkdirSync(ledgerDir, { recursive: true });\n const sessionId = randomUUID();\n mintedSessionId = sessionId;\n writeFileSync(join(ledgerDir, '.session-id'), sessionId, 'utf-8');\n // Amended ADR-078 (2026-07-15): agent_source is the env-carried seat-id\n // (TOTEM_SELF_AGENT, first non-empty comma entry), never a vendor class\n // ('claude' has no reverse projection to a seat). Omitted entirely when\n // the env var is absent: stamp absence, never guess (Tenet 4). The parse\n // deliberately mirrors deriveSearchLogAttribution (packages/mcp/src/\n // search-log.ts) and parseEnvAgentList (packages/core/src/\n // orchestration-resolver.ts) \u2014 inlined because this rendered .cjs hook\n // runs standalone in consumer repos with no access to those modules; if\n // the shared parse semantics change, change this template in the same PR.\n const selfAgent = (process.env.TOTEM_SELF_AGENT || '')\n .split(',')\n .map((s) => s.trim())\n .find((s) => s.length > 0);\n const event = {\n timestamp: new Date().toISOString(),\n type: 'session_start',\n activity_name: 'SessionStart',\n source: 'bot',\n ...(selfAgent ? { agent_source: selfAgent } : {}),\n justification: '',\n session_id: sessionId,\n };\n appendFileSync(join(ledgerDir, 'events.ndjson'), JSON.stringify(event) + '\\n', 'utf-8');\n} catch (err) {\n // Fire-and-forget; ledger failures must not block the briefing. A lightweight\n // stderr breadcrumb makes hook misconfigurations diagnosable in consumer repos\n // (CR R1 catch \u2014 empty catch suppresses all signal). stderr (not stdout) so\n // the briefing path remains clean for Claude's prompt context.\n process.stderr.write(\n '[SessionStart] Session-start telemetry unavailable (non-fatal): ' +\n (err instanceof Error ? err.message : String(err)) +\n '\\n',\n );\n}\n\n// \u2500\u2500\u2500 totem-status refresh-gh \u2014 GH-federation snapshot refresh \u2500\u2500\u2500\n// (mmnto-ai/totem-status#127 C3 residual; tracking mmnto-ai/totem#2556.)\n// Spawn-and-forget, detached+unref, fired BEFORE the synchronous describe/orient\n// briefings so it overlaps them: session start must never block on it\n// (mmnto-ai/totem#2059 measured ~3s of synchronous gh calls here). The verb's\n// exit-0-or-nothing contract (single-flight, atomic rename, no-clobber when gh\n// is missing) makes blind firing safe. ENOENT = the sidecar is not adopted in\n// this repo (the common non-cohort case) \u2014 zero noise; any other spawn failure\n// keeps a non-fatal stderr breadcrumb.\n// A SECOND verb rides this same block: `totem-status refresh-obligation-store`\n// (mmnto-ai/totem-status#127 slice-two residual, sibling of mmnto-ai/totem#2556)\n// writes the durable obligation store beside the GH snapshot, so it gets the same\n// session-start moment. Same primary-checkout gate, same detached+unref spawn, same\n// inherited log fd, same ENOENT-silent arm \u2014 and each firing stamps its own `verb=`\n// field, so the log records WHICH verbs fired and in what order. That does NOT\n// restore the #2570 per-child reap discriminator: both stamps are written\n// back-to-back before either child writes, and child output carries no verb tag\n// and arrives in nondeterministic order, so a silent tail attributes only to the\n// LAST verb stamped. Reopen when the sidecar tags its own output. Blind firing\n// stays safe here too: that verb is in-process single-flight only, so it races the\n// daemon exactly the way its manual invocation already does.\n// PRIMARY checkout only (.git must be a DIRECTORY): in a linked worktree .git is a\n// pointer FILE, and a detached child inheriting the worktree cwd holds a Windows\n// directory lock that breaks worktree removal; the primary's hooks + the daemon\n// cover the workspace-level snapshot (single-flight makes extra fires redundant).\n// A non-git cwd has no refresh moment at all. The stat is cwd-anchored, not a\n// walk-up: both host runtimes launch session hooks with cwd = project root, so a\n// subdirectory cwd (which would skip) does not occur in practice \u2014 and adding a\n// git walk would cost a synchronous process on the very path this block keeps free.\ntry {\n const nodePath = require('path');\n const { statSync } = require('fs');\n let primaryCheckout = false;\n try {\n primaryCheckout = statSync(nodePath.join(process.cwd(), '.git')).isDirectory();\n } catch {\n // not a git checkout (or .git unreadable) \u2014 no refresh moment here\n }\n if (primaryCheckout) {\n const { spawn } = require('child_process');\n // Observability leg (mmnto-ai/totem#2570, routed from the status seat's\n // 2026-08-03 silent no-write): under stdio:'ignore' plus the verb's\n // exit-0-or-nothing contract, a reaped or dying child leaves NO trace\n // (Windows detached is not job-object breakaway \u2014 a hook-harness\n // tree-kill takes the child mid-run). Each firing stamps a workspace-root\n // log and hands the children the same fd, so their output lands after the\n // stamps. Measured caveat now that TWO verbs share one fd: both stamps are\n // written back-to-back before either child writes, and the children's\n // output is unlabelled and interleaves nondeterministically \u2014 so a silent\n // tail no longer discriminates per child; it attributes only to the LAST\n // verb stamped. The stamps still record which verbs fired, and in what\n // order. Log failures degrade to the previous blind firing \u2014 the stamp\n // must never block or break the spawn.\n const { openSync, closeSync, appendFileSync, existsSync, writeFileSync } = require('fs');\n // REPO-LOCAL log, inside .git (falsification round: the primary-checkout\n // gate just proved .git is a directory; never tracked, dies with the\n // clone, writable wherever git itself writes, and per-repo so concurrent\n // firings from sibling repos never interleave). A workspace-parent path\n // would grow an un-gitignorable file OUTSIDE the repo tree for every\n // consumer of these published templates \u2014 including non-adopters, whose\n // ENOENT firing still stamps.\n const logPath = nodePath.join(process.cwd(), '.git', 'totem-status-refresh-hook.log');\n // Control characters are scrubbed from path-derived fields before they\n // reach the log (terminal-injection guideline: a crafted checkout path\n // must not forge stamp lines or inject terminal controls).\n const scrub = (v) => String(v).replace(/[\\x00-\\x1f\\x7f]/g, '?');\n let stdio = 'ignore';\n let logFd = null;\n try {\n try {\n // 1 MiB self-cap: the log truncates rather than growing forever.\n if (statSync(logPath).size > 1048576) writeFileSync(logPath, '');\n } catch {\n // no log yet \u2014 nothing to cap\n }\n appendFileSync(logPath, '[' + new Date().toISOString() + '] claude spawn cwd=' + scrub(process.cwd()) + ' path-has-go-bin=' + /go[\\\\/]bin/i.test(process.env.PATH || '') + ' cwd-shadow-exe=' + existsSync(nodePath.join(process.cwd(), 'totem-status.exe')) + ' verb=refresh-gh\\n');\n logFd = openSync(logPath, 'a');\n stdio = ['ignore', logFd, logFd];\n } catch {\n // log unavailable \u2014 refresh still fires blind, as before\n }\n const refresh = spawn('totem-status', ['refresh-gh'], {\n detached: true,\n stdio,\n });\n refresh.on('error', (err) => {\n try {\n appendFileSync(logPath, '[' + new Date().toISOString() + '] claude spawn-error code=' + ((err && err.code) || 'unknown') + ' verb=refresh-gh\\n');\n } catch {\n // log write failed \u2014 fall through to the stderr breadcrumb\n }\n if (err && err.code === 'ENOENT') return;\n process.stderr.write('[SessionStart] totem-status refresh-gh spawn failed (non-fatal): ' + (err instanceof Error ? err.message : String(err)) + '\\n');\n });\n refresh.unref();\n // Second verb, same gate and same log fd (see the banner above). Written out\n // rather than looped so the spawn, the stamp, and the breadcrumb each carry a\n // literal verb \u2014 a reader of the generated hook (or of the log) never has to\n // resolve a variable to know which refresh fired.\n try {\n appendFileSync(logPath, '[' + new Date().toISOString() + '] claude spawn cwd=' + scrub(process.cwd()) + ' path-has-go-bin=' + /go[\\\\/]bin/i.test(process.env.PATH || '') + ' cwd-shadow-exe=' + existsSync(nodePath.join(process.cwd(), 'totem-status.exe')) + ' verb=refresh-obligation-store\\n');\n } catch {\n // log unavailable \u2014 this verb still fires blind, exactly as the first does\n }\n const refreshStore = spawn('totem-status', ['refresh-obligation-store'], {\n detached: true,\n stdio,\n });\n refreshStore.on('error', (err) => {\n try {\n appendFileSync(logPath, '[' + new Date().toISOString() + '] claude spawn-error code=' + ((err && err.code) || 'unknown') + ' verb=refresh-obligation-store\\n');\n } catch {\n // log write failed \u2014 fall through to the stderr breadcrumb\n }\n if (err && err.code === 'ENOENT') return;\n process.stderr.write('[SessionStart] totem-status refresh-obligation-store spawn failed (non-fatal): ' + (err instanceof Error ? err.message : String(err)) + '\\n');\n });\n refreshStore.unref();\n // Each child holds its own copy of the fd from spawn time; release the parent's\n // once BOTH are away (an early close would hand the second spawn an EBADF).\n if (logFd !== null) {\n try {\n closeSync(logFd);\n } catch {\n // nothing to release\n }\n }\n }\n} catch (err) {\n // Block-level breadcrumb: this catch covers the whole gated block, so neither\n // verb fired \u2014 it names the SIDECAR, not one verb. The per-spawn breadcrumbs\n // inside still name their own verb.\n process.stderr.write('[SessionStart] totem-status sidecar refresh unavailable (non-fatal): ' + (err instanceof Error ? err.message : String(err)) + '\\n');\n}\n\n// \u2500\u2500\u2500 totem describe briefing (existing behavior) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Captured (mmnto-ai/totem#2468): the injected block is the selection-manifest\n// candidate below \u2014 the not-installed notice is a notice, not a briefing.\nlet describeText = '';\ntry {\n const cliPath = join(process.cwd(), 'node_modules', '@mmnto', 'cli', 'dist', 'index.js');\n if (existsSync(cliPath)) {\n const result = spawnSync(process.execPath, [cliPath, 'describe'], {\n encoding: 'utf-8',\n timeout: 30000,\n });\n if (result.error) {\n throw result.error;\n }\n // Totem CLI writes diagnostic output to stderr; route to stdout so the\n // session-start context lands in Claude's prompt rather than user-visible noise.\n describeText = (result.stdout || '') + (result.stderr || '');\n process.stdout.write(describeText);\n } else {\n process.stdout.write(\n '[Totem] @mmnto/cli not installed. Run `pnpm install` (or your package manager equivalent) to enable session-start orientation.\\n',\n );\n }\n} catch (err) {\n process.stdout.write(\n '[Totem] Briefing unavailable: ' +\n (err instanceof Error ? err.message : String(err)) +\n '\\n',\n );\n}\n\n// \u2500\u2500\u2500 totem orient --session \u2014 live derived in-flight state (mmnto-ai/totem#2044 PR-3) \u2500\u2500\n// ADDITIVE to describe (Tenet 13: describe = static identity sensor \u2014 scope/tier/\n// counts; orient = live in-flight sensor \u2014 open PRs/issues/board/freeze). Append,\n// never replace. Its OWN try/catch so an orient failure never disturbs the describe\n// briefing or the boot; `orient --session` is itself boot-safe (emits nothing when\n// nothing is high-signal, never exits non-zero, degrades to honest \"could not derive\").\nlet orientText = '';\ntry {\n const orientCliPath = join(process.cwd(), 'node_modules', '@mmnto', 'cli', 'dist', 'index.js');\n if (existsSync(orientCliPath)) {\n const orientResult = spawnSync(process.execPath, [orientCliPath, 'orient', '--session'], {\n encoding: 'utf-8',\n timeout: 30000,\n });\n // spawnSync sets .error (it does NOT throw) on a spawn-level failure; re-throw so\n // it surfaces through the catch breadcrumb below rather than writing '' silently.\n if (orientResult.error) {\n throw orientResult.error;\n }\n orientText = (orientResult.stdout || '') + (orientResult.stderr || '');\n process.stdout.write(orientText);\n }\n} catch (err) {\n // Boot-safe: orient is additive to describe (already emitted), so a failure never\n // blocks session start \u2014 but surface a NON-fatal breadcrumb to stderr (not stdout,\n // to keep the prompt clean) for debuggability rather than swallowing silently.\n process.stderr.write(\n '[SessionStart] orient briefing unavailable (non-fatal): ' +\n (err instanceof Error ? err.message : String(err)) +\n '\\n',\n );\n}\n\n// \u2500\u2500\u2500 selection manifest (mmnto-ai/totem#2468 M1) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Inline append mirroring the session_start write above \u2014 this rendered hook\n// runs standalone in consumer repos with no access to @mmnto/totem's writer.\n// The row shape is BOUND to SelectionManifestRowSchema (strict): change both\n// in the same PR; the template contract test parses this row with the real\n// schema. A zero-byte block never becomes a candidate (nothing was injected).\ntry {\n const { createHash } = require('crypto');\n const measure = (id, content, reason) => {\n const bytes = Buffer.byteLength(content, 'utf-8');\n return {\n id,\n disposition: 'selected',\n reason,\n bytes,\n approxTokens: Math.ceil(bytes / 4),\n fingerprint: createHash('sha256').update(content, 'utf-8').digest('hex').slice(0, 16),\n };\n };\n const selfAgent = (process.env.TOTEM_SELF_AGENT || '')\n .split(',')\n .map((s) => s.trim())\n .find((s) => s.length > 0);\n const row = {\n schemaVersion: 1,\n timestamp: new Date().toISOString(),\n emitter: 'session-start',\n ...(mintedSessionId ? { session_id: mintedSessionId } : {}),\n ...(selfAgent ? { agent_source: selfAgent } : {}),\n // mmnto-ai/totem#2629: provenance disclosed on every row (ruled item 1).\n // Self-minted row \u2014 the minting seat IS this process's env read, so the\n // core conflict probe is structurally inapplicable; only the two-value\n // provenance enum rides. Mirrors senseAgentAttribution's biconditional.\n agent_source_provenance: selfAgent ? 'env' : 'absent',\n context: { template: 'claude-managed' },\n universe: 'managed-template blocks: describe + orient --session',\n costBasis: { bytes: 'utf8-length', approxTokens: 'ceil(bytes/4) approximation' },\n candidates: [\n measure('describe', describeText, 'always-injected briefing'),\n measure('orient:session-block', orientText, 'always-injected briefing'),\n ].filter((c) => c.bytes > 0),\n warnings: [],\n };\n appendFileSync(\n join(process.cwd(), '.totem', 'ledger', 'selection-manifests.ndjson'),\n JSON.stringify(row) + '\\n',\n 'utf-8',\n );\n} catch (err) {\n process.stderr.write(\n '[SessionStart] selection manifest unavailable (non-fatal): ' +\n (err instanceof Error ? err.message : String(err)) +\n '\\n',\n );\n}\n// [totem] end auto-generated\n";
76
+ export declare const CLAUDE_SESSION_START = "// [totem] auto-generated \u2014 Claude Code SessionStart hook\n// Runs `@mmnto/cli describe` at the start of every Claude Code session.\n// Mirrors `.gemini/hooks/SessionStart.cjs`. `.cjs` extension because\n// package.json may have \"type\": \"module\" \u2014 Claude Code execs hooks via\n// plain `node`, which would otherwise treat `.js` as ESM.\n//\n// A.3.a: mints a session UUID, persists to .totem/ledger/.session-id,\n// and appends a `session_start` event to .totem/ledger/events.ndjson\n// BEFORE running `totem describe`. Subsequent MCP calls within the\n// session correlate via session_id (ADR-029 \u00A7 Session Heuristic).\n// Fire-and-forget: any ledger failure must NOT block the briefing.\nconst { spawnSync } = require('child_process');\nconst { existsSync, mkdirSync, writeFileSync, appendFileSync } = require('fs');\nconst { randomUUID } = require('crypto');\nconst { join } = require('path');\n\n// \u2500\u2500\u2500 A.3.a: mint session ID + log session_start event \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Hoisted so the selection-manifest row below (mmnto-ai/totem#2468) can carry\n// the same session UUID as its join key.\nlet mintedSessionId = null;\ntry {\n const ledgerDir = join(process.cwd(), '.totem', 'ledger');\n mkdirSync(ledgerDir, { recursive: true });\n const sessionId = randomUUID();\n mintedSessionId = sessionId;\n writeFileSync(join(ledgerDir, '.session-id'), sessionId, 'utf-8');\n // Amended ADR-078 (2026-07-15): agent_source is the env-carried seat-id\n // (TOTEM_SELF_AGENT, first non-empty comma entry), never a vendor class\n // ('claude' has no reverse projection to a seat). Omitted entirely when\n // the env var is absent: stamp absence, never guess (Tenet 4). The parse\n // deliberately mirrors deriveSearchLogAttribution (packages/mcp/src/\n // search-log.ts) and parseEnvAgentList (packages/core/src/\n // orchestration-resolver.ts) \u2014 inlined because this rendered .cjs hook\n // runs standalone in consumer repos with no access to those modules; if\n // the shared parse semantics change, change this template in the same PR.\n const selfAgent = (process.env.TOTEM_SELF_AGENT || '')\n .split(',')\n .map((s) => s.trim())\n .find((s) => s.length > 0);\n const event = {\n timestamp: new Date().toISOString(),\n type: 'session_start',\n activity_name: 'SessionStart',\n source: 'bot',\n ...(selfAgent ? { agent_source: selfAgent } : {}),\n justification: '',\n session_id: sessionId,\n };\n appendFileSync(join(ledgerDir, 'events.ndjson'), JSON.stringify(event) + '\\n', 'utf-8');\n} catch (err) {\n // Fire-and-forget; ledger failures must not block the briefing. A lightweight\n // stderr breadcrumb makes hook misconfigurations diagnosable in consumer repos\n // (CR R1 catch \u2014 empty catch suppresses all signal). stderr (not stdout) so\n // the briefing path remains clean for Claude's prompt context.\n process.stderr.write(\n '[SessionStart] Session-start telemetry unavailable (non-fatal): ' +\n (err instanceof Error ? err.message : String(err)) +\n '\\n',\n );\n}\n\n// \u2500\u2500\u2500 totem-status refresh-gh \u2014 GH-federation snapshot refresh \u2500\u2500\u2500\n// (mmnto-ai/totem-status#127 C3 residual; tracking mmnto-ai/totem#2556.)\n// Spawn-and-forget, detached+unref, fired BEFORE the synchronous describe/orient\n// briefings so it overlaps them: session start must never block on it\n// (mmnto-ai/totem#2059 measured ~3s of synchronous gh calls here). The verb's\n// exit-0-or-nothing contract (single-flight, atomic rename, no-clobber when gh\n// is missing) makes blind firing safe. ENOENT = the sidecar is not adopted in\n// this repo (the common non-cohort case) \u2014 zero noise; any other spawn failure\n// keeps a non-fatal stderr breadcrumb.\n// A SECOND verb rides this same block: `totem-status refresh-obligation-store`\n// (mmnto-ai/totem-status#127 slice-two residual, sibling of mmnto-ai/totem#2556)\n// writes the durable obligation store beside the GH snapshot, so it gets the same\n// session-start moment. Same primary-checkout gate, same detached+unref spawn, same\n// inherited log fd, same ENOENT-silent arm \u2014 and each firing stamps its own `verb=`\n// field, so the log records WHICH verbs fired and in what order. That does NOT\n// restore the #2570 per-child reap discriminator: both stamps are written\n// back-to-back before either child writes, and child output carries no verb tag\n// and arrives in nondeterministic order, so a silent tail attributes only to the\n// LAST verb stamped. Reopen when the sidecar tags its own output. Blind firing\n// stays safe here too: that verb is in-process single-flight only, so it races the\n// daemon exactly the way its manual invocation already does.\n// PRIMARY checkout only (.git must be a DIRECTORY): in a linked worktree .git is a\n// pointer FILE, and a detached child inheriting the worktree cwd holds a Windows\n// directory lock that breaks worktree removal; the primary's hooks + the daemon\n// cover the workspace-level snapshot (single-flight makes extra fires redundant).\n// A non-git cwd has no refresh moment at all. The stat is cwd-anchored, not a\n// walk-up: both host runtimes launch session hooks with cwd = project root, so a\n// subdirectory cwd (which would skip) does not occur in practice \u2014 and adding a\n// git walk would cost a synchronous process on the very path this block keeps free.\ntry {\n const nodePath = require('path');\n const { statSync } = require('fs');\n let primaryCheckout = false;\n try {\n primaryCheckout = statSync(nodePath.join(process.cwd(), '.git')).isDirectory();\n } catch {\n // not a git checkout (or .git unreadable) \u2014 no refresh moment here\n }\n if (primaryCheckout) {\n const { spawn } = require('child_process');\n // Observability leg (mmnto-ai/totem#2570, routed from the status seat's\n // 2026-08-03 silent no-write): under stdio:'ignore' plus the verb's\n // exit-0-or-nothing contract, a reaped or dying child leaves NO trace\n // (Windows detached is not job-object breakaway \u2014 a hook-harness\n // tree-kill takes the child mid-run). Each firing stamps a workspace-root\n // log and hands the children the same fd, so their output lands after the\n // stamps. Measured caveat now that TWO verbs share one fd: both stamps are\n // written back-to-back before either child writes, and the children's\n // output is unlabelled and interleaves nondeterministically \u2014 so a silent\n // tail no longer discriminates per child; it attributes only to the LAST\n // verb stamped. The stamps still record which verbs fired, and in what\n // order. Log failures degrade to the previous blind firing \u2014 the stamp\n // must never block or break the spawn.\n const { openSync, closeSync, appendFileSync, existsSync, writeFileSync } = require('fs');\n // REPO-LOCAL log, inside .git (falsification round: the primary-checkout\n // gate just proved .git is a directory; never tracked, dies with the\n // clone, writable wherever git itself writes, and per-repo so concurrent\n // firings from sibling repos never interleave). A workspace-parent path\n // would grow an un-gitignorable file OUTSIDE the repo tree for every\n // consumer of these published templates \u2014 including non-adopters, whose\n // ENOENT firing still stamps.\n const logPath = nodePath.join(process.cwd(), '.git', 'totem-status-refresh-hook.log');\n // Control characters are scrubbed from path-derived fields before they\n // reach the log (terminal-injection guideline: a crafted checkout path\n // must not forge stamp lines or inject terminal controls).\n const scrub = (v) => String(v).replace(/[\\x00-\\x1f\\x7f]/g, '?');\n let stdio = 'ignore';\n let logFd = null;\n try {\n try {\n // 1 MiB self-cap: the log truncates rather than growing forever.\n if (statSync(logPath).size > 1048576) writeFileSync(logPath, '');\n } catch {\n // no log yet \u2014 nothing to cap\n }\n appendFileSync(logPath, '[' + new Date().toISOString() + '] claude spawn cwd=' + scrub(process.cwd()) + ' path-has-go-bin=' + /go[\\\\/]bin/i.test(process.env.PATH || '') + ' cwd-shadow-exe=' + existsSync(nodePath.join(process.cwd(), 'totem-status.exe')) + ' verb=refresh-gh\\n');\n logFd = openSync(logPath, 'a');\n stdio = ['ignore', logFd, logFd];\n } catch {\n // log unavailable \u2014 refresh still fires blind, as before\n }\n const refresh = spawn('totem-status', ['refresh-gh'], {\n detached: true,\n stdio,\n });\n refresh.on('error', (err) => {\n try {\n appendFileSync(logPath, '[' + new Date().toISOString() + '] claude spawn-error code=' + ((err && err.code) || 'unknown') + ' verb=refresh-gh\\n');\n } catch {\n // log write failed \u2014 fall through to the stderr breadcrumb\n }\n if (err && err.code === 'ENOENT') return;\n process.stderr.write('[SessionStart] totem-status refresh-gh spawn failed (non-fatal): ' + (err instanceof Error ? err.message : String(err)) + '\\n');\n });\n refresh.unref();\n // Second verb, same gate and same log fd (see the banner above). Written out\n // rather than looped so the spawn, the stamp, and the breadcrumb each carry a\n // literal verb \u2014 a reader of the generated hook (or of the log) never has to\n // resolve a variable to know which refresh fired.\n try {\n appendFileSync(logPath, '[' + new Date().toISOString() + '] claude spawn cwd=' + scrub(process.cwd()) + ' path-has-go-bin=' + /go[\\\\/]bin/i.test(process.env.PATH || '') + ' cwd-shadow-exe=' + existsSync(nodePath.join(process.cwd(), 'totem-status.exe')) + ' verb=refresh-obligation-store\\n');\n } catch {\n // log unavailable \u2014 this verb still fires blind, exactly as the first does\n }\n const refreshStore = spawn('totem-status', ['refresh-obligation-store'], {\n detached: true,\n stdio,\n });\n refreshStore.on('error', (err) => {\n try {\n appendFileSync(logPath, '[' + new Date().toISOString() + '] claude spawn-error code=' + ((err && err.code) || 'unknown') + ' verb=refresh-obligation-store\\n');\n } catch {\n // log write failed \u2014 fall through to the stderr breadcrumb\n }\n if (err && err.code === 'ENOENT') return;\n process.stderr.write('[SessionStart] totem-status refresh-obligation-store spawn failed (non-fatal): ' + (err instanceof Error ? err.message : String(err)) + '\\n');\n });\n refreshStore.unref();\n // Each child holds its own copy of the fd from spawn time; release the parent's\n // once BOTH are away (an early close would hand the second spawn an EBADF).\n if (logFd !== null) {\n try {\n closeSync(logFd);\n } catch {\n // nothing to release\n }\n }\n }\n} catch (err) {\n // Block-level breadcrumb: this catch covers the whole gated block, so neither\n // verb fired \u2014 it names the SIDECAR, not one verb. The per-spawn breadcrumbs\n // inside still name their own verb.\n process.stderr.write('[SessionStart] totem-status sidecar refresh unavailable (non-fatal): ' + (err instanceof Error ? err.message : String(err)) + '\\n');\n}\n\n// \u2500\u2500\u2500 totem describe briefing (existing behavior) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Captured (mmnto-ai/totem#2468): the injected block is the selection-manifest\n// candidate below \u2014 the not-installed notice is a notice, not a briefing.\nlet describeText = '';\ntry {\n const cliPath = join(process.cwd(), 'node_modules', '@mmnto', 'cli', 'dist', 'index.js');\n if (existsSync(cliPath)) {\n const result = spawnSync(process.execPath, [cliPath, 'describe'], {\n encoding: 'utf-8',\n timeout: 30000,\n });\n if (result.error) {\n throw result.error;\n }\n // Totem CLI writes diagnostic output to stderr; route to stdout so the\n // session-start context lands in Claude's prompt rather than user-visible noise.\n describeText = (result.stdout || '') + (result.stderr || '');\n process.stdout.write(describeText);\n } else {\n // The notice is printed in exactly the state where a Bash|PowerShell-matched\n // gate self-blocks (no repo-local CLI), so it names the property and the exit\n // (mmnto-ai/totem#2822 ask 3): the wrapper's PATH arm usually carries a fresh\n // clone, and when it cannot, the bootstrap belongs in a real terminal.\n process.stdout.write(\n '[Totem] @mmnto/cli not installed. Run `pnpm install` (or your package manager equivalent) to enable session-start orientation. ' +\n 'If a Bash|PowerShell-matched gate is installed here it applies to the bootstrap commands and falls back to a totem on PATH; ' +\n 'with no totem anywhere, bootstrap this clone from a terminal outside the harness.\\n',\n );\n }\n} catch (err) {\n process.stdout.write(\n '[Totem] Briefing unavailable: ' +\n (err instanceof Error ? err.message : String(err)) +\n '\\n',\n );\n}\n\n// \u2500\u2500\u2500 totem orient --session \u2014 live derived in-flight state (mmnto-ai/totem#2044 PR-3) \u2500\u2500\n// ADDITIVE to describe (Tenet 13: describe = static identity sensor \u2014 scope/tier/\n// counts; orient = live in-flight sensor \u2014 open PRs/issues/board/freeze). Append,\n// never replace. Its OWN try/catch so an orient failure never disturbs the describe\n// briefing or the boot; `orient --session` is itself boot-safe (emits nothing when\n// nothing is high-signal, never exits non-zero, degrades to honest \"could not derive\").\nlet orientText = '';\ntry {\n const orientCliPath = join(process.cwd(), 'node_modules', '@mmnto', 'cli', 'dist', 'index.js');\n if (existsSync(orientCliPath)) {\n const orientResult = spawnSync(process.execPath, [orientCliPath, 'orient', '--session'], {\n encoding: 'utf-8',\n timeout: 30000,\n });\n // spawnSync sets .error (it does NOT throw) on a spawn-level failure; re-throw so\n // it surfaces through the catch breadcrumb below rather than writing '' silently.\n if (orientResult.error) {\n throw orientResult.error;\n }\n orientText = (orientResult.stdout || '') + (orientResult.stderr || '');\n process.stdout.write(orientText);\n }\n} catch (err) {\n // Boot-safe: orient is additive to describe (already emitted), so a failure never\n // blocks session start \u2014 but surface a NON-fatal breadcrumb to stderr (not stdout,\n // to keep the prompt clean) for debuggability rather than swallowing silently.\n process.stderr.write(\n '[SessionStart] orient briefing unavailable (non-fatal): ' +\n (err instanceof Error ? err.message : String(err)) +\n '\\n',\n );\n}\n\n// \u2500\u2500\u2500 selection manifest (mmnto-ai/totem#2468 M1) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Inline append mirroring the session_start write above \u2014 this rendered hook\n// runs standalone in consumer repos with no access to @mmnto/totem's writer.\n// The row shape is BOUND to SelectionManifestRowSchema (strict): change both\n// in the same PR; the template contract test parses this row with the real\n// schema. A zero-byte block never becomes a candidate (nothing was injected).\ntry {\n const { createHash } = require('crypto');\n const measure = (id, content, reason) => {\n const bytes = Buffer.byteLength(content, 'utf-8');\n return {\n id,\n disposition: 'selected',\n reason,\n bytes,\n approxTokens: Math.ceil(bytes / 4),\n fingerprint: createHash('sha256').update(content, 'utf-8').digest('hex').slice(0, 16),\n };\n };\n const selfAgent = (process.env.TOTEM_SELF_AGENT || '')\n .split(',')\n .map((s) => s.trim())\n .find((s) => s.length > 0);\n const row = {\n schemaVersion: 1,\n timestamp: new Date().toISOString(),\n emitter: 'session-start',\n ...(mintedSessionId ? { session_id: mintedSessionId } : {}),\n ...(selfAgent ? { agent_source: selfAgent } : {}),\n // mmnto-ai/totem#2629: provenance disclosed on every row (ruled item 1).\n // Self-minted row \u2014 the minting seat IS this process's env read, so the\n // core conflict probe is structurally inapplicable; only the two-value\n // provenance enum rides. Mirrors senseAgentAttribution's biconditional.\n agent_source_provenance: selfAgent ? 'env' : 'absent',\n context: { template: 'claude-managed' },\n universe: 'managed-template blocks: describe + orient --session',\n costBasis: { bytes: 'utf8-length', approxTokens: 'ceil(bytes/4) approximation' },\n candidates: [\n measure('describe', describeText, 'always-injected briefing'),\n measure('orient:session-block', orientText, 'always-injected briefing'),\n ].filter((c) => c.bytes > 0),\n warnings: [],\n };\n appendFileSync(\n join(process.cwd(), '.totem', 'ledger', 'selection-manifests.ndjson'),\n JSON.stringify(row) + '\\n',\n 'utf-8',\n );\n} catch (err) {\n process.stderr.write(\n '[SessionStart] selection manifest unavailable (non-fatal): ' +\n (err instanceof Error ? err.message : String(err)) +\n '\\n',\n );\n}\n// [totem] end auto-generated\n";
77
77
  export declare const CLAUDE_SESSION_START_ENTRY: {
78
78
  hooks: {
79
79
  type: string;
@@ -81,7 +81,7 @@ export declare const CLAUDE_SESSION_START_ENTRY: {
81
81
  timeout: number;
82
82
  }[];
83
83
  };
84
- export declare const CLAUDE_GATE_WRAPPER = "// [totem] auto-generated \u2014 Claude Code action-gate wrapper\n// ONE parameterized PreToolUse wrapper for the Totem gate engine (PR-C,\n// mmnto-ai/totem#2048). Reads --event <name> from argv (baked per-entry into\n// the installed command), reads the PreToolUse stdin envelope, shells to\n// `totem gate check`, and maps the GateVerdict disposition \u2192 host exit code.\n// `.cjs` extension because package.json may have \"type\": \"module\" \u2014 Claude\n// Code execs hooks via plain `node`, which would otherwise treat `.js` as ESM.\n//\n// Exit-code contract (LOAD-BEARING \u2014 ADR-109 \u00A72; branch ONLY on disposition):\n// 0 = allow | warn | --pilot deny | NOT-APPLICABLE fail-soft\n// (unparseable/non-object envelope, no-declared-subsystem pass-through)\n// 2 = deny (--strict, Claude block convention)\n// | APPLICABLE-gate-not-evaluable fail-closed (missing CLI, non-zero\n// `gate check`, unparseable verdict, or unknown disposition)\n'use strict';\n\nconst { spawnSync } = require('child_process');\nconst { existsSync } = require('fs');\nconst { join } = require('path');\n\n// \u2500\u2500\u2500 Parse baked args (--event <name>, optional --pilot / --strict) \u2500\u2500\u2500\u2500\u2500\n// The tier is read ONLY from argv (baked into the installed command at\n// install time). There is NO env-var override: env sourcing would be a\n// fail-open (any shell with TOTEM_GATE_TIER=pilot could silently downgrade\n// enforcement). Default (no flag) = strict, so a default install is\n// environment-immune; --pilot is an explicit install-time opt-in.\nconst argv = process.argv.slice(2);\nlet event = '';\nlet tier = 'strict';\nfor (let i = 0; i < argv.length; i++) {\n if (argv[i] === '--event') {\n event = argv[i + 1] || '';\n i++;\n } else if (argv[i] === '--pilot') {\n tier = 'pilot';\n } else if (argv[i] === '--strict') {\n tier = 'strict';\n }\n}\n\n// Read the PreToolUse stdin envelope.\nlet stdin = '';\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', (chunk) => {\n stdin += chunk;\n});\nprocess.stdin.on('end', () => {\n let parsed;\n try {\n parsed = stdin ? JSON.parse(stdin) : {};\n } catch (err) {\n // Fail-soft on a malformed envelope (mirror PreWriteShield): a broken\n // host envelope is not an applicable gate, so it must NOT block.\n process.stderr.write('[totem gate-wrapper] could not parse stdin JSON; allowing\\n');\n process.exit(0);\n }\n\n // Valid JSON can still be a non-object (the bytes `null`, `123`, or a bare\n // quoted string). Such an envelope carries no `tool_input` to dereference and\n // is NOT an applicable gate \u2192 fail-soft (exit 0). Guarding here also prevents\n // a TypeError-on-deref from leaking as exit 1.\n if (parsed === null || typeof parsed !== 'object') {\n process.stderr.write('[totem gate-wrapper] stdin JSON is not an object; allowing\\n');\n process.exit(0);\n }\n\n const input =\n typeof parsed.tool_input === 'object' && parsed.tool_input !== null ? parsed.tool_input : {};\n\n // \u2500\u2500\u2500 THE EMPTY-SUBSYSTEM GUARDRAIL \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 // freeze-check's predicate is on a DECLARED subsystem. A normal Edit/Write\n // carries tool_input.file_path (a path), NOT a subsystem. With no declared\n // subsystem, NO GATE APPLIES \u2192 pass through (exit 0). Do NOT shell out \u2014 a\n // blanket fail-closed here would block every ordinary edit.\n const declaredSubsystem =\n typeof input.subsystem === 'string' && input.subsystem.trim() !== ''\n ? input.subsystem.trim()\n : '';\n if (declaredSubsystem === '') {\n process.exit(0);\n }\n\n // A gate genuinely applies. Build the --payload from the declared fields.\n // NOTE: this payload projection is freeze-check-shaped (subsystem-only). The\n // wrapper is --event-parameterized, but the payload it builds is currently\n // freeze-check-specific; a future gate needing a different payload field must\n // extend this projection (e.g. branch on `event`).\n const payload = JSON.stringify({ subsystem: declaredSubsystem });\n\n // Resolve the LOCAL Totem CLI (the global `totem` binary may be stale and\n // missing deps \u2014 the known repo gotcha). Invoke node on the installed dist\n // entry.\n //\n // FAIL-CLOSED on a missing CLI: we are PAST the empty-subsystem guardrail, so\n // a gate genuinely APPLIES here. freeze-check has NO commit-time hard floor\n // (unlike PreWriteShield, whose fail-soft is backed by `totem-lint` at\n // commit), so an APPLICABLE gate that cannot be evaluated for ANY reason\n // (missing CLI OR corrupt freeze.json) must fail closed \u2014 not silently allow\n // (guardrail rule + Tenet 4 fail-closed). Fail-SOFT (exit 0) is reserved for\n // genuinely NOT-APPLICABLE inputs (unparseable/non-object envelope, no\n // declared subsystem), all of which already returned above.\n const cliPath = join(process.cwd(), 'node_modules', '@mmnto', 'cli', 'dist', 'index.js');\n if (!existsSync(cliPath)) {\n process.stderr.write(\n '[totem gate] ' +\n event +\n ' applies but the totem CLI is not resolvable; failing closed. ' +\n 'Reinstall totem or run `totem eject` to remove the gate.\\n',\n );\n process.exit(2);\n }\n\n const result = spawnSync(\n process.execPath,\n [cliPath, 'gate', 'check', '--event', event, '--payload', payload],\n { encoding: 'utf-8', timeout: 30000 },\n );\n\n // \u2500\u2500\u2500 FAIL-CLOSED \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 // A gate genuinely applies (a declared subsystem was present) and the\n // evaluation itself failed (non-zero exit: corrupt freeze.json, spawn\n // error, etc.). Never silently allow when an applicable gate's source is\n // broken \u2192 exit 2. (No-declared-subsystem already returned exit 0 above,\n // so this only blocks when a subsystem was actually declared.)\n if (result.error || typeof result.status !== 'number' || result.status !== 0) {\n process.stderr.write(\n '[totem gate-wrapper] gate \"' +\n event +\n '\" evaluation failed (source broken or unavailable) \u2014 blocking (fail-closed).\\n' +\n (result.stderr || (result.error ? String(result.error.message || result.error) : '')) +\n '\\n',\n );\n process.exit(2);\n }\n\n let verdict;\n try {\n verdict = JSON.parse(result.stdout || '');\n } catch (err) {\n // The command emitted unparseable stdout despite a 0 exit \u2014 an applicable\n // gate whose verdict we cannot read is a broken source \u2192 fail-closed.\n process.stderr.write(\n '[totem gate-wrapper] gate \"' + event + '\" emitted unparseable verdict \u2014 blocking (fail-closed).\\n',\n );\n process.exit(2);\n }\n\n // \u2500\u2500\u2500 Disposition \u2192 host exit code (branch ONLY on disposition) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const disposition = verdict && typeof verdict.disposition === 'string' ? verdict.disposition : '';\n // reason/provenance are OPAQUE stderr passthrough \u2014 never parsed for control flow.\n const detail =\n (verdict && verdict.reason ? verdict.reason : '') +\n (verdict && verdict.provenance ? ' [' + JSON.stringify(verdict.provenance) + ']' : '');\n\n if (disposition === 'allow') {\n process.exit(0);\n }\n if (disposition === 'warn') {\n process.stderr.write('[totem gate-wrapper] ' + event + ' (warn): ' + detail + '\\n');\n process.exit(0);\n }\n if (disposition === 'deny') {\n process.stderr.write('[totem gate-wrapper] ' + event + ' (deny): ' + detail + '\\n');\n process.exit(tier === 'pilot' ? 0 : 2);\n }\n\n // Unknown disposition from an applicable gate \u2014 fail-closed.\n process.stderr.write(\n '[totem gate-wrapper] gate \"' + event + '\" returned unknown disposition \"' + disposition + '\" \u2014 blocking (fail-closed).\\n',\n );\n process.exit(2);\n});\n// [totem] end auto-generated\n";
84
+ export declare const CLAUDE_GATE_WRAPPER = "// [totem] auto-generated \u2014 Claude Code action-gate wrapper\n// ONE parameterized PreToolUse wrapper for the Totem gate engine (PR-C,\n// mmnto-ai/totem#2048). Reads --event <name> from argv (baked per-entry into\n// the installed command), reads the PreToolUse stdin envelope, shells to\n// `totem gate check`, and maps the GateVerdict disposition \u2192 host exit code.\n// `.cjs` extension because package.json may have \"type\": \"module\" \u2014 Claude\n// Code execs hooks via plain `node`, which would otherwise treat `.js` as ESM.\n//\n// Exit-code contract (LOAD-BEARING \u2014 ADR-109 \u00A72; branch ONLY on disposition):\n// 0 = allow | warn | --pilot deny | NOT-APPLICABLE fail-soft\n// (unparseable/non-object envelope; freeze-check with no declared\n// subsystem; transport-shield on a tool other than Bash/PowerShell or\n// with no non-empty string command)\n// 2 = deny (--strict, Claude block convention)\n// | APPLICABLE-gate-not-evaluable fail-closed (no CLI resolvable\n// (repo-local, then PATH), non-zero `gate check`, unparseable verdict,\n// or unknown disposition)\n// | an --event this wrapper has no payload projection for (a baked event\n// it cannot project is an applicable gate it cannot evaluate)\n'use strict';\n\nconst { spawnSync } = require('child_process');\nconst { existsSync, realpathSync } = require('fs');\nconst { basename, delimiter, dirname, join } = require('path');\n\n// \u2500\u2500\u2500 PATH FALLBACK for the Totem CLI (mmnto-ai/totem#2822) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// A `Bash|PowerShell`-matched gate applies to the very commands that CREATE\n// the repo-local CLI on a fresh clone (`pnpm install`, then `pnpm build` in\n// this monorepo), so with a repo-local-only resolution the gate blocks its own\n// bootstrap \u2014 and blocks the cure it prints. This is a RESOLUTION arm, not an\n// exemption: an applicable gate that cannot be evaluated by EITHER arm still\n// fails closed (mmnto-ai/totem#2799 ruling, Tenet 4).\n//\n// A session started in a fresh worktree has no node_modules at its cwd and\n// takes this arm; with no global CLI it fails closed \u2014 the ruling, not a bug.\n//\n// The repo-local pinned dist stays FIRST \u2014 the pinned-beats-ambient ordering of\n// ADR-072 \u00A7 2; tiers 1, 3 and 5 are out of scope for a hook that must not shell\n// out. This runs only when the pinned dist is absent. Two npm-global layouts\n// are probed per PATH dir, first hit wins:\n// (a) <dir>/node_modules/@mmnto/cli/dist/index.js \u2014 the win32 layout, where\n// the `totem.cmd` shim sits beside `node_modules`;\n// (b) <dir>/totem realpath'd \u2014 the POSIX npm-global symlink, taken only when\n// it resolves to an existing `.js` file (a shell shim resolves to an\n// extensionless script and is correctly skipped).\n// A dir that yields neither is skipped; nothing here throws.\n//\n// PATH is trusted here at exactly the level `node` itself already is: the\n// settings.json entry invokes this hook as a bare `node`, so whoever controls\n// PATH controls the interpreter before this line ever runs.\n//\n// Returns { entry, display }: `entry` is the absolute path to spawn, `display`\n// a NON-resolvable rendering (basenames only) for the stderr provenance line \u2014\n// hook stderr lands in transcripts that get pasted into issues, so it never\n// carries a user-profile path.\nfunction resolveCliFromPath() {\n const raw = typeof process.env.PATH === 'string' ? process.env.PATH : '';\n const dirs = raw.split(delimiter);\n for (let i = 0; i < dirs.length; i++) {\n const dir = dirs[i];\n if (!dir) continue;\n const packaged = join(dir, 'node_modules', '@mmnto', 'cli', 'dist', 'index.js');\n if (existsSync(packaged)) {\n return {\n entry: packaged,\n display: basename(dir) + '/node_modules/@mmnto/cli/dist/index.js',\n };\n }\n const shim = join(dir, 'totem');\n if (existsSync(shim)) {\n try {\n const real = realpathSync(shim);\n if (typeof real === 'string' && real.endsWith('.js') && existsSync(real)) {\n return {\n entry: real,\n display:\n basename(dir) + '/totem -> ' + basename(dirname(real)) + '/' + basename(real),\n };\n }\n } catch (err) {\n // An unreadable link is not a resolution \u2014 keep scanning the PATH.\n }\n }\n }\n return null;\n}\n\n// \u2500\u2500\u2500 Parse baked args (--event <name>, optional --pilot / --strict) \u2500\u2500\u2500\u2500\u2500\n// The tier is read ONLY from argv (baked into the installed command at\n// install time). There is NO env-var override: env sourcing would be a\n// fail-open (any shell with TOTEM_GATE_TIER=pilot could silently downgrade\n// enforcement). Default (no flag) = strict, so a default install is\n// environment-immune; --pilot is an explicit install-time opt-in.\nconst argv = process.argv.slice(2);\nlet event = '';\nlet tier = 'strict';\nfor (let i = 0; i < argv.length; i++) {\n if (argv[i] === '--event') {\n event = argv[i + 1] || '';\n i++;\n } else if (argv[i] === '--pilot') {\n tier = 'pilot';\n } else if (argv[i] === '--strict') {\n tier = 'strict';\n }\n}\n\n// Read the PreToolUse stdin envelope.\nlet stdin = '';\nprocess.stdin.setEncoding('utf-8');\nprocess.stdin.on('data', (chunk) => {\n stdin += chunk;\n});\nprocess.stdin.on('end', () => {\n let parsed;\n try {\n parsed = stdin ? JSON.parse(stdin) : {};\n } catch (err) {\n // Fail-soft on a malformed envelope (mirror PreWriteShield): a broken\n // host envelope is not an applicable gate, so it must NOT block.\n process.stderr.write('[totem gate-wrapper] could not parse stdin JSON; allowing\\n');\n process.exit(0);\n }\n\n // Valid JSON can still be a non-object (the bytes `null`, `123`, or a bare\n // quoted string). Such an envelope carries no `tool_input` to dereference and\n // is NOT an applicable gate \u2192 fail-soft (exit 0). Guarding here also prevents\n // a TypeError-on-deref from leaking as exit 1.\n if (parsed === null || typeof parsed !== 'object') {\n process.stderr.write('[totem gate-wrapper] stdin JSON is not an object; allowing\\n');\n process.exit(0);\n }\n\n const input =\n typeof parsed.tool_input === 'object' && parsed.tool_input !== null ? parsed.tool_input : {};\n\n // \u2500\u2500\u2500 PER-EVENT PAYLOAD PROJECTION \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 // Each gate reads a DIFFERENT slice of the PreToolUse envelope, so the\n // projection branches on the baked --event. Every branch owns its own\n // NOT-APPLICABLE test \u2014 the point past which a gate genuinely applies and\n // any evaluation failure must fail CLOSED.\n //\n // event | applies when | payload\n // -----------------|----------------------------------|---------------------------\n // freeze-check | tool_input.subsystem is a | { subsystem }\n // | non-empty string |\n // transport-shield | tool_name is Bash or PowerShell | { tool, command, platform }\n // | AND tool_input.command is a |\n // | non-empty string |\n // (anything else) | \u2014 no projection \u2192 fail closed | \u2014\n let payload = '';\n\n if (event === 'freeze-check') {\n // THE EMPTY-SUBSYSTEM GUARDRAIL: freeze-check's predicate is on a DECLARED\n // subsystem. A normal Edit/Write carries tool_input.file_path (a path), NOT\n // a subsystem. With no declared subsystem, NO GATE APPLIES \u2192 pass through\n // (exit 0). Do NOT shell out \u2014 a blanket fail-closed here would block every\n // ordinary edit.\n const declaredSubsystem =\n typeof input.subsystem === 'string' && input.subsystem.trim() !== ''\n ? input.subsystem.trim()\n : '';\n if (declaredSubsystem === '') {\n process.exit(0);\n }\n payload = JSON.stringify({ subsystem: declaredSubsystem });\n } else if (event === 'transport-shield') {\n // transport-shield's predicate is on a SHELL COMMAND. Anything that is not\n // a Bash/PowerShell invocation carrying a command string is NOT an\n // applicable gate \u2192 pass through (exit 0), mirroring the guardrail above.\n // The installed matcher is the CLI's own, so a foreign tool_name here means\n // a hand-edited settings entry, not a shape to judge.\n const tool = parsed.tool_name;\n if (tool !== 'Bash' && tool !== 'PowerShell') {\n process.exit(0);\n }\n if (typeof input.command !== 'string' || input.command.trim() === '') {\n process.exit(0);\n }\n payload = JSON.stringify({\n tool: tool,\n command: input.command,\n platform: process.platform,\n });\n } else {\n // A baked --event this wrapper cannot project is an APPLICABLE gate it\n // cannot evaluate \u2192 fail closed (ADR-109). Reinstalling refreshes the\n // wrapper (`totem gate install` drift-repairs the bounded region).\n process.stderr.write(\n '[totem gate-wrapper] no payload projection for event \"' + event + '\"; failing closed.\\n',\n );\n process.exit(2);\n }\n\n // Resolve the Totem CLI: the repo-local pinned dist FIRST (a global `totem`\n // may be stale and missing deps \u2014 the known repo gotcha; the\n // pinned-beats-ambient ordering of ADR-072 \u00A7 2, Tenet 14), then a `totem` on\n // PATH as a FALLBACK (mmnto-ai/totem#2822 \u2014 the bootstrap self-block above).\n // Invoke node on whichever dist entry resolved.\n //\n // FAIL-CLOSED when NEITHER arm resolves: we are PAST the per-event\n // applicability guardrail (freeze-check: a declared subsystem;\n // transport-shield: a Bash or PowerShell command), so a gate genuinely\n // APPLIES here. Neither gate has a commit-time hard floor (unlike\n // PreWriteShield, whose fail-soft is backed by `totem-lint` at commit), so an\n // APPLICABLE gate that cannot be evaluated for ANY reason (no CLI anywhere OR\n // a broken source) must fail closed \u2014 not silently allow (guardrail rule +\n // Tenet 4 fail-closed). Fail-SOFT (exit 0) is reserved for genuinely\n // NOT-APPLICABLE inputs (unparseable/non-object envelope, no declared\n // subsystem, no shell command), all of which already returned above.\n const localCliPath = join(process.cwd(), 'node_modules', '@mmnto', 'cli', 'dist', 'index.js');\n let cliPath = '';\n // Which arm resolved \u2014 'repo-local' or 'PATH' \u2014 for the provenance line the\n // fail-closed arms below disclose. Empty until one resolves.\n let arm = '';\n // The PATH arm's non-resolvable rendering of what it found (basenames only).\n let cliDisplay = '';\n if (existsSync(localCliPath)) {\n cliPath = localCliPath;\n arm = 'repo-local';\n } else {\n const fromPath = resolveCliFromPath();\n if (fromPath) {\n cliPath = fromPath.entry;\n cliDisplay = fromPath.display;\n arm = 'PATH';\n }\n }\n\n if (!cliPath) {\n // The exits named here must be exits the gate does NOT block: \"reinstall\n // totem\" and `totem eject` are Bash commands a Bash|PowerShell gate blocks\n // with this very message (mmnto-ai/totem#2822). They are ORDERED: the\n // editor path still needs the bootstrap before the gate can be reinstalled.\n process.stderr.write(\n '[totem gate] ' +\n event +\n ' applies but no totem CLI is resolvable ' +\n '(repo-local node_modules/@mmnto/cli/dist/index.js absent; no totem on PATH); ' +\n 'failing closed. Exits: bootstrap from a terminal OUTSIDE the harness ' +\n '(pnpm install and pnpm build, or npm i -g @mmnto/cli); or remove this ' +\n \"gate's entry from .claude/settings.json with the editor, bootstrap, \" +\n 'then re-run totem gate install ' +\n event +\n '.\\n',\n );\n process.exit(2);\n }\n\n // The payload rides on the child's STDIN (`--payload -`), never argv: a Bash\n // command can run to tens of kilobytes and win32 caps a command line at\n // 32,767 characters \u2014 an argv payload past it fails the spawn with\n // ENAMETOOLONG and would land in the fail-closed arm below with nothing\n // broken (mmnto-ai/totem#2799, pass 3).\n const result = spawnSync(\n process.execPath,\n [cliPath, 'gate', 'check', '--event', event, '--payload', '-'],\n { encoding: 'utf-8', timeout: 30000, input: payload },\n );\n\n // Provenance for the PATH fallback arm (mmnto-ai/totem#2822): a CLI older\n // than 2.2.0 has no `gate check --payload -` and lands in the fail-closed\n // arms below (unknown option \u2192 non-zero exit, or nothing on stdout). The\n // BEHAVIOUR is unchanged \u2014 exit 2 either way \u2014 the line only names WHICH CLI\n // evaluated and how to update it. Empty on the repo-local arm. It prints the\n // basename rendering, never the absolute entry: this is transcript-bound text.\n const armNote =\n arm === 'PATH'\n ? 'evaluated by the PATH CLI at ' +\n cliDisplay +\n \"; a CLI older than 2.2.0 lacks 'gate check --payload -' \u2014 \" +\n 'update it: npm i -g @mmnto/cli@latest\\n'\n : '';\n\n // \u2500\u2500\u2500 FAIL-CLOSED \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 // A gate genuinely applies (the per-event projection above found its input:\n // a declared subsystem, or a Bash/PowerShell command) and the evaluation\n // itself failed (non-zero exit: corrupt freeze.json, an invalid payload,\n // spawn error, etc.). Never silently allow when an applicable gate's source\n // is broken \u2192 exit 2. (Not-applicable envelopes already returned exit 0\n // above, so this only blocks when the gate's input was actually present.)\n if (result.error || typeof result.status !== 'number' || result.status !== 0) {\n process.stderr.write(\n '[totem gate-wrapper] gate \"' +\n event +\n '\" evaluation failed (source broken or unavailable) \u2014 blocking (fail-closed).\\n' +\n (result.stderr || (result.error ? String(result.error.message || result.error) : '')) +\n '\\n' +\n armNote,\n );\n process.exit(2);\n }\n\n let verdict;\n try {\n verdict = JSON.parse(result.stdout || '');\n } catch (err) {\n // The command emitted unparseable stdout despite a 0 exit \u2014 an applicable\n // gate whose verdict we cannot read is a broken source \u2192 fail-closed.\n process.stderr.write(\n '[totem gate-wrapper] gate \"' + event + '\" emitted unparseable verdict \u2014 blocking (fail-closed).\\n' + armNote,\n );\n process.exit(2);\n }\n\n // \u2500\u2500\u2500 Disposition \u2192 host exit code (branch ONLY on disposition) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const disposition = verdict && typeof verdict.disposition === 'string' ? verdict.disposition : '';\n // reason/provenance are OPAQUE stderr passthrough \u2014 never parsed for control flow.\n const detail =\n (verdict && verdict.reason ? verdict.reason : '') +\n (verdict && verdict.provenance ? ' [' + JSON.stringify(verdict.provenance) + ']' : '');\n\n if (disposition === 'allow') {\n // Deliberately SILENT on the PATH arm too: a provenance line on every\n // allowed Bash command would be transcript noise on the common path, and\n // the operator already learned the property at install time (the\n // `gate install` disclosure) \u2014 stderr here is reserved for what blocks.\n process.exit(0);\n }\n if (disposition === 'warn') {\n process.stderr.write('[totem gate-wrapper] ' + event + ' (warn): ' + detail + '\\n');\n process.exit(0);\n }\n if (disposition === 'deny') {\n process.stderr.write('[totem gate-wrapper] ' + event + ' (deny): ' + detail + '\\n');\n process.exit(tier === 'pilot' ? 0 : 2);\n }\n\n // Unknown disposition from an applicable gate \u2014 fail-closed. The provenance\n // note rides here too, so all four not-evaluable causes in the exit-code\n // contract above disclose which arm evaluated.\n process.stderr.write(\n '[totem gate-wrapper] gate \"' + event + '\" returned unknown disposition \"' + disposition + '\" \u2014 blocking (fail-closed).\\n' + armNote,\n );\n process.exit(2);\n});\n// [totem] end auto-generated\n";
85
85
  export declare const CLAUDE_GATE_WRAPPER_ENTRY: {
86
86
  matcher: string;
87
87
  hooks: {
@@ -1 +1 @@
1
- {"version":3,"file":"init-templates.d.ts","sourceRoot":"","sources":["../../src/commands/init-templates.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAMpE,eAAO,MAAM,cAAc,KAAK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