@mmnto/cli 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/commands/config-drift.test.js +4 -1
  2. package/dist/commands/config-drift.test.js.map +1 -1
  3. package/dist/commands/gate-install.d.ts +35 -0
  4. package/dist/commands/gate-install.d.ts.map +1 -1
  5. package/dist/commands/gate-install.js +48 -0
  6. package/dist/commands/gate-install.js.map +1 -1
  7. package/dist/commands/gate-install.test.js +638 -9
  8. package/dist/commands/gate-install.test.js.map +1 -1
  9. package/dist/commands/gate.d.ts +9 -0
  10. package/dist/commands/gate.d.ts.map +1 -1
  11. package/dist/commands/gate.js +37 -2
  12. package/dist/commands/gate.js.map +1 -1
  13. package/dist/commands/gate.test.js +42 -1
  14. package/dist/commands/gate.test.js.map +1 -1
  15. package/dist/commands/init-templates.d.ts +8 -8
  16. package/dist/commands/init-templates.d.ts.map +1 -1
  17. package/dist/commands/init-templates.js +866 -94
  18. package/dist/commands/init-templates.js.map +1 -1
  19. package/dist/commands/init.d.ts.map +1 -1
  20. package/dist/commands/init.js +22 -1
  21. package/dist/commands/init.js.map +1 -1
  22. package/dist/commands/init.test.js +132 -0
  23. package/dist/commands/init.test.js.map +1 -1
  24. package/dist/commands/mail-cli-wiring.test.js +58 -2
  25. package/dist/commands/mail-cli-wiring.test.js.map +1 -1
  26. package/dist/commands/mail-derive-seat.test.d.ts +28 -0
  27. package/dist/commands/mail-derive-seat.test.d.ts.map +1 -0
  28. package/dist/commands/mail-derive-seat.test.js +557 -0
  29. package/dist/commands/mail-derive-seat.test.js.map +1 -0
  30. package/dist/commands/mail.d.ts +112 -0
  31. package/dist/commands/mail.d.ts.map +1 -1
  32. package/dist/commands/mail.js +189 -0
  33. package/dist/commands/mail.js.map +1 -1
  34. package/dist/commands/resolve-threads-cli-wiring.test.d.ts +19 -0
  35. package/dist/commands/resolve-threads-cli-wiring.test.d.ts.map +1 -0
  36. package/dist/commands/resolve-threads-cli-wiring.test.js +103 -0
  37. package/dist/commands/resolve-threads-cli-wiring.test.js.map +1 -0
  38. package/dist/commands/resolve-threads.d.ts +468 -0
  39. package/dist/commands/resolve-threads.d.ts.map +1 -0
  40. package/dist/commands/resolve-threads.js +794 -0
  41. package/dist/commands/resolve-threads.js.map +1 -0
  42. package/dist/commands/resolve-threads.test.d.ts +2 -0
  43. package/dist/commands/resolve-threads.test.d.ts.map +1 -0
  44. package/dist/commands/resolve-threads.test.js +1121 -0
  45. package/dist/commands/resolve-threads.test.js.map +1 -0
  46. package/dist/commands/session-context-journal-select.test.d.ts +2 -0
  47. package/dist/commands/session-context-journal-select.test.d.ts.map +1 -0
  48. package/dist/commands/session-context-journal-select.test.js +95 -0
  49. package/dist/commands/session-context-journal-select.test.js.map +1 -0
  50. package/dist/commands/sync-labels-forms.test.d.ts +36 -0
  51. package/dist/commands/sync-labels-forms.test.d.ts.map +1 -0
  52. package/dist/commands/sync-labels-forms.test.js +573 -0
  53. package/dist/commands/sync-labels-forms.test.js.map +1 -0
  54. package/dist/index.js +74 -5
  55. package/dist/index.js.map +1 -1
  56. package/dist/parsers/bot-identity-parity.test.d.ts +2 -0
  57. package/dist/parsers/bot-identity-parity.test.d.ts.map +1 -0
  58. package/dist/parsers/bot-identity-parity.test.js +175 -0
  59. package/dist/parsers/bot-identity-parity.test.js.map +1 -0
  60. package/dist/parsers/bot-review-parser.d.ts +8 -5
  61. package/dist/parsers/bot-review-parser.d.ts.map +1 -1
  62. package/dist/parsers/bot-review-parser.js +12 -34
  63. package/dist/parsers/bot-review-parser.js.map +1 -1
  64. package/package.json +2 -2
@@ -3,7 +3,7 @@
3
3
  // ─── Reflex versioning ────────────────────────────────────
4
4
  // Bump REFLEX_VERSION whenever the AI_PROMPT_BLOCK content changes materially.
5
5
  // This allows `totem init` to detect stale blocks and offer upgrades.
6
- export const REFLEX_VERSION = 14;
6
+ export const REFLEX_VERSION = 15;
7
7
  export const REFLEX_START = '<!-- totem:reflexes:start -->';
8
8
  export const REFLEX_END = '<!-- totem:reflexes:end -->';
9
9
  export const REFLEX_VERSION_RE = /<!-- totem:reflexes:version:(\d+) -->/;
@@ -42,6 +42,7 @@ Totem provides CLI commands that map to your development lifecycle. Use them at
42
42
  3. **Before Push:** Run \`totem lint\` — the deterministic enforcement floor (zero LLM, ~2s). **Before PR:** \`totem review\` runs supplementary AI lanes over the diff (~18s) — 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.
43
43
  4. **End of Session:** Run \`totem handoff\` to generate a snapshot for the next agent session with current progress and open threads.
44
44
  5. **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 — no manual re-install needed.
45
+ 6. **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).
45
46
 
46
47
  ### Cloud / PR Review Bots
47
48
  [FOR CLOUD BOTS ONLY — e.g., Gemini Code Assist, GitHub Copilot PR Review]
@@ -1195,8 +1196,14 @@ try {
1195
1196
  describeText = (result.stdout || '') + (result.stderr || '');
1196
1197
  process.stdout.write(describeText);
1197
1198
  } else {
1199
+ // The notice is printed in exactly the state where a Bash|PowerShell-matched
1200
+ // gate self-blocks (no repo-local CLI), so it names the property and the exit
1201
+ // (mmnto-ai/totem#2822 ask 3): the wrapper's PATH arm usually carries a fresh
1202
+ // clone, and when it cannot, the bootstrap belongs in a real terminal.
1198
1203
  process.stdout.write(
1199
- '[Totem] @mmnto/cli not installed. Run \`pnpm install\` (or your package manager equivalent) to enable session-start orientation.\\n',
1204
+ '[Totem] @mmnto/cli not installed. Run \`pnpm install\` (or your package manager equivalent) to enable session-start orientation. ' +
1205
+ 'If a Bash|PowerShell-matched gate is installed here it applies to the bootstrap commands and falls back to a totem on PATH; ' +
1206
+ 'with no totem anywhere, bootstrap this clone from a terminal outside the harness.\\n',
1200
1207
  );
1201
1208
  }
1202
1209
  } catch (err) {
@@ -1340,9 +1347,12 @@ export const CLAUDE_SESSION_START_ENTRY = {
1340
1347
  // subsystem IS present does the wrapper shell out; only then can a broken
1341
1348
  // deterministic source (corrupt freeze.json) fail-close (exit 2).
1342
1349
  //
1343
- // Tier (--strict default / --pilot) is read by the WRAPPER, not the engine
1344
- // (the engine stays pure per ADR-109 [LOCKED]; freeze-check never emits
1345
- // `warn`). The tier is BAKED into the installed command string at install
1350
+ // Tier (--strict default / --pilot) is read by the WRAPPER and, since
1351
+ // mmnto-ai/totem#2800 (R1), also FORWARDED to `gate check --tier` so a gate can
1352
+ // apply it to its OWN unevaluable class (merge-ready warns under pilot where a
1353
+ // read failed to derive; freeze-check ignores it and fails closed at every
1354
+ // tier). The engine stays pure — the tier is an input, not state. The tier is
1355
+ // BAKED into the installed command string at install
1346
1356
  // time and read ONLY from argv — there is NO env-var override, so a default
1347
1357
  // (`--strict`) install is enforcement-immune to a consumer's environment
1348
1358
  // (env-var sourcing would be a fail-open: a `TOTEM_GATE_TIER=pilot` in any
@@ -1363,17 +1373,81 @@ export const CLAUDE_GATE_WRAPPER = `// [totem] auto-generated — Claude Code ac
1363
1373
  // 0 = allow | warn | --pilot deny | NOT-APPLICABLE fail-soft
1364
1374
  // (unparseable/non-object envelope; freeze-check with no declared
1365
1375
  // subsystem; transport-shield on a tool other than Bash/PowerShell or
1366
- // with no non-empty string command)
1376
+ // with no non-empty string command; merge-ready on any command that is
1377
+ // not \`gh pr merge\` at command position)
1367
1378
  // 2 = deny (--strict, Claude block convention)
1368
- // | APPLICABLE-gate-not-evaluable fail-closed (missing CLI, non-zero
1369
- // \`gate check\`, unparseable verdict, or unknown disposition)
1379
+ // | APPLICABLE-gate-not-evaluable fail-closed (no CLI resolvable
1380
+ // (repo-local, then PATH), non-zero \`gate check\`, unparseable verdict,
1381
+ // or unknown disposition)
1370
1382
  // | an --event this wrapper has no payload projection for (a baked event
1371
1383
  // it cannot project is an applicable gate it cannot evaluate)
1372
1384
  'use strict';
1373
1385
 
1374
1386
  const { spawnSync } = require('child_process');
