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