@adamchanadam/agent-handoff-kit 0.3.34 → 0.3.36

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.
@@ -52,9 +52,11 @@ const requiredAnchors = [
52
52
  "dev/RULE_PACKS.md",
53
53
  "Agent Handoff Kit v<version>",
54
54
  "Display version rule",
55
- "Agent Handoff Kit template version",
56
- "continuity ready",
57
- "Start Agent Handoff",
55
+ "Agent Handoff Kit template version",
56
+ "continuity ready",
57
+ "推薦下一步",
58
+ "recommended action",
59
+ "Start Agent Handoff",
58
60
  "Ambiguous startup phrases",
59
61
  "Reachable is not the same as ingested",
60
62
  "Do not treat unread sources as absent",
@@ -111,15 +113,27 @@ const requiredAnchors = [
111
113
  "ack:section:sync-status",
112
114
  "ack:section:next-task-required-reading",
113
115
  "ack:section:state-reconciliation-check",
114
- "ack:section:next-session-opening-message",
115
- "ack:field:lifecycle-conflicts-resolved",
116
+ "ack:section:next-session-opening-message",
117
+ "ack:field:recommended-next-step-explicit",
118
+ "ack:field:lifecycle-conflicts-resolved",
116
119
  "ack:field:persistence-routing-checked",
117
120
  "📋 Next session:",
118
121
  "```text",
119
122
  "Read in order:",
120
- "dev/DOC_SYNC_REGISTRY.md"
121
- ]
122
- },
123
+ "dev/DOC_SYNC_REGISTRY.md"
124
+ ]
125
+ },
126
+ {
127
+ target: "dev/rules/communication.md",
128
+ label: "communication recommended next-step discipline",
129
+ snippets: [
130
+ "Communication Pack",
131
+ "recommended next step",
132
+ "state it directly with a short reason",
133
+ "Offer two or three choices only when the user truly must decide",
134
+ "do not turn an already-made technical judgment into an open question"
135
+ ]
136
+ },
123
137
  {
124
138
  target: "dev/SESSION_LOG.md",
125
139
  label: "session log event and opening message schema",
@@ -166,41 +180,56 @@ const requiredAnchors = [
166
180
  "not current state"
167
181
  ]
168
182
  },
169
- {
170
- target: "dev/PROJECT_INDEX.md",
171
- label: "template version metadata",
172
- placement: projectIndexAnchorPlacement,
173
- snippets: [
174
- "Agent Handoff Kit template version"
175
- ]
176
- },
177
- {
178
- target: "dev/rules/safety.md",
179
- label: "safety pack high-risk anchors",
183
+ {
184
+ target: "dev/PROJECT_INDEX.md",
185
+ label: "template version metadata",
186
+ placement: projectIndexAnchorPlacement,
187
+ snippets: [
188
+ "Agent Handoff Kit template version"
189
+ ]
190
+ },
191
+ {
192
+ target: "dev/PROJECT_INDEX.md",
193
+ label: "tool operation references",
194
+ snippets: [
195
+ "Tool Operation References",
196
+ "runtime-controlled tools",
197
+ "Source and version/date",
198
+ "Scope and known limits"
199
+ ]
200
+ },
201
+ {
202
+ target: "dev/rules/safety.md",
203
+ label: "safety pack high-risk anchors",
180
204
  placement: safetyAnchorPlacement,
181
205
  snippets: [
182
206
  "deleting, overwriting, moving, renaming",
183
207
  "filesystem root, drive root",
184
208
  "cmd /c rmdir",
185
209
  "git reset --hard",
186
- "external APIs, SDKs, CLIs",
187
- "parser failure",
188
- "secret values"
210
+ "external APIs, SDKs, CLIs",
211
+ "parser failure",
212
+ "secret values",
213
+ "task-owned or agent-managed",
214
+ "other-agent-owned",
215
+ "browser profiles",
216
+ "desktop app sessions",
217
+ "shared tool servers",
218
+ "notebook kernels"
189
219
  ]
190
220
  },
191
221
  {
192
- target: "dev/PROJECT_DECISIONS.md",
193
- label: "project decisions narrative anchors",
194
- placement: projectDecisionsAnchorPlacement,
195
- snippets: [
196
- "Project Decisions Log",
197
- "warm 資料層",
198
- "AI 開工",
199
- "不需要讀",
200
- "AI 在收工時自動 update",
201
- "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.",
202
- "This file does not store raw build / upload / QC evidence",
203
- "Evolution Timeline",
222
+ target: "dev/PROJECT_DECISIONS.md",
223
+ label: "project decisions narrative anchors",
224
+ placement: projectDecisionsAnchorPlacement,
225
+ snippets: [
226
+ "Project Decisions Log",
227
+ "warm narrative layer",
228
+ "do not need to read this file at startup",
229
+ "The AI updates it during closeout",
230
+ "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.",
231
+ "This file does not store raw build / upload / QC evidence",
232
+ "Evolution Timeline",
204
233
  "Decisions Archive",
205
234
  "Architecture Choices",
206
235
  "Insights & Learnings"
@@ -209,22 +238,22 @@ const requiredAnchors = [
209
238
  {
210
239
  target: "dev/rules/onboarding.md",
211
240
  label: "onboarding pack core anchors",
212
- placement: onboardingAnchorPlacement,
213
- snippets: [
214
- "Onboarding Pack",
215
- "transient pack",
216
- "明確 onboarding signal keywords",
217
- "5-step walk-through pattern",
218
- "Application Scenario Library",
219
- "Scenario A. 建構系統 / 工具 / 平台 / 網站或應用",
220
- "Scenario B. 整理研究資料",
221
- "Scenario C. 整理電腦檔案",
222
- "Scenario D. 學寫代碼",
223
- "Scenario E. 其他",
224
- "Scenario F. 審視已裝外部工具",
225
- "Tone Discipline"
226
- ]
227
- },
241
+ placement: onboardingAnchorPlacement,
242
+ snippets: [
243
+ "Onboarding Pack",
244
+ "transient pack",
245
+ "Explicit onboarding signal keywords",
246
+ "5-step walk-through pattern",
247
+ "Application Scenario Library",
248
+ "Scenario A. Build systems, tools, platforms, websites, or apps",
249
+ "Scenario B. Organize research or write a report",
250
+ "Scenario C. Organize local files, Notion, Google Drive, or a knowledge base",
251
+ "Scenario D. Learn to code",
252
+ "Scenario E. Custom scenario",
253
+ "Scenario F. External-tool governance",
254
+ "Tone Discipline"
255
+ ]
256
+ },
228
257
  {
229
258
  target: "dev/rules/integrations.md",
230
259
  label: "integrations pack core anchors",
@@ -235,17 +264,22 @@ const requiredAnchors = [
235
264
  "MCPs",
236
265
  "Plugins",
237
266
  "Skills",
238
- "機密分離原則",
267
+ "Credential Separation Principle",
239
268
  "External Tool Usage Verification Gate",
269
+ "External Tool Resource Lifecycle",
270
+ "other-agent-owned",
240
271
  "do not invent",
241
272
  "input schema",
242
273
  "official documentation",
243
274
  "Source-of-truth Architecture",
244
275
  "Cross-session Lifecycle",
245
276
  "Connector-first default",
246
- "Anti-pattern"
247
- ]
248
- }
277
+ "Runtime-Controlled Tool Operation Variants",
278
+ "Tool Operation References",
279
+ "Do not guess Chrome, Playwright, or DevTools commands",
280
+ "Anti-pattern"
281
+ ]
282
+ }
249
283
  ];
250
284
 
251
285
  const schemaChecks = [
@@ -278,9 +312,10 @@ const schemaChecks = [
278
312
  section("handoff-sufficiency-check", "Handoff Sufficiency Check"),
279
313
  section("next-session-opening-message", "Next Session Opening Message"),
280
314
  marker("field", "stale-snapshots-left", "Stale snapshots left in this handoff"),
281
- marker("field", "lifecycle-conflicts-resolved", "Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified"),
282
- marker("field", "persistence-routing-checked", "Persistence routing checked"),
283
- marker("field", "opening-message-matches-current-state", "Opening message matches current state"),
315
+ marker("field", "lifecycle-conflicts-resolved", "Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified"),
316
+ marker("field", "persistence-routing-checked", "Persistence routing checked"),
317
+ marker("field", "recommended-next-step-explicit", "Recommended next step is explicit and reasoned"),
318
+ marker("field", "opening-message-matches-current-state", "Opening message matches current state"),
284
319
  marker("field", "state-sections-rewritten-or-confirmed", "State sections rewritten or confirmed current"),
285
320
  marker("field", "user-intent", "User intent:"),
286
321
  marker("field", "task-essence", "Task essence:"),
@@ -337,9 +372,10 @@ const schemaChecks = [
337
372
  heading("Directory Map"),
338
373
  heading("Entry Points"),
339
374
  heading("Fact Base"),
340
- heading("External Sources"),
341
- heading("Installed Integrations"),
342
- heading("Local QC Commands"),
375
+ heading("External Sources"),
376
+ heading("Installed Integrations"),
377
+ heading("Tool Operation References"),
378
+ heading("Local QC Commands"),
343
379
  heading("Workspace Identity"),
344
380
  heading("Change Hotspots"),
345
381
  heading("Maintenance Rule"),
@@ -352,13 +388,14 @@ const schemaChecks = [
352
388
  tableHeader("Check", "Command", "Run before", "Last verified"),
353
389
  tableHeader("Change type", "Likely files", "Required checks"),
354
390
  // R-030 v0.3.0+: Installed Integrations subsection table headers
355
- tableHeader("Tool", "Project Usage", "Access Scope", "Specific Instance", "Credential Reference(no value)", "Declared", "Last Verified"),
356
- tableHeader("Server", "Source", "Project Usage", "Credential Reference(no value)", "Declared", "Last Verified"),
357
- tableHeader("Name", "Bundle Content(Skills + MCP + hooks)", "When Triggered", "Last Verified"),
358
- tableHeader("Name", "Source", "When Triggered", "Last Verified"),
359
- tableHeader("Layer", "Surface(具體 instance)", "Role", "Write Direction")
360
- ]
361
- },
391
+ tableHeader("Tool", "Project Usage", "Access Scope", "Specific Instance", "Credential Reference (no value)", "Declared", "Last Verified"),
392
+ tableHeader("Server", "Source", "Project Usage", "Credential Reference (no value)", "Declared", "Last Verified"),
393
+ tableHeader("Name", "Bundle Content (Skills + MCP + hooks)", "When Triggered", "Last Verified"),
394
+ tableHeader("Name", "Source", "When Triggered", "Last Verified"),
395
+ tableHeader("Layer", "Surface (specific instance)", "Role", "Write Direction"),
396
+ tableHeader("Tool / operation", "Reference path or URL", "Required before", "Source and version/date", "Scope and known limits", "Last verified")
397
+ ]
398
+ },
362
399
  {
363
400
  target: "dev/DOC_SYNC_REGISTRY.md",
364
401
  label: "doc sync registry status vocabulary",
@@ -388,14 +425,16 @@ const schemaChecks = [
388
425
  // stale routing table that does not route onboarding signals.
389
426
  includes("First-time user signals"),
390
427
  includes("dev/rules/onboarding.md"),
391
- // R-030 v0.3.0+: routing table must include integrations pack row.
392
- includes("dev/rules/integrations.md"),
393
- includes("Governance bridge / 治理打通"),
394
- includes("接入 Agent Handoff Kit"),
395
- includes("掃描未接入 Agent Handoff Kit 的重要文件"),
396
- includes("scan for unbridged governance documents")
397
- ]
398
- },
428
+ // R-030 v0.3.0+: routing table must include integrations pack row.
429
+ includes("dev/rules/integrations.md"),
430
+ includes("External tool resource pressure"),
431
+ includes("ownership-based external-tool resource closeout"),
432
+ includes("Governance bridge / bridge governance"),
433
+ includes("equivalent Chinese user phrases"),
434
+ includes("scan for unbridged governance documents"),
435
+ includes("scan for unbridged governance documents")
436
+ ]
437
+ },
399
438
  {
400
439
  target: "dev/rules/agent-governance.md",
401
440
  label: "agent governance pack structure",
@@ -407,11 +446,11 @@ const schemaChecks = [
407
446
  heading("Checks"),
408
447
  heading("Closeout"),
409
448
  includes("Governance bridge is a triggered review"),
410
- includes("接入 Agent Handoff Kit"),
411
- includes("掃描未接入 Agent Handoff Kit 的重要文件"),
412
- includes("Status: bridged / partially bridged / unbridged / blocked"),
413
- includes("duplicate source-of-truth risk")
414
- ]
449
+ includes("equivalent Chinese phrases"),
450
+ includes("scan for unbridged governance documents"),
451
+ includes("Status: bridged / partially bridged / unbridged / blocked"),
452
+ includes("duplicate source-of-truth risk")
453
+ ]
415
454
  },