1375
- const { existsSync } = require('fs');
1376
- const { join } = require('path');
1387
+ const { existsSync, realpathSync } = require('fs');
1388
+ const { basename, delimiter, dirname, join } = require('path');
1389
+
1390
+ // ─── PATH FALLBACK for the Totem CLI (mmnto-ai/totem#2822) ──────────────
1391
+ // A \`Bash|PowerShell\`-matched gate applies to the very commands that CREATE
1392
+ // the repo-local CLI on a fresh clone (\`pnpm install\`, then \`pnpm build\` in
1393
+ // this monorepo), so with a repo-local-only resolution the gate blocks its own
1394
+ // bootstrap — and blocks the cure it prints. This is a RESOLUTION arm, not an
1395
+ // exemption: an applicable gate that cannot be evaluated by EITHER arm still
1396
+ // fails closed (mmnto-ai/totem#2799 ruling, Tenet 4).
1397
+ //
1398
+ // A session started in a fresh worktree has no node_modules at its cwd and
1399
+ // takes this arm; with no global CLI it fails closed — the ruling, not a bug.
1400
+ //
1401
+ // The repo-local pinned dist stays FIRST — the pinned-beats-ambient ordering of
1402
+ // ADR-072 § 2; tiers 1, 3 and 5 are out of scope for a hook that must not shell
1403
+ // out. This runs only when the pinned dist is absent. Two npm-global layouts
1404
+ // are probed per PATH dir, first hit wins:
1405
+ // (a) <dir>/node_modules/@mmnto/cli/dist/index.js — the win32 layout, where
1406
+ // the \`totem.cmd\` shim sits beside \`node_modules\`;
1407
+ // (b) <dir>/totem realpath'd — the POSIX npm-global symlink, taken only when
1408
+ // it resolves to an existing \`.js\` file (a shell shim resolves to an
1409
+ // extensionless script and is correctly skipped).
1410
+ // A dir that yields neither is skipped; nothing here throws.
1411
+ //
1412
+ // PATH is trusted here at exactly the level \`node\` itself already is: the
1413
+ // settings.json entry invokes this hook as a bare \`node\`, so whoever controls
1414
+ // PATH controls the interpreter before this line ever runs.
1415
+ //
1416
+ // Returns { entry, display }: \`entry\` is the absolute path to spawn, \`display\`
1417
+ // a NON-resolvable rendering (basenames only) for the stderr provenance line —
1418
+ // hook stderr lands in transcripts that get pasted into issues, so it never
1419
+ // carries a user-profile path.
1420
+ function resolveCliFromPath() {
1421
+ const raw = typeof process.env.PATH === 'string' ? process.env.PATH : '';
1422
+ const dirs = raw.split(delimiter);
1423
+ for (let i = 0; i < dirs.length; i++) {
1424
+ const dir = dirs[i];
1425
+ if (!dir) continue;
1426
+ const packaged = join(dir, 'node_modules', '@mmnto', 'cli', 'dist', 'index.js');
1427
+ if (existsSync(packaged)) {
1428
+ return {
1429
+ entry: packaged,
1430
+ display: basename(dir) + '/node_modules/@mmnto/cli/dist/index.js',
1431
+ };
1432
+ }
1433
+ const shim = join(dir, 'totem');
1434
+ if (existsSync(shim)) {
1435
+ try {
1436
+ const real = realpathSync(shim);
1437
+ if (typeof real === 'string' && real.endsWith('.js') && existsSync(real)) {
1438
+ return {
1439
+ entry: real,
1440
+ display:
1441
+ basename(dir) + '/totem -> ' + basename(dirname(real)) + '/' + basename(real),
1442
+ };
1443
+ }
1444
+ } catch (err) {
1445
+ // An unreadable link is not a resolution — keep scanning the PATH.
1446
+ }
1447
+ }
1448
+ }
1449
+ return null;
1450
+ }
1377
1451
 
1378
1452
  // ─── Parse baked args (--event <name>, optional --pilot / --strict) ─────
1379
1453
  // The tier is read ONLY from argv (baked into the installed command at
@@ -1395,6 +1469,528 @@ for (let i = 0; i < argv.length; i++) {
1395
1469
  }
1396
1470
  }
1397
1471
 
