harnessed 4.48.0 → 4.49.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README-en.md CHANGED
@@ -491,6 +491,7 @@ planning-with-files /plan (cross-cutting tool) → write artifacts to .planning/
491
491
  | `harnessed gates <master>` | Evaluate which sub-workflows fire for a master stage (JSON: fire/skip/parallelism). Used by slash commands to orchestrate native spawns. |
492
492
  | `harnessed prompt <sub>` | Output a spawn-ready prompt (role + checklist + disciplines + completion/clarification protocols) for a sub-workflow. |
493
493
  | `harnessed checkpoint <action> <sub>` | Record sub-workflow start/complete/fail to `~/.claude/harnessed/checkpoints/`. |
494
+ | `harnessed checkpoint adopt [--from <host>]` | Cross-host relay: read-only copy of the other host's active workflow slot into this host's state root; the source is never modified; `--from <host>` overrides the inferred source host. |
494
495
  | `harnessed` (no args) | Zero-arg you-are-here: active-workflow dashboard + `NEXT: auto\|manual\|done` + run hint; `--json` machine-readable; no active workflow → onboarding hint (comet `/comet` analog, read-only). |
495
496
  | `harnessed next` | Deterministic next-step contract. Within a workflow: `NEXT: auto\|manual\|done`. When the workflow's subs are all resolved it falls through to the next **cross-unit** (next phase/task derived from `.planning/` disk state) with an exit-code contract (`0` advance · `2` done · `10` blocked). |
496
497
  | `harnessed advance` | Forward continuation — print the next work unit (next phase/task) across the milestone and the command to run it. Print-only (the main session runs the next `/auto`); refuses to step past an incomplete earlier phase (`--force` overrides); `--json` drives a `while harnessed advance --json; do :; done` loop. |
package/README.md CHANGED
@@ -489,6 +489,7 @@ planning-with-files /plan (cross-cutting tool) → write artifacts to .planning/
489
489
  | `harnessed gates <master>` | 评估某 master stage 下哪些 sub-workflow 会 fire (JSON: fire/skip/parallelism)。供 slash command 编排 native spawn |
490
490
  | `harnessed prompt <sub>` | 输出某 sub-workflow 的 spawn-ready prompt (role + checklist + disciplines + completion/clarification 协议) |
491
491
  | `harnessed checkpoint <action> <sub>` | 记录 sub-workflow 的 start/complete/fail 到 `~/.claude/harnessed/checkpoints/` |
492
+ | `harnessed checkpoint adopt [--from <host>]` | 记录到当前宿主的状态根;跨宿主接力:把另一宿主的活跃 workflow 槽位只读复制过来,源不动,默认从另一宿主推断,`--from <host>` 指定 |
492
493
  | `harnessed` (无参数) | Zero-arg you-are-here: active-workflow 仪表盘 + `NEXT: auto\|manual\|done` + run hint;`--json` 机器可读;无 active workflow → onboarding hint (comet `/comet` 类比,read-only) |
493
494
  | `harnessed next` | 确定性的下一步契约。workflow 内: `NEXT: auto\|manual\|done`。当 workflow 的所有 sub 都已解决,它会落到下一 **cross-unit** (下一 phase/task,从 `.planning/` 磁盘状态派生),带 exit-code 契约 (`0` advance · `2` done · `10` blocked) |
494
495
  | `harnessed advance` | Forward continuation —— 打印跨 milestone 的下一工作单元 (下一 phase/task) 及运行它的命令。Print-only (由主 session 运行下一个 `/auto`);拒绝越过未完成的更早 phase (`--force` 覆盖);`--json` 驱动 `while harnessed advance --json; do :; done` 循环 |
