reasonweave 0.0.0-stage → 1.3.2

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 (228) hide show
  1. package/AGENTS.md +101 -0
  2. package/INSTALL.md +258 -0
  3. package/README.md +280 -2
  4. package/bin/lab.mjs +888 -0
  5. package/constitution.md +55 -0
  6. package/docs/CONSUMER-PROMPTS.md +474 -0
  7. package/docs/backlogs/01-forward-wait-self-detach.md +18 -0
  8. package/docs/backlogs/02-decouple-wait-and-daemon-for-agent-hosts.md +35 -0
  9. package/docs/backlogs/03-baton-wait-multi-id-lightweight-pubsub.md +34 -0
  10. package/docs/backlogs/04-adr-cross-repo-automated-dispatch-boundary.md +19 -0
  11. package/docs/backlogs/05-feat-units-worktree-isolation-engine.md +23 -0
  12. package/docs/backlogs/06-feat-blind-audit-automated-clean-runner.md +22 -0
  13. package/docs/backlogs/07-feat-attention-throttle-silent-pipe.md +23 -0
  14. package/docs/backlogs/08-future-units-shadow-ledger.md +22 -0
  15. package/docs/backlogs/09-feat-agent-baton-core-convergence-and-resilience.md +42 -0
  16. package/docs/backlogs/10-feat-anti-orphan-deterministic-wiring-governance.md +35 -0
  17. package/docs/backlogs/11-perf-orphan-index-fs-read.md +16 -0
  18. package/docs/backlogs/12-feat-vibe-security-anti-suppression-and-orphan-deps.md +43 -0
  19. package/docs/backlogs/13-feat-sdd-reppit-tiered-guardrails.md +40 -0
  20. package/docs/backlogs/14-feat-universal-cli-contract-and-hermetic-test-fixtures.md +48 -0
  21. package/docs/backlogs/15-feat-reasonweave-rebranding-and-doc-code-synchronization-invariant.md +44 -0
  22. package/docs/backlogs/16-feat-micro-engineering-skills-and-sdd-baton-fusion.md +52 -0
  23. package/docs/codegraph-readiness-check.md +49 -0
  24. package/group/architecture/adr/0001-handoff-async-wait-and-reactive-wakeup.md +87 -0
  25. package/group/architecture/adr/0002-de-ritualize-handoff-prompt-for-intra-repo.md +53 -0
  26. package/group/architecture/adr/0003-attention-throttle-and-workspace-driver.md +65 -0
  27. package/group/architecture/adr/0004-spec-guard-and-drift-prevention.md +90 -0
  28. package/group/architecture/adr/0005-global-orphan-scavenger-and-read-only-invariants.md +94 -0
  29. package/group/architecture/adr/0006-triad-engineering-defense-and-mutation-sensitivity.md +68 -0
  30. package/group/architecture/adr/0007-agent-baton-state-machine-defense-and-workspace-jail-spec.md +86 -0
  31. package/group/architecture/adr/0008-agent-baton-core-convergence-and-heterogeneous-session-resilience.md +133 -0
  32. package/group/architecture/adr/0009-anti-orphan-deterministic-wiring-governance-and-federated-guardrails.md +108 -0
  33. package/group/architecture/adr/0010-agent-baton-identity-security-cryptographic-credentials-and-prompt-anti-confusion.md +119 -0
  34. package/group/architecture/adr/0011-vibe-security-anti-suppression-and-dependency-reachability.md +161 -0
  35. package/group/architecture/adr/0012-spec-driven-development-reppit-and-tiered-guardrails.md +130 -0
  36. package/group/architecture/adr/0013-universal-cli-contract-hermetic-testing-and-defensive-probes.md +110 -0
  37. package/group/architecture/adr/0014-reasonweave-rebranding-and-doc-code-synchronization-invariant.md +108 -0
  38. package/group/architecture/adr/0015-micro-engineering-skills-and-dual-core-gate-invariant.md +127 -0
  39. package/group/architecture/adr/INDEX.md +29 -0
  40. package/group/architecture/adr/templates/adr-template.md +33 -0
  41. package/group/architecture/dependency-graph.md +60 -0
  42. package/group/contracts/npm-packaging.md +69 -0
  43. package/group/product/intent.md +24 -0
  44. package/package.json +93 -4
  45. package/scripts/sync-all-consumers.mjs +174 -0
  46. package/specs/RFC-20261110-SPEC-GUARD-UNIT.md +353 -0
  47. package/specs/templates/01-research.md.template +23 -0
  48. package/specs/templates/02-proposals.md.template +22 -0
  49. package/specs/templates/03-spec.md.template +33 -0
  50. package/specs/templates/04-tasks.md.template +29 -0
  51. package/specs/templates/05-evidence.md.template +29 -0
  52. package/specs/templates/README.md +26 -0
  53. package/units/adr/AGENTS.md +85 -0
  54. package/units/adr/CHANGELOG.md +20 -0
  55. package/units/adr/README.md +88 -0
  56. package/units/adr/VERSION.md +10 -0
  57. package/units/adr/docs/existing-project-prompt.md +24 -0
  58. package/units/adr/docs/new-project-prompt.md +36 -0
  59. package/units/adr/scripts/adr-init.sh +101 -0
  60. package/units/adr/templates/INDEX.md +19 -0
  61. package/units/adr/templates/adr-frozen.md +33 -0
  62. package/units/adr/templates/adr-light.md +56 -0
  63. package/units/adr/templates/adr-standard.md +61 -0
  64. package/units/backlog/AGENTS.md +53 -0
  65. package/units/backlog/AUTONOMOUS-GOVERNANCE.md +98 -0
  66. package/units/backlog/CHANGELOG.md +37 -0
  67. package/units/backlog/README.md +124 -0
  68. package/units/backlog/VERSION.md +11 -0
  69. package/units/backlog/docs/existing-project-ironrules-prompt.md +31 -0
  70. package/units/backlog/docs/existing-project-prompt.md +24 -0
  71. package/units/backlog/docs/new-project-prompt.md +19 -0
  72. package/units/backlog/templates/entry.md +39 -0
  73. package/units/backlog/templates/project-ironrules.md +36 -0
  74. package/units/handoffs/AGENT-GUIDE.md +118 -0
  75. package/units/handoffs/AGENTS.md +28 -0
  76. package/units/handoffs/CHANGELOG.md +498 -0
  77. package/units/handoffs/CLAUDE.md +28 -0
  78. package/units/handoffs/COMMANDS.md +187 -0
  79. package/units/handoffs/DESIGN.md +74 -0
  80. package/units/handoffs/README.md +456 -0
  81. package/units/handoffs/RESPONSE-TEMPLATE.md +138 -0
  82. package/units/handoffs/VERSION.md +1 -0
  83. package/units/handoffs/handoff-status.mjs +1017 -0
  84. package/units/handoffs/handoff.mjs +5675 -0
  85. package/units/orphan/CHANGELOG.md +118 -0
  86. package/units/orphan/DESIGN.md +484 -0
  87. package/units/orphan/README.md +143 -0
  88. package/units/orphan/VERSION.md +1 -0
  89. package/units/orphan/adapters/android/index.mjs +140 -0
  90. package/units/orphan/adapters/python/index.mjs +232 -0
  91. package/units/orphan/adapters/web/index.mjs +280 -0
  92. package/units/orphan/bin/lab-orphan.mjs +298 -0
  93. package/units/orphan/core/blob-reader.mjs +142 -0
  94. package/units/orphan/core/classifier.mjs +261 -0
  95. package/units/orphan/core/cleaner.mjs +166 -0
  96. package/units/orphan/core/diff-checker.mjs +341 -0
  97. package/units/orphan/core/inverted-index.mjs +124 -0
  98. package/units/orphan/core/orphan-deps.mjs +192 -0
  99. package/units/orphan/core/protocol-s1-s3.mjs +194 -0
  100. package/units/orphan/core/solver.mjs +217 -0
  101. package/units/orphan/index.mjs +105 -0
  102. package/units/orphan/templates/ci/orphan-guard.yml +36 -0
  103. package/units/orphan/templates/pre-commit.d/30-orphan-guard +34 -0
  104. package/units/orphan/templates/wiring/README.md +51 -0
  105. package/units/orphan/templates/wiring/miniprogram-route-guard.js.template +80 -0
  106. package/units/orphan/templates/wiring/pre-commit-node.sh.template +73 -0
  107. package/units/orphan/templates/wiring/project-agents-gemini-templates.md +60 -0
  108. package/units/orphan/templates/wiring/python-parity-test.py.template +100 -0
  109. package/units/orphan/templates/wiring/rust-exhaustive-match.md +65 -0
  110. package/units/orphan/templates/wiring/swift-periphery.md +56 -0
  111. package/units/orphan/tests/adapters.test.mjs +243 -0
  112. package/units/orphan/tests/orphan-deps.test.mjs +131 -0
  113. package/units/orphan/tests/phase3-gates.test.mjs +135 -0
  114. package/units/playbook/README.md +106 -0
  115. package/units/playbook/ZSPEC-AGENT-GUIDE.md +99 -0
  116. package/units/playbook/docs/01-architecture.md +99 -0
  117. package/units/playbook/docs/02-bootstrap.md +126 -0
  118. package/units/playbook/docs/03-units.md +91 -0
  119. package/units/playbook/docs/04-constitution.md +113 -0
  120. package/units/playbook/docs/05-adr.md +33 -0
  121. package/units/playbook/docs/06-spec-kit.md +76 -0
  122. package/units/playbook/docs/07-backlog.md +30 -0
  123. package/units/playbook/docs/08-codegraph.md +79 -0
  124. package/units/playbook/docs/09-skills.md +101 -0
  125. package/units/playbook/docs/10-handoff.md +72 -0
  126. package/units/playbook/docs/11-evidence.md +163 -0
  127. package/units/playbook/docs/12-gates.md +124 -0
  128. package/units/playbook/docs/13-parallel.md +115 -0
  129. package/units/playbook/docs/14-dependency-graph.md +86 -0
  130. package/units/playbook/docs/15-memory.md +153 -0
  131. package/units/playbook/docs/16-change-control.md +121 -0
  132. package/units/playbook/docs/17-prompts.md +121 -0
  133. package/units/playbook/docs/18-shift-left.md +97 -0
  134. package/units/playbook/docs/19-anti-orphan-vertical-slicing.md +102 -0
  135. package/units/playbook/docs/20-vibe-security-and-anti-suppression.md +88 -0
  136. package/units/playbook/docs/21-spec-driven-reppit-closed-loop.md +88 -0
  137. package/units/playbook/examples/owisel.md +80 -0
  138. package/units/playbook/references/Agent-Engineering-Framework-AEF-v1.0.md +2033 -0
  139. package/units/playbook/references/links.md +103 -0
  140. package/units/playbook/templates/AGENTS.root.md +44 -0
  141. package/units/playbook/templates/AGENTS.unit.md +52 -0
  142. package/units/playbook/templates/adr/INDEX.md +17 -0
  143. package/units/playbook/templates/adr/NNNN-template.md +56 -0
  144. package/units/playbook/templates/backlogs/entry.md +30 -0
  145. package/units/playbook/templates/constitution.md +93 -0
  146. package/units/playbook/templates/evidence/README.md +36 -0
  147. package/units/playbook/templates/group/architecture/dependency-graph.md +48 -0
  148. package/units/playbook/templates/group/architecture/system.md +59 -0
  149. package/units/playbook/templates/group/contracts/api.md +67 -0
  150. package/units/playbook/templates/group/product/intent.md +30 -0
  151. package/units/playbook/templates/group/product/requirements.md +48 -0
  152. package/units/playbook/templates/unit-skeleton/README.md +35 -0
  153. package/units/preflight/AGENTS.md +45 -0
  154. package/units/preflight/CHANGELOG.md +55 -0
  155. package/units/preflight/INSTALL.md +65 -0
  156. package/units/preflight/README.md +104 -0
  157. package/units/preflight/VERSION.md +3 -0
  158. package/units/preflight/docs/audit-requirements.md +114 -0
  159. package/units/preflight/docs/existing-project-prompt.md +25 -0
  160. package/units/preflight/docs/new-project-prompt.md +25 -0
  161. package/units/preflight/docs/transfers/CONSUMER-INSTALL.md +40 -0
  162. package/units/preflight/docs/transfers/CONSUMER-SELFCHECK.md +51 -0
  163. package/units/preflight/docs/transfers/README.md +39 -0
  164. package/units/preflight/docs/transfers/prospero.md +26 -0
  165. package/units/preflight/templates/check.sh +43 -0
  166. package/units/preflight/templates/pre-commit +55 -0
  167. package/units/preflight/templates/pre-commit.d/20-preflight +15 -0
  168. package/units/preflight/templates/preflight.conf.example +21 -0
  169. package/units/preflight/templates/preflight.sh +189 -0
  170. package/units/preflight/templates/wrap-up.md +9 -0
  171. package/units/review-gate/AGENTS.md +42 -0
  172. package/units/review-gate/CHANGELOG.md +58 -0
  173. package/units/review-gate/README.md +118 -0
  174. package/units/review-gate/VERSION.md +3 -0
  175. package/units/review-gate/clean-runner.mjs +350 -0
  176. package/units/review-gate/docs/existing-project-prompt.md +28 -0
  177. package/units/review-gate/docs/new-project-prompt.md +38 -0
  178. package/units/review-gate/docs/transfers/iggle.md +34 -0
  179. package/units/review-gate/docs/transfers/prospero.md +35 -0
  180. package/units/review-gate/docs/transfers/swoop.md +36 -0
  181. package/units/review-gate/docs/transfers/yiqiyihuihua.md +35 -0
  182. package/units/review-gate/templates/.semgrepignore +37 -0
  183. package/units/review-gate/templates/pre-commit +130 -0
  184. package/units/review-gate/templates/scan.sh +158 -0
  185. package/units/skills/AGENTS.md +17 -0
  186. package/units/skills/CHANGELOG.md +18 -0
  187. package/units/skills/README.md +63 -0
  188. package/units/skills/VERSION.md +1 -0
  189. package/units/skills/bin/review-package.mjs +99 -0
  190. package/units/skills/bin/task-brief.mjs +102 -0
  191. package/units/skills/catalog/brainstorming/SKILL.md +75 -0
  192. package/units/skills/catalog/brainstorming/references/design-doc-template.md +28 -0
  193. package/units/skills/catalog/systematic-debugging/SKILL.md +101 -0
  194. package/units/skills/catalog/systematic-debugging/references/root-cause-tracing.md +23 -0
  195. package/units/skills/catalog/test-driven-development/SKILL.md +88 -0
  196. package/units/skills/catalog/test-driven-development/references/writing-good-tests.md +13 -0
  197. package/units/skills/catalog/verification-before-completion/SKILL.md +73 -0
  198. package/units/skills/skills.mjs +181 -0
  199. package/units/skills/tests/pipeline.test.mjs +131 -0
  200. package/units/skills/tests/skill-contract.test.mjs +67 -0
  201. package/units/skills/tests/skills-cli.test.mjs +107 -0
  202. package/units/spec-guard/AGENTS.md +43 -0
  203. package/units/spec-guard/CHANGELOG.md +88 -0
  204. package/units/spec-guard/README.md +148 -0
  205. package/units/spec-guard/VERSION.md +1 -0
  206. package/units/spec-guard/bin/spec-guard.mjs +431 -0
  207. package/units/spec-guard/core/adr-parser.mjs +540 -0
  208. package/units/spec-guard/core/matrix-checker.mjs +587 -0
  209. package/units/spec-guard/core/mutation-runner.mjs +267 -0
  210. package/units/spec-guard/core/scanner.mjs +333 -0
  211. package/units/spec-guard/core/telemetry_authenticator.mjs +484 -0
  212. package/units/spec-guard/core/wiring_tracer.mjs +306 -0
  213. package/units/spec-guard/templates/annotations/ContractOnly.kt +19 -0
  214. package/units/spec-guard/templates/annotations/Invariant.kt +16 -0
  215. package/units/spec-guard/templates/annotations/invariant.go +19 -0
  216. package/units/spec-guard/templates/annotations/invariant.py +38 -0
  217. package/units/spec-guard/templates/annotations/invariant.ts +39 -0
  218. package/units/spec-guard/templates/ci/spec-guard-audit.yml +23 -0
  219. package/units/spec-guard/templates/pre-commit.d/15-spec-guard +72 -0
  220. package/units/spec-guard/templates/spec-matrix.overlay.yml +70 -0
  221. package/units/spec-guard/tests/spec-guard.test.mjs +716 -0
  222. package/units/spec-guard/tests/telemetry_authenticator.test.mjs +633 -0
  223. package/units/worktree/AGENTS.md +22 -0
  224. package/units/worktree/CHANGELOG.md +14 -0
  225. package/units/worktree/README.md +65 -0
  226. package/units/worktree/VERSION.md +1 -0
  227. package/units/worktree/worktree.mjs +352 -0
  228. package//344/275/277/347/224/250/350/257/264/346/230/216.md +322 -0
