@adamchanadam/agent-handoff-kit 0.3.20 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Agent Handoff Kit
2
2
 
3
- 狀態:目前版本為 `v0.3.20`,已正式發佈。這是早期可用版本,仍在持續完善中。
3
+ 狀態:目前版本為 `v0.3.22`。這是早期可用版本,仍在持續完善中。
4
4
 
5
5
  ![Agent Handoff Kit 主視覺](https://raw.githubusercontent.com/Adamchanadam/agent-handoff-kit/main/images/agent-handoff-kit-main-visual2.png)
6
6
 
@@ -188,9 +188,9 @@ dev/rules/*.md
188
188
  | `GEMINI.md` | 讓 Google Antigravity CLI、Gemini CLI 遷移期或相容入口工具找到同一套入口。Antigravity CLI 會讀 `AGENTS.md` 與 `GEMINI.md`,所以此檔只做橋接,不另寫一套規則。 |
189
189
  | `START_NEXT_SESSION_PROMPT.txt` | 下一次開工時由 AI 讀取的提示副本;初次安裝時放新手引導,收工後由交接文件自動產生。 |
190
190
  | `dev/SESSION_HANDOFF.md` | 保存目前狀態、下一步、風險、驗收結果與下一次開工文字。 |
191
- | `dev/SESSION_LOG.md` | 保存近期實際做過的事與檢查結果。長期使用後舊條目會自動整理入封存資料夾,主檔保持簡短。日常使用不需要打開本檔,做審計或追溯時才看。 |
191
+ | `dev/SESSION_LOG.md` | 保存近期實際做過的事與檢查結果。每次收工會先做維護觸發檢查;長期使用後,命中條件時舊條目會整理入封存資料夾,主檔保持簡短。日常使用不需要打開本檔,做審計或追溯時才看。 |
192
192
  | `dev/PROJECT_INDEX.md` | 記錄專案檔案、必讀資料、外部來源與常用檢查。 |
193
- | `dev/PROJECT_DECISIONS.md` | 保存項目的長期演進、決策、架構取捨與學習觀察。AI 在每次收工時自動維護,日常開工不需要讀。當你問「之前為何這樣做」時,AI 會自己從這裡找答案。 |
193
+ | `dev/PROJECT_DECISIONS.md` | 保存項目的長期演進、決策、架構取捨與學習觀察。AI 在每次收工時檢查是否需要維護,重大決策可即時寫入;日常開工不需要讀。當你問「之前為何這樣做」時,AI 會自己從這裡找答案。 |
194
194
  | `dev/DOC_SYNC_REGISTRY.md` | 記錄哪些文件改動後需要同步。 |
195
195
  | `dev/RULE_PACKS.md` | 告訴 AI 不同任務應讀哪些工作規則。 |
196
196
  | `dev/rules/*.md` | 按任務載入的工作規則,共十份:安全、寫代碼、寫作、研究、AI 治理、發佈、知識整理、溝通、新手引導、外部工具治理。 |
@@ -199,11 +199,12 @@ dev/rules/*.md
199
199
 
200
200
  ## SESSION_LOG 的自動整理機制
201
201
 
202
- 長期使用後,`dev/SESSION_LOG.md` 不會無止境膨脹。每次你講「收工」,AI 會自動整理:
202
+ 長期使用後,`dev/SESSION_LOG.md` 不會無止境膨脹。每次你講「收工」,AI 會先做一次很短的維護觸發檢查;命中條件時才完整整理:
203
203
 
204
204
  - 最新三條對話紀錄保留完整內容,作為意外時的後備。
205
- - 之後的條目,如核心內容已被交接文件吸收,會自動縮成一行短索引(日期 + 標題 + 對應資料來源)。
206
- - 累積到第十一條開始,會自動封存到 `dev/SESSION_LOG_archive/` 資料夾;主檔末尾留一份封存索引,方便日後追溯。
205
+ - 之後的條目,如核心內容已被交接文件吸收,會在需要整理時縮成一行短索引(日期 + 標題 + 對應資料來源)。
206
+ - 累積到第十一條開始,會封存到 `dev/SESSION_LOG_archive/` 資料夾;主檔末尾留一份封存索引,方便日後追溯。
207
+ - 即使沒有明顯觸發,AI 也會每十次收工做一次完整維護兜底,避免長期使用後慢慢漏記。
207
208
 
208
209
  接力責任由 `dev/SESSION_HANDOFF.md` 承擔;`dev/SESSION_LOG.md` 主要用來日後追溯。**新對話開工不需要讀完整紀錄**,只需要讀 `AGENTS.md`、`dev/SESSION_HANDOFF.md` 和索引文件,就足夠接力。
209
210
 
@@ -211,7 +212,7 @@ dev/rules/*.md
211
212
 
212
213
  ## 項目決策日誌
213
214
 
214
- `dev/PROJECT_DECISIONS.md` 保存項目的長期演進、決策、架構取捨與學習觀察。AI 在每次收工時自動維護,日常開工不需要讀本檔;當你問「之前為何這樣做」時,AI 會自己從這裡找答案。
215
+ `dev/PROJECT_DECISIONS.md` 保存項目的長期演進、決策、架構取捨與學習觀察。AI 每次收工都會檢查是否需要維護;遇到重大決策、方向轉變、架構取捨或重複出現的模式時才寫入,並且每十次收工做一次完整兜底。日常開工不需要讀本檔;當你問「之前為何這樣做」時,AI 會自己從這裡找答案。
215
216
 
216
217
  短期單一任務的項目,本檔幾乎保持空白,你不需要維護。長期持續演進的項目,AI 會自動累積以下四類紀錄:
217
218
 
@@ -282,7 +283,7 @@ Agent Handoff Kit 可與 [Adam-AI-Instructions](https://github.com/prompt-templa
282
283
 
283
284
  ## 目前限制
284
285
 
285
- - 目前版本為 `v0.3.20`,npm registry `latest` 已對齊此版本。
286
+ - 目前版本為 `v0.3.22`;正式安裝請以 npm registry `latest` 顯示為準。
286
287
  - 這是早期可用版本,仍在持續完善中。
287
288
  - 升級合併屬窄範圍策略,不是完整的複雜合併工具。
288
289
  - `doctor` 能檢查結構,不能代替 AI 對專案內容的理解。
@@ -106,12 +106,13 @@ const requiredAnchors = [
106
106
  "dev/DOC_SYNC_REGISTRY.md"
107
107
  ]
108
108
  },
109
- {
110
- target: "dev/SESSION_LOG.md",
111
- label: "session log event and opening message schema",
112
- snippets: [
113
- "Record what actually happened in the session",
114
- "## Entry Template",
109
+ {
110
+ target: "dev/SESSION_LOG.md",
111
+ label: "session log event and opening message schema",
112
+ placement: sessionLogAnchorPlacement,
113
+ snippets: [
114
+ "Record what actually happened in the session",
115
+ "## Entry Template",
115
116
  "- **QC:**",
116
117
  "- **Sync:**",
117
118
  "- **Log maintenance:**",
@@ -122,12 +123,13 @@ const requiredAnchors = [
122
123
  "dev/DOC_SYNC_REGISTRY.md"
123
124
  ]
124
125
  },
125
- {
126
- target: "dev/SESSION_HANDOFF.md",
127
- label: "handoff log archive continuity",
128
- snippets: [
129
- "ack:section:handoff-sufficiency-check",
130
- "ack:section:state-reconciliation-check",
126
+ {
127
+ target: "dev/SESSION_HANDOFF.md",
128
+ label: "handoff log archive continuity",
129
+ placement: handoffContinuityAnchorPlacement,
130
+ snippets: [
131
+ "ack:section:handoff-sufficiency-check",
132
+ "ack:section:state-reconciliation-check",
131
133
  "ack:field:stale-snapshots-left",
132
134
  "ack:field:opening-message-matches-current-state",
133
135
  "without searching old log history",
@@ -135,41 +137,45 @@ const requiredAnchors = [
135
137
  "do not create an archive directory by default"
136
138
  ]
137
139
  },
138
- {
139
- target: "dev/SESSION_LOG.md",
140
- label: "log retention and evidence schema",
141
- snippets: [
142
- "kept, summarized, or archived",
143
- "Do not remove validation evidence",
140
+ {
141
+ target: "dev/SESSION_LOG.md",
142
+ label: "log retention and evidence schema",
143
+ placement: sessionLogAnchorPlacement,
144
+ snippets: [
145
+ "kept, summarized, or archived",
146
+ "Do not remove validation evidence",
144
147
  "latest opening message",
145
148
  "not current state"
146
149
  ]
147
150
  },
148
- {
149
- target: "dev/PROJECT_INDEX.md",
150
- label: "template version metadata",
151
- snippets: [
152
- "Agent Handoff Kit template version"
153
- ]
151
+ {
152
+ target: "dev/PROJECT_INDEX.md",
153
+ label: "template version metadata",
154
+ placement: projectIndexAnchorPlacement,
155
+ snippets: [
156
+ "Agent Handoff Kit template version"
157
+ ]
154
158
  },
155
- {
156
- target: "dev/rules/safety.md",
157
- label: "safety pack high-risk anchors",
158
- snippets: [
159
- "deleting, overwriting, moving, renaming",
160
- "filesystem root, drive root",
159
+ {
160
+ target: "dev/rules/safety.md",
161
+ label: "safety pack high-risk anchors",
162
+ placement: safetyAnchorPlacement,
163
+ snippets: [
164
+ "deleting, overwriting, moving, renaming",
165
+ "filesystem root, drive root",
161
166
  "cmd /c rmdir",
162
167
  "git reset --hard",
163
168
  "external APIs, SDKs, CLIs",
164
169
  "secret values"
165
170
  ]
166
171
  },
167
- {
168
- target: "dev/PROJECT_DECISIONS.md",
169
- label: "project decisions narrative anchors",
170
- snippets: [
171
- "Project Decisions Log",
172
- "warm 資料層",
172
+ {
173
+ target: "dev/PROJECT_DECISIONS.md",
174
+ label: "project decisions narrative anchors",
175
+ placement: projectDecisionsAnchorPlacement,
176
+ snippets: [
177
+ "Project Decisions Log",
178
+ "warm 資料層",
173
179
  "AI 開工",
174
180
  "不需要讀",
175
181
  "AI 在收工時自動 update",
@@ -179,12 +185,13 @@ const requiredAnchors = [
179
185
  "Insights & Learnings"
180
186
  ]
181
187
  },
182
- {
183
- target: "dev/rules/onboarding.md",
184
- label: "onboarding pack core anchors",
185
- snippets: [
186
- "Onboarding Pack",
187
- "transient pack",
188
+ {
189
+ target: "dev/rules/onboarding.md",
190
+ label: "onboarding pack core anchors",
191
+ placement: onboardingAnchorPlacement,
192
+ snippets: [
193
+ "Onboarding Pack",
194
+ "transient pack",
188
195
  "明確 onboarding signal keywords",
189
196
  "5-step walk-through pattern",
190
197
  "Application Scenario Library",
@@ -197,12 +204,13 @@ const requiredAnchors = [
197
204
  "Tone Discipline"
198
205
  ]
199
206
  },
200
- {
201
- target: "dev/rules/integrations.md",
202
- label: "integrations pack core anchors",
203
- snippets: [
204
- "Integrations Pack",
205
- "Connectors",
207
+ {
208
+ target: "dev/rules/integrations.md",
209
+ label: "integrations pack core anchors",
210
+ placement: integrationsAnchorPlacement,
211
+ snippets: [
212
+ "Integrations Pack",
213
+ "Connectors",
206
214
  "MCPs",
207
215
  "Plugins",
208
216
  "Skills",
@@ -1001,9 +1009,9 @@ function extractSectionText(text, markerId, headingTitle) {
1001
1009
  return text.slice(start, nextHeading ? start + nextHeading.index : text.length);
1002
1010
  }
1003
1011
 
1004
- async function checkRequiredAnchors(root) {
1005
- const rows = [];
1006
- for (const rule of requiredAnchors) {
1012
+ async function checkRequiredAnchors(root) {
1013
+ const rows = [];
1014
+ for (const rule of requiredAnchors) {
1007
1015
  const filePath = path.join(root, rule.target);
1008
1016
  let text = "";
1009
1017
  try {
@@ -1013,13 +1021,15 @@ async function checkRequiredAnchors(root) {
1013
1021
  continue;
1014
1022
  }
1015
1023
 
1016
- // Report which specific anchor snippets are absent, not just pass/fail. Mirrors
1017
- // the schema-check contract (checkSchema returns `missing`) so an anchor failure
1018
- // is self-diagnosing: the user and the AI can see the exact text to restore.
1019
- const missing = rule.snippets.filter((snippet) => !text.includes(snippet));
1020
- rows.push({
1021
- target: rule.target,
1022
- label: rule.label,
1024
+ // Report which specific anchor snippets are absent or semantically misplaced,
1025
+ // not just pass/fail. A naked snippet at file tail must not make doctor green.
1026
+ const failures = requiredAnchorFailures(rule, text);
1027
+ const missing = failures.map((failure) => failure.kind === "missing"
1028
+ ? failure.snippet
1029
+ : `misplaced: ${failure.snippet}`);
1030
+ rows.push({
1031
+ target: rule.target,
1032
+ label: rule.label,
1023
1033
  ok: missing.length === 0,
1024
1034
  missing
1025
1035
  });
@@ -1220,12 +1230,12 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1220
1230
  // content and any user customization preserved. Step 1 micro-question additions to Scenarios A-E
1221
1231
  // are NOT auto-migrated (user-customizable inline sample wording, not anchor-enforced); users get
1222
1232
  // those on fresh install only or can manually patch following CHANGELOG migration guidance.
1223
- if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario F. 審視已裝外部工具")) {
1224
- const sourceScenarioFMatch = sourceText.match(/(### Scenario F\. 審視已裝外部工具[\s\S]*?)(?=## Cross-reference to guide\.html)/);
1225
- if (sourceScenarioFMatch && targetText.includes("## Cross-reference to guide.html")) {
1226
- const scenarioFBlock = sourceScenarioFMatch[1];
1227
- return {
1228
- ...base,
1233
+ if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario F. 審視已裝外部工具")) {
1234
+ const sourceScenarioFMatch = sourceText.match(/(### Scenario F\. 審視已裝外部工具[\s\S]*?)(?=## Cross-reference to guide\.html)/);
1235
+ if (sourceScenarioFMatch && hasTrustedOnboardingScenarioLibrary(targetText)) {
1236
+ const scenarioFBlock = sourceScenarioFMatch[1];
1237
+ return {
1238
+ ...base,
1229
1239
  action: "merge",
1230
1240
  reason: "insert ### Scenario F block before ## Cross-reference to guide.html (R-030 onboarding pack migration; existing Scenarios A-E content preserved non-destructively)",
1231
1241
  mergedText: targetText.replace("## Cross-reference to guide.html", scenarioFBlock + "## Cross-reference to guide.html")
@@ -1273,10 +1283,35 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1273
1283
  };
1274
1284
  }
1275
1285
  }
1286
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && hasMissingRequiredAnchor(targetRel, targetText, "handoff log archive continuity")) {
1287
+ const mergedHandoff = mergeHandoffArchiveContinuityRule(targetText, sourceText);
1288
+ if (!mergedHandoff) {
1289
+ return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md handoff sufficiency markers were changed; manual merge required to add archive continuity rule" };
1290
+ }
1291
+ return {
1292
+ ...base,
1293
+ action: "merge",
1294
+ reason: "insert handoff archive continuity rule so upgrade self-check can pass without requiring manual anchor repair",
1295
+ mergedText: mergedHandoff
1296
+ };
1297
+ }
1298
+ if (command === "upgrade" && hasAnchorRepairMarkerDrift(targetText)) {
1299
+ return { ...base, action: "conflict", reason: "legacy anchor repair block markers are incomplete or obsolete; manual semantic cleanup required before upgrade can safely continue" };
1300
+ }
1301
+ if (command === "upgrade" && hasMisplacedRequiredAnchor(targetRel, targetText)) {
1302
+ 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" };
1303
+ }
1304
+ if (command === "upgrade" && hasMissingRequiredAnchor(targetRel, targetText)) {
1305
+ const semanticRepair = mergeMissingRequiredAnchorsSemantically(targetRel, targetText, sourceText);
1306
+ if (semanticRepair) {
1307
+ return { ...base, ...semanticRepair };
1308
+ }
1309
+ return { ...base, action: "conflict", reason: "required Kit anchors are missing but no safe semantic repair path exists; upgrade stopped without appending naked anchor text" };
1310
+ }
1276
1311
  if (targetRel === "CLAUDE.md" || targetRel === "GEMINI.md") {
1277
- if (!targetText.includes("AGENTS.md")) {
1278
- return { ...base, action: "conflict", reason: "existing bridge does not route to AGENTS.md" };
1279
- }
1312
+ if (!targetText.includes("AGENTS.md")) {
1313
+ return { ...base, action: "conflict", reason: "existing bridge does not route to AGENTS.md" };
1314
+ }
1280
1315
  if (looksLikeExpandedKitBridge(targetRel, targetText)) {
1281
1316
  return {
1282
1317
  ...base,
@@ -1312,7 +1347,7 @@ function looksLikeExpandedKitBridge(targetRel, text) {
1312
1347
  return false;
1313
1348
  }
1314
1349
 
1315
- function mergeOnboardingScenarioALabel(targetText) {
1350
+ function mergeOnboardingScenarioALabel(targetText) {
1316
1351
  let merged = targetText;
1317
1352
  merged = merged.replace(
1318
1353
  /\*\*A\. 寫 \/ 改代碼項目\*\* —— 你有一個(?: project 的 codebase|程式項目)想長期維護/g,
@@ -1322,12 +1357,401 @@ function mergeOnboardingScenarioALabel(targetText) {
1322
1357
  /### Scenario A\. 寫 \/ 改代碼項目/g,
1323
1358
  "### Scenario A. 建構系統 / 工具 / 平台 / 網站或應用"
1324
1359
  );
1325
- return merged;
1326
- }
1327
-
1360
+ return merged;
1361
+ }
1362
+
1363
+ function hasTrustedOnboardingScenarioLibrary(text) {
1364
+ const bounds = textSectionBounds(text, "## Application Scenario Library", "## Cross-reference to guide.html");
1365
+ if (!bounds) return false;
1366
+ const section = text.slice(bounds.start, bounds.end);
1367
+ return [
1368
+ "### Scenario A.",
1369
+ "### Scenario B.",
1370
+ "### Scenario C.",
1371
+ "### Scenario D.",
1372
+ "### Scenario E."
1373
+ ].every((headingText) => section.includes(headingText));
1374
+ }
1375
+
1376
+ function hasMissingRequiredAnchor(targetRel, targetText, label = null) {
1377
+ return requiredAnchors
1378
+ .filter((rule) => rule.target === targetRel && (!label || rule.label === label))
1379
+ .some((rule) => requiredAnchorFailures(rule, targetText).some((failure) => failure.kind === "missing"));
1380
+ }
1381
+
1382
+ function hasMisplacedRequiredAnchor(targetRel, targetText, label = null) {
1383
+ return requiredAnchors
1384
+ .filter((rule) => rule.target === targetRel && (!label || rule.label === label))
1385
+ .some((rule) => requiredAnchorFailures(rule, targetText).some((failure) => failure.kind === "misplaced"));
1386
+ }
1387
+
1388
+ function hasAnchorRepairMarkerDrift(text) {
1389
+ const start = countText(text, "<!-- BEGIN Agent Handoff Kit anchor repair -->");
1390
+ const end = countText(text, "<!-- END Agent Handoff Kit anchor repair -->");
1391
+ return start > 0 || end > 0;
1392
+ }
1393
+
1394
+ function countText(text, needle) {
1395
+ return text.split(needle).length - 1;
1396
+ }
1397
+
1398
+ function countRegex(text, pattern) {
1399
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
1400
+ return [...text.matchAll(new RegExp(pattern.source, flags))].length;
1401
+ }
1402
+
1403
+ function missingRequiredAnchorSnippets(targetRel, targetText) {
1404
+ return [...new Set(requiredAnchors
1405
+ .filter((rule) => rule.target === targetRel)
1406
+ .flatMap((rule) => requiredAnchorFailures(rule, targetText)
1407
+ .filter((failure) => failure.kind === "missing")
1408
+ .map((failure) => failure.snippet)))];
1409
+ }
1410
+
1411
+ function requiredAnchorFailures(rule, text) {
1412
+ return rule.snippets.flatMap((snippet) => {
1413
+ if (!text.includes(snippet)) return [{ kind: "missing", snippet }];
1414
+ if (!isRequiredAnchorSemanticallyPlaced(rule, snippet, text)) return [{ kind: "misplaced", snippet }];
1415
+ return [];
1416
+ });
1417
+ }
1418
+
1419
+ function isRequiredAnchorSemanticallyPlaced(rule, snippet, text) {
1420
+ return rule.placement ? rule.placement(snippet, text) : true;
1421
+ }
1422
+
1423
+ function sessionLogAnchorPlacement(snippet, text) {
1424
+ if (snippet === "## Entry Template") return /^## Entry Template\s*$/m.test(text);
1425
+ const preamble = [
1426
+ "Record what actually happened in the session",
1427
+ "kept, summarized, or archived",
1428
+ "Do not remove validation evidence",
1429
+ "latest opening message",
1430
+ "not current state"
1431
+ ];
1432
+ if (preamble.includes(snippet)) return snippetAppearsBeforeHeading(text, snippet, "## Entry Template");
1433
+ return snippetAppearsAfterHeading(text, snippet, "## Entry Template");
1434
+ }
1435
+
1436
+ function handoffContinuityAnchorPlacement(snippet, text) {
1437
+ const suffixContinuityAnchors = [
1438
+ "without searching old log history",
1439
+ "SESSION_LOG.md` carries recent evidence",
1440
+ "do not create an archive directory by default"
1441
+ ];
1442
+ if (suffixContinuityAnchors.includes(snippet)) {
1443
+ return snippetAppearsInSemanticSection(text, snippet, "handoff-sufficiency-check", "Handoff Sufficiency Check", "next-session-opening-message", "Next Session Opening Message");
1444
+ }
1445
+ return true;
1446
+ }
1447
+
1448
+ function projectIndexAnchorPlacement(snippet, text) {
1449
+ if (snippet === "Agent Handoff Kit template version") return Boolean(projectIndexTemplateVersion(text));
1450
+ return true;
1451
+ }
1452
+
1453
+ function safetyAnchorPlacement(snippet, text) {
1454
+ return safetyAnchorHasTrustedRuleShape(text, snippet);
1455
+ }
1456
+
1457
+ function projectDecisionsAnchorPlacement(snippet, text) {
1458
+ const preamble = [
1459
+ "Project Decisions Log",
1460
+ "warm 資料層",
1461
+ "AI 開工",
1462
+ "不需要讀",
1463
+ "AI 在收工時自動 update"
1464
+ ];
1465
+ if (preamble.includes(snippet)) return snippetAppearsBeforeHeading(text, snippet, "## Evolution Timeline");
1466
+ return true;
1467
+ }
1468
+
1469
+ function onboardingAnchorPlacement(snippet, text) {
1470
+ if (snippet === "Application Scenario Library") {
1471
+ return Boolean(textSectionBounds(text, "## Application Scenario Library", "## Cross-reference to guide.html"));
1472
+ }
1473
+ if (/^Scenario [A-F]\./.test(snippet)) {
1474
+ return snippetAppearsBetweenHeadings(text, snippet, "## Application Scenario Library", "## Cross-reference to guide.html");
1475
+ }
1476
+ return true;
1477
+ }
1478
+
1479
+ function integrationsAnchorPlacement(snippet, text) {
1480
+ if (snippet === "機密分離原則" || snippet === "Source-of-truth Architecture" || snippet === "Cross-session Lifecycle") {
1481
+ return snippetAppearsBetweenHeadings(text, snippet, "## Discipline", "## Rules");
1482
+ }
1483
+ if (snippet === "Connector-first default") {
1484
+ return snippetAppearsBetweenHeadings(text, snippet, "## Rules", "## Checks");
1485
+ }
1486
+ if (snippet === "Anti-pattern") return text.includes("## Anti-pattern(不要做的事)");
1487
+ return true;
1488
+ }
1489
+
1490
+ function snippetAppearsBeforeHeading(text, snippet, headingText) {
1491
+ const headingIndex = text.indexOf(headingText);
1492
+ if (headingIndex < 0) return false;
1493
+ return text.slice(0, headingIndex).includes(snippet);
1494
+ }
1495
+
1496
+ function snippetAppearsAfterHeading(text, snippet, headingText) {
1497
+ const headingIndex = text.indexOf(headingText);
1498
+ if (headingIndex < 0) return false;
1499
+ return text.slice(headingIndex + headingText.length).includes(snippet);
1500
+ }
1501
+
1502
+ function snippetAppearsBetweenHeadings(text, snippet, startHeading, endHeading) {
1503
+ const startIndex = text.indexOf(startHeading);
1504
+ const endIndex = text.indexOf(endHeading);
1505
+ if (startIndex < 0 || endIndex < 0 || endIndex <= startIndex) return false;
1506
+ return text.slice(startIndex + startHeading.length, endIndex).includes(snippet);
1507
+ }
1508
+
1509
+ function snippetAppearsInSemanticSection(text, snippet, startId, startHeading, endId, endHeading) {
1510
+ const startMarker = `<!-- ack:section:${startId} -->`;
1511
+ const endMarker = `<!-- ack:section:${endId} -->`;
1512
+ const markerStart = text.indexOf(startMarker);
1513
+ const markerEnd = text.indexOf(endMarker, markerStart + startMarker.length);
1514
+ if (markerStart >= 0 && markerEnd > markerStart) {
1515
+ return text.slice(markerStart + startMarker.length, markerEnd).includes(snippet);
1516
+ }
1517
+ return snippetAppearsBetweenHeadings(text, snippet, `## ${startHeading}`, `## ${endHeading}`);
1518
+ }
1519
+
1520
+ const semanticAnchorRepairStrategies = {
1521
+ "dev/PROJECT_INDEX.md": (targetText, sourceText) => {
1522
+ const mergedIndex = mergeProjectIndexTemplateVersionRow(targetText, sourceText);
1523
+ return mergedIndex ? {
1524
+ action: "merge",
1525
+ reason: "restore PROJECT_INDEX template version metadata row in ## Stack table",
1526
+ mergedText: mergedIndex
1527
+ } : null;
1528
+ },
1529
+ "dev/SESSION_LOG.md": (targetText, sourceText) => {
1530
+ const mergedLog = insertSourcePreambleBeforeHeading(targetText, sourceText, "## Entry Template");
1531
+ return mergedLog ? {
1532
+ action: "merge",
1533
+ reason: "restore SESSION_LOG Kit preamble before ## Entry Template",
1534
+ mergedText: mergedLog
1535
+ } : null;
1536
+ },
1537
+ "dev/PROJECT_DECISIONS.md": (targetText, sourceText) => {
1538
+ const mergedDecisions = insertSourcePreambleBeforeHeading(targetText, sourceText, "## Evolution Timeline");
1539
+ return mergedDecisions ? {
1540
+ action: "merge",
1541
+ reason: "restore PROJECT_DECISIONS onboarding preamble before ## Evolution Timeline",
1542
+ mergedText: mergedDecisions
1543
+ } : null;
1544
+ },
1545
+ "dev/rules/safety.md": (targetText, sourceText, missing) => {
1546
+ const mergedSafety = mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing);
1547
+ return mergedSafety ? {
1548
+ action: "merge",
1549
+ reason: "restore safety pack high-risk rules in ## Rules section",
1550
+ mergedText: mergedSafety
1551
+ } : null;
1552
+ },
1553
+ "dev/rules/integrations.md": (targetText, sourceText, missing) => {
1554
+ const mergedIntegrations = mergeIntegrationsCredentialSection(targetText, sourceText, missing);
1555
+ return mergedIntegrations ? {
1556
+ action: "merge",
1557
+ reason: "restore integrations credential-separation section in semantic position",
1558
+ mergedText: mergedIntegrations
1559
+ } : null;
1560
+ }
1561
+ };
1562
+
1563
+ function mergeMissingRequiredAnchorsSemantically(targetRel, targetText, sourceText) {
1564
+ const missing = missingRequiredAnchorSnippets(targetRel, targetText);
1565
+ if (missing.length === 0) return null;
1566
+
1567
+ return semanticAnchorRepairStrategies[targetRel]?.(targetText, sourceText, missing) ?? null;
1568
+ }
1569
+
1570
+ function insertSourcePreambleBeforeHeading(targetText, sourceText, headingText) {
1571
+ const targetIndex = targetText.indexOf(headingText);
1572
+ const sourceIndex = sourceText.indexOf(headingText);
1573
+ if (targetIndex < 0 || sourceIndex < 0) return null;
1574
+ const sourcePreamble = sourceText.slice(0, sourceIndex).trim();
1575
+ if (!sourcePreamble) return null;
1576
+ const targetBefore = targetText.slice(0, targetIndex).trimEnd();
1577
+ const targetAfter = targetText.slice(targetIndex);
1578
+ return `${targetBefore}\n\n${sourcePreamble}\n\n${targetAfter}`;
1579
+ }
1580
+
1581
+ function mergeProjectIndexTemplateVersionRow(targetText, sourceText) {
1582
+ if (projectIndexTemplateVersion(targetText)) return targetText;
1583
+ const sourceRow = sourceText.match(/^\| Agent Handoff Kit template version \| [\d.]+ \| [^|\n]+ \|$/m)?.[0];
1584
+ if (!sourceRow) return null;
1585
+ const lines = targetText.split(/\r?\n/);
1586
+ const stackIndex = lines.findIndex((line) => line.trim() === "## Stack");
1587
+ if (stackIndex < 0) return null;
1588
+ const tableHeaderIndex = lines.findIndex((line, index) => index > stackIndex && line.trim() === "| Field | Value | Last verified |");
1589
+ if (tableHeaderIndex < 0) return null;
1590
+ const separatorIndex = tableHeaderIndex + 1;
1591
+ if (!lines[separatorIndex]?.startsWith("|---")) return null;
1592
+ lines.splice(separatorIndex + 1, 0, sourceRow);
1593
+ return lines.join("\n");
1594
+ }
1595
+
1596
+ function mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing) {
1597
+ if (!hasTrustedSafetyPackShape(targetText)) return null;
1598
+ const targetBounds = sectionBounds(targetText, "## Rules", "## Checks");
1599
+ const sourceBounds = sectionBounds(sourceText, "## Rules", "## Checks");
1600
+ if (!targetBounds || !sourceBounds) return null;
1601
+ const targetLines = targetText.split(/\r?\n/);
1602
+ const sourceLines = sourceText.split(/\r?\n/);
1603
+ const targetRuleStart = targetBounds.start + 1;
1604
+ const targetRuleEnd = targetBounds.end;
1605
+ const sourceRuleLines = sourceLines.slice(sourceBounds.start + 1, sourceBounds.end);
1606
+
1607
+ let changed = false;
1608
+ for (const snippet of missing) {
1609
+ const sourceLine = sourceRuleLines.find((line) => line.includes(snippet));
1610
+ if (!sourceLine) return null;
1611
+ const ruleNumber = sourceLine.match(/^(\d+)\. /)?.[1];
1612
+ if (!ruleNumber) return null;
1613
+ const targetIndex = targetLines.findIndex((line, index) => index >= targetRuleStart && index < targetRuleEnd && line.startsWith(`${ruleNumber}. `));
1614
+ if (targetIndex < 0) return null;
1615
+ if (!sameRuleShape(targetLines[targetIndex], sourceLine, snippet)) return null;
1616
+ targetLines[targetIndex] = sourceLine;
1617
+ changed = true;
1618
+ }
1619
+
1620
+ return changed ? targetLines.join("\n") : targetText;
1621
+ }
1622
+
1623
+ function mergeIntegrationsCredentialSection(targetText, sourceText, missing) {
1624
+ if (!missing.some((snippet) => snippet === "機密分離原則")) return null;
1625
+ return replaceSectionByHeadingWithinBounds(
1626
+ targetText,
1627
+ sourceText,
1628
+ /^### 1\. 機密分離原則/m,
1629
+ /^### 2\. 四類整合嘅紀律差異/m,
1630
+ "## Discipline",
1631
+ "## Rules"
1632
+ );
1633
+ }
1634
+
1635
+ function hasTrustedSafetyPackShape(text) {
1636
+ return text.includes("# Safety Pack")
1637
+ && text.includes("## Scope")
1638
+ && text.includes("## Load When")
1639
+ && Boolean(sectionBounds(text, "## Rules", "## Checks"))
1640
+ && text.includes("## Closeout");
1641
+ }
1642
+
1643
+ function sameRuleShape(targetLine, sourceLine, snippet) {
1644
+ const snippetIndex = sourceLine.indexOf(snippet);
1645
+ if (snippetIndex < 0) return false;
1646
+ const prefix = sourceLine.slice(0, snippetIndex);
1647
+ const suffix = sourceLine.slice(snippetIndex + snippet.length);
1648
+ return prefix.length >= 12
1649
+ && suffix.length >= 8
1650
+ && targetLine.startsWith(prefix)
1651
+ && targetLine.endsWith(suffix);
1652
+ }
1653
+
1654
+ function safetyAnchorHasTrustedRuleShape(text, snippet) {
1655
+ const bounds = sectionBounds(text, "## Rules", "## Checks");
1656
+ if (!bounds) return false;
1657
+ const lines = text.split(/\r?\n/).slice(bounds.start + 1, bounds.end);
1658
+ const line = lines.find((candidate) => candidate.includes(snippet));
1659
+ if (!line) return false;
1660
+ if (snippet === "cmd /c rmdir") {
1661
+ return line.includes("cmd /c rd")
1662
+ && line.includes("cmd.exe /c")
1663
+ && line.includes("combined with `rmdir` or `rd`")
1664
+ && line.includes("Prefer native PowerShell cmdlets")
1665
+ && line.includes("do not compose filesystem modification commands across shells");
1666
+ }
1667
+ if (snippet === "git reset --hard") {
1668
+ return line.includes("branch deletion")
1669
+ && line.includes("force push")
1670
+ && line.includes("history rewrite");
1671
+ }
1672
+ if (snippet === "secret values") {
1673
+ return line.includes("Do not print")
1674
+ && line.includes("log")
1675
+ && line.includes("commit")
1676
+ && line.includes("redacted placeholders");
1677
+ }
1678
+ if (snippet === "external APIs, SDKs, CLIs") {
1679
+ return line.includes("package managers")
1680
+ && line.includes("official documentation")
1681
+ && line.includes("project-local runbooks");
1682
+ }
1683
+ return true;
1684
+ }
1685
+
1686
+ function replaceSectionByHeadingWithinBounds(targetText, sourceText, startPattern, nextPattern, boundsStart, boundsEnd) {
1687
+ if (countText(targetText, boundsStart) !== 1 || countText(targetText, boundsEnd) !== 1) return null;
1688
+ const targetBounds = textSectionBounds(targetText, boundsStart, boundsEnd);
1689
+ const sourceBounds = textSectionBounds(sourceText, boundsStart, boundsEnd);
1690
+ if (!targetBounds || !sourceBounds) return null;
1691
+
1692
+ const boundedTarget = targetText.slice(targetBounds.start, targetBounds.end);
1693
+ const boundedSource = sourceText.slice(sourceBounds.start, sourceBounds.end);
1694
+ if (countRegex(boundedTarget, startPattern) > 1 || countRegex(boundedTarget, nextPattern) !== 1) return null;
1695
+ const sourceSection = extractSection(boundedSource, startPattern, nextPattern);
1696
+ if (!sourceSection) return null;
1697
+ const targetSection = extractSection(boundedTarget, startPattern, nextPattern);
1698
+ if (targetSection) {
1699
+ return `${targetText.slice(0, targetBounds.start + targetSection.start)}${sourceSection.text}${targetText.slice(targetBounds.start + targetSection.end)}`;
1700
+ }
1701
+ const nextMatch = nextPattern.exec(boundedTarget);
1702
+ if (!nextMatch) return null;
1703
+ return `${targetText.slice(0, targetBounds.start + nextMatch.index)}${sourceSection.text}${targetText.slice(targetBounds.start + nextMatch.index)}`;
1704
+ }
1705
+
1706
+ function replaceSectionByHeading(targetText, sourceText, startPattern, nextPattern) {
1707
+ const sourceSection = extractSection(sourceText, startPattern, nextPattern);
1708
+ if (!sourceSection) return null;
1709
+ const targetSection = extractSection(targetText, startPattern, nextPattern);
1710
+ if (targetSection) {
1711
+ return `${targetText.slice(0, targetSection.start)}${sourceSection.text}${targetText.slice(targetSection.end)}`;
1712
+ }
1713
+ const nextMatch = nextPattern.exec(targetText);
1714
+ if (!nextMatch) return null;
1715
+ return `${targetText.slice(0, nextMatch.index)}${sourceSection.text}${targetText.slice(nextMatch.index)}`;
1716
+ }
1717
+
1718
+ function extractSection(text, startPattern, nextPattern) {
1719
+ const startMatch = startPattern.exec(text);
1720
+ if (!startMatch) return null;
1721
+ const afterStart = text.slice(startMatch.index + startMatch[0].length);
1722
+ const nextMatch = nextPattern.exec(afterStart);
1723
+ const end = nextMatch ? startMatch.index + startMatch[0].length + nextMatch.index : text.length;
1724
+ return { start: startMatch.index, end, text: text.slice(startMatch.index, end) };
1725
+ }
1726
+
1727
+ function sectionBounds(text, startHeading, endHeading) {
1728
+ const lines = text.split(/\r?\n/);
1729
+ const start = lines.findIndex((line) => line.trim() === startHeading);
1730
+ if (start < 0) return null;
1731
+ const end = lines.findIndex((line, index) => index > start && line.trim() === endHeading);
1732
+ if (end < 0) return null;
1733
+ return { start, end };
1734
+ }
1735
+
1736
+ function textSectionBounds(text, startHeading, endHeading) {
1737
+ const startIndex = text.indexOf(startHeading);
1738
+ if (startIndex < 0) return null;
1739
+ const endIndex = text.indexOf(endHeading, startIndex + startHeading.length);
1740
+ if (endIndex < 0) return null;
1741
+ return { start: startIndex, end: endIndex };
1742
+ }
1743
+
1744
+ function projectIndexTemplateVersion(text) {
1745
+ const bounds = textSectionBounds(text, "## Stack", "## Directory Map");
1746
+ if (!bounds) return null;
1747
+ const stack = text.slice(bounds.start, bounds.end);
1748
+ const row = stack.match(/^\| Agent Handoff Kit template version \| ([\d.]+) \| [^|\n]+ \|$/m);
1749
+ return row ? row[1] : null;
1750
+ }
1751
+
1328
1752
  function mergeHandoffLifecycleField(targetText) {
1329
- const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
1330
- if (!targetText.includes(openingMarker)) return null;
1753
+ const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
1754
+ if (!targetText.includes(openingMarker)) return null;
1331
1755
 
1332
1756
  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";
1333
1757
  let merged = targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
@@ -1373,10 +1797,34 @@ function reclassifyExistingHandoffLifecyclePlaceholder(targetText) {
1373
1797
 
1374
1798
  return merged;
1375
1799
  }
1376
-
1377
- function mergeRulePacksRows(targetText, sourceText) {
1378
- const requiredPacks = [
1379
- "dev/rules/onboarding.md",
1800
+
1801
+ function mergeHandoffArchiveContinuityRule(targetText, sourceText) {
1802
+ const sourceMatch = sourceText.match(/Continuity rule: this file carries current state and next action\.[^\r\n]*/);
1803
+ if (!sourceMatch) return null;
1804
+ const continuityRule = sourceMatch[0];
1805
+ if (targetText.includes(continuityRule)) return targetText;
1806
+
1807
+ const existingRulePattern = /Continuity rule: this file carries current state and next action\.[^\r\n]*/;
1808
+ if (existingRulePattern.test(targetText)) {
1809
+ return targetText.replace(existingRulePattern, continuityRule);
1810
+ }
1811
+
1812
+ const nextSectionMarker = "<!-- ack:section:next-session-opening-message -->";
1813
+ if (targetText.includes(nextSectionMarker)) {
1814
+ return targetText.replace(nextSectionMarker, `${continuityRule}\n\n${nextSectionMarker}`);
1815
+ }
1816
+
1817
+ const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
1818
+ if (targetText.includes(sufficiencyMarker)) {
1819
+ return `${targetText.trimEnd()}\n\n${continuityRule}\n`;
1820
+ }
1821
+
1822
+ return null;
1823
+ }
1824
+
1825
+ function mergeRulePacksRows(targetText, sourceText) {
1826
+ const requiredPacks = [
1827
+ "dev/rules/onboarding.md",
1380
1828
  "dev/rules/integrations.md"
1381
1829
  ];
1382
1830
  const sourceRows = sourceText
@@ -1416,15 +1864,14 @@ function mergeRulePacksRows(targetText, sourceText) {
1416
1864
  // maybePrintUpdateNotice which silently fails when npx auto-fetches latest (CLI version
1417
1865
  // equals npm latest, so the notice never triggers, leaving user root drift invisible).
1418
1866
  async function assessVersionAlignment(root, cliVersion) {
1419
- const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
1420
- let rootVersion = null;
1421
- try {
1422
- const text = await readFile(indexPath, "utf8");
1423
- const m = text.match(/\| Agent Handoff Kit template version \| ([\d.]+) \|/);
1424
- if (m) rootVersion = m[1];
1425
- } catch {
1426
- // file missing or unreadable; rootVersion stays null
1427
- }
1867
+ const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
1868
+ let rootVersion = null;
1869
+ try {
1870
+ const text = await readFile(indexPath, "utf8");
1871
+ rootVersion = projectIndexTemplateVersion(text);
1872
+ } catch {
1873
+ // file missing or unreadable; rootVersion stays null
1874
+ }
1428
1875
 
1429
1876
  let npmLatest = null;
1430
1877
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adamchanadam/agent-handoff-kit",
3
- "version": "0.3.20",
3
+ "version": "0.3.22",
4
4
  "description": "Lightweight agent harness for project memory, handoff, and multi-session continuity.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -18,7 +18,7 @@ Use for governance rules, prompts, agent instructions, handoff systems, startup/
18
18
  5. Check complexity budget before adding default-core behavior.
19
19
  6. Before creating durable workflow, runbook, or instruction files, first classify the knowledge type and verify whether an existing home can carry it without a new file: current state belongs in `dev/SESSION_HANDOFF.md`; trace evidence belongs in `dev/SESSION_LOG.md`; file / command / reference maps belong in `dev/PROJECT_INDEX.md`; sync obligations belong in `dev/DOC_SYNC_REGISTRY.md`; reusable operating procedures belong in the relevant rule pack or registered reference. New runbooks are last resort only.
20
20
  7. When a task uses external skills, subagents, demo workspaces, or another tool's closeout, treat those flows as subordinate to the active root's Agent Handoff Kit governance. The active root still needs its own handoff/log/index/registry persistence.
21
- 8. For long-running projects, maintain `dev/PROJECT_DECISIONS.md` per R-028 closeout discipline (see `runtime-core/AGENTS.core.md` step 12): smart-detect substantive task evolution, multi-option architectural trade-offs, and cross-session patterns, then append entries to the appropriate H2 section. Short single-task projects keep this as a no-op default; users are not expected to edit this file manually.
21
+ 8. For long-running projects, maintain `dev/PROJECT_DECISIONS.md` per R-028 closeout discipline (see `runtime-core/AGENTS.core.md` closeout maintenance trigger check): capture major decisions when they happen, run the short trigger check at every closeout, and do full long-term maintenance only when a hard trigger, semantic trigger, or 10-closeout backstop applies. Short single-task projects keep this as a no-op default; users are not expected to edit this file manually.
22
22
 
23
23
  ## Checks
24
24
 
@@ -28,7 +28,7 @@ Use for governance rules, prompts, agent instructions, handoff systems, startup/
28
28
  - Confirm any new durable file is reachable from `dev/PROJECT_INDEX.md` and does not rely only on a one-session handoff note.
29
29
  - 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.
30
30
  - Before claiming completion, inspect the active root's `dev/SESSION_HANDOFF.md`, `dev/SESSION_LOG.md`, `dev/PROJECT_INDEX.md`, and `dev/DOC_SYNC_REGISTRY.md`; do not assume child or demo workspaces cover the parent/root workspace.
31
- - For long-running projects, confirm `dev/PROJECT_DECISIONS.md` retains its four H2 sections in order (Evolution Timeline / Decisions Archive / Architecture Choices / Insights & Learnings) and that closeout step 12 was applied where its trigger conditions were met.
31
+ - For long-running projects, confirm `dev/PROJECT_DECISIONS.md` retains its four H2 sections in order (Evolution Timeline / Decisions Archive / Architecture Choices / Insights & Learnings) and that the closeout maintenance trigger check was recorded, with full maintenance applied where its trigger conditions were met.
32
32
 
33
33
  ## Closeout
34
34
 
@@ -99,23 +99,19 @@ At full closeout:
99
99
  8. If either check fails, fix `dev/SESSION_HANDOFF.md` first; do not push current-state responsibility into `dev/SESSION_LOG.md`.
100
100
  9. Regenerate `START_NEXT_SESSION_PROMPT.txt` from the fenced opening message in `dev/SESSION_HANDOFF.md`, then read it back or run the project's prompt mirror check before declaring closeout ready. `dev/SESSION_HANDOFF.md` is authoritative; `START_NEXT_SESSION_PROMPT.txt` is the stateful startup prompt that the next local agent must read. During an active session, do not regenerate it just to silence `doctor`; normal `doctor` may warn about drift, but closeout must make the copy match before handoff is declared ready.
101
101
  10. Show a short closeout card, then provide the next-session startup entry in a fenced `text` code block. Primary entry, when the next local AI agent is already opened at this project root: `Start Agent Handoff` / `開工`. Fallback entry, when the next AI agent is not yet pointed at the project root: `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.` Do not compose a separate stateful final-response prompt; the final response points to the persisted prompt file, not a third source of truth.
102
- 11. Advance the SESSION_LOG N-rule (R-010 SESSION_LOG handoff-role discipline). After prepending the new closeout entry, count `## YYYY-MM-DD` H2 entries in `dev/SESSION_LOG.md`. Any entry now at position N ≥ 11 (oldest end) must be moved into `dev/SESSION_LOG_archive/archive_<batch>_<low_date>_to_<high_date>.md` with raw content preserved. Maintain `dev/SESSION_LOG_archive/INDEX.md` (master index of all archive batches; create on first archive). Entries at N=4–10 whose core facts are already absorbed into HANDOFF / PROJECT_INDEX / requirements / decision records collapse to a short-index line using structural anchors, not line numbers. Entries with unique narrative not yet absorbed must first be ported into the relevant durable source, then collapsed. This is mandatory; do not skip. Handoff capability rests on `dev/SESSION_HANDOFF.md`; `dev/SESSION_LOG.md` is trace-back / audit trail and does not carry handoff responsibility.
102
+ 11. Run the closeout maintenance trigger check. This is a short required check, not a full maintenance pass every time. Record the result in the new `dev/SESSION_LOG.md` entry under `Log maintenance`.
103
103
 
104
- 12. Maintain `dev/PROJECT_DECISIONS.md` per R-028 project narrative discipline. Each closeout must run the following checks with equal mechanical rigor as the SESSION_LOG N-rule (step 11):
105
-
106
- (a) Decisions split check: If `dev/SESSION_HANDOFF.md` contains a decisions-like H2 section (e.g. `## Confirmed Decisions`, `## Decisions`, `## 已定案決策`) with a numbered list of ≥ 30 entries, AI must split the oldest entries (retaining the most recent 8–22 in the handoff hot tier) into `dev/PROJECT_DECISIONS.md` `## Decisions Archive`, newest first. If no such section exists in the handoff, this check is no-op (default for short single-task projects).
107
-
108
- (b) Evolution append: If the current session observed substantive task evolution (user's task description differs substantially from prior sessions, or HANDOFF Current Baseline narrative shifted direction), AI must append an entry to `## Evolution Timeline`.
109
-
110
- (c) Architecture append: If the current session plan involved a multi-option architectural trade-off (≥ 2 candidate paths + selected one + recorded rationale), AI must append an entry to `## Architecture Choices`.
111
-
112
- (d) Insights append: If AI observed a cross-session accumulated pattern (recurring same-type problem, sustained-effective approach, persistently-painful tool), AI must append an entry to `## Insights & Learnings`.
113
-
114
- AI must execute (a)–(d) proactively, not wait for user trigger or doctor warning. When none of the conditions are met, this step is no-op.
115
-
116
- AI must smart-detect long-term vs short-term project signals to gauge how proactively to look for (b)–(d) trigger conditions: long-term signals (session count ≥ 4, active objective shifting, multi-subtask SESSION_LOG entries, decisions list ≥ 10, user asking "why did we do X earlier") imply more proactive detection; short-term single-task projects keep this step as no-op default.
117
-
118
- Skipping any required (a)–(d) action when its condition is met is what would cause the next AI session to lose the long-term narrative — do not repeat that pattern. Handoff capability still rests on `dev/SESSION_HANDOFF.md`; `dev/PROJECT_DECISIONS.md` is the long-term narrative archive that surfaces when users ask retrospective questions.
104
+ Hard triggers:
105
+
106
+ (a) Advance the SESSION_LOG N-rule (R-010 SESSION_LOG handoff-role discipline) when `dev/SESSION_LOG.md` reaches N ≥ 11 entries, or when the main log exceeds 1500 lines. If triggered, move N ≥ 11 entries into `dev/SESSION_LOG_archive/archive_<batch>_<low_date>_to_<high_date>.md` with raw content preserved, maintain `dev/SESSION_LOG_archive/INDEX.md`, collapse absorbed N=4–10 entries to short-index lines, and port any unique narrative into the relevant durable source before collapsing it. Handoff capability rests on `dev/SESSION_HANDOFF.md`; `dev/SESSION_LOG.md` is trace-back / audit trail and does not carry handoff responsibility.
107
+
108
+ (b) Maintain `dev/PROJECT_DECISIONS.md` per R-028 project narrative discipline when `dev/SESSION_HANDOFF.md` contains a decisions-like H2 section (e.g. `## Confirmed Decisions`, `## Decisions`, `## 已定案決策`) with a numbered list of ≥ 30 entries. If triggered, split the oldest entries, retaining the most recent 8–22 in the handoff hot tier, into `dev/PROJECT_DECISIONS.md` `## Decisions Archive`, newest first.
109
+
110
+ (c) Append to `dev/PROJECT_DECISIONS.md` immediately, or at closeout, when the current session includes substantive task evolution, a multi-option architectural trade-off with recorded rationale, a cross-session accumulated pattern, or a user retrospective question. Use `## Evolution Timeline`, `## Architecture Choices`, or `## Insights & Learnings` as appropriate.
111
+
112
+ (d) Run a full long-term maintenance pass every 10 closeouts as a backstop, even if no trigger seems obvious. Count closeouts from the main `dev/SESSION_LOG.md` entries plus archive index entry counts when an archive exists; if the count cannot be determined confidently, treat the current N=10 boundary as the backstop trigger.
113
+
114
+ If none of the hard triggers, semantic triggers, or 10-closeout backstop applies, write a one-line no-op reason and do not perform full long-term maintenance. This keeps routine closeout fast while still preventing silent drift.
119
115
 
120
116
  Installed handoff templates use English headings by default for cross-tool stability, but project teams may translate `dev/SESSION_HANDOFF.md` section headings and visible field labels into the project's working language. Keep the `ack:section:*` and `ack:field:*` semantic markers intact; `doctor` validates those markers so localized handoff notes remain supported.
121
117
 
@@ -3,9 +3,9 @@
3
3
  這個檔保存項目的長期演進、決策、架構取捨與學習觀察 narrative。屬 warm 資料層 —— AI 開工**不需要讀**本檔。
4
4
 
5
5
  🔹 短期 single-task project:本檔保持近空,你不需要 maintain
6
- 🔹 長期持續演進項目:AI 會自動 maintain;當你問「我們之前為何這樣做」時,AI 會在這裡找答案
6
+ 🔹 長期持續演進項目:AI 會在收工時先做維護觸發檢查;命中觸發或到定期兜底時才完整整理。當你問「我們之前為何這樣做」時,AI 會在這裡找答案
7
7
 
8
- 不需要你手動寫 —— AI 在收工時自動 update。
8
+ 不需要你手動寫 —— AI 在收工時自動 update;重大決策可在發生時即時記錄,不必等到最後才回想。
9
9
 
10
10
  ---
11
11
 
@@ -1,14 +1,14 @@
1
1
  # Session Log
2
2
 
3
- > **Handoff role**: This log is the trace-back / audit trail layer. Handoff capability rests on `dev/SESSION_HANDOFF.md`. The next AI session can continue by reading `AGENTS.md` + `dev/SESSION_HANDOFF.md` + `dev/PROJECT_INDEX.md` + needed rule packs; reading this log is not required for continuity. Each closeout must advance the N-rule per `AGENTS.md` `## Closeout And Handoff` step 11 (R-010 SESSION_LOG handoff-role discipline): N=1–3 keep full, N=4–10 short-index after absorbed-source check, N=11+ archive into `dev/SESSION_LOG_archive/`.
3
+ > **Handoff role**: This log is the trace-back / audit trail layer. Handoff capability rests on `dev/SESSION_HANDOFF.md`. The next AI session can continue by reading `AGENTS.md` + `dev/SESSION_HANDOFF.md` + `dev/PROJECT_INDEX.md` + needed rule packs; reading this log is not required for continuity. Each closeout must run the maintenance trigger check per `AGENTS.md` `## Closeout And Handoff` step 11 (R-010 SESSION_LOG handoff-role discipline): N=1–3 keep full, N=4–10 may short-index after absorbed-source check when triggered, N=11+ archive into `dev/SESSION_LOG_archive/`.
4
4
 
5
5
  Add new session entries at the top. Record what actually happened in the session; do not copy old completed work forward as new work.
6
6
 
7
7
  This log carries recent evidence, not current state. Put the current objective, next action, risks, and workspace identity in `dev/SESSION_HANDOFF.md`.
8
8
 
9
- Keep recent entries concise. If older entries no longer affect the next action, reduce them to short dated indexes that point to the durable source of truth. Archive long error output, validation detail, or research trails only when needed; do not create an archive directory by default.
9
+ Keep recent entries concise. If older entries no longer affect the next action and the maintenance trigger check says cleanup is due, reduce them to short dated indexes that point to the durable source of truth. Archive long error output, validation detail, or research trails only when triggered; do not create an archive directory by default.
10
10
 
11
- Before closeout, check whether older log detail should be kept, summarized, or archived. Do not remove validation evidence, unresolved risks, or the latest opening message.
11
+ Before closeout, record whether older log detail was kept, summarized, or archived, and whether the maintenance trigger check was no-op, triggered, or backstop-driven. Do not remove validation evidence, unresolved risks, or the latest opening message.
12
12
 
13
13
  ## Entry Template
14
14
 
@@ -23,7 +23,7 @@ Before closeout, check whether older log detail should be kept, summarized, or a
23
23
  - **Sync:** <doc/external sync status>
24
24
  - **Pending:** <next work>
25
25
  - **Risks:** <known risks or none>
26
- - **Log maintenance:** <kept/summarized/archived/not_needed and why>
26
+ - **Log maintenance:** <trigger check result; full maintenance action if triggered, otherwise no-op reason>
27
27
 
28
28
  ### Next Session Opening Message
29
29