@@ -0,0 +1,452 @@
1
+ #!/usr/bin/env node
2
+ // biome-ignore-all format: esbuild-generated (hook drift gate owns this file)
3
+ // biome-ignore-all lint: esbuild-generated
4
+ // biome-ignore-all assist/source/organizeImports: esbuild-generated
5
+
6
+ // src/cli/checkDocs.ts
7
+ import { existsSync, readFileSync as readFileSync2 } from "node:fs";
8
+ import { join as join2 } from 'node:path'
9
+
10
+ // src/i18n/index.ts
11
+ import { readFileSync } from 'node:fs'
12
+ import { dirname, join, resolve } from 'node:path'
13
+ import { fileURLToPath } from 'node:url'
14
+
15
+ // messages/en.json
16
+ var en_default = {
17
+ 'setup.workflows_not_found': 'error: workflows directory not found at {{path}}',
18
+ 'setup.nothing_to_install':
19
+ 'setup: no workflow directories with SKILL.md found \u2014 nothing to install',
20
+ 'setup.dry_run.header': '[dry-run] setup would install {{count}} workflow(s) to {{path}}:',
21
+ 'setup.dry_run.run_hint': ' run without --dry-run to execute',
22
+ 'setup.copy_failed': ' error: failed to copy {{name}}: {{message}}',
23
+ 'setup.step_a_complete': 'Step A: {{count}} workflows installed to {{path}}',
24
+ 'setup.step_a_render.complete': ' generated {{count}}/{{total}} command files',
25
+ 'setup.step_a_render.warnings_header':
26
+ ' [A.5] warnings \u2014 some capability cmds could not be fully resolved:',
27
+ 'setup.step_c.created': ' [C] created {{path}} + enabled Agent Teams',
28
+ 'setup.step_c.already_enabled': ' [C] Agent Teams already enabled ({{path}})',
29
+ 'setup.step_c.enabled_backup':
30
+ ' [C] enabled Agent Teams in {{path}} (backup saved \u2192 {{backupPath}})',
31
+ 'setup.step_c.skipped': ' [C] Agent Teams enable skipped: {{message}}',
32
+ 'setup.step_d.created': ' [D] created {{path}} + wrote env.HARNESSED_USER_LANG={{lang}}',
33
+ 'setup.step_d.already_set':
34
+ ' [D] env.HARNESSED_USER_LANG={{lang}} already set in {{path}} \u2014 respecting user override',
35
+ 'setup.step_d.enabled_backup':
36
+ ' [D] wrote env.HARNESSED_USER_LANG={{lang}} in {{path}} (backup saved \u2192 {{backupPath}})',
37
+ 'setup.step_d.skipped': ' [D] User language write skipped: {{message}}',
38
+ 'setup.step_b_complete':
39
+ 'Upstream components: {{installed}} installed / {{already}} already-installed / {{skipped}} skipped / {{failed}} failed [{{seconds}}s]',
40
+ 'setup.complete':
41
+ 'setup complete \u2014 {{skills}} workflows + {{manifests}} base manifests configured',
42
+ 'setup.mcp_hint': 'Run /mcp in Claude Code to verify MCP server connections.',
43
+ 'setup.mcp_hint_codex': 'Run codex mcp list to verify MCP server connections.',
44
+ 'setup.search_key_hint.header':
45
+ '\n\u26A0 Search MCP API keys missing \u2014 the server(s) below are installed but will fail at query time until the key is configured:',
46
+ 'setup.search_key_hint.line':
47
+ ' {{server}}: set {{envVar}} \u2014 add it to the ~/.claude/settings.json "env" block (e.g. {"env": {"{{envVar}}": "<your-key>"}}) or export {{envVar}} in your shell',
48
+ 'setup.optional_offer.ecc_note':
49
+ " ecc (bonus tier): installing it unlocks finer-grained scenario orchestration (per-language review/build expert routing etc.); the trade-off is ~20k+ tokens/session of static listing overhead \u2014 inherent to ECC's own scale (281 skills / 94 commands / 67 agents), not introduced by harnessed.",
50
+ 'setup.bundled_summary':
51
+ '\nharnessed workflows bundled at <packageRoot>/workflows/ (share-only, read-only)',
52
+ 'setup.bundled_location': '',
53
+ 'setup.doctor_hint': '\nRun harnessed doctor to verify your environment.',
54
+ 'agent_teams.missing_header':
55
+ '\n\u26A0\uFE0F Agent Teams not enabled \u2014 parallelism upgrade path unavailable',
56
+ 'agent_teams.missing_fix': ' fix: claude config set env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS 1',
57
+ 'agent_teams.missing_explanation':
58
+ ' harnessed task parallelism uses Subagent or Agent Teams (CC 2.1.178+)',
59
+ 'agent_teams.missing_nonblocking': ' non-blocking \u2014 auto-degrades to subagent fan-out\n',
60
+ 'install.manifest_not_found': "error: manifest '{{name}}' not found",
61
+ 'install.manifest_not_found.fix':
62
+ ' fix: ensure manifests/tools/{{name}}.yaml, manifests/skill-packs/{{name}}.yaml, or manifests/optional/{{name}}.yaml exists',
63
+ 'install.audit_hint': " fix: run 'harnessed audit' to inspect manifest issues",
64
+ 'install.success': 'installed {{name}}',
65
+ 'install.success_with_version': 'installed {{name}}@{{version}}',
66
+ 'install.already_installed': 'already-installed {{name}} (idempotent check hit; nothing to do)',
67
+ 'install.already_installed_with_version':
68
+ 'already-installed {{name}}@{{version}} (idempotent check hit; nothing to do)',
69
+ 'install.aborted': 'aborted: {{reason}}',
70
+ 'uninstall.dry_run.preview': "[dry-run] would uninstall '{{name}}' via method '{{method}}'",
71
+ 'uninstall.dry_run.run_hint': ' run without --dry-run to execute',
72
+ 'uninstall.confirm.prompt': "Uninstall '{{name}}'? This cannot be undone.",
73
+ 'uninstall.cancelled': 'aborted: user cancelled',
74
+ 'uninstall.completed': 'uninstalled {{name}}',
75
+ 'uninstall.unified.nothing': 'nothing to do \u2014 no harnessed artifacts found',
76
+ 'uninstall.unified.header': 'harnessed uninstall will remove the following:',
77
+ 'uninstall.unified.commands':
78
+ ' Commands: {{count}} harnessed-generated slash command file(s) in ~/.claude/commands/',
79
+ 'uninstall.unified.agent_roles':
80
+ ' Agent roles: {{count}} harnessed-generated codex agent role file(s) in ~/.codex/agents/',
81
+ 'uninstall.unified.skills':
82
+ ' Skills: {{count}} workflow skill directory(ies) in ~/.claude/skills/',
83
+ 'uninstall.unified.settings':
84
+ ' Settings: harnessed env vars (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS, HARNESSED_USER_LANG) from ~/.claude/settings.json',
85
+ 'uninstall.unified.hooks':
86
+ ' Hooks: {{count}} harnessed Stop/UserPromptSubmit hook(s) in ~/.claude/settings.json',
87
+ 'uninstall.unified.state_dir':
88
+ ' State directory: ~/.claude/harnessed/ (includes backups, audit log, state, lock)',
89
+ 'uninstall.unified.upstream_note':
90
+ '\nUpstream components (npm packages, MCP servers, CC plugins, git-cloned repos, npx skills) are NOT affected.',
91
+ 'uninstall.unified.dry_run_hint':
92
+ '\n(dry-run \u2014 re-run without --dry-run to actually remove)',
93
+ 'uninstall.unified.confirm':
94
+ "Remove harnessed's own files? Upstream components (npm packages, MCP servers, CC plugins, etc.) will NOT be affected. This cannot be undone.",
95
+ 'uninstall.unified.removing': 'removing harnessed files...',
96
+ 'uninstall.unified.removed_commands': ' removed {{count}} command file(s)',
97
+ 'uninstall.unified.removed_agent_roles': ' removed {{count}} codex agent role file(s)',
98
+ 'uninstall.unified.removed_skills': ' removed {{count}} skill directory(ies)',
99
+ 'uninstall.unified.removed_settings': ' removed harnessed env vars from ~/.claude/settings.json',
100
+ 'uninstall.unified.removed_hooks':
101
+ ' removed {{count}} harnessed hook(s) from ~/.claude/settings.json',
102
+ 'uninstall.unified.removed_state_dir': ' removed ~/.claude/harnessed/',
103
+ 'uninstall.unified.partial_failure':
104
+ '\n{{count}} item(s) could not be removed (permission denied or already gone):',
105
+ 'uninstall.unified.complete': "uninstall complete \u2014 harnessed's own files have been removed",
106
+ 'uninstall.unified.cli_hint_header':
107
+ '\nto remove the harnessed CLI itself (the step above did not \u2014 it only cleared setup files):',
108
+ 'uninstall.unified.cli_hint_binary':
109
+ ' binary: delete {{path}}\n then remove {{dir}} from your PATH',
110
+ 'uninstall.unified.cli_hint_npm': ' npm: npm uninstall -g harnessed',
111
+ 'uninstall.unified.cli_hint_other':
112
+ " installed both ways? remove the other too \u2014 npm: 'npm uninstall -g harnessed' / binary: delete the exe + its bin dir from PATH",
113
+ 'gc.invalid_duration': "error: invalid --older-than '{{value}}'",
114
+ 'gc.invalid_duration.fix': ' fix: use format <N>{d|h|m|w} e.g. 30d / 24h / 60m / 4w',
115
+ 'gc.no_backups': 'no backups found ({{root}} absent) \u2014 nothing to gc',
116
+ 'gc.no_old_snapshots': 'no snapshots older than {{cutoff}} (kept {{keptCount}} most-recent)',
117
+ 'gc.summary_will_delete': 'would delete {{count}} snapshot(s), ~{{sizeKb}} KB total:',
118
+ 'gc.summary_deleting': 'deleting {{count}} snapshot(s), ~{{sizeKb}} KB total:',
119
+ 'gc.dry_run_rerun_hint': '\n(dry-run \u2014 re-run without --dry-run to actually delete)',
120
+ 'gc.ledger_will_prune':
121
+ 'would prune {{count}} stale workflow slot(s) from the ledger (kept {{kept}}):',
122
+ 'gc.ledger_pruned': 'pruned {{count}} stale workflow slot(s) from the ledger (kept {{kept}}):',
123
+ 'doctor.summary.fail': '\nsome checks failed (see fix hints above)',
124
+ 'doctor.summary.warn': '\nall checks ok (with warnings \u2014 see hints above)',
125
+ 'doctor.summary.pass': '\nall checks passed',
126
+ 'doctor.host_scope': 'host: {{host}} \u2014 {{applied}} of {{total}} checks apply\n',
127
+ 'doctor.matrix.legend':
128
+ '\nn/a = the check is not declared for that host in the registry, so it was not run',
129
+ 'check_docs.clean': 'documentation discipline: no violations',
130
+ 'check_docs.state_line_limit':
131
+ 'STATE.md is {{lines}} lines > the {{limit}}-line digest limit \u2014 archive older phase narrative to RETROSPECTIVE.md (override for one run: HARNESSED_ALLOW_LONG_STATE=1)',
132
+ 'check_docs.state_key_decisions':
133
+ "{{count}} '\u5173\u952E\u51B3\u8BAE ship \u603B\u7ED3' section(s) > {{limit}} \u2014 keep only the current one; move the rest to RETROSPECTIVE.md",
134
+ 'check_docs.state_errata':
135
+ "historical commentary '{{excerpt}}' belongs in RETROSPECTIVE.md, not in the STATE digest",
136
+ 'check_docs.roadmap_narrative':
137
+ 'closing narrative inlined in an overview doc ({{signals}}) \u2014 ROADMAP carries one line + a pointer per phase; narrative goes to SUMMARY / VERIFICATION',
138
+ 'check_docs.summary_halt':
139
+ '\ndocumentation discipline: {{halt}} blocking + {{warn}} advisory violation(s)',
140
+ 'check_docs.summary_warn':
141
+ '\ndocumentation discipline: {{warn}} advisory violation(s) (non-blocking)',
142
+ 'backup.no_backups': 'no backups found ({{root}} absent)',
143
+ 'backup.no_backups_empty': 'no backups found ({{root}} empty)',
144
+ 'backup.total_snapshots': '\n{{count}} snapshot(s) total',
145
+ 'rollback.metadata_unreadable': 'error: cannot read {{path}}: {{message}}',
146
+ 'rollback.metadata_unreadable.fix':
147
+ " fix: run 'harnessed backup list' to see available timestamps",
148
+ 'rollback.checksum_mismatch':
149
+ 'error: backup checksum mismatch for {{target}} (expected {{expected}}, got {{actual}})',
150
+ 'rollback.restored': 'restored {{count}} file(s) from {{timestamp}}',
151
+ 'status.no_installs': 'no installs recorded ({{path}} absent or empty)',
152
+ 'status.summary_installs': '\n{{count}} install(s) recorded',
153
+ 'status.lock_held': '\nlock: held (since {{since}}){{staleSuffix}}',
154
+ 'status.lock_held.stale_suffix': ' \u2014 STALE',
155
+ 'status.lock_release_hint': ' to release: wait for process to finish or delete {{path}}',
156
+ 'status.lock_free': '\nlock: free',
157
+ 'here.no_workflow': 'no active workflow for this repo ({{path}} has no entry for cwd)',
158
+ 'here.no_workflow.hint':
159
+ ' to start: run a stage (e.g. `harnessed gates discuss`) or `harnessed run <workflow>`',
160
+ 'audit_log.no_records_file': 'no audit records found ({{path}} does not exist)',
161
+ 'audit_log.no_records_empty': 'no audit records found (audit.log is empty)',
162
+ 'audit_log.jq_missing': '\u2717 jq not found in PATH \u2014 run: harnessed doctor',
163
+ 'audit_log.tail_invalid': '\u2717 --tail must be a positive integer',
164
+ 'audit_log.head_invalid': '\u2717 --head must be a positive integer',
165
+ 'execute_task.require_task': 'error: --task <text> is required',
166
+ 'execute_task.load_phases_failed':
167
+ 'error: failed to load workflows/{{workflow}}/phases.yaml \u2014 {{message}}',
168
+ 'execute_task.precommit_skipped':
169
+ '\u26A0\uFE0F before-commit pre-flight skipped ({{message}}); subagent will biome-check at commit time.',
170
+ 'research.require_query': 'error: --query <text> is required',
171
+ 'manifest_add.non_interactive_warn':
172
+ '[ee-5-gate] WARN: --non-interactive skips 5-question prompt (D-03 dry-run-only). plan-phase hard reject still applies.',
173
+ 'manifest_add.dry_run_preview':
174
+ '[manifest-add] dry-run preview for upstream: {{upstream}} \u2192 {{path}}',
175
+ 'manifest_add.empty_answer': 'error: EE-5 gate requires non-empty answer',
176
+ 'manifest_add.gate_passed_wrote': '[manifest-add] EE-5 gate passed; wrote {{path}}',
177
+ 'manifest_add.gate_passed_dry_run':
178
+ '[manifest-add] EE-5 gate passed (dry-run); would write {{path}}',
179
+ 'resume.fail': '\u2717 {{error}}',
180
+ 'resume.corrupt': '\u2717 {{error}}\n path: {{path}}',
181
+ }
182
+
183
+ // src/i18n/index.ts
184
+ var currentLocale = null
185
+ var cache = {}
186
+ function mapToSupported(raw2) {
187
+ if (!raw2) return 'en'
188
+ if (/^zh([^a-z]|$)/i.test(raw2)) return 'zh-Hans'
189
+ return 'en'
190
+ }
191
+ function detectLocale() {
192
+ const raw2 =
193
+ process.env.HARNESSED_LANG ||
194
+ process.env.LC_ALL ||
195
+ process.env.LANG ||
196
+ process.env.LANGUAGE ||
197
+ safeIntlLocale()
198
+ return mapToSupported(raw2)
199
+ }
200
+ function safeIntlLocale() {
201
+ try {
202
+ return Intl.DateTimeFormat().resolvedOptions().locale
203
+ } catch {
204
+ return void 0
205
+ }
206
+ }
207
+ var wiredMessagesDirProvider = null
208
+ function messagesDir() {
209
+ const here = dirname(fileURLToPath(import.meta.url))
210
+ const candidates = []
211
+ if (wiredMessagesDirProvider) {
212
+ try {
213
+ candidates.push(wiredMessagesDirProvider())
214
+ } catch {}
215
+ }
216
+ candidates.push(resolve(here, '..', '..', 'messages'), resolve(here, '..', 'messages'))
217
+ for (const c of candidates) {
218
+ try {
219
+ readFileSync(join(c, 'en.json'), 'utf8')
220
+ return c
221
+ } catch {}
222
+ }
223
+ return resolve(process.cwd(), 'messages')
224
+ }
225
+ function loadLocale(locale) {
226
+ if (cache[locale]) return cache[locale]
227
+ const path = join(messagesDir(), `${locale}.json`)
228
+ try {
229
+ const raw2 = readFileSync(path, 'utf8')
230
+ cache[locale] = JSON.parse(raw2)
231
+ } catch {
232
+ cache[locale] = locale === 'en' ? en_default : {}
233
+ }
234
+ return cache[locale]
235
+ }
236
+ function getLocale() {
237
+ if (currentLocale === null) currentLocale = detectLocale()
238
+ return currentLocale
239
+ }
240
+ function t(key, params) {
241
+ const locale = getLocale()
242
+ const primary = loadLocale(locale)
243
+ let template = primary[key]
244
+ if (template === void 0 && locale !== 'en') {
245
+ template = loadLocale('en')[key]
246
+ }
247
+ if (template === void 0) template = key
248
+ if (!params) return template
249
+ return template.replace(/\{\{(\w+)\}\}/g, (_match, name) => {
250
+ const v = params[name]
251
+ return v === void 0 ? `{{${name}}}` : String(v)
252
+ })
253
+ }
254
+
255
+ // src/platform/ablation.ts
256
+ function isAblated(env = process.env) {
257
+ return env.HARNESSED_OFF === '1'
258
+ }
259
+
260
+ // src/cli/checkDocs.ts
261
+ var DEFAULT_MAX_STATE_LINES = 100
262
+ var KEY_DECISIONS_SECTION_RE = /^##\s+.*关键决议\s*ship\s*总结/gm
263
+ var KEY_DECISIONS_SECTION_LIMIT = 1
264
+ var HISTORICAL_ERRATA_RE = /W-[1-9]\s+errata|sister\s+review\s+M[1-9]\s+修正/
265
+ var ROADMAP_NARRATIVE_SIGNALS = [
266
+ { id: 'commit-hash', test: hasCommitHash },
267
+ { id: 'test-tally', test: (l) => /\b\d{2,}\s*\/\s*0\b/.test(l) },
268
+ { id: 'ci-verdict', test: (l) => /\bCI\s+(green|red|绿|红)/i.test(l) },
269
+ { id: 'lesson', test: (l) => /(教训|lesson\s*[::]|lessons?\s+learned)/i.test(l) },
270
+ ]
271
+ function hasCommitHash(line) {
272
+ for (const m of line.matchAll(/\b[0-9a-f]{7,40}\b/g)) {
273
+ if (/\d/.test(m[0]) && /[a-f]/.test(m[0])) return true
274
+ }
275
+ return false
276
+ }
277
+ function read(cwd, rel) {
278
+ const p = join2(cwd, rel)
279
+ if (!existsSync(p)) return null
280
+ try {
281
+ return readFileSync2(p, 'utf8')
282
+ } catch {
283
+ return null
284
+ }
285
+ }
286
+ function contentLines(content) {
287
+ const lines = content.split(/\r?\n/)
288
+ if (lines[lines.length - 1] === '') lines.pop()
289
+ return lines
290
+ }
291
+ function collectDocViolations(opts) {
292
+ const limit = opts.maxStateLines ?? DEFAULT_MAX_STATE_LINES
293
+ const out = []
294
+ const state = read(opts.cwd, join2('.planning', 'STATE.md'))
295
+ if (state !== null) {
296
+ const lines = contentLines(state)
297
+ if (lines.length > limit && !opts.allowLongState) {
298
+ out.push({
299
+ rule: 'state-digest-line-limit',
300
+ tier: 'halt',
301
+ file: '.planning/STATE.md',
302
+ message: t('check_docs.state_line_limit', { lines: lines.length, limit }),
303
+ })
304
+ }
305
+ const sections = state.match(KEY_DECISIONS_SECTION_RE) ?? []
306
+ if (sections.length > KEY_DECISIONS_SECTION_LIMIT) {
307
+ out.push({
308
+ rule: 'state-key-decisions-section-limit',
309
+ tier: 'warn',
310
+ file: '.planning/STATE.md',
311
+ message: t('check_docs.state_key_decisions', {
312
+ count: sections.length,
313
+ limit: KEY_DECISIONS_SECTION_LIMIT,
314
+ }),
315
+ })
316
+ }
317
+ for (let i = 0; i < lines.length; i++) {
318
+ const line = lines[i] ?? ''
319
+ if (HISTORICAL_ERRATA_RE.test(line)) {
320
+ out.push({
321
+ rule: 'state-historical-errata',
322
+ tier: 'warn',
323
+ file: '.planning/STATE.md',
324
+ line: i + 1,
325
+ message: t('check_docs.state_errata', { excerpt: line.trim().slice(0, 80) }),
326
+ })
327
+ }
328
+ }
329
+ }
330
+ const roadmap = read(opts.cwd, join2('.planning', 'ROADMAP.md'))
331
+ if (roadmap !== null) {
332
+ const lines = contentLines(roadmap)
333
+ for (let i = 0; i < lines.length; i++) {
334
+ const line = lines[i] ?? ''
335
+ const hits = ROADMAP_NARRATIVE_SIGNALS.filter((s) => s.test(line)).map((s) => s.id)
336
+ if (hits.length > 0) {
337
+ out.push({
338
+ rule: 'roadmap-no-inline-narrative',
339
+ tier: 'warn',
340
+ file: '.planning/ROADMAP.md',
341
+ line: i + 1,
342
+ message: t('check_docs.roadmap_narrative', { signals: hits.join(', ') }),
343
+ })
344
+ }
345
+ }
346
+ }
347
+ return out
348
+ }
349
+ function exitCodeFor(violations) {
350
+ if (violations.some((v) => v.tier === 'halt')) return 2
351
+ return violations.length > 0 ? 1 : 0
352
+ }
353
+ function shouldGateForHookPayload(raw2) {
354
+ if (!raw2.trim()) return false
355
+ let payload
356
+ try {
357
+ payload = JSON.parse(raw2)
358
+ } catch {
359
+ return false
360
+ }
361
+ if (payload?.tool_name !== 'Bash') return false
362
+ const cmd = payload.tool_input?.command
363
+ return typeof cmd === 'string' && /\bgit\s+(?:-\S+\s+)*commit\b/.test(cmd)
364
+ }
365
+ function codexHookOutput(code, lines) {
366
+ const text = lines.join('\n')
367
+ if (code === 2)
368
+ return JSON.stringify({
369
+ hookSpecificOutput: {
370
+ hookEventName: 'PreToolUse',
371
+ permissionDecision: 'deny',
372
+ permissionDecisionReason: text,
373
+ },
374
+ })
375
+ if (code === 1) return JSON.stringify({ systemMessage: text })
376
+ return null
377
+ }
378
+ async function readStdin() {
379
+ if (process.stdin.isTTY) return ''
380
+ try {
381
+ const chunks = []
382
+ for await (const c of process.stdin) chunks.push(c)
383
+ return Buffer.concat(chunks).toString('utf8')
384
+ } catch {
385
+ return ''
386
+ }
387
+ }
388
+ async function runCheckDocsCommand(opts) {
389
+ if (opts.hook && isAblated()) process.exit(0)
390
+ if (opts.hook && !shouldGateForHookPayload(await readStdin())) process.exit(0)
391
+ const parsed = Number(opts.maxStateLines)
392
+ const violations = collectDocViolations({
393
+ cwd: opts.cwd ?? process.cwd(),
394
+ ...(Number.isFinite(parsed) && parsed > 0 ? { maxStateLines: parsed } : {}),
395
+ allowLongState: !!process.env.HARNESSED_ALLOW_LONG_STATE,
396
+ })
397
+ const code = exitCodeFor(violations)
398
+ const summary = code === 2 ? 'halt' : code === 1 ? 'warn' : 'pass'
399
+ if (opts.hook && opts.platform === 'codex') {
400
+ const lines = violations.map((v) => {
401
+ const where = v.line === void 0 ? v.file : `${v.file}:${v.line}`
402
+ return `${v.tier === 'halt' ? '\u2717' : '\u26A0'} ${where} [${v.rule}] ${v.message}`
403
+ })
404
+ const verdict = codexHookOutput(code, lines)
405
+ if (verdict !== null)
406
+ process.stdout.write(`${verdict}
407
+ `)
408
+ process.exit(0)
409
+ }
410
+ if (opts.json) {
411
+ console.log(JSON.stringify({ violations, summary, exit_code: code }, null, 2))
412
+ } else if (violations.length === 0) {
413
+ console.log(t('check_docs.clean'))
414
+ } else {
415
+ for (const v of violations) {
416
+ const where = v.line === void 0 ? v.file : `${v.file}:${v.line}`
417
+ console.error(`${v.tier === 'halt' ? '\u2717' : '\u26A0'} ${where} [${v.rule}] ${v.message}`)
418
+ }
419
+ console.error(
420
+ code === 2
421
+ ? t('check_docs.summary_halt', {
422
+ halt: violations.filter((v) => v.tier === 'halt').length,
423
+ warn: violations.filter((v) => v.tier === 'warn').length,
424
+ })
425
+ : t('check_docs.summary_warn', { warn: violations.length }),
426
+ )
427
+ }
428
+ process.exit(code)
429
+ }
430
+
431
+ // src/cli/checkDocsHookMain.ts
432
+ var raw = process.argv.slice(2)
433
+ var args = raw[0] === 'check-docs' ? raw.slice(1) : raw
434
+ var value = (name) => {
435
+ const at = args.indexOf(`--${name}`)
436
+ if (at >= 0) return args[at + 1]
437
+ const prefix = `--${name}=`
438
+ return args.find((a) => a.startsWith(prefix))?.slice(prefix.length)
439
+ }
440
+ var has = (name) => args.includes(`--${name}`)
441
+ try {
442
+ await runCheckDocsCommand({
443
+ json: has('json'),
444
+ cwd: value('cwd'),
445
+ maxStateLines: value('max-state-lines'),
446
+ hook: has('hook'),
447
+ platform: value('platform'),
448
+ })
449
+ } catch (error) {
450
+ console.error(error.message)
451
+ process.exit(1)
452
+ }
@@ -54,10 +54,15 @@ function codexDescriptor(home = homedir()) {
54
54
  sessionIdEnv: 'CODEX_SESSION_ID',
55
55
  }