416
455
  {
417
456
  target: "dev/PROJECT_DECISIONS.md",
@@ -427,7 +466,7 @@ const schemaChecks = [
427
466
  },
428
467
  {
429
468
  target: "dev/rules/onboarding.md",
430
- label: "onboarding pack structure (新手引導包)",
469
+ label: "onboarding pack structure",
431
470
  checks: [
432
471
  heading("Scope"),
433
472
  heading("Load When"),
@@ -440,15 +479,17 @@ const schemaChecks = [
440
479
  },
441
480
  {
442
481
  target: "dev/rules/integrations.md",
443
- label: "integrations pack structure (外部工具治理)",
444
- checks: [
445
- heading("Scope"),
446
- heading("Load When"),
447
- heading("Discipline"),
448
- heading("Rules"),
482
+ label: "integrations pack structure",
483
+ checks: [
484
+ heading("Scope"),
485
+ heading("Load When"),
486
+ heading("Discipline"),
487
+ includes("External Tool Resource Lifecycle"),
488
+ includes("other-agent-owned"),
489
+ heading("Rules"),
449
490
  heading("Checks"),
450
491
  heading("Closeout"),
451
- heading("Anti-pattern(不要做的事)"),
492
+ heading("Anti-patterns"),
452
493
  heading("Cross-reference")
453
494
  ]
454
495
  }
@@ -866,7 +907,7 @@ async function runDoctor(root, version, options = {}) {
866
907
 
867
908
  // R-030 v0.3.0+: credential leak prevention sweep over governance files.
868
909
  const credentialResult = await checkInstalledIntegrationsCredentialLeak(root);
869
- console.log(`Credential 機密分離 sweep: ${credentialResult.ok ? "ok" : "FAILED"}`);
910
+ console.log(`Credential separation sweep: ${credentialResult.ok ? "ok" : "FAILED"}`);
870
911
  if (!credentialResult.ok) {
871
912
  for (const finding of credentialResult.findings) {
872
913
  console.log(` CRITICAL: ${finding}`);
@@ -1691,25 +1732,39 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1691
1732
  };
1692
1733
  }
1693
1734
  // R-030 v0.3.0+: dev/RULE_PACKS.md must also include integrations pack routing row.
1694
- if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && !targetText.includes("External tool integrations")) {
1695
- const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1696
- if (!mergedRulePacks) {
1697
- return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
1735
+ if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && !targetText.includes("External tool integrations")) {
1736
+ const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1737
+ if (!mergedRulePacks) {
1738
+ return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
1698
1739
  }
1699
1740
  return {
1700
1741
  ...base,
1701
1742
  action: "merge",
1702
1743
  reason: "merge missing v0.3.0+ routing rows while preserving existing custom rows (Integration governance routing)",
1703
- mergedText: mergedRulePacks
1704
- };
1705
- }
1744
+ mergedText: mergedRulePacks
1745
+ };
1746
+ }
1747
+ // External-tool resource lifecycle extension: old v0.3.x installs may already
1748
+ // have the integrations row, but still lack the resource-pressure routing row.
1749
+ if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && !targetText.includes("External tool resource pressure")) {
1750
+ const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1751
+ if (!mergedRulePacks) {
1752
+ return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
1753
+ }
1754
+ return {
1755
+ ...base,
1756
+ action: "merge",
1757
+ reason: "merge missing external-tool resource lifecycle routing row while preserving existing custom rows",
1758
+ mergedText: mergedRulePacks
1759
+ };
1760
+ }
1706
1761
  // Governance bridge v0.3.27+: route durable document bridging requests to
1707
1762
  // agent-governance without replacing user-added routing rows.
1708
- if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && (
1709
- !targetText.includes("Governance bridge / 治理打通")
1710
- || !targetText.includes("接入 Agent Handoff Kit")
1711
- || !targetText.includes("掃描未接入 Agent Handoff Kit 的重要文件")
1712
- )) {
1763
+ if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && (
1764
+ !targetText.includes("Governance bridge / bridge governance")
1765
+ || !targetText.includes("equivalent Chinese user phrases")
1766
+ || !targetText.includes("scan for unbridged governance documents")
1767
+ )) {
1713
1768
  const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1714
1769
  if (!mergedRulePacks) {
1715
1770
  return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
@@ -1718,16 +1773,29 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1718
1773
  ...base,
1719
1774
  action: "merge",
1720
1775
  reason: "merge missing governance bridge routing row while preserving existing custom rows",
1721
- mergedText: mergedRulePacks
1722
- };
1723
- }
1724
- // Governance bridge v0.3.27+: add the triggered review workflow to the
1725
- // agent-governance pack only when the pack still has a trusted Checks section.
1726
- if (targetRel === "dev/rules/agent-governance.md" && command === "upgrade" && (
1727
- !targetText.includes("## Governance Bridge Workflow")
1728
- || !targetText.includes("接入 Agent Handoff Kit")
1729
- || !targetText.includes("掃描未接入 Agent Handoff Kit 的重要文件")
1730
- )) {
1776
+ mergedText: mergedRulePacks
1777
+ };
1778
+ }
1779
+ // Language migration: older integrations packs were AI-facing rules written
1780
+ // partly in Chinese/Cantonese. If the file still has the trusted legacy Kit
1781
+ // shape, replace it with the current English maintainer pack. If the shape is
1782
+ // ambiguous or locally restructured, stop as a conflict instead of doing a
1783
+ // partial merge that could create a half-English, half-legacy pack.
1784
+ if (targetRel === "dev/rules/integrations.md" && command === "upgrade" && isLegacyChineseIntegrationsPack(targetText)) {
1785
+ return {
1786
+ ...base,
1787
+ action: "merge",
1788
+ reason: "replace legacy Chinese integrations pack with current English maintainer pack",
1789
+ mergedText: sourceText
1790
+ };
1791
+ }
1792
+ // Governance bridge v0.3.27+: add the triggered review workflow to the
1793
+ // agent-governance pack only when the pack still has a trusted Checks section.
1794
+ if (targetRel === "dev/rules/agent-governance.md" && command === "upgrade" && (
1795
+ !targetText.includes("## Governance Bridge Workflow")
1796
+ || !targetText.includes("equivalent Chinese phrases")
1797
+ || !targetText.includes("scan for unbridged governance documents")
1798
+ )) {
1731
1799
  const mergedGovernancePack = mergeAgentGovernanceBridgeWorkflow(targetText, sourceText);
1732
1800
  if (!mergedGovernancePack) {
1733
1801
  return { ...base, action: "conflict", reason: "agent-governance pack structure was changed; manual merge required to add governance bridge workflow" };
@@ -1747,7 +1815,7 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1747
1815
  // Extract just the ## Installed Integrations block from source (not touching External Sources).
1748
1816
  const sourceInstalledMatch = sourceText.match(/(## Installed Integrations[\s\S]*?)(?=## Local QC Commands)/);
1749
1817
  if (sourceInstalledMatch && targetText.includes("## Local QC Commands")) {
1750
- const installedBlock = sourceInstalledMatch[1];
1818
+ const installedBlock = sourceInstalledMatch[1];
1751
1819
  return {
1752
1820
  ...base,
1753
1821
  action: "merge",
@@ -1756,10 +1824,25 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1756
1824
  };
1757
1825
  }
1758
1826
  }
1827
+ if (targetRel === "dev/PROJECT_INDEX.md" && command === "upgrade" && !targetText.includes("## Tool Operation References")) {
1828
+ const sourceToolRefsMatch = sourceText.match(/(## Tool Operation References[\s\S]*?)(?=## Local QC Commands)/);
1829
+ if (sourceToolRefsMatch && targetText.includes("## Local QC Commands")) {
1830
+ const toolRefsBlock = sourceToolRefsMatch[1];
1831
+ const normalizedTarget = mergeProjectIndexCredentialReferences(targetText);
1832
+ return {
1833
+ ...base,
1834
+ action: "merge",
1835
+ reason: "insert ## Tool Operation References section template before ## Local QC Commands and normalize integration reference wording (runtime-controlled tool operation governance)",
1836
+ mergedText: normalizedTarget.replace("## Local QC Commands", toolRefsBlock + "## Local QC Commands")
1837
+ };
1838
+ }
1839
+ }
1759
1840
  if (targetRel === "dev/PROJECT_INDEX.md" && command === "upgrade" && (
1760
1841
  targetText.includes("Credential Location")
1842
+ || targetText.includes("Credential Reference(no value)")
1761
1843
  || targetText.includes("Claude Code MCP config + env var")
1762
1844
  || targetText.includes("Credential 應由 AI 工具自身 secure storage 管理(譬如 Claude Desktop Extensions")
1845
+ || targetText.includes("機密分離原則")
1763
1846
  )) {
1764
1847
  const mergedProjectIndex = mergeProjectIndexCredentialReferences(targetText);
1765
1848
  if (mergedProjectIndex !== targetText) {
@@ -1771,14 +1854,25 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1771
1854
  };
1772
1855
  }
1773
1856
  }
1774
- // R-030 v0.3.0+: dev/rules/onboarding.md gets ### Scenario F block auto-inserted before
1775
- // ## Cross-reference to guide.html on upgrade if missing. NON-DESTRUCTIVE: existing Scenarios A-E
1776
- // content and any user customization preserved. Step 1 micro-question additions to Scenarios A-E
1777
- // are NOT auto-migrated (user-customizable inline sample wording, not anchor-enforced); users get
1778
- // those on fresh install only or can manually patch following CHANGELOG migration guidance.
1779
- if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario F. 審視已裝外部工具")) {
1780
- const sourceScenarioFMatch = sourceText.match(/(### Scenario F\. 審視已裝外部工具[\s\S]*?)(?=## Cross-reference to guide\.html)/);
1781
- if (sourceScenarioFMatch && hasTrustedOnboardingScenarioLibrary(targetText)) {
1857
+ // Language migration: older onboarding packs were AI-facing rules written
1858
+ // mostly in Chinese. If the file still has the trusted legacy Kit shape,
1859
+ // replace it with the current concise English maintainer pack. If the shape
1860
+ // is ambiguous or locally restructured, stop as a conflict instead of
1861
+ // producing a half-English, half-legacy pack.
1862
+ if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && isLegacyChineseOnboardingPack(targetText)) {
1863
+ return {
1864
+ ...base,
1865
+ action: "merge",
1866
+ reason: "replace legacy Chinese onboarding pack with current English maintainer pack",
1867
+ mergedText: sourceText
1868
+ };
1869
+ }
1870
+ // R-030 v0.3.0+: dev/rules/onboarding.md gets Scenario F auto-inserted before
1871
+ // ## Cross-reference to guide.html on upgrade if missing and the pack is not
1872
+ // a legacy Chinese pack that should be replaced wholesale.
1873
+ if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario F. External-tool governance")) {
1874
+ const sourceScenarioFMatch = sourceText.match(/(### Scenario F\. External-tool governance[\s\S]*?)(?=## Cross-reference to guide\.html)/);
1875
+ if (sourceScenarioFMatch && hasTrustedOnboardingScenarioLibrary(targetText)) {
1782
1876
  const scenarioFBlock = sourceScenarioFMatch[1];
1783
1877
  return {
1784
1878
  ...base,
@@ -1788,7 +1882,7 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1788
1882
  };
1789
1883
  }
1790
1884
  }
1791
- if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario A. 建構系統 / 工具 / 平台 / 網站或應用")) {
1885
+ if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario A. Build systems, tools, platforms, websites, or apps")) {
1792
1886
  const mergedOnboarding = mergeOnboardingScenarioALabel(targetText);
1793
1887
  if (mergedOnboarding !== targetText) {
1794
1888
  return {
@@ -1814,20 +1908,32 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1814
1908
  mergedText: mergedHandoff
1815
1909
  };
1816
1910
  }
1817
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:persistence-routing-checked")) {
1818
- const mergedHandoff = mergeHandoffPersistenceRoutingField(targetText);
1819
- if (!mergedHandoff) {
1820
- return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add persistence routing field" };
1821
- }
1911
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:persistence-routing-checked")) {
1912
+ const mergedHandoff = mergeHandoffPersistenceRoutingField(targetText);
1913
+ if (!mergedHandoff) {
1914
+ return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add persistence routing field" };
1915
+ }
1822
1916
  return {
1823
1917
  ...base,
1824
1918
  action: "merge",
1825
1919
  reason: "insert persistence routing field into State Reconciliation Check (one-time evidence must not drive next-session state)",
1826
- mergedText: mergedHandoff
1827
- };
1828
- }
1829
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && isUpgradeFromOlderTemplate(context)) {
1830
- const lifecycleValue = fieldValueAfterMarker(targetText, "lifecycle-conflicts-resolved");
1920
+ mergedText: mergedHandoff
1921
+ };
1922
+ }
1923
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:recommended-next-step-explicit")) {
1924
+ const mergedHandoff = mergeHandoffRecommendedNextStepDiscipline(targetText);
1925
+ if (!mergedHandoff) {
1926
+ return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add recommended next-step field" };
1927
+ }
1928
+ return {
1929
+ ...base,
1930
+ action: "merge",
1931
+ reason: "insert recommended next-step field and preserve existing next-priority items",
1932
+ mergedText: mergedHandoff
1933
+ };
1934
+ }
1935
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && isUpgradeFromOlderTemplate(context)) {
1936
+ const lifecycleValue = fieldValueAfterMarker(targetText, "lifecycle-conflicts-resolved");
1831
1937
  if (isPlaceholderLifecycleFieldValue(lifecycleValue) && hasSubstantiveHandoffState(targetText)) {
1832
1938
  const mergedHandoff = reclassifyExistingHandoffLifecyclePlaceholder(targetText);
1833
1939
  if (!mergedHandoff) {
@@ -1942,47 +2048,69 @@ function looksLikeExpandedKitBridge(targetRel, text) {
1942
2048
  return false;
1943
2049
  }
1944
2050
 
1945
- function mergeOnboardingScenarioALabel(targetText) {
1946
- let merged = targetText;
1947
- merged = merged.replace(
1948
- /\*\*A\. 寫 \/ 改代碼項目\*\* —— 你有一個(?: project 的 codebase|程式項目)想長期維護/g,
1949
- "**A. 建構系統 / 工具 / 平台 / 網站或應用** —— 你想由 AI 協助建立或長期維護一個可運作的項目"
1950
- );
1951
- merged = merged.replace(
1952
- /### Scenario A\. 寫 \/ 改代碼項目/g,
1953
- "### Scenario A. 建構系統 / 工具 / 平台 / 網站或應用"
1954
- );
1955
- return merged;
1956
- }
1957
-
1958
- function mergeAgentGovernanceBridgeWorkflow(targetText, sourceText) {
1959
- const sourceMatch = sourceText.match(/9\. Governance bridge[\s\S]*?(?=\n## Checks)/);
1960
- const workflowMatch = sourceText.match(/\n## Governance Bridge Workflow[\s\S]*?(?=\n## Checks)/);
1961
- const sourceLoadWhenLine = sourceText.split(/\r?\n/).find((line) => line.startsWith("- User asks to \"治理打通\""));
1962
- const sourceWorkflowIntroLine = sourceText.split(/\r?\n/).find((line) => line.startsWith("Use this workflow when"));
1963
- if (!sourceMatch || !workflowMatch || !targetText.includes("\n## Checks")) return null;
2051
+ function mergeOnboardingScenarioALabel(targetText) {
2052
+ let merged = targetText;
2053
+ merged = merged.replace(
2054
+ /\*\*A\. 寫 \/ 改代碼項目\*\* —— 你有一個(?: project 的 codebase|程式項目)想長期維護/g,
2055
+ "**A. Build systems, tools, platforms, websites, or apps**: the user wants AI help to create or maintain a working project."
2056
+ );
2057
+ merged = merged.replace(
2058
+ /### Scenario A\. 寫 \/ 改代碼項目/g,
2059
+ "### Scenario A. Build systems, tools, platforms, websites, or apps"
2060
+ );
2061
+ merged = merged.replace(
2062
+ /### Scenario A\. 建構系統 \/ 工具 \/ 平台 \/ 網站或應用/g,
2063
+ "### Scenario A. Build systems, tools, platforms, websites, or apps"
2064
+ );
2065
+ return merged;
2066
+ }
1964
2067
 
1965
- let merged = targetText;
1966
- const targetLoadWhenLine = merged.split(/\r?\n/).find((line) => line.startsWith("- User asks to \"治理打通\""));
1967
- if (sourceLoadWhenLine && (!targetLoadWhenLine || !targetLoadWhenLine.includes("接入 Agent Handoff Kit"))) {
1968
- merged = merged.replace(/- User asks to "治理打通"[^\n]*\n/, `${sourceLoadWhenLine}\n`);
1969
- }
1970
- const targetWorkflowIntroLine = merged.match(/^Use this workflow when[^\n]*$/m)?.[0] ?? "";
1971
- if (sourceWorkflowIntroLine && !targetWorkflowIntroLine.includes("掃描未接入 Agent Handoff Kit 的重要文件")) {
1972
- merged = merged.replace(/^Use this workflow when[^\n]*$/m, sourceWorkflowIntroLine);
1973
- }
1974
- if (!merged.includes("Governance bridge is a triggered review")) {
1975
- const rulePrefix = sourceMatch[0].trimEnd();
1976
- merged = merged.replace(/\n## Checks/, `\n${rulePrefix}\n${workflowMatch[0]}\n## Checks`);
1977
- }
1978
- if (!merged.includes("For governance bridge work, confirm the target file")) {
2068
+ function mergeAgentGovernanceBridgeWorkflow(targetText, sourceText) {
2069
+ const sourceRuleLine = sourceText.split(/\r?\n/).find((line) => line.startsWith("9. Governance bridge"));
2070
+ const workflowMatch = sourceText.match(/\n## Governance Bridge Workflow[\s\S]*?(?=\n## Generated Artifact Governance Workflow|\n## Checks)/);
2071
+ const sourceLoadWhenLine = sourceText.split(/\r?\n/).find((line) => line.startsWith("- User asks to bridge governance"));
2072
+ if (!sourceRuleLine || !workflowMatch || !targetText.includes("\n## Checks")) return null;
2073
+
2074
+ let merged = targetText;
2075
+ const targetLoadWhenLine = merged.split(/\r?\n/).find((line) => line.startsWith("- User asks to bridge governance") || line.startsWith("- User asks to \"治理打通\""));
2076
+ if (sourceLoadWhenLine && targetLoadWhenLine && !targetLoadWhenLine.includes("scan for unbridged governance documents")) {
2077
+ merged = merged.replace(/- User asks to (?:bridge governance|"治理打通")[^\n]*\n/, `${sourceLoadWhenLine}\n`);
2078
+ }
2079
+ if (sourceLoadWhenLine && !targetLoadWhenLine && !merged.includes("equivalent Chinese phrases")) {
2080
+ const loadWhenMarker = "- A change affects `AGENTS.md`, `dev/*`, rule packs, installer templates, or durable workflow docs.";
2081
+ if (merged.includes(loadWhenMarker)) {
2082
+ merged = merged.replace(loadWhenMarker, `${loadWhenMarker}\n${sourceLoadWhenLine}`);
2083
+ }
2084
+ }
2085
+ if (/^9\. Governance bridge/m.test(merged)) {
2086
+ merged = merged.replace(/^9\. Governance bridge[^\n]*$/m, sourceRuleLine);
2087
+ } else if (!merged.includes(sourceRuleLine)) {
2088
+ merged = merged.replace(/\n## Governance Bridge Workflow|\n## Checks/, `\n${sourceRuleLine}$&`);
2089
+ }
2090
+ merged = removeAllSectionsByHeading(merged, "## Governance Bridge Workflow");
2091
+ merged = merged.replace(/\n## Checks/, `${workflowMatch[0]}\n## Checks`);
2092
+ if (!merged.includes("Governance bridge is a triggered review")) {
2093
+ return null;
2094
+ }
2095
+ if (!merged.includes("For governance bridge work, confirm the target file")) {
1979
2096
  merged = merged.replace(
1980
2097
  "- 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.",
1981
2098
  "- 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."
1982
2099
  );
1983
2100
  }
1984
- return merged;
1985
- }
2101
+ return merged;
2102
+ }
2103
+
2104
+ function removeAllSectionsByHeading(text, heading) {
2105
+ let result = text;
2106
+ while (true) {
2107
+ const start = result.indexOf(`\n${heading}`);
2108
+ if (start < 0) return result;
2109
+ const next = result.indexOf("\n## ", start + heading.length + 1);
2110
+ if (next < 0) return result.slice(0, start).trimEnd() + "\n";
2111
+ result = result.slice(0, start) + result.slice(next);
2112
+ }
2113
+ }
1986
2114
 
1987
2115
  function hasTrustedOnboardingScenarioLibrary(text) {
1988
2116
  const bounds = textSectionBounds(text, "## Application Scenario Library", "## Cross-reference to guide.html");
@@ -2095,16 +2223,15 @@ function safetyAnchorPlacement(snippet, text) {
2095
2223
  return safetyAnchorHasTrustedRuleShape(text, snippet);
2096
2224
  }
2097
2225
 
2098
- function projectDecisionsAnchorPlacement(snippet, text) {
2099
- const preamble = [
2100
- "Project Decisions Log",
2101
- "warm 資料層",
2102
- "AI 開工",
2103
- "不需要讀",
2104
- "AI 在收工時自動 update",
2105
- "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.",
2106
- "This file does not store raw build / upload / QC evidence"
2107
- ];
2226
+ function projectDecisionsAnchorPlacement(snippet, text) {
2227
+ const preamble = [
2228
+ "Project Decisions Log",
2229
+ "warm narrative layer",
2230
+ "do not need to read this file at startup",
2231
+ "The AI updates it during closeout",
2232
+ "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.",
2233
+ "This file does not store raw build / upload / QC evidence"
2234
+ ];
2108
2235
  if (preamble.includes(snippet)) return snippetAppearsBeforeHeading(text, snippet, "## Evolution Timeline");
2109
2236
  return true;
2110
2237
  }
@@ -2120,13 +2247,13 @@ function onboardingAnchorPlacement(snippet, text) {
2120
2247
  }
2121
2248
 
2122
2249
  function integrationsAnchorPlacement(snippet, text) {
2123
- if (snippet === "機密分離原則" || snippet === "External Tool Usage Verification Gate" || snippet === "do not invent" || snippet === "input schema" || snippet === "official documentation" || snippet === "Source-of-truth Architecture" || snippet === "Cross-session Lifecycle") {
2250
+ if (snippet === "Credential Separation Principle" || snippet === "External Tool Usage Verification Gate" || snippet === "External Tool Resource Lifecycle" || snippet === "do not invent" || snippet === "input schema" || snippet === "official documentation" || snippet === "Source-of-truth Architecture" || snippet === "Cross-session Lifecycle" || snippet === "Runtime-Controlled Tool Operation Variants" || snippet === "Tool Operation References" || snippet === "Do not guess Chrome, Playwright, or DevTools commands") {
2124
2251
  return snippetAppearsBetweenHeadings(text, snippet, "## Discipline", "## Rules");
2125
2252
  }
2126
2253
  if (snippet === "Connector-first default") {
2127
2254
  return snippetAppearsBetweenHeadings(text, snippet, "## Rules", "## Checks");
2128
2255
  }
2129
- if (snippet === "Anti-pattern") return text.includes("## Anti-pattern(不要做的事)");
2256
+ if (snippet === "Anti-pattern") return text.includes("## Anti-patterns") || text.includes("## Anti-pattern(不要做的事)");
2130
2257
  return true;
2131
2258
  }
2132
2259
 
@@ -2185,14 +2312,22 @@ const semanticAnchorRepairStrategies = {
2185
2312
  mergedText: mergedDecisions
2186
2313
  } : null;
2187
2314
  },
2188
- "dev/rules/safety.md": (targetText, sourceText, missing) => {
2189
- const mergedSafety = mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing);
2190
- return mergedSafety ? {
2191
- action: "merge",
2192
- reason: "restore safety pack high-risk rules in ## Rules section",
2193
- mergedText: mergedSafety
2194
- } : null;
2195
- },
2315
+ "dev/rules/safety.md": (targetText, sourceText, missing) => {
2316
+ const mergedSafety = mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing);
2317
+ return mergedSafety ? {
2318
+ action: "merge",
2319
+ reason: "restore safety pack high-risk rules in ## Rules section",
2320
+ mergedText: mergedSafety
2321
+ } : null;
2322
+ },
2323
+ "dev/rules/communication.md": (targetText, sourceText, missing) => {
2324
+ const mergedCommunication = mergeCommunicationNextStepDiscipline(targetText, sourceText, missing);
2325
+ return mergedCommunication ? {
2326
+ action: "merge",
2327
+ reason: "insert communication pack recommended next-step discipline without replacing local prose",
2328
+ mergedText: mergedCommunication
2329
+ } : null;
2330
+ },
2196
2331
  "dev/rules/integrations.md": (targetText, sourceText, missing) => {
2197
2332
  const mergedIntegrations = mergeIntegrationsSectionsByMissingAnchors(targetText, sourceText, missing);
2198
2333
  return mergedIntegrations ? {
@@ -2203,7 +2338,7 @@ const semanticAnchorRepairStrategies = {
2203
2338
  }
2204
2339
  };
2205
2340
 
2206
- function mergeMissingRequiredAnchorsSemantically(targetRel, targetText, sourceText) {
2341
+ function mergeMissingRequiredAnchorsSemantically(targetRel, targetText, sourceText) {
2207
2342
  const missing = missingRequiredAnchorSnippets(targetRel, targetText);
2208
2343
  if (missing.length === 0) return null;
2209
2344
 
@@ -2263,8 +2398,84 @@ function mergeProjectIndexTemplateVersionRow(targetText, sourceText) {
2263
2398
  return lines.join("\n");
2264
2399
  }
2265
2400
 
2401
+ function mergeCommunicationNextStepDiscipline(targetText, sourceText, missing) {
2402
+ if (!missing.some((snippet) => snippet === "recommended next step" || snippet === "state it directly with a short reason" || snippet === "do not turn an already-made technical judgment into an open question")) return null;
2403
+ if (!targetText.includes("# Communication Pack")) return null;
2404
+ if (countText(targetText, "## Rules") !== 1 || countText(targetText, "## Checks") !== 1 || countText(targetText, "## Closeout") !== 1) return null;
2405
+
2406
+ const sourceRule = sourceText.split(/\r?\n/).find((line) => line.includes("Give a clear recommended next step"));
2407
+ const sourceCheck = sourceText.split(/\r?\n/).find((line) => line.includes("Confirm user-facing next-step wording names the recommended action"));
2408
+ if (!sourceRule || !sourceCheck) return null;
2409
+
2410
+ let merged = targetText;
2411
+ if (!merged.includes("Give a clear recommended next step")) {
2412
+ const rulesBounds = textSectionBounds(merged, "## Rules", "## Checks");
2413
+ if (!rulesBounds) return null;
2414
+ const rulesBlock = merged.slice(rulesBounds.start, rulesBounds.end);
2415
+ if (/^6\. /m.test(rulesBlock)) return null;
2416
+ merged = `${merged.slice(0, rulesBounds.end).trimEnd()}\n${sourceRule}\n\n${merged.slice(rulesBounds.end).trimStart()}`;
2417
+ }
2418
+
2419
+ if (!merged.includes("Confirm user-facing next-step wording names the recommended action")) {
2420
+ const checksBounds = textSectionBounds(merged, "## Checks", "## Closeout");
2421
+ if (!checksBounds) return null;
2422
+ merged = `${merged.slice(0, checksBounds.end).trimEnd()}\n${sourceCheck}\n\n${merged.slice(checksBounds.end).trimStart()}`;
2423
+ }
2424
+
2425
+ return merged === targetText ? null : merged;
2426
+ }
2427
+
2266
2428
  function mergeProjectIndexCredentialReferences(targetText) {
2267
2429
  return targetText
2430
+ .replace(
2431
+ /`via` column 紀律:每行 External Sources 必引用 `## Installed Integrations`[^\r\n]*/,
2432
+ "`via` column discipline: every External Sources row must reference an entry name under `## Installed Integrations`, such as `Notion Connector` or `Google Drive Connector`, so the access path is explicit. Sources without a declared integration use `manual paste`. Doctor and release QA enforce cross-section consistency."
2433
+ )
2434
+ .replace(
2435
+ /⚠️ \*\*機密分離原則\*\*:本 section 只記錄[^\r\n]*/,
2436
+ "**Credential Separation Principle**: this section records only project usage and public reference coordinates such as Notion database names, URLs, or folder paths. It must never record API keys, OAuth tokens, or credential values. Credentials belong in AI runtime secure storage, OS credential stores, tool configuration, or user-managed secret stores. If an environment variable is used, record only the variable name, never the value. Before writing this section, self-check that no credential value is being persisted. Doctor scans this section, `SESSION_HANDOFF`, and `SESSION_LOG` for common credential prefixes such as `sk-`, `ntn_`, `ya29.`, `xoxp-`, `ghp_`, `sl.`, `AKIA`, and `AIza`."
2437
+ )
2438
+ .replace(
2439
+ /用途:新 AI session 開工讀本 section 知道[^\r\n]*/,
2440
+ "Purpose: a new AI session reads this section to understand declared external-tool capabilities and their project roles. Declarations persist across sessions. Every entry must include `Declared` and `Last Verified` fields so stale capability assumptions can be detected."
2441
+ )
2442
+ .replace("### Connectors(Anthropic 官方 vetted)", "### Connectors")
2443
+ .replace("### MCPs(community / custom)", "### MCPs")
2444
+ .replace("### Plugins(Claude Code plugin bundle)", "### Plugins")
2445
+ .replace("### Skills(SKILL.md instruction set)", "### Skills")
2446
+ .replace("### Source-of-truth Architecture(多層持久化組合)", "### Source-of-truth Architecture")
2447
+ .replace(
2448
+ /當項目用多個整合構成 source-of-truth 架構[^\r\n]*/,
2449
+ "When a project uses several integrations as a source-of-truth system, for example Notion index + local primary sources + Google Drive reference mirror, this table records each layer's role so agents do not cross write boundaries."
2450
+ )
2451
+ .replace(
2452
+ "| TBD | TBD(譬如 DB Index 記真源 path / 持久化參考檔儲存) | read / read+write | TBD(譬如 DB 名 + URL / folder path) | TBD(譬如 `AI tool secure storage` / `OS credential store`) | TBD | TBD |",
2453
+ "| TBD | TBD, for example an index of source paths or persistent reference storage | read / read+write | TBD, for example database name + URL or folder path | TBD, for example `AI tool secure storage` / `OS credential store` | TBD | TBD |"
2454
+ )
2455
+ .replace(
2456
+ "| TBD | TBD(譬如 GitHub repo URL) | TBD | TBD(譬如 `tool config + env var name only` / `user-managed secret store`) | TBD | TBD |",
2457
+ "| TBD | TBD, for example GitHub repository URL | TBD | TBD, for example `tool config + env var name only` / `user-managed secret store` | TBD | TBD |"
2458
+ )
2459
+ .replace(
2460
+ "| TBD | TBD(譬如 plugin bundle / user-level install) | TBD | TBD |",
2461
+ "| TBD | TBD, for example plugin bundle or user-level install | TBD | TBD |"
2462
+ )
2463
+ .replace(
2464
+ "| 真源(source of truth) | TBD(譬如 本機 `~/project/reference/`) | 原始可審計 reference 內容 | 用戶手動置入;AI 不直接寫入 |",
2465
+ "| Source of truth | TBD, for example local `~/project/reference/` | Original auditable reference content | User-controlled placement; agent does not write directly unless explicitly authorized |"
2466
+ )
2467
+ .replace(
2468
+ "| Index | TBD(譬如 Notion DB「Project Index」) | 登記每份真源檔 metadata + 摘要 + tag | AI 經 Connector 直接讀寫 |",
2469
+ "| Index | TBD, for example Notion database `Project Index` | Metadata, summaries, and tags for each source file | Agent may read/write through a verified Connector |"
2470
+ )
2471
+ .replace(
2472
+ "| 持久化參考檔(mirror) | TBD(譬如 Drive folder「Project Reference/」) | 防本機 disk failure / 跨裝置 access | 用戶手動同步;AI 唔自動 push |",
2473
+ "| Persistent mirror | TBD, for example Drive folder `Project Reference/` | Backup or cross-device reference mirror | User-controlled sync by default; agent does not push automatically |"
2474
+ )
2475
+ .replace(
2476
+ "| Working draft | TBD(譬如 本機 `~/project/output/`) | AI 寫 task output | AI 直接 read + write 本機 |",
2477
+ "| Working draft | TBD, for example local `~/project/output/` | Agent task output | Agent may read and write local files under normal safety rules |"
2478
+ )
2268
2479
  .replace(
2269
2480
  "Credential 應由 AI 工具自身 secure storage 管理(譬如 Claude Desktop Extensions 嘅 OS Keychain / Claude Code MCP config)。",
2270
2481
  "Credential 應由 AI 工具自身 secure storage / OS credential store / tool config / user-managed secret store 管理;若使用 env,只可記錄 env var name,不可讀取、貼出或保存 value。"
@@ -2273,6 +2484,18 @@ function mergeProjectIndexCredentialReferences(targetText) {
2273
2484
  "Credential Location",
2274
2485
  "Credential Reference(no value)"
2275
2486
  )
2487
+ .replaceAll(
2488
+ "Credential Reference(no value)",
2489
+ "Credential Reference (no value)"
2490
+ )
2491
+ .replaceAll(
2492
+ "Bundle Content(Skills + MCP + hooks)",
2493
+ "Bundle Content (Skills + MCP + hooks)"
2494
+ )
2495
+ .replaceAll(
2496
+ "Surface(具體 instance)",
2497
+ "Surface (specific instance)"
2498
+ )
2276
2499
  .replace(
2277
2500
  "`Claude Desktop Extensions`",
2278
2501
  "`AI tool secure storage` / `OS credential store`"
@@ -2296,20 +2519,52 @@ function mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing) {
2296
2519
 
2297
2520
  let changed = false;
2298
2521
  const remainingMissing = [...missing];
2299
- if (remainingMissing.includes("parser failure") && !targetText.includes("parser failure")) {
2300
- const parserFailureRule = sourceRuleLines.find((line) => line.includes("parser failure"));
2301
- if (!parserFailureRule || !parserFailureRule.startsWith("13. ")) return null;
2302
- targetLines.splice(targetRuleEnd, 0, parserFailureRule);
2303
- changed = true;
2304
- remainingMissing.splice(remainingMissing.indexOf("parser failure"), 1);
2305
- }
2306
-
2307
- for (const snippet of remainingMissing) {
2308
- const sourceLine = sourceRuleLines.find((line) => line.includes(snippet));
2309
- if (!sourceLine) return null;
2310
- const ruleNumber = sourceLine.match(/^(\d+)\. /)?.[1];
2311
- if (!ruleNumber) return null;
2312
- const targetIndex = targetLines.findIndex((line, index) => index >= targetRuleStart && index < targetRuleEnd && line.startsWith(`${ruleNumber}. `));
2522
+ const appendableRules = [
2523
+ { snippet: "parser failure", number: "13" },
2524
+ { snippet: "Process termination and cache cleanup boundary", number: "14" },
2525
+ { snippet: "task-owned or agent-managed", number: "14" },
2526
+ { snippet: "other-agent-owned", number: "14" }
2527
+ ];
2528
+ for (const { snippet, number } of appendableRules) {
2529
+ if (!remainingMissing.includes(snippet) || targetText.includes(snippet)) continue;
2530
+ const sourceRule = sourceRuleLines.find((line) => line.includes(snippet));
2531
+ if (!sourceRule || !sourceRule.startsWith(`${number}. `)) return null;
2532
+ if (!targetLines.some((line, index) => index >= targetRuleStart && line.startsWith(`${number}. `))) {
2533
+ targetLines.splice(targetRuleEnd, 0, sourceRule);
2534
+ changed = true;
2535
+ remainingMissing.splice(remainingMissing.indexOf(snippet), 1);
2536
+ continue;
2537
+ }
2538
+ // If the numbered rule already exists, leave it for the same-shape replacement path below.
2539
+ }
2540
+
2541
+ if (remainingMissing.includes("parser failure") && !targetText.includes("parser failure")) {
2542
+ const parserFailureRule = sourceRuleLines.find((line) => line.includes("parser failure"));
2543
+ if (!parserFailureRule || !parserFailureRule.startsWith("13. ")) return null;
2544
+ targetLines.splice(targetRuleEnd, 0, parserFailureRule);
2545
+ changed = true;
2546
+ remainingMissing.splice(remainingMissing.indexOf("parser failure"), 1);
2547
+ }
2548
+
2549
+ const rule14Snippets = ["browser profiles", "desktop app sessions", "shared tool servers", "notebook kernels"];
2550
+ if (remainingMissing.some((snippet) => rule14Snippets.includes(snippet))) {
2551
+ const sourceRule14 = sourceRuleLines.find((line) => line.startsWith("14. ") && line.includes("Process termination and cache cleanup boundary"));
2552
+ const targetRule14Index = targetLines.findIndex((line, index) => index >= targetRuleStart && line.startsWith("14. "));
2553
+ if (!sourceRule14 || targetRule14Index < 0) return null;
2554
+ targetLines[targetRule14Index] = sourceRule14;
2555
+ changed = true;
2556
+ for (const snippet of rule14Snippets) {
2557
+ const index = remainingMissing.indexOf(snippet);
2558
+ if (index >= 0) remainingMissing.splice(index, 1);
2559
+ }
2560
+ }
2561
+
2562
+ for (const snippet of remainingMissing) {
2563
+ const sourceLine = sourceRuleLines.find((line) => line.includes(snippet));
2564
+ if (!sourceLine) return null;
2565
+ const ruleNumber = sourceLine.match(/^(\d+)\. /)?.[1];
2566
+ if (!ruleNumber) return null;
2567
+ const targetIndex = targetLines.findIndex((line, index) => index >= targetRuleStart && line.startsWith(`${ruleNumber}. `));
2313
2568
  if (targetIndex < 0) return null;
2314
2569
  if (!sameRuleShape(targetLines[targetIndex], sourceLine, snippet)) return null;
2315
2570
  targetLines[targetIndex] = sourceLine;
@@ -2323,11 +2578,11 @@ function mergeIntegrationsSectionsByMissingAnchors(targetText, sourceText, missi
2323
2578
  let merged = targetText;
2324
2579
  let changed = false;
2325
2580
 
2326
- if (missing.some((snippet) => snippet === "機密分離原則")) {
2581
+ if (missing.some((snippet) => snippet === "Credential Separation Principle" || snippet === "機密分離原則")) {
2327
2582
  const withCredential = replaceSectionByHeadingWithinBounds(
2328
2583
  merged,
2329
2584
  sourceText,
2330
- /^### 1\. (機密分離原則|credential-separation anchor removed from this stale local copy)/m,
2585
+ /^### 1\. (Credential Separation Principle|機密分離原則|credential-separation anchor removed from this stale local copy)/m,
2331
2586
  /^### 2\. /m,
2332
2587
  "## Discipline",
2333
2588
  "## Rules"
@@ -2337,7 +2592,7 @@ function mergeIntegrationsSectionsByMissingAnchors(targetText, sourceText, missi
2337
2592
  changed = true;
2338
2593
  }
2339
2594
 
2340
- if (missing.some((snippet) => snippet === "External Tool Usage Verification Gate" || snippet === "do not invent" || snippet === "input schema" || snippet === "official documentation")) {
2595
+ if (missing.some((snippet) => snippet === "External Tool Usage Verification Gate" || snippet === "External Tool Resource Lifecycle" || snippet === "other-agent-owned" || snippet === "do not invent" || snippet === "input schema" || snippet === "official documentation" || snippet === "Runtime-Controlled Tool Operation Variants" || snippet === "Tool Operation References" || snippet === "Do not guess Chrome, Playwright, or DevTools commands")) {
2341
2596
  const withVerificationGate = mergeIntegrationsVerificationGateSection(merged, sourceText);
2342
2597
  if (!withVerificationGate) return null;
2343
2598
  merged = withVerificationGate;
@@ -2373,10 +2628,47 @@ function mergeIntegrationsVerificationGateSection(targetText, sourceText) {
2373
2628
  return `${targetText.slice(0, targetBounds.start + currentFourTypesHeading.index)}${sourceSection.text}${targetText.slice(targetBounds.start + currentFourTypesHeading.index)}`;
2374
2629
  }
2375
2630
 
2631
+ const englishTypeHeading = /^### 3\. Integration Type Discipline/m.exec(boundedTarget);
2632
+ if (englishTypeHeading) {
2633
+ return `${targetText.slice(0, targetBounds.start + englishTypeHeading.index)}${sourceSection.text}${targetText.slice(targetBounds.start + englishTypeHeading.index)}`;
2634
+ }
2635
+
2376
2636
  return null;
2377
2637
  }
2378
-
2379
- function hasTrustedSafetyPackShape(text) {
2638
+
2639
+ function isLegacyChineseIntegrationsPack(text) {
2640
+ return text.includes("# Integrations Pack")
2641
+ && countText(text, "## Scope") === 1
2642
+ && countText(text, "## Load When") === 1
2643
+ && countText(text, "## Discipline") === 1
2644
+ && countText(text, "## Rules") === 1
2645
+ && countText(text, "## Checks") === 1
2646
+ && countText(text, "## Closeout") === 1
2647
+ && countText(text, "## Cross-reference") === 1
2648
+ && (text.includes("機密分離原則") || text.includes("四類整合"))
2649
+ && !text.includes("## Local Discipline")
2650
+ && !text.includes("Duplicate ambiguous local heading")
2651
+ && countText(text, "四類整合") <= 2;
2652
+ }
2653
+
2654
+ function isLegacyChineseOnboardingPack(text) {
2655
+ return text.includes("# Onboarding Pack")
2656
+ && countText(text, "## Scope") === 1
2657
+ && countText(text, "## Load When") === 1
2658
+ && countText(text, "## Discipline") === 1
2659
+ && countText(text, "## Application Scenario Library") === 1
2660
+ && countText(text, "## Cross-reference to guide.html") === 1
2661
+ && countText(text, "## Tone Discipline") === 1
2662
+ && countText(text, "## Closeout") === 1
2663
+ && text.includes("### Scenario A.")
2664
+ && text.includes("### Scenario E.")
2665
+ && (text.includes("明確 onboarding signal keywords") || text.includes("Scenario F. 審視已裝外部工具") || text.includes("Anti-pattern(不要做的事)"))
2666
+ && !text.includes("### Local Scenario A")
2667
+ && !text.includes("structurally ambiguous onboarding")
2668
+ && !text.includes("## Local Discipline");
2669
+ }
2670
+
2671
+ function hasTrustedSafetyPackShape(text) {
2380
2672
  return text.includes("# Safety Pack")
2381
2673
  && text.includes("## Scope")
2382
2674
  && Boolean(sectionBounds(text, "## Rules", "## Checks"))
@@ -2502,10 +2794,10 @@ function mergeHandoffLifecycleField(targetText) {
2502
2794
  const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
2503
2795
  if (!targetText.includes(openingMarker)) return null;
2504
2796
 
2505
- 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";
2506
- let merged = targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
2507
- return ensureHandoffStateReconciliationRules(ensureHandoffPersistenceRoutingField(merged));
2508
- }
2797
+ 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";
2798
+ let merged = targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
2799
+ return ensureCurrentHandoffMigrationFields(merged);
2800
+ }
2509
2801
 
2510
2802
  function reclassifyExistingHandoffLifecyclePlaceholder(targetText) {
2511
2803
  const marker = "ack:field:lifecycle-conflicts-resolved";
@@ -2525,19 +2817,57 @@ function reclassifyExistingHandoffLifecyclePlaceholder(targetText) {
2525
2817
  return ensureHandoffStateReconciliationRules(lines.join("\n"));
2526
2818
  }
2527
2819
 
2528
- function mergeHandoffPersistenceRoutingField(targetText) {
2529
- const merged = ensureHandoffPersistenceRoutingField(targetText);
2530
- if (!merged || merged === targetText) return null;
2531
- return ensureHandoffStateReconciliationRules(merged);
2532
- }
2820
+ function mergeHandoffPersistenceRoutingField(targetText) {
2821
+ const merged = ensureCurrentHandoffMigrationFields(targetText);
2822
+ if (!merged || merged === targetText) return null;
2823
+ return merged;
2824
+ }
2825
+
2826
+ function mergeHandoffRecommendedNextStepDiscipline(targetText) {
2827
+ const merged = ensureCurrentHandoffMigrationFields(targetText);
2828
+ if (!merged || merged === targetText) return null;
2829
+ return merged;
2830
+ }
2831
+
2832
+ function ensureCurrentHandoffMigrationFields(targetText) {
2833
+ let merged = ensureHandoffPersistenceRoutingField(targetText);
2834
+ if (!merged) return null;
2835
+ merged = ensureHandoffRecommendedNextStepField(merged);
2836
+ if (!merged) return null;
2837
+ merged = ensureHandoffRecommendedNextPriorityLine(merged);
2838
+ if (!merged) return null;
2839
+ return ensureHandoffStateReconciliationRules(merged);
2840
+ }
2533
2841
 
2534
- function ensureHandoffPersistenceRoutingField(targetText) {
2535
- if (targetText.includes("ack:field:persistence-routing-checked")) return targetText;
2536
- const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
2537
- if (!targetText.includes(openingMarker)) return null;
2538
- 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";
2539
- return targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
2540
- }
2842
+ function ensureHandoffPersistenceRoutingField(targetText) {
2843
+ if (targetText.includes("ack:field:persistence-routing-checked")) return targetText;
2844
+ const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
2845
+ if (!targetText.includes(openingMarker)) return null;
2846
+ 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";
2847
+ return targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
2848
+ }
2849
+
2850
+ function ensureHandoffRecommendedNextStepField(targetText) {
2851
+ if (targetText.includes("ack:field:recommended-next-step-explicit")) return targetText;
2852
+ const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
2853
+ if (!targetText.includes(openingMarker)) return null;
2854
+ const fieldBlock = "<!-- ack:field:recommended-next-step-explicit -->\n- Recommended next step is explicit and reasoned: Reclassified at upgrade: field added by template migration; confirm at next closeout.\n";
2855
+ return targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
2856
+ }
2857
+
2858
+ function ensureHandoffRecommendedNextPriorityLine(targetText) {
2859
+ if (/^Recommended next step:/m.test(targetText)) return targetText;
2860
+ const marker = "<!-- ack:section:next-priorities -->";
2861
+ const markerIndex = targetText.indexOf(marker);
2862
+ if (markerIndex < 0) return null;
2863
+ const afterMarker = targetText.slice(markerIndex);
2864
+ const headingMatch = /^##\s+.+$/m.exec(afterMarker);
2865
+ if (!headingMatch) return null;
2866
+ const headingIndex = markerIndex + headingMatch.index;
2867
+ const headingEnd = targetText.indexOf("\n", headingIndex);
2868
+ if (headingEnd < 0) return null;
2869
+ return `${targetText.slice(0, headingEnd + 1)}\nRecommended next step: Reclassified at upgrade — reason: confirm at next closeout.\n${targetText.slice(headingEnd + 1)}`;
2870
+ }
2541
2871
 
2542
2872
  function ensureHandoffStateReconciliationRules(targetText) {
2543
2873
  if (!targetText) return null;
@@ -2545,9 +2875,12 @@ function ensureHandoffStateReconciliationRules(targetText) {
2545
2875
  if (!targetText.includes("Lifecycle consistency rule: compare `Completed This Session`")) {
2546
2876
  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.");
2547
2877
  }
2548
- if (!targetText.includes("Persistence routing rule: one-time delivery instructions")) {
2549
- 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.");
2550
- }
2878
+ if (!targetText.includes("Persistence routing rule: one-time delivery instructions")) {
2879
+ 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.");
2880
+ }
2881
+ if (!targetText.includes("Recommended next-step rule:")) {
2882
+ rules.push("Recommended next-step rule: `Next Priorities` must name the single recommended next action and a short reason before listing additional options, unless the next action is blocked or genuinely requires a user decision.");
2883
+ }
2551
2884
  if (rules.length === 0) return targetText;
2552
2885
  const ruleBlock = `${rules.join("\n")}\n\n`;
2553
2886
  const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
@@ -2690,28 +3023,24 @@ function mergeRulePacksRows(targetText, sourceText) {
2690
3023
 
2691
3024
  let tableEnd = tableStart;
2692
3025
  while (tableEnd < lines.length && lines[tableEnd].startsWith("|")) tableEnd++;
2693
-
2694
- const before = lines.slice(0, tableStart);
2695
- const table = lines.slice(tableStart, tableEnd);
2696
- const after = lines.slice(tableEnd);
2697
- const governanceBridgeSourceRow = sourceRows.find((row) => row.includes("Governance bridge / 治理打通"));
2698
- if (
2699
- governanceBridgeSourceRow
2700
- && targetText.includes("Governance bridge / 治理打通")
2701
- && (!targetText.includes("接入 Agent Handoff Kit") || !targetText.includes("掃描未接入 Agent Handoff Kit 的重要文件"))
2702
- ) {
2703
- const replaced = lines.map((line) => (
2704
- line.includes("Governance bridge / 治理打通") ? governanceBridgeSourceRow : line
2705
- ));
2706
- return replaced.join("\n");
2707
- }
2708
- const sourceRowsToApply = sourceRows.filter((row) => {
2709
- if (row.includes("dev/rules/onboarding.md")) return !targetText.includes("First-time user signals");
2710
- if (row.includes("dev/rules/integrations.md")) return !targetText.includes("External tool integrations");
2711
- if (row.includes("Governance bridge / 治理打通")) return !targetText.includes("Governance bridge / 治理打通");
2712
- return false;
2713
- });
2714
- if (sourceRowsToApply.length === 0) return targetText;
3026
+
3027
+ const before = lines.slice(0, tableStart);
3028
+ const governanceBridgeSourceRow = sourceRows.find((row) => row.includes("Governance bridge / bridge governance"));
3029
+ const hasAnyGovernanceRow = targetText.includes("Governance bridge / 治理打通") || targetText.includes("Governance bridge / bridge governance");
3030
+ const table = lines.slice(tableStart, tableEnd).map((line) => (
3031
+ governanceBridgeSourceRow && (line.includes("Governance bridge / 治理打通") || line.includes("Governance bridge / bridge governance"))
3032
+ ? governanceBridgeSourceRow
3033
+ : line
3034
+ ));
3035
+ const after = lines.slice(tableEnd);
3036
+ const sourceRowsToApply = sourceRows.filter((row) => {
3037
+ if (row.includes("dev/rules/onboarding.md")) return !targetText.includes("First-time user signals");
3038
+ if (row.includes("External tool resource pressure")) return !targetText.includes("External tool resource pressure");
3039
+ if (row.includes("dev/rules/integrations.md")) return !targetText.includes("External tool integrations");
3040
+ if (row.includes("Governance bridge / bridge governance")) return !hasAnyGovernanceRow;
3041
+ return false;
3042
+ });
3043
+ if (sourceRowsToApply.length === 0 && table.join("\n") === lines.slice(tableStart, tableEnd).join("\n")) return targetText;
2715
3044
 
2716
3045
  const merged = [
2717
3046
  ...before,