1472
+ // ─── merge-ready: \`gh pr merge\` at COMMAND POSITION + its payload ──────
1473
+ //
1474
+ // One walk over the command text does BOTH jobs, so recognition and argv
1475
+ // extraction can never disagree: it tracks quoting, splits on the unquoted
1476
+ // command separators (\`;\`, \`&\`, \`|\`, a newline, \`(\`/\`)\`, \`{\`/\`}\`) and
1477
+ // tokenizes each segment. A segment whose FIRST token is \`gh\`, followed by
1478
+ // \`pr\` and \`merge\`, is a merge at command position; a quoted
1479
+ // "gh pr merge" is a single token and never matches, so
1480
+ // \`echo "gh pr merge"\` does not fire. The shell's own COMMAND-POSITION words
1481
+ // are skipped before the anchor is read — the reserved words \`do\`, \`then\`,
1482
+ // \`else\`, \`if\`, \`elif\`, \`while\`, \`until\` and \`!\`, the builtins \`exec\` and
1483
+ // \`command\` (which run their operand as the command), and any run of
1484
+ // \`NAME=value\` assignment prefixes — so \`for … ; do gh pr merge; done\`,
1485
+ // \`if gh pr merge 5; then …\` and \`GH_TOKEN=x gh pr merge 5\` all fire. Before
1486
+ // the PR's review round only \`do\`/\`then\`/\`else\`/\`!\` were skipped, so a merge
1487
+ // used AS an \`if\` condition, or behind an assignment prefix, went unjudged
1488
+ // (mmnto-ai/totem#2844 round 1, greptile). EVERY matching segment is
1489
+ // collected, not the first: \`gh pr merge 7; gh pr merge 8\` yields two argv
1490
+ // lists and the wrapper judges each PR on its own facts (same round).
1491
+ //
1492
+ // HEREDOC BODIES ARE BLANKED FIRST (mmnto-ai/totem#2800 fold F4). A heredoc
1493
+ // body is DATA, not commands: \`cat <<EOF\` … \`gh pr merge 5\` … \`EOF\` writes a
1494
+ // line of text and merges nothing, and firing there was a false deny — the one
1495
+ // direction this projection must not have. The blanker is the shape core's
1496
+ // transport-shield scanner uses, in a self-contained form because a distributed
1497
+ // hook cannot import core: quoted (\`<<'EOF'\`, \`<<"EOF"\`, \`<<\\EOF\`) and bare
1498
+ // delimiters, \`<<\` and \`<<-\` (whose terminator may be tab-indented), an
1499
+ // unterminated body read to the end of the command, and \`<<<\` left alone (a
1500
+ // here-string is not a heredoc). Round 2 added the two guards that keep the
1501
+ // blanker from EATING commands: \`$(( … ))\` / \`(( … ))\` is skipped whole, so a
1502
+ // shift (\`$((1<<2))\`) opens nothing, and a \`#\` that begins a word is a comment
1503
+ // discarded to end-of-line, so neither its text nor a \`<<note\` inside it is
1504
+ // read — before them, either one swallowed the rest of the command and a real
1505
+ // merge after it went unjudged. Every \`<<\` on the operator line is queued and
1506
+ // its body consumed in order, as bash does for \`cat <<A <<B\`.
1507
+ //
1508
+ // Disclosed misses, same posture as transport-shield's scanner — the gate does
1509
+ // NOT fire, which is the safe direction, never a false deny:
1510
+ // - a wrapper PROGRAM that takes operands before \`gh\` (\`sudo\`, \`timeout 30\`,
1511
+ // \`npx\`, \`env\`, \`nohup\`): the program is the segment's first token, so the
1512
+ // position anchor does not see \`gh\` (the shell's reserved words and the
1513
+ // \`exec\`/\`command\`/\`eval\` builtins are skipped; an arbitrary program is
1514
+ // not, since the walk cannot know which of its operands is the command);
1515
+ // - a skipped word carrying a FLAG (\`command -p gh pr merge 5\`,
1516
+ // \`exec -a x gh pr merge 5\`, and the reserved word's own \`time -p\` /
1517
+ // \`time --\`): the flag is a token before \`gh\`, and bash runs the merge
1518
+ // all the same (round 3, F1);
1519
+ // - a merge handed over as ONE quoted word (\`eval "gh pr merge 5"\`,
1520
+ // \`bash -c "gh pr merge 5"\`): a quoted string is data to this walk;
1521
+ // - a backtick command substitution (\`echo \\\`gh pr merge 5\\\`\`): the walk
1522
+ // splits on \`$( … )\` parens but treats a backtick as an ordinary character,
1523
+ // so the merge inside it stays part of \`echo\`'s segment;
1524
+ // - a leading redirection (\`> out.txt gh pr merge 5\`): the redirection word
1525
+ // is the segment's first token;
1526
+ // - PowerShell's own quoting (backtick escapes, here-strings) is not
1527
+ // modelled — the walk reads POSIX quoting for both tools.
1528
+ // Disclosed FALSE FIRES, the deny direction, all contrived — text the shell
1529
+ // does not execute as a merge but that sits at a segment's front here: a bash
1530
+ // array assignment whose elements spell a merge (\`A=(gh pr merge 8)\`) is judged
1531
+ // as a merge of 8, because \`(\` is a separator and the segment inside it starts
1532
+ // with \`gh\`; a \`case\` pattern \`gh pr merge)\` yields an EMPTY argv, which
1533
+ // projects to the current branch's PR (both surfaced when every segment began
1534
+ // to be collected, round 2 F6); and a function DEFINITION whose body is a
1535
+ // merge (\`f() { gh pr merge 5; }\`) fires at definition time, because \`{\` is a
1536
+ // separator and the body is its own segment (round 3, F4; it fired before this
1537
+ // PR's rounds too). \`TOTEM_MERGE_GATE_OVERRIDE=1\` is the audited way past any
1538
+ // of them.
1539
+ // Which characters END a word, so the scanner can say whether the next one
1540
+ // BEGINS one. Same set core's scanner uses (mmnto-ai/totem#2800 round 2, F1).
1541
+ function isWordBoundary(ch) {
1542
+ return (
1543
+ ch === ' ' ||
1544
+ ch === '\\t' ||
1545
+ ch === '\\r' ||
1546
+ ch === '\\n' ||
1547
+ ch === ';' ||
1548
+ ch === '|' ||
1549
+ ch === '&'
1550
+ );
1551
+ }
1552
+
1553
+ // The index just past the \`))\` that closes an arithmetic expansion whose
1554
+ // opening \`$((\` / \`((\` ends at \`from\`; the end of the command when it is
1555
+ // unterminated. A \`<<\` inside is a SHIFT, never a heredoc operator — without
1556
+ // this guard \`echo $((1<<2))\` opened a heredoc and swallowed every command
1557
+ // after it, so a real \`gh pr merge\` went unjudged (F1).
1558
+ function skipArithmetic(command, from) {
1559
+ let depth = 2;
1560
+ let i = from;
1561
+ while (i < command.length) {
1562
+ const ch = command[i];
1563
+ if (ch === '(') depth += 1;
1564
+ else if (ch === ')') {
1565
+ depth -= 1;
1566
+ if (depth === 0) return i + 1;
1567
+ }
1568
+ i += 1;
1569
+ }
1570
+ return command.length;
1571
+ }
1572
+
1573
+ function blankHeredocBodies(command, powershell) {
1574
+ let out = '';
1575
+ let i = 0;
1576
+ let quote = '';
1577
+ let boundary = true;
1578
+ let pending = [];
1579
+
1580
+ // Consume EVERY body queued on the operator line, in order, starting just
1581
+ // past that line's newline — bash reads \`cat <<A <<B\` as two bodies, so a
1582
+ // command sitting in B's body is data too (F2). Terminator lines are kept;
1583
+ // body lines are dropped with their newlines, so the segments around them
1584
+ // stay separated exactly as the shell separates them. An unterminated body
1585
+ // runs to the end and is dropped whole.
1586
+ const consumeBodies = (from) => {
1587
+ let cursor = from;
1588
+ for (let p = 0; p < pending.length; p++) {
1589
+ const h = pending[p];
1590
+ let at = cursor;
1591
+ cursor = command.length;
1592
+ while (at <= command.length) {
1593
+ const nl = command.indexOf('\\n', at);
1594
+ const stop = nl === -1 ? command.length : nl;
1595
+ let line = command.slice(at, stop);
1596
+ if (h.stripTabs) line = line.replace(/^\\t+/, '');
1597
+ line = line.replace(/\\r$/, '');
1598
+ const next = nl === -1 ? command.length : nl + 1;
1599
+ if (line === h.delimiter) {
1600
+ out += command.slice(at, next);
1601
+ cursor = next;
1602
+ break;
1603
+ }
1604
+ if (nl === -1) break;
1605
+ out += '\\n';
1606
+ at = next;
1607
+ }
1608
+ }
1609
+ pending = [];
1610
+ return cursor;
1611
+ };
1612
+
1613
+ while (i < command.length) {
1614
+ const ch = command[i];
1615
+ if (quote !== '') {
1616
+ out += ch;
1617
+ if (ch === '\\\\' && quote === '"' && i + 1 < command.length) {
1618
+ out += command[i + 1];
1619
+ i += 2;
1620
+ continue;
1621
+ }
1622
+ if (ch === quote) quote = '';
1623
+ i++;
1624
+ boundary = false;
1625
+ continue;
1626
+ }
1627
+ if (ch === "'" || ch === '"') {
1628
+ quote = ch;
1629
+ out += ch;
1630
+ i++;
1631
+ boundary = false;
1632
+ continue;
1633
+ }
1634
+ // A backslash before a NEWLINE is a line continuation: the shell removes
1635
+ // both characters and the command carries on, so the scanner must too
1636
+ // (mmnto-ai/totem#2800 round 3, F6). Absorbing the newline into a token is
1637
+ // what hid \`gh \\<LF>pr merge 5\` from the position anchor.
1638
+ if (ch === '\\\\' && (command[i + 1] === '\\n' || (command[i + 1] === '\\r' && command[i + 2] === '\\n'))) {
1639
+ i += command[i + 1] === '\\r' ? 3 : 2;
1640
+ continue;
1641
+ }
1642
+ if (ch === '\\\\' && i + 1 < command.length) {
1643
+ out += ch + command[i + 1];
1644
+ i += 2;
1645
+ boundary = false;
1646
+ continue;
1647
+ }
1648
+ // A \`#\` that BEGINS a word is a comment: discarded to the end of the line
1649
+ // WITHOUT quote processing, so neither its text nor a \`<<note\` inside it
1650
+ // reaches the tokenizer (F1). The newline stays — it may end an operator
1651
+ // line whose bodies are still queued.
1652
+ if (ch === '#' && boundary) {
1653
+ const nl = command.indexOf('\\n', i);
1654
+ i = nl === -1 ? command.length : nl;
1655
+ continue;
1656
+ }
1657
+ // PowerShell's \`<# … #>\` block comment is data, not commands: blank it
1658
+ // whole, the way a heredoc body is blanked (round 3, F8). Applied ONLY when
1659
+ // the TOOL is PowerShell (round 4, F8): bash has no such comment, and there
1660
+ // \`sort <#tmp\` is a redirect from a file named \`#tmp\` — blanking from it
1661
+ // to a later \`#>\` would swallow real commands. A \`<#\` inside a quoted
1662
+ // string never reaches here, because the quote arms run first.
1663
+ if (powershell && ch === '<' && command[i + 1] === '#') {
1664
+ const close = command.indexOf('#>', i + 2);
1665
+ i = close === -1 ? command.length : close + 2;
1666
+ boundary = true;
1667
+ continue;
1668
+ }
1669
+ if (ch === '$' && command.slice(i, i + 3) === '$((') {
1670
+ const end = skipArithmetic(command, i + 3);
1671
+ out += command.slice(i, end);
1672
+ i = end;
1673
+ boundary = false;
1674
+ continue;
1675
+ }
1676
+ if (ch === '(' && command[i + 1] === '(' && boundary) {
1677
+ const end = skipArithmetic(command, i + 2);
1678
+ out += command.slice(i, end);
1679
+ i = end;
1680
+ boundary = false;
1681
+ continue;
1682
+ }
1683
+ // \`<<\` opens a heredoc; \`<<<\` is a here-string and is left alone.
1684
+ if (ch === '<' && command[i + 1] === '<' && command[i + 2] !== '<') {
1685
+ let j = i + 2;
1686
+ let head = '<<';
1687
+ let dash = false;
1688
+ if (command[j] === '-') {
1689
+ dash = true;
1690
+ head += '-';
1691
+ j++;
1692
+ }
1693
+ while (j < command.length && (command[j] === ' ' || command[j] === '\\t')) {
1694
+ head += command[j];
1695
+ j++;
1696
+ }
1697
+ // The delimiter word, quoted (\`<<'EOF'\`, \`<<"EOF"\`) or bare, with a
1698
+ // backslash-quoted form (\`<<\\EOF\`) read as bash reads it.
1699
+ let delim = '';
1700
+ const q = command[j] === "'" || command[j] === '"' ? command[j] : '';
1701
+ if (q !== '') {
1702
+ head += q;
1703
+ j++;
1704
+ }
1705
+ while (j < command.length) {
1706
+ const c = command[j];
1707
+ if (q !== '') {
1708
+ head += c;
1709
+ j++;
1710
+ if (c === q) break;
1711
+ delim += c;
1712
+ continue;
1713
+ }
1714
+ if (c === '\\\\' && j + 1 < command.length) {
1715
+ head += c + command[j + 1];
1716
+ delim += command[j + 1];
1717
+ j += 2;
1718
+ continue;
1719
+ }
1720
+ if (/[A-Za-z0-9_.\\-\\/]/.test(c)) {
1721
+ head += c;
1722
+ delim += c;
1723
+ j++;
1724
+ continue;
1725
+ }
1726
+ break;
1727
+ }
1728
+ out += head;
1729
+ i = j;
1730
+ boundary = false;
1731
+ if (delim !== '') pending.push({ delimiter: delim, stripTabs: dash });
1732
+ continue;
1733
+ }
1734
+ if (ch === '\\n') {
1735
+ out += '\\n';
1736
+ i += 1;
1737
+ if (pending.length > 0) i = consumeBodies(i);
1738
+ boundary = true;
1739
+ continue;
1740
+ }
1741
+ out += ch;
1742
+ boundary = isWordBoundary(ch);
1743
+ i++;
1744
+ }
1745
+ return out;
1746
+ }
1747
+
1748
+ // The words the shell reads at command position that are NOT the command:
1749
+ // reserved words that introduce a compound command (\`time\` and \`coproc\` are
1750
+ // reserved words too — the round-2 leg found them missing), the negation, and
1751
+ // the builtins that execute their operand as the command (\`exec\`, \`command\`,
1752
+ // and \`eval\` on an UNQUOTED operand — \`eval "gh pr merge 5"\` hands the shell a
1753
+ // single quoted word, which this walk reads as data, a disclosed miss below).
1754
+ // Stripped from a segment's front, in any run, before the \`gh pr merge\`
1755
+ // anchor is read.
1756
+ const COMMAND_POSITION_WORDS = [
1757
+ 'do',
1758
+ 'then',
1759
+ 'else',
1760
+ 'if',
1761
+ 'elif',
1762
+ 'while',
1763
+ 'until',
1764
+ 'time',
1765
+ 'coproc',
1766
+ '!',
1767
+ 'exec',
1768
+ 'command',
1769
+ 'eval',
1770
+ ];
1771
+
1772
+ // A \`NAME=value\` word at a segment's front is an assignment PREFIX to the
1773
+ // command that follows it (\`GH_TOKEN=x gh pr merge 5\`), never the command.
1774
+ function isAssignmentPrefix(token) {
1775
+ return /^[A-Za-z_][A-Za-z0-9_]*=/.test(token);
1776
+ }
1777
+
1778
+ /**
1779
+ * The argv after EVERY \`gh pr merge\` at command position in the command —
1780
+ * one array per merge, in command order — or an empty array when there is
1781
+ * none. A compound command that merges twice yields two, and the wrapper
1782
+ * judges each (mmnto-ai/totem#2844 round 1).
1783
+ */
1784
+ function ghPrMergeArgvs(rawCommand, powershell) {
1785
+ const command = blankHeredocBodies(rawCommand, powershell === true);
1786
+ const segments = [];
1787
+ let current = [];
1788
+ let token = '';
1789
+ let hasToken = false;
1790
+ let i = 0;
1791
+ const endToken = () => {
1792
+ if (hasToken) {
1793
+ current.push(token);
1794
+ token = '';
1795
+ hasToken = false;
1796
+ }
1797
+ };
1798
+ const endSegment = () => {
1799
+ endToken();
1800
+ segments.push(current);
1801
+ current = [];
1802
+ };
1803
+ while (i < command.length) {
1804
+ const ch = command[i];
1805
+ if (ch === "'") {
1806
+ hasToken = true;
1807
+ i++;
1808
+ while (i < command.length && command[i] !== "'") {
1809
+ token += command[i];
1810
+ i++;
1811
+ }
1812
+ i++;
1813
+ continue;
1814
+ }
1815
+ if (ch === '"') {
1816
+ hasToken = true;
1817
+ i++;
1818
+ while (i < command.length && command[i] !== '"') {
1819
+ if (command[i] === '\\\\' && i + 1 < command.length) {
1820
+ token += command[i + 1];
1821
+ i += 2;
1822
+ continue;
1823
+ }
1824
+ token += command[i];
1825
+ i++;
1826
+ }
1827
+ i++;
1828
+ continue;
1829
+ }
1830
+ // A parameter expansion is ONE word: without this, \`\${PR}\` splits on its
1831
+ // braces and the unresolved-target evidence line reads just "$"
1832
+ // (mmnto-ai/totem#2800 round 2, F10). A \`$( … )\` is deliberately NOT
1833
+ // swallowed the same way — a real \`gh pr merge\` inside a command
1834
+ // substitution has to keep firing, so its parens stay separators.
1835
+ if (ch === '$' && command[i + 1] === '{') {
1836
+ const close = command.indexOf('}', i + 2);
1837
+ const end = close === -1 ? command.length : close + 1;
1838
+ token += command.slice(i, end);
1839
+ hasToken = true;
1840
+ i = end;
1841
+ continue;
1842
+ }
1843
+ if (ch === ' ' || ch === '\\t' || ch === '\\r') {
1844
+ endToken();
1845
+ i++;
1846
+ continue;
1847
+ }
1848
+ if (
1849
+ ch === ';' ||
1850
+ ch === '&' ||
1851
+ ch === '|' ||
1852
+ ch === '\\n' ||
1853
+ ch === '(' ||
1854
+ ch === ')' ||
1855
+ ch === '{' ||
1856
+ ch === '}'
1857
+ ) {
1858
+ endSegment();
1859
+ i++;
1860
+ continue;
1861
+ }
1862
+ // A line continuation joins the two halves of ONE word (\`gh \\<LF>pr\` is
1863
+ // \`ghpr\` to the shell, and \`gh \\<LF>pr merge\` keeps \`gh\` at the front of
1864
+ // the segment): drop both characters and keep tokenizing (round 3, F6).
1865
+ if (ch === '\\\\' && (command[i + 1] === '\\n' || (command[i + 1] === '\\r' && command[i + 2] === '\\n'))) {
1866
+ i += command[i + 1] === '\\r' ? 3 : 2;
1867
+ continue;
1868
+ }
1869
+ if (ch === '\\\\' && i + 1 < command.length) {
1870
+ token += command[i + 1];
1871
+ hasToken = true;
1872
+ i += 2;
1873
+ continue;
1874
+ }
1875
+ token += ch;
1876
+ hasToken = true;
1877
+ i++;
1878
+ }
1879
+ endSegment();
1880
+
1881
+ const found = [];
1882
+ for (const segment of segments) {
1883
+ let tokens = segment;
1884
+ while (
1885
+ tokens.length > 0 &&
1886
+ (COMMAND_POSITION_WORDS.indexOf(tokens[0]) !== -1 || isAssignmentPrefix(tokens[0]))
1887
+ ) {
1888
+ tokens = tokens.slice(1);
1889
+ }
1890
+ if (tokens.length >= 3 && tokens[0] === 'gh' && tokens[1] === 'pr' && tokens[2] === 'merge') {
1891
+ found.push(tokens.slice(3));
1892
+ }
1893
+ }
1894
+ return found;
1895
+ }
1896
+
1897
+ /** Run git read-only and return trimmed stdout, or '' when it did not answer. */
1898
+ function gitRead(args) {
1899
+ const res = spawnSync('git', args, { encoding: 'utf-8', timeout: 10000 });
1900
+ if (res.error || typeof res.status !== 'number' || res.status !== 0) return '';
1901
+ return (res.stdout || '').trim();
1902
+ }
1903
+
1904
+ /** \`owner/name\` out of any git remote URL shape (ssh, https, with or without .git). */
1905
+ function repoFromRemote(url) {
1906
+ const m = /[:/]([^/:]+)\\/([^/]+?)(?:\\.git)?$/.exec(url.trim());
1907
+ return m ? m[1] + '/' + m[2] : '';
1908
+ }
1909
+
1910
+ // The flags of \`gh pr merge\` that CONSUME the next argv element — without this
1911
+ // list, \`gh pr merge -b "some branch"\` would read the body as the PR target.
1912
+ const GH_MERGE_VALUE_FLAGS = [
1913
+ '-R',
1914
+ '--repo',
1915
+ '-b',
1916
+ '--body',
1917
+ '-F',
1918
+ '--body-file',
1919
+ '-t',
1920
+ '--subject',
1921
+ '--match-head-commit',
1922
+ '--author-email',
1923
+ ];
1924
+
1925
+ /**
1926
+ * Project { repo, pr, branch?, headSha? } from the argv after \`gh pr merge\`:
1927
+ * a number, a PR URL, a branch, \`-R/--repo\`. With no argument at all, gh
1928
+ * merges the PR for the CURRENT branch — so the payload carries pr: null plus
1929
+ * that branch, exactly as the gate's payload contract allows.
1930
+ */
1931
+ function projectMergeReady(argv) {
1932
+ let repo = '';
1933
+ let pr = null;
1934
+ let branch = '';
1935
+ let positional = null;
1936
+
1937
+ for (let i = 0; i < argv.length; i++) {
1938
+ const arg = argv[i];
1939
+ const eq = arg.indexOf('=');
1940
+ if (arg.slice(0, 2) === '--' && eq > 2) {
1941
+ if (arg.slice(0, eq) === '--repo') repo = arg.slice(eq + 1);
1942
+ continue;
1943
+ }
1944
+ if (GH_MERGE_VALUE_FLAGS.indexOf(arg) !== -1) {
1945
+ if (arg === '-R' || arg === '--repo') repo = argv[i + 1] || '';
1946
+ i++;
1947
+ continue;
1948
+ }
1949
+ if (arg.charAt(0) === '-') continue;
1950
+ if (positional === null) positional = arg;
1951
+ }
1952
+
1953
+ // An UNEXPANDED shell variable (\`gh pr merge $PR\`) is not a target this
1954
+ // projection can know (mmnto-ai/totem#2800 fold F13): the shell expands it
1955
+ // after the hook has already decided. Reading it as a branch name would judge
1956
+ // the wrong PR — or none — so it rides as \`unresolvedTarget\`, which the
1957
+ // engine treats as unevaluable (strict denies, pilot warns).
1958
+ let unresolvedTarget = '';
1959
+ if (positional !== null && /[$\`]/.test(positional)) {
1960
+ unresolvedTarget = positional;
1961
+ positional = null;
1962
+ }
1963
+
1964
+ if (positional !== null) {
1965
+ const url = /^https?:\\/\\/[^/]+\\/([^/]+)\\/([^/]+)\\/pull\\/(\\d+)/.exec(positional);
1966
+ if (url) {
1967
+ if (repo === '') repo = url[1] + '/' + url[2];
1968
+ pr = parseInt(url[3], 10);
1969
+ } else if (/^\\d+$/.test(positional)) {
1970
+ pr = parseInt(positional, 10);
1971
+ } else {
1972
+ branch = positional;
1973
+ }
1974
+ }
1975
+
1976
+ // gh itself honours GH_REPO before the git remote; mirror that order so the
1977
+ // gate reads the SAME pull request the command would merge.
1978
+ if (repo === '') repo = (process.env.GH_REPO || '').trim();
1979
+ if (repo === '') repo = repoFromRemote(gitRead(['config', '--get', 'remote.origin.url']));
1980
+ // The current-branch fallback is for a command that named NO target. An
1981
+ // unresolved one named a target we could not read, so it must not fall back.
1982
+ if (pr === null && branch === '' && unresolvedTarget === '') {
1983
+ branch = gitRead(['rev-parse', '--abbrev-ref', 'HEAD']);
1984
+ }
1985
+
1986
+ const headSha = gitRead(['rev-parse', 'HEAD']);
1987
+ const out = { repo: repo, pr: pr };
1988
+ if (branch !== '') out.branch = branch;
1989
+ if (unresolvedTarget !== '') out.unresolvedTarget = unresolvedTarget;
1990
+ if (/^[0-9a-f]{40}$/i.test(headSha)) out.headSha = headSha;
1991
+ return out;
1992
+ }
1993
+
1398
1994
  // Read the PreToolUse stdin envelope.
1399
1995
  let stdin = '';
1400
1996
  process.stdin.setEncoding('utf-8');
@@ -1437,8 +2033,15 @@ process.stdin.on('end', () => {
1437
2033
  // transport-shield | tool_name is Bash or PowerShell | { tool, command, platform }
1438
2034
  // | AND tool_input.command is a |
1439
2035
  // | non-empty string |
2036
+ // merge-ready | tool_name is Bash or PowerShell | { repo, pr, branch?, headSha? }
2037
+ // | AND the command runs \`gh pr merge\`|
2038
+ // | at COMMAND POSITION |
1440
2039
  // (anything else) | — no projection → fail closed | —
1441
- let payload = '';
2040
+ //
2041
+ // A projection yields ONE payload per gate evaluation — and merge-ready can
2042
+ // yield several for one envelope (one per \`gh pr merge\` at command
2043
+ // position), each judged on its own below.
2044
+ let payloads = [];
1442
2045
 
1443
2046
  if (event === 'freeze-check') {
1444
2047
  // THE EMPTY-SUBSYSTEM GUARDRAIL: freeze-check's predicate is on a DECLARED
@@ -1453,7 +2056,7 @@ process.stdin.on('end', () => {
1453
2056
  if (declaredSubsystem === '') {
1454
2057
  process.exit(0);
1455
2058
  }
1456
- payload = JSON.stringify({ subsystem: declaredSubsystem });
2059
+ payloads = [JSON.stringify({ subsystem: declaredSubsystem })];
1457
2060
  } else if (event === 'transport-shield') {
1458
2061
  // transport-shield's predicate is on a SHELL COMMAND. Anything that is not
1459
2062
  // a Bash/PowerShell invocation carrying a command string is NOT an
@@ -1467,11 +2070,34 @@ process.stdin.on('end', () => {
1467
2070
  if (typeof input.command !== 'string' || input.command.trim() === '') {
1468
2071
  process.exit(0);
1469
2072
  }
1470
- payload = JSON.stringify({
1471
- tool: tool,
1472
- command: input.command,
1473
- platform: process.platform,
1474
- });
2073
+ payloads = [
2074
+ JSON.stringify({
2075
+ tool: tool,
2076
+ command: input.command,
2077
+ platform: process.platform,
2078
+ }),
2079
+ ];
2080
+ } else if (event === 'merge-ready') {
2081
+ // merge-ready's predicate is on a PULL REQUEST about to be merged. The gate
2082
+ // installs under Bash|PowerShell, so this branch sees every shell command:
2083
+ // anything that is not \`gh pr merge\` at COMMAND POSITION is NOT an
2084
+ // applicable gate → pass through (exit 0) WITHOUT spawning.
2085
+ const tool = parsed.tool_name;
2086
+ if (tool !== 'Bash' && tool !== 'PowerShell') {
2087
+ process.exit(0);
2088
+ }
2089
+ if (typeof input.command !== 'string' || input.command.trim() === '') {
2090
+ process.exit(0);
2091
+ }
2092
+ const merges = ghPrMergeArgvs(input.command, tool === 'PowerShell');
2093
+ if (merges.length === 0) {
2094
+ process.exit(0);
2095
+ }
2096
+ // One payload per merge: \`gh pr merge 7; gh pr merge 8\` is judged twice,
2097
+ // each PR against its own facts (mmnto-ai/totem#2844 round 1).
2098
+ for (let m = 0; m < merges.length; m++) {
2099
+ payloads.push(JSON.stringify(projectMergeReady(merges[m])));
2100
+ }
1475
2101
  } else {
1476
2102
  // A baked --event this wrapper cannot project is an APPLICABLE gate it
1477
2103
  // cannot evaluate → fail closed (ADR-109). Reinstalling refreshes the
@@ -1482,27 +2108,68 @@ process.stdin.on('end', () => {
1482
2108
  process.exit(2);
1483
2109
  }
1484
2110
 
1485
- // Resolve the LOCAL Totem CLI (the global \`totem\` binary may be stale and
1486
- // missing deps the known repo gotcha). Invoke node on the installed dist
1487
- // entry.
2111
+ // No payload past the projection is not an applicable gate that passed it
2112
+ // is a branch above that forgot to project, and before the loop that shape
2113
+ // fail-closed through the child's non-zero exit. Keep the default closed
2114
+ // (round 2, F7).
2115
+ if (payloads.length === 0) {
2116
+ process.stderr.write(
2117
+ '[totem gate-wrapper] event "' + event + '" projected no payload; failing closed.\\n',
2118
+ );
2119
+ process.exit(2);
2120
+ }
2121
+
2122
+ // Resolve the Totem CLI: the repo-local pinned dist FIRST (a global \`totem\`
2123
+ // may be stale and missing deps — the known repo gotcha; the
2124
+ // pinned-beats-ambient ordering of ADR-072 § 2, Tenet 14), then a \`totem\` on
2125
+ // PATH as a FALLBACK (mmnto-ai/totem#2822 — the bootstrap self-block above).
2126
+ // Invoke node on whichever dist entry resolved.
1488
2127
  //
1489
- // FAIL-CLOSED on a missing CLI: we are PAST the per-event applicability
1490
- // guardrail (freeze-check: a declared subsystem; transport-shield: a Bash or
1491
- // PowerShell command), so a gate genuinely APPLIES here. Neither gate has a
1492
- // commit-time hard floor (unlike PreWriteShield, whose fail-soft is backed by
1493
- // \`totem-lint\` at commit), so an APPLICABLE gate that cannot be evaluated
1494
- // for ANY reason (missing CLI OR a broken source) must fail closed — not
1495
- // silently allow (guardrail rule + Tenet 4 fail-closed). Fail-SOFT (exit 0)
1496
- // is reserved for genuinely NOT-APPLICABLE inputs (unparseable/non-object
1497
- // envelope, no declared subsystem, no shell command), all of which already
1498
- // returned above.
1499
- const cliPath = join(process.cwd(), 'node_modules', '@mmnto', 'cli', 'dist', 'index.js');
1500
- if (!existsSync(cliPath)) {
2128
+ // FAIL-CLOSED when NEITHER arm resolves: we are PAST the per-event
2129
+ // applicability guardrail (freeze-check: a declared subsystem;
2130
+ // transport-shield: a Bash or PowerShell command), so a gate genuinely
2131
+ // APPLIES here. Neither gate has a commit-time hard floor (unlike
2132
+ // PreWriteShield, whose fail-soft is backed by \`totem-lint\` at commit), so an
2133
+ // APPLICABLE gate that cannot be evaluated for ANY reason (no CLI anywhere OR
2134
+ // a broken source) must fail closed not silently allow (guardrail rule +
2135
+ // Tenet 4 fail-closed). Fail-SOFT (exit 0) is reserved for genuinely
2136
+ // NOT-APPLICABLE inputs (unparseable/non-object envelope, no declared
2137
+ // subsystem, no shell command), all of which already returned above.
2138
+ const localCliPath = join(process.cwd(), 'node_modules', '@mmnto', 'cli', 'dist', 'index.js');
2139
+ let cliPath = '';
2140
+ // Which arm resolved — 'repo-local' or 'PATH' — for the provenance line the
2141
+ // fail-closed arms below disclose. Empty until one resolves.
2142
+ let arm = '';
2143
+ // The PATH arm's non-resolvable rendering of what it found (basenames only).
2144
+ let cliDisplay = '';
2145
+ if (existsSync(localCliPath)) {
2146
+ cliPath = localCliPath;
2147
+ arm = 'repo-local';
2148
+ } else {
2149
+ const fromPath = resolveCliFromPath();
2150
+ if (fromPath) {
2151
+ cliPath = fromPath.entry;
2152
+ cliDisplay = fromPath.display;
2153
+ arm = 'PATH';
2154
+ }
2155
+ }
2156
+
2157
+ if (!cliPath) {
2158
+ // The exits named here must be exits the gate does NOT block: "reinstall
2159
+ // totem" and \`totem eject\` are Bash commands a Bash|PowerShell gate blocks
2160
+ // with this very message (mmnto-ai/totem#2822). They are ORDERED: the
2161
+ // editor path still needs the bootstrap before the gate can be reinstalled.
1501
2162
  process.stderr.write(
1502
2163
  '[totem gate] ' +
1503
2164
  event +
1504
- ' applies but the totem CLI is not resolvable; failing closed. ' +
1505
- 'Reinstall totem or run \`totem eject\` to remove the gate.\\n',
2165
+ ' applies but no totem CLI is resolvable ' +
2166
+ '(repo-local node_modules/@mmnto/cli/dist/index.js absent; no totem on PATH); ' +
2167
+ 'failing closed. Exits: bootstrap from a terminal OUTSIDE the harness ' +
2168
+ '(pnpm install and pnpm build, or npm i -g @mmnto/cli); or remove this ' +
2169
+ "gate's entry from .claude/settings.json with the editor, bootstrap, " +
2170
+ 'then re-run totem gate install ' +
2171
+ event +
2172
+ '.\\n',
1506
2173
  );
1507
2174
  process.exit(2);
1508
2175
  }
@@ -1512,66 +2179,153 @@ process.stdin.on('end', () => {
1512
2179
  // 32,767 characters — an argv payload past it fails the spawn with
1513
2180
  // ENAMETOOLONG and would land in the fail-closed arm below with nothing
1514
2181
  // broken (mmnto-ai/totem#2799, pass 3).
1515
- const result = spawnSync(
1516
- process.execPath,
1517
- [cliPath, 'gate', 'check', '--event', event, '--payload', '-'],
1518
- { encoding: 'utf-8', timeout: 30000, input: payload },
1519
- );
1520
-
1521
- // ─── FAIL-CLOSED ──────────────────────────────────────────────────────
1522
- // A gate genuinely applies (the per-event projection above found its input:
1523
- // a declared subsystem, or a Bash/PowerShell command) and the evaluation
1524
- // itself failed (non-zero exit: corrupt freeze.json, an invalid payload,
1525
- // spawn error, etc.). Never silently allow when an applicable gate's source
1526
- // is broken exit 2. (Not-applicable envelopes already returned exit 0
1527
- // above, so this only blocks when the gate's input was actually present.)
1528
- if (result.error || typeof result.status !== 'number' || result.status !== 0) {
1529
- process.stderr.write(
1530
- '[totem gate-wrapper] gate "' +
1531
- event +
1532
- '" evaluation failed (source broken or unavailable) — blocking (fail-closed).\\n' +
1533
- (result.stderr || (result.error ? String(result.error.message || result.error) : '')) +
1534
- '\\n',
1535
- );
1536
- process.exit(2);
2182
+ // The baked tier rides along (mmnto-ai/totem#2800 R1): the ENGINE owns the
2183
+ // strict/pilot split for a gate's UNEVALUABLE class (a read that could not
2184
+ // derive), while the disposition → exit map below stays the wrapper's. A gate
2185
+ // that ignores the tier — freeze-check still fails closed at both.
2186
+ //
2187
+ // \`--tier\` is forwarded ONLY when it is NOT the default (fold F3): a CLI at
2188
+ // or below 2.2.1 has no such option and would exit non-zero with
2189
+ // "unknown option", which is the fail-closed arm and on a
2190
+ // \`Bash|PowerShell\` gate that re-creates the mmnto-ai/totem#2822 bootstrap
2191
+ // self-block through the PATH arm. \`strict\` IS the engine's default, so a
2192
+ // strict wrapper stays runnable against a 2.2.x CLI; a \`--pilot\` install
2193
+ // passes the flag and needs a CLI at 2.3.0 or newer (the install-time
2194
+ // disclosure says so).
2195
+ const checkArgs = [cliPath, 'gate', 'check', '--event', event];
2196
+ if (tier !== 'strict') {
2197
+ checkArgs.push('--tier', tier);
1537
2198
  }
2199
+ checkArgs.push('--payload', '-');
2200
+
2201
+ // Provenance for the PATH fallback arm (mmnto-ai/totem#2822): a CLI older
2202
+ // than 2.2.0 has no \`gate check --payload -\` and lands in the fail-closed
2203
+ // arms below (unknown option → non-zero exit, or nothing on stdout). The
2204
+ // BEHAVIOUR is unchanged — exit 2 either way — the line only names WHICH CLI
2205
+ // evaluated and how to update it. Empty on the repo-local arm. It prints the
2206
+ // basename rendering, never the absolute entry: this is transcript-bound text.
2207
+ // The floor NAMED here is the floor this wrapper actually needs: a strict
2208
+ // wrapper sends no \`--tier\`, so 2.2.0 (the \`--payload -\` cut) still answers
2209
+ // it; a pilot wrapper sends \`--tier pilot\`, which only 2.3.0 and newer parse
2210
+ // (mmnto-ai/totem#2800 fold F3).
2211
+ const armNote =
2212
+ arm === 'PATH'
2213
+ ? 'evaluated by the PATH CLI at ' +
2214
+ cliDisplay +
2215
+ (tier === 'strict'
2216
+ ? "; a CLI older than 2.2.0 lacks 'gate check --payload -' — "
2217
+ : "; a CLI older than 2.3.0 lacks 'gate check --tier' (this entry is baked --pilot) — ") +
2218
+ 'update it: npm i -g @mmnto/cli@latest\\n'
2219
+ : '';
2220
+
2221
+ // ─── One evaluation per projected payload ─────────────────────────────
2222
+ // freeze-check and transport-shield project exactly one. merge-ready projects
2223
+ // one per \`gh pr merge\` at command position, so \`gh pr merge 7; gh pr merge 8\`
2224
+ // is judged TWICE, each PR on its own facts — judging only the first let the
2225
+ // shell run the second unjudged (mmnto-ai/totem#2844 round 1). The first
2226
+ // strict deny, and every fail-closed arm, EXITS at once; a warn, and a deny
2227
+ // under --pilot, print their line and let the NEXT payload be judged, so every
2228
+ // merge in the envelope gets its stderr line; exit 0 only once every payload
2229
+ // has allowed or warned.
2230
+ //
2231
+ // ONE 30-second budget across every payload, not 30 seconds each (round 2,
2232
+ // F5): the hook host kills a PreToolUse hook at its own default budget (60 s
2233
+ // on both Claude Code and Gemini, the same figure the session-hook templates
2234
+ // above cut their legs against) and a killed hook's exit code is never
2235
+ // applied — a fail-OPEN on a gate whose posture is fail-closed. With the
2236
+ // budget shared, the loop's wall time is bounded at 30 s plus the one-second
2237
+ // floor each payload past the budget still gets (round 3, F2), and a merge
2238
+ // that cannot be judged inside it lands in the fail-closed arm below (the
2239
+ // spawn times out → \`result.error\`) rather than in the host's kill. What the
2240
+ // budget does NOT cover, disclosed (round 3, F3): the projection above runs
2241
+ // up to three \`gitRead\`s per merge, each on its own 10 s timeout, before this
2242
+ // deadline exists — a hung git on a multi-merge envelope can still reach the
2243
+ // host's budget through them.
2244
+ const deadline = Date.now() + 30000;
2245
+ for (let p = 0; p < payloads.length; p++) {
2246
+ const result = spawnSync(process.execPath, checkArgs, {
2247
+ encoding: 'utf-8',
2248
+ timeout: Math.max(1000, deadline - Date.now()),
2249
+ input: payloads[p],
2250
+ });
1538
2251
 
1539
- let verdict;
1540
- try {
1541
- verdict = JSON.parse(result.stdout || '');
1542
- } catch (err) {
1543
- // The command emitted unparseable stdout despite a 0 exit an applicable
1544
- // gate whose verdict we cannot read is a broken source → fail-closed.
2252
+ // ─── The child's stderr IS a gate surface (fold F1) ──────────────────
2253
+ // merge-ready's audited-override line, its zero-checks fact and every
2254
+ // "could not derive" line are written by the ENGINE to stderr. Passing them
2255
+ // through verbatim in EVERY arm — allow included — is what puts them in the
2256
+ // transcript; printing them only on failure hid the override's audit trail,
2257
+ // the one line that must never be silent.
2258
+ if (typeof result.stderr === 'string' && result.stderr !== '') {
2259
+ process.stderr.write(result.stderr);
2260
+ }
2261
+
2262
+ // ─── FAIL-CLOSED ────────────────────────────────────────────────────
2263
+ // A gate genuinely applies (the per-event projection above found its input:
2264
+ // a declared subsystem, or a Bash/PowerShell command) and the evaluation
2265
+ // itself failed (non-zero exit: corrupt freeze.json, an invalid payload,
2266
+ // spawn error, etc.). Never silently allow when an applicable gate's source
2267
+ // is broken → exit 2. (Not-applicable envelopes already returned exit 0
2268
+ // above, so this only blocks when the gate's input was actually present.)
2269
+ if (result.error || typeof result.status !== 'number' || result.status !== 0) {
2270
+ process.stderr.write(
2271
+ '[totem gate-wrapper] gate "' +
2272
+ event +
2273
+ '" evaluation failed (source broken or unavailable) — blocking (fail-closed).\\n' +
2274
+ // The child's stderr already went through verbatim above (fold F1);
2275
+ // only a spawn-level error (no child, so no stderr) is added here.
2276
+ (result.error ? String(result.error.message || result.error) + '\\n' : '') +
2277
+ armNote,
2278
+ );
2279
+ process.exit(2);
2280
+ }
2281
+
2282
+ let verdict;
2283
+ try {
2284
+ verdict = JSON.parse(result.stdout || '');
2285
+ } catch (err) {
2286
+ // The command emitted unparseable stdout despite a 0 exit — an applicable
2287
+ // gate whose verdict we cannot read is a broken source → fail-closed.
2288
+ process.stderr.write(
2289
+ '[totem gate-wrapper] gate "' + event + '" emitted unparseable verdict — blocking (fail-closed).\\n' + armNote,
2290
+ );
2291
+ process.exit(2);
2292
+ }
2293
+
2294
+ // ─── Disposition → host exit code (branch ONLY on disposition) ───────
2295
+ const disposition = verdict && typeof verdict.disposition === 'string' ? verdict.disposition : '';
2296
+ // reason/provenance are OPAQUE stderr passthrough — never parsed for control flow.
2297
+ const detail =
2298
+ (verdict && verdict.reason ? verdict.reason : '') +
2299
+ (verdict && verdict.provenance ? ' [' + JSON.stringify(verdict.provenance) + ']' : '');
2300
+
2301
+ if (disposition === 'allow') {
2302
+ // Deliberately SILENT on the PATH arm too: a provenance line on every
2303
+ // allowed Bash command would be transcript noise on the common path, and
2304
+ // the operator already learned the property at install time (the
2305
+ // \`gate install\` disclosure) — stderr here is reserved for what blocks.
2306
+ continue;
2307
+ }
2308
+ if (disposition === 'warn') {
2309
+ process.stderr.write('[totem gate-wrapper] ' + event + ' (warn): ' + detail + '\\n');
2310
+ continue;
2311
+ }
2312
+ if (disposition === 'deny') {
2313
+ process.stderr.write('[totem gate-wrapper] ' + event + ' (deny): ' + detail + '\\n');
2314
+ if (tier !== 'pilot') {
2315
+ process.exit(2);
2316
+ }
2317
+ continue;
2318
+ }
2319
+
2320
+ // Unknown disposition from an applicable gate — fail-closed. The provenance
2321
+ // note rides here too, so all four not-evaluable causes in the exit-code
2322
+ // contract above disclose which arm evaluated.
1545
2323
  process.stderr.write(
1546
- '[totem gate-wrapper] gate "' + event + '" emitted unparseable verdict — blocking (fail-closed).\\n',
2324
+ '[totem gate-wrapper] gate "' + event + '" returned unknown disposition "' + disposition + '" — blocking (fail-closed).\\n' + armNote,
1547
2325
  );
1548
2326
  process.exit(2);
1549
2327
  }
1550
-
1551
- // ─── Disposition → host exit code (branch ONLY on disposition) ─────────
1552
- const disposition = verdict && typeof verdict.disposition === 'string' ? verdict.disposition : '';
1553
- // reason/provenance are OPAQUE stderr passthrough — never parsed for control flow.
1554
- const detail =
1555
- (verdict && verdict.reason ? verdict.reason : '') +
1556
- (verdict && verdict.provenance ? ' [' + JSON.stringify(verdict.provenance) + ']' : '');
1557
-
1558
- if (disposition === 'allow') {
1559
- process.exit(0);
1560
- }
1561
- if (disposition === 'warn') {
1562
- process.stderr.write('[totem gate-wrapper] ' + event + ' (warn): ' + detail + '\\n');
1563
- process.exit(0);
1564
- }
1565
- if (disposition === 'deny') {
1566
- process.stderr.write('[totem gate-wrapper] ' + event + ' (deny): ' + detail + '\\n');
1567
- process.exit(tier === 'pilot' ? 0 : 2);
1568
- }
1569
-
1570
- // Unknown disposition from an applicable gate — fail-closed.
1571
- process.stderr.write(
1572
- '[totem gate-wrapper] gate "' + event + '" returned unknown disposition "' + disposition + '" — blocking (fail-closed).\\n',
1573
- );
1574
- process.exit(2);
2328
+ process.exit(0);
1575
2329
  });
1576
2330
  ${TOTEM_FILE_END}
1577
2331
  `;
@@ -1901,15 +2655,19 @@ ${SKILL_MARKER_START}
1901
2655
 
1902
2656
  Session-start bring-up. **Read-only** — no mutations, no dispatches, no board edits until the operator rules on next steps (Proposal 295 d2: read-only orient + grounded next-work). Solo — no agent fleet (\`feedback_session_start_derive_cheaply\`: cheap derivation IS the validation dogfood).
1903
2657
 
1904
- 1. **Consume the injected orientation.** On Claude Code seats a SessionStart hook may inject a journal + carryforward, inbound mail, branch/ticket-matched context, and a bounded session-orientation slice (parked/freeze state, open PRs, board↔issue coherence drift, and an open-issue-count pointer) the hook serves the seat it is CONFIGURED for, not a derived identity, so confirm the injected journal is YOURS: a visiting session receives the HOST seat's, and your carryforward derives from \`.totem/orchestration/<your-seat>/journal/\` (step 3), never from a foreign journal. On a hook-seat MISMATCH (the injected journal or mail banner names another seat), consume NONE of the injected materialtreat the session as hook-less: derive it all via \`totem orient\` plus your own seat-anchored poll (step 2). Do not re-run what the hook injected. Everything else the bring-up needs (the full board in-flight set, corpus freshness, doctrine currency) is derived on demand via \`totem orient\`. On a hook-less seat (other vendors, cold starts), derive it all: \`totem orient\`.
2658
+ 0. **Derive the seat FIRST before orient, before any journal read, before any knowledge search** (mmnto-ai/totem#2801). Read the INHERITED \`TOTEM_SELF_AGENT\` this session was launched with; \`totem mail --derive-seat\` is the probe — one stdout line \`seat=<id> source=env\` and exit 0 when the inherited env names exactly one seat this repo hosts, otherwise a stderr refusal (exit 2) naming the supplied value (or \`unset\`) and every seat this repo hosts. **Hosts** means one thing everywhere: config.json \`host_agents\`, else the seat dirs, else the cohort map keyed on the origin repository — never the env you supplied, which is the thing being checked. **Set → that is your seat: use it, and never write a different one.** An inline \`TOTEM_SELF_AGENT=<seat>\` on any later command may only RESTATE the inherited value; writing a different seat over it silently re-points every step below at a seat that is not yours, and once overridden the tool can no longer see what you inherited — the operator's account is the only witness left. **Set but REFUSED** (the probe exits 2 while the env names a seat): your declaration and this repo disagree, so act as if you have no seat put the refusal line itself in front of the operator, verbatim, and change nothing to make it pass; signon is read-only, so \`totem seat add\` is never run here. On a repo with no seat registration at all the refusal says the repo cannot CORROBORATE you, not that your seat is wrong: \`totem mail --as <your-seat>\` and a per-shell poll still serve your declaration, because a declaration on the command line is yours to make and this probe only checks one. **Empty STOP and ask the operator.** Do not guess, do not fall back to the crown, do not derive a seat from the repo basename, the branch, or the only seat in sight; a bring-up on an unknown identity is worse than no bring-up. Report exactly one line and wait: \`Failure Mode: Hook-less session launched without TOTEM_SELF_AGENT set.\`
2659
+
2660
+ 1. **Assignment mail before orient — poll since last signoff, seat-anchored.** On a hook-less seat the order is fixed: assignment mail before orient, before any journal read, and before any knowledge search — an assignment can turn every one of those into a disclosure (step 2), and the managed hook derives neither the poll nor the journal for you (step 3). Poll AS YOUR SEAT: per-shell \`TOTEM_SELF_AGENT=<your-seat>\` (the mmnto-ai/totem#2629 scope ruling — never user/machine scope; prefer the inline form \`TOTEM_SELF_AGENT=<seat> totem mail\` where shell state does not persist between tool calls, and on a session whose step-0 env is already set that inline form RESTATES that seat and never another) or \`totem mail --as <your-seat>\`. **S0 identity check:** the banner's \`Self agents:\` line must name exactly your seat. Since @mmnto/cli 1.117.0 an identity-less multi-seat poll gates itself (broadcast-only serve, directed mail withheld as a count, exit 2 — the mmnto-ai/totem#2204 deterministic floor), so the residual S0 catches is the WRONG-single-identity class: a mis-scoped or inherited env naming a foreign seat resolves single-seat, ungated, and serves that seat's directed mail. A banner naming a FOREIGN seat = STOP: act on nothing served, propagate nothing from it, fix the identity, re-poll. A GATED poll's LISTING is broadcast-only by construction — but warning lines can still name an unclassifiable or unresolvable file (an ECL basename is recipient + compressed subject — the CLI's named limit), so propagate nothing from a gated poll's warnings either: fix the identity and re-poll for your directed mail. An \`Error:\` line is the same surface: since the mmnto-ai/totem#2685 fix a poll whose OWN outbox (one this repo hosts for a resolved seat) carries a dispatch with an unresolvable \`to:\` exits 4 (SENDER FAULT) — the verdict IS derived, read it, but the \`to:\` is yours to fix first (one recipient per dispatch, or broadcast; a comma list is never a recipient), and propagate nothing from the fault line; exit 2 stays NOT-DERIVED and wins when both hold. Unread = inbound − handled: consumption is tracked by \`processed/\` marks (\`feedback_check_outbox_before_replying\`), so the CLI path needs no cutoff stamp. Read every hit before proceeding — new mail can reprioritize everything below. (Fallback — a seat that must stamp-poll instead derives the cutoff from the newest journal's CONTENT date, the filename stamp or frontmatter, **never file mtime**, which git resets on clone/worktree and silently reports "inbox clean" over waiting mail; mmnto-ai/totem-strategy#813.)
2661
+
2662
+ 2. **Kit-first — while a BLIND round is in flight, read the kit and nothing else.** The BLIND-kit marker is the dispatch SUBJECT's literal prefix \`BLIND round: \`, followed by the round's name and, in the same subject, the deposit clause \`— deposit to <orchestrator-seat> by <ISO-8601 deadline>\`; no frontmatter key carries it, so the subject line is what you read. **A round is in flight while such a dispatch has an unpassed deadline and no deposit received.** In flight, signon ENDS here: read the kit and the artifact the kit names, and nothing else — no \`totem orient\`, no journal, no knowledge search, no board or PR read — because live repository detail is precisely what a blind classification must not carry. The kit-first rule has no partial arm: if any step ran before you reached the kit, report the exposure to the round's orchestrator seat by directed mail and do not classify; a disclosed round is re-armed in a fresh session, never repaired in place.
1905
2663
 
1906
- 2. **Poll mail since last signoff seat-anchored.** Poll AS YOUR SEAT: per-shell \`TOTEM_SELF_AGENT=<your-seat>\` (the mmnto-ai/totem#2629 scope ruling never user/machine scope; prefer the inline form \`TOTEM_SELF_AGENT=<seat> totem mail\` where shell state does not persist between tool calls) or \`totem mail --as <your-seat>\`. **S0 identity check:** the banner's \`Self agents:\` line must name exactly your seat. Since @mmnto/cli 1.117.0 an identity-less multi-seat poll gates itself (broadcast-only serve, directed mail withheld as a count, exit 2 the mmnto-ai/totem#2204 deterministic floor), so the residual S0 catches is the WRONG-single-identity class: a mis-scoped or inherited env naming a foreign seat resolves single-seat, ungated, and serves that seat's directed mail. A banner naming a FOREIGN seat = STOP: act on nothing served, propagate nothing from it, fix the identity, re-poll. A GATED poll's LISTING is broadcast-only by construction but warning lines can still name an unclassifiable or unresolvable file (an ECL basename is recipient + compressed subject the CLI's named limit), so propagate nothing from a gated poll's warnings either: fix the identity and re-poll for your directed mail. An \`Error:\` line is the same surface: since the mmnto-ai/totem#2685 fix a poll whose OWN outbox (one this repo hosts for a resolved seat) carries a dispatch with an unresolvable \`to:\` exits 4 (SENDER FAULT) — the verdict IS derived, read it, but the \`to:\` is yours to fix first (one recipient per dispatch, or broadcast; a comma list is never a recipient), and propagate nothing from the fault line; exit 2 stays NOT-DERIVED and wins when both hold. Unread = inbound − handled: consumption is tracked by \`processed/\` marks (\`feedback_check_outbox_before_replying\`), so the CLI path needs no cutoff stamp. Read every hit before proceeding — new mail can reprioritize everything below. (Fallback a seat that must stamp-poll instead derives the cutoff from the newest journal's CONTENT date, the filename stamp or frontmatter, **never file mtime**, which git resets on clone/worktree and silently reports "inbox clean" over waiting mail; mmnto-ai/totem-strategy#813.)
2664
+ 3. **Consume the injected orientationthe managed hook injects exactly two blocks.** The managed SessionStart hook injects exactly two briefing blocks \`totem describe\` and \`totem orient --session\` and injects nothing else: no journal and no mail (it does other work at boot, none of which reaches your context), so your latest journal (step 4) and your seat-anchored mail (step 1) are derived BY HAND on every seat, hook or not never assumed present. Do not re-run the two blocks it did inject. A repo may also run its own session hook; whatever such a hook injects serves the seat it is CONFIGURED for, not a derived identity, so confirm the injected material is YOURS: a visiting session receives the HOST seat's, and your carryforward derives from \`.totem/orchestration/<your-seat>/journal/\` (step 4), never from a foreign journal. On a hook-seat MISMATCH (an injected journal or mail banner naming another seat), consume NONE of the injected material treat the session as hook-less and derive it all: \`totem orient\` plus your own seat-anchored poll (step 1). Everything else the bring-up needs (the full board in-flight set, corpus freshness, doctrine currency) is derived on demand via \`totem orient\`. On a hook-less seat (other vendors, cold starts), derive it all: \`totem orient\`.
1907
2665
 
1908
- 3. **Re-derive the carryforward gates — don't trust the journal's framing** (Tenet 20 read-side twin). For each carryforward item in YOUR SEAT's latest journal (\`.totem/orchestration/<your-seat>/journal/\` — on a multi-seat repo another seat's newer journal is not your carryforward), freshly derive its gate state (the PR it waits on, the issue, the date, the release train) via \`gh\` / \`git\` reads. Cross-repo gates resolve through the frozen cohort roster — \`totem\` / \`strategy\` / \`status\` / \`lc\` → \`mmnto-ai/{totem, totem-strategy, totem-status, liquid-city}\` (mmnto-ai/totem-strategy#611 gates any change). An item whose gate fired leads the next-steps list; an item still gated is reported as waiting, not worked.
2666
+ 4. **Re-derive the carryforward gates — don't trust the journal's framing** (Tenet 20 read-side twin). For each carryforward item in YOUR SEAT's latest journal (\`.totem/orchestration/<your-seat>/journal/\` — on a multi-seat repo another seat's newer journal is not your carryforward), freshly derive its gate state (the PR it waits on, the issue, the date, the release train) via \`gh\` / \`git\` reads. Cross-repo gates resolve through the frozen cohort roster — \`totem\` / \`strategy\` / \`status\` / \`lc\` → \`mmnto-ai/{totem, totem-strategy, totem-status, liquid-city}\` (mmnto-ai/totem-strategy#611 gates any change). An item whose gate fired leads the next-steps list; an item still gated is reported as waiting, not worked.
1909
2667
 
1910
- 4. **Surface owed-now sensors.** Anything the injected/derived orientation flags as owed (corpus \`⚠ stale\`, strategy-doctrine \`⚠ publish owed\`, board drift) goes on the list as a candidate — sensors report, they don't gate (Tenet 13).
2668
+ 5. **Surface owed-now sensors.** Anything the injected/derived orientation flags as owed (corpus \`⚠ stale\`, strategy-doctrine \`⚠ publish owed\`, board drift) goes on the list as a candidate — sensors report, they don't gate (Tenet 13).
1911
2669
 
1912
- 5. **Present and stop.** One message: state summary (inbox, gate states, owed-now items) + ranked next-steps with a recommendation. Then wait for the operator's ruling — signon ends at the judgment handoff; mutations belong to the ruled work, not the bring-up.
2670
+ 6. **Present and stop.** One message: state summary (seat, inbox, gate states, owed-now items) + ranked next-steps with a recommendation. Then wait for the operator's ruling — signon ends at the judgment handoff; mutations belong to the ruled work, not the bring-up.
1913
2671
 
1914
2672
  ${SKILL_MARKER_END}
1915
2673
  `;
@@ -1969,7 +2727,7 @@ For each selected finding, generate a lesson and call \`mcp__totem-dev__add_less
1969
2727
 
1970
2728
  ### \`done\`
1971
2729
 
1972
- Print a summary of actions taken, then — when the round is being dispositioned — assemble and post the single consolidated round-disposition comment (see the section below), which EXECUTES \`totem review --covariate\` to carry the \`local-lane:\` line, on the operator's explicit go. Then exit.
2730
+ Print a summary of actions taken, then — when the round is being dispositioned — assemble and post the single consolidated round-disposition comment (see the section below), which EXECUTES \`totem review --covariate\` to carry the \`local-lane:\` line, on the operator's explicit go. Then, as the LAST action of the round, run \`totem resolve-threads\` (step 4 of that section) — dry first, \`--apply\` only on the operator's explicit go. Then exit.
1973
2731
 
1974
2732
  ## CRITICAL: GCA Reply Protocol
1975
2733
 
@@ -1991,6 +2749,20 @@ It resolves the current branch lineage exactly as the review fan does and prints
1991
2749
 
1992
2750
  3. **Post on an explicit go.** Show the assembled body and wait for the operator; on their go, post the ONE comment with \`gh pr comment $ARGUMENTS --body-file -\` (pipe the body via stdin). Never mutate the PR autonomously.
1993
2751
 
2752
+ 4. **Resolve the threads this round dispositioned — dry first, \`--apply\` on the operator's explicit go.** The comment you just posted IS the evidence the verb reads, so this step runs AFTER it, and it is the LAST action of the round. Print the plan (this never mutates):
2753
+
2754
+ \`\`\`bash
2755
+ totem resolve-threads $ARGUMENTS
2756
+ \`\`\`
2757
+
2758
+ Every bot-rooted thread prints one row carrying its REST root comment id and a verdict: \`resolve\`, \`skip:already-resolved\`, \`skip:outdated\`, \`skip:no-evidence\`, \`skip:not-selected\`. A \`skip:no-evidence\` row is a thread this round has not answered — neither an in-thread reply from a human nor a PR-level comment created after that thread's root — and the verb will NEVER resolve it under any flag; give it evidence and re-run rather than working around it. Show the plan and wait. Only on the operator's explicit go, run the mutating half (add \`--ids <comma-separated REST root comment ids>\` to narrow it to named rows; an unmatched id aborts before anything is resolved):
2759
+
2760
+ \`\`\`bash
2761
+ totem resolve-threads $ARGUMENTS --apply
2762
+ \`\`\`
2763
+
2764
+ The verb never posts a comment, a reply or a review — the only mutation it can issue is \`resolveReviewThread\`, which is what the merge-ready gate's unresolved-bot-threads predicate reads. Exit \`2\` means it did not do everything asked (an unmatched id, a failed mutation, or a selected thread with no evidence); exit \`1\` means the read did not complete and NOTHING was resolved. Report what it printed, verbatim.
2765
+
1994
2766
  ${SKILL_MARKER_END}
1995
2767
  `;
1996
2768
  export const REVIEW_LOOP_SKILL_CONTENT = `---