@adamchanadam/agent-handoff-kit 0.3.21 → 0.3.23
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 +2 -2
- package/bin/agent-handoff-kit.mjs +849 -157
- package/package.json +1 -1
- package/packs/research.md +2 -0
- package/runtime-core/AGENTS.core.md +14 -10
- package/runtime-core/PROJECT_DECISIONS.md +10 -0
- package/runtime-core/SESSION_HANDOFF.md +3 -1
- package/runtime-core/SESSION_LOG.md +1 -0
|
@@ -46,8 +46,10 @@ const requiredAnchors = [
|
|
|
46
46
|
"dev/SESSION_HANDOFF.md",
|
|
47
47
|
"dev/SESSION_LOG.md",
|
|
48
48
|
"dev/PROJECT_INDEX.md",
|
|
49
|
-
"dev/RULE_PACKS.md",
|
|
49
|
+
"dev/RULE_PACKS.md",
|
|
50
50
|
"Agent Handoff Kit v<version>",
|
|
51
|
+
"Display version rule",
|
|
52
|
+
"Agent Handoff Kit template version",
|
|
51
53
|
"continuity ready",
|
|
52
54
|
"Start Agent Handoff",
|
|
53
55
|
"Ambiguous startup phrases",
|
|
@@ -75,6 +77,8 @@ const requiredAnchors = [
|
|
|
75
77
|
"next-session opening message",
|
|
76
78
|
"fenced `text` code block",
|
|
77
79
|
"handoff saved",
|
|
80
|
+
"Use the same display version rule as startup",
|
|
81
|
+
"Never print the literal placeholder `v<version>`",
|
|
78
82
|
"next-session startup entry",
|
|
79
83
|
"State Reconciliation Check",
|
|
80
84
|
"handoff lifecycle consistency",
|
|
@@ -97,21 +101,23 @@ const requiredAnchors = [
|
|
|
97
101
|
"ack:section:workspace-identity",
|
|
98
102
|
"ack:section:sync-status",
|
|
99
103
|
"ack:section:next-task-required-reading",
|
|
100
|
-
"ack:section:state-reconciliation-check",
|
|
104
|
+
"ack:section:state-reconciliation-check",
|
|
101
105
|
"ack:section:next-session-opening-message",
|
|
102
106
|
"ack:field:lifecycle-conflicts-resolved",
|
|
107
|
+
"ack:field:persistence-routing-checked",
|
|
103
108
|
"📋 Next session:",
|
|
104
109
|
"```text",
|
|
105
110
|
"Read in order:",
|
|
106
111
|
"dev/DOC_SYNC_REGISTRY.md"
|
|
107
112
|
]
|
|
108
113
|
},
|
|
109
|
-
{
|
|
110
|
-
target: "dev/SESSION_LOG.md",
|
|
111
|
-
label: "session log event and opening message schema",
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
"
|
|
114
|
+
{
|
|
115
|
+
target: "dev/SESSION_LOG.md",
|
|
116
|
+
label: "session log event and opening message schema",
|
|
117
|
+
placement: sessionLogAnchorPlacement,
|
|
118
|
+
snippets: [
|
|
119
|
+
"Record what actually happened in the session",
|
|
120
|
+
"## Entry Template",
|
|
115
121
|
"- **QC:**",
|
|
116
122
|
"- **Sync:**",
|
|
117
123
|
"- **Log maintenance:**",
|
|
@@ -122,12 +128,13 @@ const requiredAnchors = [
|
|
|
122
128
|
"dev/DOC_SYNC_REGISTRY.md"
|
|
123
129
|
]
|
|
124
130
|
},
|
|
125
|
-
{
|
|
126
|
-
target: "dev/SESSION_HANDOFF.md",
|
|
127
|
-
label: "handoff log archive continuity",
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
"ack:section:
|
|
131
|
+
{
|
|
132
|
+
target: "dev/SESSION_HANDOFF.md",
|
|
133
|
+
label: "handoff log archive continuity",
|
|
134
|
+
placement: handoffContinuityAnchorPlacement,
|
|
135
|
+
snippets: [
|
|
136
|
+
"ack:section:handoff-sufficiency-check",
|
|
137
|
+
"ack:section:state-reconciliation-check",
|
|
131
138
|
"ack:field:stale-snapshots-left",
|
|
132
139
|
"ack:field:opening-message-matches-current-state",
|
|
133
140
|
"without searching old log history",
|
|
@@ -135,56 +142,63 @@ const requiredAnchors = [
|
|
|
135
142
|
"do not create an archive directory by default"
|
|
136
143
|
]
|
|
137
144
|
},
|
|
138
|
-
{
|
|
139
|
-
target: "dev/SESSION_LOG.md",
|
|
140
|
-
label: "log retention and evidence schema",
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
"
|
|
145
|
+
{
|
|
146
|
+
target: "dev/SESSION_LOG.md",
|
|
147
|
+
label: "log retention and evidence schema",
|
|
148
|
+
placement: sessionLogAnchorPlacement,
|
|
149
|
+
snippets: [
|
|
150
|
+
"kept, summarized, or archived",
|
|
151
|
+
"Do not remove validation evidence",
|
|
144
152
|
"latest opening message",
|
|
145
153
|
"not current state"
|
|
146
154
|
]
|
|
147
155
|
},
|
|
148
|
-
{
|
|
149
|
-
target: "dev/PROJECT_INDEX.md",
|
|
150
|
-
label: "template version metadata",
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
156
|
+
{
|
|
157
|
+
target: "dev/PROJECT_INDEX.md",
|
|
158
|
+
label: "template version metadata",
|
|
159
|
+
placement: projectIndexAnchorPlacement,
|
|
160
|
+
snippets: [
|
|
161
|
+
"Agent Handoff Kit template version"
|
|
162
|
+
]
|
|
154
163
|
},
|
|
155
|
-
{
|
|
156
|
-
target: "dev/rules/safety.md",
|
|
157
|
-
label: "safety pack high-risk anchors",
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
"
|
|
164
|
+
{
|
|
165
|
+
target: "dev/rules/safety.md",
|
|
166
|
+
label: "safety pack high-risk anchors",
|
|
167
|
+
placement: safetyAnchorPlacement,
|
|
168
|
+
snippets: [
|
|
169
|
+
"deleting, overwriting, moving, renaming",
|
|
170
|
+
"filesystem root, drive root",
|
|
161
171
|
"cmd /c rmdir",
|
|
162
172
|
"git reset --hard",
|
|
163
173
|
"external APIs, SDKs, CLIs",
|
|
164
174
|
"secret values"
|
|
165
175
|
]
|
|
166
176
|
},
|
|
167
|
-
{
|
|
168
|
-
target: "dev/PROJECT_DECISIONS.md",
|
|
169
|
-
label: "project decisions narrative anchors",
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
"
|
|
173
|
-
"
|
|
174
|
-
"
|
|
175
|
-
"
|
|
176
|
-
"
|
|
177
|
-
"
|
|
178
|
-
"
|
|
177
|
+
{
|
|
178
|
+
target: "dev/PROJECT_DECISIONS.md",
|
|
179
|
+
label: "project decisions narrative anchors",
|
|
180
|
+
placement: projectDecisionsAnchorPlacement,
|
|
181
|
+
snippets: [
|
|
182
|
+
"Project Decisions Log",
|
|
183
|
+
"warm 資料層",
|
|
184
|
+
"AI 開工",
|
|
185
|
+
"不需要讀",
|
|
186
|
+
"AI 在收工時自動 update",
|
|
187
|
+
"Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.",
|
|
188
|
+
"This file does not store raw build / upload / QC evidence",
|
|
189
|
+
"Evolution Timeline",
|
|
190
|
+
"Decisions Archive",
|
|
191
|
+
"Architecture Choices",
|
|
179
192
|
"Insights & Learnings"
|
|
180
193
|
]
|
|
181
194
|
},
|
|
182
|
-
{
|
|
183
|
-
target: "dev/rules/onboarding.md",
|
|
184
|
-
label: "onboarding pack core anchors",
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
"
|
|
195
|
+
{
|
|
196
|
+
target: "dev/rules/onboarding.md",
|
|
197
|
+
label: "onboarding pack core anchors",
|
|
198
|
+
placement: onboardingAnchorPlacement,
|
|
199
|
+
snippets: [
|
|
200
|
+
"Onboarding Pack",
|
|
201
|
+
"transient pack",
|
|
188
202
|
"明確 onboarding signal keywords",
|
|
189
203
|
"5-step walk-through pattern",
|
|
190
204
|
"Application Scenario Library",
|
|
@@ -197,12 +211,13 @@ const requiredAnchors = [
|
|
|
197
211
|
"Tone Discipline"
|
|
198
212
|
]
|
|
199
213
|
},
|
|
200
|
-
{
|
|
201
|
-
target: "dev/rules/integrations.md",
|
|
202
|
-
label: "integrations pack core anchors",
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
"
|
|
214
|
+
{
|
|
215
|
+
target: "dev/rules/integrations.md",
|
|
216
|
+
label: "integrations pack core anchors",
|
|
217
|
+
placement: integrationsAnchorPlacement,
|
|
218
|
+
snippets: [
|
|
219
|
+
"Integrations Pack",
|
|
220
|
+
"Connectors",
|
|
206
221
|
"MCPs",
|
|
207
222
|
"Plugins",
|
|
208
223
|
"Skills",
|
|
@@ -244,10 +259,11 @@ const schemaChecks = [
|
|
|
244
259
|
section("state-reconciliation-check", "State Reconciliation Check"),
|
|
245
260
|
section("handoff-sufficiency-check", "Handoff Sufficiency Check"),
|
|
246
261
|
section("next-session-opening-message", "Next Session Opening Message"),
|
|
247
|
-
marker("field", "stale-snapshots-left", "Stale snapshots left in this handoff"),
|
|
248
|
-
marker("field", "lifecycle-conflicts-resolved", "Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified"),
|
|
249
|
-
marker("field", "
|
|
250
|
-
marker("field", "
|
|
262
|
+
marker("field", "stale-snapshots-left", "Stale snapshots left in this handoff"),
|
|
263
|
+
marker("field", "lifecycle-conflicts-resolved", "Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified"),
|
|
264
|
+
marker("field", "persistence-routing-checked", "Persistence routing checked"),
|
|
265
|
+
marker("field", "opening-message-matches-current-state", "Opening message matches current state"),
|
|
266
|
+
marker("field", "state-sections-rewritten-or-confirmed", "State sections rewritten or confirmed current"),
|
|
251
267
|
marker("field", "user-intent", "User intent:"),
|
|
252
268
|
marker("field", "task-essence", "Task essence:"),
|
|
253
269
|
marker("field", "success-criteria", "Success criteria:")
|
|
@@ -282,9 +298,10 @@ const schemaChecks = [
|
|
|
282
298
|
includes("- **ID:**"),
|
|
283
299
|
includes("- **Summary:**"),
|
|
284
300
|
includes("- **Changed:**"),
|
|
285
|
-
includes("- **Done:**"),
|
|
286
|
-
includes("- **QC:**"),
|
|
287
|
-
includes("- **
|
|
301
|
+
includes("- **Done:**"),
|
|
302
|
+
includes("- **QC:**"),
|
|
303
|
+
includes("- **Evidence disposition:**"),
|
|
304
|
+
includes("- **Sync:**"),
|
|
288
305
|
includes("- **Pending:**"),
|
|
289
306
|
includes("- **Risks:**"),
|
|
290
307
|
includes("- **Log maintenance:**")
|
|
@@ -353,17 +370,18 @@ const schemaChecks = [
|
|
|
353
370
|
includes("dev/rules/integrations.md")
|
|
354
371
|
]
|
|
355
372
|
},
|
|
356
|
-
{
|
|
357
|
-
target: "dev/PROJECT_DECISIONS.md",
|
|
358
|
-
label: "project decisions log structure",
|
|
359
|
-
checks: [
|
|
360
|
-
heading("Evolution Timeline"),
|
|
361
|
-
heading("Decisions Archive"),
|
|
362
|
-
heading("Architecture Choices"),
|
|
363
|
-
heading("Insights & Learnings"),
|
|
364
|
-
includes("
|
|
365
|
-
|
|
366
|
-
|
|
373
|
+
{
|
|
374
|
+
target: "dev/PROJECT_DECISIONS.md",
|
|
375
|
+
label: "project decisions log structure",
|
|
376
|
+
checks: [
|
|
377
|
+
heading("Evolution Timeline"),
|
|
378
|
+
heading("Decisions Archive"),
|
|
379
|
+
heading("Architecture Choices"),
|
|
380
|
+
heading("Insights & Learnings"),
|
|
381
|
+
includes("Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>."),
|
|
382
|
+
includes("(empty)")
|
|
383
|
+
]
|
|
384
|
+
},
|
|
367
385
|
{
|
|
368
386
|
target: "dev/rules/onboarding.md",
|
|
369
387
|
label: "onboarding pack structure (新手引導包)",
|
|
@@ -694,18 +712,52 @@ async function runDoctor(root, version, options = {}) {
|
|
|
694
712
|
}
|
|
695
713
|
}
|
|
696
714
|
|
|
697
|
-
if (schemaFailures.length > 0) {
|
|
698
|
-
printDoctorSummary(version, root, "needs-fix", {
|
|
699
|
-
checked: rows.length + anchorRows.length + schemaRows.length,
|
|
700
|
-
failedKind: "schema checks",
|
|
715
|
+
if (schemaFailures.length > 0) {
|
|
716
|
+
printDoctorSummary(version, root, "needs-fix", {
|
|
717
|
+
checked: rows.length + anchorRows.length + schemaRows.length,
|
|
718
|
+
failedKind: "schema checks",
|
|
701
719
|
failedCount: schemaFailures.length,
|
|
702
720
|
nextStep: "把這段 doctor 輸出貼給 AI,請它先修交接結構,不要直接重裝覆蓋。"
|
|
703
721
|
});
|
|
704
722
|
process.exitCode = 1;
|
|
705
|
-
return "failed";
|
|
706
|
-
}
|
|
707
|
-
|
|
708
|
-
const
|
|
723
|
+
return "failed";
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
const researchTraceResult = await checkResearchDecisionTrace(root);
|
|
727
|
+
console.log(`\nresearch decision trace checks: ${researchTraceResult.checked}`);
|
|
728
|
+
console.log(`${researchTraceResult.ok ? "ok" : "missing"} dev/PROJECT_DECISIONS.md (research-derived decision evidence chains)`);
|
|
729
|
+
if (!researchTraceResult.ok) {
|
|
730
|
+
for (const finding of researchTraceResult.findings) {
|
|
731
|
+
console.log(` missing: ${finding}`);
|
|
732
|
+
}
|
|
733
|
+
printDoctorSummary(version, root, "needs-fix", {
|
|
734
|
+
checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked,
|
|
735
|
+
failedKind: "research decision trace checks",
|
|
736
|
+
failedCount: researchTraceResult.findings.length,
|
|
737
|
+
nextStep: "把 research-derived decision 的 Evidence chain 補齊,並確認 Source=source:<id> token 已登記在 dev/PROJECT_INDEX.md 的 Fact Base 或 External Sources。"
|
|
738
|
+
});
|
|
739
|
+
process.exitCode = 1;
|
|
740
|
+
return "failed";
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
const temperatureResult = await checkHandoffTemperatureBoundary(root);
|
|
744
|
+
console.log(`\nhandoff temperature boundary checks: ${temperatureResult.checked}`);
|
|
745
|
+
console.log(`${temperatureResult.ok ? "ok" : "missing"} dev/SESSION_HANDOFF.md / START_NEXT_SESSION_PROMPT.txt (current-state evidence boundary)`);
|
|
746
|
+
if (!temperatureResult.ok) {
|
|
747
|
+
for (const finding of temperatureResult.findings) {
|
|
748
|
+
console.log(` missing: ${finding}`);
|
|
749
|
+
}
|
|
750
|
+
printDoctorSummary(version, root, "needs-fix", {
|
|
751
|
+
checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked + temperatureResult.checked,
|
|
752
|
+
failedKind: "handoff temperature boundary checks",
|
|
753
|
+
failedCount: temperatureResult.findings.length,
|
|
754
|
+
nextStep: "把一次性驗收證據、舊版本狀態、source token 或 Evidence chain 從 Durable Anchors / Next Priorities / opening message 移回 SESSION_LOG、PROJECT_INDEX 或 PROJECT_DECISIONS。"
|
|
755
|
+
});
|
|
756
|
+
process.exitCode = 1;
|
|
757
|
+
return "failed";
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
const mirrorRows = await checkPromptMirror(root);
|
|
709
761
|
const mirrorBlockingFailures = mirrorRows.filter((row) => !row.ok && row.reason !== "convenience copy differs from dev/SESSION_HANDOFF.md");
|
|
710
762
|
const mirrorWarnings = mirrorRows.filter((row) => !row.ok && row.reason === "convenience copy differs from dev/SESSION_HANDOFF.md");
|
|
711
763
|
console.log(`\nprompt mirror checks: ${mirrorRows.length}`);
|
|
@@ -761,9 +813,9 @@ async function runDoctor(root, version, options = {}) {
|
|
|
761
813
|
? "檢查已通過。START_NEXT_SESSION_PROMPT.txt 只是下次開工便利副本;session 進行中不用手動重生,收工 closeout 時 AI 會從 dev/SESSION_HANDOFF.md 重生。"
|
|
762
814
|
: null;
|
|
763
815
|
|
|
764
|
-
const overallHealthy = credentialResult.ok;
|
|
765
|
-
printDoctorSummary(version, root, overallHealthy ? "healthy" : "needs-attention", {
|
|
766
|
-
checked: rows.length + anchorRows.length + schemaRows.length + mirrorRows.length + 2,
|
|
816
|
+
const overallHealthy = credentialResult.ok;
|
|
817
|
+
printDoctorSummary(version, root, overallHealthy ? "healthy" : "needs-attention", {
|
|
818
|
+
checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked + temperatureResult.checked + mirrorRows.length + 2,
|
|
767
819
|
failedKind: !credentialResult.ok ? "credential leak" : null,
|
|
768
820
|
failedCount: !credentialResult.ok ? credentialResult.findings.length : 0,
|
|
769
821
|
warningKind: mirrorWarnings.length > 0 ? "prompt mirror warning" : null,
|
|
@@ -774,9 +826,140 @@ async function runDoctor(root, version, options = {}) {
|
|
|
774
826
|
? versionNextStep ?? promptMirrorNextStep ?? onboardingNextStep ?? "檢查已通過。繼續使用你原本的 AI 開工方式;如剛完成一個任務,記得在 AI 對話輸入「收工」保存交接。"
|
|
775
827
|
: "繼續使用;下次 closeout 時 AI 應自動執行 SESSION_LOG N 規則推進(見上面 warn 行)。如未動請要求 AI 重做 closeout。"
|
|
776
828
|
});
|
|
777
|
-
return overallHealthy ? "passed" : "failed";
|
|
778
|
-
}
|
|
779
|
-
|
|
829
|
+
return overallHealthy ? "passed" : "failed";
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
async function checkResearchDecisionTrace(root) {
|
|
833
|
+
const decisionsPath = path.join(root, "dev/PROJECT_DECISIONS.md");
|
|
834
|
+
const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
|
|
835
|
+
let decisionsText = "";
|
|
836
|
+
let indexText = "";
|
|
837
|
+
try {
|
|
838
|
+
decisionsText = await readFile(decisionsPath, "utf8");
|
|
839
|
+
indexText = await readFile(indexPath, "utf8");
|
|
840
|
+
} catch {
|
|
841
|
+
return { ok: false, checked: 1, findings: ["dev/PROJECT_DECISIONS.md or dev/PROJECT_INDEX.md unreadable"] };
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
const findings = [];
|
|
845
|
+
const sourceTokenPattern = /\bsource:[A-Za-z0-9._-]+\b/g;
|
|
846
|
+
const blocks = markdownListBlocks(stripFencedCodeBlocks(decisionsText));
|
|
847
|
+
const researchBlocks = blocks.filter((block) => /\bresearch-derived\b/i.test(block) || /Evidence chain:/i.test(block));
|
|
848
|
+
|
|
849
|
+
researchBlocks.forEach((block, index) => {
|
|
850
|
+
const label = `research-derived decision #${index + 1}`;
|
|
851
|
+
if (!/Evidence chain:/i.test(block)) {
|
|
852
|
+
findings.push(`${label} missing Evidence chain`);
|
|
853
|
+
}
|
|
854
|
+
const tokens = [...block.matchAll(sourceTokenPattern)].map((match) => match[0]);
|
|
855
|
+
if (tokens.length === 0) {
|
|
856
|
+
findings.push(`${label} missing source:<id> token`);
|
|
857
|
+
}
|
|
858
|
+
for (const token of tokens) {
|
|
859
|
+
if (!indexText.includes(token)) {
|
|
860
|
+
findings.push(`${label} references ${token}, but dev/PROJECT_INDEX.md does not contain that token`);
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
});
|
|
864
|
+
|
|
865
|
+
return { ok: findings.length === 0, checked: 1, findings };
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
function stripFencedCodeBlocks(text) {
|
|
869
|
+
return text.replace(/```[\s\S]*?```/g, "");
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
function markdownListBlocks(text) {
|
|
873
|
+
const blocks = [];
|
|
874
|
+
let current = [];
|
|
875
|
+
for (const line of text.split(/\r?\n/)) {
|
|
876
|
+
if (/^\s*[-*]\s+/.test(line)) {
|
|
877
|
+
if (current.length > 0) blocks.push(current.join("\n"));
|
|
878
|
+
current = [line];
|
|
879
|
+
} else if (current.length > 0 && (/^\s{2,}\S/.test(line) || /^\s*$/.test(line))) {
|
|
880
|
+
current.push(line);
|
|
881
|
+
} else if (current.length > 0) {
|
|
882
|
+
blocks.push(current.join("\n"));
|
|
883
|
+
current = [];
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
if (current.length > 0) blocks.push(current.join("\n"));
|
|
887
|
+
return blocks;
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
async function checkHandoffTemperatureBoundary(root) {
|
|
891
|
+
const findings = [];
|
|
892
|
+
const sections = [];
|
|
893
|
+
let handoffText = "";
|
|
894
|
+
|
|
895
|
+
try {
|
|
896
|
+
handoffText = await readFile(path.join(root, "dev/SESSION_HANDOFF.md"), "utf8");
|
|
897
|
+
} catch {
|
|
898
|
+
return { ok: false, checked: 1, findings: ["dev/SESSION_HANDOFF.md unreadable"] };
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
sections.push(
|
|
902
|
+
{ label: "Durable Anchors", text: extractHandoffSectionText(handoffText, "durable-anchors", "Durable Anchors") },
|
|
903
|
+
{ label: "Next Priorities", text: extractHandoffSectionText(handoffText, "next-priorities", "Next Priorities") },
|
|
904
|
+
{ label: "Next Session Opening Message", text: extractHandoffSectionText(handoffText, "next-session-opening-message", "Next Session Opening Message") }
|
|
905
|
+
);
|
|
906
|
+
|
|
907
|
+
const requiredReading = extractHandoffSectionText(handoffText, "next-task-required-reading", "Next Task Required Reading");
|
|
908
|
+
sections.push({ label: "Next Task Required Reading", text: requiredReading, allowSourceTokens: true });
|
|
909
|
+
|
|
910
|
+
try {
|
|
911
|
+
const promptText = await readFile(path.join(root, "START_NEXT_SESSION_PROMPT.txt"), "utf8");
|
|
912
|
+
sections.push({ label: "START_NEXT_SESSION_PROMPT.txt", text: promptText });
|
|
913
|
+
} catch {
|
|
914
|
+
// Missing prompt mirror is handled by prompt mirror checks; do not duplicate the failure here.
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
const evidencePatterns = [
|
|
918
|
+
{ pattern: /post-publish artifact smoke/i, label: "post-publish artifact smoke evidence" },
|
|
919
|
+
{ pattern: /PASS\s+7\/7/i, label: "historical PASS count" },
|
|
920
|
+
{ pattern: /\bfileCount\b/i, label: "published artifact fileCount evidence" },
|
|
921
|
+
{ pattern: /\brelease source\b/i, label: "release source evidence" },
|
|
922
|
+
{ pattern: /Cross-mind evidence/i, label: "cross-agent review evidence" },
|
|
923
|
+
{ pattern: /Evidence chain:/i, label: "research evidence chain" },
|
|
924
|
+
{ pattern: /\bnpm latest\s+(?:is|=|v?\d)/i, label: "historical npm latest state" },
|
|
925
|
+
{ pattern: /GitHub Release\s+(?:metadata|published|view|`?v?\d)/i, label: "historical GitHub Release state" }
|
|
926
|
+
];
|
|
927
|
+
const sourceTokenPattern = /\bsource:[A-Za-z0-9._-]+\b/;
|
|
928
|
+
|
|
929
|
+
for (const section of sections) {
|
|
930
|
+
if (!section.text) continue;
|
|
931
|
+
for (const rule of evidencePatterns) {
|
|
932
|
+
if (rule.pattern.test(section.text)) {
|
|
933
|
+
findings.push(`${section.label} contains ${rule.label}; keep it in trace evidence unless it still affects the next action`);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
if (!section.allowSourceTokens && sourceTokenPattern.test(section.text)) {
|
|
937
|
+
findings.push(`${section.label} contains source:<id>; keep source tokens in PROJECT_INDEX / PROJECT_DECISIONS, not hot startup state`);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
return { ok: findings.length === 0, checked: 1, findings };
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
function extractHandoffSectionText(text, id, headingText) {
|
|
945
|
+
const marker = `<!-- ack:section:${id} -->`;
|
|
946
|
+
const markerStart = text.indexOf(marker);
|
|
947
|
+
if (markerStart >= 0) {
|
|
948
|
+
const afterMarker = markerStart + marker.length;
|
|
949
|
+
const nextMarker = text.indexOf("<!-- ack:section:", afterMarker);
|
|
950
|
+
return text.slice(afterMarker, nextMarker >= 0 ? nextMarker : text.length);
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
const headingPattern = new RegExp(`^##\\s+${escapeRegExp(headingText)}\\s*$`, "m");
|
|
954
|
+
const headingMatch = headingPattern.exec(text);
|
|
955
|
+
if (!headingMatch) return "";
|
|
956
|
+
const start = headingMatch.index + headingMatch[0].length;
|
|
957
|
+
const nextHeading = /\n##\s+/g;
|
|
958
|
+
nextHeading.lastIndex = start;
|
|
959
|
+
const nextMatch = nextHeading.exec(text);
|
|
960
|
+
return text.slice(start, nextMatch ? nextMatch.index : text.length);
|
|
961
|
+
}
|
|
962
|
+
|
|
780
963
|
function getFirstUseNextStep(root, lastCloseout) {
|
|
781
964
|
if (lastCloseout.date) return null;
|
|
782
965
|
return `檢查已通過。下一步不要再留在終端機;打開能讀寫此資料夾的 AI agent。若 AI 已在此資料夾內,輸入 Start Agent Handoff 或「開工」;若 AI 還未指向此資料夾,才貼:${startupPathBootstrapPrompt(root)}`;
|
|
@@ -838,10 +1021,10 @@ function printDoctorSummary(version, root, mode, details) {
|
|
|
838
1021
|
} else {
|
|
839
1022
|
console.log("✅ 檢查通過:必要文件存在,基本結構完整,下次開工提示副本已與 handoff 一致。");
|
|
840
1023
|
}
|
|
841
|
-
} else {
|
|
842
|
-
console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
|
|
843
|
-
console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : "下次開工提示副本與 handoff 真源不同。"}`);
|
|
844
|
-
}
|
|
1024
|
+
} else {
|
|
1025
|
+
console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
|
|
1026
|
+
console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : details.failedKind === "research decision trace checks" ? "研究導向決策缺少可追溯來源鏈。" : details.failedKind === "handoff temperature boundary checks" ? "當前交接內容混入一次性或歷史證據。" : "下次開工提示副本與 handoff 真源不同。"}`);
|
|
1027
|
+
}
|
|
845
1028
|
console.log("");
|
|
846
1029
|
console.log(`📦 版本:v${version}`);
|
|
847
1030
|
console.log(`🩺 模式:${mode}`);
|
|
@@ -1001,9 +1184,9 @@ function extractSectionText(text, markerId, headingTitle) {
|
|
|
1001
1184
|
return text.slice(start, nextHeading ? start + nextHeading.index : text.length);
|
|
1002
1185
|
}
|
|
1003
1186
|
|
|
1004
|
-
async function checkRequiredAnchors(root) {
|
|
1005
|
-
const rows = [];
|
|
1006
|
-
for (const rule of requiredAnchors) {
|
|
1187
|
+
async function checkRequiredAnchors(root) {
|
|
1188
|
+
const rows = [];
|
|
1189
|
+
for (const rule of requiredAnchors) {
|
|
1007
1190
|
const filePath = path.join(root, rule.target);
|
|
1008
1191
|
let text = "";
|
|
1009
1192
|
try {
|
|
@@ -1013,13 +1196,15 @@ async function checkRequiredAnchors(root) {
|
|
|
1013
1196
|
continue;
|
|
1014
1197
|
}
|
|
1015
1198
|
|
|
1016
|
-
// Report which specific anchor snippets are absent
|
|
1017
|
-
//
|
|
1018
|
-
|
|
1019
|
-
const missing =
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1199
|
+
// Report which specific anchor snippets are absent or semantically misplaced,
|
|
1200
|
+
// not just pass/fail. A naked snippet at file tail must not make doctor green.
|
|
1201
|
+
const failures = requiredAnchorFailures(rule, text);
|
|
1202
|
+
const missing = failures.map((failure) => failure.kind === "missing"
|
|
1203
|
+
? failure.snippet
|
|
1204
|
+
: `misplaced: ${failure.snippet}`);
|
|
1205
|
+
rows.push({
|
|
1206
|
+
target: rule.target,
|
|
1207
|
+
label: rule.label,
|
|
1023
1208
|
ok: missing.length === 0,
|
|
1024
1209
|
missing
|
|
1025
1210
|
});
|
|
@@ -1220,12 +1405,12 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
|
|
|
1220
1405
|
// content and any user customization preserved. Step 1 micro-question additions to Scenarios A-E
|
|
1221
1406
|
// are NOT auto-migrated (user-customizable inline sample wording, not anchor-enforced); users get
|
|
1222
1407
|
// 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
|
|
1226
|
-
const scenarioFBlock = sourceScenarioFMatch[1];
|
|
1227
|
-
return {
|
|
1228
|
-
...base,
|
|
1408
|
+
if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario F. 審視已裝外部工具")) {
|
|
1409
|
+
const sourceScenarioFMatch = sourceText.match(/(### Scenario F\. 審視已裝外部工具[\s\S]*?)(?=## Cross-reference to guide\.html)/);
|
|
1410
|
+
if (sourceScenarioFMatch && hasTrustedOnboardingScenarioLibrary(targetText)) {
|
|
1411
|
+
const scenarioFBlock = sourceScenarioFMatch[1];
|
|
1412
|
+
return {
|
|
1413
|
+
...base,
|
|
1229
1414
|
action: "merge",
|
|
1230
1415
|
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
1416
|
mergedText: targetText.replace("## Cross-reference to guide.html", scenarioFBlock + "## Cross-reference to guide.html")
|
|
@@ -1246,9 +1431,9 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
|
|
|
1246
1431
|
// v0.3.6+: SESSION_HANDOFF.md gains a non-destructive lifecycle consistency
|
|
1247
1432
|
// field. Existing handoff content stays intact; only the missing field and
|
|
1248
1433
|
// rule note are inserted around stable ack markers.
|
|
1249
|
-
if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:lifecycle-conflicts-resolved")) {
|
|
1250
|
-
const mergedHandoff = mergeHandoffLifecycleField(targetText);
|
|
1251
|
-
if (!mergedHandoff) {
|
|
1434
|
+
if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:lifecycle-conflicts-resolved")) {
|
|
1435
|
+
const mergedHandoff = mergeHandoffLifecycleField(targetText);
|
|
1436
|
+
if (!mergedHandoff) {
|
|
1252
1437
|
return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add lifecycle consistency field" };
|
|
1253
1438
|
}
|
|
1254
1439
|
return {
|
|
@@ -1258,6 +1443,18 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
|
|
|
1258
1443
|
mergedText: mergedHandoff
|
|
1259
1444
|
};
|
|
1260
1445
|
}
|
|
1446
|
+
if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:persistence-routing-checked")) {
|
|
1447
|
+
const mergedHandoff = mergeHandoffPersistenceRoutingField(targetText);
|
|
1448
|
+
if (!mergedHandoff) {
|
|
1449
|
+
return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add persistence routing field" };
|
|
1450
|
+
}
|
|
1451
|
+
return {
|
|
1452
|
+
...base,
|
|
1453
|
+
action: "merge",
|
|
1454
|
+
reason: "insert persistence routing field into State Reconciliation Check (one-time evidence must not drive next-session state)",
|
|
1455
|
+
mergedText: mergedHandoff
|
|
1456
|
+
};
|
|
1457
|
+
}
|
|
1261
1458
|
if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && isUpgradeFromOlderTemplate(context)) {
|
|
1262
1459
|
const lifecycleValue = fieldValueAfterMarker(targetText, "lifecycle-conflicts-resolved");
|
|
1263
1460
|
if (isPlaceholderLifecycleFieldValue(lifecycleValue) && hasSubstantiveHandoffState(targetText)) {
|
|
@@ -1273,10 +1470,47 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
|
|
|
1273
1470
|
};
|
|
1274
1471
|
}
|
|
1275
1472
|
}
|
|
1473
|
+
if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && hasMissingRequiredAnchor(targetRel, targetText, "handoff log archive continuity")) {
|
|
1474
|
+
const mergedHandoff = mergeHandoffArchiveContinuityRule(targetText, sourceText);
|
|
1475
|
+
if (!mergedHandoff) {
|
|
1476
|
+
return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md handoff sufficiency markers were changed; manual merge required to add archive continuity rule" };
|
|
1477
|
+
}
|
|
1478
|
+
return {
|
|
1479
|
+
...base,
|
|
1480
|
+
action: "merge",
|
|
1481
|
+
reason: "insert handoff archive continuity rule so upgrade self-check can pass without requiring manual anchor repair",
|
|
1482
|
+
mergedText: mergedHandoff
|
|
1483
|
+
};
|
|
1484
|
+
}
|
|
1485
|
+
if (targetRel === "dev/SESSION_LOG.md" && command === "upgrade" && !targetText.includes("- **Evidence disposition:**")) {
|
|
1486
|
+
const mergedLog = mergeSessionLogEvidenceDispositionField(targetText);
|
|
1487
|
+
if (!mergedLog) {
|
|
1488
|
+
return { ...base, action: "conflict", reason: "SESSION_LOG.md entry template markers were changed; manual merge required to add evidence disposition field" };
|
|
1489
|
+
}
|
|
1490
|
+
return {
|
|
1491
|
+
...base,
|
|
1492
|
+
action: "merge",
|
|
1493
|
+
reason: "insert SESSION_LOG evidence disposition field into Entry Template",
|
|
1494
|
+
mergedText: mergedLog
|
|
1495
|
+
};
|
|
1496
|
+
}
|
|
1497
|
+
if (command === "upgrade" && hasAnchorRepairMarkerDrift(targetText)) {
|
|
1498
|
+
return { ...base, action: "conflict", reason: "legacy anchor repair block markers are incomplete or obsolete; manual semantic cleanup required before upgrade can safely continue" };
|
|
1499
|
+
}
|
|
1500
|
+
if (command === "upgrade" && hasMisplacedRequiredAnchor(targetRel, targetText)) {
|
|
1501
|
+
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" };
|
|
1502
|
+
}
|
|
1503
|
+
if (command === "upgrade" && hasMissingRequiredAnchor(targetRel, targetText)) {
|
|
1504
|
+
const semanticRepair = mergeMissingRequiredAnchorsSemantically(targetRel, targetText, sourceText);
|
|
1505
|
+
if (semanticRepair) {
|
|
1506
|
+
return { ...base, ...semanticRepair };
|
|
1507
|
+
}
|
|
1508
|
+
return { ...base, action: "conflict", reason: "required Kit anchors are missing but no safe semantic repair path exists; upgrade stopped without appending naked anchor text" };
|
|
1509
|
+
}
|
|
1276
1510
|
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
|
-
}
|
|
1511
|
+
if (!targetText.includes("AGENTS.md")) {
|
|
1512
|
+
return { ...base, action: "conflict", reason: "existing bridge does not route to AGENTS.md" };
|
|
1513
|
+
}
|
|
1280
1514
|
if (looksLikeExpandedKitBridge(targetRel, targetText)) {
|
|
1281
1515
|
return {
|
|
1282
1516
|
...base,
|
|
@@ -1312,7 +1546,7 @@ function looksLikeExpandedKitBridge(targetRel, text) {
|
|
|
1312
1546
|
return false;
|
|
1313
1547
|
}
|
|
1314
1548
|
|
|
1315
|
-
function mergeOnboardingScenarioALabel(targetText) {
|
|
1549
|
+
function mergeOnboardingScenarioALabel(targetText) {
|
|
1316
1550
|
let merged = targetText;
|
|
1317
1551
|
merged = merged.replace(
|
|
1318
1552
|
/\*\*A\. 寫 \/ 改代碼項目\*\* —— 你有一個(?: project 的 codebase|程式項目)想長期維護/g,
|
|
@@ -1322,27 +1556,434 @@ function mergeOnboardingScenarioALabel(targetText) {
|
|
|
1322
1556
|
/### Scenario A\. 寫 \/ 改代碼項目/g,
|
|
1323
1557
|
"### Scenario A. 建構系統 / 工具 / 平台 / 網站或應用"
|
|
1324
1558
|
);
|
|
1325
|
-
return merged;
|
|
1326
|
-
}
|
|
1327
|
-
|
|
1559
|
+
return merged;
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
function hasTrustedOnboardingScenarioLibrary(text) {
|
|
1563
|
+
const bounds = textSectionBounds(text, "## Application Scenario Library", "## Cross-reference to guide.html");
|
|
1564
|
+
if (!bounds) return false;
|
|
1565
|
+
const section = text.slice(bounds.start, bounds.end);
|
|
1566
|
+
return [
|
|
1567
|
+
"### Scenario A.",
|
|
1568
|
+
"### Scenario B.",
|
|
1569
|
+
"### Scenario C.",
|
|
1570
|
+
"### Scenario D.",
|
|
1571
|
+
"### Scenario E."
|
|
1572
|
+
].every((headingText) => section.includes(headingText));
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
function hasMissingRequiredAnchor(targetRel, targetText, label = null) {
|
|
1576
|
+
return requiredAnchors
|
|
1577
|
+
.filter((rule) => rule.target === targetRel && (!label || rule.label === label))
|
|
1578
|
+
.some((rule) => requiredAnchorFailures(rule, targetText).some((failure) => failure.kind === "missing"));
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
function hasMisplacedRequiredAnchor(targetRel, targetText, label = null) {
|
|
1582
|
+
return requiredAnchors
|
|
1583
|
+
.filter((rule) => rule.target === targetRel && (!label || rule.label === label))
|
|
1584
|
+
.some((rule) => requiredAnchorFailures(rule, targetText).some((failure) => failure.kind === "misplaced"));
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
function hasAnchorRepairMarkerDrift(text) {
|
|
1588
|
+
const start = countText(text, "<!-- BEGIN Agent Handoff Kit anchor repair -->");
|
|
1589
|
+
const end = countText(text, "<!-- END Agent Handoff Kit anchor repair -->");
|
|
1590
|
+
return start > 0 || end > 0;
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
function countText(text, needle) {
|
|
1594
|
+
return text.split(needle).length - 1;
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
function countRegex(text, pattern) {
|
|
1598
|
+
const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
|
|
1599
|
+
return [...text.matchAll(new RegExp(pattern.source, flags))].length;
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
function missingRequiredAnchorSnippets(targetRel, targetText) {
|
|
1603
|
+
return [...new Set(requiredAnchors
|
|
1604
|
+
.filter((rule) => rule.target === targetRel)
|
|
1605
|
+
.flatMap((rule) => requiredAnchorFailures(rule, targetText)
|
|
1606
|
+
.filter((failure) => failure.kind === "missing")
|
|
1607
|
+
.map((failure) => failure.snippet)))];
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
function requiredAnchorFailures(rule, text) {
|
|
1611
|
+
return rule.snippets.flatMap((snippet) => {
|
|
1612
|
+
if (!text.includes(snippet)) return [{ kind: "missing", snippet }];
|
|
1613
|
+
if (!isRequiredAnchorSemanticallyPlaced(rule, snippet, text)) return [{ kind: "misplaced", snippet }];
|
|
1614
|
+
return [];
|
|
1615
|
+
});
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
function isRequiredAnchorSemanticallyPlaced(rule, snippet, text) {
|
|
1619
|
+
return rule.placement ? rule.placement(snippet, text) : true;
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
function sessionLogAnchorPlacement(snippet, text) {
|
|
1623
|
+
if (snippet === "## Entry Template") return /^## Entry Template\s*$/m.test(text);
|
|
1624
|
+
const preamble = [
|
|
1625
|
+
"Record what actually happened in the session",
|
|
1626
|
+
"kept, summarized, or archived",
|
|
1627
|
+
"Do not remove validation evidence",
|
|
1628
|
+
"latest opening message",
|
|
1629
|
+
"not current state"
|
|
1630
|
+
];
|
|
1631
|
+
if (preamble.includes(snippet)) return snippetAppearsBeforeHeading(text, snippet, "## Entry Template");
|
|
1632
|
+
return snippetAppearsAfterHeading(text, snippet, "## Entry Template");
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
function handoffContinuityAnchorPlacement(snippet, text) {
|
|
1636
|
+
const suffixContinuityAnchors = [
|
|
1637
|
+
"without searching old log history",
|
|
1638
|
+
"SESSION_LOG.md` carries recent evidence",
|
|
1639
|
+
"do not create an archive directory by default"
|
|
1640
|
+
];
|
|
1641
|
+
if (suffixContinuityAnchors.includes(snippet)) {
|
|
1642
|
+
return snippetAppearsInSemanticSection(text, snippet, "handoff-sufficiency-check", "Handoff Sufficiency Check", "next-session-opening-message", "Next Session Opening Message");
|
|
1643
|
+
}
|
|
1644
|
+
return true;
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
function projectIndexAnchorPlacement(snippet, text) {
|
|
1648
|
+
if (snippet === "Agent Handoff Kit template version") return Boolean(projectIndexTemplateVersion(text));
|
|
1649
|
+
return true;
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
function safetyAnchorPlacement(snippet, text) {
|
|
1653
|
+
return safetyAnchorHasTrustedRuleShape(text, snippet);
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
function projectDecisionsAnchorPlacement(snippet, text) {
|
|
1657
|
+
const preamble = [
|
|
1658
|
+
"Project Decisions Log",
|
|
1659
|
+
"warm 資料層",
|
|
1660
|
+
"AI 開工",
|
|
1661
|
+
"不需要讀",
|
|
1662
|
+
"AI 在收工時自動 update",
|
|
1663
|
+
"Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.",
|
|
1664
|
+
"This file does not store raw build / upload / QC evidence"
|
|
1665
|
+
];
|
|
1666
|
+
if (preamble.includes(snippet)) return snippetAppearsBeforeHeading(text, snippet, "## Evolution Timeline");
|
|
1667
|
+
return true;
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
function onboardingAnchorPlacement(snippet, text) {
|
|
1671
|
+
if (snippet === "Application Scenario Library") {
|
|
1672
|
+
return Boolean(textSectionBounds(text, "## Application Scenario Library", "## Cross-reference to guide.html"));
|
|
1673
|
+
}
|
|
1674
|
+
if (/^Scenario [A-F]\./.test(snippet)) {
|
|
1675
|
+
return snippetAppearsBetweenHeadings(text, snippet, "## Application Scenario Library", "## Cross-reference to guide.html");
|
|
1676
|
+
}
|
|
1677
|
+
return true;
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
function integrationsAnchorPlacement(snippet, text) {
|
|
1681
|
+
if (snippet === "機密分離原則" || snippet === "Source-of-truth Architecture" || snippet === "Cross-session Lifecycle") {
|
|
1682
|
+
return snippetAppearsBetweenHeadings(text, snippet, "## Discipline", "## Rules");
|
|
1683
|
+
}
|
|
1684
|
+
if (snippet === "Connector-first default") {
|
|
1685
|
+
return snippetAppearsBetweenHeadings(text, snippet, "## Rules", "## Checks");
|
|
1686
|
+
}
|
|
1687
|
+
if (snippet === "Anti-pattern") return text.includes("## Anti-pattern(不要做的事)");
|
|
1688
|
+
return true;
|
|
1689
|
+
}
|
|
1690
|
+
|
|
1691
|
+
function snippetAppearsBeforeHeading(text, snippet, headingText) {
|
|
1692
|
+
const headingIndex = text.indexOf(headingText);
|
|
1693
|
+
if (headingIndex < 0) return false;
|
|
1694
|
+
return text.slice(0, headingIndex).includes(snippet);
|
|
1695
|
+
}
|
|
1696
|
+
|
|
1697
|
+
function snippetAppearsAfterHeading(text, snippet, headingText) {
|
|
1698
|
+
const headingIndex = text.indexOf(headingText);
|
|
1699
|
+
if (headingIndex < 0) return false;
|
|
1700
|
+
return text.slice(headingIndex + headingText.length).includes(snippet);
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
function snippetAppearsBetweenHeadings(text, snippet, startHeading, endHeading) {
|
|
1704
|
+
const startIndex = text.indexOf(startHeading);
|
|
1705
|
+
const endIndex = text.indexOf(endHeading);
|
|
1706
|
+
if (startIndex < 0 || endIndex < 0 || endIndex <= startIndex) return false;
|
|
1707
|
+
return text.slice(startIndex + startHeading.length, endIndex).includes(snippet);
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
function snippetAppearsInSemanticSection(text, snippet, startId, startHeading, endId, endHeading) {
|
|
1711
|
+
const startMarker = `<!-- ack:section:${startId} -->`;
|
|
1712
|
+
const endMarker = `<!-- ack:section:${endId} -->`;
|
|
1713
|
+
const markerStart = text.indexOf(startMarker);
|
|
1714
|
+
const markerEnd = text.indexOf(endMarker, markerStart + startMarker.length);
|
|
1715
|
+
if (markerStart >= 0 && markerEnd > markerStart) {
|
|
1716
|
+
return text.slice(markerStart + startMarker.length, markerEnd).includes(snippet);
|
|
1717
|
+
}
|
|
1718
|
+
return snippetAppearsBetweenHeadings(text, snippet, `## ${startHeading}`, `## ${endHeading}`);
|
|
1719
|
+
}
|
|
1720
|
+
|
|
1721
|
+
const semanticAnchorRepairStrategies = {
|
|
1722
|
+
"dev/PROJECT_INDEX.md": (targetText, sourceText) => {
|
|
1723
|
+
const mergedIndex = mergeProjectIndexTemplateVersionRow(targetText, sourceText);
|
|
1724
|
+
return mergedIndex ? {
|
|
1725
|
+
action: "merge",
|
|
1726
|
+
reason: "restore PROJECT_INDEX template version metadata row in ## Stack table",
|
|
1727
|
+
mergedText: mergedIndex
|
|
1728
|
+
} : null;
|
|
1729
|
+
},
|
|
1730
|
+
"dev/SESSION_LOG.md": (targetText, sourceText) => {
|
|
1731
|
+
const mergedLog = insertSourcePreambleBeforeHeading(targetText, sourceText, "## Entry Template");
|
|
1732
|
+
return mergedLog ? {
|
|
1733
|
+
action: "merge",
|
|
1734
|
+
reason: "restore SESSION_LOG Kit preamble before ## Entry Template",
|
|
1735
|
+
mergedText: mergedLog
|
|
1736
|
+
} : null;
|
|
1737
|
+
},
|
|
1738
|
+
"dev/PROJECT_DECISIONS.md": (targetText, sourceText, missing) => {
|
|
1739
|
+
const mergedDecisions = mergeProjectDecisionsPreamble(targetText, sourceText, missing);
|
|
1740
|
+
return mergedDecisions ? {
|
|
1741
|
+
action: "merge",
|
|
1742
|
+
reason: "restore PROJECT_DECISIONS onboarding preamble before ## Evolution Timeline",
|
|
1743
|
+
mergedText: mergedDecisions
|
|
1744
|
+
} : null;
|
|
1745
|
+
},
|
|
1746
|
+
"dev/rules/safety.md": (targetText, sourceText, missing) => {
|
|
1747
|
+
const mergedSafety = mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing);
|
|
1748
|
+
return mergedSafety ? {
|
|
1749
|
+
action: "merge",
|
|
1750
|
+
reason: "restore safety pack high-risk rules in ## Rules section",
|
|
1751
|
+
mergedText: mergedSafety
|
|
1752
|
+
} : null;
|
|
1753
|
+
},
|
|
1754
|
+
"dev/rules/integrations.md": (targetText, sourceText, missing) => {
|
|
1755
|
+
const mergedIntegrations = mergeIntegrationsCredentialSection(targetText, sourceText, missing);
|
|
1756
|
+
return mergedIntegrations ? {
|
|
1757
|
+
action: "merge",
|
|
1758
|
+
reason: "restore integrations credential-separation section in semantic position",
|
|
1759
|
+
mergedText: mergedIntegrations
|
|
1760
|
+
} : null;
|
|
1761
|
+
}
|
|
1762
|
+
};
|
|
1763
|
+
|
|
1764
|
+
function mergeMissingRequiredAnchorsSemantically(targetRel, targetText, sourceText) {
|
|
1765
|
+
const missing = missingRequiredAnchorSnippets(targetRel, targetText);
|
|
1766
|
+
if (missing.length === 0) return null;
|
|
1767
|
+
|
|
1768
|
+
return semanticAnchorRepairStrategies[targetRel]?.(targetText, sourceText, missing) ?? null;
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
function insertSourcePreambleBeforeHeading(targetText, sourceText, headingText) {
|
|
1772
|
+
const targetIndex = targetText.indexOf(headingText);
|
|
1773
|
+
const sourceIndex = sourceText.indexOf(headingText);
|
|
1774
|
+
if (targetIndex < 0 || sourceIndex < 0) return null;
|
|
1775
|
+
const sourcePreamble = sourceText.slice(0, sourceIndex).trim();
|
|
1776
|
+
if (!sourcePreamble) return null;
|
|
1777
|
+
const targetBefore = targetText.slice(0, targetIndex).trimEnd();
|
|
1778
|
+
const targetAfter = targetText.slice(targetIndex);
|
|
1779
|
+
return `${targetBefore}\n\n${sourcePreamble}\n\n${targetAfter}`;
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
function mergeProjectDecisionsPreamble(targetText, sourceText, missing) {
|
|
1783
|
+
const evidenceSnippet = "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.";
|
|
1784
|
+
const boundarySnippet = "This file does not store raw build / upload / QC evidence";
|
|
1785
|
+
const targetIndex = targetText.indexOf("## Evolution Timeline");
|
|
1786
|
+
const sourceIndex = sourceText.indexOf("## Evolution Timeline");
|
|
1787
|
+
if (targetIndex < 0 || sourceIndex < 0) return null;
|
|
1788
|
+
if (targetText.includes("Project Decisions Log")) {
|
|
1789
|
+
const sourcePreamble = sourceText.slice(0, sourceIndex).trim();
|
|
1790
|
+
const blocks = [];
|
|
1791
|
+
if (missing.includes(evidenceSnippet)) {
|
|
1792
|
+
const researchBlock = sourcePreamble.match(/Research-derived decisions use[\s\S]*?source map\./)?.[0];
|
|
1793
|
+
if (!researchBlock) return null;
|
|
1794
|
+
if (!targetText.includes(researchBlock)) blocks.push(researchBlock);
|
|
1795
|
+
}
|
|
1796
|
+
if (missing.includes(boundarySnippet)) {
|
|
1797
|
+
const boundaryBlock = sourcePreamble.match(/This file does not store raw build \/ upload \/ QC evidence[^\r\n]*/)?.[0];
|
|
1798
|
+
if (!boundaryBlock) return null;
|
|
1799
|
+
if (!targetText.includes(boundaryBlock)) blocks.push(boundaryBlock);
|
|
1800
|
+
}
|
|
1801
|
+
if (blocks.length > 0) {
|
|
1802
|
+
return `${targetText.slice(0, targetIndex).trimEnd()}\n\n${blocks.join("\n\n")}\n\n${targetText.slice(targetIndex)}`;
|
|
1803
|
+
}
|
|
1804
|
+
if (missing.includes(evidenceSnippet) || missing.includes(boundarySnippet)) return targetText;
|
|
1805
|
+
}
|
|
1806
|
+
return insertSourcePreambleBeforeHeading(targetText, sourceText, "## Evolution Timeline");
|
|
1807
|
+
}
|
|
1808
|
+
|
|
1809
|
+
function mergeProjectIndexTemplateVersionRow(targetText, sourceText) {
|
|
1810
|
+
if (projectIndexTemplateVersion(targetText)) return targetText;
|
|
1811
|
+
const sourceRow = sourceText.match(/^\| Agent Handoff Kit template version \| [\d.]+ \| [^|\n]+ \|$/m)?.[0];
|
|
1812
|
+
if (!sourceRow) return null;
|
|
1813
|
+
const lines = targetText.split(/\r?\n/);
|
|
1814
|
+
const stackIndex = lines.findIndex((line) => line.trim() === "## Stack");
|
|
1815
|
+
if (stackIndex < 0) return null;
|
|
1816
|
+
const tableHeaderIndex = lines.findIndex((line, index) => index > stackIndex && line.trim() === "| Field | Value | Last verified |");
|
|
1817
|
+
if (tableHeaderIndex < 0) return null;
|
|
1818
|
+
const separatorIndex = tableHeaderIndex + 1;
|
|
1819
|
+
if (!lines[separatorIndex]?.startsWith("|---")) return null;
|
|
1820
|
+
lines.splice(separatorIndex + 1, 0, sourceRow);
|
|
1821
|
+
return lines.join("\n");
|
|
1822
|
+
}
|
|
1823
|
+
|
|
1824
|
+
function mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing) {
|
|
1825
|
+
if (!hasTrustedSafetyPackShape(targetText)) return null;
|
|
1826
|
+
const targetBounds = sectionBounds(targetText, "## Rules", "## Checks");
|
|
1827
|
+
const sourceBounds = sectionBounds(sourceText, "## Rules", "## Checks");
|
|
1828
|
+
if (!targetBounds || !sourceBounds) return null;
|
|
1829
|
+
const targetLines = targetText.split(/\r?\n/);
|
|
1830
|
+
const sourceLines = sourceText.split(/\r?\n/);
|
|
1831
|
+
const targetRuleStart = targetBounds.start + 1;
|
|
1832
|
+
const targetRuleEnd = targetBounds.end;
|
|
1833
|
+
const sourceRuleLines = sourceLines.slice(sourceBounds.start + 1, sourceBounds.end);
|
|
1834
|
+
|
|
1835
|
+
let changed = false;
|
|
1836
|
+
for (const snippet of missing) {
|
|
1837
|
+
const sourceLine = sourceRuleLines.find((line) => line.includes(snippet));
|
|
1838
|
+
if (!sourceLine) return null;
|
|
1839
|
+
const ruleNumber = sourceLine.match(/^(\d+)\. /)?.[1];
|
|
1840
|
+
if (!ruleNumber) return null;
|
|
1841
|
+
const targetIndex = targetLines.findIndex((line, index) => index >= targetRuleStart && index < targetRuleEnd && line.startsWith(`${ruleNumber}. `));
|
|
1842
|
+
if (targetIndex < 0) return null;
|
|
1843
|
+
if (!sameRuleShape(targetLines[targetIndex], sourceLine, snippet)) return null;
|
|
1844
|
+
targetLines[targetIndex] = sourceLine;
|
|
1845
|
+
changed = true;
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
return changed ? targetLines.join("\n") : targetText;
|
|
1849
|
+
}
|
|
1850
|
+
|
|
1851
|
+
function mergeIntegrationsCredentialSection(targetText, sourceText, missing) {
|
|
1852
|
+
if (!missing.some((snippet) => snippet === "機密分離原則")) return null;
|
|
1853
|
+
return replaceSectionByHeadingWithinBounds(
|
|
1854
|
+
targetText,
|
|
1855
|
+
sourceText,
|
|
1856
|
+
/^### 1\. 機密分離原則/m,
|
|
1857
|
+
/^### 2\. 四類整合嘅紀律差異/m,
|
|
1858
|
+
"## Discipline",
|
|
1859
|
+
"## Rules"
|
|
1860
|
+
);
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
function hasTrustedSafetyPackShape(text) {
|
|
1864
|
+
return text.includes("# Safety Pack")
|
|
1865
|
+
&& text.includes("## Scope")
|
|
1866
|
+
&& text.includes("## Load When")
|
|
1867
|
+
&& Boolean(sectionBounds(text, "## Rules", "## Checks"))
|
|
1868
|
+
&& text.includes("## Closeout");
|
|
1869
|
+
}
|
|
1870
|
+
|
|
1871
|
+
function sameRuleShape(targetLine, sourceLine, snippet) {
|
|
1872
|
+
const snippetIndex = sourceLine.indexOf(snippet);
|
|
1873
|
+
if (snippetIndex < 0) return false;
|
|
1874
|
+
const prefix = sourceLine.slice(0, snippetIndex);
|
|
1875
|
+
const suffix = sourceLine.slice(snippetIndex + snippet.length);
|
|
1876
|
+
return prefix.length >= 12
|
|
1877
|
+
&& suffix.length >= 8
|
|
1878
|
+
&& targetLine.startsWith(prefix)
|
|
1879
|
+
&& targetLine.endsWith(suffix);
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
function safetyAnchorHasTrustedRuleShape(text, snippet) {
|
|
1883
|
+
const bounds = sectionBounds(text, "## Rules", "## Checks");
|
|
1884
|
+
if (!bounds) return false;
|
|
1885
|
+
const lines = text.split(/\r?\n/).slice(bounds.start + 1, bounds.end);
|
|
1886
|
+
const line = lines.find((candidate) => candidate.includes(snippet));
|
|
1887
|
+
if (!line) return false;
|
|
1888
|
+
if (snippet === "cmd /c rmdir") {
|
|
1889
|
+
return line.includes("cmd /c rd")
|
|
1890
|
+
&& line.includes("cmd.exe /c")
|
|
1891
|
+
&& line.includes("combined with `rmdir` or `rd`")
|
|
1892
|
+
&& line.includes("Prefer native PowerShell cmdlets")
|
|
1893
|
+
&& line.includes("do not compose filesystem modification commands across shells");
|
|
1894
|
+
}
|
|
1895
|
+
if (snippet === "git reset --hard") {
|
|
1896
|
+
return line.includes("branch deletion")
|
|
1897
|
+
&& line.includes("force push")
|
|
1898
|
+
&& line.includes("history rewrite");
|
|
1899
|
+
}
|
|
1900
|
+
if (snippet === "secret values") {
|
|
1901
|
+
return line.includes("Do not print")
|
|
1902
|
+
&& line.includes("log")
|
|
1903
|
+
&& line.includes("commit")
|
|
1904
|
+
&& line.includes("redacted placeholders");
|
|
1905
|
+
}
|
|
1906
|
+
if (snippet === "external APIs, SDKs, CLIs") {
|
|
1907
|
+
return line.includes("package managers")
|
|
1908
|
+
&& line.includes("official documentation")
|
|
1909
|
+
&& line.includes("project-local runbooks");
|
|
1910
|
+
}
|
|
1911
|
+
return true;
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
function replaceSectionByHeadingWithinBounds(targetText, sourceText, startPattern, nextPattern, boundsStart, boundsEnd) {
|
|
1915
|
+
if (countText(targetText, boundsStart) !== 1 || countText(targetText, boundsEnd) !== 1) return null;
|
|
1916
|
+
const targetBounds = textSectionBounds(targetText, boundsStart, boundsEnd);
|
|
1917
|
+
const sourceBounds = textSectionBounds(sourceText, boundsStart, boundsEnd);
|
|
1918
|
+
if (!targetBounds || !sourceBounds) return null;
|
|
1919
|
+
|
|
1920
|
+
const boundedTarget = targetText.slice(targetBounds.start, targetBounds.end);
|
|
1921
|
+
const boundedSource = sourceText.slice(sourceBounds.start, sourceBounds.end);
|
|
1922
|
+
if (countRegex(boundedTarget, startPattern) > 1 || countRegex(boundedTarget, nextPattern) !== 1) return null;
|
|
1923
|
+
const sourceSection = extractSection(boundedSource, startPattern, nextPattern);
|
|
1924
|
+
if (!sourceSection) return null;
|
|
1925
|
+
const targetSection = extractSection(boundedTarget, startPattern, nextPattern);
|
|
1926
|
+
if (targetSection) {
|
|
1927
|
+
return `${targetText.slice(0, targetBounds.start + targetSection.start)}${sourceSection.text}${targetText.slice(targetBounds.start + targetSection.end)}`;
|
|
1928
|
+
}
|
|
1929
|
+
const nextMatch = nextPattern.exec(boundedTarget);
|
|
1930
|
+
if (!nextMatch) return null;
|
|
1931
|
+
return `${targetText.slice(0, targetBounds.start + nextMatch.index)}${sourceSection.text}${targetText.slice(targetBounds.start + nextMatch.index)}`;
|
|
1932
|
+
}
|
|
1933
|
+
|
|
1934
|
+
function replaceSectionByHeading(targetText, sourceText, startPattern, nextPattern) {
|
|
1935
|
+
const sourceSection = extractSection(sourceText, startPattern, nextPattern);
|
|
1936
|
+
if (!sourceSection) return null;
|
|
1937
|
+
const targetSection = extractSection(targetText, startPattern, nextPattern);
|
|
1938
|
+
if (targetSection) {
|
|
1939
|
+
return `${targetText.slice(0, targetSection.start)}${sourceSection.text}${targetText.slice(targetSection.end)}`;
|
|
1940
|
+
}
|
|
1941
|
+
const nextMatch = nextPattern.exec(targetText);
|
|
1942
|
+
if (!nextMatch) return null;
|
|
1943
|
+
return `${targetText.slice(0, nextMatch.index)}${sourceSection.text}${targetText.slice(nextMatch.index)}`;
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
function extractSection(text, startPattern, nextPattern) {
|
|
1947
|
+
const startMatch = startPattern.exec(text);
|
|
1948
|
+
if (!startMatch) return null;
|
|
1949
|
+
const afterStart = text.slice(startMatch.index + startMatch[0].length);
|
|
1950
|
+
const nextMatch = nextPattern.exec(afterStart);
|
|
1951
|
+
const end = nextMatch ? startMatch.index + startMatch[0].length + nextMatch.index : text.length;
|
|
1952
|
+
return { start: startMatch.index, end, text: text.slice(startMatch.index, end) };
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1955
|
+
function sectionBounds(text, startHeading, endHeading) {
|
|
1956
|
+
const lines = text.split(/\r?\n/);
|
|
1957
|
+
const start = lines.findIndex((line) => line.trim() === startHeading);
|
|
1958
|
+
if (start < 0) return null;
|
|
1959
|
+
const end = lines.findIndex((line, index) => index > start && line.trim() === endHeading);
|
|
1960
|
+
if (end < 0) return null;
|
|
1961
|
+
return { start, end };
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
function textSectionBounds(text, startHeading, endHeading) {
|
|
1965
|
+
const startIndex = text.indexOf(startHeading);
|
|
1966
|
+
if (startIndex < 0) return null;
|
|
1967
|
+
const endIndex = text.indexOf(endHeading, startIndex + startHeading.length);
|
|
1968
|
+
if (endIndex < 0) return null;
|
|
1969
|
+
return { start: startIndex, end: endIndex };
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
function projectIndexTemplateVersion(text) {
|
|
1973
|
+
const bounds = textSectionBounds(text, "## Stack", "## Directory Map");
|
|
1974
|
+
if (!bounds) return null;
|
|
1975
|
+
const stack = text.slice(bounds.start, bounds.end);
|
|
1976
|
+
const row = stack.match(/^\| Agent Handoff Kit template version \| ([\d.]+) \| [^|\n]+ \|$/m);
|
|
1977
|
+
return row ? row[1] : null;
|
|
1978
|
+
}
|
|
1979
|
+
|
|
1328
1980
|
function mergeHandoffLifecycleField(targetText) {
|
|
1329
|
-
const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
|
|
1330
|
-
if (!targetText.includes(openingMarker)) return null;
|
|
1331
|
-
|
|
1332
|
-
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
|
-
let merged = targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
|
|
1334
|
-
|
|
1335
|
-
if (!merged.includes("Lifecycle consistency rule: compare `Completed This Session`")) {
|
|
1336
|
-
const ruleBlock = "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.\n\n";
|
|
1337
|
-
const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
|
|
1338
|
-
if (merged.includes(sufficiencyMarker)) {
|
|
1339
|
-
merged = merged.replace(sufficiencyMarker, `${ruleBlock}${sufficiencyMarker}`);
|
|
1340
|
-
} else {
|
|
1341
|
-
merged = `${merged.trimEnd()}\n\n${ruleBlock}`;
|
|
1342
|
-
}
|
|
1343
|
-
}
|
|
1981
|
+
const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
|
|
1982
|
+
if (!targetText.includes(openingMarker)) return null;
|
|
1344
1983
|
|
|
1345
|
-
|
|
1984
|
+
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";
|
|
1985
|
+
let merged = targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
|
|
1986
|
+
return ensureHandoffStateReconciliationRules(ensureHandoffPersistenceRoutingField(merged));
|
|
1346
1987
|
}
|
|
1347
1988
|
|
|
1348
1989
|
function reclassifyExistingHandoffLifecyclePlaceholder(targetText) {
|
|
@@ -1360,23 +2001,75 @@ function reclassifyExistingHandoffLifecyclePlaceholder(targetText) {
|
|
|
1360
2001
|
if (colonIndex < 0) return null;
|
|
1361
2002
|
lines[fieldIndex] = `${lines[fieldIndex].slice(0, colonIndex + 1)} Reclassified at upgrade: existing lifecycle placeholder predates this version; pre-existing handoff state predates this check; reconcile at next closeout.`;
|
|
1362
2003
|
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
2004
|
+
return ensureHandoffStateReconciliationRules(lines.join("\n"));
|
|
2005
|
+
}
|
|
2006
|
+
|
|
2007
|
+
function mergeHandoffPersistenceRoutingField(targetText) {
|
|
2008
|
+
const merged = ensureHandoffPersistenceRoutingField(targetText);
|
|
2009
|
+
if (!merged || merged === targetText) return null;
|
|
2010
|
+
return ensureHandoffStateReconciliationRules(merged);
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
function ensureHandoffPersistenceRoutingField(targetText) {
|
|
2014
|
+
if (targetText.includes("ack:field:persistence-routing-checked")) return targetText;
|
|
2015
|
+
const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
|
|
2016
|
+
if (!targetText.includes(openingMarker)) return null;
|
|
2017
|
+
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";
|
|
2018
|
+
return targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
|
|
2019
|
+
}
|
|
2020
|
+
|
|
2021
|
+
function ensureHandoffStateReconciliationRules(targetText) {
|
|
2022
|
+
if (!targetText) return null;
|
|
2023
|
+
const rules = [];
|
|
2024
|
+
if (!targetText.includes("Lifecycle consistency rule: compare `Completed This Session`")) {
|
|
2025
|
+
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.");
|
|
2026
|
+
}
|
|
2027
|
+
if (!targetText.includes("Persistence routing rule: one-time delivery instructions")) {
|
|
2028
|
+
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.");
|
|
1372
2029
|
}
|
|
2030
|
+
if (rules.length === 0) return targetText;
|
|
2031
|
+
const ruleBlock = `${rules.join("\n")}\n\n`;
|
|
2032
|
+
const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
|
|
2033
|
+
if (targetText.includes(sufficiencyMarker)) {
|
|
2034
|
+
return targetText.replace(sufficiencyMarker, `${ruleBlock}${sufficiencyMarker}`);
|
|
2035
|
+
}
|
|
2036
|
+
return `${targetText.trimEnd()}\n\n${ruleBlock}`;
|
|
2037
|
+
}
|
|
1373
2038
|
|
|
1374
|
-
|
|
2039
|
+
function mergeSessionLogEvidenceDispositionField(targetText) {
|
|
2040
|
+
if (targetText.includes("- **Evidence disposition:**")) return targetText;
|
|
2041
|
+
const qcField = "- **QC:**";
|
|
2042
|
+
if (!targetText.includes(qcField)) return null;
|
|
2043
|
+
return targetText.replace(qcField, `${qcField}\n- **Evidence disposition:** <one-time only / kept as recent trace evidence / absorbed into handoff / indexed in PROJECT_INDEX / promoted to PROJECT_DECISIONS / promoted to rule pack>`);
|
|
1375
2044
|
}
|
|
1376
|
-
|
|
1377
|
-
function
|
|
1378
|
-
const
|
|
1379
|
-
|
|
2045
|
+
|
|
2046
|
+
function mergeHandoffArchiveContinuityRule(targetText, sourceText) {
|
|
2047
|
+
const sourceMatch = sourceText.match(/Continuity rule: this file carries current state and next action\.[^\r\n]*/);
|
|
2048
|
+
if (!sourceMatch) return null;
|
|
2049
|
+
const continuityRule = sourceMatch[0];
|
|
2050
|
+
if (targetText.includes(continuityRule)) return targetText;
|
|
2051
|
+
|
|
2052
|
+
const existingRulePattern = /Continuity rule: this file carries current state and next action\.[^\r\n]*/;
|
|
2053
|
+
if (existingRulePattern.test(targetText)) {
|
|
2054
|
+
return targetText.replace(existingRulePattern, continuityRule);
|
|
2055
|
+
}
|
|
2056
|
+
|
|
2057
|
+
const nextSectionMarker = "<!-- ack:section:next-session-opening-message -->";
|
|
2058
|
+
if (targetText.includes(nextSectionMarker)) {
|
|
2059
|
+
return targetText.replace(nextSectionMarker, `${continuityRule}\n\n${nextSectionMarker}`);
|
|
2060
|
+
}
|
|
2061
|
+
|
|
2062
|
+
const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
|
|
2063
|
+
if (targetText.includes(sufficiencyMarker)) {
|
|
2064
|
+
return `${targetText.trimEnd()}\n\n${continuityRule}\n`;
|
|
2065
|
+
}
|
|
2066
|
+
|
|
2067
|
+
return null;
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
function mergeRulePacksRows(targetText, sourceText) {
|
|
2071
|
+
const requiredPacks = [
|
|
2072
|
+
"dev/rules/onboarding.md",
|
|
1380
2073
|
"dev/rules/integrations.md"
|
|
1381
2074
|
];
|
|
1382
2075
|
const sourceRows = sourceText
|
|
@@ -1416,15 +2109,14 @@ function mergeRulePacksRows(targetText, sourceText) {
|
|
|
1416
2109
|
// maybePrintUpdateNotice which silently fails when npx auto-fetches latest (CLI version
|
|
1417
2110
|
// equals npm latest, so the notice never triggers, leaving user root drift invisible).
|
|
1418
2111
|
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
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
}
|
|
2112
|
+
const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
|
|
2113
|
+
let rootVersion = null;
|
|
2114
|
+
try {
|
|
2115
|
+
const text = await readFile(indexPath, "utf8");
|
|
2116
|
+
rootVersion = projectIndexTemplateVersion(text);
|
|
2117
|
+
} catch {
|
|
2118
|
+
// file missing or unreadable; rootVersion stays null
|
|
2119
|
+
}
|
|
1428
2120
|
|
|
1429
2121
|
let npmLatest = null;
|
|
1430
2122
|
try {
|