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