@adamchanadam/agent-handoff-kit 0.3.29 → 0.3.31

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.
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { createInterface } from "node:readline/promises";
4
- import { stdin as input, stdout as output } from "node:process";
5
- import { copyFile, mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
6
- import path from "node:path";
7
- import { fileURLToPath } from "node:url";
8
- import { assessPromptMirrorTexts, extractOpeningMessage } from "./prompt-mirror-core.mjs";
9
-
10
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
3
+ import { createInterface } from "node:readline/promises";
4
+ import { stdin as input, stdout as output } from "node:process";
5
+ import { copyFile, mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { assessPromptMirrorTexts, extractOpeningMessage } from "./prompt-mirror-core.mjs";
9
+
10
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
11
11
  const packageRoot = path.resolve(__dirname, "..");
12
12
 
13
13
  const mappings = [
@@ -33,10 +33,10 @@ const mappings = [
33
33
  ["packs/integrations.md", "dev/rules/integrations.md"]
34
34
  ];
35
35
 
36
- const requiredTargets = mappings.map(([, target]) => target);
37
- const rulePackTargets = mappings
38
- .map(([, target]) => target)
39
- .filter((target) => target.startsWith("dev/rules/"));
36
+ const requiredTargets = mappings.map(([, target]) => target);
37
+ const rulePackTargets = mappings
38
+ .map(([, target]) => target)
39
+ .filter((target) => target.startsWith("dev/rules/"));
40
40
  const managedCoreStart = "<!-- BEGIN Agent Handoff Kit managed core -->";
41
41
  const managedCoreEnd = "<!-- END Agent Handoff Kit managed core -->";
42
42
 
@@ -49,15 +49,17 @@ const requiredAnchors = [
49
49
  "dev/SESSION_HANDOFF.md",
50
50
  "dev/SESSION_LOG.md",
51
51
  "dev/PROJECT_INDEX.md",
52
- "dev/RULE_PACKS.md",
53
- "Agent Handoff Kit v<version>",
54
- "Display version rule",
55
- "Agent Handoff Kit template version",
56
- "continuity ready",
57
- "Start Agent Handoff",
58
- "Ambiguous startup phrases",
59
- "Reachable is not the same as ingested",
52
+ "dev/RULE_PACKS.md",
53
+ "Agent Handoff Kit v<version>",
54
+ "Display version rule",
55
+ "Agent Handoff Kit template version",
56
+ "continuity ready",
57
+ "Start Agent Handoff",
58
+ "Ambiguous startup phrases",
59
+ "Reachable is not the same as ingested",
60
60
  "Do not treat unread sources as absent",
61
+ "Task contract changes are durable facts",
62
+ "External Impact Note",
61
63
  // R-030 v0.3.0+: forces managed-core merge on v0.2.x → v0.3.0 upgrade to propagate
62
64
  // startup availability probe + integrations pack reference + credential separation discipline.
63
65
  "startup availability probe",
@@ -70,24 +72,24 @@ const requiredAnchors = [
70
72
  label: "closeout intent and full handoff",
71
73
  snippets: [
72
74
  "Detect end-of-session or handoff intent",
73
- "收工",
74
- "Wrap up Agent Handoff",
75
- "Ambiguous closeout phrases",
76
- "wrap up",
77
- "handoff",
78
- "Reconcile `dev/SESSION_HANDOFF.md`",
79
- "Add a concise entry to `dev/SESSION_LOG.md`",
80
- "Closeout Write Contract",
81
- "ack:log-entry:start/end",
82
- "next-session opening message",
83
- "fenced `text` code block",
84
- "handoff saved",
85
- "Use the same display version rule as startup",
86
- "Never print the literal placeholder `v<version>`",
87
- "next-session startup entry",
88
- "State Reconciliation Check",
89
- "handoff lifecycle consistency",
90
- "Do not append a new state snapshot",
75
+ "收工",
76
+ "Wrap up Agent Handoff",
77
+ "Ambiguous closeout phrases",
78
+ "wrap up",
79
+ "handoff",
80
+ "Reconcile `dev/SESSION_HANDOFF.md`",
81
+ "Add a concise entry to `dev/SESSION_LOG.md`",
82
+ "Closeout Write Contract",
83
+ "ack:log-entry:start/end",
84
+ "next-session opening message",
85
+ "fenced `text` code block",
86
+ "handoff saved",
87
+ "Use the same display version rule as startup",
88
+ "Never print the literal placeholder `v<version>`",
89
+ "next-session startup entry",
90
+ "State Reconciliation Check",
91
+ "handoff lifecycle consistency",
92
+ "Do not append a new state snapshot",
91
93
  "START_NEXT_SESSION_PROMPT.txt"
92
94
  ]
93
95
  },
@@ -106,44 +108,44 @@ const requiredAnchors = [
106
108
  "ack:section:workspace-identity",
107
109
  "ack:section:sync-status",
108
110
  "ack:section:next-task-required-reading",
109
- "ack:section:state-reconciliation-check",
110
- "ack:section:next-session-opening-message",
111
- "ack:field:lifecycle-conflicts-resolved",
112
- "ack:field:persistence-routing-checked",
113
- "📋 Next session:",
114
- "```text",
115
- "Read in order:",
116
- "dev/DOC_SYNC_REGISTRY.md"
111
+ "ack:section:state-reconciliation-check",
112
+ "ack:section:next-session-opening-message",
113
+ "ack:field:lifecycle-conflicts-resolved",
114
+ "ack:field:persistence-routing-checked",
115
+ "📋 Next session:",
116
+ "```text",
117
+ "Read in order:",
118
+ "dev/DOC_SYNC_REGISTRY.md"
117
119
  ]
118
120
  },
119
- {
120
- target: "dev/SESSION_LOG.md",
121
- label: "session log event and opening message schema",
122
- placement: sessionLogAnchorPlacement,
123
- snippets: [
124
- "ack:section:session-log-preamble",
125
- "ack:section:session-log-entry-template",
126
- "ack:log-entry:start",
127
- "ack:log-entry:end",
128
- "Record what actually happened in the session",
129
- "## Entry Template",
130
- "- **QC:**",
121
+ {
122
+ target: "dev/SESSION_LOG.md",
123
+ label: "session log event and opening message schema",
124
+ placement: sessionLogAnchorPlacement,
125
+ snippets: [
126
+ "ack:section:session-log-preamble",
127
+ "ack:section:session-log-entry-template",
128
+ "ack:log-entry:start",
129
+ "ack:log-entry:end",
130
+ "Record what actually happened in the session",
131
+ "## Entry Template",
132
+ "- **QC:**",
131
133
  "- **Sync:**",
132
- "- **Log maintenance:**",
133
- "### Next Session Opening Message",
134
- "📋 Next session:",
135
- "```text",
136
- "Read in order:",
137
- "dev/DOC_SYNC_REGISTRY.md"
134
+ "- **Log maintenance:**",
135
+ "### Next Session Opening Message",
136
+ "📋 Next session:",
137
+ "```text",
138
+ "Read in order:",
139
+ "dev/DOC_SYNC_REGISTRY.md"
138
140
  ]
139
141
  },
140
- {
141
- target: "dev/SESSION_HANDOFF.md",
142
- label: "handoff log archive continuity",
143
- placement: handoffContinuityAnchorPlacement,
144
- snippets: [
145
- "ack:section:handoff-sufficiency-check",
146
- "ack:section:state-reconciliation-check",
142
+ {
143
+ target: "dev/SESSION_HANDOFF.md",
144
+ label: "handoff log archive continuity",
145
+ placement: handoffContinuityAnchorPlacement,
146
+ snippets: [
147
+ "ack:section:handoff-sufficiency-check",
148
+ "ack:section:state-reconciliation-check",
147
149
  "ack:field:stale-snapshots-left",
148
150
  "ack:field:opening-message-matches-current-state",
149
151
  "without searching old log history",
@@ -151,63 +153,64 @@ const requiredAnchors = [
151
153
  "do not create an archive directory by default"
152
154
  ]
153
155
  },
154
- {
155
- target: "dev/SESSION_LOG.md",
156
- label: "log retention and evidence schema",
157
- placement: sessionLogAnchorPlacement,
158
- snippets: [
159
- "kept, summarized, or archived",
160
- "Do not remove validation evidence",
156
+ {
157
+ target: "dev/SESSION_LOG.md",
158
+ label: "log retention and evidence schema",
159
+ placement: sessionLogAnchorPlacement,
160
+ snippets: [
161
+ "kept, summarized, or archived",
162
+ "Do not remove validation evidence",
161
163
  "latest opening message",
162
164
  "not current state"
163
165
  ]
164
166
  },
165
- {
166
- target: "dev/PROJECT_INDEX.md",
167
- label: "template version metadata",
168
- placement: projectIndexAnchorPlacement,
169
- snippets: [
170
- "Agent Handoff Kit template version"
171
- ]
167
+ {
168
+ target: "dev/PROJECT_INDEX.md",
169
+ label: "template version metadata",
170
+ placement: projectIndexAnchorPlacement,
171
+ snippets: [
172
+ "Agent Handoff Kit template version"
173
+ ]
172
174
  },
173
- {
174
- target: "dev/rules/safety.md",
175
- label: "safety pack high-risk anchors",
176
- placement: safetyAnchorPlacement,
177
- snippets: [
178
- "deleting, overwriting, moving, renaming",
179
- "filesystem root, drive root",
175
+ {
176
+ target: "dev/rules/safety.md",
177
+ label: "safety pack high-risk anchors",
178
+ placement: safetyAnchorPlacement,
179
+ snippets: [
180
+ "deleting, overwriting, moving, renaming",
181
+ "filesystem root, drive root",
180
182
  "cmd /c rmdir",
181
183
  "git reset --hard",
182
184
  "external APIs, SDKs, CLIs",
185
+ "parser failure",
183
186
  "secret values"
184
187
  ]
185
188
  },
186
- {
187
- target: "dev/PROJECT_DECISIONS.md",
188
- label: "project decisions narrative anchors",
189
- placement: projectDecisionsAnchorPlacement,
190
- snippets: [
191
- "Project Decisions Log",
192
- "warm 資料層",
193
- "AI 開工",
194
- "不需要讀",
195
- "AI 在收工時自動 update",
196
- "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.",
197
- "This file does not store raw build / upload / QC evidence",
198
- "Evolution Timeline",
199
- "Decisions Archive",
200
- "Architecture Choices",
189
+ {
190
+ target: "dev/PROJECT_DECISIONS.md",
191
+ label: "project decisions narrative anchors",
192
+ placement: projectDecisionsAnchorPlacement,
193
+ snippets: [
194
+ "Project Decisions Log",
195
+ "warm 資料層",
196
+ "AI 開工",
197
+ "不需要讀",
198
+ "AI 在收工時自動 update",
199
+ "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.",
200
+ "This file does not store raw build / upload / QC evidence",
201
+ "Evolution Timeline",
202
+ "Decisions Archive",
203
+ "Architecture Choices",
201
204
  "Insights & Learnings"
202
205
  ]
203
206
  },
204
- {
205
- target: "dev/rules/onboarding.md",
206
- label: "onboarding pack core anchors",
207
- placement: onboardingAnchorPlacement,
208
- snippets: [
209
- "Onboarding Pack",
210
- "transient pack",
207
+ {
208
+ target: "dev/rules/onboarding.md",
209
+ label: "onboarding pack core anchors",
210
+ placement: onboardingAnchorPlacement,
211
+ snippets: [
212
+ "Onboarding Pack",
213
+ "transient pack",
211
214
  "明確 onboarding signal keywords",
212
215
  "5-step walk-through pattern",
213
216
  "Application Scenario Library",
@@ -220,13 +223,13 @@ const requiredAnchors = [
220
223
  "Tone Discipline"
221
224
  ]
222
225
  },
223
- {
224
- target: "dev/rules/integrations.md",
225
- label: "integrations pack core anchors",
226
- placement: integrationsAnchorPlacement,
227
- snippets: [
228
- "Integrations Pack",
229
- "Connectors",
226
+ {
227
+ target: "dev/rules/integrations.md",
228
+ label: "integrations pack core anchors",
229
+ placement: integrationsAnchorPlacement,
230
+ snippets: [
231
+ "Integrations Pack",
232
+ "Connectors",
230
233
  "MCPs",
231
234
  "Plugins",
232
235
  "Skills",
@@ -268,24 +271,24 @@ const schemaChecks = [
268
271
  section("state-reconciliation-check", "State Reconciliation Check"),
269
272
  section("handoff-sufficiency-check", "Handoff Sufficiency Check"),
270
273
  section("next-session-opening-message", "Next Session Opening Message"),
271
- marker("field", "stale-snapshots-left", "Stale snapshots left in this handoff"),
272
- marker("field", "lifecycle-conflicts-resolved", "Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified"),
273
- marker("field", "persistence-routing-checked", "Persistence routing checked"),
274
- marker("field", "opening-message-matches-current-state", "Opening message matches current state"),
275
- marker("field", "state-sections-rewritten-or-confirmed", "State sections rewritten or confirmed current"),
274
+ marker("field", "stale-snapshots-left", "Stale snapshots left in this handoff"),
275
+ marker("field", "lifecycle-conflicts-resolved", "Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified"),
276
+ marker("field", "persistence-routing-checked", "Persistence routing checked"),
277
+ marker("field", "opening-message-matches-current-state", "Opening message matches current state"),
278
+ marker("field", "state-sections-rewritten-or-confirmed", "State sections rewritten or confirmed current"),
276
279
  marker("field", "user-intent", "User intent:"),
277
280
  marker("field", "task-essence", "Task essence:"),
278
281
  marker("field", "success-criteria", "Success criteria:")
279
282
  ]
280
283
  },
281
284
  {
282
- target: "dev/SESSION_HANDOFF.md",
283
- label: "handoff opening message structure",
284
- checks: [
285
- includes("📋 Next session:"),
286
- includes("```text"),
287
- includes("Work in "),
288
- includes("Read in order:"),
285
+ target: "dev/SESSION_HANDOFF.md",
286
+ label: "handoff opening message structure",
287
+ checks: [
288
+ includes("📋 Next session:"),
289
+ includes("```text"),
290
+ includes("Work in "),
291
+ includes("Read in order:"),
289
292
  includes("If this root does not match the expected project root")
290
293
  ]
291
294
  },
@@ -303,18 +306,18 @@ const schemaChecks = [
303
306
  target: "dev/SESSION_LOG.md",
304
307
  label: "session log entry fields",
305
308
  checks: [
306
- heading("Entry Template"),
307
- marker("section", "session-log-preamble", "Handoff role"),
308
- marker("section", "session-log-entry-template", "Entry Template"),
309
- includes("ack:log-entry:start"),
310
- includes("ack:log-entry:end"),
311
- includes("- **ID:**"),
309
+ heading("Entry Template"),
310
+ marker("section", "session-log-preamble", "Handoff role"),
311
+ marker("section", "session-log-entry-template", "Entry Template"),
312
+ includes("ack:log-entry:start"),
313
+ includes("ack:log-entry:end"),
314
+ includes("- **ID:**"),
312
315
  includes("- **Summary:**"),
313
316
  includes("- **Changed:**"),
314
- includes("- **Done:**"),
315
- includes("- **QC:**"),
316
- includes("- **Evidence disposition:**"),
317
- includes("- **Sync:**"),
317
+ includes("- **Done:**"),
318
+ includes("- **QC:**"),
319
+ includes("- **Evidence disposition:**"),
320
+ includes("- **Sync:**"),
318
321
  includes("- **Pending:**"),
319
322
  includes("- **Risks:**"),
320
323
  includes("- **Log maintenance:**")
@@ -363,11 +366,11 @@ const schemaChecks = [
363
366
  tableHeader("Change type", "Also check/update", "Verification")
364
367
  ]
365
368
  },
366
- {
367
- target: "dev/RULE_PACKS.md",
368
- label: "rule pack router coverage",
369
- checks: [
370
- heading("Routing Rule"),
369
+ {
370
+ target: "dev/RULE_PACKS.md",
371
+ label: "rule pack router coverage",
372
+ checks: [
373
+ heading("Routing Rule"),
371
374
  includes("Load the minimum set"),
372
375
  includes("cannot weaken core safety"),
373
376
  includes("dev/rules/safety.md"),
@@ -379,43 +382,43 @@ const schemaChecks = [
379
382
  // stale routing table that does not route onboarding signals.
380
383
  includes("First-time user signals"),
381
384
  includes("dev/rules/onboarding.md"),
382
- // R-030 v0.3.0+: routing table must include integrations pack row.
383
- includes("dev/rules/integrations.md"),
384
- includes("Governance bridge / 治理打通"),
385
- includes("接入 Agent Handoff Kit"),
386
- includes("掃描未接入 Agent Handoff Kit 的重要文件"),
387
- includes("scan for unbridged governance documents")
388
- ]
389
- },
390
- {
391
- target: "dev/rules/agent-governance.md",
392
- label: "agent governance pack structure",
393
- checks: [
394
- heading("Scope"),
395
- heading("Load When"),
396
- heading("Rules"),
397
- heading("Governance Bridge Workflow"),
398
- heading("Checks"),
399
- heading("Closeout"),
400
- includes("Governance bridge is a triggered review"),
401
- includes("接入 Agent Handoff Kit"),
402
- includes("掃描未接入 Agent Handoff Kit 的重要文件"),
403
- includes("Status: bridged / partially bridged / unbridged / blocked"),
404
- includes("duplicate source-of-truth risk")
405
- ]
406
- },
407
- {
408
- target: "dev/PROJECT_DECISIONS.md",
409
- label: "project decisions log structure",
410
- checks: [
411
- heading("Evolution Timeline"),
412
- heading("Decisions Archive"),
413
- heading("Architecture Choices"),
414
- heading("Insights & Learnings"),
415
- includes("Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>."),
416
- includes("(empty)")
417
- ]
418
- },
385
+ // R-030 v0.3.0+: routing table must include integrations pack row.
386
+ includes("dev/rules/integrations.md"),
387
+ includes("Governance bridge / 治理打通"),
388
+ includes("接入 Agent Handoff Kit"),
389
+ includes("掃描未接入 Agent Handoff Kit 的重要文件"),
390
+ includes("scan for unbridged governance documents")
391
+ ]
392
+ },
393
+ {
394
+ target: "dev/rules/agent-governance.md",
395
+ label: "agent governance pack structure",
396
+ checks: [
397
+ heading("Scope"),
398
+ heading("Load When"),
399
+ heading("Rules"),
400
+ heading("Governance Bridge Workflow"),
401
+ heading("Checks"),
402
+ heading("Closeout"),
403
+ includes("Governance bridge is a triggered review"),
404
+ includes("接入 Agent Handoff Kit"),
405
+ includes("掃描未接入 Agent Handoff Kit 的重要文件"),
406
+ includes("Status: bridged / partially bridged / unbridged / blocked"),
407
+ includes("duplicate source-of-truth risk")
408
+ ]
409
+ },
410
+ {
411
+ target: "dev/PROJECT_DECISIONS.md",
412
+ label: "project decisions log structure",
413
+ checks: [
414
+ heading("Evolution Timeline"),
415
+ heading("Decisions Archive"),
416
+ heading("Architecture Choices"),
417
+ heading("Insights & Learnings"),
418
+ includes("Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>."),
419
+ includes("(empty)")
420
+ ]
421
+ },
419
422
  {
420
423
  target: "dev/rules/onboarding.md",
421
424
  label: "onboarding pack structure (新手引導包)",
@@ -513,9 +516,9 @@ async function needsProjectIndexVersionInject(root, command, version) {
513
516
  return false;
514
517
  }
515
518
 
516
- async function runInstall(command, root, options, version) {
517
- const mode = await detectMode(root);
518
- const plan = await buildPlan(root, command, version);
519
+ async function runInstall(command, root, options, version) {
520
+ const mode = await detectMode(root);
521
+ const plan = await buildPlan(root, command, version);
519
522
 
520
523
  // R-031 v0.3.1+: plan-time upgrade no-op detection. When upgrade has zero
521
524
  // create/merge/conflict actions (skip-only), skip the full plan listing +
@@ -531,29 +534,29 @@ async function runInstall(command, root, options, version) {
531
534
  // this guard, plan-time short-circuit returns before inject can fire, leaving
532
535
  // root on stale version forever.
533
536
  const projectIndexVersionNeedsInject = await needsProjectIndexVersionInject(root, command, version);
534
- const isUpgradeNoopAtPlanTime = command === "upgrade"
535
- && planCreateCount === 0
536
- && planMergeCount === 0
537
- && planConflictCount === 0
538
- && !projectIndexVersionNeedsInject;
539
-
540
- if (isUpgradeNoopAtPlanTime) {
541
- const noOpHealth = await assessUpgradeNoopHealth(root, version);
542
- printCard(version, "continuity ready", "o.o");
543
- console.log(`command: ${command}`);
544
- console.log(`current directory: ${process.cwd()}`);
537
+ const isUpgradeNoopAtPlanTime = command === "upgrade"
538
+ && planCreateCount === 0
539
+ && planMergeCount === 0
540
+ && planConflictCount === 0
541
+ && !projectIndexVersionNeedsInject;
542
+
543
+ if (isUpgradeNoopAtPlanTime) {
544
+ const noOpHealth = await assessUpgradeNoopHealth(root, version);
545
+ printCard(version, "continuity ready", "o.o");
546
+ console.log(`command: ${command}`);
547
+ console.log(`current directory: ${process.cwd()}`);
545
548
  console.log(`selected root: ${root}`);
546
549
  console.log(`mode: ${mode}`);
547
550
  console.log("");
548
551
  console.log(`📋 計劃預覽:create 0 / merge 0 / skip ${planSkipCount} / conflict 0 — 沒有檔案需要建立或合併。`);
549
552
  if (options.dryRun) {
550
- console.log("");
551
- console.log("dry-run: no files written");
552
- }
553
- printUpgradeNoopShortCircuit(version, noOpHealth);
554
- if (!noOpHealth.ok) process.exitCode = 1;
555
- return;
556
- }
553
+ console.log("");
554
+ console.log("dry-run: no files written");
555
+ }
556
+ printUpgradeNoopShortCircuit(version, noOpHealth);
557
+ if (!noOpHealth.ok) process.exitCode = 1;
558
+ return;
559
+ }
557
560
 
558
561
  printPlan(command, root, mode, plan, version, options.dryRun);
559
562
 
@@ -579,33 +582,33 @@ async function runInstall(command, root, options, version) {
579
582
  const migrationDir = path.join(root, "dev/governance_migrations", stamp);
580
583
  const backupDir = path.join(migrationDir, "backup");
581
584
 
582
- for (const item of plan) {
583
- if (item.action !== "create") continue;
584
- await mkdir(path.dirname(item.targetAbs), { recursive: true });
585
- if (item.targetRel === "AGENTS.md") {
586
- const sourceText = await readFile(item.sourceAbs, "utf8");
587
- await writeFile(item.targetAbs, mergeManagedBlock("", sourceText), "utf8");
588
- } else {
589
- await copyFile(item.sourceAbs, item.targetAbs);
590
- }
591
- created.push(item.targetRel);
585
+ for (const item of plan) {
586
+ if (item.action !== "create") continue;
587
+ await mkdir(path.dirname(item.targetAbs), { recursive: true });
588
+ if (item.targetRel === "AGENTS.md") {
589
+ const sourceText = await readFile(item.sourceAbs, "utf8");
590
+ await writeFile(item.targetAbs, mergeManagedBlock("", sourceText), "utf8");
591
+ } else {
592
+ await copyFile(item.sourceAbs, item.targetAbs);
593
+ }
594
+ created.push(item.targetRel);
592
595
  }
593
596
 
594
597
  await hydrateInitialOpeningPrompt(root, created);
595
598
 
596
- for (const item of plan) {
597
- if (item.action !== "merge") continue;
598
- const backupPath = path.join(backupDir, item.targetRel);
599
- await mkdir(path.dirname(backupPath), { recursive: true });
600
- await copyFile(item.targetAbs, backupPath);
601
- await writeFile(item.targetAbs, item.mergedText, "utf8");
602
- merged.push(item.reason ? `${item.targetRel} - ${item.reason}` : item.targetRel);
603
- }
604
-
605
- const promptRegenerated = await regeneratePromptFromHandoffIfHotEvidence(root, backupDir, merged);
606
- if (promptRegenerated) {
607
- console.log("auto-repair: START_NEXT_SESSION_PROMPT.txt - regenerate prompt from repaired handoff opening message");
608
- }
599
+ for (const item of plan) {
600
+ if (item.action !== "merge") continue;
601
+ const backupPath = path.join(backupDir, item.targetRel);
602
+ await mkdir(path.dirname(backupPath), { recursive: true });
603
+ await copyFile(item.targetAbs, backupPath);
604
+ await writeFile(item.targetAbs, item.mergedText, "utf8");
605
+ merged.push(item.reason ? `${item.targetRel} - ${item.reason}` : item.targetRel);
606
+ }
607
+
608
+ const promptRegenerated = await regeneratePromptFromHandoffIfHotEvidence(root, backupDir, merged);
609
+ if (promptRegenerated) {
610
+ console.log("auto-repair: START_NEXT_SESSION_PROMPT.txt - regenerate prompt from repaired handoff opening message");
611
+ }
609
612
 
610
613
  // R-031.3 v0.3.4+: Inject current CLI version into PROJECT_INDEX template version
611
614
  // metadata row — placed AFTER the merge loop to avoid the ordering bug where merge
@@ -648,18 +651,18 @@ async function runInstall(command, root, options, version) {
648
651
  // metadata row was stale (counts 0/0/0 but metadataUpdated truthy), user just
649
652
  // received a substantive upgrade — proceed through full ceremony so doctor
650
653
  // self-check confirms the inject result.
651
- const isUpgradeNoop = command === "upgrade"
652
- && created.length === 0
653
- && merged.length === 0
654
- && conflicts.length === 0
655
- && !metadataUpdated;
656
-
657
- if (isUpgradeNoop) {
658
- const noOpHealth = await assessUpgradeNoopHealth(root, version);
659
- printUpgradeNoopShortCircuit(version, noOpHealth);
660
- if (!noOpHealth.ok) process.exitCode = 1;
661
- return;
662
- }
654
+ const isUpgradeNoop = command === "upgrade"
655
+ && created.length === 0
656
+ && merged.length === 0
657
+ && conflicts.length === 0
658
+ && !metadataUpdated;
659
+
660
+ if (isUpgradeNoop) {
661
+ const noOpHealth = await assessUpgradeNoopHealth(root, version);
662
+ printUpgradeNoopShortCircuit(version, noOpHealth);
663
+ if (!noOpHealth.ok) process.exitCode = 1;
664
+ return;
665
+ }
663
666
 
664
667
  const report = await writeMigrationReport(root, command, mode, plan, created, merged, conflicts, migrationDir, backupDir, metadataUpdated);
665
668
  printInstallSummary(version, command, mode, root, {
@@ -671,12 +674,12 @@ async function runInstall(command, root, options, version) {
671
674
  reportRel: path.relative(root, report)
672
675
  });
673
676
 
674
- // R-031 v0.3.1+: install vs upgrade narrative split.
675
- if (command === "upgrade") {
676
- printUpgradeNextSteps(root, conflicts.length);
677
- } else {
678
- printInstallNextSteps(root, conflicts.length, mode, skippedCount);
679
- }
677
+ // R-031 v0.3.1+: install vs upgrade narrative split.
678
+ if (command === "upgrade") {
679
+ printUpgradeNextSteps(root, conflicts.length);
680
+ } else {
681
+ printInstallNextSteps(root, conflicts.length, mode, skippedCount);
682
+ }
680
683
 
681
684
  // R-024 upgrade.done self-check: after substantive upgrade writes, run doctor automatically.
682
685
  // The user must see whether the merged state actually reaches a clean health state.
@@ -712,21 +715,21 @@ async function runDoctor(root, version, options = {}) {
712
715
  console.log(`required files: ${rows.length}`);
713
716
  for (const row of rows) {
714
717
  console.log(`${row.ok ? "ok" : "missing"} ${row.target}`);
715
- }
716
-
717
- if (missing.length > 0) {
718
- const misplacedRulePacks = await findMisplacedRulePacks(root, missing);
719
- printMisplacedRulePackWarnings(misplacedRulePacks);
720
- printDoctorSummary(version, root, "needs-fix", {
721
- checked: rows.length,
722
- failedKind: "missing files",
723
- failedCount: missing.length,
724
- nextStep: misplacedRulePacks.length > 0
725
- ? "同名 rules 檔疑似放錯層。先不要刪除或搬移;請執行 upgrade --dry-run,再正式 upgrade 補回 dev/rules/ 內的正確檔案。"
726
- : missing.length === rows.length
727
- ? "這個資料夾未安裝 Kit。若這就是你的項目資料夾,請執行:npx --yes @adamchanadam/agent-handoff-kit@latest init"
728
- : "這個資料夾只裝了一部分 Kit 檔案。請先確認路徑;如路徑正確,執行:npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run"
729
- });
718
+ }
719
+
720
+ if (missing.length > 0) {
721
+ const misplacedRulePacks = await findMisplacedRulePacks(root, missing);
722
+ printMisplacedRulePackWarnings(misplacedRulePacks);
723
+ printDoctorSummary(version, root, "needs-fix", {
724
+ checked: rows.length,
725
+ failedKind: "missing files",
726
+ failedCount: missing.length,
727
+ nextStep: misplacedRulePacks.length > 0
728
+ ? "同名 rules 檔疑似放錯層。先不要刪除或搬移;請執行 upgrade --dry-run,再正式 upgrade 補回 dev/rules/ 內的正確檔案。"
729
+ : missing.length === rows.length
730
+ ? "這個資料夾未安裝 Kit。若這就是你的項目資料夾,請執行:npx --yes @adamchanadam/agent-handoff-kit@latest init"
731
+ : "這個資料夾只裝了一部分 Kit 檔案。請先確認路徑;如路徑正確,執行:npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run"
732
+ });
730
733
  process.exitCode = 1;
731
734
  return "failed";
732
735
  }
@@ -763,52 +766,52 @@ async function runDoctor(root, version, options = {}) {
763
766
  }
764
767
  }
765
768
 
766
- if (schemaFailures.length > 0) {
767
- printDoctorSummary(version, root, "needs-fix", {
768
- checked: rows.length + anchorRows.length + schemaRows.length,
769
- failedKind: "schema checks",
769
+ if (schemaFailures.length > 0) {
770
+ printDoctorSummary(version, root, "needs-fix", {
771
+ checked: rows.length + anchorRows.length + schemaRows.length,
772
+ failedKind: "schema checks",
770
773
  failedCount: schemaFailures.length,
771
774
  nextStep: "把這段 doctor 輸出貼給 AI,請它先修交接結構,不要直接重裝覆蓋。"
772
775
  });
773
776
  process.exitCode = 1;
774
- return "failed";
775
- }
776
-
777
- const researchTraceResult = await checkResearchDecisionTrace(root);
778
- console.log(`\nresearch decision trace checks: ${researchTraceResult.checked}`);
779
- console.log(`${researchTraceResult.ok ? "ok" : "missing"} dev/PROJECT_DECISIONS.md (research-derived decision evidence chains)`);
780
- if (!researchTraceResult.ok) {
781
- for (const finding of researchTraceResult.findings) {
782
- console.log(` missing: ${finding}`);
783
- }
784
- printDoctorSummary(version, root, "needs-fix", {
785
- checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked,
786
- failedKind: "research decision trace checks",
787
- failedCount: researchTraceResult.findings.length,
788
- nextStep: "把 research-derived decision 的 Evidence chain 補齊,並確認 Source=source:<id> token 已登記在 dev/PROJECT_INDEX.md 的 Fact Base 或 External Sources。"
789
- });
790
- process.exitCode = 1;
791
- return "failed";
792
- }
793
-
794
- const temperatureResult = await checkHandoffTemperatureBoundary(root);
795
- console.log(`\nhandoff temperature boundary checks: ${temperatureResult.checked}`);
796
- console.log(`${temperatureResult.ok ? "ok" : "missing"} dev/SESSION_HANDOFF.md / START_NEXT_SESSION_PROMPT.txt (current-state evidence boundary)`);
797
- if (!temperatureResult.ok) {
798
- for (const finding of temperatureResult.findings) {
799
- console.log(` missing: ${finding}`);
800
- }
801
- printDoctorSummary(version, root, "needs-fix", {
802
- checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked + temperatureResult.checked,
803
- failedKind: "handoff temperature boundary checks",
804
- failedCount: temperatureResult.findings.length,
805
- nextStep: "把一次性驗收證據、舊版本狀態、source token 或 Evidence chain 從 Durable Anchors / Next Priorities / opening message 移回 SESSION_LOG、PROJECT_INDEX 或 PROJECT_DECISIONS。"
806
- });
807
- process.exitCode = 1;
808
- return "failed";
809
- }
810
-
811
- const mirrorRows = await checkPromptMirror(root);
777
+ return "failed";
778
+ }
779
+
780
+ const researchTraceResult = await checkResearchDecisionTrace(root);
781
+ console.log(`\nresearch decision trace checks: ${researchTraceResult.checked}`);
782
+ console.log(`${researchTraceResult.ok ? "ok" : "missing"} dev/PROJECT_DECISIONS.md (research-derived decision evidence chains)`);
783
+ if (!researchTraceResult.ok) {
784
+ for (const finding of researchTraceResult.findings) {
785
+ console.log(` missing: ${finding}`);
786
+ }
787
+ printDoctorSummary(version, root, "needs-fix", {
788
+ checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked,
789
+ failedKind: "research decision trace checks",
790
+ failedCount: researchTraceResult.findings.length,
791
+ nextStep: "把 research-derived decision 的 Evidence chain 補齊,並確認 Source=source:<id> token 已登記在 dev/PROJECT_INDEX.md 的 Fact Base 或 External Sources。"
792
+ });
793
+ process.exitCode = 1;
794
+ return "failed";
795
+ }
796
+
797
+ const temperatureResult = await checkHandoffTemperatureBoundary(root);
798
+ console.log(`\nhandoff temperature boundary checks: ${temperatureResult.checked}`);
799
+ console.log(`${temperatureResult.ok ? "ok" : "missing"} dev/SESSION_HANDOFF.md / START_NEXT_SESSION_PROMPT.txt (current-state evidence boundary)`);
800
+ if (!temperatureResult.ok) {
801
+ for (const finding of temperatureResult.findings) {
802
+ console.log(` missing: ${finding}`);
803
+ }
804
+ printDoctorSummary(version, root, "needs-fix", {
805
+ checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked + temperatureResult.checked,
806
+ failedKind: "handoff temperature boundary checks",
807
+ failedCount: temperatureResult.findings.length,
808
+ nextStep: "把一次性驗收證據、舊版本狀態、source token 或 Evidence chain 從 Durable Anchors / Next Priorities / opening message 移回 SESSION_LOG、PROJECT_INDEX 或 PROJECT_DECISIONS。"
809
+ });
810
+ process.exitCode = 1;
811
+ return "failed";
812
+ }
813
+
814
+ const mirrorRows = await checkPromptMirror(root);
812
815
  const mirrorBlockingFailures = mirrorRows.filter((row) => !row.ok && row.reason !== "convenience copy differs from dev/SESSION_HANDOFF.md");
813
816
  const mirrorWarnings = mirrorRows.filter((row) => !row.ok && row.reason === "convenience copy differs from dev/SESSION_HANDOFF.md");
814
817
  console.log(`\nprompt mirror checks: ${mirrorRows.length}`);
@@ -864,9 +867,9 @@ async function runDoctor(root, version, options = {}) {
864
867
  ? "檢查已通過。START_NEXT_SESSION_PROMPT.txt 只是下次開工便利副本;session 進行中不用手動重生,收工 closeout 時 AI 會從 dev/SESSION_HANDOFF.md 重生。"
865
868
  : null;
866
869
 
867
- const overallHealthy = credentialResult.ok;
868
- printDoctorSummary(version, root, overallHealthy ? "healthy" : "needs-attention", {
869
- checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked + temperatureResult.checked + mirrorRows.length + 2,
870
+ const overallHealthy = credentialResult.ok;
871
+ printDoctorSummary(version, root, overallHealthy ? "healthy" : "needs-attention", {
872
+ checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked + temperatureResult.checked + mirrorRows.length + 2,
870
873
  failedKind: !credentialResult.ok ? "credential leak" : null,
871
874
  failedCount: !credentialResult.ok ? credentialResult.findings.length : 0,
872
875
  warningKind: mirrorWarnings.length > 0 ? "prompt mirror warning" : null,
@@ -874,252 +877,252 @@ async function runDoctor(root, version, options = {}) {
874
877
  nextStep: !credentialResult.ok
875
878
  ? "立即從相關檔案 redact credential value + rotate 已泄露 token;credential 應該由 AI 工具自身 secure storage 管理,永不寫入 dev/* 任何檔。"
876
879
  : disciplineResult.ok
877
- ? versionNextStep ?? promptMirrorNextStep ?? onboardingNextStep ?? "檢查已通過。繼續使用你原本的 AI 開工方式;如剛完成一個任務,記得在 AI 對話輸入「收工」保存交接。"
880
+ ? versionNextStep ?? promptMirrorNextStep ?? onboardingNextStep ?? "檢查已通過。繼續使用你原本的 AI 開工方式;準備結束本輪工作、需要保存交接、或有下一輪必須知道的狀態時,在 AI 對話輸入「收工」。"
878
881
  : "繼續使用;下次 closeout 時 AI 應自動執行 SESSION_LOG N 規則推進(見上面 warn 行)。如未動請要求 AI 重做 closeout。"
879
882
  });
880
- return overallHealthy ? "passed" : "failed";
881
- }
882
-
883
- async function checkResearchDecisionTrace(root) {
884
- const decisionsPath = path.join(root, "dev/PROJECT_DECISIONS.md");
885
- const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
886
- let decisionsText = "";
887
- let indexText = "";
888
- try {
889
- decisionsText = await readFile(decisionsPath, "utf8");
890
- indexText = await readFile(indexPath, "utf8");
891
- } catch {
892
- return { ok: false, checked: 1, findings: ["dev/PROJECT_DECISIONS.md or dev/PROJECT_INDEX.md unreadable"] };
893
- }
894
-
895
- const findings = [];
896
- const sourceTokenPattern = /\bsource:[A-Za-z0-9._-]+\b/g;
897
- const blocks = markdownListBlocks(stripFencedCodeBlocks(decisionsText));
898
- const researchBlocks = blocks.filter((block) => /\bresearch-derived\b/i.test(block) || /Evidence chain:/i.test(block));
899
-
900
- researchBlocks.forEach((block, index) => {
901
- const label = `research-derived decision #${index + 1}`;
902
- if (!/Evidence chain:/i.test(block)) {
903
- findings.push(`${label} missing Evidence chain`);
904
- }
905
- const tokens = [...block.matchAll(sourceTokenPattern)].map((match) => match[0]);
906
- if (tokens.length === 0) {
907
- findings.push(`${label} missing source:<id> token`);
908
- }
909
- for (const token of tokens) {
910
- if (!indexText.includes(token)) {
911
- findings.push(`${label} references ${token}, but dev/PROJECT_INDEX.md does not contain that token`);
912
- }
913
- }
914
- });
915
-
916
- return { ok: findings.length === 0, checked: 1, findings };
917
- }
918
-
919
- function stripFencedCodeBlocks(text) {
920
- return text.replace(/```[\s\S]*?```/g, "");
921
- }
922
-
923
- function markdownListBlocks(text) {
924
- const blocks = [];
925
- let current = [];
926
- for (const line of text.split(/\r?\n/)) {
927
- if (/^\s*[-*]\s+/.test(line)) {
928
- if (current.length > 0) blocks.push(current.join("\n"));
929
- current = [line];
930
- } else if (current.length > 0 && (/^\s{2,}\S/.test(line) || /^\s*$/.test(line))) {
931
- current.push(line);
932
- } else if (current.length > 0) {
933
- blocks.push(current.join("\n"));
934
- current = [];
935
- }
936
- }
937
- if (current.length > 0) blocks.push(current.join("\n"));
938
- return blocks;
939
- }
940
-
941
- async function checkHandoffTemperatureBoundary(root) {
942
- const findings = [];
943
- const sections = [];
944
- let handoffText = "";
945
-
946
- try {
947
- handoffText = await readFile(path.join(root, "dev/SESSION_HANDOFF.md"), "utf8");
948
- } catch {
949
- return { ok: false, checked: 1, findings: ["dev/SESSION_HANDOFF.md unreadable"] };
950
- }
951
-
952
- sections.push(
953
- { label: "Durable Anchors", text: extractHandoffSectionText(handoffText, "durable-anchors", "Durable Anchors") },
954
- { label: "Next Priorities", text: extractHandoffSectionText(handoffText, "next-priorities", "Next Priorities") },
955
- { label: "Next Session Opening Message", text: extractHandoffSectionText(handoffText, "next-session-opening-message", "Next Session Opening Message") }
956
- );
957
-
958
- const requiredReading = extractHandoffSectionText(handoffText, "next-task-required-reading", "Next Task Required Reading");
959
- sections.push({ label: "Next Task Required Reading", text: requiredReading, allowSourceTokens: true });
960
-
961
- try {
962
- const promptText = await readFile(path.join(root, "START_NEXT_SESSION_PROMPT.txt"), "utf8");
963
- sections.push({ label: "START_NEXT_SESSION_PROMPT.txt", text: promptText });
964
- } catch {
965
- // Missing prompt mirror is handled by prompt mirror checks; do not duplicate the failure here.
966
- }
967
-
968
- for (const section of sections) {
969
- if (!section.text) continue;
970
- findings.push(...currentStateEvidenceFindings(section.label, section.text, { allowSourceTokens: section.allowSourceTokens }));
971
- }
972
-
973
- return { ok: findings.length === 0, checked: 1, findings };
974
- }
975
-
976
- const rootMismatchGuard = "If this root does not match the expected project root";
977
-
978
- function currentStateEvidenceRules() {
979
- return [
980
- { pattern: /post-publish artifact smoke/i, label: "post-publish artifact smoke evidence" },
981
- { pattern: /PASS\s+7\/7/i, label: "historical PASS count" },
982
- { pattern: /\bfileCount\b/i, label: "published artifact fileCount evidence" },
983
- { pattern: /\brelease source\b/i, label: "release source evidence" },
984
- { pattern: /Cross-mind evidence/i, label: "cross-agent review evidence" },
985
- { pattern: /Evidence chain:/i, label: "research evidence chain" },
986
- { pattern: /\bnpm latest\s+(?:is|=|v?\d)/i, label: "historical npm latest state" },
987
- { pattern: /GitHub Release\s+(?:metadata|published|view|`?v?\d)/i, label: "historical GitHub Release state" }
988
- ];
989
- }
990
-
991
- function currentStateEvidenceFindings(sectionLabel, text, options = {}) {
992
- const findings = [];
993
- for (const rule of currentStateEvidenceRules()) {
994
- if (rule.pattern.test(text)) {
995
- findings.push(`${sectionLabel} contains ${rule.label}; keep it in trace evidence unless it still affects the next action`);
996
- }
997
- }
998
- if (!options.allowSourceTokens && /\bsource:[A-Za-z0-9._-]+\b/.test(text)) {
999
- findings.push(`${sectionLabel} contains source:<id>; keep source tokens in PROJECT_INDEX / PROJECT_DECISIONS, not hot startup state`);
1000
- }
1001
- return findings;
1002
- }
1003
-
1004
- function lineHasCurrentStateEvidence(line, options = {}) {
1005
- return currentStateEvidenceFindings("line", line, options).length > 0;
1006
- }
1007
-
1008
- function repairHandoffOpeningRootGuard(text) {
1009
- if (text.includes(rootMismatchGuard)) return { changed: false, text };
1010
- const bounds = handoffSectionContentBounds(text, "next-session-opening-message", "Next Session Opening Message");
1011
- if (!bounds) return { changed: false, text };
1012
- const section = text.slice(bounds.start, bounds.end);
1013
- if (!section.includes("```text")) return { changed: false, text };
1014
-
1015
- let repairedSection = section;
1016
- if (/^Before changing anything,/m.test(repairedSection)) {
1017
- repairedSection = repairedSection.replace(/^Before changing anything,/m, `${rootMismatchGuard}, stop and ask for confirmation.\n\nBefore changing anything,`);
1018
- } else if (/\n```/.test(repairedSection)) {
1019
- repairedSection = repairedSection.replace(/\n```/, `\n${rootMismatchGuard}, stop and ask for confirmation.\n\n\`\`\``);
1020
- } else {
1021
- return { changed: false, text };
1022
- }
1023
-
1024
- return {
1025
- changed: repairedSection !== section,
1026
- text: `${text.slice(0, bounds.start)}${repairedSection}${text.slice(bounds.end)}`
1027
- };
1028
- }
1029
-
1030
- function repairHandoffCurrentStateEvidenceBoundary(text) {
1031
- let repaired = text;
1032
- let changed = false;
1033
- for (const section of [
1034
- { id: "durable-anchors", heading: "Durable Anchors" },
1035
- { id: "next-priorities", heading: "Next Priorities" },
1036
- { id: "next-session-opening-message", heading: "Next Session Opening Message" }
1037
- ]) {
1038
- const bounds = handoffSectionContentBounds(repaired, section.id, section.heading);
1039
- if (!bounds) continue;
1040
- const originalSection = repaired.slice(bounds.start, bounds.end);
1041
- const lines = originalSection.split(/\r?\n/);
1042
- const cleanedLines = lines.filter((line) => !lineHasCurrentStateEvidence(line));
1043
- if (cleanedLines.length !== lines.length) {
1044
- const cleanedSection = cleanedLines.join("\n");
1045
- repaired = `${repaired.slice(0, bounds.start)}${cleanedSection}${repaired.slice(bounds.end)}`;
1046
- changed = true;
1047
- }
1048
- }
1049
- return { changed, text: repaired };
1050
- }
1051
-
1052
- function handoffSectionContentBounds(text, id, headingText) {
1053
- const marker = `<!-- ack:section:${id} -->`;
1054
- const markerStart = text.indexOf(marker);
1055
- if (markerStart >= 0) {
1056
- const start = markerStart + marker.length;
1057
- const nextMarker = text.indexOf("<!-- ack:section:", start);
1058
- return { start, end: nextMarker >= 0 ? nextMarker : text.length };
1059
- }
1060
-
1061
- const headingPattern = new RegExp(`^##\\s+${escapeRegExp(headingText)}\\s*$`, "m");
1062
- const headingMatch = headingPattern.exec(text);
1063
- if (!headingMatch) return null;
1064
- const start = headingMatch.index + headingMatch[0].length;
1065
- const nextHeading = /\n##\s+/g;
1066
- nextHeading.lastIndex = start;
1067
- const nextMatch = nextHeading.exec(text);
1068
- return { start, end: nextMatch ? nextMatch.index : text.length };
1069
- }
1070
-
1071
- function extractHandoffSectionText(text, id, headingText) {
1072
- const marker = `<!-- ack:section:${id} -->`;
1073
- const markerStart = text.indexOf(marker);
1074
- if (markerStart >= 0) {
1075
- const afterMarker = markerStart + marker.length;
1076
- const nextMarker = text.indexOf("<!-- ack:section:", afterMarker);
1077
- return text.slice(afterMarker, nextMarker >= 0 ? nextMarker : text.length);
1078
- }
1079
-
1080
- const headingPattern = new RegExp(`^##\\s+${escapeRegExp(headingText)}\\s*$`, "m");
1081
- const headingMatch = headingPattern.exec(text);
1082
- if (!headingMatch) return "";
1083
- const start = headingMatch.index + headingMatch[0].length;
1084
- const nextHeading = /\n##\s+/g;
1085
- nextHeading.lastIndex = start;
1086
- const nextMatch = nextHeading.exec(text);
1087
- return text.slice(start, nextMatch ? nextMatch.index : text.length);
1088
- }
1089
-
1090
- async function regeneratePromptFromHandoffIfHotEvidence(root, backupDir, merged) {
1091
- const handoffPath = path.join(root, "dev/SESSION_HANDOFF.md");
1092
- const promptPath = path.join(root, "START_NEXT_SESSION_PROMPT.txt");
1093
- let handoffText = "";
1094
- let promptText = "";
1095
- try {
1096
- handoffText = await readFile(handoffPath, "utf8");
1097
- promptText = await readFile(promptPath, "utf8");
1098
- } catch {
1099
- return false;
1100
- }
1101
-
1102
- const opening = extractOpeningMessage(handoffText);
1103
- if (opening == null) return false;
1104
-
1105
- const promptNeedsRepair = lineHasCurrentStateEvidence(promptText)
1106
- || (!promptText.includes(rootMismatchGuard) && opening.includes(rootMismatchGuard));
1107
- if (!promptNeedsRepair) return false;
1108
-
1109
- const backupPath = path.join(backupDir, "START_NEXT_SESSION_PROMPT.txt");
1110
- await mkdir(path.dirname(backupPath), { recursive: true });
1111
- await copyFile(promptPath, backupPath);
1112
- await writeFile(promptPath, `${opening}\n`, "utf8");
1113
- if (!merged.some((item) => item.startsWith("START_NEXT_SESSION_PROMPT.txt"))) {
1114
- merged.push("START_NEXT_SESSION_PROMPT.txt - regenerate prompt from repaired handoff opening message");
1115
- }
1116
- return true;
1117
- }
1118
-
1119
- function getFirstUseNextStep(root, lastCloseout) {
1120
- if (lastCloseout.date) return null;
1121
- return `檢查已通過。下一步不要再留在終端機;打開能讀寫此資料夾的 AI agent。若 AI 已在此資料夾內,輸入 Start Agent Handoff 或「開工」;若 AI 還未指向此資料夾,才貼:${startupPathBootstrapPrompt(root)}`;
1122
- }
883
+ return overallHealthy ? "passed" : "failed";
884
+ }
885
+
886
+ async function checkResearchDecisionTrace(root) {
887
+ const decisionsPath = path.join(root, "dev/PROJECT_DECISIONS.md");
888
+ const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
889
+ let decisionsText = "";
890
+ let indexText = "";
891
+ try {
892
+ decisionsText = await readFile(decisionsPath, "utf8");
893
+ indexText = await readFile(indexPath, "utf8");
894
+ } catch {
895
+ return { ok: false, checked: 1, findings: ["dev/PROJECT_DECISIONS.md or dev/PROJECT_INDEX.md unreadable"] };
896
+ }
897
+
898
+ const findings = [];
899
+ const sourceTokenPattern = /\bsource:[A-Za-z0-9._-]+\b/g;
900
+ const blocks = markdownListBlocks(stripFencedCodeBlocks(decisionsText));
901
+ const researchBlocks = blocks.filter((block) => /\bresearch-derived\b/i.test(block) || /Evidence chain:/i.test(block));
902
+
903
+ researchBlocks.forEach((block, index) => {
904
+ const label = `research-derived decision #${index + 1}`;
905
+ if (!/Evidence chain:/i.test(block)) {
906
+ findings.push(`${label} missing Evidence chain`);
907
+ }
908
+ const tokens = [...block.matchAll(sourceTokenPattern)].map((match) => match[0]);
909
+ if (tokens.length === 0) {
910
+ findings.push(`${label} missing source:<id> token`);
911
+ }
912
+ for (const token of tokens) {
913
+ if (!indexText.includes(token)) {
914
+ findings.push(`${label} references ${token}, but dev/PROJECT_INDEX.md does not contain that token`);
915
+ }
916
+ }
917
+ });
918
+
919
+ return { ok: findings.length === 0, checked: 1, findings };
920
+ }
921
+
922
+ function stripFencedCodeBlocks(text) {
923
+ return text.replace(/```[\s\S]*?```/g, "");
924
+ }
925
+
926
+ function markdownListBlocks(text) {
927
+ const blocks = [];
928
+ let current = [];
929
+ for (const line of text.split(/\r?\n/)) {
930
+ if (/^\s*[-*]\s+/.test(line)) {
931
+ if (current.length > 0) blocks.push(current.join("\n"));
932
+ current = [line];
933
+ } else if (current.length > 0 && (/^\s{2,}\S/.test(line) || /^\s*$/.test(line))) {
934
+ current.push(line);
935
+ } else if (current.length > 0) {
936
+ blocks.push(current.join("\n"));
937
+ current = [];
938
+ }
939
+ }
940
+ if (current.length > 0) blocks.push(current.join("\n"));
941
+ return blocks;
942
+ }
943
+
944
+ async function checkHandoffTemperatureBoundary(root) {
945
+ const findings = [];
946
+ const sections = [];
947
+ let handoffText = "";
948
+
949
+ try {
950
+ handoffText = await readFile(path.join(root, "dev/SESSION_HANDOFF.md"), "utf8");
951
+ } catch {
952
+ return { ok: false, checked: 1, findings: ["dev/SESSION_HANDOFF.md unreadable"] };
953
+ }
954
+
955
+ sections.push(
956
+ { label: "Durable Anchors", text: extractHandoffSectionText(handoffText, "durable-anchors", "Durable Anchors") },
957
+ { label: "Next Priorities", text: extractHandoffSectionText(handoffText, "next-priorities", "Next Priorities") },
958
+ { label: "Next Session Opening Message", text: extractHandoffSectionText(handoffText, "next-session-opening-message", "Next Session Opening Message") }
959
+ );
960
+
961
+ const requiredReading = extractHandoffSectionText(handoffText, "next-task-required-reading", "Next Task Required Reading");
962
+ sections.push({ label: "Next Task Required Reading", text: requiredReading, allowSourceTokens: true });
963
+
964
+ try {
965
+ const promptText = await readFile(path.join(root, "START_NEXT_SESSION_PROMPT.txt"), "utf8");
966
+ sections.push({ label: "START_NEXT_SESSION_PROMPT.txt", text: promptText });
967
+ } catch {
968
+ // Missing prompt mirror is handled by prompt mirror checks; do not duplicate the failure here.
969
+ }
970
+
971
+ for (const section of sections) {
972
+ if (!section.text) continue;
973
+ findings.push(...currentStateEvidenceFindings(section.label, section.text, { allowSourceTokens: section.allowSourceTokens }));
974
+ }
975
+
976
+ return { ok: findings.length === 0, checked: 1, findings };
977
+ }
978
+
979
+ const rootMismatchGuard = "If this root does not match the expected project root";
980
+
981
+ function currentStateEvidenceRules() {
982
+ return [
983
+ { pattern: /post-publish artifact smoke/i, label: "post-publish artifact smoke evidence" },
984
+ { pattern: /PASS\s+7\/7/i, label: "historical PASS count" },
985
+ { pattern: /\bfileCount\b/i, label: "published artifact fileCount evidence" },
986
+ { pattern: /\brelease source\b/i, label: "release source evidence" },
987
+ { pattern: /Cross-mind evidence/i, label: "cross-agent review evidence" },
988
+ { pattern: /Evidence chain:/i, label: "research evidence chain" },
989
+ { pattern: /\bnpm latest\s+(?:is|=|v?\d)/i, label: "historical npm latest state" },
990
+ { pattern: /GitHub Release\s+(?:metadata|published|view|`?v?\d)/i, label: "historical GitHub Release state" }
991
+ ];
992
+ }
993
+
994
+ function currentStateEvidenceFindings(sectionLabel, text, options = {}) {
995
+ const findings = [];
996
+ for (const rule of currentStateEvidenceRules()) {
997
+ if (rule.pattern.test(text)) {
998
+ findings.push(`${sectionLabel} contains ${rule.label}; keep it in trace evidence unless it still affects the next action`);
999
+ }
1000
+ }
1001
+ if (!options.allowSourceTokens && /\bsource:[A-Za-z0-9._-]+\b/.test(text)) {
1002
+ findings.push(`${sectionLabel} contains source:<id>; keep source tokens in PROJECT_INDEX / PROJECT_DECISIONS, not hot startup state`);
1003
+ }
1004
+ return findings;
1005
+ }
1006
+
1007
+ function lineHasCurrentStateEvidence(line, options = {}) {
1008
+ return currentStateEvidenceFindings("line", line, options).length > 0;
1009
+ }
1010
+
1011
+ function repairHandoffOpeningRootGuard(text) {
1012
+ if (text.includes(rootMismatchGuard)) return { changed: false, text };
1013
+ const bounds = handoffSectionContentBounds(text, "next-session-opening-message", "Next Session Opening Message");
1014
+ if (!bounds) return { changed: false, text };
1015
+ const section = text.slice(bounds.start, bounds.end);
1016
+ if (!section.includes("```text")) return { changed: false, text };
1017
+
1018
+ let repairedSection = section;
1019
+ if (/^Before changing anything,/m.test(repairedSection)) {
1020
+ repairedSection = repairedSection.replace(/^Before changing anything,/m, `${rootMismatchGuard}, stop and ask for confirmation.\n\nBefore changing anything,`);
1021
+ } else if (/\n```/.test(repairedSection)) {
1022
+ repairedSection = repairedSection.replace(/\n```/, `\n${rootMismatchGuard}, stop and ask for confirmation.\n\n\`\`\``);
1023
+ } else {
1024
+ return { changed: false, text };
1025
+ }
1026
+
1027
+ return {
1028
+ changed: repairedSection !== section,
1029
+ text: `${text.slice(0, bounds.start)}${repairedSection}${text.slice(bounds.end)}`
1030
+ };
1031
+ }
1032
+
1033
+ function repairHandoffCurrentStateEvidenceBoundary(text) {
1034
+ let repaired = text;
1035
+ let changed = false;
1036
+ for (const section of [
1037
+ { id: "durable-anchors", heading: "Durable Anchors" },
1038
+ { id: "next-priorities", heading: "Next Priorities" },
1039
+ { id: "next-session-opening-message", heading: "Next Session Opening Message" }
1040
+ ]) {
1041
+ const bounds = handoffSectionContentBounds(repaired, section.id, section.heading);
1042
+ if (!bounds) continue;
1043
+ const originalSection = repaired.slice(bounds.start, bounds.end);
1044
+ const lines = originalSection.split(/\r?\n/);
1045
+ const cleanedLines = lines.filter((line) => !lineHasCurrentStateEvidence(line));
1046
+ if (cleanedLines.length !== lines.length) {
1047
+ const cleanedSection = cleanedLines.join("\n");
1048
+ repaired = `${repaired.slice(0, bounds.start)}${cleanedSection}${repaired.slice(bounds.end)}`;
1049
+ changed = true;
1050
+ }
1051
+ }
1052
+ return { changed, text: repaired };
1053
+ }
1054
+
1055
+ function handoffSectionContentBounds(text, id, headingText) {
1056
+ const marker = `<!-- ack:section:${id} -->`;
1057
+ const markerStart = text.indexOf(marker);
1058
+ if (markerStart >= 0) {
1059
+ const start = markerStart + marker.length;
1060
+ const nextMarker = text.indexOf("<!-- ack:section:", start);
1061
+ return { start, end: nextMarker >= 0 ? nextMarker : text.length };
1062
+ }
1063
+
1064
+ const headingPattern = new RegExp(`^##\\s+${escapeRegExp(headingText)}\\s*$`, "m");
1065
+ const headingMatch = headingPattern.exec(text);
1066
+ if (!headingMatch) return null;
1067
+ const start = headingMatch.index + headingMatch[0].length;
1068
+ const nextHeading = /\n##\s+/g;
1069
+ nextHeading.lastIndex = start;
1070
+ const nextMatch = nextHeading.exec(text);
1071
+ return { start, end: nextMatch ? nextMatch.index : text.length };
1072
+ }
1073
+
1074
+ function extractHandoffSectionText(text, id, headingText) {
1075
+ const marker = `<!-- ack:section:${id} -->`;
1076
+ const markerStart = text.indexOf(marker);
1077
+ if (markerStart >= 0) {
1078
+ const afterMarker = markerStart + marker.length;
1079
+ const nextMarker = text.indexOf("<!-- ack:section:", afterMarker);
1080
+ return text.slice(afterMarker, nextMarker >= 0 ? nextMarker : text.length);
1081
+ }
1082
+
1083
+ const headingPattern = new RegExp(`^##\\s+${escapeRegExp(headingText)}\\s*$`, "m");
1084
+ const headingMatch = headingPattern.exec(text);
1085
+ if (!headingMatch) return "";
1086
+ const start = headingMatch.index + headingMatch[0].length;
1087
+ const nextHeading = /\n##\s+/g;
1088
+ nextHeading.lastIndex = start;
1089
+ const nextMatch = nextHeading.exec(text);
1090
+ return text.slice(start, nextMatch ? nextMatch.index : text.length);
1091
+ }
1092
+
1093
+ async function regeneratePromptFromHandoffIfHotEvidence(root, backupDir, merged) {
1094
+ const handoffPath = path.join(root, "dev/SESSION_HANDOFF.md");
1095
+ const promptPath = path.join(root, "START_NEXT_SESSION_PROMPT.txt");
1096
+ let handoffText = "";
1097
+ let promptText = "";
1098
+ try {
1099
+ handoffText = await readFile(handoffPath, "utf8");
1100
+ promptText = await readFile(promptPath, "utf8");
1101
+ } catch {
1102
+ return false;
1103
+ }
1104
+
1105
+ const opening = extractOpeningMessage(handoffText);
1106
+ if (opening == null) return false;
1107
+
1108
+ const promptNeedsRepair = lineHasCurrentStateEvidence(promptText)
1109
+ || (!promptText.includes(rootMismatchGuard) && opening.includes(rootMismatchGuard));
1110
+ if (!promptNeedsRepair) return false;
1111
+
1112
+ const backupPath = path.join(backupDir, "START_NEXT_SESSION_PROMPT.txt");
1113
+ await mkdir(path.dirname(backupPath), { recursive: true });
1114
+ await copyFile(promptPath, backupPath);
1115
+ await writeFile(promptPath, `${opening}\n`, "utf8");
1116
+ if (!merged.some((item) => item.startsWith("START_NEXT_SESSION_PROMPT.txt"))) {
1117
+ merged.push("START_NEXT_SESSION_PROMPT.txt - regenerate prompt from repaired handoff opening message");
1118
+ }
1119
+ return true;
1120
+ }
1121
+
1122
+ function getFirstUseNextStep(root, lastCloseout) {
1123
+ if (lastCloseout.date) return null;
1124
+ return `檢查已通過。下一步不要再留在終端機;打開能讀寫此資料夾的 AI agent。若 AI 已在此資料夾內,輸入 Start Agent Handoff 或「開工」;若 AI 還未指向此資料夾,才貼:${startupPathBootstrapPrompt(root)}`;
1125
+ }
1123
1126
 
1124
1127
  // R-030 v0.3.0+: Credential leak prevention sweep. Scans dev/PROJECT_INDEX.md,
1125
1128
  // dev/SESSION_HANDOFF.md, dev/SESSION_LOG.md for common credential prefix patterns.
@@ -1177,10 +1180,10 @@ function printDoctorSummary(version, root, mode, details) {
1177
1180
  } else {
1178
1181
  console.log("✅ 檢查通過:必要文件存在,基本結構完整,下次開工提示副本已與 handoff 一致。");
1179
1182
  }
1180
- } else {
1181
- console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
1182
- console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : details.failedKind === "research decision trace checks" ? "研究導向決策缺少可追溯來源鏈。" : details.failedKind === "handoff temperature boundary checks" ? "當前交接內容混入一次性或歷史證據。" : "下次開工提示副本與 handoff 真源不同。"}`);
1183
- }
1183
+ } else {
1184
+ console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
1185
+ console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : details.failedKind === "research decision trace checks" ? "研究導向決策缺少可追溯來源鏈。" : details.failedKind === "handoff temperature boundary checks" ? "當前交接內容混入一次性或歷史證據。" : "下次開工提示副本與 handoff 真源不同。"}`);
1186
+ }
1184
1187
  console.log("");
1185
1188
  console.log(`📦 版本:v${version}`);
1186
1189
  console.log(`🩺 模式:${mode}`);
@@ -1242,7 +1245,7 @@ async function hydrateInitialOpeningPrompt(root, created) {
1242
1245
  }
1243
1246
  }
1244
1247
 
1245
- async function checkPromptMirror(root) {
1248
+ async function checkPromptMirror(root) {
1246
1249
  const handoffPath = path.join(root, "dev/SESSION_HANDOFF.md");
1247
1250
  const promptPath = path.join(root, "START_NEXT_SESSION_PROMPT.txt");
1248
1251
  let handoffText = "";
@@ -1257,14 +1260,14 @@ async function checkPromptMirror(root) {
1257
1260
  } catch {
1258
1261
  return [{ target: "START_NEXT_SESSION_PROMPT.txt", label: "matches handoff opening message", ok: false, reason: "prompt copy unreadable" }];
1259
1262
  }
1260
- const mirror = assessPromptMirrorTexts(handoffText, promptText);
1261
- return [{
1262
- target: "START_NEXT_SESSION_PROMPT.txt",
1263
- label: "matches handoff opening message",
1264
- ok: mirror.ok,
1265
- reason: mirror.ok ? "" : mirror.reason
1266
- }];
1267
- }
1263
+ const mirror = assessPromptMirrorTexts(handoffText, promptText);
1264
+ return [{
1265
+ target: "START_NEXT_SESSION_PROMPT.txt",
1266
+ label: "matches handoff opening message",
1267
+ ok: mirror.ok,
1268
+ reason: mirror.ok ? "" : mirror.reason
1269
+ }];
1270
+ }
1268
1271
 
1269
1272
  function assessHandoffLifecycleConsistency(text) {
1270
1273
  const fieldValue = fieldValueAfterMarker(text, "lifecycle-conflicts-resolved");
@@ -1285,21 +1288,21 @@ function isAffirmativeLifecycleFieldValue(value) {
1285
1288
  return /^(yes|resolved|confirmed|complete|completed|ok|passed|all clear)\b|^(是|已|完成|已完成|已解決|已核對|已確認|通過)\b/i.test(trimmed);
1286
1289
  }
1287
1290
 
1288
- function isUnresolvedLifecycleFieldValue(value) {
1289
- const trimmed = normalizeLifecycleFieldValue(value);
1290
- return /^(no|blocked|uncertain)\b|^(否|阻擋|不確定)\b/i.test(trimmed)
1291
- || /\b(still unresolved|not resolved)\b|仍未解決|尚未解決/i.test(trimmed);
1292
- }
1293
-
1294
- function isPlaceholderLifecycleFieldValue(value) {
1295
- const trimmed = normalizeLifecycleFieldValue(value);
1296
- return !trimmed
1297
- || /^(TBD|todo|pending|unverified|unknown|needs-review)\b|^(待核對|待確認|未核對|未確認)\b/i.test(trimmed);
1298
- }
1299
-
1300
- function normalizeLifecycleFieldValue(value) {
1301
- return (value || "").trim().replace(/^[-*]\s*/, "");
1302
- }
1291
+ function isUnresolvedLifecycleFieldValue(value) {
1292
+ const trimmed = normalizeLifecycleFieldValue(value);
1293
+ return /^(no|blocked|uncertain)\b|^(否|阻擋|不確定)\b/i.test(trimmed)
1294
+ || /\b(still unresolved|not resolved)\b|仍未解決|尚未解決/i.test(trimmed);
1295
+ }
1296
+
1297
+ function isPlaceholderLifecycleFieldValue(value) {
1298
+ const trimmed = normalizeLifecycleFieldValue(value);
1299
+ return !trimmed
1300
+ || /^(TBD|todo|pending|unverified|unknown|needs-review)\b|^(待核對|待確認|未核對|未確認)\b/i.test(trimmed);
1301
+ }
1302
+
1303
+ function normalizeLifecycleFieldValue(value) {
1304
+ return (value || "").trim().replace(/^[-*]\s*/, "");
1305
+ }
1303
1306
 
1304
1307
  function hasSubstantiveHandoffState(text) {
1305
1308
  const sections = [
@@ -1331,10 +1334,10 @@ function fieldValueAfterMarker(text, fieldId) {
1331
1334
  return fallback ? fallback[1].trim() : "";
1332
1335
  }
1333
1336
 
1334
- function extractSectionText(text, markerId, headingTitle) {
1335
- const markerText = `ack:section:${markerId}`;
1336
- const markerIndex = text.indexOf(markerText);
1337
- if (markerIndex >= 0) {
1337
+ function extractSectionText(text, markerId, headingTitle) {
1338
+ const markerText = `ack:section:${markerId}`;
1339
+ const markerIndex = text.indexOf(markerText);
1340
+ if (markerIndex >= 0) {
1338
1341
  const start = text.indexOf("\n", markerIndex);
1339
1342
  if (start < 0) return "";
1340
1343
  const nextMarker = text.indexOf("<!-- ack:section:", start + 1);
@@ -1344,37 +1347,37 @@ function extractSectionText(text, markerId, headingTitle) {
1344
1347
  const headingMatch = new RegExp(`^## ${escapeRegExp(headingTitle)}\\s*$`, "m").exec(text);
1345
1348
  if (!headingMatch) return "";
1346
1349
  const start = headingMatch.index + headingMatch[0].length;
1347
- const nextHeading = /\n##\s+/.exec(text.slice(start));
1348
- return text.slice(start, nextHeading ? start + nextHeading.index : text.length);
1349
- }
1350
-
1351
- async function findMisplacedRulePacks(root, missingRows) {
1352
- const missingTargets = new Set(missingRows.map((row) => row.target));
1353
- const findings = [];
1354
- for (const target of rulePackTargets) {
1355
- if (!missingTargets.has(target)) continue;
1356
- const fileName = path.basename(target);
1357
- const misplacedRel = path.join("dev", fileName).replaceAll(path.sep, "/");
1358
- if (await exists(path.join(root, misplacedRel))) {
1359
- findings.push({ expected: target, misplaced: misplacedRel });
1360
- }
1361
- }
1362
- return findings;
1363
- }
1364
-
1365
- function printMisplacedRulePackWarnings(findings) {
1366
- if (findings.length === 0) return;
1367
- console.log("");
1368
- console.log("misplaced rule pack hints:");
1369
- for (const finding of findings) {
1370
- console.log(`warning ${finding.expected} missing, but ${finding.misplaced} exists`);
1371
- }
1372
- console.log(" 同名 rules 檔疑似放錯層;upgrade 會補回 dev/rules/ 內的正確檔案,但不會自動刪除或搬移 dev/ 根層副本。");
1373
- }
1374
-
1375
- async function checkRequiredAnchors(root) {
1376
- const rows = [];
1377
- for (const rule of requiredAnchors) {
1350
+ const nextHeading = /\n##\s+/.exec(text.slice(start));
1351
+ return text.slice(start, nextHeading ? start + nextHeading.index : text.length);
1352
+ }
1353
+
1354
+ async function findMisplacedRulePacks(root, missingRows) {
1355
+ const missingTargets = new Set(missingRows.map((row) => row.target));
1356
+ const findings = [];
1357
+ for (const target of rulePackTargets) {
1358
+ if (!missingTargets.has(target)) continue;
1359
+ const fileName = path.basename(target);
1360
+ const misplacedRel = path.join("dev", fileName).replaceAll(path.sep, "/");
1361
+ if (await exists(path.join(root, misplacedRel))) {
1362
+ findings.push({ expected: target, misplaced: misplacedRel });
1363
+ }
1364
+ }
1365
+ return findings;
1366
+ }
1367
+
1368
+ function printMisplacedRulePackWarnings(findings) {
1369
+ if (findings.length === 0) return;
1370
+ console.log("");
1371
+ console.log("misplaced rule pack hints:");
1372
+ for (const finding of findings) {
1373
+ console.log(`warning ${finding.expected} missing, but ${finding.misplaced} exists`);
1374
+ }
1375
+ console.log(" 同名 rules 檔疑似放錯層;upgrade 會補回 dev/rules/ 內的正確檔案,但不會自動刪除或搬移 dev/ 根層副本。");
1376
+ }
1377
+
1378
+ async function checkRequiredAnchors(root) {
1379
+ const rows = [];
1380
+ for (const rule of requiredAnchors) {
1378
1381
  const filePath = path.join(root, rule.target);
1379
1382
  let text = "";
1380
1383
  try {
@@ -1384,15 +1387,15 @@ async function checkRequiredAnchors(root) {
1384
1387
  continue;
1385
1388
  }
1386
1389
 
1387
- // Report which specific anchor snippets are absent or semantically misplaced,
1388
- // not just pass/fail. A naked snippet at file tail must not make doctor green.
1389
- const failures = requiredAnchorFailures(rule, text);
1390
- const missing = failures.map((failure) => failure.kind === "missing"
1391
- ? failure.snippet
1392
- : `misplaced: ${failure.snippet}`);
1393
- rows.push({
1394
- target: rule.target,
1395
- label: rule.label,
1390
+ // Report which specific anchor snippets are absent or semantically misplaced,
1391
+ // not just pass/fail. A naked snippet at file tail must not make doctor green.
1392
+ const failures = requiredAnchorFailures(rule, text);
1393
+ const missing = failures.map((failure) => failure.kind === "missing"
1394
+ ? failure.snippet
1395
+ : `misplaced: ${failure.snippet}`);
1396
+ rows.push({
1397
+ target: rule.target,
1398
+ label: rule.label,
1396
1399
  ok: missing.length === 0,
1397
1400
  missing
1398
1401
  });
@@ -1462,52 +1465,52 @@ function tableHeader(...cells) {
1462
1465
  };
1463
1466
  }
1464
1467
 
1465
- async function buildPlan(root, command, version = null) {
1466
- const plan = [];
1467
- const context = {
1468
- currentVersion: version,
1469
- rootTemplateVersion: command === "upgrade" ? await readRootTemplateVersion(root) : null
1470
- };
1471
- for (const [sourceRel, targetRel] of mappings) {
1472
- const sourceAbs = path.join(packageRoot, sourceRel);
1473
- const targetAbs = path.join(root, targetRel);
1474
- const sourceText = await readFile(sourceAbs, "utf8");
1475
- if (await exists(targetAbs)) {
1476
- const targetText = await readFile(targetAbs, "utf8");
1477
- plan.push(classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAbs, sourceText, targetText, context));
1478
- continue;
1479
- }
1480
- const misplacedRel = targetRel.startsWith("dev/rules/")
1481
- ? path.join("dev", path.basename(targetRel)).replaceAll(path.sep, "/")
1482
- : null;
1483
- const reason = misplacedRel && await exists(path.join(root, misplacedRel))
1484
- ? `same-named rules file appears one level up at ${misplacedRel}; create correct dev/rules/ copy without deleting or moving the misplaced file`
1485
- : undefined;
1486
- plan.push({
1487
- sourceRel,
1488
- targetRel,
1489
- sourceAbs,
1490
- targetAbs,
1491
- action: "create",
1492
- ...(reason ? { reason } : {})
1493
- });
1494
- }
1495
- return plan;
1496
- }
1497
-
1498
- async function readRootTemplateVersion(root) {
1499
- try {
1500
- const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
1501
- const text = await readFile(indexPath, "utf8");
1502
- const m = text.match(/\| Agent Handoff Kit template version \| ([\d.]+) \|/);
1503
- return m?.[1] ?? null;
1504
- } catch {
1505
- return null;
1506
- }
1507
- }
1508
-
1509
- function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAbs, sourceText, targetText, context = {}) {
1510
- const base = { sourceRel, targetRel, sourceAbs, targetAbs };
1468
+ async function buildPlan(root, command, version = null) {
1469
+ const plan = [];
1470
+ const context = {
1471
+ currentVersion: version,
1472
+ rootTemplateVersion: command === "upgrade" ? await readRootTemplateVersion(root) : null
1473
+ };
1474
+ for (const [sourceRel, targetRel] of mappings) {
1475
+ const sourceAbs = path.join(packageRoot, sourceRel);
1476
+ const targetAbs = path.join(root, targetRel);
1477
+ const sourceText = await readFile(sourceAbs, "utf8");
1478
+ if (await exists(targetAbs)) {
1479
+ const targetText = await readFile(targetAbs, "utf8");
1480
+ plan.push(classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAbs, sourceText, targetText, context));
1481
+ continue;
1482
+ }
1483
+ const misplacedRel = targetRel.startsWith("dev/rules/")
1484
+ ? path.join("dev", path.basename(targetRel)).replaceAll(path.sep, "/")
1485
+ : null;
1486
+ const reason = misplacedRel && await exists(path.join(root, misplacedRel))
1487
+ ? `same-named rules file appears one level up at ${misplacedRel}; create correct dev/rules/ copy without deleting or moving the misplaced file`
1488
+ : undefined;
1489
+ plan.push({
1490
+ sourceRel,
1491
+ targetRel,
1492
+ sourceAbs,
1493
+ targetAbs,
1494
+ action: "create",
1495
+ ...(reason ? { reason } : {})
1496
+ });
1497
+ }
1498
+ return plan;
1499
+ }
1500
+
1501
+ async function readRootTemplateVersion(root) {
1502
+ try {
1503
+ const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
1504
+ const text = await readFile(indexPath, "utf8");
1505
+ const m = text.match(/\| Agent Handoff Kit template version \| ([\d.]+) \|/);
1506
+ return m?.[1] ?? null;
1507
+ } catch {
1508
+ return null;
1509
+ }
1510
+ }
1511
+
1512
+ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAbs, sourceText, targetText, context = {}) {
1513
+ const base = { sourceRel, targetRel, sourceAbs, targetAbs };
1511
1514
  if (targetText === sourceText && targetRel !== "AGENTS.md") return { ...base, action: "skip", reason: "already current" };
1512
1515
  if (command !== "upgrade") return { ...base, action: "skip", reason: "init preserves existing files" };
1513
1516
  if (targetRel === "AGENTS.md") {
@@ -1566,54 +1569,54 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1566
1569
  };
1567
1570
  }
1568
1571
  // R-030 v0.3.0+: dev/RULE_PACKS.md must also include integrations pack routing row.
1569
- if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && !targetText.includes("External tool integrations")) {
1570
- const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1571
- if (!mergedRulePacks) {
1572
- return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
1572
+ if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && !targetText.includes("External tool integrations")) {
1573
+ const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1574
+ if (!mergedRulePacks) {
1575
+ return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
1573
1576
  }
1574
1577
  return {
1575
1578
  ...base,
1576
1579
  action: "merge",
1577
1580
  reason: "merge missing v0.3.0+ routing rows while preserving existing custom rows (Integration governance routing)",
1578
- mergedText: mergedRulePacks
1579
- };
1580
- }
1581
- // Governance bridge v0.3.27+: route durable document bridging requests to
1582
- // agent-governance without replacing user-added routing rows.
1583
- if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && (
1584
- !targetText.includes("Governance bridge / 治理打通")
1585
- || !targetText.includes("接入 Agent Handoff Kit")
1586
- || !targetText.includes("掃描未接入 Agent Handoff Kit 的重要文件")
1587
- )) {
1588
- const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1589
- if (!mergedRulePacks) {
1590
- return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
1591
- }
1592
- return {
1593
- ...base,
1594
- action: "merge",
1595
- reason: "merge missing governance bridge routing row while preserving existing custom rows",
1596
- mergedText: mergedRulePacks
1597
- };
1598
- }
1599
- // Governance bridge v0.3.27+: add the triggered review workflow to the
1600
- // agent-governance pack only when the pack still has a trusted Checks section.
1601
- if (targetRel === "dev/rules/agent-governance.md" && command === "upgrade" && (
1602
- !targetText.includes("## Governance Bridge Workflow")
1603
- || !targetText.includes("接入 Agent Handoff Kit")
1604
- || !targetText.includes("掃描未接入 Agent Handoff Kit 的重要文件")
1605
- )) {
1606
- const mergedGovernancePack = mergeAgentGovernanceBridgeWorkflow(targetText, sourceText);
1607
- if (!mergedGovernancePack) {
1608
- return { ...base, action: "conflict", reason: "agent-governance pack structure was changed; manual merge required to add governance bridge workflow" };
1609
- }
1610
- return {
1611
- ...base,
1612
- action: "merge",
1613
- reason: "insert governance bridge workflow into agent-governance pack without replacing local additions",
1614
- mergedText: mergedGovernancePack
1615
- };
1616
- }
1581
+ mergedText: mergedRulePacks
1582
+ };
1583
+ }
1584
+ // Governance bridge v0.3.27+: route durable document bridging requests to
1585
+ // agent-governance without replacing user-added routing rows.
1586
+ if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && (
1587
+ !targetText.includes("Governance bridge / 治理打通")
1588
+ || !targetText.includes("接入 Agent Handoff Kit")
1589
+ || !targetText.includes("掃描未接入 Agent Handoff Kit 的重要文件")
1590
+ )) {
1591
+ const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1592
+ if (!mergedRulePacks) {
1593
+ return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
1594
+ }
1595
+ return {
1596
+ ...base,
1597
+ action: "merge",
1598
+ reason: "merge missing governance bridge routing row while preserving existing custom rows",
1599
+ mergedText: mergedRulePacks
1600
+ };
1601
+ }
1602
+ // Governance bridge v0.3.27+: add the triggered review workflow to the
1603
+ // agent-governance pack only when the pack still has a trusted Checks section.
1604
+ if (targetRel === "dev/rules/agent-governance.md" && command === "upgrade" && (
1605
+ !targetText.includes("## Governance Bridge Workflow")
1606
+ || !targetText.includes("接入 Agent Handoff Kit")
1607
+ || !targetText.includes("掃描未接入 Agent Handoff Kit 的重要文件")
1608
+ )) {
1609
+ const mergedGovernancePack = mergeAgentGovernanceBridgeWorkflow(targetText, sourceText);
1610
+ if (!mergedGovernancePack) {
1611
+ return { ...base, action: "conflict", reason: "agent-governance pack structure was changed; manual merge required to add governance bridge workflow" };
1612
+ }
1613
+ return {
1614
+ ...base,
1615
+ action: "merge",
1616
+ reason: "insert governance bridge workflow into agent-governance pack without replacing local additions",
1617
+ mergedText: mergedGovernancePack
1618
+ };
1619
+ }
1617
1620
  // R-030 v0.3.0+: dev/PROJECT_INDEX.md gets ## Installed Integrations section auto-inserted before
1618
1621
  // ## Local QC Commands on upgrade if missing. NON-DESTRUCTIVE: existing ## External Sources content
1619
1622
  // is fully preserved (including any user-filled rows). User can later manually add the `via` column
@@ -1636,12 +1639,12 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1636
1639
  // content and any user customization preserved. Step 1 micro-question additions to Scenarios A-E
1637
1640
  // are NOT auto-migrated (user-customizable inline sample wording, not anchor-enforced); users get
1638
1641
  // those on fresh install only or can manually patch following CHANGELOG migration guidance.
1639
- if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario F. 審視已裝外部工具")) {
1640
- const sourceScenarioFMatch = sourceText.match(/(### Scenario F\. 審視已裝外部工具[\s\S]*?)(?=## Cross-reference to guide\.html)/);
1641
- if (sourceScenarioFMatch && hasTrustedOnboardingScenarioLibrary(targetText)) {
1642
- const scenarioFBlock = sourceScenarioFMatch[1];
1643
- return {
1644
- ...base,
1642
+ if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario F. 審視已裝外部工具")) {
1643
+ const sourceScenarioFMatch = sourceText.match(/(### Scenario F\. 審視已裝外部工具[\s\S]*?)(?=## Cross-reference to guide\.html)/);
1644
+ if (sourceScenarioFMatch && hasTrustedOnboardingScenarioLibrary(targetText)) {
1645
+ const scenarioFBlock = sourceScenarioFMatch[1];
1646
+ return {
1647
+ ...base,
1645
1648
  action: "merge",
1646
1649
  reason: "insert ### Scenario F block before ## Cross-reference to guide.html (R-030 onboarding pack migration; existing Scenarios A-E content preserved non-destructively)",
1647
1650
  mergedText: targetText.replace("## Cross-reference to guide.html", scenarioFBlock + "## Cross-reference to guide.html")
@@ -1662,111 +1665,111 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1662
1665
  // v0.3.6+: SESSION_HANDOFF.md gains a non-destructive lifecycle consistency
1663
1666
  // field. Existing handoff content stays intact; only the missing field and
1664
1667
  // rule note are inserted around stable ack markers.
1665
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:lifecycle-conflicts-resolved")) {
1666
- const mergedHandoff = mergeHandoffLifecycleField(targetText);
1667
- if (!mergedHandoff) {
1668
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:lifecycle-conflicts-resolved")) {
1669
+ const mergedHandoff = mergeHandoffLifecycleField(targetText);
1670
+ if (!mergedHandoff) {
1668
1671
  return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add lifecycle consistency field" };
1669
1672
  }
1670
1673
  return {
1671
1674
  ...base,
1672
1675
  action: "merge",
1673
1676
  reason: "insert lifecycle consistency field into State Reconciliation Check (completed work must not carry forward as unresolved next work)",
1674
- mergedText: mergedHandoff
1675
- };
1676
- }
1677
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:persistence-routing-checked")) {
1678
- const mergedHandoff = mergeHandoffPersistenceRoutingField(targetText);
1679
- if (!mergedHandoff) {
1680
- return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add persistence routing field" };
1681
- }
1682
- return {
1683
- ...base,
1684
- action: "merge",
1685
- reason: "insert persistence routing field into State Reconciliation Check (one-time evidence must not drive next-session state)",
1686
- mergedText: mergedHandoff
1687
- };
1688
- }
1689
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && isUpgradeFromOlderTemplate(context)) {
1690
- const lifecycleValue = fieldValueAfterMarker(targetText, "lifecycle-conflicts-resolved");
1691
- if (isPlaceholderLifecycleFieldValue(lifecycleValue) && hasSubstantiveHandoffState(targetText)) {
1692
- const mergedHandoff = reclassifyExistingHandoffLifecyclePlaceholder(targetText);
1693
- if (!mergedHandoff) {
1694
- return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md lifecycle field exists but could not be safely reclassified; manual closeout required" };
1695
- }
1696
- return {
1697
- ...base,
1698
- action: "merge",
1699
- reason: "reclassify stale lifecycle placeholder from earlier template version so upgrade self-check can validate pre-existing handoff content",
1700
- mergedText: mergedHandoff
1701
- };
1702
- }
1703
- }
1704
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && hasMisplacedRequiredAnchor(targetRel, targetText, "handoff log archive continuity")) {
1705
- return { ...base, action: "conflict", reason: "required Kit anchors are present outside trusted semantic sections; upgrade stopped to avoid accepting naked anchor text as valid state" };
1706
- }
1707
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && hasMissingRequiredAnchor(targetRel, targetText, "handoff log archive continuity")) {
1708
- const mergedHandoff = mergeHandoffArchiveContinuityRule(targetText, sourceText);
1709
- if (!mergedHandoff) {
1710
- return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md handoff sufficiency markers were changed; manual merge required to add archive continuity rule" };
1711
- }
1712
- return {
1713
- ...base,
1714
- action: "merge",
1715
- reason: "insert handoff archive continuity rule so upgrade self-check can pass without requiring manual anchor repair",
1716
- mergedText: mergedHandoff
1717
- };
1718
- }
1719
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
1720
- const repairedOpening = repairHandoffOpeningRootGuard(targetText);
1721
- if (repairedOpening.changed) {
1722
- return {
1723
- ...base,
1724
- action: "merge",
1725
- reason: "restore root mismatch guard in Next Session Opening Message",
1726
- mergedText: repairedOpening.text
1727
- };
1728
- }
1729
- }
1730
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
1731
- const repairedTemperature = repairHandoffCurrentStateEvidenceBoundary(targetText);
1732
- if (repairedTemperature.changed) {
1733
- return {
1734
- ...base,
1735
- action: "merge",
1736
- reason: "move historical evidence out of hot handoff state",
1737
- mergedText: repairedTemperature.text
1738
- };
1739
- }
1740
- }
1741
- if (targetRel === "dev/SESSION_LOG.md" && command === "upgrade" && !targetText.includes("- **Evidence disposition:**")) {
1742
- const mergedLog = mergeSessionLogEvidenceDispositionField(targetText);
1743
- if (!mergedLog) {
1744
- return { ...base, action: "conflict", reason: "SESSION_LOG.md entry template markers were changed; manual merge required to add evidence disposition field" };
1745
- }
1746
- return {
1747
- ...base,
1748
- action: "merge",
1749
- reason: "insert SESSION_LOG evidence disposition field into Entry Template",
1750
- mergedText: mergedLog
1751
- };
1752
- }
1753
- if (command === "upgrade" && hasAnchorRepairMarkerDrift(targetText)) {
1754
- return { ...base, action: "conflict", reason: "legacy anchor repair block markers are incomplete or obsolete; manual semantic cleanup required before upgrade can safely continue" };
1755
- }
1756
- if (command === "upgrade" && hasMisplacedRequiredAnchor(targetRel, targetText)) {
1757
- return { ...base, action: "conflict", reason: "required Kit anchors are present outside trusted semantic sections; upgrade stopped to avoid accepting naked anchor text as valid state" };
1758
- }
1759
- if (command === "upgrade" && hasMissingRequiredAnchor(targetRel, targetText)) {
1760
- const semanticRepair = mergeMissingRequiredAnchorsSemantically(targetRel, targetText, sourceText);
1761
- if (semanticRepair) {
1762
- return { ...base, ...semanticRepair };
1763
- }
1764
- return { ...base, action: "conflict", reason: "required Kit anchors are missing but no safe semantic repair path exists; upgrade stopped without appending naked anchor text" };
1765
- }
1766
- if (targetRel === "CLAUDE.md" || targetRel === "GEMINI.md") {
1767
- if (!targetText.includes("AGENTS.md")) {
1768
- return { ...base, action: "conflict", reason: "existing bridge does not route to AGENTS.md" };
1769
- }
1677
+ mergedText: mergedHandoff
1678
+ };
1679
+ }
1680
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:persistence-routing-checked")) {
1681
+ const mergedHandoff = mergeHandoffPersistenceRoutingField(targetText);
1682
+ if (!mergedHandoff) {
1683
+ return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add persistence routing field" };
1684
+ }
1685
+ return {
1686
+ ...base,
1687
+ action: "merge",
1688
+ reason: "insert persistence routing field into State Reconciliation Check (one-time evidence must not drive next-session state)",
1689
+ mergedText: mergedHandoff
1690
+ };
1691
+ }
1692
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && isUpgradeFromOlderTemplate(context)) {
1693
+ const lifecycleValue = fieldValueAfterMarker(targetText, "lifecycle-conflicts-resolved");
1694
+ if (isPlaceholderLifecycleFieldValue(lifecycleValue) && hasSubstantiveHandoffState(targetText)) {
1695
+ const mergedHandoff = reclassifyExistingHandoffLifecyclePlaceholder(targetText);
1696
+ if (!mergedHandoff) {
1697
+ return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md lifecycle field exists but could not be safely reclassified; manual closeout required" };
1698
+ }
1699
+ return {
1700
+ ...base,
1701
+ action: "merge",
1702
+ reason: "reclassify stale lifecycle placeholder from earlier template version so upgrade self-check can validate pre-existing handoff content",
1703
+ mergedText: mergedHandoff
1704
+ };
1705
+ }
1706
+ }
1707
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && hasMisplacedRequiredAnchor(targetRel, targetText, "handoff log archive continuity")) {
1708
+ return { ...base, action: "conflict", reason: "required Kit anchors are present outside trusted semantic sections; upgrade stopped to avoid accepting naked anchor text as valid state" };
1709
+ }
1710
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && hasMissingRequiredAnchor(targetRel, targetText, "handoff log archive continuity")) {
1711
+ const mergedHandoff = mergeHandoffArchiveContinuityRule(targetText, sourceText);
1712
+ if (!mergedHandoff) {
1713
+ return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md handoff sufficiency markers were changed; manual merge required to add archive continuity rule" };
1714
+ }
1715
+ return {
1716
+ ...base,
1717
+ action: "merge",
1718
+ reason: "insert handoff archive continuity rule so upgrade self-check can pass without requiring manual anchor repair",
1719
+ mergedText: mergedHandoff
1720
+ };
1721
+ }
1722
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
1723
+ const repairedOpening = repairHandoffOpeningRootGuard(targetText);
1724
+ if (repairedOpening.changed) {
1725
+ return {
1726
+ ...base,
1727
+ action: "merge",
1728
+ reason: "restore root mismatch guard in Next Session Opening Message",
1729
+ mergedText: repairedOpening.text
1730
+ };
1731
+ }
1732
+ }
1733
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
1734
+ const repairedTemperature = repairHandoffCurrentStateEvidenceBoundary(targetText);
1735
+ if (repairedTemperature.changed) {
1736
+ return {
1737
+ ...base,
1738
+ action: "merge",
1739
+ reason: "move historical evidence out of hot handoff state",
1740
+ mergedText: repairedTemperature.text
1741
+ };
1742
+ }
1743
+ }
1744
+ if (targetRel === "dev/SESSION_LOG.md" && command === "upgrade" && !targetText.includes("- **Evidence disposition:**")) {
1745
+ const mergedLog = mergeSessionLogEvidenceDispositionField(targetText);
1746
+ if (!mergedLog) {
1747
+ return { ...base, action: "conflict", reason: "SESSION_LOG.md entry template markers were changed; manual merge required to add evidence disposition field" };
1748
+ }
1749
+ return {
1750
+ ...base,
1751
+ action: "merge",
1752
+ reason: "insert SESSION_LOG evidence disposition field into Entry Template",
1753
+ mergedText: mergedLog
1754
+ };
1755
+ }
1756
+ if (command === "upgrade" && hasAnchorRepairMarkerDrift(targetText)) {
1757
+ return { ...base, action: "conflict", reason: "legacy anchor repair block markers are incomplete or obsolete; manual semantic cleanup required before upgrade can safely continue" };
1758
+ }
1759
+ if (command === "upgrade" && hasMisplacedRequiredAnchor(targetRel, targetText)) {
1760
+ return { ...base, action: "conflict", reason: "required Kit anchors are present outside trusted semantic sections; upgrade stopped to avoid accepting naked anchor text as valid state" };
1761
+ }
1762
+ if (command === "upgrade" && hasMissingRequiredAnchor(targetRel, targetText)) {
1763
+ const semanticRepair = mergeMissingRequiredAnchorsSemantically(targetRel, targetText, sourceText);
1764
+ if (semanticRepair) {
1765
+ return { ...base, ...semanticRepair };
1766
+ }
1767
+ return { ...base, action: "conflict", reason: "required Kit anchors are missing but no safe semantic repair path exists; upgrade stopped without appending naked anchor text" };
1768
+ }
1769
+ if (targetRel === "CLAUDE.md" || targetRel === "GEMINI.md") {
1770
+ if (!targetText.includes("AGENTS.md")) {
1771
+ return { ...base, action: "conflict", reason: "existing bridge does not route to AGENTS.md" };
1772
+ }
1770
1773
  if (looksLikeExpandedKitBridge(targetRel, targetText)) {
1771
1774
  return {
1772
1775
  ...base,
@@ -1776,17 +1779,17 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1776
1779
  };
1777
1780
  }
1778
1781
  }
1779
- return { ...base, action: "skip", reason: "preserve existing file" };
1780
- }
1781
-
1782
- function isUpgradeFromOlderTemplate(context) {
1783
- const { rootTemplateVersion, currentVersion } = context;
1784
- return isStableSemver(rootTemplateVersion)
1785
- && isStableSemver(currentVersion)
1786
- && compareSemver(rootTemplateVersion, currentVersion) < 0;
1787
- }
1788
-
1789
- function looksLikeExpandedKitBridge(targetRel, text) {
1782
+ return { ...base, action: "skip", reason: "preserve existing file" };
1783
+ }
1784
+
1785
+ function isUpgradeFromOlderTemplate(context) {
1786
+ const { rootTemplateVersion, currentVersion } = context;
1787
+ return isStableSemver(rootTemplateVersion)
1788
+ && isStableSemver(currentVersion)
1789
+ && compareSemver(rootTemplateVersion, currentVersion) < 0;
1790
+ }
1791
+
1792
+ function looksLikeExpandedKitBridge(targetRel, text) {
1790
1793
  if (text.includes("This file is a bridge only")) return false;
1791
1794
  if (targetRel === "CLAUDE.md") {
1792
1795
  return (text.includes("This file provides guidance to Claude Code") && text.includes("## Session Startup"))
@@ -1802,7 +1805,7 @@ function looksLikeExpandedKitBridge(targetRel, text) {
1802
1805
  return false;
1803
1806
  }
1804
1807
 
1805
- function mergeOnboardingScenarioALabel(targetText) {
1808
+ function mergeOnboardingScenarioALabel(targetText) {
1806
1809
  let merged = targetText;
1807
1810
  merged = merged.replace(
1808
1811
  /\*\*A\. 寫 \/ 改代碼項目\*\* —— 你有一個(?: project 的 codebase|程式項目)想長期維護/g,
@@ -1812,654 +1815,668 @@ function mergeOnboardingScenarioALabel(targetText) {
1812
1815
  /### Scenario A\. 寫 \/ 改代碼項目/g,
1813
1816
  "### Scenario A. 建構系統 / 工具 / 平台 / 網站或應用"
1814
1817
  );
1815
- return merged;
1816
- }
1817
-
1818
- function mergeAgentGovernanceBridgeWorkflow(targetText, sourceText) {
1819
- const sourceMatch = sourceText.match(/9\. Governance bridge[\s\S]*?(?=\n## Checks)/);
1820
- const workflowMatch = sourceText.match(/\n## Governance Bridge Workflow[\s\S]*?(?=\n## Checks)/);
1821
- const sourceLoadWhenLine = sourceText.split(/\r?\n/).find((line) => line.startsWith("- User asks to \"治理打通\""));
1822
- const sourceWorkflowIntroLine = sourceText.split(/\r?\n/).find((line) => line.startsWith("Use this workflow when"));
1823
- if (!sourceMatch || !workflowMatch || !targetText.includes("\n## Checks")) return null;
1824
-
1825
- let merged = targetText;
1826
- const targetLoadWhenLine = merged.split(/\r?\n/).find((line) => line.startsWith("- User asks to \"治理打通\""));
1827
- if (sourceLoadWhenLine && (!targetLoadWhenLine || !targetLoadWhenLine.includes("接入 Agent Handoff Kit"))) {
1828
- merged = merged.replace(/- User asks to "治理打通"[^\n]*\n/, `${sourceLoadWhenLine}\n`);
1829
- }
1830
- const targetWorkflowIntroLine = merged.match(/^Use this workflow when[^\n]*$/m)?.[0] ?? "";
1831
- if (sourceWorkflowIntroLine && !targetWorkflowIntroLine.includes("掃描未接入 Agent Handoff Kit 的重要文件")) {
1832
- merged = merged.replace(/^Use this workflow when[^\n]*$/m, sourceWorkflowIntroLine);
1833
- }
1834
- if (!merged.includes("Governance bridge is a triggered review")) {
1835
- const rulePrefix = sourceMatch[0].trimEnd();
1836
- merged = merged.replace(/\n## Checks/, `\n${rulePrefix}\n${workflowMatch[0]}\n## Checks`);
1837
- }
1838
- if (!merged.includes("For governance bridge work, confirm the target file")) {
1839
- merged = merged.replace(
1840
- "- Confirm reusable operating procedure knowledge is not stored only in `dev/SESSION_HANDOFF.md`, `dev/SESSION_LOG.md`, or a decision narrative when it belongs in a pack or registered reference.",
1841
- "- Confirm reusable operating procedure knowledge is not stored only in `dev/SESSION_HANDOFF.md`, `dev/SESSION_LOG.md`, or a decision narrative when it belongs in a pack or registered reference.\n- For governance bridge work, confirm the target file, project index, sync registry, related workflow, handoff/log role split, and duplicate-source risk were all checked or explicitly marked not applicable."
1842
- );
1843
- }
1844
- return merged;
1845
- }
1846
-
1847
- function hasTrustedOnboardingScenarioLibrary(text) {
1848
- const bounds = textSectionBounds(text, "## Application Scenario Library", "## Cross-reference to guide.html");
1849
- if (!bounds) return false;
1850
- const section = text.slice(bounds.start, bounds.end);
1851
- return [
1852
- "### Scenario A.",
1853
- "### Scenario B.",
1854
- "### Scenario C.",
1855
- "### Scenario D.",
1856
- "### Scenario E."
1857
- ].every((headingText) => section.includes(headingText));
1858
- }
1859
-
1860
- function hasMissingRequiredAnchor(targetRel, targetText, label = null) {
1861
- return requiredAnchors
1862
- .filter((rule) => rule.target === targetRel && (!label || rule.label === label))
1863
- .some((rule) => requiredAnchorFailures(rule, targetText).some((failure) => failure.kind === "missing"));
1864
- }
1865
-
1866
- function hasMisplacedRequiredAnchor(targetRel, targetText, label = null) {
1867
- return requiredAnchors
1868
- .filter((rule) => rule.target === targetRel && (!label || rule.label === label))
1869
- .some((rule) => requiredAnchorFailures(rule, targetText).some((failure) => failure.kind === "misplaced"));
1870
- }
1871
-
1872
- function hasAnchorRepairMarkerDrift(text) {
1873
- const start = countText(text, "<!-- BEGIN Agent Handoff Kit anchor repair -->");
1874
- const end = countText(text, "<!-- END Agent Handoff Kit anchor repair -->");
1875
- return start > 0 || end > 0;
1876
- }
1877
-
1878
- function countText(text, needle) {
1879
- return text.split(needle).length - 1;
1880
- }
1881
-
1882
- function countRegex(text, pattern) {
1883
- const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
1884
- return [...text.matchAll(new RegExp(pattern.source, flags))].length;
1885
- }
1886
-
1887
- function missingRequiredAnchorSnippets(targetRel, targetText) {
1888
- return [...new Set(requiredAnchors
1889
- .filter((rule) => rule.target === targetRel)
1890
- .flatMap((rule) => requiredAnchorFailures(rule, targetText)
1891
- .filter((failure) => failure.kind === "missing")
1892
- .map((failure) => failure.snippet)))];
1893
- }
1894
-
1895
- function requiredAnchorFailures(rule, text) {
1896
- return rule.snippets.flatMap((snippet) => {
1897
- if (!text.includes(snippet)) return [{ kind: "missing", snippet }];
1898
- if (!isRequiredAnchorSemanticallyPlaced(rule, snippet, text)) return [{ kind: "misplaced", snippet }];
1899
- return [];
1900
- });
1901
- }
1902
-
1903
- function isRequiredAnchorSemanticallyPlaced(rule, snippet, text) {
1904
- return rule.placement ? rule.placement(snippet, text) : true;
1905
- }
1906
-
1907
- function sessionLogAnchorPlacement(snippet, text) {
1908
- if (snippet === "ack:section:session-log-preamble") return text.includes("ack:section:session-log-preamble");
1909
- if (snippet === "ack:section:session-log-entry-template") return text.includes("ack:section:session-log-entry-template");
1910
- if (snippet === "## Entry Template") return /^## Entry Template\s*$/m.test(text);
1911
- if (snippet === "ack:log-entry:start" || snippet === "ack:log-entry:end") {
1912
- return sessionLogEntryTemplateContains(text, snippet);
1913
- }
1914
- const preamble = [
1915
- "Record what actually happened in the session",
1916
- "kept, summarized, or archived",
1917
- "Do not remove validation evidence",
1918
- "latest opening message",
1919
- "not current state"
1920
- ];
1921
- if (preamble.includes(snippet)) return sessionLogPreambleContains(text, snippet);
1922
- return sessionLogEntryTemplateContains(text, snippet);
1923
- }
1924
-
1925
- function sessionLogPreambleContains(text, snippet) {
1926
- const markerBounds = textSectionBounds(text, "<!-- ack:section:session-log-preamble -->", "<!-- ack:section:session-log-entry-template -->");
1927
- if (markerBounds) return text.slice(markerBounds.start, markerBounds.end).includes(snippet);
1928
- return snippetAppearsBeforeHeading(text, snippet, "## Entry Template");
1929
- }
1930
-
1931
- function sessionLogEntryTemplateContains(text, snippet) {
1932
- const markerIndex = text.indexOf("<!-- ack:section:session-log-entry-template -->");
1933
- if (markerIndex >= 0) return text.slice(markerIndex).includes(snippet);
1934
- return snippetAppearsAfterHeading(text, snippet, "## Entry Template");
1935
- }
1936
-
1937
- function handoffContinuityAnchorPlacement(snippet, text) {
1938
- const suffixContinuityAnchors = [
1939
- "without searching old log history",
1940
- "SESSION_LOG.md` carries recent evidence",
1941
- "do not create an archive directory by default"
1942
- ];
1943
- if (suffixContinuityAnchors.includes(snippet)) {
1944
- return snippetAppearsInSemanticSection(text, snippet, "handoff-sufficiency-check", "Handoff Sufficiency Check", "next-session-opening-message", "Next Session Opening Message");
1945
- }
1946
- return true;
1947
- }
1948
-
1949
- function projectIndexAnchorPlacement(snippet, text) {
1950
- if (snippet === "Agent Handoff Kit template version") return Boolean(projectIndexTemplateVersion(text));
1951
- return true;
1952
- }
1953
-
1954
- function safetyAnchorPlacement(snippet, text) {
1955
- return safetyAnchorHasTrustedRuleShape(text, snippet);
1956
- }
1957
-
1958
- function projectDecisionsAnchorPlacement(snippet, text) {
1959
- const preamble = [
1960
- "Project Decisions Log",
1961
- "warm 資料層",
1962
- "AI 開工",
1963
- "不需要讀",
1964
- "AI 在收工時自動 update",
1965
- "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.",
1966
- "This file does not store raw build / upload / QC evidence"
1967
- ];
1968
- if (preamble.includes(snippet)) return snippetAppearsBeforeHeading(text, snippet, "## Evolution Timeline");
1969
- return true;
1970
- }
1971
-
1972
- function onboardingAnchorPlacement(snippet, text) {
1973
- if (snippet === "Application Scenario Library") {
1974
- return Boolean(textSectionBounds(text, "## Application Scenario Library", "## Cross-reference to guide.html"));
1975
- }
1976
- if (/^Scenario [A-F]\./.test(snippet)) {
1977
- return snippetAppearsBetweenHeadings(text, snippet, "## Application Scenario Library", "## Cross-reference to guide.html");
1978
- }
1979
- return true;
1980
- }
1981
-
1982
- function integrationsAnchorPlacement(snippet, text) {
1983
- if (snippet === "機密分離原則" || snippet === "Source-of-truth Architecture" || snippet === "Cross-session Lifecycle") {
1984
- return snippetAppearsBetweenHeadings(text, snippet, "## Discipline", "## Rules");
1985
- }
1986
- if (snippet === "Connector-first default") {
1987
- return snippetAppearsBetweenHeadings(text, snippet, "## Rules", "## Checks");
1988
- }
1989
- if (snippet === "Anti-pattern") return text.includes("## Anti-pattern(不要做的事)");
1990
- return true;
1991
- }
1992
-
1993
- function snippetAppearsBeforeHeading(text, snippet, headingText) {
1994
- const headingIndex = text.indexOf(headingText);
1995
- if (headingIndex < 0) return false;
1996
- return text.slice(0, headingIndex).includes(snippet);
1997
- }
1998
-
1999
- function snippetAppearsAfterHeading(text, snippet, headingText) {
2000
- const headingIndex = text.indexOf(headingText);
2001
- if (headingIndex < 0) return false;
2002
- return text.slice(headingIndex + headingText.length).includes(snippet);
2003
- }
2004
-
2005
- function snippetAppearsBetweenHeadings(text, snippet, startHeading, endHeading) {
2006
- const startIndex = text.indexOf(startHeading);
2007
- const endIndex = text.indexOf(endHeading);
2008
- if (startIndex < 0 || endIndex < 0 || endIndex <= startIndex) return false;
2009
- return text.slice(startIndex + startHeading.length, endIndex).includes(snippet);
2010
- }
2011
-
2012
- function snippetAppearsInSemanticSection(text, snippet, startId, startHeading, endId, endHeading) {
2013
- const startMarker = `<!-- ack:section:${startId} -->`;
2014
- const endMarker = `<!-- ack:section:${endId} -->`;
2015
- const markerStart = text.indexOf(startMarker);
2016
- const markerEnd = text.indexOf(endMarker, markerStart + startMarker.length);
2017
- if (markerStart >= 0 && markerEnd > markerStart) {
2018
- return text.slice(markerStart + startMarker.length, markerEnd).includes(snippet);
2019
- }
2020
- return snippetAppearsBetweenHeadings(text, snippet, `## ${startHeading}`, `## ${endHeading}`);
2021
- }
2022
-
2023
- const semanticAnchorRepairStrategies = {
2024
- "dev/PROJECT_INDEX.md": (targetText, sourceText) => {
2025
- const mergedIndex = mergeProjectIndexTemplateVersionRow(targetText, sourceText);
2026
- return mergedIndex ? {
2027
- action: "merge",
2028
- reason: "restore PROJECT_INDEX template version metadata row in ## Stack table",
2029
- mergedText: mergedIndex
2030
- } : null;
2031
- },
2032
- "dev/SESSION_LOG.md": (targetText, sourceText) => {
2033
- const mergedLog = mergeSessionLogTemplateContract(targetText, sourceText);
2034
- return mergedLog ? {
2035
- action: "merge",
2036
- reason: "restore SESSION_LOG machine boundaries and entry template contract",
2037
- mergedText: mergedLog
2038
- } : null;
2039
- },
2040
- "dev/PROJECT_DECISIONS.md": (targetText, sourceText, missing) => {
2041
- const mergedDecisions = mergeProjectDecisionsPreamble(targetText, sourceText, missing);
2042
- return mergedDecisions ? {
2043
- action: "merge",
2044
- reason: "restore PROJECT_DECISIONS onboarding preamble before ## Evolution Timeline",
2045
- mergedText: mergedDecisions
2046
- } : null;
2047
- },
2048
- "dev/rules/safety.md": (targetText, sourceText, missing) => {
2049
- const mergedSafety = mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing);
2050
- return mergedSafety ? {
2051
- action: "merge",
2052
- reason: "restore safety pack high-risk rules in ## Rules section",
2053
- mergedText: mergedSafety
2054
- } : null;
2055
- },
2056
- "dev/rules/integrations.md": (targetText, sourceText, missing) => {
2057
- const mergedIntegrations = mergeIntegrationsCredentialSection(targetText, sourceText, missing);
2058
- return mergedIntegrations ? {
2059
- action: "merge",
2060
- reason: "restore integrations credential-separation section in semantic position",
2061
- mergedText: mergedIntegrations
2062
- } : null;
2063
- }
2064
- };
2065
-
2066
- function mergeMissingRequiredAnchorsSemantically(targetRel, targetText, sourceText) {
2067
- const missing = missingRequiredAnchorSnippets(targetRel, targetText);
2068
- if (missing.length === 0) return null;
2069
-
2070
- return semanticAnchorRepairStrategies[targetRel]?.(targetText, sourceText, missing) ?? null;
2071
- }
2072
-
2073
- function insertSourcePreambleBeforeHeading(targetText, sourceText, headingText) {
2074
- const targetIndex = targetText.indexOf(headingText);
2075
- const sourceIndex = sourceText.indexOf(headingText);
2076
- if (targetIndex < 0 || sourceIndex < 0) return null;
2077
- const sourcePreamble = sourceText.slice(0, sourceIndex).trim();
2078
- if (!sourcePreamble) return null;
2079
- const targetBefore = targetText.slice(0, targetIndex).trimEnd();
2080
- const targetAfter = targetText.slice(targetIndex);
2081
- return `${targetBefore}\n\n${sourcePreamble}\n\n${targetAfter}`;
2082
- }
2083
-
2084
- function mergeProjectDecisionsPreamble(targetText, sourceText, missing) {
2085
- const evidenceSnippet = "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.";
2086
- const boundarySnippet = "This file does not store raw build / upload / QC evidence";
2087
- const targetIndex = targetText.indexOf("## Evolution Timeline");
2088
- const sourceIndex = sourceText.indexOf("## Evolution Timeline");
2089
- if (targetIndex < 0 || sourceIndex < 0) return null;
2090
- if (targetText.includes("Project Decisions Log")) {
2091
- const sourcePreamble = sourceText.slice(0, sourceIndex).trim();
2092
- const blocks = [];
2093
- if (missing.includes(evidenceSnippet)) {
2094
- const researchBlock = sourcePreamble.match(/Research-derived decisions use[\s\S]*?source map\./)?.[0];
2095
- if (!researchBlock) return null;
2096
- if (!targetText.includes(researchBlock)) blocks.push(researchBlock);
2097
- }
2098
- if (missing.includes(boundarySnippet)) {
2099
- const boundaryBlock = sourcePreamble.match(/This file does not store raw build \/ upload \/ QC evidence[^\r\n]*/)?.[0];
2100
- if (!boundaryBlock) return null;
2101
- if (!targetText.includes(boundaryBlock)) blocks.push(boundaryBlock);
2102
- }
2103
- if (blocks.length > 0) {
2104
- return `${targetText.slice(0, targetIndex).trimEnd()}\n\n${blocks.join("\n\n")}\n\n${targetText.slice(targetIndex)}`;
2105
- }
2106
- if (missing.includes(evidenceSnippet) || missing.includes(boundarySnippet)) return targetText;
2107
- }
2108
- return insertSourcePreambleBeforeHeading(targetText, sourceText, "## Evolution Timeline");
2109
- }
2110
-
2111
- function mergeProjectIndexTemplateVersionRow(targetText, sourceText) {
2112
- if (projectIndexTemplateVersion(targetText)) return targetText;
2113
- const sourceRow = sourceText.match(/^\| Agent Handoff Kit template version \| [\d.]+ \| [^|\n]+ \|$/m)?.[0];
2114
- if (!sourceRow) return null;
2115
- const lines = targetText.split(/\r?\n/);
2116
- const stackIndex = lines.findIndex((line) => line.trim() === "## Stack");
2117
- if (stackIndex < 0) return null;
2118
- const tableHeaderIndex = lines.findIndex((line, index) => index > stackIndex && line.trim() === "| Field | Value | Last verified |");
2119
- if (tableHeaderIndex < 0) return null;
2120
- const separatorIndex = tableHeaderIndex + 1;
2121
- if (!lines[separatorIndex]?.startsWith("|---")) return null;
2122
- lines.splice(separatorIndex + 1, 0, sourceRow);
2123
- return lines.join("\n");
2124
- }
2125
-
2126
- function mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing) {
2127
- if (!hasTrustedSafetyPackShape(targetText)) return null;
2128
- const targetBounds = sectionBounds(targetText, "## Rules", "## Checks");
2129
- const sourceBounds = sectionBounds(sourceText, "## Rules", "## Checks");
2130
- if (!targetBounds || !sourceBounds) return null;
2131
- const targetLines = targetText.split(/\r?\n/);
2132
- const sourceLines = sourceText.split(/\r?\n/);
2133
- const targetRuleStart = targetBounds.start + 1;
2134
- const targetRuleEnd = targetBounds.end;
2135
- const sourceRuleLines = sourceLines.slice(sourceBounds.start + 1, sourceBounds.end);
2136
-
2137
- let changed = false;
2138
- for (const snippet of missing) {
2139
- const sourceLine = sourceRuleLines.find((line) => line.includes(snippet));
2140
- if (!sourceLine) return null;
2141
- const ruleNumber = sourceLine.match(/^(\d+)\. /)?.[1];
2142
- if (!ruleNumber) return null;
2143
- const targetIndex = targetLines.findIndex((line, index) => index >= targetRuleStart && index < targetRuleEnd && line.startsWith(`${ruleNumber}. `));
2144
- if (targetIndex < 0) return null;
2145
- if (!sameRuleShape(targetLines[targetIndex], sourceLine, snippet)) return null;
2146
- targetLines[targetIndex] = sourceLine;
2147
- changed = true;
2148
- }
2149
-
2150
- return changed ? targetLines.join("\n") : targetText;
2151
- }
2152
-
2153
- function mergeIntegrationsCredentialSection(targetText, sourceText, missing) {
2154
- if (!missing.some((snippet) => snippet === "機密分離原則")) return null;
2155
- return replaceSectionByHeadingWithinBounds(
2156
- targetText,
2157
- sourceText,
2158
- /^### 1\. 機密分離原則/m,
2159
- /^### 2\. 四類整合嘅紀律差異/m,
2160
- "## Discipline",
2161
- "## Rules"
2162
- );
2163
- }
2164
-
2165
- function hasTrustedSafetyPackShape(text) {
2166
- return text.includes("# Safety Pack")
2167
- && text.includes("## Scope")
2168
- && text.includes("## Load When")
2169
- && Boolean(sectionBounds(text, "## Rules", "## Checks"))
2170
- && text.includes("## Closeout");
2171
- }
2172
-
2173
- function sameRuleShape(targetLine, sourceLine, snippet) {
2174
- const snippetIndex = sourceLine.indexOf(snippet);
2175
- if (snippetIndex < 0) return false;
2176
- const prefix = sourceLine.slice(0, snippetIndex);
2177
- const suffix = sourceLine.slice(snippetIndex + snippet.length);
2178
- return prefix.length >= 12
2179
- && suffix.length >= 8
2180
- && targetLine.startsWith(prefix)
2181
- && targetLine.endsWith(suffix);
2182
- }
2183
-
2184
- function safetyAnchorHasTrustedRuleShape(text, snippet) {
2185
- const bounds = sectionBounds(text, "## Rules", "## Checks");
2186
- if (!bounds) return false;
2187
- const lines = text.split(/\r?\n/).slice(bounds.start + 1, bounds.end);
2188
- const line = lines.find((candidate) => candidate.includes(snippet));
2189
- if (!line) return false;
2190
- if (snippet === "cmd /c rmdir") {
2191
- return line.includes("cmd /c rd")
2192
- && line.includes("cmd.exe /c")
2193
- && line.includes("combined with `rmdir` or `rd`")
2194
- && line.includes("Prefer native PowerShell cmdlets")
2195
- && line.includes("do not compose filesystem modification commands across shells");
2196
- }
2197
- if (snippet === "git reset --hard") {
2198
- return line.includes("branch deletion")
2199
- && line.includes("force push")
2200
- && line.includes("history rewrite");
2201
- }
2202
- if (snippet === "secret values") {
2203
- return line.includes("Do not print")
2204
- && line.includes("log")
2205
- && line.includes("commit")
2206
- && line.includes("redacted placeholders");
2207
- }
2208
- if (snippet === "external APIs, SDKs, CLIs") {
2209
- return line.includes("package managers")
2210
- && line.includes("official documentation")
2211
- && line.includes("project-local runbooks");
2212
- }
2213
- return true;
2214
- }
2215
-
2216
- function replaceSectionByHeadingWithinBounds(targetText, sourceText, startPattern, nextPattern, boundsStart, boundsEnd) {
2217
- if (countText(targetText, boundsStart) !== 1 || countText(targetText, boundsEnd) !== 1) return null;
2218
- const targetBounds = textSectionBounds(targetText, boundsStart, boundsEnd);
2219
- const sourceBounds = textSectionBounds(sourceText, boundsStart, boundsEnd);
2220
- if (!targetBounds || !sourceBounds) return null;
2221
-
2222
- const boundedTarget = targetText.slice(targetBounds.start, targetBounds.end);
2223
- const boundedSource = sourceText.slice(sourceBounds.start, sourceBounds.end);
2224
- if (countRegex(boundedTarget, startPattern) > 1 || countRegex(boundedTarget, nextPattern) !== 1) return null;
2225
- const sourceSection = extractSection(boundedSource, startPattern, nextPattern);
2226
- if (!sourceSection) return null;
2227
- const targetSection = extractSection(boundedTarget, startPattern, nextPattern);
2228
- if (targetSection) {
2229
- return `${targetText.slice(0, targetBounds.start + targetSection.start)}${sourceSection.text}${targetText.slice(targetBounds.start + targetSection.end)}`;
2230
- }
2231
- const nextMatch = nextPattern.exec(boundedTarget);
2232
- if (!nextMatch) return null;
2233
- return `${targetText.slice(0, targetBounds.start + nextMatch.index)}${sourceSection.text}${targetText.slice(targetBounds.start + nextMatch.index)}`;
2234
- }
2235
-
2236
- function replaceSectionByHeading(targetText, sourceText, startPattern, nextPattern) {
2237
- const sourceSection = extractSection(sourceText, startPattern, nextPattern);
2238
- if (!sourceSection) return null;
2239
- const targetSection = extractSection(targetText, startPattern, nextPattern);
2240
- if (targetSection) {
2241
- return `${targetText.slice(0, targetSection.start)}${sourceSection.text}${targetText.slice(targetSection.end)}`;
2242
- }
2243
- const nextMatch = nextPattern.exec(targetText);
2244
- if (!nextMatch) return null;
2245
- return `${targetText.slice(0, nextMatch.index)}${sourceSection.text}${targetText.slice(nextMatch.index)}`;
2246
- }
2247
-
2248
- function extractSection(text, startPattern, nextPattern) {
2249
- const startMatch = startPattern.exec(text);
2250
- if (!startMatch) return null;
2251
- const afterStart = text.slice(startMatch.index + startMatch[0].length);
2252
- const nextMatch = nextPattern.exec(afterStart);
2253
- const end = nextMatch ? startMatch.index + startMatch[0].length + nextMatch.index : text.length;
2254
- return { start: startMatch.index, end, text: text.slice(startMatch.index, end) };
2255
- }
2256
-
2257
- function sectionBounds(text, startHeading, endHeading) {
2258
- const lines = text.split(/\r?\n/);
2259
- const start = lines.findIndex((line) => line.trim() === startHeading);
2260
- if (start < 0) return null;
2261
- const end = lines.findIndex((line, index) => index > start && line.trim() === endHeading);
2262
- if (end < 0) return null;
2263
- return { start, end };
2264
- }
2265
-
2266
- function textSectionBounds(text, startHeading, endHeading) {
2267
- const startIndex = text.indexOf(startHeading);
2268
- if (startIndex < 0) return null;
2269
- const endIndex = text.indexOf(endHeading, startIndex + startHeading.length);
2270
- if (endIndex < 0) return null;
2271
- return { start: startIndex, end: endIndex };
2272
- }
2273
-
2274
- function projectIndexTemplateVersion(text) {
2275
- const bounds = textSectionBounds(text, "## Stack", "## Directory Map");
2276
- if (!bounds) return null;
2277
- const stack = text.slice(bounds.start, bounds.end);
2278
- const row = stack.match(/^\| Agent Handoff Kit template version \| ([\d.]+) \| [^|\n]+ \|$/m);
2279
- return row ? row[1] : null;
2280
- }
2281
-
2282
- function mergeHandoffLifecycleField(targetText) {
2283
- const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
2284
- if (!targetText.includes(openingMarker)) return null;
2285
-
2286
- const fieldBlock = "<!-- ack:field:lifecycle-conflicts-resolved -->\n- Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified: Reclassified at upgrade: field added by v0.3.6+ migration; pre-existing handoff state predates it; reconcile at next closeout.\n";
2287
- let merged = targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
2288
- return ensureHandoffStateReconciliationRules(ensureHandoffPersistenceRoutingField(merged));
2289
- }
2290
-
2291
- function reclassifyExistingHandoffLifecyclePlaceholder(targetText) {
2292
- const marker = "ack:field:lifecycle-conflicts-resolved";
2293
- const lines = targetText.split(/\r?\n/);
2294
- const markerIndex = lines.findIndex((line) => line.includes(marker));
2295
- if (markerIndex < 0) return null;
2296
-
2297
- const nextMarkerIndex = lines.findIndex((line, index) => index > markerIndex && line.includes("<!-- ack:"));
2298
- const searchEnd = nextMarkerIndex < 0 ? lines.length : nextMarkerIndex;
2299
- const fieldIndex = lines.findIndex((line, index) => index > markerIndex && index < searchEnd && line.trim().startsWith("- "));
2300
- if (fieldIndex < 0) return null;
2301
-
2302
- const colonIndex = lines[fieldIndex].indexOf(":");
2303
- if (colonIndex < 0) return null;
2304
- lines[fieldIndex] = `${lines[fieldIndex].slice(0, colonIndex + 1)} Reclassified at upgrade: existing lifecycle placeholder predates this version; pre-existing handoff state predates this check; reconcile at next closeout.`;
2305
-
2306
- return ensureHandoffStateReconciliationRules(lines.join("\n"));
2307
- }
2308
-
2309
- function mergeHandoffPersistenceRoutingField(targetText) {
2310
- const merged = ensureHandoffPersistenceRoutingField(targetText);
2311
- if (!merged || merged === targetText) return null;
2312
- return ensureHandoffStateReconciliationRules(merged);
2313
- }
2314
-
2315
- function ensureHandoffPersistenceRoutingField(targetText) {
2316
- if (targetText.includes("ack:field:persistence-routing-checked")) return targetText;
2317
- const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
2318
- if (!targetText.includes(openingMarker)) return null;
2319
- const fieldBlock = "<!-- ack:field:persistence-routing-checked -->\n- Persistence routing checked: Reclassified at upgrade: field added by template migration; pre-existing handoff state predates it; reconcile at next closeout.\n";
2320
- return targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
2321
- }
2322
-
2323
- function ensureHandoffStateReconciliationRules(targetText) {
2324
- if (!targetText) return null;
2325
- const rules = [];
2326
- if (!targetText.includes("Lifecycle consistency rule: compare `Completed This Session`")) {
2327
- rules.push("Lifecycle consistency rule: compare `Completed This Session`, `Validation / QC`, `Next Priorities`, `Risks / Blockers`, and `Next Session Opening Message`. A completed or verified item must not remain as an unresolved next priority, active risk, or startup instruction unless it is explicitly reclassified as monitor-only, follow-up scope, blocked, or reopened with the missing evidence or trigger condition stated.");
2328
- }
2329
- if (!targetText.includes("Persistence routing rule: one-time delivery instructions")) {
2330
- rules.push("Persistence routing rule: one-time delivery instructions, historical validation evidence, old hashes, old version facts, and incident notes must stay in trace evidence unless they still affect the next action.");
2331
- }
2332
- if (rules.length === 0) return targetText;
2333
- const ruleBlock = `${rules.join("\n")}\n\n`;
2334
- const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
2335
- if (targetText.includes(sufficiencyMarker)) {
2336
- return targetText.replace(sufficiencyMarker, `${ruleBlock}${sufficiencyMarker}`);
2337
- }
2338
- return `${targetText.trimEnd()}\n\n${ruleBlock}`;
2339
- }
2340
-
2341
- function mergeSessionLogEvidenceDispositionField(targetText) {
2342
- if (targetText.includes("- **Evidence disposition:**")) return mergeSessionLogTemplateContract(targetText, null) ?? targetText;
2343
- const qcField = "- **QC:**";
2344
- if (!targetText.includes(qcField)) return null;
2345
- const withEvidence = targetText.replace(qcField, `${qcField}\n- **Evidence disposition:** <one-time only / kept as recent trace evidence / absorbed into handoff / indexed in PROJECT_INDEX / promoted to PROJECT_DECISIONS / promoted to rule pack>`);
2346
- return mergeSessionLogTemplateContract(withEvidence, null) ?? withEvidence;
2347
- }
2348
-
2349
- function mergeSessionLogTemplateContract(targetText, sourceText = null) {
2350
- let merged = targetText;
2351
- let changed = false;
2352
-
2353
- if (!merged.includes("ack:section:session-log-preamble")) {
2354
- const titleMatch = /^# Session Log\s*$/m.exec(merged);
2355
- if (titleMatch) {
2356
- const insertAt = titleMatch.index + titleMatch[0].length;
2357
- merged = `${merged.slice(0, insertAt)}\n\n<!-- ack:section:session-log-preamble -->${merged.slice(insertAt)}`;
2358
- changed = true;
2359
- } else if (sourceText?.includes("ack:section:session-log-preamble")) {
2360
- const sourcePreambleMarker = "<!-- ack:section:session-log-preamble -->";
2361
- merged = `${sourcePreambleMarker}\n\n${merged}`;
2362
- changed = true;
2363
- }
2364
- }
2365
-
2366
- if (!merged.includes("ack:section:session-log-entry-template")) {
2367
- const headingMatch = /^## Entry Template\s*$/m.exec(merged);
2368
- if (headingMatch) {
2369
- merged = `${merged.slice(0, headingMatch.index)}<!-- ack:section:session-log-entry-template -->\n\n${merged.slice(headingMatch.index)}`;
2370
- changed = true;
2371
- }
2372
- }
2373
-
2374
- if (sourceText) {
2375
- const restored = restoreMissingSessionLogPreambleLines(merged, sourceText);
2376
- if (restored !== merged) {
2377
- merged = restored;
2378
- changed = true;
2379
- }
2380
- }
2381
-
2382
- const entryTemplateIndex = merged.search(/^## Entry Template\s*$/m);
2383
- if (entryTemplateIndex >= 0) {
2384
- const beforeTemplate = merged.slice(0, entryTemplateIndex);
2385
- let templateAndAfter = merged.slice(entryTemplateIndex);
2386
- if (!templateAndAfter.includes("ack:log-entry:start")) {
2387
- const replaced = templateAndAfter.replace(/````markdown(\r?\n)/, "````markdown$1<!-- ack:log-entry:start -->$1");
2388
- if (replaced !== templateAndAfter) {
2389
- templateAndAfter = replaced;
2390
- changed = true;
2391
- }
2392
- }
2393
- if (!templateAndAfter.includes("ack:log-entry:end")) {
2394
- const openingIndex = templateAndAfter.indexOf("````markdown");
2395
- const closingIndex = openingIndex >= 0
2396
- ? templateAndAfter.indexOf("\n````", openingIndex + "````markdown".length)
2397
- : -1;
2398
- if (closingIndex >= 0) {
2399
- templateAndAfter = `${templateAndAfter.slice(0, closingIndex)}\n<!-- ack:log-entry:end -->${templateAndAfter.slice(closingIndex)}`;
2400
- changed = true;
2401
- }
2402
- }
2403
- merged = `${beforeTemplate}${templateAndAfter}`;
2404
- }
2405
-
2406
- return changed ? merged : targetText;
2407
- }
2408
-
2409
- function restoreMissingSessionLogPreambleLines(targetText, sourceText) {
2410
- const sourceEntryIndex = sourceText.search(/^## Entry Template\s*$/m);
2411
- const targetEntryMarkerIndex = targetText.indexOf("<!-- ack:section:session-log-entry-template -->");
2412
- const targetEntryHeadingIndex = targetText.search(/^## Entry Template\s*$/m);
2413
- const insertIndex = targetEntryMarkerIndex >= 0 ? targetEntryMarkerIndex : targetEntryHeadingIndex;
2414
- if (sourceEntryIndex < 0 || insertIndex < 0) return targetText;
2415
-
2416
- const sourcePreamble = sourceText.slice(0, sourceEntryIndex);
2417
- const missingLines = [
2418
- "Record what actually happened in the session",
2419
- "kept, summarized, or archived",
2420
- "Do not remove validation evidence",
2421
- "latest opening message",
2422
- "not current state"
2423
- ].flatMap((snippet) => {
2424
- if (targetText.includes(snippet)) return [];
2425
- const line = sourcePreamble.split(/\r?\n/).find((candidate) => candidate.includes(snippet));
2426
- return line ? [line] : [];
2427
- });
2428
-
2429
- if (missingLines.length === 0) return targetText;
2430
- return `${targetText.slice(0, insertIndex).trimEnd()}\n\n${missingLines.join("\n\n")}\n\n${targetText.slice(insertIndex)}`;
2431
- }
2432
-
2433
- function mergeHandoffArchiveContinuityRule(targetText, sourceText) {
2434
- const sourceMatch = sourceText.match(/Continuity rule: this file carries current state and next action\.[^\r\n]*/);
2435
- if (!sourceMatch) return null;
2436
- const continuityRule = sourceMatch[0];
2437
- if (targetText.includes(continuityRule)) return targetText;
2438
-
2439
- const existingRulePattern = /Continuity rule: this file carries current state and next action\.[^\r\n]*/;
2440
- if (existingRulePattern.test(targetText)) {
2441
- return targetText.replace(existingRulePattern, continuityRule);
2442
- }
2443
-
2444
- const nextSectionMarker = "<!-- ack:section:next-session-opening-message -->";
2445
- if (targetText.includes(nextSectionMarker)) {
2446
- return targetText.replace(nextSectionMarker, `${continuityRule}\n\n${nextSectionMarker}`);
2447
- }
2448
-
2449
- const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
2450
- if (targetText.includes(sufficiencyMarker)) {
2451
- return `${targetText.trimEnd()}\n\n${continuityRule}\n`;
2452
- }
2453
-
2454
- return null;
2455
- }
2456
-
2457
- function mergeRulePacksRows(targetText, sourceText) {
2458
- const requiredPacks = [
2459
- "dev/rules/onboarding.md",
2460
- "dev/rules/integrations.md",
2461
- "dev/rules/agent-governance.md"
2462
- ];
1818
+ return merged;
1819
+ }
1820
+
1821
+ function mergeAgentGovernanceBridgeWorkflow(targetText, sourceText) {
1822
+ const sourceMatch = sourceText.match(/9\. Governance bridge[\s\S]*?(?=\n## Checks)/);
1823
+ const workflowMatch = sourceText.match(/\n## Governance Bridge Workflow[\s\S]*?(?=\n## Checks)/);
1824
+ const sourceLoadWhenLine = sourceText.split(/\r?\n/).find((line) => line.startsWith("- User asks to \"治理打通\""));
1825
+ const sourceWorkflowIntroLine = sourceText.split(/\r?\n/).find((line) => line.startsWith("Use this workflow when"));
1826
+ if (!sourceMatch || !workflowMatch || !targetText.includes("\n## Checks")) return null;
1827
+
1828
+ let merged = targetText;
1829
+ const targetLoadWhenLine = merged.split(/\r?\n/).find((line) => line.startsWith("- User asks to \"治理打通\""));
1830
+ if (sourceLoadWhenLine && (!targetLoadWhenLine || !targetLoadWhenLine.includes("接入 Agent Handoff Kit"))) {
1831
+ merged = merged.replace(/- User asks to "治理打通"[^\n]*\n/, `${sourceLoadWhenLine}\n`);
1832
+ }
1833
+ const targetWorkflowIntroLine = merged.match(/^Use this workflow when[^\n]*$/m)?.[0] ?? "";
1834
+ if (sourceWorkflowIntroLine && !targetWorkflowIntroLine.includes("掃描未接入 Agent Handoff Kit 的重要文件")) {
1835
+ merged = merged.replace(/^Use this workflow when[^\n]*$/m, sourceWorkflowIntroLine);
1836
+ }
1837
+ if (!merged.includes("Governance bridge is a triggered review")) {
1838
+ const rulePrefix = sourceMatch[0].trimEnd();
1839
+ merged = merged.replace(/\n## Checks/, `\n${rulePrefix}\n${workflowMatch[0]}\n## Checks`);
1840
+ }
1841
+ if (!merged.includes("For governance bridge work, confirm the target file")) {
1842
+ merged = merged.replace(
1843
+ "- Confirm reusable operating procedure knowledge is not stored only in `dev/SESSION_HANDOFF.md`, `dev/SESSION_LOG.md`, or a decision narrative when it belongs in a pack or registered reference.",
1844
+ "- Confirm reusable operating procedure knowledge is not stored only in `dev/SESSION_HANDOFF.md`, `dev/SESSION_LOG.md`, or a decision narrative when it belongs in a pack or registered reference.\n- For governance bridge work, confirm the target file, project index, sync registry, related workflow, handoff/log role split, and duplicate-source risk were all checked or explicitly marked not applicable."
1845
+ );
1846
+ }
1847
+ return merged;
1848
+ }
1849
+
1850
+ function hasTrustedOnboardingScenarioLibrary(text) {
1851
+ const bounds = textSectionBounds(text, "## Application Scenario Library", "## Cross-reference to guide.html");
1852
+ if (!bounds) return false;
1853
+ const section = text.slice(bounds.start, bounds.end);
1854
+ return [
1855
+ "### Scenario A.",
1856
+ "### Scenario B.",
1857
+ "### Scenario C.",
1858
+ "### Scenario D.",
1859
+ "### Scenario E."
1860
+ ].every((headingText) => section.includes(headingText));
1861
+ }
1862
+
1863
+ function hasMissingRequiredAnchor(targetRel, targetText, label = null) {
1864
+ return requiredAnchors
1865
+ .filter((rule) => rule.target === targetRel && (!label || rule.label === label))
1866
+ .some((rule) => requiredAnchorFailures(rule, targetText).some((failure) => failure.kind === "missing"));
1867
+ }
1868
+
1869
+ function hasMisplacedRequiredAnchor(targetRel, targetText, label = null) {
1870
+ return requiredAnchors
1871
+ .filter((rule) => rule.target === targetRel && (!label || rule.label === label))
1872
+ .some((rule) => requiredAnchorFailures(rule, targetText).some((failure) => failure.kind === "misplaced"));
1873
+ }
1874
+
1875
+ function hasAnchorRepairMarkerDrift(text) {
1876
+ const start = countText(text, "<!-- BEGIN Agent Handoff Kit anchor repair -->");
1877
+ const end = countText(text, "<!-- END Agent Handoff Kit anchor repair -->");
1878
+ return start > 0 || end > 0;
1879
+ }
1880
+
1881
+ function countText(text, needle) {
1882
+ return text.split(needle).length - 1;
1883
+ }
1884
+
1885
+ function countRegex(text, pattern) {
1886
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
1887
+ return [...text.matchAll(new RegExp(pattern.source, flags))].length;
1888
+ }
1889
+
1890
+ function missingRequiredAnchorSnippets(targetRel, targetText) {
1891
+ return [...new Set(requiredAnchors
1892
+ .filter((rule) => rule.target === targetRel)
1893
+ .flatMap((rule) => requiredAnchorFailures(rule, targetText)
1894
+ .filter((failure) => failure.kind === "missing")
1895
+ .map((failure) => failure.snippet)))];
1896
+ }
1897
+
1898
+ function requiredAnchorFailures(rule, text) {
1899
+ return rule.snippets.flatMap((snippet) => {
1900
+ if (!text.includes(snippet)) return [{ kind: "missing", snippet }];
1901
+ if (!isRequiredAnchorSemanticallyPlaced(rule, snippet, text)) return [{ kind: "misplaced", snippet }];
1902
+ return [];
1903
+ });
1904
+ }
1905
+
1906
+ function isRequiredAnchorSemanticallyPlaced(rule, snippet, text) {
1907
+ return rule.placement ? rule.placement(snippet, text) : true;
1908
+ }
1909
+
1910
+ function sessionLogAnchorPlacement(snippet, text) {
1911
+ if (snippet === "ack:section:session-log-preamble") return text.includes("ack:section:session-log-preamble");
1912
+ if (snippet === "ack:section:session-log-entry-template") return text.includes("ack:section:session-log-entry-template");
1913
+ if (snippet === "## Entry Template") return /^## Entry Template\s*$/m.test(text);
1914
+ if (snippet === "ack:log-entry:start" || snippet === "ack:log-entry:end") {
1915
+ return sessionLogEntryTemplateContains(text, snippet);
1916
+ }
1917
+ const preamble = [
1918
+ "Record what actually happened in the session",
1919
+ "kept, summarized, or archived",
1920
+ "Do not remove validation evidence",
1921
+ "latest opening message",
1922
+ "not current state"
1923
+ ];
1924
+ if (preamble.includes(snippet)) return sessionLogPreambleContains(text, snippet);
1925
+ return sessionLogEntryTemplateContains(text, snippet);
1926
+ }
1927
+
1928
+ function sessionLogPreambleContains(text, snippet) {
1929
+ const markerBounds = textSectionBounds(text, "<!-- ack:section:session-log-preamble -->", "<!-- ack:section:session-log-entry-template -->");
1930
+ if (markerBounds) return text.slice(markerBounds.start, markerBounds.end).includes(snippet);
1931
+ return snippetAppearsBeforeHeading(text, snippet, "## Entry Template");
1932
+ }
1933
+
1934
+ function sessionLogEntryTemplateContains(text, snippet) {
1935
+ const markerIndex = text.indexOf("<!-- ack:section:session-log-entry-template -->");
1936
+ if (markerIndex >= 0) return text.slice(markerIndex).includes(snippet);
1937
+ return snippetAppearsAfterHeading(text, snippet, "## Entry Template");
1938
+ }
1939
+
1940
+ function handoffContinuityAnchorPlacement(snippet, text) {
1941
+ const suffixContinuityAnchors = [
1942
+ "without searching old log history",
1943
+ "SESSION_LOG.md` carries recent evidence",
1944
+ "do not create an archive directory by default"
1945
+ ];
1946
+ if (suffixContinuityAnchors.includes(snippet)) {
1947
+ return snippetAppearsInSemanticSection(text, snippet, "handoff-sufficiency-check", "Handoff Sufficiency Check", "next-session-opening-message", "Next Session Opening Message");
1948
+ }
1949
+ return true;
1950
+ }
1951
+
1952
+ function projectIndexAnchorPlacement(snippet, text) {
1953
+ if (snippet === "Agent Handoff Kit template version") return Boolean(projectIndexTemplateVersion(text));
1954
+ return true;
1955
+ }
1956
+
1957
+ function safetyAnchorPlacement(snippet, text) {
1958
+ return safetyAnchorHasTrustedRuleShape(text, snippet);
1959
+ }
1960
+
1961
+ function projectDecisionsAnchorPlacement(snippet, text) {
1962
+ const preamble = [
1963
+ "Project Decisions Log",
1964
+ "warm 資料層",
1965
+ "AI 開工",
1966
+ "不需要讀",
1967
+ "AI 在收工時自動 update",
1968
+ "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.",
1969
+ "This file does not store raw build / upload / QC evidence"
1970
+ ];
1971
+ if (preamble.includes(snippet)) return snippetAppearsBeforeHeading(text, snippet, "## Evolution Timeline");
1972
+ return true;
1973
+ }
1974
+
1975
+ function onboardingAnchorPlacement(snippet, text) {
1976
+ if (snippet === "Application Scenario Library") {
1977
+ return Boolean(textSectionBounds(text, "## Application Scenario Library", "## Cross-reference to guide.html"));
1978
+ }
1979
+ if (/^Scenario [A-F]\./.test(snippet)) {
1980
+ return snippetAppearsBetweenHeadings(text, snippet, "## Application Scenario Library", "## Cross-reference to guide.html");
1981
+ }
1982
+ return true;
1983
+ }
1984
+
1985
+ function integrationsAnchorPlacement(snippet, text) {
1986
+ if (snippet === "機密分離原則" || snippet === "Source-of-truth Architecture" || snippet === "Cross-session Lifecycle") {
1987
+ return snippetAppearsBetweenHeadings(text, snippet, "## Discipline", "## Rules");
1988
+ }
1989
+ if (snippet === "Connector-first default") {
1990
+ return snippetAppearsBetweenHeadings(text, snippet, "## Rules", "## Checks");
1991
+ }
1992
+ if (snippet === "Anti-pattern") return text.includes("## Anti-pattern(不要做的事)");
1993
+ return true;
1994
+ }
1995
+
1996
+ function snippetAppearsBeforeHeading(text, snippet, headingText) {
1997
+ const headingIndex = text.indexOf(headingText);
1998
+ if (headingIndex < 0) return false;
1999
+ return text.slice(0, headingIndex).includes(snippet);
2000
+ }
2001
+
2002
+ function snippetAppearsAfterHeading(text, snippet, headingText) {
2003
+ const headingIndex = text.indexOf(headingText);
2004
+ if (headingIndex < 0) return false;
2005
+ return text.slice(headingIndex + headingText.length).includes(snippet);
2006
+ }
2007
+
2008
+ function snippetAppearsBetweenHeadings(text, snippet, startHeading, endHeading) {
2009
+ const startIndex = text.indexOf(startHeading);
2010
+ const endIndex = text.indexOf(endHeading);
2011
+ if (startIndex < 0 || endIndex < 0 || endIndex <= startIndex) return false;
2012
+ return text.slice(startIndex + startHeading.length, endIndex).includes(snippet);
2013
+ }
2014
+
2015
+ function snippetAppearsInSemanticSection(text, snippet, startId, startHeading, endId, endHeading) {
2016
+ const startMarker = `<!-- ack:section:${startId} -->`;
2017
+ const endMarker = `<!-- ack:section:${endId} -->`;
2018
+ const markerStart = text.indexOf(startMarker);
2019
+ const markerEnd = text.indexOf(endMarker, markerStart + startMarker.length);
2020
+ if (markerStart >= 0 && markerEnd > markerStart) {
2021
+ return text.slice(markerStart + startMarker.length, markerEnd).includes(snippet);
2022
+ }
2023
+ return snippetAppearsBetweenHeadings(text, snippet, `## ${startHeading}`, `## ${endHeading}`);
2024
+ }
2025
+
2026
+ const semanticAnchorRepairStrategies = {
2027
+ "dev/PROJECT_INDEX.md": (targetText, sourceText) => {
2028
+ const mergedIndex = mergeProjectIndexTemplateVersionRow(targetText, sourceText);
2029
+ return mergedIndex ? {
2030
+ action: "merge",
2031
+ reason: "restore PROJECT_INDEX template version metadata row in ## Stack table",
2032
+ mergedText: mergedIndex
2033
+ } : null;
2034
+ },
2035
+ "dev/SESSION_LOG.md": (targetText, sourceText) => {
2036
+ const mergedLog = mergeSessionLogTemplateContract(targetText, sourceText);
2037
+ return mergedLog ? {
2038
+ action: "merge",
2039
+ reason: "restore SESSION_LOG machine boundaries and entry template contract",
2040
+ mergedText: mergedLog
2041
+ } : null;
2042
+ },
2043
+ "dev/PROJECT_DECISIONS.md": (targetText, sourceText, missing) => {
2044
+ const mergedDecisions = mergeProjectDecisionsPreamble(targetText, sourceText, missing);
2045
+ return mergedDecisions ? {
2046
+ action: "merge",
2047
+ reason: "restore PROJECT_DECISIONS onboarding preamble before ## Evolution Timeline",
2048
+ mergedText: mergedDecisions
2049
+ } : null;
2050
+ },
2051
+ "dev/rules/safety.md": (targetText, sourceText, missing) => {
2052
+ const mergedSafety = mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing);
2053
+ return mergedSafety ? {
2054
+ action: "merge",
2055
+ reason: "restore safety pack high-risk rules in ## Rules section",
2056
+ mergedText: mergedSafety
2057
+ } : null;
2058
+ },
2059
+ "dev/rules/integrations.md": (targetText, sourceText, missing) => {
2060
+ const mergedIntegrations = mergeIntegrationsCredentialSection(targetText, sourceText, missing);
2061
+ return mergedIntegrations ? {
2062
+ action: "merge",
2063
+ reason: "restore integrations credential-separation section in semantic position",
2064
+ mergedText: mergedIntegrations
2065
+ } : null;
2066
+ }
2067
+ };
2068
+
2069
+ function mergeMissingRequiredAnchorsSemantically(targetRel, targetText, sourceText) {
2070
+ const missing = missingRequiredAnchorSnippets(targetRel, targetText);
2071
+ if (missing.length === 0) return null;
2072
+
2073
+ return semanticAnchorRepairStrategies[targetRel]?.(targetText, sourceText, missing) ?? null;
2074
+ }
2075
+
2076
+ function insertSourcePreambleBeforeHeading(targetText, sourceText, headingText) {
2077
+ const targetIndex = targetText.indexOf(headingText);
2078
+ const sourceIndex = sourceText.indexOf(headingText);
2079
+ if (targetIndex < 0 || sourceIndex < 0) return null;
2080
+ const sourcePreamble = sourceText.slice(0, sourceIndex).trim();
2081
+ if (!sourcePreamble) return null;
2082
+ const targetBefore = targetText.slice(0, targetIndex).trimEnd();
2083
+ const targetAfter = targetText.slice(targetIndex);
2084
+ return `${targetBefore}\n\n${sourcePreamble}\n\n${targetAfter}`;
2085
+ }
2086
+
2087
+ function mergeProjectDecisionsPreamble(targetText, sourceText, missing) {
2088
+ const evidenceSnippet = "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.";
2089
+ const boundarySnippet = "This file does not store raw build / upload / QC evidence";
2090
+ const targetIndex = targetText.indexOf("## Evolution Timeline");
2091
+ const sourceIndex = sourceText.indexOf("## Evolution Timeline");
2092
+ if (targetIndex < 0 || sourceIndex < 0) return null;
2093
+ if (targetText.includes("Project Decisions Log")) {
2094
+ const sourcePreamble = sourceText.slice(0, sourceIndex).trim();
2095
+ const blocks = [];
2096
+ if (missing.includes(evidenceSnippet)) {
2097
+ const researchBlock = sourcePreamble.match(/Research-derived decisions use[\s\S]*?source map\./)?.[0];
2098
+ if (!researchBlock) return null;
2099
+ if (!targetText.includes(researchBlock)) blocks.push(researchBlock);
2100
+ }
2101
+ if (missing.includes(boundarySnippet)) {
2102
+ const boundaryBlock = sourcePreamble.match(/This file does not store raw build \/ upload \/ QC evidence[^\r\n]*/)?.[0];
2103
+ if (!boundaryBlock) return null;
2104
+ if (!targetText.includes(boundaryBlock)) blocks.push(boundaryBlock);
2105
+ }
2106
+ if (blocks.length > 0) {
2107
+ return `${targetText.slice(0, targetIndex).trimEnd()}\n\n${blocks.join("\n\n")}\n\n${targetText.slice(targetIndex)}`;
2108
+ }
2109
+ if (missing.includes(evidenceSnippet) || missing.includes(boundarySnippet)) return targetText;
2110
+ }
2111
+ return insertSourcePreambleBeforeHeading(targetText, sourceText, "## Evolution Timeline");
2112
+ }
2113
+
2114
+ function mergeProjectIndexTemplateVersionRow(targetText, sourceText) {
2115
+ if (projectIndexTemplateVersion(targetText)) return targetText;
2116
+ const sourceRow = sourceText.match(/^\| Agent Handoff Kit template version \| [\d.]+ \| [^|\n]+ \|$/m)?.[0];
2117
+ if (!sourceRow) return null;
2118
+ const lines = targetText.split(/\r?\n/);
2119
+ const stackIndex = lines.findIndex((line) => line.trim() === "## Stack");
2120
+ if (stackIndex < 0) return null;
2121
+ const tableHeaderIndex = lines.findIndex((line, index) => index > stackIndex && line.trim() === "| Field | Value | Last verified |");
2122
+ if (tableHeaderIndex < 0) return null;
2123
+ const separatorIndex = tableHeaderIndex + 1;
2124
+ if (!lines[separatorIndex]?.startsWith("|---")) return null;
2125
+ lines.splice(separatorIndex + 1, 0, sourceRow);
2126
+ return lines.join("\n");
2127
+ }
2128
+
2129
+ function mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing) {
2130
+ if (!hasTrustedSafetyPackShape(targetText)) return null;
2131
+ const targetBounds = sectionBounds(targetText, "## Rules", "## Checks");
2132
+ const sourceBounds = sectionBounds(sourceText, "## Rules", "## Checks");
2133
+ if (!targetBounds || !sourceBounds) return null;
2134
+ const targetLines = targetText.split(/\r?\n/);
2135
+ const sourceLines = sourceText.split(/\r?\n/);
2136
+ const targetRuleStart = targetBounds.start + 1;
2137
+ const targetRuleEnd = targetBounds.end;
2138
+ const sourceRuleLines = sourceLines.slice(sourceBounds.start + 1, sourceBounds.end);
2139
+
2140
+ let changed = false;
2141
+ const remainingMissing = [...missing];
2142
+ if (remainingMissing.includes("parser failure") && !targetText.includes("parser failure")) {
2143
+ const parserFailureRule = sourceRuleLines.find((line) => line.includes("parser failure"));
2144
+ if (!parserFailureRule || !parserFailureRule.startsWith("13. ")) return null;
2145
+ targetLines.splice(targetRuleEnd, 0, parserFailureRule);
2146
+ changed = true;
2147
+ remainingMissing.splice(remainingMissing.indexOf("parser failure"), 1);
2148
+ }
2149
+
2150
+ for (const snippet of remainingMissing) {
2151
+ const sourceLine = sourceRuleLines.find((line) => line.includes(snippet));
2152
+ if (!sourceLine) return null;
2153
+ const ruleNumber = sourceLine.match(/^(\d+)\. /)?.[1];
2154
+ if (!ruleNumber) return null;
2155
+ const targetIndex = targetLines.findIndex((line, index) => index >= targetRuleStart && index < targetRuleEnd && line.startsWith(`${ruleNumber}. `));
2156
+ if (targetIndex < 0) return null;
2157
+ if (!sameRuleShape(targetLines[targetIndex], sourceLine, snippet)) return null;
2158
+ targetLines[targetIndex] = sourceLine;
2159
+ changed = true;
2160
+ }
2161
+
2162
+ return changed ? targetLines.join("\n") : targetText;
2163
+ }
2164
+
2165
+ function mergeIntegrationsCredentialSection(targetText, sourceText, missing) {
2166
+ if (!missing.some((snippet) => snippet === "機密分離原則")) return null;
2167
+ return replaceSectionByHeadingWithinBounds(
2168
+ targetText,
2169
+ sourceText,
2170
+ /^### 1\. 機密分離原則/m,
2171
+ /^### 2\. 四類整合嘅紀律差異/m,
2172
+ "## Discipline",
2173
+ "## Rules"
2174
+ );
2175
+ }
2176
+
2177
+ function hasTrustedSafetyPackShape(text) {
2178
+ return text.includes("# Safety Pack")
2179
+ && text.includes("## Scope")
2180
+ && Boolean(sectionBounds(text, "## Rules", "## Checks"))
2181
+ && text.includes("## Closeout");
2182
+ }
2183
+
2184
+ function sameRuleShape(targetLine, sourceLine, snippet) {
2185
+ const snippetIndex = sourceLine.indexOf(snippet);
2186
+ if (snippetIndex < 0) return false;
2187
+ const prefix = sourceLine.slice(0, snippetIndex);
2188
+ const suffix = sourceLine.slice(snippetIndex + snippet.length);
2189
+ return prefix.length >= 12
2190
+ && suffix.length >= 8
2191
+ && targetLine.startsWith(prefix)
2192
+ && targetLine.endsWith(suffix);
2193
+ }
2194
+
2195
+ function safetyAnchorHasTrustedRuleShape(text, snippet) {
2196
+ const bounds = sectionBounds(text, "## Rules", "## Checks");
2197
+ if (!bounds) return false;
2198
+ const lines = text.split(/\r?\n/).slice(bounds.start + 1, bounds.end);
2199
+ const line = lines.find((candidate) => candidate.includes(snippet));
2200
+ if (!line) return false;
2201
+ if (snippet === "cmd /c rmdir") {
2202
+ return line.includes("cmd /c rd")
2203
+ && line.includes("cmd.exe /c")
2204
+ && line.includes("combined with `rmdir` or `rd`")
2205
+ && line.includes("Prefer native PowerShell cmdlets")
2206
+ && line.includes("do not compose filesystem modification commands across shells");
2207
+ }
2208
+ if (snippet === "git reset --hard") {
2209
+ return line.includes("branch deletion")
2210
+ && line.includes("force push")
2211
+ && line.includes("history rewrite");
2212
+ }
2213
+ if (snippet === "secret values") {
2214
+ return line.includes("Do not print")
2215
+ && line.includes("log")
2216
+ && line.includes("commit")
2217
+ && line.includes("redacted placeholders");
2218
+ }
2219
+ if (snippet === "external APIs, SDKs, CLIs") {
2220
+ return line.includes("package managers")
2221
+ && line.includes("official documentation")
2222
+ && line.includes("project-local runbooks");
2223
+ }
2224
+ if (snippet === "parser failure") {
2225
+ return line.includes("same-pattern retries")
2226
+ && line.includes("minimal reproducible script")
2227
+ && line.includes("syntax-only check")
2228
+ && line.includes("read back the affected files");
2229
+ }
2230
+ return true;
2231
+ }
2232
+
2233
+ function replaceSectionByHeadingWithinBounds(targetText, sourceText, startPattern, nextPattern, boundsStart, boundsEnd) {
2234
+ if (countText(targetText, boundsStart) !== 1 || countText(targetText, boundsEnd) !== 1) return null;
2235
+ const targetBounds = textSectionBounds(targetText, boundsStart, boundsEnd);
2236
+ const sourceBounds = textSectionBounds(sourceText, boundsStart, boundsEnd);
2237
+ if (!targetBounds || !sourceBounds) return null;
2238
+
2239
+ const boundedTarget = targetText.slice(targetBounds.start, targetBounds.end);
2240
+ const boundedSource = sourceText.slice(sourceBounds.start, sourceBounds.end);
2241
+ if (countRegex(boundedTarget, startPattern) > 1 || countRegex(boundedTarget, nextPattern) !== 1) return null;
2242
+ const sourceSection = extractSection(boundedSource, startPattern, nextPattern);
2243
+ if (!sourceSection) return null;
2244
+ const targetSection = extractSection(boundedTarget, startPattern, nextPattern);
2245
+ if (targetSection) {
2246
+ return `${targetText.slice(0, targetBounds.start + targetSection.start)}${sourceSection.text}${targetText.slice(targetBounds.start + targetSection.end)}`;
2247
+ }
2248
+ const nextMatch = nextPattern.exec(boundedTarget);
2249
+ if (!nextMatch) return null;
2250
+ return `${targetText.slice(0, targetBounds.start + nextMatch.index)}${sourceSection.text}${targetText.slice(targetBounds.start + nextMatch.index)}`;
2251
+ }
2252
+
2253
+ function replaceSectionByHeading(targetText, sourceText, startPattern, nextPattern) {
2254
+ const sourceSection = extractSection(sourceText, startPattern, nextPattern);
2255
+ if (!sourceSection) return null;
2256
+ const targetSection = extractSection(targetText, startPattern, nextPattern);
2257
+ if (targetSection) {
2258
+ return `${targetText.slice(0, targetSection.start)}${sourceSection.text}${targetText.slice(targetSection.end)}`;
2259
+ }
2260
+ const nextMatch = nextPattern.exec(targetText);
2261
+ if (!nextMatch) return null;
2262
+ return `${targetText.slice(0, nextMatch.index)}${sourceSection.text}${targetText.slice(nextMatch.index)}`;
2263
+ }
2264
+
2265
+ function extractSection(text, startPattern, nextPattern) {
2266
+ const startMatch = startPattern.exec(text);
2267
+ if (!startMatch) return null;
2268
+ const afterStart = text.slice(startMatch.index + startMatch[0].length);
2269
+ const nextMatch = nextPattern.exec(afterStart);
2270
+ const end = nextMatch ? startMatch.index + startMatch[0].length + nextMatch.index : text.length;
2271
+ return { start: startMatch.index, end, text: text.slice(startMatch.index, end) };
2272
+ }
2273
+
2274
+ function sectionBounds(text, startHeading, endHeading) {
2275
+ const lines = text.split(/\r?\n/);
2276
+ const start = lines.findIndex((line) => line.trim() === startHeading);
2277
+ if (start < 0) return null;
2278
+ const end = lines.findIndex((line, index) => index > start && line.trim() === endHeading);
2279
+ if (end < 0) return null;
2280
+ return { start, end };
2281
+ }
2282
+
2283
+ function textSectionBounds(text, startHeading, endHeading) {
2284
+ const startIndex = text.indexOf(startHeading);
2285
+ if (startIndex < 0) return null;
2286
+ const endIndex = text.indexOf(endHeading, startIndex + startHeading.length);
2287
+ if (endIndex < 0) return null;
2288
+ return { start: startIndex, end: endIndex };
2289
+ }
2290
+
2291
+ function projectIndexTemplateVersion(text) {
2292
+ const bounds = textSectionBounds(text, "## Stack", "## Directory Map");
2293
+ if (!bounds) return null;
2294
+ const stack = text.slice(bounds.start, bounds.end);
2295
+ const row = stack.match(/^\| Agent Handoff Kit template version \| ([\d.]+) \| [^|\n]+ \|$/m);
2296
+ return row ? row[1] : null;
2297
+ }
2298
+
2299
+ function mergeHandoffLifecycleField(targetText) {
2300
+ const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
2301
+ if (!targetText.includes(openingMarker)) return null;
2302
+
2303
+ const fieldBlock = "<!-- ack:field:lifecycle-conflicts-resolved -->\n- Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified: Reclassified at upgrade: field added by v0.3.6+ migration; pre-existing handoff state predates it; reconcile at next closeout.\n";
2304
+ let merged = targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
2305
+ return ensureHandoffStateReconciliationRules(ensureHandoffPersistenceRoutingField(merged));
2306
+ }
2307
+
2308
+ function reclassifyExistingHandoffLifecyclePlaceholder(targetText) {
2309
+ const marker = "ack:field:lifecycle-conflicts-resolved";
2310
+ const lines = targetText.split(/\r?\n/);
2311
+ const markerIndex = lines.findIndex((line) => line.includes(marker));
2312
+ if (markerIndex < 0) return null;
2313
+
2314
+ const nextMarkerIndex = lines.findIndex((line, index) => index > markerIndex && line.includes("<!-- ack:"));
2315
+ const searchEnd = nextMarkerIndex < 0 ? lines.length : nextMarkerIndex;
2316
+ const fieldIndex = lines.findIndex((line, index) => index > markerIndex && index < searchEnd && line.trim().startsWith("- "));
2317
+ if (fieldIndex < 0) return null;
2318
+
2319
+ const colonIndex = lines[fieldIndex].indexOf(":");
2320
+ if (colonIndex < 0) return null;
2321
+ lines[fieldIndex] = `${lines[fieldIndex].slice(0, colonIndex + 1)} Reclassified at upgrade: existing lifecycle placeholder predates this version; pre-existing handoff state predates this check; reconcile at next closeout.`;
2322
+
2323
+ return ensureHandoffStateReconciliationRules(lines.join("\n"));
2324
+ }
2325
+
2326
+ function mergeHandoffPersistenceRoutingField(targetText) {
2327
+ const merged = ensureHandoffPersistenceRoutingField(targetText);
2328
+ if (!merged || merged === targetText) return null;
2329
+ return ensureHandoffStateReconciliationRules(merged);
2330
+ }
2331
+
2332
+ function ensureHandoffPersistenceRoutingField(targetText) {
2333
+ if (targetText.includes("ack:field:persistence-routing-checked")) return targetText;
2334
+ const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
2335
+ if (!targetText.includes(openingMarker)) return null;
2336
+ const fieldBlock = "<!-- ack:field:persistence-routing-checked -->\n- Persistence routing checked: Reclassified at upgrade: field added by template migration; pre-existing handoff state predates it; reconcile at next closeout.\n";
2337
+ return targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
2338
+ }
2339
+
2340
+ function ensureHandoffStateReconciliationRules(targetText) {
2341
+ if (!targetText) return null;
2342
+ const rules = [];
2343
+ if (!targetText.includes("Lifecycle consistency rule: compare `Completed This Session`")) {
2344
+ rules.push("Lifecycle consistency rule: compare `Completed This Session`, `Validation / QC`, `Next Priorities`, `Risks / Blockers`, and `Next Session Opening Message`. A completed or verified item must not remain as an unresolved next priority, active risk, or startup instruction unless it is explicitly reclassified as monitor-only, follow-up scope, blocked, or reopened with the missing evidence or trigger condition stated.");
2345
+ }
2346
+ if (!targetText.includes("Persistence routing rule: one-time delivery instructions")) {
2347
+ rules.push("Persistence routing rule: one-time delivery instructions, historical validation evidence, old hashes, old version facts, and incident notes must stay in trace evidence unless they still affect the next action.");
2348
+ }
2349
+ if (rules.length === 0) return targetText;
2350
+ const ruleBlock = `${rules.join("\n")}\n\n`;
2351
+ const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
2352
+ if (targetText.includes(sufficiencyMarker)) {
2353
+ return targetText.replace(sufficiencyMarker, `${ruleBlock}${sufficiencyMarker}`);
2354
+ }
2355
+ return `${targetText.trimEnd()}\n\n${ruleBlock}`;
2356
+ }
2357
+
2358
+ function mergeSessionLogEvidenceDispositionField(targetText) {
2359
+ if (targetText.includes("- **Evidence disposition:**")) return mergeSessionLogTemplateContract(targetText, null) ?? targetText;
2360
+ const qcField = "- **QC:**";
2361
+ if (!targetText.includes(qcField)) return null;
2362
+ const withEvidence = targetText.replace(qcField, `${qcField}\n- **Evidence disposition:** <one-time only / kept as recent trace evidence / absorbed into handoff / indexed in PROJECT_INDEX / promoted to PROJECT_DECISIONS / promoted to rule pack>`);
2363
+ return mergeSessionLogTemplateContract(withEvidence, null) ?? withEvidence;
2364
+ }
2365
+
2366
+ function mergeSessionLogTemplateContract(targetText, sourceText = null) {
2367
+ let merged = targetText;
2368
+ let changed = false;
2369
+
2370
+ if (!merged.includes("ack:section:session-log-preamble")) {
2371
+ const titleMatch = /^# Session Log\s*$/m.exec(merged);
2372
+ if (titleMatch) {
2373
+ const insertAt = titleMatch.index + titleMatch[0].length;
2374
+ merged = `${merged.slice(0, insertAt)}\n\n<!-- ack:section:session-log-preamble -->${merged.slice(insertAt)}`;
2375
+ changed = true;
2376
+ } else if (sourceText?.includes("ack:section:session-log-preamble")) {
2377
+ const sourcePreambleMarker = "<!-- ack:section:session-log-preamble -->";
2378
+ merged = `${sourcePreambleMarker}\n\n${merged}`;
2379
+ changed = true;
2380
+ }
2381
+ }
2382
+
2383
+ if (!merged.includes("ack:section:session-log-entry-template")) {
2384
+ const headingMatch = /^## Entry Template\s*$/m.exec(merged);
2385
+ if (headingMatch) {
2386
+ merged = `${merged.slice(0, headingMatch.index)}<!-- ack:section:session-log-entry-template -->\n\n${merged.slice(headingMatch.index)}`;
2387
+ changed = true;
2388
+ }
2389
+ }
2390
+
2391
+ if (sourceText) {
2392
+ const restored = restoreMissingSessionLogPreambleLines(merged, sourceText);
2393
+ if (restored !== merged) {
2394
+ merged = restored;
2395
+ changed = true;
2396
+ }
2397
+ }
2398
+
2399
+ const entryTemplateIndex = merged.search(/^## Entry Template\s*$/m);
2400
+ if (entryTemplateIndex >= 0) {
2401
+ const beforeTemplate = merged.slice(0, entryTemplateIndex);
2402
+ let templateAndAfter = merged.slice(entryTemplateIndex);
2403
+ if (!templateAndAfter.includes("ack:log-entry:start")) {
2404
+ const replaced = templateAndAfter.replace(/````markdown(\r?\n)/, "````markdown$1<!-- ack:log-entry:start -->$1");
2405
+ if (replaced !== templateAndAfter) {
2406
+ templateAndAfter = replaced;
2407
+ changed = true;
2408
+ }
2409
+ }
2410
+ if (!templateAndAfter.includes("ack:log-entry:end")) {
2411
+ const openingIndex = templateAndAfter.indexOf("````markdown");
2412
+ const closingIndex = openingIndex >= 0
2413
+ ? templateAndAfter.indexOf("\n````", openingIndex + "````markdown".length)
2414
+ : -1;
2415
+ if (closingIndex >= 0) {
2416
+ templateAndAfter = `${templateAndAfter.slice(0, closingIndex)}\n<!-- ack:log-entry:end -->${templateAndAfter.slice(closingIndex)}`;
2417
+ changed = true;
2418
+ }
2419
+ }
2420
+ merged = `${beforeTemplate}${templateAndAfter}`;
2421
+ }
2422
+
2423
+ return changed ? merged : targetText;
2424
+ }
2425
+
2426
+ function restoreMissingSessionLogPreambleLines(targetText, sourceText) {
2427
+ const sourceEntryIndex = sourceText.search(/^## Entry Template\s*$/m);
2428
+ const targetEntryMarkerIndex = targetText.indexOf("<!-- ack:section:session-log-entry-template -->");
2429
+ const targetEntryHeadingIndex = targetText.search(/^## Entry Template\s*$/m);
2430
+ const insertIndex = targetEntryMarkerIndex >= 0 ? targetEntryMarkerIndex : targetEntryHeadingIndex;
2431
+ if (sourceEntryIndex < 0 || insertIndex < 0) return targetText;
2432
+
2433
+ const sourcePreamble = sourceText.slice(0, sourceEntryIndex);
2434
+ const missingLines = [
2435
+ "Record what actually happened in the session",
2436
+ "kept, summarized, or archived",
2437
+ "Do not remove validation evidence",
2438
+ "latest opening message",
2439
+ "not current state"
2440
+ ].flatMap((snippet) => {
2441
+ if (targetText.includes(snippet)) return [];
2442
+ const line = sourcePreamble.split(/\r?\n/).find((candidate) => candidate.includes(snippet));
2443
+ return line ? [line] : [];
2444
+ });
2445
+
2446
+ if (missingLines.length === 0) return targetText;
2447
+ return `${targetText.slice(0, insertIndex).trimEnd()}\n\n${missingLines.join("\n\n")}\n\n${targetText.slice(insertIndex)}`;
2448
+ }
2449
+
2450
+ function mergeHandoffArchiveContinuityRule(targetText, sourceText) {
2451
+ const sourceMatch = sourceText.match(/Continuity rule: this file carries current state and next action\.[^\r\n]*/);
2452
+ if (!sourceMatch) return null;
2453
+ const continuityRule = sourceMatch[0];
2454
+ if (targetText.includes(continuityRule)) return targetText;
2455
+
2456
+ const existingRulePattern = /Continuity rule: this file carries current state and next action\.[^\r\n]*/;
2457
+ if (existingRulePattern.test(targetText)) {
2458
+ return targetText.replace(existingRulePattern, continuityRule);
2459
+ }
2460
+
2461
+ const nextSectionMarker = "<!-- ack:section:next-session-opening-message -->";
2462
+ if (targetText.includes(nextSectionMarker)) {
2463
+ return targetText.replace(nextSectionMarker, `${continuityRule}\n\n${nextSectionMarker}`);
2464
+ }
2465
+
2466
+ const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
2467
+ if (targetText.includes(sufficiencyMarker)) {
2468
+ return `${targetText.trimEnd()}\n\n${continuityRule}\n`;
2469
+ }
2470
+
2471
+ return null;
2472
+ }
2473
+
2474
+ function mergeRulePacksRows(targetText, sourceText) {
2475
+ const requiredPacks = [
2476
+ "dev/rules/onboarding.md",
2477
+ "dev/rules/integrations.md",
2478
+ "dev/rules/agent-governance.md"
2479
+ ];
2463
2480
  const sourceRows = sourceText
2464
2481
  .split(/\r?\n/)
2465
2482
  .filter((line) => line.startsWith("|") && requiredPacks.some((pack) => line.includes(pack)));
@@ -2474,24 +2491,24 @@ function mergeRulePacksRows(targetText, sourceText) {
2474
2491
 
2475
2492
  const before = lines.slice(0, tableStart);
2476
2493
  const table = lines.slice(tableStart, tableEnd);
2477
- const after = lines.slice(tableEnd);
2478
- const governanceBridgeSourceRow = sourceRows.find((row) => row.includes("Governance bridge / 治理打通"));
2479
- if (
2480
- governanceBridgeSourceRow
2481
- && targetText.includes("Governance bridge / 治理打通")
2482
- && (!targetText.includes("接入 Agent Handoff Kit") || !targetText.includes("掃描未接入 Agent Handoff Kit 的重要文件"))
2483
- ) {
2484
- const replaced = lines.map((line) => (
2485
- line.includes("Governance bridge / 治理打通") ? governanceBridgeSourceRow : line
2486
- ));
2487
- return replaced.join("\n");
2488
- }
2489
- const sourceRowsToApply = sourceRows.filter((row) => {
2490
- if (row.includes("dev/rules/onboarding.md")) return !targetText.includes("First-time user signals");
2491
- if (row.includes("dev/rules/integrations.md")) return !targetText.includes("External tool integrations");
2492
- if (row.includes("Governance bridge / 治理打通")) return !targetText.includes("Governance bridge / 治理打通");
2493
- return false;
2494
- });
2494
+ const after = lines.slice(tableEnd);
2495
+ const governanceBridgeSourceRow = sourceRows.find((row) => row.includes("Governance bridge / 治理打通"));
2496
+ if (
2497
+ governanceBridgeSourceRow
2498
+ && targetText.includes("Governance bridge / 治理打通")
2499
+ && (!targetText.includes("接入 Agent Handoff Kit") || !targetText.includes("掃描未接入 Agent Handoff Kit 的重要文件"))
2500
+ ) {
2501
+ const replaced = lines.map((line) => (
2502
+ line.includes("Governance bridge / 治理打通") ? governanceBridgeSourceRow : line
2503
+ ));
2504
+ return replaced.join("\n");
2505
+ }
2506
+ const sourceRowsToApply = sourceRows.filter((row) => {
2507
+ if (row.includes("dev/rules/onboarding.md")) return !targetText.includes("First-time user signals");
2508
+ if (row.includes("dev/rules/integrations.md")) return !targetText.includes("External tool integrations");
2509
+ if (row.includes("Governance bridge / 治理打通")) return !targetText.includes("Governance bridge / 治理打通");
2510
+ return false;
2511
+ });
2495
2512
  if (sourceRowsToApply.length === 0) return targetText;
2496
2513
 
2497
2514
  const merged = [
@@ -2509,14 +2526,14 @@ function mergeRulePacksRows(targetText, sourceText) {
2509
2526
  // maybePrintUpdateNotice which silently fails when npx auto-fetches latest (CLI version
2510
2527
  // equals npm latest, so the notice never triggers, leaving user root drift invisible).
2511
2528
  async function assessVersionAlignment(root, cliVersion) {
2512
- const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
2513
- let rootVersion = null;
2514
- try {
2515
- const text = await readFile(indexPath, "utf8");
2516
- rootVersion = projectIndexTemplateVersion(text);
2517
- } catch {
2518
- // file missing or unreadable; rootVersion stays null
2519
- }
2529
+ const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
2530
+ let rootVersion = null;
2531
+ try {
2532
+ const text = await readFile(indexPath, "utf8");
2533
+ rootVersion = projectIndexTemplateVersion(text);
2534
+ } catch {
2535
+ // file missing or unreadable; rootVersion stays null
2536
+ }
2520
2537
 
2521
2538
  let npmLatest = null;
2522
2539
  try {
@@ -2597,7 +2614,7 @@ async function assessLastCloseout(root) {
2597
2614
 
2598
2615
  function printLastCloseout(result) {
2599
2616
  if (!result.date) {
2600
- console.log(" 📅 上次收工:尚未收工過。第一次完成任務後,可以在 AI 對話輸入「收工」。");
2617
+ console.log(" 📅 上次收工:尚未收工過。準備結束本輪工作、需要保存交接、或有下一輪必須知道的狀態時,可以在 AI 對話輸入「收工」。");
2601
2618
  return;
2602
2619
  }
2603
2620
  const today = new Date();
@@ -2922,10 +2939,10 @@ function printInstallSummary(version, command, mode, root, counts) {
2922
2939
  console.log("🚀 下一步:把 migration report 或這段輸出貼給 AI,請它判斷衝突檔案怎樣處理;工具已停手,沒有覆寫 conflict 檔案。");
2923
2940
  } else if (command === "upgrade") {
2924
2941
  console.log("🚀 下一步:留意下方升級後自動檢查;若全綠即升級完成。");
2925
- } else if (mode === "partial" || counts.skipped > 0) {
2926
- console.log("🚀 下一步:先看下方提示。若你原本已有 AGENTS.md 或其他 AI 規則,請先執行 upgrade --dry-run 補入口連接,再執行 doctor。");
2927
- } else {
2928
- console.log("🚀 下一步:不用再留在終端機。打開 AI 工具,啟動 Agent Handoff。");
2942
+ } else if (mode === "partial" || counts.skipped > 0) {
2943
+ console.log("🚀 下一步:先看下方提示。若你原本已有 AGENTS.md 或其他 AI 規則,請先執行 upgrade --dry-run 補入口連接,再執行 doctor。");
2944
+ } else {
2945
+ console.log("🚀 下一步:不用再留在終端機。打開 AI 工具,啟動 Agent Handoff。");
2929
2946
  }
2930
2947
  }
2931
2948
 
@@ -3135,28 +3152,28 @@ function printInstallNextSteps(root, conflictCount, mode = "first-install", skip
3135
3152
  console.log("============================================================");
3136
3153
  return;
3137
3154
  }
3138
- console.log("------------------------------------------------------------");
3139
- console.log("⚠️ 下面這句不是終端機指令。");
3140
- console.log("📋 請打開能讀寫此資料夾的 AI agent。若 AI 已在此資料夾內,新增對話後輸入:");
3141
- console.log(" 例如 Claude Code、OpenAI Codex、Gemini CLI、Google Antigravity。");
3142
- console.log(" 普通 web chat AI 若不能讀寫本機資料夾,並不適合使用本工具。");
3143
- console.log("------------------------------------------------------------");
3144
- console.log("Start Agent Handoff");
3145
- console.log("或:開工");
3146
- console.log("------------------------------------------------------------");
3147
- console.log("若 AI 還未指向此資料夾,才貼以下帶路徑啟動句:");
3148
- console.log(startupPathBootstrapPrompt(root));
3149
- console.log("------------------------------------------------------------");
3150
- console.log("");
3151
- console.log("🚀 AI 會依 AGENTS.md 讀取 START_NEXT_SESSION_PROMPT.txt。第一次安裝後,該檔案會觸發新手引導;收工後,該檔案會承載下一次接力狀態。");
3152
- console.log(" 收工可說「Wrap up Agent Handoff」/「收工」;「某某開工 / 某某收工」會先確認是否指本工具交接。");
3153
- console.log("============================================================");
3154
- }
3155
+ console.log("------------------------------------------------------------");
3156
+ console.log("⚠️ 下面這句不是終端機指令。");
3157
+ console.log("📋 請打開能讀寫此資料夾的 AI agent。若 AI 已在此資料夾內,新增對話後輸入:");
3158
+ console.log(" 例如 Claude Code、OpenAI Codex、Gemini CLI、Google Antigravity。");
3159
+ console.log(" 普通 web chat AI 若不能讀寫本機資料夾,並不適合使用本工具。");
3160
+ console.log("------------------------------------------------------------");
3161
+ console.log("Start Agent Handoff");
3162
+ console.log("或:開工");
3163
+ console.log("------------------------------------------------------------");
3164
+ console.log("若 AI 還未指向此資料夾,才貼以下帶路徑啟動句:");
3165
+ console.log(startupPathBootstrapPrompt(root));
3166
+ console.log("------------------------------------------------------------");
3167
+ console.log("");
3168
+ console.log("🚀 AI 會依 AGENTS.md 讀取 START_NEXT_SESSION_PROMPT.txt。第一次安裝後,該檔案會觸發新手引導;收工後,該檔案會承載下一次接力狀態。");
3169
+ console.log(" 收工可說「Wrap up Agent Handoff」/「收工」;「某某開工 / 某某收工」會先確認是否指本工具交接。");
3170
+ console.log("============================================================");
3171
+ }
3155
3172
 
3156
3173
  // R-031 v0.3.1+: Upgrade substantive next-step block. Distinct from install
3157
3174
  // (`printInstallNextSteps`) because the user is not first-time; pushing them through
3158
3175
  // the onboarding canonical phrase resets context they already have.
3159
- function printUpgradeNextSteps(root, conflictCount) {
3176
+ function printUpgradeNextSteps(root, conflictCount) {
3160
3177
  console.log("");
3161
3178
  console.log("============================================================");
3162
3179
  if (conflictCount > 0) {
@@ -3168,79 +3185,79 @@ function printUpgradeNextSteps(root, conflictCount) {
3168
3185
  console.log("============================================================");
3169
3186
  return;
3170
3187
  }
3171
- console.log("🛠️ Kit 檔案已更新:等待下方 doctor 驗收");
3172
- console.log("============================================================");
3173
- console.log("📋 如你正在進行中的工作對話已熟悉 Agent Handoff Kit,繼續使用原本的開工方式即可,無需重新做新手引導。");
3174
- console.log("");
3175
- console.log("💡 版本詳情不在升級流程內展開;如需要,可稍後查看 GitHub Release:");
3176
- console.log(" https://github.com/Adamchanadam/agent-handoff-kit/releases/latest");
3177
- console.log("");
3178
- console.log("🩺 升級驗收會在下方自動執行 doctor;若全綠即升級完成。");
3179
- console.log("============================================================");
3180
- }
3181
-
3182
- // R-031 v0.3.24+: Upgrade no-op may skip file writes, but it must not skip the
3183
- // single health authority. If the CLI says a latest root can continue, that claim
3184
- // is backed by the same runDoctor() implementation users would invoke manually.
3185
- async function assessUpgradeNoopHealth(root, version) {
3186
- const originalLog = console.log;
3187
- const originalError = console.error;
3188
- const previousExitCode = process.exitCode;
3189
- const stdout = [];
3190
- const stderr = [];
3191
-
3192
- try {
3193
- console.log = (...args) => stdout.push(args.join(" "));
3194
- console.error = (...args) => stderr.push(args.join(" "));
3195
- process.exitCode = undefined;
3196
- const status = await runDoctor(root, version, { silentCard: true, context: "upgrade-noop-health-check" });
3197
- const doctorExitCode = process.exitCode;
3198
- return {
3199
- ok: status === "passed" && !doctorExitCode,
3200
- status,
3201
- stdout: stdout.join("\n"),
3202
- stderr: stderr.join("\n"),
3203
- error: null
3204
- };
3205
- } catch (error) {
3206
- return {
3207
- ok: false,
3208
- status: "failed",
3209
- stdout: stdout.join("\n"),
3210
- stderr: stderr.join("\n"),
3211
- error: error.message
3212
- };
3213
- } finally {
3214
- console.log = originalLog;
3215
- console.error = originalError;
3216
- process.exitCode = previousExitCode;
3217
- }
3218
- }
3219
-
3220
- function printUpgradeNoopShortCircuit(version, health = { ok: true }) {
3221
- console.log("");
3222
- console.log(`📦 版本:v${version}`);
3223
- console.log("🛠️ 模式:upgrade-existing");
3224
- console.log("🔎 剛完成:檢查所有 Kit 檔案的狀態(含 AGENTS.md、dev/SESSION_HANDOFF.md、dev/PROJECT_INDEX.md 等)。");
3225
- if (health.ok) {
3226
- console.log("✅ 結果:你已經是最新版本,沒有檔案需要建立或合併;用戶填寫的內容全部保留現狀。");
3227
- console.log("");
3228
- console.log("🚀 下一步:回到原本的 AI 對話或開工句即可;如果剛完成任務,記得在 AI 對話輸入「收工」保存交接。");
3229
- console.log("");
3230
- return;
3231
- }
3232
- console.log("⚠️ 結果:Kit 檔案已是最新版本,沒有檔案需要建立或合併;但完整 doctor 健康檢查未通過。");
3233
- console.log("");
3234
- console.log("🩺 doctor 輸出:");
3235
- const doctorOutput = [health.stdout, health.stderr, health.error ? `error: ${health.error}` : ""]
3236
- .filter(Boolean)
3237
- .join("\n")
3238
- .trim();
3239
- console.log(doctorOutput || "doctor did not return readable output.");
3240
- console.log("");
3241
- console.log("🚀 下一步:把上方 doctor 輸出貼給能讀寫此資料夾的 AI,請它按失敗項修補;不要重裝或覆寫用戶內容。");
3242
- console.log("");
3243
- }
3188
+ console.log("🛠️ Kit 檔案已更新:等待下方 doctor 驗收");
3189
+ console.log("============================================================");
3190
+ console.log("📋 如你正在進行中的工作對話已熟悉 Agent Handoff Kit,繼續使用原本的開工方式即可,無需重新做新手引導。");
3191
+ console.log("");
3192
+ console.log("💡 版本詳情不在升級流程內展開;如需要,可稍後查看 GitHub Release:");
3193
+ console.log(" https://github.com/Adamchanadam/agent-handoff-kit/releases/latest");
3194
+ console.log("");
3195
+ console.log("🩺 升級驗收會在下方自動執行 doctor;若全綠即升級完成。");
3196
+ console.log("============================================================");
3197
+ }
3198
+
3199
+ // R-031 v0.3.24+: Upgrade no-op may skip file writes, but it must not skip the
3200
+ // single health authority. If the CLI says a latest root can continue, that claim
3201
+ // is backed by the same runDoctor() implementation users would invoke manually.
3202
+ async function assessUpgradeNoopHealth(root, version) {
3203
+ const originalLog = console.log;
3204
+ const originalError = console.error;
3205
+ const previousExitCode = process.exitCode;
3206
+ const stdout = [];
3207
+ const stderr = [];
3208
+
3209
+ try {
3210
+ console.log = (...args) => stdout.push(args.join(" "));
3211
+ console.error = (...args) => stderr.push(args.join(" "));
3212
+ process.exitCode = undefined;
3213
+ const status = await runDoctor(root, version, { silentCard: true, context: "upgrade-noop-health-check" });
3214
+ const doctorExitCode = process.exitCode;
3215
+ return {
3216
+ ok: status === "passed" && !doctorExitCode,
3217
+ status,
3218
+ stdout: stdout.join("\n"),
3219
+ stderr: stderr.join("\n"),
3220
+ error: null
3221
+ };
3222
+ } catch (error) {
3223
+ return {
3224
+ ok: false,
3225
+ status: "failed",
3226
+ stdout: stdout.join("\n"),
3227
+ stderr: stderr.join("\n"),
3228
+ error: error.message
3229
+ };
3230
+ } finally {
3231
+ console.log = originalLog;
3232
+ console.error = originalError;
3233
+ process.exitCode = previousExitCode;
3234
+ }
3235
+ }
3236
+
3237
+ function printUpgradeNoopShortCircuit(version, health = { ok: true }) {
3238
+ console.log("");
3239
+ console.log(`📦 版本:v${version}`);
3240
+ console.log("🛠️ 模式:upgrade-existing");
3241
+ console.log("🔎 剛完成:檢查所有 Kit 檔案的狀態(含 AGENTS.md、dev/SESSION_HANDOFF.md、dev/PROJECT_INDEX.md 等)。");
3242
+ if (health.ok) {
3243
+ console.log("✅ 結果:你已經是最新版本,沒有檔案需要建立或合併;用戶填寫的內容全部保留現狀。");
3244
+ console.log("");
3245
+ console.log("🚀 下一步:回到原本的 AI 對話或開工句即可;準備結束本輪工作、需要保存交接、或有下一輪必須知道的狀態時,在 AI 對話輸入「收工」。");
3246
+ console.log("");
3247
+ return;
3248
+ }
3249
+ console.log("⚠️ 結果:Kit 檔案已是最新版本,沒有檔案需要建立或合併;但完整 doctor 健康檢查未通過。");
3250
+ console.log("");
3251
+ console.log("🩺 doctor 輸出:");
3252
+ const doctorOutput = [health.stdout, health.stderr, health.error ? `error: ${health.error}` : ""]
3253
+ .filter(Boolean)
3254
+ .join("\n")
3255
+ .trim();
3256
+ console.log(doctorOutput || "doctor did not return readable output.");
3257
+ console.log("");
3258
+ console.log("🚀 下一步:把上方 doctor 輸出貼給能讀寫此資料夾的 AI,請它按失敗項修補;不要重裝或覆寫用戶內容。");
3259
+ console.log("");
3260
+ }
3244
3261
 
3245
3262
  function listOrNone(items) {
3246
3263
  if (items.length === 0) return ["- none"];
@@ -3270,48 +3287,48 @@ Commands:
3270
3287
  upgrade Preserve existing files; merge safe core updates or report conflicts.
3271
3288
  doctor Check required installed files.
3272
3289
 
3273
- 中文速讀:
3274
- ✅ 第一次用:先在項目資料夾執行 init。
3275
- 🔄 已裝過:執行 upgrade;若想先預覽,才加 --dry-run。
3276
- 🩺 不確定狀態:用 doctor 檢查;doctor 只檢查,不會改檔。
3277
-
3278
- 安裝之後:
3279
- 不要把顯示出來的 Start Agent Handoff 或 "Work in ..." 文字輸入終端機。
3280
- 請打開能讀寫此資料夾的 AI agent。若 AI 已在此資料夾內,新增對話後輸入:
3281
- Start Agent Handoff
3282
- 或:開工
3283
- 若 AI 還未指向此資料夾,才貼帶路徑啟動句:
3284
- Work in <project root>. Read AGENTS.md first, then Start Agent Handoff. Before changing anything, tell me the current state and your recommended next step.
3285
- 例如 Claude Code、OpenAI Codex、Gemini CLI、Google Antigravity。
3286
- 普通 web chat AI 若不能讀寫本機資料夾,並不適合使用本工具。
3287
- AI 會依 AGENTS.md 讀取 START_NEXT_SESSION_PROMPT.txt;第一次安裝後該檔案會啟動新手引導,
3288
- 收工後該檔案會承載下一次接力狀態。
3289
- 用「Wrap up Agent Handoff」/「收工」保存交接;「某某開工 / 某某收工」
3290
- 會先確認是否指本工具交接。
3291
-
3292
- 終端機範例:
3293
- npx --yes @adamchanadam/agent-handoff-kit@latest init
3294
- npx --yes @adamchanadam/agent-handoff-kit@latest upgrade
3295
- npx --yes @adamchanadam/agent-handoff-kit@latest doctor
3296
-
3297
- 升級前如想先看會改甚麼,才用預演:
3298
- npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run
3299
- --dry-run 只預覽、不寫入;它不是正式升級完成。
3290
+ 中文速讀:
3291
+ ✅ 第一次用:先在項目資料夾執行 init。
3292
+ 🔄 已裝過:執行 upgrade;若想先預覽,才加 --dry-run。
3293
+ 🩺 不確定狀態:用 doctor 檢查;doctor 只檢查,不會改檔。
3294
+
3295
+ 安裝之後:
3296
+ 不要把顯示出來的 Start Agent Handoff 或 "Work in ..." 文字輸入終端機。
3297
+ 請打開能讀寫此資料夾的 AI agent。若 AI 已在此資料夾內,新增對話後輸入:
3298
+ Start Agent Handoff
3299
+ 或:開工
3300
+ 若 AI 還未指向此資料夾,才貼帶路徑啟動句:
3301
+ Work in <project root>. Read AGENTS.md first, then Start Agent Handoff. Before changing anything, tell me the current state and your recommended next step.
3302
+ 例如 Claude Code、OpenAI Codex、Gemini CLI、Google Antigravity。
3303
+ 普通 web chat AI 若不能讀寫本機資料夾,並不適合使用本工具。
3304
+ AI 會依 AGENTS.md 讀取 START_NEXT_SESSION_PROMPT.txt;第一次安裝後該檔案會啟動新手引導,
3305
+ 收工後該檔案會承載下一次接力狀態。
3306
+ 用「Wrap up Agent Handoff」/「收工」保存交接;「某某開工 / 某某收工」
3307
+ 會先確認是否指本工具交接。
3308
+
3309
+ 終端機範例:
3310
+ npx --yes @adamchanadam/agent-handoff-kit@latest init
3311
+ npx --yes @adamchanadam/agent-handoff-kit@latest upgrade
3312
+ npx --yes @adamchanadam/agent-handoff-kit@latest doctor
3313
+
3314
+ 升級前如想先看會改甚麼,才用預演:
3315
+ npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run
3316
+ --dry-run 只預覽、不寫入;它不是正式升級完成。
3300
3317
 
3301
3318
  以上才是建議的 npx 用戶路徑。裸寫不帶 --yes / @latest 的 npx doctor
3302
3319
  不是本工具的建議用戶路徑,容易先出現 npm 自己的安裝提示。
3303
3320
 
3304
3321
  即使資料夾已有 AGENTS.md 或 dev/,電腦也未必已經有可直接執行的工具;
3305
- npx --yes 只是先取得工具,然後才執行你指定的 init / upgrade / doctor。
3322
+ npx --yes 只是先取得工具,然後才執行你指定的 init / upgrade / doctor。
3306
3323
 
3307
3324
  放在 package 名稱前的 --yes 只讓 npm 先取得執行工具,避免額外出現
3308
3325
  "Need to install" 提示。真正會建立項目文件的是 init;doctor 只檢查。
3309
3326
  `);
3310
3327
  console.log(`📦 版本:v${version}`);
3311
- console.log(`🛠️ 模式:help ready`);
3312
- console.log(`🚀 下一步:新項目先執行 init;舊項目執行 upgrade;只想檢查才執行 doctor。`);
3313
- }
3314
-
3315
- function startupPathBootstrapPrompt(root) {
3316
- return `Work in ${root}. Read AGENTS.md first, then Start Agent Handoff. Before changing anything, tell me the current state and your recommended next step.`;
3317
- }
3328
+ console.log(`🛠️ 模式:help ready`);
3329
+ console.log(`🚀 下一步:新項目先執行 init;舊項目執行 upgrade;只想檢查才執行 doctor。`);
3330
+ }
3331
+
3332
+ function startupPathBootstrapPrompt(root) {
3333
+ return `Work in ${root}. Read AGENTS.md first, then Start Agent Handoff. Before changing anything, tell me the current state and your recommended next step.`;
3334
+ }