@@ -0,0 +1,1017 @@
1
+ #!/usr/bin/env node
2
+ // 公共交接目录(Handoff Hub)状态巡检工具。
3
+ // 脚本位置即交接根:<root>/handoff-status.mjs,<root>/handoffs/,<root>/receipts/。
4
+ // 人类可读摘要: node <root>/handoff-status.mjs
5
+ // 机器可读(自动化运营轮询,v1,字段禁止改): node <root>/handoff-status.mjs --json
6
+ // 依赖方待办视角: node <root>/handoff-status.mjs --for <swoop|prospero|iggle|coreml|tappy|yiqiyihuihua|lab> [--json=v2]
7
+ // 根目录由脚本自身位置推导,整个 hub 目录可整体移动而不失灵。
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ const SCRIPT_ROOT = path.dirname(fileURLToPath(import.meta.url));
13
+ // 仓内模式:根与模式由调用方(handoff.mjs)经 --root/--mode 显式传入;缺省回退脚本目录(lab Hub,跨仓)。
14
+ let ROOT = SCRIPT_ROOT;
15
+ let MODE = 'cross';
16
+ // JSON 输出分两档(v2.6):
17
+ // --json → v1(兼容默认,schema 不变;裸 status 的 v1 被自动化轮询消费,禁止改字段)
18
+ // --json=v2 → v2(仅 --for 时有效,新增 target 感知的 pending + counts;禁止替换 v1)
19
+ let JSON_MODE = false;
20
+ let JSON_V2 = false;
21
+ let ACTIVE_ONLY = false;
22
+ let SHOW_ALL = false;
23
+ for (const a of process.argv) {
24
+ if (a === '--json') JSON_MODE = true;
25
+ else if (a === '--json=v2') { JSON_MODE = true; JSON_V2 = true; }
26
+ else if (a === '--active' || a === '-a') ACTIVE_ONLY = true;
27
+ else if (a === '--all') SHOW_ALL = true;
28
+ else if (a === '--root') { const i = process.argv.indexOf(a); if (process.argv[i + 1]) ROOT = process.argv[i + 1]; }
29
+ else if (a.startsWith('--root=')) { ROOT = a.slice('--root='.length); }
30
+ else if (a === '--mode') { const i = process.argv.indexOf(a); if (process.argv[i + 1]) MODE = process.argv[i + 1]; }
31
+ else if (a.startsWith('--mode=')) { MODE = a.slice('--mode='.length); }
32
+ }
33
+ const H_DIR = path.join(ROOT, 'handoffs');
34
+ const R_DIR = path.join(ROOT, 'receipts');
35
+
36
+ // ── 审计日志流水追溯(支持精准回退驳回方归属 · ADR-0008)──────────────────────────
37
+ const journalEventsMap = (() => {
38
+ const map = new Map();
39
+ const jFile = path.join(ROOT, 'logs', 'state-journal.jsonl');
40
+ if (!fs.existsSync(jFile)) return map;
41
+ try {
42
+ const lines = fs.readFileSync(jFile, 'utf8').split('\n');
43
+ for (const line of lines) {
44
+ if (!line.trim()) continue;
45
+ try {
46
+ const item = JSON.parse(line);
47
+ if (item && item.id) {
48
+ if (!map.has(item.id)) map.set(item.id, []);
49
+ map.get(item.id).push(item);
50
+ }
51
+ } catch {}
52
+ }
53
+ } catch {}
54
+ return map;
55
+ })();
56
+
57
+ function getEffectiveRejection(r) {
58
+ // 1. 若工单 frontmatter 显式留存 rejected_by,直接以其为准
59
+ if (r.rejected_by) {
60
+ return {
61
+ rejected_by: String(r.rejected_by).toLowerCase(),
62
+ rejected_at: r.rejected_at || '',
63
+ is_rejected: true
64
+ };
65
+ }
66
+ // 2. 查 state-journal 最近一次 op=reject 记录
67
+ const events = journalEventsMap.get(r.id);
68
+ if (events && events.length) {
69
+ let lastReject = null;
70
+ let deliveredAfter = false;
71
+ for (let i = events.length - 1; i >= 0; i--) {
72
+ const ev = events[i];
73
+ if (ev.op === 'deliver' || ev.op === 'accept') {
74
+ deliveredAfter = true;
75
+ break;
76
+ }
77
+ if (ev.op === 'reject') {
78
+ lastReject = ev;
79
+ break;
80
+ }
81
+ }
82
+ if (lastReject && !deliveredAfter) {
83
+ const by = String(lastReject.rejected_by || lastReject.lane || '').toLowerCase();
84
+ return {
85
+ rejected_by: by,
86
+ rejected_at: lastReject.ts || lastReject.rejected_at || r.rejected_at || '',
87
+ is_rejected: Boolean(by)
88
+ };
89
+ }
90
+ }
91
+ // 3. 保底回退:若工单留有 rejected_at 但流水缺失
92
+ if (r.rejected_at) {
93
+ return {
94
+ rejected_by: String(r.from_lane || '').toLowerCase(),
95
+ rejected_at: r.rejected_at,
96
+ is_rejected: true
97
+ };
98
+ }
99
+ return { rejected_by: '', rejected_at: '', is_rejected: false };
100
+ }
101
+
102
+ // ── 依赖方视角(--for <target>,跨仓)/ --for <lane>(仓内)──
103
+ // 依赖方 agent 用「我的待办」单一入口:只列 target===<target>(或 to_lane===<lane>)且未闭环的交接。
104
+ // 是否计入 pending 见 isPendingFor:draft + forwarded 一律计入(v2.7 修正,不再按 target 区分)。
105
+ let hubCfg = null;
106
+ try {
107
+ const cfgPath = path.join(ROOT, '.handoff-hub.json');
108
+ if (fs.existsSync(cfgPath)) hubCfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
109
+ } catch {}
110
+
111
+ const VALID_TARGETS = new Set(
112
+ hubCfg && Array.isArray(hubCfg.targets) && hubCfg.targets.length
113
+ ? hubCfg.targets.map(s => String(s).toLowerCase())
114
+ : ['frontend', 'backend', 'mobile', 'audit', 'lab']
115
+ );
116
+
117
+ function detectLang() {
118
+ if (process.env.BATON_LANG) {
119
+ return process.env.BATON_LANG.toLowerCase().startsWith('zh') ? 'zh' : 'en';
120
+ }
121
+ if (hubCfg && (hubCfg.locale || hubCfg.lang)) {
122
+ return String(hubCfg.locale || hubCfg.lang).toLowerCase().startsWith('zh') ? 'zh' : 'en';
123
+ }
124
+ const allLabels = [
125
+ ...Object.values((hubCfg && (hubCfg.lane_labels || hubCfg.lane_roles)) || {}),
126
+ ...Object.values((hubCfg && hubCfg.target_labels) || {})
127
+ ];
128
+ if (allLabels.some(r => /[\u4e00-\u9fa5]/.test(String(r)))) {
129
+ return 'zh';
130
+ }
131
+ const envLang = process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || '';
132
+ if (envLang.toLowerCase().startsWith('zh')) {
133
+ return 'zh';
134
+ }
135
+ return 'en';
136
+ }
137
+
138
+ function extractBaggageSessionId(baggage) {
139
+ if (!baggage || typeof baggage !== 'string') return '';
140
+ for (const part of baggage.split(',')) {
141
+ const eqIdx = part.indexOf('=');
142
+ if (eqIdx === -1) continue;
143
+ const k = part.slice(0, eqIdx).trim().toLowerCase();
144
+ if (k === 'codebuddy.session_id' || k === 'workbuddy.session_id' || k === 'session_id') {
145
+ let v = part.slice(eqIdx + 1).split(';')[0].trim();
146
+ try { v = decodeURIComponent(v); } catch {}
147
+ if (v) return v;
148
+ }
149
+ }
150
+ return '';
151
+ }
152
+
153
+ function getSessionId() {
154
+ const envKey = process.env.BATON_SESSION_ID ||
155
+ process.env.ANTIGRAVITY_CONVERSATION_ID ||
156
+ process.env.CURSOR_CONVERSATION_ID ||
157
+ process.env.CLAUDE_CONVERSATION_ID ||
158
+ process.env.CLAUDE_SESSION_ID ||
159
+ process.env.WORKBUDDY_CONVERSATION_ID ||
160
+ process.env.WORKBUDDY_SESSION_ID ||
161
+ process.env.CODEBUDDY_CONVERSATION_ID ||
162
+ process.env.CODEBUDDY_SESSION_ID ||
163
+ process.env.CODEBUDDY_SANDBOX_BROKER_SESSION_ID ||
164
+ process.env.WORKBUDDY_SANDBOX_BROKER_SESSION_ID ||
165
+ process.env.WINDSURF_CONVERSATION_ID ||
166
+ process.env.TERM_SESSION_ID ||
167
+ process.env.SESSION_ID ||
168
+ extractBaggageSessionId(process.env.BAGGAGE);
169
+ if (envKey) return String(envKey).replace(/[^a-zA-Z0-9_-]/g, '_');
170
+ const ppid = process.ppid || 'global';
171
+ return `ppid-${ppid}`;
172
+ }
173
+
174
+ const currentSessionId = getSessionId();
175
+ const ONLY_CURRENT = process.argv.includes('--current') || process.argv.includes('--mine') || process.argv.includes('--this-session');
176
+
177
+ let FOR = '';
178
+ for (let i = 0; i < process.argv.length; i++) {
179
+ if ((process.argv[i] === '--for' || process.argv[i] === '--as') && process.argv[i + 1]) { FOR = process.argv[i + 1].toLowerCase(); break; }
180
+ if (process.argv[i].startsWith('--for=')) { FOR = process.argv[i].slice('--for='.length).toLowerCase(); break; }
181
+ if (process.argv[i].startsWith('--as=')) { FOR = process.argv[i].slice('--as='.length).toLowerCase(); break; }
182
+ }
183
+ if (FOR && MODE !== 'intra-repo' && !VALID_TARGETS.has(FOR)) {
184
+ console.error(`--for 必须是 ${[...VALID_TARGETS].join(' / ')}(收到: ${FOR || '(空)'})`);
185
+ process.exit(2);
186
+ }
187
+ // 仓内模式:--for <lane> 按 .handoff-hub.json 的 lanes 校验(2026-10-18 修)。
188
+ // 原缺校验的后果:lane 拼错 ⇒ mine 为空 ⇒ 输出「✅ 没有待 X 处理的交接」——假阴性,
189
+ // agent 会据此判定「本轮无事可做」而跳过真正的待办(与 v2.7 draft 语义事故同类:可见性缺失)。
190
+ // 配置读不到 ⇒ 不校验(fail-open,宁可漏拦不误伤);intra 模式 ROOT 即 .handoffs/,配置就在 ROOT 下。
191
+ if (FOR && MODE === 'intra-repo') {
192
+ let lanes = [];
193
+ try {
194
+ const cfg = JSON.parse(fs.readFileSync(path.join(ROOT, '.handoff-hub.json'), 'utf8'));
195
+ lanes = (cfg.lanes || []).map(s => String(s).toLowerCase());
196
+ } catch { /* 配置不可读:跳过校验 */ }
197
+ if (lanes.length && !lanes.includes(FOR)) {
198
+ console.error(`--for 必须是 ${lanes.join(' / ')}(来自 .handoff-hub.json 的 lanes;收到: ${FOR})`);
199
+ process.exit(2);
200
+ }
201
+ }
202
+
203
+ // 命名规范:跨仓 <TARGET>-<YYYYMMDD>-<NN>-<TYPE>;仓内 <LANE>-<YYYYMMDD>-<NN>-<TYPE>
204
+ const _TARGET_ALT = [...VALID_TARGETS].map(t => t.toUpperCase()).join('|');
205
+ const ID_RE = MODE === 'intra-repo'
206
+ ? /^(?!README)(?!.*-resp$)([A-Za-z0-9_-]+)$/i
207
+ : new RegExp(`^(${_TARGET_ALT})-\\d{8}-(?:(?:\\d{2}-(?:bug|feature|breaking|question))|(?:\\d{4,6}(?:-\\d{2})?))$`);
208
+
209
+ function parseFM(content) {
210
+ if (!content) return null;
211
+ const m = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);
212
+ if (!m) return null;
213
+ const obj = {};
214
+ for (const line of m[1].split(/\r?\n/)) {
215
+ const idx = line.indexOf(':');
216
+ if (idx === -1) continue;
217
+ const k = line.slice(0, idx).trim();
218
+ let v = line.slice(idx + 1).trim();
219
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
220
+ if (v === 'true') v = true; else if (v === 'false') v = false;
221
+ obj[k] = v;
222
+ }
223
+ // ADR-0008 Phase 3: 统一数据模型归一化(将历史分化字段 needs_iggle_change 自动对齐为 needs_change)
224
+ if (obj.needs_change === undefined && obj.needs_iggle_change !== undefined) {
225
+ obj.needs_change = obj.needs_iggle_change;
226
+ }
227
+ return obj;
228
+ }
229
+
230
+ function listMd(dir) {
231
+ try { return fs.readdirSync(dir).filter(f => f.endsWith('.md') && f.toUpperCase() !== 'README.MD'); }
232
+ catch { return []; }
233
+ }
234
+
235
+ const hFiles = listMd(H_DIR);
236
+ const rFiles = listMd(R_DIR);
237
+ const hFmMap = new Map();
238
+ const rFmMap = new Map();
239
+
240
+ const handoffs = {};
241
+ for (const f of hFiles) {
242
+ let fm = null;
243
+ try { fm = parseFM(fs.readFileSync(path.join(H_DIR, f), 'utf8')); } catch {}
244
+ hFmMap.set(f, fm);
245
+ if (!fm || !fm.handoff_id) continue;
246
+ const rec = {
247
+ id: fm.handoff_id,
248
+ target: fm.target || '',
249
+ type: fm.type || '',
250
+ status: fm.status || 'draft',
251
+ conversation_id: fm.conversation_id || '',
252
+ needs: fm && (fm.needs_change !== undefined ? fm.needs_change : fm.needs_iggle_change),
253
+ created: fm.created || '',
254
+ closed: fm.closed || '',
255
+ delivered_at: fm.delivered_at || '',
256
+ rejected_at: fm.rejected_at || '',
257
+ accepted_at: fm.accepted_at || '',
258
+ reopened_at: fm.reopened_at || '',
259
+ audit_nonce: fm.audit_nonce || '',
260
+ blind: Boolean(fm.blind),
261
+ rejected_by: fm.rejected_by || '',
262
+ file: `handoffs/${f}`,
263
+ };
264
+ // 仓内模式:target 位复用为 to_lane,并补 from_lane / needs_change。跨仓 v1 schema 字段保持冻结。
265
+ if (MODE === 'intra-repo') {
266
+ rec.target = fm.to_lane || fm.target || '';
267
+ rec.to_lane = fm.to_lane || '';
268
+ rec.from_lane = fm.from_lane || '';
269
+ rec.needs = fm.needs_change;
270
+ }
271
+ handoffs[fm.handoff_id] = rec;
272
+ }
273
+
274
+ const receipts = {};
275
+ for (const f of rFiles) {
276
+ let fm = null;
277
+ try { fm = parseFM(fs.readFileSync(path.join(R_DIR, f), 'utf8')); } catch {}
278
+ rFmMap.set(f, fm);
279
+ const id = (fm && fm.handoff_id) || f.replace(/-resp\.md$/i, '').replace(/\.md$/i, '');
280
+ receipts[id] = {
281
+ file: `receipts/${f}`,
282
+ needs: fm && (fm.needs_change !== undefined ? fm.needs_change : fm.needs_iggle_change),
283
+ delivered_at: fm && fm.delivered_at,
284
+ audit_nonce: fm && fm.audit_nonce,
285
+ blind: fm && Boolean(fm.blind)
286
+ };
287
+ }
288
+
289
+ // ── 规范性校验(直接利用内存缓存,0 重复磁盘 I/O)──
290
+ const warnings = [];
291
+ for (const f of hFiles) {
292
+ const base = f.replace(/\.md$/i, '');
293
+ const fm = hFmMap.get(f);
294
+ if (!fm || !fm.handoff_id) { warnings.push(`交接文件缺 frontmatter handoff_id:${f}`); continue; }
295
+ if (base !== fm.handoff_id) warnings.push(`文件名(${base}) 与 frontmatter handoff_id(${fm.handoff_id}) 不一致:${f}`);
296
+ if (!ID_RE.test(fm.handoff_id)) warnings.push(`handoff_id 不符合规范(应为 ${MODE === 'intra-repo' ? '<LANE>-<YYYYMMDD>-<NN>-<TYPE>' : '<TARGET>-<YYYYMMDD>-<NN>-<TYPE>'}):${fm.handoff_id}`);
297
+ }
298
+ for (const f of rFiles) {
299
+ const base = f.replace(/-resp\.md$/i, '').replace(/\.md$/i, '');
300
+ const fm = rFmMap.get(f);
301
+ const id = (fm && fm.handoff_id) || base;
302
+ if (!handoffs[id]) warnings.push(`回执找不到对应交接:${f} (id=${id})`);
303
+ }
304
+
305
+ function formatDurationShort(ms) {
306
+ const sec = Math.floor(ms / 1000);
307
+ if (sec < 60) return `${sec}s`;
308
+ const min = Math.floor(sec / 60);
309
+ if (min < 60) return `${min}m`;
310
+ const hr = Math.floor(min / 60);
311
+ return `${hr}h`;
312
+ }
313
+
314
+ function getWatchInfo(id) {
315
+ const watchFile = path.join(ROOT, '.watch', `${id}.json`);
316
+ let isAlive = false;
317
+ let data = null;
318
+ if (fs.existsSync(watchFile)) {
319
+ try {
320
+ data = JSON.parse(fs.readFileSync(watchFile, 'utf8'));
321
+ if (data) {
322
+ if (Array.isArray(data.watchers) && data.watchers.length > 0) {
323
+ const aliveWatchers = [];
324
+ for (const w of data.watchers) {
325
+ try {
326
+ if (w && w.pid) {
327
+ process.kill(w.pid, 0);
328
+ aliveWatchers.push(w);
329
+ }
330
+ } catch (e) {
331
+ if (e.code === 'EPERM') aliveWatchers.push(w);
332
+ }
333
+ }
334
+ if (aliveWatchers.length > 0) {
335
+ isAlive = true;
336
+ data.watchers = aliveWatchers;
337
+ data.pid = aliveWatchers[0].pid;
338
+ } else {
339
+ isAlive = false;
340
+ try { fs.unlinkSync(watchFile); } catch {}
341
+ }
342
+ } else if (data.pid) {
343
+ try {
344
+ process.kill(data.pid, 0);
345
+ isAlive = true;
346
+ } catch (e) {
347
+ if (e.code === 'EPERM') {
348
+ isAlive = true;
349
+ } else {
350
+ isAlive = false;
351
+ try { fs.unlinkSync(watchFile); } catch {}
352
+ }
353
+ }
354
+ }
355
+ }
356
+ } catch {}
357
+ }
358
+ if (isAlive && data) {
359
+ const started = data.started_at ? new Date(data.started_at).getTime() : 0;
360
+ const elapsed = started ? Math.max(0, Date.now() - started) : 0;
361
+ const durStr = formatDurationShort(elapsed);
362
+ const watcherCount = Array.isArray(data.watchers) ? data.watchers.length : 1;
363
+ const watcherText = watcherCount > 1
364
+ ? `监听: ${watcherCount} 窗口 (首个 pid ${data.pid}, ${durStr})`
365
+ : `监听: pid ${data.pid} (${durStr})`;
366
+ return {
367
+ listening: true,
368
+ pid: data.pid,
369
+ started_at: data.started_at,
370
+ duration: durStr,
371
+ text: watcherText
372
+ };
373
+ }
374
+ return {
375
+ listening: false,
376
+ text: `⚠️ 无监听`
377
+ };
378
+ }
379
+
380
+ function getCreatedTime(r) {
381
+ if (r.created) {
382
+ const t = new Date(r.created).getTime();
383
+ if (!isNaN(t)) return t;
384
+ }
385
+ try {
386
+ const hFile = path.join(ROOT, r.file);
387
+ return fs.statSync(hFile).mtimeMs;
388
+ } catch {
389
+ return 0;
390
+ }
391
+ }
392
+
393
+ function extractConclusion(raw) {
394
+ if (!raw) return '';
395
+ const m = raw.match(/^##\s*(?:结论|Conclusion|Verdict|Status|状态)[^\n]*\n+([\s\S]*?)(?=\n##|$)/im);
396
+ if (m) {
397
+ const lines = m[1].split('\n').map(s => s.trim()).filter(Boolean);
398
+ for (const l of lines) {
399
+ if (l.startsWith('#')) continue;
400
+ const match = l.match(/^(?:[-*]\s*)?(?:\*\*)?(?:结论|Conclusion|Verdict|Status|状态)(?:\*\*)?[::]\s*(.*)$/i);
401
+ if (match && match[1]) {
402
+ const val = match[1].trim();
403
+ return val.length > 50 ? val.slice(0, 50) + '…' : val;
404
+ }
405
+ }
406
+ for (const l of lines) {
407
+ if (l.startsWith('#') || l.startsWith('>')) continue;
408
+ const listMatch = l.match(/^[-*]\s+(.*)$/);
409
+ if (listMatch && listMatch[1] && !listMatch[1].startsWith('**说明**') && !listMatch[1].startsWith('**Note**')) {
410
+ const val = listMatch[1].trim();
411
+ return val.length > 50 ? val.slice(0, 50) + '…' : val;
412
+ }
413
+ if (!l.startsWith('-') && !l.startsWith('*')) {
414
+ return l.length > 50 ? l.slice(0, 50) + '…' : l;
415
+ }
416
+ }
417
+ }
418
+ return '';
419
+ }
420
+
421
+ function getReceiptConclusion(id) {
422
+ const rFile = path.join(R_DIR, `${id}-resp.md`);
423
+ if (!fs.existsSync(rFile)) return '';
424
+ try {
425
+ return extractConclusion(fs.readFileSync(rFile, 'utf8'));
426
+ } catch {
427
+ return '';
428
+ }
429
+ }
430
+
431
+ function isVerdictRejected(verdict) {
432
+ if (!verdict) return false;
433
+ const s = String(verdict).trim();
434
+ if (/^(?:verified|accepted|passed|pass|通过|合规)\b/i.test(s)) return false;
435
+ if (/\b(?:rejected|no-go)\b/i.test(s) || /^(?:reject|fail|failed)\b/i.test(s) || /驳回|不通过|未通过/.test(s)) return true;
436
+ if (/\bfail(?:ed|ure)?s?\b/i.test(s)) {
437
+ if (/(?:fail-open|fail-closed|0\s*fail|no\s*fail|zero\s*fail)/i.test(s)) return false;
438
+ return true;
439
+ }
440
+ return false;
441
+ }
442
+
443
+ function isVerdictBlocked(verdict) {
444
+ if (!verdict) return false;
445
+ const s = String(verdict).trim();
446
+ if (/^(?:verified|accepted|passed|pass|通过|合规)\b/i.test(s)) return false;
447
+ if (/\b(?:incomplete|blocked|waiting|hold)\b/i.test(s) || /受阻|待条件|未完成|真机未到位|等待外部/.test(s)) return true;
448
+ return false;
449
+ }
450
+
451
+ function getReceiptMtime(id) {
452
+ const rFile = path.join(R_DIR, `${id}-resp.md`);
453
+ if (!fs.existsSync(rFile)) return 0;
454
+ try {
455
+ return fs.statSync(rFile).mtimeMs;
456
+ } catch {
457
+ return 0;
458
+ }
459
+ }
460
+
461
+ const SEVEN_DAYS_MS = 7 * 24 * 3600 * 1000;
462
+
463
+ function isTicketActive(r) {
464
+ if (r.status === 'closed') return false;
465
+ let lastAct = 0;
466
+ if (r.created) {
467
+ const t = new Date(r.created).getTime();
468
+ if (!Number.isNaN(t) && t > lastAct) lastAct = t;
469
+ }
470
+ if (r.rejected_at) {
471
+ const t = new Date(r.rejected_at).getTime();
472
+ if (!Number.isNaN(t) && t > lastAct) lastAct = t;
473
+ }
474
+ if (r.delivered_at) {
475
+ const t = new Date(r.delivered_at).getTime();
476
+ if (!Number.isNaN(t) && t > lastAct) lastAct = t;
477
+ }
478
+ const rMtime = getReceiptMtime(r.id);
479
+ if (rMtime > lastAct) lastAct = rMtime;
480
+ const hFile = path.join(H_DIR, `${r.id}.md`);
481
+ try {
482
+ if (fs.existsSync(hFile)) {
483
+ const hMtime = fs.statSync(hFile).mtimeMs;
484
+ if (hMtime > lastAct) lastAct = hMtime;
485
+ }
486
+ } catch {}
487
+ if (!lastAct) return true;
488
+ return (Date.now() - lastAct) < SEVEN_DAYS_MS;
489
+ }
490
+
491
+ function isReceivedIdle(r) {
492
+ if (r.status !== 'received') return false;
493
+ if (r.delivered_at) return false;
494
+ const hFm = hFmMap.get(path.basename(r.file));
495
+ if (hFm && hFm.delivered_at) return false;
496
+ const rObj = receipts[r.id];
497
+ if (rObj && rObj.delivered_at) return false;
498
+
499
+ // 若回执标记 needs_change=true 或 结论为受阻/驳回,绝非等待 deliver 的空转!
500
+ const concl = getReceiptConclusion(r.id);
501
+ if (r.needs === true || (rObj && rObj.needs === true)) return false;
502
+ if (isVerdictRejected(concl) || isVerdictBlocked(concl)) return false;
503
+
504
+ // 依据回执修改时间判定回执草稿停滞,而非工单创建时间
505
+ const rMtime = getReceiptMtime(r.id);
506
+ if (!rMtime) return false;
507
+ const idleMs = Date.now() - rMtime;
508
+ // 超过 7 天属于历史陈旧工单,不作为高频空转告警刷屏(避免高频多窗口排障被历史噪声淹没)
509
+ if (idleMs > SEVEN_DAYS_MS) return false;
510
+ return idleMs >= 10 * 60 * 1000;
511
+ }
512
+
513
+ function getRejectionSummary(r) {
514
+ const rFile = path.join(R_DIR, `${r.id}-resp.md`);
515
+ if (fs.existsSync(rFile)) {
516
+ try {
517
+ const raw = fs.readFileSync(rFile, 'utf8');
518
+ const m = raw.match(/理由[::]\s*([^\n]+)/);
519
+ if (m) return m[1].trim();
520
+ } catch {}
521
+ }
522
+ const events = journalEventsMap.get(r.id);
523
+ if (events) {
524
+ for (let i = events.length - 1; i >= 0; i--) {
525
+ if (events[i].op === 'reject' && events[i].note) {
526
+ return events[i].note;
527
+ }
528
+ }
529
+ }
530
+ return '';
531
+ }
532
+
533
+ const isZh = detectLang() === 'zh';
534
+
535
+ function formatRowLine(r, isZh) {
536
+ const receiptPart = r.receiptFile ? ' ' + (isZh ? '回执:' : 'Receipt:') + r.receiptFile : '';
537
+ const watch = getWatchInfo(r.id);
538
+ const idle = isReceivedIdle(r);
539
+ const idleAlert = idle ? (isZh ? ' ⚠️ [空转告警: received 超 10m 未 deliver]' : ' ⚠️ [空转告警 / Idle Warning: received >10m without deliver]') : '';
540
+ let rejPart = '';
541
+ const effRej = getEffectiveRejection(r);
542
+ if (effRej.is_rejected && (r.status === 'forwarded' || r.status === 'draft')) {
543
+ const reason = getRejectionSummary(r);
544
+ rejPart = isZh
545
+ ? ` ⚠️ [已驳回退回 · 待整改${reason ? ':' + reason.slice(0, 40) : ''}]`
546
+ : ` ⚠️ [REJECTED · Revision required${reason ? ': ' + reason.slice(0, 40) : ''}]`;
547
+ }
548
+ let noncePart = '';
549
+ if (r.to_lane === 'audit') {
550
+ noncePart = r.audit_nonce
551
+ ? ` [Nonce: ${r.audit_nonce}]`
552
+ : (isZh ? ` ⚠️ [Nonce 缺失 · 可运行 baton nonce ${r.id} --reissue 补签]` : ` ⚠️ [Missing Nonce · run baton nonce ${r.id} --reissue]`);
553
+ } else if (r.audit_nonce) {
554
+ noncePart = ` [Nonce: ${r.audit_nonce}]`;
555
+ }
556
+ const blindPart = r.blind ? ' [Blind: true]' : '';
557
+ let sessionPart = '';
558
+ if (r.conversation_id) {
559
+ if (r.conversation_id === currentSessionId) {
560
+ sessionPart = isZh ? ' [本对话]' : ' [This Session]';
561
+ } else {
562
+ const shortConv = r.conversation_id.slice(0, 8);
563
+ sessionPart = isZh ? ` [外部对话: ${shortConv}]` : ` [External: ${shortConv}]`;
564
+ }
565
+ }
566
+ return ` - ${r.id} ${r.file}${receiptPart} [${watch.text}]${noncePart}${blindPart}${sessionPart}${idleAlert}${rejPart}`;
567
+ }
568
+
569
+ const allRows = Object.values(handoffs).map(h => ({
570
+ ...h,
571
+ hasReceipt: !!receipts[h.id],
572
+ receiptFile: receipts[h.id] ? receipts[h.id].file : '',
573
+ audit_nonce: h.audit_nonce || (receipts[h.id] && receipts[h.id].audit_nonce) || '',
574
+ blind: h.blind || (receipts[h.id] && receipts[h.id].blind) || false,
575
+ }));
576
+
577
+ const rows = ONLY_CURRENT ? allRows.filter(r => r.conversation_id === currentSessionId) : allRows;
578
+
579
+ for (const r of rows) {
580
+ if (isReceivedIdle(r)) {
581
+ warnings.push(`[空转告警] 交接 ${r.id} 处于 received 状态超过 10 分钟且未 deliver(发起方监听无法唤醒,请尽快运行 baton deliver ${r.id} 确认交付)`);
582
+ }
583
+ if (r.to_lane === 'audit' && !r.audit_nonce && r.status !== 'closed') {
584
+ warnings.push(isZh
585
+ ? `工单 ${r.id}(to_lane=audit)缺少 Audit Nonce,可运行 baton nonce ${r.id} --reissue 补发`
586
+ : `Ticket ${r.id} (to_lane=audit) missing Audit Nonce, run baton nonce ${r.id} --reissue`);
587
+ }
588
+ }
589
+
590
+ const open = rows.filter(r => r.status !== 'closed');
591
+ const byStatus = {};
592
+ for (const r of open) (byStatus[r.status] = byStatus[r.status] || []).push(r);
593
+ const receiptButStale = open.filter(r => r.hasReceipt && r.status !== 'received' && r.status !== 'delivered' && r.status !== 'closed' && !r.rejected_at);
594
+
595
+ // ── 下一步导航 ──
596
+ // 状态名中文化 + 每项给出「谁该做什么」,消除「看到状态名却不知下一步」的记忆负担。
597
+ // v2.12.5 · P1-b 标签分区:仓内 draft/forwarded 渲染「待执行」——原「待转递/已转递」是跨仓
598
+ // 口吻(发起方视角的转递进度),放在仓内会被读成「已发出去、有人接手了」,误导执行 lane 不动工
599
+ // (同仓新单天生停在 draft,标签还说「待转递」= 暗示『不该我处理』)。跨仓标签保持不变。
600
+
601
+ const STATUS_LABEL = isZh
602
+ ? (MODE === 'intra-repo'
603
+ ? { draft: '待执行', forwarded: '待执行', received: '已写回执', delivered: '已交付(待验收)', closed: '已闭环' }
604
+ : { draft: '待转递', forwarded: '已转递', received: '已写回执', delivered: '已交付(待验收)', closed: '已闭环' })
605
+ : (MODE === 'intra-repo'
606
+ ? { draft: 'Pending Execution', forwarded: 'Pending Execution', received: 'Receipt Drafted', delivered: 'Delivered (Pending Acceptance)', closed: 'Closed' }
607
+ : { draft: 'Draft', forwarded: 'Forwarded', received: 'Receipt Drafted', delivered: 'Delivered (Pending Acceptance)', closed: 'Closed' });
608
+
609
+ // 只引导固定命令(/inbox、/sync),不带 <ID> 的 /handoff 子命令——带 ID 命令用户记不住。
610
+ function nextStep(r) {
611
+ if (MODE === 'intra-repo') {
612
+ // v2.12.5:仓内下一步给动作而非只给状态复读——「lane=x · 待执行」读者仍不知道该干嘛;
613
+ // 对齐 --for 视图的 nextStepFor,让中央视图每项自带「读→写」动作。
614
+ const lane = r.to_lane || '?';
615
+ if (r.status === 'received') {
616
+ const concl = getReceiptConclusion(r.id);
617
+ const isBlocked = (r.needs === true) || (receipts[r.id] && receipts[r.id].needs === true) || isVerdictRejected(concl) || isVerdictBlocked(concl);
618
+ if (isBlocked) {
619
+ return isZh
620
+ ? `lane=${lane} · 审计未通过/受阻待整改(${concl ? concl.slice(0, 30) : 'needs_change=true'}):等待发起方(${r.from_lane || '发起方'})整改或补齐条件,严禁执行 deliver`
621
+ : `lane=${lane} · Receipt incomplete/blocked (${concl ? concl.slice(0, 30) : 'needs_change=true'}): awaiting initiator (${r.from_lane || 'initiator'}), do not deliver`;
622
+ }
623
+ return isZh
624
+ ? `lane=${lane} · 已写回执草稿(等执行方 baton deliver 交付)`
625
+ : `lane=${lane} · Receipt drafted (awaiting executor baton deliver)`;
626
+ }
627
+ if (r.status === 'delivered') {
628
+ return isZh
629
+ ? `lane=${lane} · 已交付(等发起 lane 实测后 close)`
630
+ : `lane=${lane} · Delivered (awaiting initiator verification to close)`;
631
+ }
632
+ if (r.status === 'closed') {
633
+ return isZh ? `lane=${lane} · 已闭环` : `lane=${lane} · Closed`;
634
+ }
635
+ if (r.rejected_at && (r.status === 'forwarded' || r.status === 'draft')) {
636
+ return isZh
637
+ ? `lane=${lane} · 【驳回重做】查看回执「驳回记录」完成整改并重新 baton deliver`
638
+ : `lane=${lane} · 【Rejected/Rework】Revise per rejection record & baton deliver`;
639
+ }
640
+ return isZh
641
+ ? `lane=${lane} · 待执行:读 ${r.file} 开工 → 写 receipts/${r.id}-resp.md`
642
+ : `lane=${lane} · Pending: read ${r.file} → write receipts/${r.id}-resp.md`;
643
+ }
644
+ const t = (r.target || '').toLowerCase();
645
+ switch (r.status) {
646
+ case 'draft':
647
+ if (t === 'coreml') return isZh ? '同工作区,不用请人转交:切 coreml 角色直接做 → 写回执' : 'Same workspace: switch to coreml role → write receipt';
648
+ if (t === 'iggle') return isZh ? '依赖方发起,iggle 侧适配本仓' : 'Initiated by dependency, adapter work';
649
+ return isZh ? `待转递:输 /inbox 生成收件箱转给 ${t}` : `Pending forward: pass to ${t}`;
650
+ case 'forwarded':
651
+ if (t === 'coreml') return isZh ? '规格已定稿,可开工(切 coreml 角色)' : 'Spec finalized, ready to execute (coreml)';
652
+ if (t === 'iggle') return isZh ? '已转递,等 iggle 适配回执' : 'Forwarded, awaiting adapter receipt';
653
+ return isZh ? `已转递,等 ${t} 回执(回执到后输 /sync 登记)` : `Forwarded, awaiting ${t} receipt`;
654
+ case 'received':
655
+ if (t === 'iggle') return isZh ? '已写回执草稿,等执行方 deliver 交付' : 'Receipt drafted, awaiting delivery';
656
+ return isZh ? `已收 ${t} 回执草稿:等待终态交付 (baton deliver)` : `Received ${t} draft: awaiting baton deliver`;
657
+ case 'delivered':
658
+ if (t === 'iggle') return isZh ? '已终态交付,等独立实测后闭环' : 'Delivered, awaiting verification';
659
+ return isZh ? `已收 ${t} 终态交付:发起方独立实测后闭环` : `Delivered by ${t}: verify independently then close`;
660
+ default:
661
+ return '';
662
+ }
663
+ }
664
+
665
+ // ── `draft` 对依赖方 = 待处理,不是「尚未转递」(v2.7 修正)──
666
+ // 2026-09-04 事故根因:用户常把交接文档直接交给依赖方而不跑 `forward`,
667
+ // 旧逻辑把 draft 排除在依赖方待办之外 → SWOOP-20260904-02 被误判「不属于本轮范围」。
668
+ // `forward` 只是 iggle 侧可选的事后标记,**不是「已送达」的可靠信号**。
669
+ // 故:draft / forwarded 一律计入 pending;received / delivered = 已回执/已交付(不 pending);closed 不列出。
670
+ // 「是否落到我手上」的可靠判据只有两条:① target === 当前工作区;② 用户直接给了文档
671
+ // 或它出现在本命令的输出里。**不要用 draft/forwarded 判断该不该开工。**
672
+ function isPendingFor(_target, status) {
673
+ if (status === 'closed' || status === 'received' || status === 'delivered') return false;
674
+ if (status === 'draft' || status === 'forwarded') return true;
675
+ return false;
676
+ }
677
+
678
+ // ── 依赖方视角的「下一步」导航 ──
679
+ // 与中心视角 nextStep 相反:这里「我」= target,只有 isPendingFor() 为真的项才进 pending。
680
+ function nextStepFor(r) {
681
+ if (MODE === 'intra-repo') {
682
+ if (r.status === 'received') {
683
+ const concl = getReceiptConclusion(r.id);
684
+ const isBlocked = (r.needs === true) || (receipts[r.id] && receipts[r.id].needs === true) || isVerdictRejected(concl) || isVerdictBlocked(concl);
685
+ if (isBlocked) {
686
+ return isZh
687
+ ? `审计未通过/受阻待整改(${concl ? concl.slice(0, 30) : 'needs_change=true'}):等待发起方(${r.from_lane || '发起方'})处理,严禁执行 deliver`
688
+ : `Receipt incomplete/blocked (${concl ? concl.slice(0, 30) : 'needs_change=true'}): awaiting initiator (${r.from_lane || 'initiator'}), do not deliver`;
689
+ }
690
+ return isZh
691
+ ? '已写回执草稿,请在会话收尾时运行 baton deliver 交付'
692
+ : 'Receipt drafted, run baton deliver when wrapping up';
693
+ }
694
+ if (r.status === 'delivered') {
695
+ return isZh
696
+ ? '已终态交付,等发起 lane 独立实测后 close'
697
+ : 'Delivered, awaiting initiator verification to close';
698
+ }
699
+ const eff = getEffectiveRejection(r);
700
+ if (eff.is_rejected && (r.status === 'forwarded' || r.status === 'draft')) {
701
+ return isZh
702
+ ? `【驳回重做】查看回执 receipts/${r.id}-resp.md 驳回记录完成整改 → 更新回执并 baton deliver`
703
+ : `【Rejected/Rework】Revise per receipts/${r.id}-resp.md rejection record → update receipt & baton deliver`;
704
+ }
705
+ return isZh
706
+ ? `读 handoffs/${r.id}.md 开工 → 写 receipts/${r.id}-resp.md`
707
+ : `Read handoffs/${r.id}.md to start → write receipts/${r.id}-resp.md`;
708
+ }
709
+ const t = (r.target || '').toLowerCase();
710
+ switch (r.status) {
711
+ case 'draft':
712
+ // v2.7 起所有 target 的 draft 都进 pending
713
+ return t === 'coreml'
714
+ ? (isZh ? `同工作区,读完交接即可切 coreml 角色开工 → 写 receipts/${r.id}-resp.md` : `Same workspace: read handoff and start as coreml → write receipts/${r.id}-resp.md`)
715
+ : (isZh ? `待 ${t} 处理:读 handoffs/${r.id}.md 直接开工 → 写 receipts/${r.id}-resp.md` : `Pending for ${t}: read handoffs/${r.id}.md to start → write receipts/${r.id}-resp.md`);
716
+ case 'forwarded':
717
+ return t === 'coreml'
718
+ ? (isZh ? `规格已定稿,切 coreml 角色开工 → 写 receipts/${r.id}-resp.md` : `Spec finalized, start as coreml → write receipts/${r.id}-resp.md`)
719
+ : (isZh ? `已转递,读 handoffs/${r.id}.md 直接开工 → 写 receipts/${r.id}-resp.md` : `Forwarded: read handoffs/${r.id}.md to start → write receipts/${r.id}-resp.md`);
720
+ case 'received':
721
+ return isZh ? '回执草稿已登记,请在收尾时运行 baton deliver 交付' : 'Receipt drafted, run baton deliver to finalize';
722
+ case 'delivered':
723
+ return isZh ? '已终态交付,等发起方独立实测后 close' : 'Delivered, awaiting verification to close';
724
+ default:
725
+ return '';
726
+ }
727
+ }
728
+
729
+ if (FOR) {
730
+ // 依赖方视角:只列 target===FOR(跨仓)或 to_lane===FOR(仓内)且未闭环;pending 按角色语义过滤(isPendingFor)。
731
+ const laneMatch = (r) => {
732
+ if (MODE === 'intra-repo') {
733
+ const eff = getEffectiveRejection(r);
734
+ if (r.to_lane === FOR) {
735
+ // 我已驳回退回给对方的项在等待对方整改,不计入我方待办
736
+ return eff.is_rejected ? eff.rejected_by !== FOR : true;
737
+ }
738
+ // 对方驳回给我的项(我是发起方),落入我方整改待办
739
+ if (r.from_lane === FOR && eff.is_rejected && eff.rejected_by !== FOR) {
740
+ return true;
741
+ }
742
+ return false;
743
+ }
744
+ return r.target === FOR;
745
+ };
746
+ const mineAll = rows.filter(r => laneMatch(r) && r.status !== 'closed');
747
+ const mine = ACTIVE_ONLY ? mineAll.filter(isTicketActive) : mineAll;
748
+ if (JSON_MODE) {
749
+ if (JSON_V2) {
750
+ const pending = mine.filter(r => isPendingFor(FOR, r.status) && (!getEffectiveRejection(r).is_rejected || getEffectiveRejection(r).rejected_by !== FOR)).map(r => ({
751
+ handoff_id: r.id,
752
+ status: r.status,
753
+ path: r.file,
754
+ }));
755
+ const closedForTarget = rows.filter(r => laneMatch(r) && r.status === 'closed').length;
756
+ const counts = {
757
+ pending: pending.length,
758
+ received: mine.filter(r => r.status === 'received').length,
759
+ closed: closedForTarget,
760
+ draft: mine.filter(r => r.status === 'draft').length,
761
+ };
762
+ console.log(JSON.stringify({ target: FOR, pending, counts }, null, 2));
763
+ } else {
764
+ console.log(JSON.stringify({ root: ROOT, for: FOR, total: mine.length, open: mine.length, warnings, rows: mine }, null, 2));
765
+ }
766
+ process.exit(0);
767
+ }
768
+ const todo = mine.filter(r => isPendingFor(FOR, r.status) && (!getEffectiveRejection(r).is_rejected || getEffectiveRejection(r).rejected_by !== FOR));
769
+ const recv = mine.filter(r => r.status === 'received');
770
+ const isRecvBlocked = (r) => (r.needs === true) || (receipts[r.id] && receipts[r.id].needs === true) || isVerdictRejected(getReceiptConclusion(r.id)) || isVerdictBlocked(getReceiptConclusion(r.id));
771
+ const recvBlocked = recv.filter(isRecvBlocked);
772
+ const recvReady = recv.filter(r => !isRecvBlocked(r));
773
+ const deliv = mine.filter(r => r.status === 'delivered');
774
+
775
+ const rejectedByMe = (MODE === 'intra-repo')
776
+ ? rows.filter(r => {
777
+ const eff = getEffectiveRejection(r);
778
+ return eff.is_rejected && eff.rejected_by === FOR && r.status !== 'closed' && (r.status === 'forwarded' || r.status === 'draft');
779
+ })
780
+ : [];
781
+ const rejectedToMe = (MODE === 'intra-repo')
782
+ ? rows.filter(r => {
783
+ const eff = getEffectiveRejection(r);
784
+ return eff.is_rejected && eff.rejected_by !== FOR && r.from_lane === FOR && r.status !== 'closed' && (r.status === 'forwarded' || r.status === 'draft');
785
+ })
786
+ : [];
787
+ const sessionTagZh = ONLY_CURRENT ? ` · 本会话过滤 (${currentSessionId.slice(0, 8)})` : '';
788
+ const sessionTagEn = ONLY_CURRENT ? ` · Session Filter (${currentSessionId.slice(0, 8)})` : '';
789
+ const lines = [];
790
+ if (isZh) {
791
+ lines.push(`[交接追踪 · ${ROOT}${sessionTagZh}] ${FOR} 未闭环 ${mine.length} 项(${MODE === 'intra-repo' ? 'lane' : 'target'}=${FOR})`);
792
+ if (mine.length === 0 && rejectedByMe.length === 0 && rejectedToMe.length === 0) {
793
+ lines.push(ONLY_CURRENT ? `✅ 当前会话没有待 ${FOR} 处理的交接。` : `✅ 没有待 ${FOR} 处理的交接。`);
794
+ } else {
795
+ if (todo.length) {
796
+ lines.push(`- 待 ${FOR} 处理(${todo.length}):`);
797
+ for (const r of todo) {
798
+ lines.push(formatRowLine(r, true));
799
+ const step = nextStepFor(r);
800
+ if (step) lines.push(` → 下一步:${step}`);
801
+ }
802
+ }
803
+ if (rejectedToMe.length) {
804
+ lines.push(`- 收到驳回待整改(由 ${rejectedToMe[0].rejected_by || '对方'} 驳回 · ${rejectedToMe.length}):`);
805
+ for (const r of rejectedToMe) {
806
+ lines.push(formatRowLine(r, true));
807
+ lines.push(` → 下一步:查看回执「驳回记录」完成整改后 baton forward ${r.id} 或补充条件重新转递`);
808
+ }
809
+ }
810
+ if (rejectedByMe.length) {
811
+ lines.push(`- 我方已驳回退回(等待执行方整改并重新交付 · ${rejectedByMe.length}):`);
812
+ for (const r of rejectedByMe) {
813
+ lines.push(formatRowLine(r, true));
814
+ lines.push(` → 状态:已驳回退回给 lane=${r.to_lane === FOR ? r.from_lane : r.to_lane},等待其整改并重新交付`);
815
+ }
816
+ }
817
+ if (recvBlocked.length) {
818
+ lines.push(`- 审计未通过/受阻待处理(${recvBlocked.length}):`);
819
+ for (const r of recvBlocked) {
820
+ lines.push(formatRowLine(r, true));
821
+ const step = nextStepFor(r);
822
+ if (step) lines.push(` → 下一步:${step}`);
823
+ }
824
+ }
825
+ if (recvReady.length) {
826
+ lines.push(`- 已写回执待终态交付(${recvReady.length}):`);
827
+ for (const r of recvReady) {
828
+ lines.push(formatRowLine(r, true));
829
+ const step = nextStepFor(r);
830
+ if (step) lines.push(` → 下一步:${step}`);
831
+ }
832
+ }
833
+ if (deliv.length) {
834
+ lines.push(MODE === 'intra-repo'
835
+ ? `- 已交付待发起 lane 实测(${deliv.length}):`
836
+ : `- 已交付待发起方实测(${deliv.length}):`);
837
+ for (const r of deliv) {
838
+ lines.push(formatRowLine(r, true));
839
+ const step = nextStepFor(r);
840
+ if (step) lines.push(` → 下一步:${step}`);
841
+ }
842
+ }
843
+ }
844
+ if (warnings.length) {
845
+ lines.push('⚠️ 规范性问题(请修正以免影响 agent 识别):');
846
+ for (const w of warnings) lines.push(` - ${w}`);
847
+ }
848
+ } else {
849
+ lines.push(`[Baton Status · ${ROOT}${sessionTagEn}] ${FOR}: ${mine.length} open item(s) (${MODE === 'intra-repo' ? 'lane' : 'target'}=${FOR})`);
850
+ if (mine.length === 0 && rejectedByMe.length === 0 && rejectedToMe.length === 0) {
851
+ lines.push(ONLY_CURRENT ? `✅ No pending handoffs for ${FOR} in current session.` : `✅ No pending handoffs for ${FOR}.`);
852
+ } else {
853
+ if (todo.length) {
854
+ lines.push(`- Pending for ${FOR} (${todo.length}):`);
855
+ for (const r of todo) {
856
+ lines.push(formatRowLine(r, false));
857
+ const step = nextStepFor(r);
858
+ if (step) lines.push(` → Next step: ${step}`);
859
+ }
860
+ }
861
+ if (rejectedToMe.length) {
862
+ lines.push(`- Rejections received awaiting revision (${rejectedToMe.length}):`);
863
+ for (const r of rejectedToMe) {
864
+ lines.push(formatRowLine(r, false));
865
+ lines.push(` → Next step: Revise per rejection record in receipt → baton forward ${r.id}`);
866
+ }
867
+ }
868
+ if (rejectedByMe.length) {
869
+ lines.push(`- My rejections awaiting revision (${rejectedByMe.length}):`);
870
+ for (const r of rejectedByMe) {
871
+ lines.push(formatRowLine(r, false));
872
+ lines.push(` → Status: Rejected back to lane=${r.to_lane === FOR ? r.from_lane : r.to_lane}, awaiting revision & deliver`);
873
+ }
874
+ }
875
+ if (recvBlocked.length) {
876
+ lines.push(`- Incomplete / Blocked / Revision Needed (${recvBlocked.length}):`);
877
+ for (const r of recvBlocked) {
878
+ lines.push(formatRowLine(r, false));
879
+ const step = nextStepFor(r);
880
+ if (step) lines.push(` → Next step: ${step}`);
881
+ }
882
+ }
883
+ if (recvReady.length) {
884
+ lines.push(`- Draft receipts awaiting final delivery (${recvReady.length}):`);
885
+ for (const r of recvReady) {
886
+ lines.push(formatRowLine(r, false));
887
+ const step = nextStepFor(r);
888
+ if (step) lines.push(` → Next step: ${step}`);
889
+ }
890
+ }
891
+ if (deliv.length) {
892
+ lines.push(MODE === 'intra-repo'
893
+ ? `- Delivered, awaiting initiator verification (${deliv.length}):`
894
+ : `- Delivered, awaiting verification (${deliv.length}):`);
895
+ for (const r of deliv) {
896
+ lines.push(formatRowLine(r, false));
897
+ const step = nextStepFor(r);
898
+ if (step) lines.push(` → Next step: ${step}`);
899
+ }
900
+ }
901
+ }
902
+ if (warnings.length) {
903
+ lines.push('⚠️ Compliance issues:');
904
+ for (const w of warnings) lines.push(` - ${w}`);
905
+ }
906
+ }
907
+ console.log(lines.join('\n'));
908
+ process.exit(0);
909
+ }
910
+
911
+ if (JSON_MODE) {
912
+ console.log(JSON.stringify({ root: ROOT, total: rows.length, open: open.length, warnings, rows }, null, 2));
913
+ process.exit(0);
914
+ }
915
+
916
+ const lines = [];
917
+ let openDisplay = open;
918
+ let foldedCount = 0;
919
+ if (ACTIVE_ONLY) {
920
+ openDisplay = open.filter(isTicketActive);
921
+ foldedCount = open.length - openDisplay.length;
922
+ } else if (!SHOW_ALL && open.length > 5) {
923
+ openDisplay = open.filter(isTicketActive);
924
+ foldedCount = open.length - openDisplay.length;
925
+ }
926
+
927
+ const byStatusDisplay = {};
928
+ for (const r of openDisplay) (byStatusDisplay[r.status] = byStatusDisplay[r.status] || []).push(r);
929
+
930
+ if (isZh) {
931
+ const sessionTagZh = ONLY_CURRENT ? ` · 本会话过滤 (${currentSessionId.slice(0, 8)})` : '';
932
+ if (ACTIVE_ONLY) {
933
+ lines.push(`[交接追踪 · ${ROOT}${sessionTagZh}] 进行中 ${openDisplay.length} 项活跃(已聚焦折叠 ${foldedCount} 项历史沉睡工单 / 累计 ${open.length} 项)/ 总计 ${rows.length} 项`);
934
+ } else if (foldedCount > 0) {
935
+ lines.push(`[交接追踪 · ${ROOT}${sessionTagZh}] 进行中 ${open.length} 项(当前展示活跃 ${openDisplay.length} 项 / 已聚焦折叠 ${foldedCount} 项)/ 总计 ${rows.length} 项`);
936
+ } else {
937
+ lines.push(`[交接追踪 · ${ROOT}${sessionTagZh}] 进行中 ${open.length} 项 / 总计 ${rows.length} 项`);
938
+ }
939
+ if (rows.length === 0) {
940
+ lines.push(ONLY_CURRENT ? '✅ 当前会话无关联待办工单。' : '✅ 公共交接目录为空(或已全部闭环)。');
941
+ } else {
942
+ const buckets = MODE === 'intra-repo'
943
+ ? [
944
+ ['待执行', openDisplay.filter(r => r.status === 'draft' || r.status === 'forwarded')],
945
+ ['已收回执', byStatusDisplay.received || []],
946
+ ...[...new Set(openDisplay.map(r => r.status))].sort()
947
+ .filter(st => !['draft', 'forwarded', 'received'].includes(st))
948
+ .map(st => [STATUS_LABEL[st] || st, byStatusDisplay[st]]),
949
+ ].filter(([, arr]) => arr.length)
950
+ : [...new Set(openDisplay.map(r => r.status))].sort().map(st => [STATUS_LABEL[st] || st, byStatusDisplay[st]]);
951
+ for (const [label, arr] of buckets) {
952
+ lines.push(`- ${label}(${arr.length}):`);
953
+ for (const r of arr) {
954
+ lines.push(formatRowLine(r, true));
955
+ const step = nextStep(r);
956
+ if (step) lines.push(` → 下一步:${step}`);
957
+ }
958
+ }
959
+ if (foldedCount > 0) {
960
+ lines.push(`\nℹ️ [看板聚焦] 已折叠 ${foldedCount} 个超过 7 天未更新的历史工单(可使用 baton status --all 展开全量)。`);
961
+ }
962
+ if (receiptButStale.length) {
963
+ lines.push(MODE === 'intra-repo'
964
+ ? '⚠️ 已收到回执但未翻状态(仓内:发起 lane 跑 handoff receipt <id> 登记回执并翻 received):'
965
+ : '⚠️ 已收到回执但未翻状态(请核对是否需升依赖版本 / 改调用):');
966
+ for (const r of receiptButStale) lines.push(` - ${r.id}`);
967
+ }
968
+ }
969
+ if (warnings.length) {
970
+ lines.push('⚠️ 规范性问题(请修正以免影响 agent 识别):');
971
+ for (const w of warnings) lines.push(` - ${w}`);
972
+ }
973
+ } else {
974
+ const sessionTagEn = ONLY_CURRENT ? ` · Session Filter (${currentSessionId.slice(0, 8)})` : '';
975
+ if (ACTIVE_ONLY) {
976
+ lines.push(`[Baton Status · ${ROOT}${sessionTagEn}] In Progress: ${openDisplay.length} active (${foldedCount} folded / ${open.length} total ongoing) / Total: ${rows.length}`);
977
+ } else if (foldedCount > 0) {
978
+ lines.push(`[Baton Status · ${ROOT}${sessionTagEn}] In Progress: ${open.length} (Showing Active: ${openDisplay.length} / Folded: ${foldedCount}) / Total: ${rows.length}`);
979
+ } else {
980
+ lines.push(`[Baton Status · ${ROOT}${sessionTagEn}] In Progress: ${open.length} / Total: ${rows.length}`);
981
+ }
982
+ if (rows.length === 0) {
983
+ lines.push(ONLY_CURRENT ? '✅ No active tickets associated with the current session.' : '✅ Hub directory is empty (or all handoffs are closed).');
984
+ } else {
985
+ const buckets = MODE === 'intra-repo'
986
+ ? [
987
+ ['Pending Execution', openDisplay.filter(r => r.status === 'draft' || r.status === 'forwarded')],
988
+ ['Receipt Submitted', byStatusDisplay.received || []],
989
+ ...[...new Set(openDisplay.map(r => r.status))].sort()
990
+ .filter(st => !['draft', 'forwarded', 'received'].includes(st))
991
+ .map(st => [STATUS_LABEL[st] || st, byStatusDisplay[st]]),
992
+ ].filter(([, arr]) => arr.length)
993
+ : [...new Set(openDisplay.map(r => r.status))].sort().map(st => [STATUS_LABEL[st] || st, byStatusDisplay[st]]);
994
+ for (const [label, arr] of buckets) {
995
+ lines.push(`- ${label} (${arr.length}):`);
996
+ for (const r of arr) {
997
+ lines.push(formatRowLine(r, false));
998
+ const step = nextStep(r);
999
+ if (step) lines.push(` → Next step: ${step}`);
1000
+ }
1001
+ }
1002
+ if (foldedCount > 0) {
1003
+ lines.push(`\nℹ️ [View Focus] Folded ${foldedCount} dormant tickets older than 7 days (use baton status --all to display all).`);
1004
+ }
1005
+ if (receiptButStale.length) {
1006
+ lines.push(MODE === 'intra-repo'
1007
+ ? '⚠️ Receipt received but status not updated (run baton receipt <id> to register):'
1008
+ : '⚠️ Receipt received but status not updated:');
1009
+ for (const r of receiptButStale) lines.push(` - ${r.id}`);
1010
+ }
1011
+ }
1012
+ if (warnings.length) {
1013
+ lines.push('⚠️ Compliance issues:');
1014
+ for (const w of warnings) lines.push(` - ${w}`);
1015
+ }
1016
+ }
1017
+ console.log(lines.join('\n'));