56
56
  }
57
+ var HOST_IDS = ['claude', 'codex']
58
+ function isHostId(id) {
59
+ return HOST_IDS.includes(id)
60
+ }
61
+ function descriptorFor(id, home = homedir()) {
62
+ return id === 'codex' ? codexDescriptor(home) : claudeDescriptor(home)
63
+ }
57
64
  function descriptorById(id, home) {
58
- if (id === 'claude') return claudeDescriptor(home)
59
- if (id === 'codex') return codexDescriptor(home)
60
- return void 0
65
+ return isHostId(id) ? descriptorFor(id, home) : void 0
61
66
  }
62
67
  function detectPlatform(home = homedir()) {
63
68
  const resolved = resolveHost(home)
@@ -66,27 +71,63 @@ function detectPlatform(home = homedir()) {
66
71
  return resolved
67
72
  }
68
73
  function resolveHost(home) {
74
+ return resolveHostWithReason(home).descriptor
75
+ }
76
+ function resolveHostWithReason(home = homedir()) {
69
77
  const base = claudeDescriptor(home)
78
+ const skipped = []
70
79
  const envPlatform = process.env.HARNESSED_PLATFORM
71
80
  if (envPlatform !== void 0 && envPlatform !== '') {
72
81
  const d = descriptorById(envPlatform, home)
73
- if (d) return d
82
+ if (d) {
83
+ return {
84
+ descriptor: d,
85
+ reason: { kind: 'env-platform', envVar: 'HARNESSED_PLATFORM', value: envPlatform },
86
+ skipped,
87
+ }
88
+ }
89
+ skipped.push({ kind: 'env-platform-unknown', envVar: 'HARNESSED_PLATFORM', value: envPlatform })
74
90
  }
75
91
  const inClaude = Boolean(process.env.CLAUDE_CODE_SESSION_ID?.trim())
76
92
  const inCodex = Boolean(process.env.CODEX_SESSION_ID?.trim())
77
- if (inClaude !== inCodex) return inClaude ? base : codexDescriptor(home)
93
+ if (inClaude !== inCodex) {
94
+ return {
95
+ descriptor: inClaude ? base : codexDescriptor(home),
96
+ reason: {
97
+ kind: 'host-session-env',
98
+ envVar: inClaude ? 'CLAUDE_CODE_SESSION_ID' : 'CODEX_SESSION_ID',
99
+ },
100
+ skipped,
101
+ }
102
+ }
103
+ if (inClaude && inCodex) skipped.push({ kind: 'host-session-env-ambiguous' })
78
104
  for (const pinRoot of [codexDescriptor(home).stateRoot, base.stateRoot]) {
105
+ const pinPath = join(pinRoot, '.platform')
79
106
  try {
80
- const d = descriptorById(readFileSync(join(pinRoot, '.platform'), 'utf8').trim(), home)
81
- if (d) return d
107
+ const value = readFileSync(pinPath, 'utf8').trim()
108
+ const d = descriptorById(value, home)
109
+ if (d) return { descriptor: d, reason: { kind: 'platform-pin', pinPath, value }, skipped }
110
+ skipped.push({ kind: 'platform-pin-unknown', pinPath, value })
82
111
  } catch {}
83
112
  }
84
113
  try {
85
- if (existsSync(base.homeDir)) return base
114
+ if (existsSync(base.homeDir)) {
115
+ return {
116
+ descriptor: base,
117
+ reason: { kind: 'directory-probe', probedDir: base.homeDir },
118
+ skipped,
119
+ }
120
+ }
86
121
  const codex = codexDescriptor(home)
87
- if (existsSync(codex.homeDir)) return codex
122
+ if (existsSync(codex.homeDir)) {
123
+ return {
124
+ descriptor: codex,
125
+ reason: { kind: 'directory-probe', probedDir: codex.homeDir },
126
+ skipped,
127
+ }
128
+ }
88
129
  } catch {}
89
- return base
130
+ return { descriptor: base, reason: { kind: 'fallback' }, skipped }
90
131
  }
91
132
 
92
133
  // src/checkpoint/hookHost.ts
@@ -523,7 +564,7 @@ function forwardPointer(repoRoot, wf) {
523
564
  }
524
565
 
525
566
  // src/checkpoint/injectStateMain.ts
526
- function repoKey(cwd) {
567
+ function repoRootPath(cwd) {
527
568
  let dir = resolve(cwd)
528
569
  for (;;) {
529
570
  if (existsSync4(join5(dir, '.git'))) return dir
@@ -533,6 +574,10 @@ function repoKey(cwd) {
533
574
  }
534
575
  return resolve(cwd)
535
576
  }
577
+ function repoKey(cwd) {
578
+ const root = repoRootPath(cwd)
579
+ return process.platform === 'win32' ? root.toLowerCase() : root
580
+ }
536
581
  function readWorkflow(root, keys) {
537
582
  let wf = null
538
583
  let intent = null
@@ -591,20 +636,31 @@ async function main() {
591
636
  invalidateInjectCache(root)
592
637
  return
593
638
  }
594
- const key = repoKey(process.cwd())
639
+ const repoPath = repoRootPath(process.cwd())
640
+ const slotKey = repoKey(process.cwd())
595
641
  const envName = platform.sessionIdEnv
596
642
  const sid =
597
643
  (envName ? process.env[envName]?.trim() : void 0) ||
598
644
  (hostArg ? sessionIdFromPayload(await readHookStdin()) : void 0)
599
- const { wf, intent, ledgerAgeMs } = readWorkflow(root, sid ? [`${key}::${sid}`, key] : [key])
645
+ const { wf, intent, ledgerAgeMs } = readWorkflow(
646
+ root,
647
+ sid ? [`${slotKey}::${sid}`, slotKey] : [slotKey],
648
+ )
600
649
  let learningsMd = ''
601
650
  try {
602
- learningsMd = readFileSync5(join5(key, '.planning', 'LEARNINGS.md'), 'utf8')
651
+ learningsMd = readFileSync5(join5(repoPath, '.planning', 'LEARNINGS.md'), 'utf8')
603
652
  } catch {}
604
653
  const budget = Number(process.env.HARNESSED_INJECT_BUDGET) || DEFAULT_INJECT_BUDGET
605
654
  const pcOff = process.env.HARNESSED_INJECT_PC_OFF === '1'
606
- const pcGate = pcOff ? () => false : sid ? (pc) => shouldEmitPc(root, key, sid, pc) : void 0
607
- const out = buildInjection(key, wf, learningsMd, budget, intent, Date.now(), {
655
+ const pcGate = pcOff
656
+ ? () => false
657
+ : sid
658
+ ? // slotKey (folded): the PC-emission cache keys state, same reason as the
659
+ // ledger. Pre-upgrade entries keyed by the unfolded path simply become
660
+ // unreachable — at most one extra emission after upgrading.
661
+ (pc) => shouldEmitPc(root, slotKey, sid, pc)
662
+ : void 0
663
+ const out = buildInjection(repoPath, wf, learningsMd, budget, intent, Date.now(), {
608
664
  ledgerAgeMs,
609
665
  pcGate,
610
666
  })