@adamchanadam/agent-handoff-kit 0.3.38 → 0.3.40
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/LICENSE +21 -21
- package/README.md +5 -5
- package/bin/agent-handoff-kit.mjs +1570 -752
- package/bin/migration-baselines/v0.3.38/integrations.md +235 -0
- package/bin/migration-baselines/v0.3.38/onboarding.md +201 -0
- package/bin/migration-baselines/v0.3.38/safety.md +46 -0
- package/bin/prompt-mirror-core.mjs +187 -114
- package/package.json +20 -31
- package/packs/agent-governance.md +103 -103
- package/packs/closeout.md +72 -0
- package/packs/coding.md +28 -28
- package/packs/communication.md +30 -30
- package/packs/integrations.md +251 -235
- package/packs/knowledge.md +5 -5
- package/packs/onboarding.md +214 -201
- package/packs/release.md +28 -28
- package/packs/research.md +30 -30
- package/packs/safety.md +29 -27
- package/packs/writing.md +36 -36
- package/runtime-core/AGENTS.core.md +61 -139
- package/runtime-core/CLAUDE.md +13 -13
- package/runtime-core/DOC_SYNC_REGISTRY.md +24 -24
- package/runtime-core/GEMINI.md +17 -17
- package/runtime-core/PROJECT_DECISIONS.md +43 -43
- package/runtime-core/PROJECT_INDEX.md +10 -8
- package/runtime-core/RULE_PACKS.md +12 -11
- package/runtime-core/SESSION_HANDOFF.md +35 -44
- package/runtime-core/SESSION_LOG.md +35 -57
- package/runtime-core/START_NEXT_SESSION_PROMPT.txt +5 -16
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
import { createInterface } from "node:readline/promises";
|
|
4
4
|
import { stdin as input, stdout as output } from "node:process";
|
|
5
|
-
import { copyFile, mkdir,
|
|
5
|
+
import { chmod, copyFile, lstat, mkdir, open, readFile, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
6
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
7
|
+
import { hostname } from "node:os";
|
|
6
8
|
import path from "node:path";
|
|
7
9
|
import { fileURLToPath } from "node:url";
|
|
8
|
-
import { assessPromptMirrorTexts, extractOpeningMessage } from "./prompt-mirror-core.mjs";
|
|
10
|
+
import { assessPromptMirrorRoot, assessPromptMirrorTexts, extractOpeningMessage } from "./prompt-mirror-core.mjs";
|
|
9
11
|
|
|
10
12
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
11
13
|
const packageRoot = path.resolve(__dirname, "..");
|
|
@@ -28,8 +30,9 @@ const mappings = [
|
|
|
28
30
|
["packs/agent-governance.md", "dev/rules/agent-governance.md"],
|
|
29
31
|
["packs/release.md", "dev/rules/release.md"],
|
|
30
32
|
["packs/knowledge.md", "dev/rules/knowledge.md"],
|
|
31
|
-
["packs/communication.md", "dev/rules/communication.md"],
|
|
32
|
-
["packs/
|
|
33
|
+
["packs/communication.md", "dev/rules/communication.md"],
|
|
34
|
+
["packs/closeout.md", "dev/rules/closeout.md"],
|
|
35
|
+
["packs/onboarding.md", "dev/rules/onboarding.md"],
|
|
33
36
|
["packs/integrations.md", "dev/rules/integrations.md"]
|
|
34
37
|
];
|
|
35
38
|
|
|
@@ -37,68 +40,87 @@ const requiredTargets = mappings.map(([, target]) => target);
|
|
|
37
40
|
const rulePackTargets = mappings
|
|
38
41
|
.map(([, target]) => target)
|
|
39
42
|
.filter((target) => target.startsWith("dev/rules/"));
|
|
40
|
-
const managedCoreStart = "<!-- BEGIN Agent Handoff Kit managed core -->";
|
|
41
|
-
const managedCoreEnd = "<!-- END Agent Handoff Kit managed core -->";
|
|
43
|
+
const managedCoreStart = "<!-- BEGIN Agent Handoff Kit managed core -->";
|
|
44
|
+
const managedCoreEnd = "<!-- END Agent Handoff Kit managed core -->";
|
|
45
|
+
const credentialLeakPatterns = [
|
|
46
|
+
{ pattern: /sk-ant-[A-Za-z0-9_-]{20,}/, label: "Anthropic API key" },
|
|
47
|
+
{ pattern: /\bsk-[A-Za-z0-9_-]{20,}/, label: "sk-prefixed token" },
|
|
48
|
+
{ pattern: /\bntn_[A-Za-z0-9_-]{40,}/, label: "Notion token" },
|
|
49
|
+
{ pattern: /\bsecret_[A-Za-z0-9_-]{40,}/, label: "secret-prefixed token" },
|
|
50
|
+
{ pattern: /\bya29\.[A-Za-z0-9_-]{20,}/, label: "Google OAuth token" },
|
|
51
|
+
{ pattern: /\b1\/\/[A-Za-z0-9_-]{30,}/, label: "Google refresh token" },
|
|
52
|
+
{ pattern: /\bxox[abprs]-[A-Za-z0-9-]{10,}/, label: "Slack token" },
|
|
53
|
+
{ pattern: /\b(?:ghp|gho|ghs)_[A-Za-z0-9]{36}/, label: "GitHub token" },
|
|
54
|
+
{ pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}/, label: "GitHub fine-grained token" },
|
|
55
|
+
{ pattern: /\bsl\.[A-Za-z0-9_-]{50,}/, label: "Dropbox token" },
|
|
56
|
+
{ pattern: /\bAKIA[A-Z0-9]{16}/, label: "AWS access key" },
|
|
57
|
+
{ pattern: /\bAIza[A-Za-z0-9_-]{35}/, label: "Google API key" }
|
|
58
|
+
];
|
|
59
|
+
|
|
60
|
+
// Exact v0.3.38 continuity quick-fix packs observed in real projects before the
|
|
61
|
+
// product migration shipped. They contain no project-specific state. Matching
|
|
62
|
+
// is whole-file and newline-normalized so an extra local edit still takes the
|
|
63
|
+
// conservative three-way merge/conflict path instead of being overwritten.
|
|
64
|
+
const knownV038ContinuityQuickFixHashes = new Map([
|
|
65
|
+
["packs/onboarding.md", "5dc32d9e164604379eb60f7ea0a731a2accb3da945ac5f28654ac253add187cf"],
|
|
66
|
+
["packs/integrations.md", "8110bfb1e09fb503463072909c06027de0b39850c22a4f4c208c5752cf380826"]
|
|
67
|
+
]);
|
|
42
68
|
|
|
43
69
|
const requiredAnchors = [
|
|
44
|
-
{
|
|
45
|
-
target: "AGENTS.md",
|
|
46
|
-
label: "startup
|
|
47
|
-
snippets: [
|
|
48
|
-
"## 1. Startup
|
|
49
|
-
"dev/SESSION_HANDOFF.md",
|
|
50
|
-
"dev/SESSION_LOG.md",
|
|
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",
|
|
70
|
+
{
|
|
71
|
+
target: "AGENTS.md",
|
|
72
|
+
label: "continuity-first startup and proportional work",
|
|
73
|
+
snippets: [
|
|
74
|
+
"## 1. Intent And Startup",
|
|
75
|
+
"dev/SESSION_HANDOFF.md",
|
|
76
|
+
"Do not read `dev/SESSION_LOG.md` during ordinary startup",
|
|
77
|
+
"dev/PROJECT_INDEX.md",
|
|
78
|
+
"dev/RULE_PACKS.md",
|
|
79
|
+
"Agent Handoff Kit v<version>",
|
|
56
80
|
"continuity ready",
|
|
57
81
|
"推薦下一步",
|
|
58
|
-
"recommended action",
|
|
59
82
|
"Start Agent Handoff",
|
|
60
|
-
"
|
|
61
|
-
"
|
|
62
|
-
"
|
|
63
|
-
"
|
|
64
|
-
"
|
|
65
|
-
"
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
"
|
|
78
|
-
"
|
|
79
|
-
"
|
|
80
|
-
"
|
|
81
|
-
"wrap up",
|
|
82
|
-
"handoff",
|
|
83
|
-
"Reconcile `dev/SESSION_HANDOFF.md`",
|
|
84
|
-
"Add a concise entry to `dev/SESSION_LOG.md`",
|
|
85
|
-
"Closeout Write Contract",
|
|
86
|
-
"ack:log-entry:start/end",
|
|
87
|
-
"next-session opening message",
|
|
88
|
-
"fenced `text` code block",
|
|
89
|
-
"handoff saved",
|
|
90
|
-
"Use the same display version rule as startup",
|
|
91
|
-
"Never print the literal placeholder `v<version>`",
|
|
92
|
-
"next-session startup entry",
|
|
93
|
-
"State Reconciliation Check",
|
|
94
|
-
"handoff lifecycle consistency",
|
|
95
|
-
"A final chat summary without updated handoff/log/prompt evidence is not closeout",
|
|
96
|
-
"Do not append a new state snapshot",
|
|
97
|
-
"If this session used external tools",
|
|
98
|
-
"ownership-based external-tool resource closeout check",
|
|
83
|
+
"A fresh install or short message only makes guidance available",
|
|
84
|
+
"Direct ordinary tasks do not show the card",
|
|
85
|
+
"Reachable is not the same as ingested",
|
|
86
|
+
"Proportionate Work Loop",
|
|
87
|
+
"Pack loading is normally silent",
|
|
88
|
+
"dev/rules/integrations.md",
|
|
89
|
+
"Probe an integration only immediately before a task uses it"
|
|
90
|
+
]
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
target: "AGENTS.md",
|
|
94
|
+
label: "closeout trigger and invariants",
|
|
95
|
+
snippets: [
|
|
96
|
+
"## 4. Closeout Trigger",
|
|
97
|
+
"收工",
|
|
98
|
+
"Wrap up Agent Handoff",
|
|
99
|
+
"wrap up",
|
|
100
|
+
"handoff",
|
|
101
|
+
"dev/rules/closeout.md",
|
|
102
|
+
"Current state lives in `dev/SESSION_HANDOFF.md`",
|
|
103
|
+
"no third full copy is retained",
|
|
99
104
|
"START_NEXT_SESSION_PROMPT.txt"
|
|
100
105
|
]
|
|
101
106
|
},
|
|
107
|
+
{
|
|
108
|
+
target: "dev/rules/closeout.md",
|
|
109
|
+
label: "closeout pack complete contract",
|
|
110
|
+
snippets: [
|
|
111
|
+
"Closeout Pack",
|
|
112
|
+
"single detailed contract",
|
|
113
|
+
"Reconcile lifecycle state",
|
|
114
|
+
"Completed This Session",
|
|
115
|
+
"prompt-mirror verification result",
|
|
116
|
+
"Mark first-use guidance",
|
|
117
|
+
"Maintenance Trigger Check",
|
|
118
|
+
"START_NEXT_SESSION_PROMPT.txt",
|
|
119
|
+
"omit the full opening message by design",
|
|
120
|
+
"handoff saved",
|
|
121
|
+
"Stop Conditions"
|
|
122
|
+
]
|
|
123
|
+
},
|
|
102
124
|
{
|
|
103
125
|
target: "dev/SESSION_HANDOFF.md",
|
|
104
126
|
label: "handoff workspace and opening message schema",
|
|
@@ -118,11 +140,11 @@ const requiredAnchors = [
|
|
|
118
140
|
"ack:section:next-session-opening-message",
|
|
119
141
|
"ack:field:recommended-next-step-explicit",
|
|
120
142
|
"ack:field:lifecycle-conflicts-resolved",
|
|
121
|
-
"ack:field:persistence-routing-checked",
|
|
122
|
-
"
|
|
123
|
-
"
|
|
124
|
-
"
|
|
125
|
-
"dev/
|
|
143
|
+
"ack:field:persistence-routing-checked",
|
|
144
|
+
"ack:field:first-use-guidance-state",
|
|
145
|
+
"📋 Next session:",
|
|
146
|
+
"```text",
|
|
147
|
+
"Do not read dev/SESSION_LOG.md during ordinary startup"
|
|
126
148
|
]
|
|
127
149
|
},
|
|
128
150
|
{
|
|
@@ -138,7 +160,7 @@ const requiredAnchors = [
|
|
|
138
160
|
},
|
|
139
161
|
{
|
|
140
162
|
target: "dev/SESSION_LOG.md",
|
|
141
|
-
label: "session log event
|
|
163
|
+
label: "session log event schema without prompt copy",
|
|
142
164
|
placement: sessionLogAnchorPlacement,
|
|
143
165
|
snippets: [
|
|
144
166
|
"ack:section:session-log-preamble",
|
|
@@ -148,13 +170,10 @@ const requiredAnchors = [
|
|
|
148
170
|
"Record what actually happened in the session",
|
|
149
171
|
"## Entry Template",
|
|
150
172
|
"- **QC:**",
|
|
151
|
-
"- **Sync:**",
|
|
152
|
-
"- **Log maintenance:**",
|
|
153
|
-
"
|
|
154
|
-
"
|
|
155
|
-
"```text",
|
|
156
|
-
"Read in order:",
|
|
157
|
-
"dev/DOC_SYNC_REGISTRY.md"
|
|
173
|
+
"- **Sync:**",
|
|
174
|
+
"- **Log maintenance:**",
|
|
175
|
+
"- **Opening-message mirror:**",
|
|
176
|
+
"full text omitted by design"
|
|
158
177
|
]
|
|
159
178
|
},
|
|
160
179
|
{
|
|
@@ -176,10 +195,10 @@ const requiredAnchors = [
|
|
|
176
195
|
label: "log retention and evidence schema",
|
|
177
196
|
placement: sessionLogAnchorPlacement,
|
|
178
197
|
snippets: [
|
|
179
|
-
"kept, summarized, or archived",
|
|
180
|
-
"Do not remove validation evidence",
|
|
181
|
-
"
|
|
182
|
-
"not current state"
|
|
198
|
+
"kept, summarized, or archived",
|
|
199
|
+
"Do not remove validation evidence",
|
|
200
|
+
"full opening message never belongs in this log",
|
|
201
|
+
"not current state"
|
|
183
202
|
]
|
|
184
203
|
},
|
|
185
204
|
{
|
|
@@ -217,7 +236,8 @@ const requiredAnchors = [
|
|
|
217
236
|
"browser profiles",
|
|
218
237
|
"desktop app sessions",
|
|
219
238
|
"shared tool servers",
|
|
220
|
-
"notebook kernels"
|
|
239
|
+
"notebook kernels",
|
|
240
|
+
"Short-lived localhost validation services"
|
|
221
241
|
]
|
|
222
242
|
},
|
|
223
243
|
{
|
|
@@ -245,7 +265,9 @@ const requiredAnchors = [
|
|
|
245
265
|
"Onboarding Pack",
|
|
246
266
|
"transient pack",
|
|
247
267
|
"Explicit onboarding signal keywords",
|
|
248
|
-
"
|
|
268
|
+
"Continuity startup boundary",
|
|
269
|
+
"starts continuity and reads the current handoff state; it is not an onboarding signal",
|
|
270
|
+
"Infer when sufficient; ask only when unresolved",
|
|
249
271
|
"Application Scenario Library",
|
|
250
272
|
"Scenario A. Build systems, tools, platforms, websites, or apps",
|
|
251
273
|
"Scenario B. Organize research or write a report",
|
|
@@ -279,6 +301,8 @@ const requiredAnchors = [
|
|
|
279
301
|
"Runtime-Controlled Tool Operation Variants",
|
|
280
302
|
"Tool Operation References",
|
|
281
303
|
"Do not guess Chrome, Playwright, or DevTools commands",
|
|
304
|
+
"Local HTML / app validation fallback",
|
|
305
|
+
"`file://` rejection alone is not enough evidence to stop",
|
|
282
306
|
"Anti-pattern"
|
|
283
307
|
]
|
|
284
308
|
}
|
|
@@ -321,36 +345,42 @@ const schemaChecks = [
|
|
|
321
345
|
marker("field", "state-sections-rewritten-or-confirmed", "State sections rewritten or confirmed current"),
|
|
322
346
|
marker("field", "user-intent", "User intent:"),
|
|
323
347
|
marker("field", "task-essence", "Task essence:"),
|
|
324
|
-
marker("field", "success-criteria", "Success criteria:")
|
|
348
|
+
marker("field", "success-criteria", "Success criteria:")
|
|
349
|
+
,marker("field", "first-use-guidance-state", "First-use guidance state:")
|
|
325
350
|
]
|
|
326
351
|
},
|
|
327
352
|
{
|
|
328
353
|
target: "dev/SESSION_HANDOFF.md",
|
|
329
354
|
label: "handoff opening message structure",
|
|
330
355
|
checks: [
|
|
331
|
-
includes("📋 Next session:"),
|
|
332
|
-
includes("```text"),
|
|
333
|
-
includes("Work in "),
|
|
334
|
-
includes("Read
|
|
335
|
-
includes("
|
|
356
|
+
includes("📋 Next session:"),
|
|
357
|
+
includes("```text"),
|
|
358
|
+
includes("Work in "),
|
|
359
|
+
includes("Read AGENTS.md, then dev/SESSION_HANDOFF.md"),
|
|
360
|
+
includes("Do not read dev/SESSION_LOG.md during ordinary startup")
|
|
336
361
|
]
|
|
337
362
|
},
|
|
338
363
|
{
|
|
339
364
|
target: "dev/SESSION_HANDOFF.md",
|
|
340
|
-
label: "handoff lifecycle
|
|
365
|
+
label: "handoff lifecycle mechanical checks",
|
|
341
366
|
checks: [
|
|
342
|
-
{
|
|
343
|
-
label: "completed work is not carried forward as unresolved next work",
|
|
344
|
-
test: (text) => assessHandoffLifecycleConsistency(text).ok
|
|
367
|
+
{
|
|
368
|
+
label: "completed work is not carried forward as unresolved next work",
|
|
369
|
+
test: (text) => assessHandoffLifecycleConsistency(text).ok,
|
|
370
|
+
explain: (text) => assessHandoffLifecycleConsistency(text).reason
|
|
345
371
|
}
|
|
346
372
|
]
|
|
347
373
|
},
|
|
348
|
-
{
|
|
349
|
-
target: "dev/SESSION_LOG.md",
|
|
350
|
-
label: "session log entry fields",
|
|
351
|
-
checks: [
|
|
352
|
-
heading("Entry Template"),
|
|
353
|
-
|
|
374
|
+
{
|
|
375
|
+
target: "dev/SESSION_LOG.md",
|
|
376
|
+
label: "session log entry fields",
|
|
377
|
+
checks: [
|
|
378
|
+
heading("Entry Template"),
|
|
379
|
+
{
|
|
380
|
+
label: "SESSION_LOG has one trusted current entry-template boundary",
|
|
381
|
+
test: (text) => Boolean(sessionLogEntryTemplateContract(text))
|
|
382
|
+
},
|
|
383
|
+
marker("section", "session-log-preamble", "Handoff role"),
|
|
354
384
|
marker("section", "session-log-entry-template", "Entry Template"),
|
|
355
385
|
includes("ack:log-entry:start"),
|
|
356
386
|
includes("ack:log-entry:end"),
|
|
@@ -362,8 +392,13 @@ const schemaChecks = [
|
|
|
362
392
|
includes("- **Evidence disposition:**"),
|
|
363
393
|
includes("- **Sync:**"),
|
|
364
394
|
includes("- **Pending:**"),
|
|
365
|
-
includes("- **Risks:**"),
|
|
366
|
-
includes("- **Log maintenance:**")
|
|
395
|
+
includes("- **Risks:**"),
|
|
396
|
+
includes("- **Log maintenance:**"),
|
|
397
|
+
includes("- **Opening-message mirror:**"),
|
|
398
|
+
{
|
|
399
|
+
label: "SESSION_LOG does not contain a full opening-message copy",
|
|
400
|
+
test: (text) => !text.includes("Read AGENTS.md, then dev/SESSION_HANDOFF.md. Trust the handoff over this generated mirror.")
|
|
401
|
+
}
|
|
367
402
|
]
|
|
368
403
|
},
|
|
369
404
|
{
|
|
@@ -378,6 +413,10 @@ const schemaChecks = [
|
|
|
378
413
|
heading("Installed Integrations"),
|
|
379
414
|
heading("Tool Operation References"),
|
|
380
415
|
heading("Local QC Commands"),
|
|
416
|
+
{
|
|
417
|
+
label: "Installed Integrations and Tool Operation References are unique real H2 sections before Local QC Commands",
|
|
418
|
+
test: (text) => projectIndexGovernanceSectionsAreValid(text)
|
|
419
|
+
},
|
|
381
420
|
heading("Workspace Identity"),
|
|
382
421
|
heading("Change Hotspots"),
|
|
383
422
|
heading("Maintenance Rule"),
|
|
@@ -425,20 +464,40 @@ const schemaChecks = [
|
|
|
425
464
|
// R-029 v0.2.1+: routing table must include onboarding pack first-time signal row.
|
|
426
465
|
// Without this anchor, the upgrade flow may silently leave v0.1.X users with a
|
|
427
466
|
// stale routing table that does not route onboarding signals.
|
|
428
|
-
includes("
|
|
429
|
-
includes("dev/rules/onboarding.md"),
|
|
467
|
+
includes("Explicit onboarding requests"),
|
|
468
|
+
includes("dev/rules/onboarding.md"),
|
|
469
|
+
includes("fresh install"),
|
|
470
|
+
includes("dev/rules/closeout.md"),
|
|
430
471
|
// R-030 v0.3.0+: routing table must include integrations pack row.
|
|
431
472
|
includes("dev/rules/integrations.md"),
|
|
432
473
|
includes("External tool resource pressure"),
|
|
433
474
|
includes("ownership-based external-tool resource closeout"),
|
|
475
|
+
includes("local HTML validation"),
|
|
476
|
+
includes("localhost fallback"),
|
|
434
477
|
includes("Governance bridge / bridge governance"),
|
|
435
478
|
includes("equivalent Chinese user phrases"),
|
|
436
479
|
includes("scan for unbridged governance documents"),
|
|
437
480
|
includes("scan for unbridged governance documents")
|
|
438
481
|
]
|
|
439
482
|
},
|
|
440
|
-
{
|
|
441
|
-
target: "dev/rules/
|
|
483
|
+
{
|
|
484
|
+
target: "dev/rules/closeout.md",
|
|
485
|
+
label: "closeout pack structure",
|
|
486
|
+
checks: [
|
|
487
|
+
heading("Scope"),
|
|
488
|
+
heading("Required Reads"),
|
|
489
|
+
heading("Write Contract"),
|
|
490
|
+
heading("Full Closeout"),
|
|
491
|
+
heading("Maintenance Trigger Check"),
|
|
492
|
+
heading("Opening Message And Card"),
|
|
493
|
+
heading("Stop Conditions"),
|
|
494
|
+
includes("full opening message"),
|
|
495
|
+
includes("first-use guidance"),
|
|
496
|
+
includes("START_NEXT_SESSION_PROMPT.txt")
|
|
497
|
+
]
|
|
498
|
+
},
|
|
499
|
+
{
|
|
500
|
+
target: "dev/rules/agent-governance.md",
|
|
442
501
|
label: "agent governance pack structure",
|
|
443
502
|
checks: [
|
|
444
503
|
heading("Scope"),
|
|
@@ -565,9 +624,25 @@ async function needsProjectIndexVersionInject(root, command, version) {
|
|
|
565
624
|
return false;
|
|
566
625
|
}
|
|
567
626
|
|
|
568
|
-
async function runInstall(command, root, options, version) {
|
|
569
|
-
|
|
570
|
-
|
|
627
|
+
async function runInstall(command, root, options, version) {
|
|
628
|
+
if (options.dryRun) await assertDryRunHasNoPendingTransaction(root);
|
|
629
|
+
else await recoverInterruptedTransaction(root);
|
|
630
|
+
const installedVersion = await readInstalledTemplateVersion(root);
|
|
631
|
+
if (command === "upgrade" && installedVersion && compareSemver(installedVersion, version) > 0) {
|
|
632
|
+
printCard(version, "upgrade blocked", "x.x");
|
|
633
|
+
console.log(`selected root: ${root}`);
|
|
634
|
+
console.log(`status: blocked`);
|
|
635
|
+
console.log(`reason: project template v${installedVersion} is newer than this CLI v${version}`);
|
|
636
|
+
console.log("no files written: use an equal or newer Agent Handoff Kit CLI; downgrade requires a separately designed command");
|
|
637
|
+
process.exitCode = 1;
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
const mode = await detectMode(root);
|
|
641
|
+
const plan = await buildPlan(root, command, version);
|
|
642
|
+
// Validate the operator-selected path before every exit path, including
|
|
643
|
+
// dry-run, conflicts, and already-current no-op upgrades. Otherwise a
|
|
644
|
+
// junction can be silently accepted whenever there is nothing to write.
|
|
645
|
+
await validateTransactionRoot(root, plan, { createMissingRoot: !options.dryRun });
|
|
571
646
|
|
|
572
647
|
// R-031 v0.3.1+: plan-time upgrade no-op detection. When upgrade has zero
|
|
573
648
|
// create/merge/conflict actions (skip-only), skip the full plan listing +
|
|
@@ -609,150 +684,566 @@ async function runInstall(command, root, options, version) {
|
|
|
609
684
|
|
|
610
685
|
printPlan(command, root, mode, plan, version, options.dryRun);
|
|
611
686
|
|
|
612
|
-
if (options.dryRun) {
|
|
687
|
+
if (options.dryRun) {
|
|
613
688
|
console.log("\ndry-run: no files written");
|
|
614
689
|
printDryRunExplanation(command, mode, plan);
|
|
615
690
|
if (plan.some((item) => item.action === "conflict")) process.exitCode = 1;
|
|
616
|
-
return;
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
if (
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
if (plan.some((item) => item.action === "conflict")) {
|
|
695
|
+
console.log("");
|
|
696
|
+
console.log("⛔ 升級預檢發現 conflict;治理目標檔、版本與 migration artifact 均沒有寫入。");
|
|
697
|
+
console.log("📋 下一步:根據上方 conflict 資料作非破壞性合併;不要以舊版本資料列當作已完成。");
|
|
698
|
+
process.exitCode = 1;
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
if (!options.yes) {
|
|
620
703
|
const ok = await confirmWrite();
|
|
621
704
|
if (!ok) {
|
|
622
705
|
console.log("cancelled: no files written");
|
|
623
|
-
return;
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
const conflicts = plan.filter((item) => item.action === "conflict");
|
|
630
|
-
const stamp = migrationStamp();
|
|
631
|
-
const migrationDir = path.join(root, "dev/governance_migrations", stamp);
|
|
632
|
-
const backupDir = path.join(migrationDir, "backup");
|
|
633
|
-
|
|
634
|
-
for (const item of plan) {
|
|
635
|
-
if (item.action !== "create") continue;
|
|
636
|
-
await mkdir(path.dirname(item.targetAbs), { recursive: true });
|
|
637
|
-
if (item.targetRel === "AGENTS.md") {
|
|
638
|
-
const sourceText = await readFile(item.sourceAbs, "utf8");
|
|
639
|
-
await writeFile(item.targetAbs, mergeManagedBlock("", sourceText), "utf8");
|
|
640
|
-
} else {
|
|
641
|
-
await copyFile(item.sourceAbs, item.targetAbs);
|
|
642
|
-
}
|
|
643
|
-
created.push(item.targetRel);
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
await hydrateInitialOpeningPrompt(root, created);
|
|
647
|
-
|
|
648
|
-
for (const item of plan) {
|
|
649
|
-
if (item.action !== "merge") continue;
|
|
650
|
-
const backupPath = path.join(backupDir, item.targetRel);
|
|
651
|
-
await mkdir(path.dirname(backupPath), { recursive: true });
|
|
652
|
-
await copyFile(item.targetAbs, backupPath);
|
|
653
|
-
await writeFile(item.targetAbs, item.mergedText, "utf8");
|
|
654
|
-
merged.push(item.reason ? `${item.targetRel} - ${item.reason}` : item.targetRel);
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
const promptRegenerated = await regeneratePromptFromHandoffIfHotEvidence(root, backupDir, merged);
|
|
658
|
-
if (promptRegenerated) {
|
|
659
|
-
console.log("auto-repair: START_NEXT_SESSION_PROMPT.txt - regenerate prompt from repaired handoff opening message");
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
// R-031.3 v0.3.4+: Inject current CLI version into PROJECT_INDEX template version
|
|
663
|
-
// metadata row — placed AFTER the merge loop to avoid the ordering bug where merge
|
|
664
|
-
// overwrites inject. Merge writes item.mergedText computed at plan-build phase
|
|
665
|
-
// (which contains the pre-inject stale version row); if inject ran before merge,
|
|
666
|
-
// merge would silently revert it. R-016 still protected: only the metadata row
|
|
667
|
-
// mutates, user content rows (External Sources / Fact Base etc.) preserved.
|
|
668
|
-
// The captured metadataUpdated object is passed to writeMigrationReport so the
|
|
669
|
-
// audit trail records this mutation alongside file create/merge operations.
|
|
670
|
-
let metadataUpdated = null;
|
|
671
|
-
if (command === "upgrade" || created.includes("dev/PROJECT_INDEX.md")) {
|
|
672
|
-
const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
|
|
673
|
-
try {
|
|
674
|
-
const text = await readFile(indexPath, "utf8");
|
|
675
|
-
const m = text.match(/\| Agent Handoff Kit template version \| ([\d.]+) \|/);
|
|
676
|
-
if (m && isStableSemver(m[1]) && compareSemver(m[1], version) < 0) {
|
|
677
|
-
const updated = text.replace(
|
|
678
|
-
/\| Agent Handoff Kit template version \| [\d.]+ \|/,
|
|
679
|
-
`| Agent Handoff Kit template version | ${version} |`
|
|
680
|
-
);
|
|
681
|
-
await writeFile(indexPath, updated, "utf8");
|
|
682
|
-
metadataUpdated = {
|
|
683
|
-
file: "dev/PROJECT_INDEX.md",
|
|
684
|
-
field: "Agent Handoff Kit template version",
|
|
685
|
-
from: m[1],
|
|
686
|
-
to: version
|
|
687
|
-
};
|
|
688
|
-
}
|
|
689
|
-
} catch {
|
|
690
|
-
// ignore — doctor anchor (R-016) only checks row existence, not specific value.
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
|
|
694
|
-
const skippedCount = plan.filter((item) => item.action === "skip").length;
|
|
695
|
-
|
|
696
|
-
// R-031 v0.3.1+: scenario branching. Upgrade no-op (零改動) short-circuits — skip
|
|
697
|
-
// migration report, self-check doctor, install banner, onboarding canonical phrase.
|
|
698
|
-
// Prevents misleading "安裝完成" framing when user is just verifying they are latest.
|
|
699
|
-
// R-031.3 v0.3.4+: also short-circuit only when metadata is current. If only the
|
|
700
|
-
// metadata row was stale (counts 0/0/0 but metadataUpdated truthy), user just
|
|
701
|
-
// received a substantive upgrade — proceed through full ceremony so doctor
|
|
702
|
-
// self-check confirms the inject result.
|
|
703
|
-
const isUpgradeNoop = command === "upgrade"
|
|
704
|
-
&& created.length === 0
|
|
705
|
-
&& merged.length === 0
|
|
706
|
-
&& conflicts.length === 0
|
|
707
|
-
&& !metadataUpdated;
|
|
708
|
-
|
|
709
|
-
if (isUpgradeNoop) {
|
|
710
|
-
const noOpHealth = await assessUpgradeNoopHealth(root, version);
|
|
711
|
-
printUpgradeNoopShortCircuit(version, noOpHealth);
|
|
712
|
-
if (!noOpHealth.ok) process.exitCode = 1;
|
|
713
|
-
return;
|
|
714
|
-
}
|
|
715
|
-
|
|
716
|
-
const report = await writeMigrationReport(root, command, mode, plan, created, merged, conflicts, migrationDir, backupDir, metadataUpdated);
|
|
717
|
-
printInstallSummary(version, command, mode, root, {
|
|
718
|
-
created: created.length,
|
|
719
|
-
merged: merged.length,
|
|
720
|
-
skipped: skippedCount,
|
|
721
|
-
conflicts: conflicts.length,
|
|
722
|
-
backupRel: merged.length > 0 ? path.relative(root, backupDir) : null,
|
|
723
|
-
reportRel: path.relative(root, report)
|
|
724
|
-
});
|
|
725
|
-
|
|
726
|
-
// R-031 v0.3.1+: install vs upgrade narrative split.
|
|
727
|
-
if (command === "upgrade") {
|
|
728
|
-
printUpgradeNextSteps(root, conflicts.length);
|
|
729
|
-
} else {
|
|
730
|
-
printInstallNextSteps(root, conflicts.length, mode, skippedCount);
|
|
731
|
-
}
|
|
732
|
-
|
|
733
|
-
// R-024 upgrade.done self-check: after substantive upgrade writes, run doctor automatically.
|
|
734
|
-
// The user must see whether the merged state actually reaches a clean health state.
|
|
735
|
-
if (command === "upgrade" && conflicts.length === 0) {
|
|
736
|
-
console.log("");
|
|
737
|
-
console.log("------------------------------------------------------------");
|
|
738
|
-
console.log("🩺 升級後自動檢查:正在檢查升級後的資料夾");
|
|
739
|
-
console.log("------------------------------------------------------------");
|
|
740
|
-
const doctorStatus = await runDoctor(root, version, { silentCard: true, context: "upgrade-self-check" });
|
|
741
|
-
if (doctorStatus !== "passed") {
|
|
742
|
-
console.log("");
|
|
743
|
-
console.log("⚠️ 升級後自動檢查未通過;請看上方檢查輸出。");
|
|
744
|
-
console.log("📋 下一步:把上面 doctor 輸出貼給 AI,請它先按提示修補後再宣稱 upgrade 完成。");
|
|
745
|
-
process.exitCode = 1;
|
|
746
|
-
} else {
|
|
747
|
-
console.log("");
|
|
748
|
-
console.log("✅ 升級驗收完成:doctor 已通過;可以繼續使用這個項目。");
|
|
749
|
-
}
|
|
750
|
-
}
|
|
751
|
-
|
|
752
|
-
if (conflicts.length > 0) process.exitCode = 1;
|
|
753
|
-
}
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
await executeInstallTransaction(command, root, mode, plan, version);
|
|
711
|
+
}
|
|
754
712
|
|
|
755
|
-
async function
|
|
713
|
+
async function readInstalledTemplateVersion(root) {
|
|
714
|
+
try {
|
|
715
|
+
const text = await readFile(path.join(root, "dev/PROJECT_INDEX.md"), "utf8");
|
|
716
|
+
const match = text.match(/\| Agent Handoff Kit template version \| ([\d.]+) \|/);
|
|
717
|
+
return match && isStableSemver(match[1]) ? match[1] : null;
|
|
718
|
+
} catch {
|
|
719
|
+
return null;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
async function executeInstallTransaction(command, root, mode, plan, version) {
|
|
724
|
+
const outputs = await buildTransactionOutputs(command, root, plan, version);
|
|
725
|
+
if (outputs.length === 0) {
|
|
726
|
+
const health = await assessUpgradeNoopHealth(root, version);
|
|
727
|
+
printUpgradeNoopShortCircuit(version, health);
|
|
728
|
+
if (!health.ok) process.exitCode = 1;
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
const credentialInputs = [];
|
|
733
|
+
for (const relative of requiredTargets) {
|
|
734
|
+
const buffer = await readOptionalBuffer(path.join(root, relative));
|
|
735
|
+
if (buffer) credentialInputs.push({ relative, text: decodeUtf8(buffer, relative).text });
|
|
736
|
+
}
|
|
737
|
+
const credentialFindings = detectCredentialValues(credentialInputs);
|
|
738
|
+
if (credentialFindings.length > 0) {
|
|
739
|
+
console.log("⛔ 升級已停止:待備份的治理檔疑似含有 credential value。");
|
|
740
|
+
console.log("機密值不會顯示或複製;請先移除並輪換機密,再重跑 upgrade。");
|
|
741
|
+
for (const finding of credentialFindings) console.log(`blocked ${finding.relative}:${finding.line} (${finding.label})`);
|
|
742
|
+
process.exitCode = 1;
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
const transaction = await prepareTransaction(root, command, version, outputs, mode, plan);
|
|
747
|
+
try {
|
|
748
|
+
await validateTransactionOverlay(root, outputs);
|
|
749
|
+
transaction.journal.state = "committing";
|
|
750
|
+
await writeSecureJson(transaction.journalPath, transaction.journal);
|
|
751
|
+
|
|
752
|
+
let committedCount = 0;
|
|
753
|
+
const qaFailAfterCommit = Number.parseInt(process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_COMMIT ?? "", 10);
|
|
754
|
+
for (const entry of transaction.journal.entries) {
|
|
755
|
+
const output = outputs.find((item) => item.targetRel === entry.targetRel);
|
|
756
|
+
await atomicReplaceFromBuffer(root, output.targetAbs, output.after, transaction.id);
|
|
757
|
+
entry.committed = true;
|
|
758
|
+
committedCount += 1;
|
|
759
|
+
await writeSecureJson(transaction.journalPath, transaction.journal);
|
|
760
|
+
if (Number.isInteger(qaFailAfterCommit) && qaFailAfterCommit === committedCount) {
|
|
761
|
+
throw new Error(`QA fault injection after committed target ${committedCount}`);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
transaction.journal.committedVersion = version;
|
|
766
|
+
transaction.journal.state = "committed";
|
|
767
|
+
transaction.journal.committedAt = new Date().toISOString();
|
|
768
|
+
await writeSecureJson(transaction.journalPath, transaction.journal);
|
|
769
|
+
if (process.env.AGENT_HANDOFF_KIT_QA_INTERRUPT_AFTER_JOURNAL_COMMIT === "1") {
|
|
770
|
+
const interruption = new Error("QA interruption after committed journal before migration report");
|
|
771
|
+
interruption.code = "ACK_QA_INTERRUPT_AFTER_JOURNAL_COMMIT";
|
|
772
|
+
throw interruption;
|
|
773
|
+
}
|
|
774
|
+
const reportPath = await writeTransactionReport(transaction);
|
|
775
|
+
await unlinkIfExists(transaction.lockPath);
|
|
776
|
+
|
|
777
|
+
const created = outputs.filter((item) => !item.before).map((item) => item.targetRel);
|
|
778
|
+
const merged = outputs.filter((item) => item.before).map((item) => item.reason ? `${item.targetRel} - ${item.reason}` : item.targetRel);
|
|
779
|
+
printInstallSummary(version, command, mode, root, {
|
|
780
|
+
created: created.length,
|
|
781
|
+
merged: merged.length,
|
|
782
|
+
skipped: plan.filter((item) => item.action === "skip").length,
|
|
783
|
+
conflicts: 0,
|
|
784
|
+
backupRel: path.relative(root, transaction.backupDir),
|
|
785
|
+
reportRel: path.relative(root, reportPath)
|
|
786
|
+
});
|
|
787
|
+
if (command === "upgrade") printUpgradeNextSteps(root, 0);
|
|
788
|
+
else printInstallNextSteps(root, 0, mode, plan.filter((item) => item.action === "skip").length);
|
|
789
|
+
|
|
790
|
+
if (command === "upgrade") {
|
|
791
|
+
console.log("");
|
|
792
|
+
console.log("✅ migration committed:離線遷移驗收已通過,版本代表本次成功提交。");
|
|
793
|
+
console.log("🩺 project health:現在執行完整 doctor;它的結果與 migration committed 分開。");
|
|
794
|
+
const doctorStatus = await runDoctor(root, version, { silentCard: true, context: "post-transaction-project-health" });
|
|
795
|
+
if (doctorStatus === "passed") console.log("✅ project health: passed");
|
|
796
|
+
else console.log("⚠️ project health: needs attention; migration remains committed because the deterministic migration gate passed");
|
|
797
|
+
}
|
|
798
|
+
} catch (error) {
|
|
799
|
+
if (error?.code === "ACK_QA_INTERRUPT_AFTER_JOURNAL_COMMIT") throw error;
|
|
800
|
+
transaction.journal.state = "rollback-needed";
|
|
801
|
+
transaction.journal.error = safeErrorLabel(error);
|
|
802
|
+
await writeSecureJson(transaction.journalPath, transaction.journal).catch(() => {});
|
|
803
|
+
const rollback = await rollbackTransaction(root, transaction.journal, transaction.journalPath);
|
|
804
|
+
if (rollback.ok) {
|
|
805
|
+
await unlinkIfExists(transaction.lockPath);
|
|
806
|
+
console.log("⚠️ migration rolled back:遷移驗收或寫入失敗,已復原本次交易所改動的目標。");
|
|
807
|
+
} else {
|
|
808
|
+
console.log("⛔ migration incomplete:現存檔案已出現第三種內容,工具沒有強制回滾以免覆寫後續修改。");
|
|
809
|
+
for (const conflict of rollback.conflicts) console.log(`blocked ${conflict}`);
|
|
810
|
+
}
|
|
811
|
+
throw error;
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
async function buildTransactionOutputs(command, root, plan, version) {
|
|
816
|
+
const byTarget = new Map();
|
|
817
|
+
for (const item of plan) {
|
|
818
|
+
if (item.action !== "create" && item.action !== "merge") continue;
|
|
819
|
+
const before = await readOptionalBuffer(item.targetAbs);
|
|
820
|
+
let afterText;
|
|
821
|
+
if (item.action === "create") {
|
|
822
|
+
const sourceText = await readFile(item.sourceAbs, "utf8");
|
|
823
|
+
afterText = item.targetRel === "AGENTS.md" ? mergeManagedBlock("", sourceText) : sourceText;
|
|
824
|
+
} else {
|
|
825
|
+
afterText = item.mergedText;
|
|
826
|
+
}
|
|
827
|
+
afterText = afterText.replaceAll("<absolute project root>", root);
|
|
828
|
+
byTarget.set(item.targetRel, {
|
|
829
|
+
targetRel: item.targetRel,
|
|
830
|
+
targetAbs: item.targetAbs,
|
|
831
|
+
before,
|
|
832
|
+
afterText,
|
|
833
|
+
reason: item.reason ?? item.action
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
const indexRel = "dev/PROJECT_INDEX.md";
|
|
838
|
+
const indexAbs = path.join(root, indexRel);
|
|
839
|
+
let indexOutput = byTarget.get(indexRel);
|
|
840
|
+
if (!indexOutput && (command === "upgrade" || await exists(indexAbs))) {
|
|
841
|
+
const before = await readOptionalBuffer(indexAbs);
|
|
842
|
+
if (before) indexOutput = { targetRel: indexRel, targetAbs: indexAbs, before, afterText: decodeUtf8(before, indexRel).text, reason: "template version metadata" };
|
|
843
|
+
}
|
|
844
|
+
if (indexOutput) {
|
|
845
|
+
const updated = indexOutput.afterText.replace(/\| Agent Handoff Kit template version \| [\d.]+ \|/, `| Agent Handoff Kit template version | ${version} |`);
|
|
846
|
+
indexOutput.afterText = updated;
|
|
847
|
+
byTarget.set(indexRel, indexOutput);
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
const handoffRel = "dev/SESSION_HANDOFF.md";
|
|
851
|
+
const promptRel = "START_NEXT_SESSION_PROMPT.txt";
|
|
852
|
+
const handoffOutput = byTarget.get(handoffRel);
|
|
853
|
+
const finalHandoffText = handoffOutput?.afterText ?? await readOptionalText(path.join(root, handoffRel));
|
|
854
|
+
if (finalHandoffText) {
|
|
855
|
+
const opening = extractOpeningMessage(finalHandoffText);
|
|
856
|
+
if (opening != null) {
|
|
857
|
+
const promptAbs = path.join(root, promptRel);
|
|
858
|
+
const promptBefore = await readOptionalBuffer(promptAbs);
|
|
859
|
+
const existing = byTarget.get(promptRel);
|
|
860
|
+
byTarget.set(promptRel, {
|
|
861
|
+
targetRel: promptRel,
|
|
862
|
+
targetAbs: promptAbs,
|
|
863
|
+
before: existing?.before ?? promptBefore,
|
|
864
|
+
afterText: opening.replaceAll("<absolute project root>", root),
|
|
865
|
+
reason: "regenerated from authoritative handoff opening message"
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
const outputs = [];
|
|
871
|
+
for (const item of byTarget.values()) {
|
|
872
|
+
const after = encodeLikeExisting(item.afterText, item.before, item.targetRel);
|
|
873
|
+
if (item.before && item.before.equals(after)) continue;
|
|
874
|
+
outputs.push({ ...item, after, beforeHash: item.before ? sha256(item.before) : null, afterHash: sha256(after) });
|
|
875
|
+
}
|
|
876
|
+
return outputs;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
async function prepareTransaction(root, command, version, outputs, mode, plan) {
|
|
880
|
+
const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}`;
|
|
881
|
+
const migrationsRoot = path.join(root, "dev", "governance_migrations");
|
|
882
|
+
const migrationDir = path.join(migrationsRoot, id);
|
|
883
|
+
const backupDir = path.join(migrationDir, "backup");
|
|
884
|
+
const stageDir = path.join(migrationDir, "stage");
|
|
885
|
+
const journalPath = path.join(migrationDir, "transaction.json");
|
|
886
|
+
const lockPath = path.join(migrationsRoot, ".upgrade.lock");
|
|
887
|
+
await mkdir(backupDir, { recursive: true });
|
|
888
|
+
await mkdir(stageDir, { recursive: true });
|
|
889
|
+
await tightenPermissions(migrationsRoot, 0o700);
|
|
890
|
+
await tightenPermissions(migrationDir, 0o700);
|
|
891
|
+
const lock = await open(lockPath, "wx", 0o600).catch((error) => {
|
|
892
|
+
if (error?.code === "EEXIST") throw new Error("another upgrade transaction or unresolved recovery lock is present");
|
|
893
|
+
throw error;
|
|
894
|
+
});
|
|
895
|
+
await lock.writeFile(JSON.stringify({ id, host: hostname(), pid: process.pid, journal: path.relative(root, journalPath) }, null, 2));
|
|
896
|
+
await lock.close();
|
|
897
|
+
|
|
898
|
+
const entries = [];
|
|
899
|
+
for (const output of outputs) {
|
|
900
|
+
const stagePath = path.join(stageDir, output.targetRel);
|
|
901
|
+
await mkdir(path.dirname(stagePath), { recursive: true });
|
|
902
|
+
await writeFile(stagePath, output.after, { mode: 0o600 });
|
|
903
|
+
let backupRel = null;
|
|
904
|
+
if (output.before) {
|
|
905
|
+
const backupPath = path.join(backupDir, output.targetRel);
|
|
906
|
+
await mkdir(path.dirname(backupPath), { recursive: true });
|
|
907
|
+
await writeFile(backupPath, output.before, { mode: 0o600 });
|
|
908
|
+
backupRel = path.relative(root, backupPath);
|
|
909
|
+
}
|
|
910
|
+
entries.push({ targetRel: output.targetRel, existed: Boolean(output.before), beforeHash: output.beforeHash, afterHash: output.afterHash, backupRel, committed: false });
|
|
911
|
+
}
|
|
912
|
+
const journal = {
|
|
913
|
+
id,
|
|
914
|
+
command,
|
|
915
|
+
mode,
|
|
916
|
+
attemptedVersion: version,
|
|
917
|
+
committedVersion: null,
|
|
918
|
+
plannedSkips: plan.filter((item) => item.action === "skip").length,
|
|
919
|
+
host: hostname(),
|
|
920
|
+
pid: process.pid,
|
|
921
|
+
state: "prepared",
|
|
922
|
+
createdAt: new Date().toISOString(),
|
|
923
|
+
entries
|
|
924
|
+
};
|
|
925
|
+
await writeSecureJson(journalPath, journal);
|
|
926
|
+
return { id, migrationDir, backupDir, stageDir, journalPath, lockPath, journal };
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
async function validateTransactionRoot(root, plan, { createMissingRoot = true } = {}) {
|
|
930
|
+
let rootStats;
|
|
931
|
+
try {
|
|
932
|
+
rootStats = await lstat(root);
|
|
933
|
+
} catch (error) {
|
|
934
|
+
if (error?.code !== "ENOENT") throw error;
|
|
935
|
+
if (path.parse(path.resolve(root)).root === path.resolve(root)) throw new Error("selected root cannot be a filesystem root");
|
|
936
|
+
const parent = await nearestExistingParent(path.dirname(root));
|
|
937
|
+
if (!samePath(parent.lexical, parent.real)) throw new Error("selected root resolves through a symbolic link or junction; use the resolved project root");
|
|
938
|
+
if (!createMissingRoot) {
|
|
939
|
+
for (const item of plan) {
|
|
940
|
+
if (item.action !== "create" && item.action !== "merge") continue;
|
|
941
|
+
const relative = path.relative(path.resolve(root), path.resolve(item.targetAbs));
|
|
942
|
+
if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) throw new Error(`target escapes selected root: ${item.targetRel}`);
|
|
943
|
+
}
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
await mkdir(root, { recursive: true });
|
|
947
|
+
rootStats = await lstat(root);
|
|
948
|
+
if (!isInside(parent.real, await realpath(root))) throw new Error("created root escaped its verified parent");
|
|
949
|
+
}
|
|
950
|
+
if (rootStats.isSymbolicLink()) throw new Error("selected root is a symbolic link or junction; use the resolved project root");
|
|
951
|
+
const realRoot = await realpath(root);
|
|
952
|
+
for (const item of plan) {
|
|
953
|
+
if (item.action !== "create" && item.action !== "merge") continue;
|
|
954
|
+
const relative = path.relative(root, item.targetAbs);
|
|
955
|
+
if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) throw new Error(`target escapes selected root: ${item.targetRel}`);
|
|
956
|
+
const parent = await nearestExistingRealParent(path.dirname(item.targetAbs));
|
|
957
|
+
if (!isInside(realRoot, parent)) throw new Error(`target parent resolves outside selected root: ${item.targetRel}`);
|
|
958
|
+
try {
|
|
959
|
+
if ((await lstat(item.targetAbs)).isSymbolicLink()) throw new Error(`target is a symbolic link or junction: ${item.targetRel}`);
|
|
960
|
+
const buffer = await readFile(item.targetAbs);
|
|
961
|
+
decodeUtf8(buffer, item.targetRel);
|
|
962
|
+
} catch (error) {
|
|
963
|
+
if (error?.code !== "ENOENT") throw error;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
async function validateTransactionOverlay(root, outputs) {
|
|
969
|
+
const outputMap = new Map(outputs.map((item) => [item.targetRel, decodeUtf8(item.after, item.targetRel).text]));
|
|
970
|
+
const finalText = async (relative) => outputMap.get(relative) ?? await readOptionalText(path.join(root, relative));
|
|
971
|
+
const failures = [];
|
|
972
|
+
for (const target of requiredTargets) if ((await finalText(target)) == null) failures.push(`${target}: missing after transaction`);
|
|
973
|
+
for (const rule of requiredAnchors) {
|
|
974
|
+
const text = await finalText(rule.target);
|
|
975
|
+
if (text == null) continue;
|
|
976
|
+
for (const failure of requiredAnchorFailures(rule, text)) failures.push(`${rule.target}: ${failure.kind} ${failure.snippet}`);
|
|
977
|
+
}
|
|
978
|
+
for (const rule of schemaChecks) {
|
|
979
|
+
const text = await finalText(rule.target);
|
|
980
|
+
if (text == null) continue;
|
|
981
|
+
for (const check of rule.checks) if (!check.test(text)) failures.push(`${rule.target}: ${check.label}`);
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
const handoffText = await finalText("dev/SESSION_HANDOFF.md");
|
|
985
|
+
const promptText = await finalText("START_NEXT_SESSION_PROMPT.txt");
|
|
986
|
+
if (handoffText && promptText) {
|
|
987
|
+
const otherTexts = [];
|
|
988
|
+
for (const target of requiredTargets) {
|
|
989
|
+
if (target === "dev/SESSION_HANDOFF.md" || target === "START_NEXT_SESSION_PROMPT.txt") continue;
|
|
990
|
+
const text = await finalText(target);
|
|
991
|
+
if (text) otherTexts.push({ relative: target, text });
|
|
992
|
+
}
|
|
993
|
+
const mirror = assessPromptMirrorTexts(handoffText, promptText, otherTexts);
|
|
994
|
+
if (!mirror.ok) failures.push(`prompt mirror: ${mirror.reason}`);
|
|
995
|
+
}
|
|
996
|
+
const bridgeFailures = await validateBridgeTexts(finalText);
|
|
997
|
+
failures.push(...bridgeFailures);
|
|
998
|
+
if (failures.length > 0) throw new Error(`migration acceptance gate failed: ${failures.slice(0, 12).join("; ")}${failures.length > 12 ? `; +${failures.length - 12} more` : ""}`);
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
async function validateBridgeTexts(finalText) {
|
|
1002
|
+
const failures = [];
|
|
1003
|
+
for (const target of ["CLAUDE.md", "GEMINI.md"]) {
|
|
1004
|
+
const failure = bridgeTextFailure(target, await finalText(target) ?? "");
|
|
1005
|
+
if (failure) failures.push(`${target}: ${failure}`);
|
|
1006
|
+
}
|
|
1007
|
+
return failures;
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
function bridgeTextFailure(targetRel, text) {
|
|
1011
|
+
const active = stripMarkdownCommentsAndFences(text);
|
|
1012
|
+
if (targetRel === "CLAUDE.md") {
|
|
1013
|
+
const imports = active.split(/\r?\n/).filter((line) => line.trim() === "@AGENTS.md");
|
|
1014
|
+
return imports.length === 1 ? null : `expected one active @AGENTS.md import, found ${imports.length}`;
|
|
1015
|
+
}
|
|
1016
|
+
if (targetRel === "GEMINI.md") {
|
|
1017
|
+
return /^Authoritative operating rules remain in `AGENTS\.md`\.\s*$/m.test(active)
|
|
1018
|
+
&& /^2\. Read `AGENTS\.md`\.\s*$/m.test(active)
|
|
1019
|
+
? null
|
|
1020
|
+
: "active AGENTS.md bridge instructions missing or misplaced";
|
|
1021
|
+
}
|
|
1022
|
+
return "unknown bridge target";
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
async function atomicReplaceFromBuffer(root, targetAbs, buffer, id) {
|
|
1026
|
+
const relative = path.relative(root, targetAbs);
|
|
1027
|
+
if (relative.startsWith("..") || path.isAbsolute(relative)) throw new Error("atomic target escaped root");
|
|
1028
|
+
await mkdir(path.dirname(targetAbs), { recursive: true });
|
|
1029
|
+
const tempPath = path.join(path.dirname(targetAbs), `.${path.basename(targetAbs)}.ack-${id}.tmp`);
|
|
1030
|
+
await writeFile(tempPath, buffer, { mode: 0o600 });
|
|
1031
|
+
await rename(tempPath, targetAbs);
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
async function rollbackTransaction(root, journal, journalPath) {
|
|
1035
|
+
const conflicts = [];
|
|
1036
|
+
for (const entry of [...journal.entries].reverse()) {
|
|
1037
|
+
if (!entry.committed) continue;
|
|
1038
|
+
const targetAbs = path.join(root, entry.targetRel);
|
|
1039
|
+
const current = await readOptionalBuffer(targetAbs);
|
|
1040
|
+
const currentHash = current ? sha256(current) : null;
|
|
1041
|
+
if (currentHash === entry.beforeHash) continue;
|
|
1042
|
+
if (currentHash !== entry.afterHash) {
|
|
1043
|
+
conflicts.push(`${entry.targetRel}: current content differs from both transaction input and candidate`);
|
|
1044
|
+
continue;
|
|
1045
|
+
}
|
|
1046
|
+
if (entry.existed) {
|
|
1047
|
+
const backup = await readFile(path.join(root, entry.backupRel));
|
|
1048
|
+
await atomicReplaceFromBuffer(root, targetAbs, backup, `${journal.id}-rollback`);
|
|
1049
|
+
} else {
|
|
1050
|
+
await unlink(targetAbs);
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
journal.state = conflicts.length === 0 ? "rolled-back" : "manual-recovery-required";
|
|
1054
|
+
journal.committedVersion = null;
|
|
1055
|
+
journal.rollbackAt = new Date().toISOString();
|
|
1056
|
+
journal.recoveryConflicts = conflicts;
|
|
1057
|
+
await writeSecureJson(journalPath, journal).catch(() => {});
|
|
1058
|
+
return { ok: conflicts.length === 0, conflicts };
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
async function recoverInterruptedTransaction(root) {
|
|
1062
|
+
const lockPath = path.join(root, "dev", "governance_migrations", ".upgrade.lock");
|
|
1063
|
+
let lock;
|
|
1064
|
+
try {
|
|
1065
|
+
lock = JSON.parse(await readFile(lockPath, "utf8"));
|
|
1066
|
+
} catch (error) {
|
|
1067
|
+
if (error?.code === "ENOENT") return;
|
|
1068
|
+
throw new Error("upgrade lock exists but is unreadable; no writes attempted");
|
|
1069
|
+
}
|
|
1070
|
+
if (lock.host === hostname() && processIsAlive(lock.pid)) throw new Error(`another upgrade process is active (pid ${lock.pid})`);
|
|
1071
|
+
if (lock.host && lock.host !== hostname()) throw new Error(`upgrade lock belongs to another host (${lock.host}); no automatic recovery attempted`);
|
|
1072
|
+
const journalPath = path.resolve(root, lock.journal ?? "");
|
|
1073
|
+
if (!isInside(root, journalPath)) throw new Error("upgrade lock journal path escapes selected root");
|
|
1074
|
+
let journal;
|
|
1075
|
+
try {
|
|
1076
|
+
journal = JSON.parse(await readFile(journalPath, "utf8"));
|
|
1077
|
+
} catch {
|
|
1078
|
+
throw new Error("incomplete upgrade lock has no readable journal; no automatic recovery attempted");
|
|
1079
|
+
}
|
|
1080
|
+
if (journal.state === "committed") {
|
|
1081
|
+
if (!journal.committedVersion) journal.committedVersion = journal.attemptedVersion;
|
|
1082
|
+
const migrationDir = path.dirname(journalPath);
|
|
1083
|
+
await writeSecureJson(journalPath, journal);
|
|
1084
|
+
await writeTransactionReport({ id: journal.id, migrationDir, journal });
|
|
1085
|
+
await unlinkIfExists(lockPath);
|
|
1086
|
+
console.log("⚠️ recovered committed upgrade: migration report was verified or rebuilt before planning this run");
|
|
1087
|
+
return;
|
|
1088
|
+
}
|
|
1089
|
+
if (journal.state === "rolled-back") {
|
|
1090
|
+
await unlinkIfExists(lockPath);
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
const rollback = await rollbackTransaction(root, journal, journalPath);
|
|
1094
|
+
if (!rollback.ok) throw new Error(`interrupted upgrade has third-state edits: ${rollback.conflicts.join("; ")}`);
|
|
1095
|
+
await unlinkIfExists(lockPath);
|
|
1096
|
+
console.log("⚠️ recovered interrupted upgrade: transaction-owned changes were safely rolled back before planning this run");
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
async function writeTransactionReport(transaction) {
|
|
1100
|
+
const reportPath = path.join(transaction.migrationDir, "migration-report.md");
|
|
1101
|
+
const lines = [
|
|
1102
|
+
"# Agent Handoff Kit Migration Report",
|
|
1103
|
+
"",
|
|
1104
|
+
`- Transaction: ${transaction.id}`,
|
|
1105
|
+
`- Mode: ${transaction.journal.mode ?? "unknown"}`,
|
|
1106
|
+
`- Attempted version: ${transaction.journal.attemptedVersion}`,
|
|
1107
|
+
`- Committed version: ${transaction.journal.committedVersion ?? "none"}`,
|
|
1108
|
+
`- Transaction state: ${transaction.journal.state}`,
|
|
1109
|
+
`- Created at: ${transaction.journal.createdAt}`,
|
|
1110
|
+
`- Committed at: ${transaction.journal.committedAt}`,
|
|
1111
|
+
"- Credential values: not recorded",
|
|
1112
|
+
"",
|
|
1113
|
+
"## Actions",
|
|
1114
|
+
"",
|
|
1115
|
+
...transaction.journal.entries.map((entry) => `- ${entry.existed ? "merge" : "create"}: ${entry.targetRel}; backup=${entry.backupRel ?? "none"}; committed=${entry.committed}`),
|
|
1116
|
+
"",
|
|
1117
|
+
`- Planned skips: ${transaction.journal.plannedSkips ?? "unknown"}`,
|
|
1118
|
+
"- Conflicts: 0"
|
|
1119
|
+
];
|
|
1120
|
+
await writeFile(reportPath, `${lines.join("\n")}\n`, { mode: 0o600 });
|
|
1121
|
+
await tightenPermissions(reportPath, 0o600);
|
|
1122
|
+
return reportPath;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
function decodeUtf8(buffer, relative) {
|
|
1126
|
+
const bom = buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf;
|
|
1127
|
+
const body = bom ? buffer.subarray(3) : buffer;
|
|
1128
|
+
let text;
|
|
1129
|
+
try {
|
|
1130
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(body);
|
|
1131
|
+
} catch {
|
|
1132
|
+
throw new Error(`${relative}: invalid UTF-8; conflict required`);
|
|
1133
|
+
}
|
|
1134
|
+
const crlfCount = (text.match(/\r\n/g) ?? []).length;
|
|
1135
|
+
const loneLfCount = (text.match(/(^|[^\r])\n/g) ?? []).length;
|
|
1136
|
+
return {
|
|
1137
|
+
text,
|
|
1138
|
+
bom,
|
|
1139
|
+
newline: crlfCount > loneLfCount ? "\r\n" : "\n",
|
|
1140
|
+
mixed: crlfCount > 0 && loneLfCount > 0
|
|
1141
|
+
};
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
function encodeLikeExisting(text, before, relative) {
|
|
1145
|
+
if (!before) return Buffer.from(text.replace(/\r\n?/g, "\n"), "utf8");
|
|
1146
|
+
const style = decodeUtf8(before, relative);
|
|
1147
|
+
const normalized = text.replace(/\r\n?/g, "\n").replace(/\n/g, style.newline);
|
|
1148
|
+
return style.bom ? Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from(normalized, "utf8")]) : Buffer.from(normalized, "utf8");
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
function detectCredentialValues(items) {
|
|
1152
|
+
const findings = [];
|
|
1153
|
+
for (const item of items) {
|
|
1154
|
+
for (const { pattern, label } of credentialLeakPatterns) {
|
|
1155
|
+
const match = item.text.match(pattern);
|
|
1156
|
+
if (match) findings.push({ relative: item.relative, line: item.text.slice(0, match.index).split("\n").length, label });
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
return findings;
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
async function nearestExistingRealParent(start) {
|
|
1163
|
+
let current = path.resolve(start);
|
|
1164
|
+
while (true) {
|
|
1165
|
+
try { return await realpath(current); } catch (error) {
|
|
1166
|
+
if (error?.code !== "ENOENT") throw error;
|
|
1167
|
+
const parent = path.dirname(current);
|
|
1168
|
+
if (parent === current) throw error;
|
|
1169
|
+
current = parent;
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
async function nearestExistingParent(start) {
|
|
1175
|
+
let current = path.resolve(start);
|
|
1176
|
+
while (true) {
|
|
1177
|
+
try { return { lexical: current, real: await realpath(current) }; } catch (error) {
|
|
1178
|
+
if (error?.code !== "ENOENT") throw error;
|
|
1179
|
+
const parent = path.dirname(current);
|
|
1180
|
+
if (parent === current) throw error;
|
|
1181
|
+
current = parent;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
function samePath(left, right) {
|
|
1187
|
+
const normalize = (value) => process.platform === "win32" ? path.resolve(value).toLowerCase() : path.resolve(value);
|
|
1188
|
+
return normalize(left) === normalize(right);
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
function isInside(root, candidate) {
|
|
1192
|
+
const relative = path.relative(path.resolve(root), path.resolve(candidate));
|
|
1193
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
function sha256(buffer) {
|
|
1197
|
+
return createHash("sha256").update(buffer).digest("hex");
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
async function readOptionalBuffer(filePath) {
|
|
1201
|
+
try { return await readFile(filePath); } catch (error) { if (error?.code === "ENOENT") return null; throw error; }
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
async function readOptionalText(filePath) {
|
|
1205
|
+
const buffer = await readOptionalBuffer(filePath);
|
|
1206
|
+
return buffer ? decodeUtf8(buffer, filePath).text : null;
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
async function writeSecureJson(filePath, value) {
|
|
1210
|
+
await writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
1211
|
+
await tightenPermissions(filePath, 0o600);
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
async function tightenPermissions(filePath, mode) {
|
|
1215
|
+
try { await chmod(filePath, mode); } catch { /* best effort on platforms without POSIX modes */ }
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
async function unlinkIfExists(filePath) {
|
|
1219
|
+
try { await unlink(filePath); } catch (error) { if (error?.code !== "ENOENT") throw error; }
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
function processIsAlive(pid) {
|
|
1223
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
1224
|
+
try { process.kill(pid, 0); return true; } catch { return false; }
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
async function assertDryRunHasNoPendingTransaction(root) {
|
|
1228
|
+
const lockPath = path.join(root, "dev", "governance_migrations", ".upgrade.lock");
|
|
1229
|
+
try {
|
|
1230
|
+
await lstat(lockPath);
|
|
1231
|
+
} catch (error) {
|
|
1232
|
+
if (error?.code === "ENOENT") return;
|
|
1233
|
+
throw error;
|
|
1234
|
+
}
|
|
1235
|
+
throw new Error("dry-run blocked: an unresolved transaction requires a non-dry-run recovery; no files written");
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
function stripMarkdownCommentsAndFences(text) {
|
|
1239
|
+
return text.replace(/<!--[\s\S]*?-->/g, "").replace(/```[\s\S]*?```/g, "");
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
function safeErrorLabel(error) {
|
|
1243
|
+
return String(error?.message ?? error).slice(0, 500);
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
async function runDoctor(root, version, options = {}) {
|
|
756
1247
|
if (!options.silentCard) printCard(version, "doctor ready", "o.o");
|
|
757
1248
|
const rows = [];
|
|
758
1249
|
for (const target of requiredTargets) {
|
|
@@ -815,7 +1306,7 @@ async function runDoctor(root, version, options = {}) {
|
|
|
815
1306
|
}
|
|
816
1307
|
}
|
|
817
1308
|
|
|
818
|
-
if (schemaFailures.length > 0) {
|
|
1309
|
+
if (schemaFailures.length > 0) {
|
|
819
1310
|
printDoctorSummary(version, root, "needs-fix", {
|
|
820
1311
|
checked: rows.length + anchorRows.length + schemaRows.length,
|
|
821
1312
|
failedKind: "schema checks",
|
|
@@ -823,10 +1314,25 @@ async function runDoctor(root, version, options = {}) {
|
|
|
823
1314
|
nextStep: "把這段 doctor 輸出貼給 AI,請它先修交接結構,不要直接重裝覆蓋。"
|
|
824
1315
|
});
|
|
825
1316
|
process.exitCode = 1;
|
|
826
|
-
return "failed";
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
const
|
|
1317
|
+
return "failed";
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
const bridgeFailures = await validateBridgeTexts(async (relative) => readOptionalText(path.join(root, relative)));
|
|
1321
|
+
console.log(`\nbridge checks: 2`);
|
|
1322
|
+
console.log(`${bridgeFailures.length === 0 ? "ok" : "missing"} CLAUDE.md / GEMINI.md (active one-hop AGENTS.md bridges)`);
|
|
1323
|
+
for (const finding of bridgeFailures) console.log(` missing: ${finding}`);
|
|
1324
|
+
if (bridgeFailures.length > 0) {
|
|
1325
|
+
printDoctorSummary(version, root, "needs-fix", {
|
|
1326
|
+
checked: rows.length + anchorRows.length + schemaRows.length + 2,
|
|
1327
|
+
failedKind: "bridge checks",
|
|
1328
|
+
failedCount: bridgeFailures.length,
|
|
1329
|
+
nextStep: "修正 CLAUDE.md / GEMINI.md 的有效橋接指令;註解、程式碼區塊或重複字樣不能代替真實路由。"
|
|
1330
|
+
});
|
|
1331
|
+
process.exitCode = 1;
|
|
1332
|
+
return "failed";
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
const researchTraceResult = await checkResearchDecisionTrace(root);
|
|
830
1336
|
console.log(`\nresearch decision trace checks: ${researchTraceResult.checked}`);
|
|
831
1337
|
console.log(`${researchTraceResult.ok ? "ok" : "missing"} dev/PROJECT_DECISIONS.md (research-derived decision evidence chains)`);
|
|
832
1338
|
if (!researchTraceResult.ok) {
|
|
@@ -862,7 +1368,7 @@ async function runDoctor(root, version, options = {}) {
|
|
|
862
1368
|
|
|
863
1369
|
const artifactResult = await checkGeneratedMarkdownGovernance(root);
|
|
864
1370
|
console.log(`\ngenerated markdown governance checks: ${artifactResult.checked}`);
|
|
865
|
-
console.log(`${artifactResult.ok ? "ok" : "missing"} dev/PROJECT_INDEX.md (generated Markdown
|
|
1371
|
+
console.log(`${artifactResult.ok ? "ok" : "missing"} dev/PROJECT_INDEX.md (generated Markdown registration; other formats require human review)`);
|
|
866
1372
|
if (!artifactResult.ok) {
|
|
867
1373
|
for (const finding of artifactResult.findings) {
|
|
868
1374
|
console.log(` missing: ${finding}`);
|
|
@@ -871,7 +1377,7 @@ async function runDoctor(root, version, options = {}) {
|
|
|
871
1377
|
checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked + temperatureResult.checked + artifactResult.checked,
|
|
872
1378
|
failedKind: "generated markdown governance checks",
|
|
873
1379
|
failedCount: artifactResult.findings.length,
|
|
874
|
-
nextStep: "把新生成或新修改的 Markdown
|
|
1380
|
+
nextStep: "把新生成或新修改的 Markdown 登記到 dev/PROJECT_INDEX.md,或在 SESSION_LOG / task summary 以同一紀錄精確標成 draft、temporary 或 one-time evidence;如內容重複,先合併到單一真源。其他持久格式須由 AI 另作人工治理核對。"
|
|
875
1381
|
});
|
|
876
1382
|
process.exitCode = 1;
|
|
877
1383
|
return "failed";
|
|
@@ -1073,15 +1579,38 @@ function isGeneratedArtifactCandidate(rel) {
|
|
|
1073
1579
|
|
|
1074
1580
|
function isArtifactGoverned(rel, { indexText, logText, handoffText }) {
|
|
1075
1581
|
const normalized = rel.replaceAll("\\", "/");
|
|
1076
|
-
if (indexText
|
|
1582
|
+
if (projectIndexRegistersExactPath(indexText, normalized)) return true;
|
|
1583
|
+
return textExplicitlyClassifiesExactArtifact(logText, normalized)
|
|
1584
|
+
|| textExplicitlyClassifiesExactArtifact(handoffText, normalized);
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
function projectIndexRegistersExactPath(indexText, normalized) {
|
|
1588
|
+
const active = stripMarkdownCommentsAndFences(indexText);
|
|
1589
|
+
for (const line of active.split(/\r?\n/)) {
|
|
1590
|
+
if (!line.trim().startsWith("|")) continue;
|
|
1591
|
+
const cells = line.split("|").slice(1, -1);
|
|
1592
|
+
for (const rawCell of cells) {
|
|
1593
|
+
const cell = rawCell.trim().replace(/^`([^`]+)`$/, "$1");
|
|
1594
|
+
if (cell === normalized) return true;
|
|
1595
|
+
const link = /^\[[^\]]*\]\(([^)]+)\)$/.exec(cell);
|
|
1596
|
+
if (link && link[1].replace(/^<|>$/g, "") === normalized) return true;
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
return false;
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
function textExplicitlyClassifiesExactArtifact(text, normalized) {
|
|
1603
|
+
const active = stripMarkdownCommentsAndFences(text);
|
|
1077
1604
|
const escaped = normalized.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1078
|
-
const
|
|
1079
|
-
const
|
|
1080
|
-
const
|
|
1081
|
-
|
|
1082
|
-
||
|
|
1083
|
-
|
|
1084
|
-
|
|
1605
|
+
const exactPath = new RegExp(`(?:^|[\\s\`|([<])${escaped}(?=$|[\\s\`|)\\]>.,;:])`, "i");
|
|
1606
|
+
const label = /(draft|temporary|one-time evidence|non-authoritative|not source of truth|草稿|臨時|暫存|一次性|非真源|非權威)/i;
|
|
1607
|
+
const markdownPath = /(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.md\b/gi;
|
|
1608
|
+
for (const line of active.split(/\r?\n/)) {
|
|
1609
|
+
if (!exactPath.test(line) || !label.test(line)) continue;
|
|
1610
|
+
const paths = new Set((line.match(markdownPath) ?? []).map((item) => item.replaceAll("\\", "/").toLowerCase()));
|
|
1611
|
+
if (paths.size === 1 && paths.has(normalized.toLowerCase())) return true;
|
|
1612
|
+
}
|
|
1613
|
+
return false;
|
|
1085
1614
|
}
|
|
1086
1615
|
|
|
1087
1616
|
function stripFencedCodeBlocks(text) {
|
|
@@ -1173,29 +1702,7 @@ function lineHasCurrentStateEvidence(line, options = {}) {
|
|
|
1173
1702
|
return currentStateEvidenceFindings("line", line, options).length > 0;
|
|
1174
1703
|
}
|
|
1175
1704
|
|
|
1176
|
-
function
|
|
1177
|
-
if (text.includes(rootMismatchGuard)) return { changed: false, text };
|
|
1178
|
-
const bounds = handoffSectionContentBounds(text, "next-session-opening-message", "Next Session Opening Message");
|
|
1179
|
-
if (!bounds) return { changed: false, text };
|
|
1180
|
-
const section = text.slice(bounds.start, bounds.end);
|
|
1181
|
-
if (!section.includes("```text")) return { changed: false, text };
|
|
1182
|
-
|
|
1183
|
-
let repairedSection = section;
|
|
1184
|
-
if (/^Before changing anything,/m.test(repairedSection)) {
|
|
1185
|
-
repairedSection = repairedSection.replace(/^Before changing anything,/m, `${rootMismatchGuard}, stop and ask for confirmation.\n\nBefore changing anything,`);
|
|
1186
|
-
} else if (/\n```/.test(repairedSection)) {
|
|
1187
|
-
repairedSection = repairedSection.replace(/\n```/, `\n${rootMismatchGuard}, stop and ask for confirmation.\n\n\`\`\``);
|
|
1188
|
-
} else {
|
|
1189
|
-
return { changed: false, text };
|
|
1190
|
-
}
|
|
1191
|
-
|
|
1192
|
-
return {
|
|
1193
|
-
changed: repairedSection !== section,
|
|
1194
|
-
text: `${text.slice(0, bounds.start)}${repairedSection}${text.slice(bounds.end)}`
|
|
1195
|
-
};
|
|
1196
|
-
}
|
|
1197
|
-
|
|
1198
|
-
function repairHandoffCurrentStateEvidenceBoundary(text) {
|
|
1705
|
+
function repairHandoffCurrentStateEvidenceBoundary(text) {
|
|
1199
1706
|
let repaired = text;
|
|
1200
1707
|
let changed = false;
|
|
1201
1708
|
for (const section of [
|
|
@@ -1292,23 +1799,7 @@ function getFirstUseNextStep(root, lastCloseout) {
|
|
|
1292
1799
|
// R-030 v0.3.0+: Credential leak prevention sweep. Scans dev/PROJECT_INDEX.md,
|
|
1293
1800
|
// dev/SESSION_HANDOFF.md, dev/SESSION_LOG.md for common credential prefix patterns.
|
|
1294
1801
|
// Credentials must live in OS-level secure storage or AI-tool config, never in dev/*.
|
|
1295
|
-
async function checkInstalledIntegrationsCredentialLeak(root) {
|
|
1296
|
-
const credentialPatterns = [
|
|
1297
|
-
{ pattern: /sk-ant-[A-Za-z0-9_-]{20,}/, label: "Anthropic API key (sk-ant-)" },
|
|
1298
|
-
{ pattern: /\bsk-[A-Za-z0-9_-]{20,}/, label: "OpenAI / generic sk- prefix" },
|
|
1299
|
-
{ pattern: /\bntn_[A-Za-z0-9_-]{40,}/, label: "Notion Integration Token (ntn_)" },
|
|
1300
|
-
{ pattern: /\bsecret_[A-Za-z0-9_-]{40,}/, label: "Notion legacy secret_ token" },
|
|
1301
|
-
{ pattern: /\bya29\.[A-Za-z0-9_-]{20,}/, label: "Google OAuth access token (ya29.)" },
|
|
1302
|
-
{ pattern: /\b1\/\/[A-Za-z0-9_-]{30,}/, label: "Google refresh token (1//)" },
|
|
1303
|
-
{ pattern: /\bxox[abprs]-[A-Za-z0-9-]{10,}/, label: "Slack token (xoxp-/xoxb-/etc)" },
|
|
1304
|
-
{ pattern: /\bghp_[A-Za-z0-9]{36}/, label: "GitHub Personal Access Token (ghp_)" },
|
|
1305
|
-
{ pattern: /\bgho_[A-Za-z0-9]{36}/, label: "GitHub OAuth token (gho_)" },
|
|
1306
|
-
{ pattern: /\bghs_[A-Za-z0-9]{36}/, label: "GitHub server token (ghs_)" },
|
|
1307
|
-
{ pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}/, label: "GitHub fine-grained PAT (github_pat_)" },
|
|
1308
|
-
{ pattern: /\bsl\.[A-Za-z0-9_-]{50,}/, label: "Dropbox token (sl.)" },
|
|
1309
|
-
{ pattern: /\bAKIA[A-Z0-9]{16}/, label: "AWS access key (AKIA)" },
|
|
1310
|
-
{ pattern: /\bAIza[A-Za-z0-9_-]{35}/, label: "Google API key (AIza)" }
|
|
1311
|
-
];
|
|
1802
|
+
async function checkInstalledIntegrationsCredentialLeak(root) {
|
|
1312
1803
|
const targetFiles = [
|
|
1313
1804
|
"dev/PROJECT_INDEX.md",
|
|
1314
1805
|
"dev/SESSION_HANDOFF.md",
|
|
@@ -1323,7 +1814,7 @@ async function checkInstalledIntegrationsCredentialLeak(root) {
|
|
|
1323
1814
|
} catch {
|
|
1324
1815
|
continue;
|
|
1325
1816
|
}
|
|
1326
|
-
for (const { pattern, label } of
|
|
1817
|
+
for (const { pattern, label } of credentialLeakPatterns) {
|
|
1327
1818
|
const match = text.match(pattern);
|
|
1328
1819
|
if (match) {
|
|
1329
1820
|
const line = text.slice(0, match.index).split("\n").length;
|
|
@@ -1347,7 +1838,7 @@ function printDoctorSummary(version, root, mode, details) {
|
|
|
1347
1838
|
}
|
|
1348
1839
|
} else {
|
|
1349
1840
|
console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
|
|
1350
|
-
console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : details.failedKind === "research decision trace checks" ? "研究導向決策缺少可追溯來源鏈。" : details.failedKind === "handoff temperature boundary checks" ? "當前交接內容混入一次性或歷史證據。" : details.failedKind === "generated markdown governance checks" ? "有 Markdown
|
|
1841
|
+
console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : details.failedKind === "research decision trace checks" ? "研究導向決策缺少可追溯來源鏈。" : details.failedKind === "handoff temperature boundary checks" ? "當前交接內容混入一次性或歷史證據。" : details.failedKind === "generated markdown governance checks" ? "有 Markdown 未完成登記、同步或精確臨時分類;其他持久格式須另作人工治理核對。" : "下次開工提示副本與 handoff 真源不同。"}`);
|
|
1351
1842
|
}
|
|
1352
1843
|
console.log("");
|
|
1353
1844
|
console.log(`📦 版本:v${version}`);
|
|
@@ -1410,22 +1901,8 @@ async function hydrateInitialOpeningPrompt(root, created) {
|
|
|
1410
1901
|
}
|
|
1411
1902
|
}
|
|
1412
1903
|
|
|
1413
|
-
async function checkPromptMirror(root) {
|
|
1414
|
-
const
|
|
1415
|
-
const promptPath = path.join(root, "START_NEXT_SESSION_PROMPT.txt");
|
|
1416
|
-
let handoffText = "";
|
|
1417
|
-
let promptText = "";
|
|
1418
|
-
try {
|
|
1419
|
-
handoffText = await readFile(handoffPath, "utf8");
|
|
1420
|
-
} catch {
|
|
1421
|
-
return [{ target: "START_NEXT_SESSION_PROMPT.txt", label: "matches handoff opening message", ok: false, reason: "handoff unreadable" }];
|
|
1422
|
-
}
|
|
1423
|
-
try {
|
|
1424
|
-
promptText = await readFile(promptPath, "utf8");
|
|
1425
|
-
} catch {
|
|
1426
|
-
return [{ target: "START_NEXT_SESSION_PROMPT.txt", label: "matches handoff opening message", ok: false, reason: "prompt copy unreadable" }];
|
|
1427
|
-
}
|
|
1428
|
-
const mirror = assessPromptMirrorTexts(handoffText, promptText);
|
|
1904
|
+
async function checkPromptMirror(root) {
|
|
1905
|
+
const mirror = assessPromptMirrorRoot(root);
|
|
1429
1906
|
return [{
|
|
1430
1907
|
target: "START_NEXT_SESSION_PROMPT.txt",
|
|
1431
1908
|
label: "matches handoff opening message",
|
|
@@ -1434,19 +1911,128 @@ async function checkPromptMirror(root) {
|
|
|
1434
1911
|
}];
|
|
1435
1912
|
}
|
|
1436
1913
|
|
|
1437
|
-
function assessHandoffLifecycleConsistency(text) {
|
|
1438
|
-
const fieldValue = fieldValueAfterMarker(text, "lifecycle-conflicts-resolved");
|
|
1439
|
-
if (
|
|
1440
|
-
return { ok:
|
|
1441
|
-
}
|
|
1442
|
-
if (
|
|
1443
|
-
return { ok: false, reason: "lifecycle field is
|
|
1444
|
-
}
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
}
|
|
1914
|
+
function assessHandoffLifecycleConsistency(text) {
|
|
1915
|
+
const fieldValue = fieldValueAfterMarker(text, "lifecycle-conflicts-resolved");
|
|
1916
|
+
if (isUnresolvedLifecycleFieldValue(fieldValue)) {
|
|
1917
|
+
return { ok: false, reason: "lifecycle field is explicitly unresolved" };
|
|
1918
|
+
}
|
|
1919
|
+
if (isPlaceholderLifecycleFieldValue(fieldValue) && hasSubstantiveHandoffState(text)) {
|
|
1920
|
+
return { ok: false, reason: "lifecycle field is still placeholder after handoff content changed" };
|
|
1921
|
+
}
|
|
1922
|
+
const contradictions = findHandoffLifecycleContradictions(text);
|
|
1923
|
+
if (contradictions.length > 0) {
|
|
1924
|
+
return { ok: false, reason: `resolved work overlaps unresolved carry-forward state: ${contradictions[0]}` };
|
|
1925
|
+
}
|
|
1926
|
+
return { ok: true, reason: "" };
|
|
1927
|
+
}
|
|
1928
|
+
|
|
1929
|
+
function handoffStateLines(text, markerId, headingTitle) {
|
|
1930
|
+
const sectionText = markerId === "next-session-opening-message"
|
|
1931
|
+
? (extractOpeningMessage(text) ?? "")
|
|
1932
|
+
: extractSectionText(text, markerId, headingTitle);
|
|
1933
|
+
return sectionText
|
|
1934
|
+
.replace(/```[\s\S]*?```/g, "")
|
|
1935
|
+
.split(/\r?\n/)
|
|
1936
|
+
.map((line) => line.replace(/^[-*\d.)\s]+/, "").trim())
|
|
1937
|
+
.filter((line) => line.length > 3 && !line.startsWith("##") && !line.startsWith("<!--") && !/^(TBD|none|n\/a|未適用|無)$/i.test(line))
|
|
1938
|
+
.filter((line) => markerId !== "next-session-opening-message" || !isOwnedOpeningLifecycleBoilerplate(line));
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
function isOwnedOpeningLifecycleBoilerplate(line) {
|
|
1942
|
+
return /^Resume the current objective\. If my message or the handoff already gives an executable task, begin its first safe action in this response\./i.test(line)
|
|
1943
|
+
|| /^A fresh install only makes guidance available; it does not force onboarding\./i.test(line)
|
|
1944
|
+
|| /^Load onboarding only when I explicitly ask for guidance or no executable objective remains after state reading\./i.test(line);
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1947
|
+
function stripResolvedNegatedActionClauses(line) {
|
|
1948
|
+
return line.split(/(?<=[.;;。])\s*/).filter((clause) => {
|
|
1949
|
+
const negated = /\b(?:no|not|never|without|did not|has not|have not)\b/i.test(clause);
|
|
1950
|
+
const action = /\b(?:commit|push|tag|release|publish|deploy|deployment|sync|write|upgrade)\b/i.test(clause);
|
|
1951
|
+
return !(negated && action);
|
|
1952
|
+
}).join(" ");
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1955
|
+
const ignoredLifecycleEnglish = new Set([
|
|
1956
|
+
"completed", "complete", "finish", "finished", "continue", "incomplete", "passed", "verified", "pending", "blocked", "follow", "scope",
|
|
1957
|
+
"monitor", "only", "reopened", "recommended", "next", "step", "session", "current", "work", "task", "with",
|
|
1958
|
+
"from", "that", "this", "handoff", "lifecycle", "migration", "regression", "agent", "reason", "condition",
|
|
1959
|
+
"the", "and", "for", "into", "still", "remains"
|
|
1960
|
+
]);
|
|
1961
|
+
|
|
1962
|
+
function lifecycleEnglishTokens(line, stripNegated = false) {
|
|
1963
|
+
const source = stripNegated ? stripResolvedNegatedActionClauses(line) : line;
|
|
1964
|
+
return (source.toLowerCase().match(/[a-z0-9][a-z0-9_-]{2,}/g) ?? [])
|
|
1965
|
+
.filter((token) => !ignoredLifecycleEnglish.has(token));
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1968
|
+
function lifecycleTopicWindows(line, stripNegated = false) {
|
|
1969
|
+
const source = stripNegated ? stripResolvedNegatedActionClauses(line) : line;
|
|
1970
|
+
const englishTokens = lifecycleEnglishTokens(source);
|
|
1971
|
+
const english = Array.from({ length: Math.max(0, englishTokens.length - 2) }, (_, index) => englishTokens.slice(index, index + 3).join(" "));
|
|
1972
|
+
const chineseRuns = source.match(/[\u3400-\u9fff]{6,}/g) ?? [];
|
|
1973
|
+
const chinese = chineseRuns.flatMap((run) => Array.from({ length: Math.max(0, run.length - 5) }, (_, index) => run.slice(index, index + 6)));
|
|
1974
|
+
return new Set([...english, ...chinese]);
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
function lifecycleShortChineseCore(line, stripNegated = false) {
|
|
1978
|
+
const rawSource = stripNegated ? stripResolvedNegatedActionClauses(line) : line;
|
|
1979
|
+
const source = rawSource.split(/(?:\s+[—–-]\s*)?(?:reason|condition)\s*[::]|(?:原因|條件)\s*[::]/i)[0];
|
|
1980
|
+
const ignored = /(後續追蹤|只監察|尚未完成|已經完成|重新開啟|完成|已驗證|繼續|下一步|待辦|尚未|未完成|通過|風險|受阻|重開|監察|追蹤|修復|修補|修正)/g;
|
|
1981
|
+
const core = (source.match(/[\u3400-\u9fff]+/g) ?? []).join("").replace(ignored, "");
|
|
1982
|
+
return core.length >= 2 && core.length <= 5 ? core : null;
|
|
1983
|
+
}
|
|
1984
|
+
|
|
1985
|
+
function lifecycleTopicsOverlap(left, right) {
|
|
1986
|
+
const leftWindows = lifecycleTopicWindows(left, true);
|
|
1987
|
+
if ([...lifecycleTopicWindows(right)].some((window) => leftWindows.has(window))) return true;
|
|
1988
|
+
const leftEnglish = lifecycleEnglishTokens(left, true);
|
|
1989
|
+
const rightEnglish = lifecycleEnglishTokens(right);
|
|
1990
|
+
if (leftEnglish.length === 2 && rightEnglish.length === 2 && leftEnglish.join(" ") === rightEnglish.join(" ")) return true;
|
|
1991
|
+
const leftChinese = lifecycleShortChineseCore(left, true);
|
|
1992
|
+
return Boolean(leftChinese && leftChinese === lifecycleShortChineseCore(right));
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
function isExplicitLifecycleReclassification(line) {
|
|
1996
|
+
const normalized = line
|
|
1997
|
+
.replace(/^recommended next step\s*:\s*/i, "")
|
|
1998
|
+
.replace(/^[\s—–:-]+/, "")
|
|
1999
|
+
.trim();
|
|
2000
|
+
if (!/^(?:(?:monitor-only|follow-up scope|blocked|reopened)\b|只監察|後續追蹤|受阻|重開)/i.test(normalized)) return false;
|
|
2001
|
+
if (/\b(no condition|without condition|unconditional)\b|無條件|沒有條件/i.test(normalized)) return false;
|
|
2002
|
+
|
|
2003
|
+
const labelled = normalized.match(/(?:\bcondition|\btrigger|\bmissing evidence|條件|觸發條件|缺少證據|證據|原因|\breason)\s*[::-]\s*([^;;\n]+)/i);
|
|
2004
|
+
if (labelled) return isSubstantiveLifecycleCondition(labelled[1]);
|
|
2005
|
+
const temporal = normalized.match(/(?:\bwhen|\buntil|待)(?:\s+|:|:)([^;;\n]+)/i);
|
|
2006
|
+
return temporal ? isSubstantiveLifecycleCondition(temporal[1]) : false;
|
|
2007
|
+
}
|
|
2008
|
+
|
|
2009
|
+
function isSubstantiveLifecycleCondition(value) {
|
|
2010
|
+
const normalized = (value ?? "").trim().replace(/[.。]+$/, "");
|
|
2011
|
+
if (normalized.length < 4) return false;
|
|
2012
|
+
if (/^(TBD|todo|pending|unknown|unverified|none|n\/a|待定|待確認|未知|無)$/i.test(normalized)) return false;
|
|
2013
|
+
if (/\b(no condition|without condition|unconditional)\b|無條件|沒有條件/i.test(normalized)) return false;
|
|
2014
|
+
return true;
|
|
2015
|
+
}
|
|
2016
|
+
|
|
2017
|
+
function findHandoffLifecycleContradictions(text) {
|
|
2018
|
+
const resolved = [
|
|
2019
|
+
...handoffStateLines(text, "completed-this-session", "Completed This Session"),
|
|
2020
|
+
...handoffStateLines(text, "validation-qc", "Validation / QC").filter((line) => /(pass|passed|verified|complete|success|通過|完成|已驗證|已核對)/i.test(line))
|
|
2021
|
+
];
|
|
2022
|
+
const carryForward = [
|
|
2023
|
+
...handoffStateLines(text, "next-priorities", "Next Priorities"),
|
|
2024
|
+
...handoffStateLines(text, "risks-blockers", "Risks / Blockers"),
|
|
2025
|
+
...handoffStateLines(text, "next-session-opening-message", "Next Session Opening Message")
|
|
2026
|
+
];
|
|
2027
|
+
const findings = [];
|
|
2028
|
+
for (const pending of carryForward) {
|
|
2029
|
+
if (isExplicitLifecycleReclassification(pending)) continue;
|
|
2030
|
+
for (const done of resolved) {
|
|
2031
|
+
if (lifecycleTopicsOverlap(done, pending)) findings.push(`${done} <> ${pending}`);
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
return findings;
|
|
2035
|
+
}
|
|
1450
2036
|
|
|
1451
2037
|
function isAffirmativeLifecycleFieldValue(value) {
|
|
1452
2038
|
const trimmed = (value || "").trim();
|
|
@@ -1579,9 +2165,9 @@ async function checkSchema(root) {
|
|
|
1579
2165
|
rows.push({ target: rule.target, label: rule.label, ok: false, missing: ["file unreadable"] });
|
|
1580
2166
|
continue;
|
|
1581
2167
|
}
|
|
1582
|
-
const missing = rule.checks
|
|
1583
|
-
.filter((check) => !check.test(text))
|
|
1584
|
-
.map((check) => check.label);
|
|
2168
|
+
const missing = rule.checks
|
|
2169
|
+
.filter((check) => !check.test(text))
|
|
2170
|
+
.map((check) => check.explain?.(text) ? `${check.label}: ${check.explain(text)}` : check.label);
|
|
1585
2171
|
rows.push({
|
|
1586
2172
|
target: rule.target,
|
|
1587
2173
|
label: rule.label,
|
|
@@ -1632,10 +2218,17 @@ function tableHeader(...cells) {
|
|
|
1632
2218
|
|
|
1633
2219
|
async function buildPlan(root, command, version = null) {
|
|
1634
2220
|
const plan = [];
|
|
1635
|
-
const context = {
|
|
1636
|
-
currentVersion: version,
|
|
1637
|
-
rootTemplateVersion: command === "upgrade" ? await readRootTemplateVersion(root) : null
|
|
1638
|
-
|
|
2221
|
+
const context = {
|
|
2222
|
+
currentVersion: version,
|
|
2223
|
+
rootTemplateVersion: command === "upgrade" ? await readRootTemplateVersion(root) : null,
|
|
2224
|
+
migrationBaselines: new Map()
|
|
2225
|
+
};
|
|
2226
|
+
if (command === "upgrade" && context.rootTemplateVersion === "0.3.38") {
|
|
2227
|
+
for (const relative of ["packs/integrations.md", "packs/onboarding.md", "packs/safety.md"]) {
|
|
2228
|
+
const baseline = await readOptionalText(path.join(packageRoot, "bin", "migration-baselines", "v0.3.38", path.basename(relative)));
|
|
2229
|
+
if (baseline != null) context.migrationBaselines.set(relative, baseline);
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
1639
2232
|
for (const [sourceRel, targetRel] of mappings) {
|
|
1640
2233
|
const sourceAbs = path.join(packageRoot, sourceRel);
|
|
1641
2234
|
const targetAbs = path.join(root, targetRel);
|
|
@@ -1674,11 +2267,10 @@ async function readRootTemplateVersion(root) {
|
|
|
1674
2267
|
}
|
|
1675
2268
|
}
|
|
1676
2269
|
|
|
1677
|
-
function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAbs, sourceText, targetText, context = {}) {
|
|
1678
|
-
const base = { sourceRel, targetRel, sourceAbs, targetAbs };
|
|
1679
|
-
if (targetText === sourceText && targetRel !== "AGENTS.md") return { ...base, action: "skip", reason: "already current" };
|
|
1680
|
-
if (
|
|
1681
|
-
if (targetRel === "AGENTS.md") {
|
|
2270
|
+
function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAbs, sourceText, targetText, context = {}) {
|
|
2271
|
+
const base = { sourceRel, targetRel, sourceAbs, targetAbs };
|
|
2272
|
+
if (targetText.replace(/\r\n/g, "\n") === sourceText.replace(/\r\n/g, "\n") && targetRel !== "AGENTS.md") return { ...base, action: "skip", reason: "already current" };
|
|
2273
|
+
if (targetRel === "AGENTS.md") {
|
|
1682
2274
|
const health = assessAgentsMdHealth(targetText);
|
|
1683
2275
|
if (health.state === "conflict") {
|
|
1684
2276
|
return {
|
|
@@ -1718,78 +2310,83 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
|
|
|
1718
2310
|
mergedText: mergeManagedBlock(targetText, sourceText)
|
|
1719
2311
|
};
|
|
1720
2312
|
}
|
|
1721
|
-
// R-029/R-030: RULE_PACKS.md is a routing table, but upgrade still preserves
|
|
1722
|
-
// user-added rows. Missing maintainer rows are merged into the existing table
|
|
1723
|
-
// instead of replacing the whole file.
|
|
1724
|
-
if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade"
|
|
1725
|
-
const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
|
|
1726
|
-
if (!mergedRulePacks) {
|
|
1727
|
-
return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
|
|
1728
|
-
}
|
|
1729
|
-
return {
|
|
1730
|
-
...base,
|
|
1731
|
-
action: "merge",
|
|
1732
|
-
reason: "merge missing v0.2.0+ routing rows while preserving existing custom rows (新手引導 signal routing)",
|
|
1733
|
-
mergedText: mergedRulePacks
|
|
1734
|
-
};
|
|
1735
|
-
}
|
|
1736
|
-
// R-030 v0.3.0+: dev/RULE_PACKS.md must also include integrations pack routing row.
|
|
1737
|
-
if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && !targetText.includes("External tool integrations")) {
|
|
2313
|
+
// R-029/R-030: RULE_PACKS.md is a routing table, but upgrade still preserves
|
|
2314
|
+
// user-added rows. Missing maintainer rows are merged into the existing table
|
|
2315
|
+
// instead of replacing the whole file.
|
|
2316
|
+
if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade") {
|
|
1738
2317
|
const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
|
|
1739
2318
|
if (!mergedRulePacks) {
|
|
1740
|
-
return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table
|
|
1741
|
-
}
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
2319
|
+
return { ...base, action: "conflict", reason: "RULE_PACKS.md must contain one valid routing table; marked official rows and local rows could not be separated safely" };
|
|
2320
|
+
}
|
|
2321
|
+
if (mergedRulePacks !== targetText) {
|
|
2322
|
+
return {
|
|
2323
|
+
...base,
|
|
2324
|
+
action: "merge",
|
|
2325
|
+
reason: "update marker-identified official routing rows while preserving every unmarked local row",
|
|
2326
|
+
mergedText: mergedRulePacks
|
|
2327
|
+
};
|
|
2328
|
+
}
|
|
2329
|
+
return { ...base, action: "skip", reason: "official marked routes current; local rows preserved" };
|
|
1748
2330
|
}
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
2331
|
+
if (targetRel === "dev/PROJECT_INDEX.md" && command === "upgrade") {
|
|
2332
|
+
const mergedProjectIndex = mergeProjectIndexGovernanceSections(targetText, sourceText);
|
|
2333
|
+
if (!mergedProjectIndex) {
|
|
2334
|
+
return {
|
|
2335
|
+
...base,
|
|
2336
|
+
action: "conflict",
|
|
2337
|
+
reason: "PROJECT_INDEX.md must contain unique real H2 governance sections in the expected order; inline or fenced lookalikes are not sections"
|
|
2338
|
+
};
|
|
1755
2339
|
}
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
2340
|
+
if (mergedProjectIndex !== targetText) {
|
|
2341
|
+
return {
|
|
2342
|
+
...base,
|
|
2343
|
+
action: "merge",
|
|
2344
|
+
reason: "insert or normalize the unique Installed Integrations and Tool Operation References H2 sections while preserving all existing project content",
|
|
2345
|
+
mergedText: mergedProjectIndex
|
|
2346
|
+
};
|
|
2347
|
+
}
|
|
2348
|
+
return { ...base, action: "skip", reason: "PROJECT_INDEX.md governance sections current and structurally unique" };
|
|
1762
2349
|
}
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
|
|
1773
|
-
}
|
|
1774
|
-
return {
|
|
1775
|
-
...base,
|
|
1776
|
-
action: "merge",
|
|
1777
|
-
reason: "merge missing governance bridge routing row while preserving existing custom rows",
|
|
1778
|
-
mergedText: mergedRulePacks
|
|
1779
|
-
};
|
|
2350
|
+
if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
|
|
2351
|
+
const migratedHandoff = migrateSessionHandoff(targetText, sourceText, context);
|
|
2352
|
+
if (!migratedHandoff) {
|
|
2353
|
+
return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md lacks unique trusted state/opening boundaries; migration stopped without replacing project state" };
|
|
2354
|
+
}
|
|
2355
|
+
if (migratedHandoff !== targetText) {
|
|
2356
|
+
return { ...base, action: "merge", reason: "update handoff lifecycle/startup contracts while preserving current project state", mergedText: migratedHandoff };
|
|
2357
|
+
}
|
|
2358
|
+
return { ...base, action: "skip", reason: "SESSION_HANDOFF.md lifecycle and startup contracts current" };
|
|
1780
2359
|
}
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
2360
|
+
if (targetRel === "dev/SESSION_LOG.md" && command === "upgrade") {
|
|
2361
|
+
const migratedLog = migrateSessionLog(targetText, sourceText);
|
|
2362
|
+
if (!migratedLog) {
|
|
2363
|
+
return { ...base, action: "conflict", reason: "SESSION_LOG.md lacks a unique trusted entry-template boundary; migration stopped without replacing trace history" };
|
|
2364
|
+
}
|
|
2365
|
+
if (migratedLog !== targetText) {
|
|
2366
|
+
return { ...base, action: "merge", reason: "update only the trusted current log preamble/template while preserving every historical trace entry", mergedText: migratedLog };
|
|
2367
|
+
}
|
|
2368
|
+
return { ...base, action: "skip", reason: "SESSION_LOG.md trace/template boundary current" };
|
|
2369
|
+
}
|
|
2370
|
+
if (command === "upgrade" && ["dev/rules/integrations.md", "dev/rules/onboarding.md", "dev/rules/safety.md"].includes(targetRel)) {
|
|
2371
|
+
const baseline = context.migrationBaselines?.get(sourceRel);
|
|
2372
|
+
if (baseline != null) {
|
|
2373
|
+
if (isKnownV038ContinuityQuickFix(sourceRel, targetText)) {
|
|
2374
|
+
return {
|
|
2375
|
+
...base,
|
|
2376
|
+
action: "merge",
|
|
2377
|
+
reason: `replace the exact known v0.3.38 continuity quick-fix ${path.basename(targetRel)} with the current official pack`,
|
|
2378
|
+
mergedText: sourceText
|
|
2379
|
+
};
|
|
2380
|
+
}
|
|
2381
|
+
const mergedPack = threeWayPreserveLocalChanges(baseline, targetText, sourceText);
|
|
2382
|
+
if (!mergedPack) {
|
|
2383
|
+
return { ...base, action: "conflict", reason: `${targetRel} has local edits that overlap changed Kit rules; upgrade stopped without replacing custom content` };
|
|
2384
|
+
}
|
|
2385
|
+
if (mergedPack !== targetText) {
|
|
2386
|
+
return { ...base, action: "merge", reason: `three-way merge v0.3.38 official rules while preserving non-overlapping local ${path.basename(targetRel)} changes`, mergedText: mergedPack };
|
|
2387
|
+
}
|
|
2388
|
+
return { ...base, action: "skip", reason: `${targetRel} current after three-way preservation check` };
|
|
2389
|
+
}
|
|
1793
2390
|
}
|
|
1794
2391
|
// Governance bridge v0.3.27+: add the triggered review workflow to the
|
|
1795
2392
|
// agent-governance pack only when the pack still has a trusted Checks section.
|
|
@@ -1809,69 +2406,9 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
|
|
|
1809
2406
|
mergedText: mergedGovernancePack
|
|
1810
2407
|
};
|
|
1811
2408
|
}
|
|
1812
|
-
// R-030 v0.3.0+: dev/PROJECT_INDEX.md gets ## Installed Integrations section auto-inserted before
|
|
1813
|
-
// ## Local QC Commands on upgrade if missing. NON-DESTRUCTIVE: existing ## External Sources content
|
|
1814
|
-
// is fully preserved (including any user-filled rows). User can later manually add the `via` column
|
|
1815
|
-
// to External Sources rows (or AI can guide that incremental migration during a later session).
|
|
1816
|
-
if (targetRel === "dev/PROJECT_INDEX.md" && command === "upgrade" && !targetText.includes("## Installed Integrations")) {
|
|
1817
|
-
// Extract just the ## Installed Integrations block from source (not touching External Sources).
|
|
1818
|
-
const sourceInstalledMatch = sourceText.match(/(## Installed Integrations[\s\S]*?)(?=## Local QC Commands)/);
|
|
1819
|
-
if (sourceInstalledMatch && targetText.includes("## Local QC Commands")) {
|
|
1820
|
-
const installedBlock = sourceInstalledMatch[1];
|
|
1821
|
-
return {
|
|
1822
|
-
...base,
|
|
1823
|
-
action: "merge",
|
|
1824
|
-
reason: "insert ## Installed Integrations section template before ## Local QC Commands (R-030 Integration governance migration; existing External Sources content preserved non-destructively)",
|
|
1825
|
-
mergedText: targetText.replace("## Local QC Commands", installedBlock + "## Local QC Commands")
|
|
1826
|
-
};
|
|
1827
|
-
}
|
|
1828
|
-
}
|
|
1829
|
-
if (targetRel === "dev/PROJECT_INDEX.md" && command === "upgrade" && !targetText.includes("## Tool Operation References")) {
|
|
1830
|
-
const sourceToolRefsMatch = sourceText.match(/(## Tool Operation References[\s\S]*?)(?=## Local QC Commands)/);
|
|
1831
|
-
if (sourceToolRefsMatch && targetText.includes("## Local QC Commands")) {
|
|
1832
|
-
const toolRefsBlock = sourceToolRefsMatch[1];
|
|
1833
|
-
const normalizedTarget = mergeProjectIndexCredentialReferences(targetText);
|
|
1834
|
-
return {
|
|
1835
|
-
...base,
|
|
1836
|
-
action: "merge",
|
|
1837
|
-
reason: "insert ## Tool Operation References section template before ## Local QC Commands and normalize integration reference wording (runtime-controlled tool operation governance)",
|
|
1838
|
-
mergedText: normalizedTarget.replace("## Local QC Commands", toolRefsBlock + "## Local QC Commands")
|
|
1839
|
-
};
|
|
1840
|
-
}
|
|
1841
|
-
}
|
|
1842
|
-
if (targetRel === "dev/PROJECT_INDEX.md" && command === "upgrade" && (
|
|
1843
|
-
targetText.includes("Credential Location")
|
|
1844
|
-
|| targetText.includes("Credential Reference(no value)")
|
|
1845
|
-
|| targetText.includes("Claude Code MCP config + env var")
|
|
1846
|
-
|| targetText.includes("Credential 應由 AI 工具自身 secure storage 管理(譬如 Claude Desktop Extensions")
|
|
1847
|
-
|| targetText.includes("機密分離原則")
|
|
1848
|
-
)) {
|
|
1849
|
-
const mergedProjectIndex = mergeProjectIndexCredentialReferences(targetText);
|
|
1850
|
-
if (mergedProjectIndex !== targetText) {
|
|
1851
|
-
return {
|
|
1852
|
-
...base,
|
|
1853
|
-
action: "merge",
|
|
1854
|
-
reason: "update PROJECT_INDEX credential reference wording without changing user integration rows",
|
|
1855
|
-
mergedText: mergedProjectIndex
|
|
1856
|
-
};
|
|
1857
|
-
}
|
|
1858
|
-
}
|
|
1859
|
-
// Language migration: older onboarding packs were AI-facing rules written
|
|
1860
|
-
// mostly in Chinese. If the file still has the trusted legacy Kit shape,
|
|
1861
|
-
// replace it with the current concise English maintainer pack. If the shape
|
|
1862
|
-
// is ambiguous or locally restructured, stop as a conflict instead of
|
|
1863
|
-
// producing a half-English, half-legacy pack.
|
|
1864
|
-
if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && isLegacyChineseOnboardingPack(targetText)) {
|
|
1865
|
-
return {
|
|
1866
|
-
...base,
|
|
1867
|
-
action: "merge",
|
|
1868
|
-
reason: "replace legacy Chinese onboarding pack with current English maintainer pack",
|
|
1869
|
-
mergedText: sourceText
|
|
1870
|
-
};
|
|
1871
|
-
}
|
|
1872
2409
|
// R-030 v0.3.0+: dev/rules/onboarding.md gets Scenario F auto-inserted before
|
|
1873
2410
|
// ## Cross-reference to guide.html on upgrade if missing and the pack is not
|
|
1874
|
-
// a legacy
|
|
2411
|
+
// a legacy pack whose structure cannot accept this bounded insertion safely.
|
|
1875
2412
|
if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario F. External-tool governance")) {
|
|
1876
2413
|
const sourceScenarioFMatch = sourceText.match(/(### Scenario F\. External-tool governance[\s\S]*?)(?=## Cross-reference to guide\.html)/);
|
|
1877
2414
|
if (sourceScenarioFMatch && hasTrustedOnboardingScenarioLibrary(targetText)) {
|
|
@@ -1892,112 +2429,33 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
|
|
|
1892
2429
|
action: "merge",
|
|
1893
2430
|
reason: "update onboarding Scenario A wording from narrow coding label to broader system/tool/platform/app label",
|
|
1894
2431
|
mergedText: mergedOnboarding
|
|
1895
|
-
};
|
|
1896
|
-
}
|
|
1897
|
-
}
|
|
1898
|
-
// v0.3.6+: SESSION_HANDOFF.md gains a non-destructive lifecycle consistency
|
|
1899
|
-
// field. Existing handoff content stays intact; only the missing field and
|
|
1900
|
-
// rule note are inserted around stable ack markers.
|
|
1901
|
-
if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:lifecycle-conflicts-resolved")) {
|
|
1902
|
-
const mergedHandoff = mergeHandoffLifecycleField(targetText);
|
|
1903
|
-
if (!mergedHandoff) {
|
|
1904
|
-
return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add lifecycle consistency field" };
|
|
1905
|
-
}
|
|
1906
|
-
return {
|
|
1907
|
-
...base,
|
|
1908
|
-
action: "merge",
|
|
1909
|
-
reason: "insert lifecycle consistency field into State Reconciliation Check (completed work must not carry forward as unresolved next work)",
|
|
1910
|
-
mergedText: mergedHandoff
|
|
1911
|
-
};
|
|
1912
|
-
}
|
|
1913
|
-
if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:persistence-routing-checked")) {
|
|
1914
|
-
const mergedHandoff = mergeHandoffPersistenceRoutingField(targetText);
|
|
1915
|
-
if (!mergedHandoff) {
|
|
1916
|
-
return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add persistence routing field" };
|
|
2432
|
+
};
|
|
1917
2433
|
}
|
|
1918
|
-
return {
|
|
1919
|
-
...base,
|
|
1920
|
-
action: "merge",
|
|
1921
|
-
reason: "insert persistence routing field into State Reconciliation Check (one-time evidence must not drive next-session state)",
|
|
1922
|
-
mergedText: mergedHandoff
|
|
1923
|
-
};
|
|
1924
2434
|
}
|
|
1925
|
-
if (targetRel === "dev/
|
|
1926
|
-
const
|
|
1927
|
-
if (!
|
|
1928
|
-
return { ...base, action: "conflict", reason: "
|
|
2435
|
+
if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Infer when sufficient; ask only when unresolved")) {
|
|
2436
|
+
const mergedOnboarding = mergeOnboardingDecisionFirstPolicy(targetText, sourceText);
|
|
2437
|
+
if (!mergedOnboarding) {
|
|
2438
|
+
return { ...base, action: "conflict", reason: "onboarding decision flow was customized or structurally changed; manual merge required rather than forcing the chooser-policy migration" };
|
|
1929
2439
|
}
|
|
1930
2440
|
return {
|
|
1931
2441
|
...base,
|
|
1932
2442
|
action: "merge",
|
|
1933
|
-
reason: "
|
|
1934
|
-
mergedText:
|
|
2443
|
+
reason: "replace the trusted mandatory chooser flow with decision-first onboarding while preserving scenario content and local sections",
|
|
2444
|
+
mergedText: mergedOnboarding
|
|
1935
2445
|
};
|
|
1936
2446
|
}
|
|
1937
|
-
if (
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
};
|
|
1950
|
-
}
|
|
1951
|
-
}
|
|
1952
|
-
if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && hasMisplacedRequiredAnchor(targetRel, targetText, "handoff log archive continuity")) {
|
|
1953
|
-
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" };
|
|
1954
|
-
}
|
|
1955
|
-
if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && hasMissingRequiredAnchor(targetRel, targetText, "handoff log archive continuity")) {
|
|
1956
|
-
const mergedHandoff = mergeHandoffArchiveContinuityRule(targetText, sourceText);
|
|
1957
|
-
if (!mergedHandoff) {
|
|
1958
|
-
return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md handoff sufficiency markers were changed; manual merge required to add archive continuity rule" };
|
|
1959
|
-
}
|
|
1960
|
-
return {
|
|
1961
|
-
...base,
|
|
1962
|
-
action: "merge",
|
|
1963
|
-
reason: "insert handoff archive continuity rule so upgrade self-check can pass without requiring manual anchor repair",
|
|
1964
|
-
mergedText: mergedHandoff
|
|
1965
|
-
};
|
|
1966
|
-
}
|
|
1967
|
-
if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
|
|
1968
|
-
const repairedOpening = repairHandoffOpeningRootGuard(targetText);
|
|
1969
|
-
if (repairedOpening.changed) {
|
|
1970
|
-
return {
|
|
1971
|
-
...base,
|
|
1972
|
-
action: "merge",
|
|
1973
|
-
reason: "restore root mismatch guard in Next Session Opening Message",
|
|
1974
|
-
mergedText: repairedOpening.text
|
|
1975
|
-
};
|
|
1976
|
-
}
|
|
1977
|
-
}
|
|
1978
|
-
if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
|
|
1979
|
-
const repairedTemperature = repairHandoffCurrentStateEvidenceBoundary(targetText);
|
|
1980
|
-
if (repairedTemperature.changed) {
|
|
1981
|
-
return {
|
|
1982
|
-
...base,
|
|
1983
|
-
action: "merge",
|
|
1984
|
-
reason: "move historical evidence out of hot handoff state",
|
|
1985
|
-
mergedText: repairedTemperature.text
|
|
1986
|
-
};
|
|
1987
|
-
}
|
|
1988
|
-
}
|
|
1989
|
-
if (targetRel === "dev/SESSION_LOG.md" && command === "upgrade" && !targetText.includes("- **Evidence disposition:**")) {
|
|
1990
|
-
const mergedLog = mergeSessionLogEvidenceDispositionField(targetText);
|
|
1991
|
-
if (!mergedLog) {
|
|
1992
|
-
return { ...base, action: "conflict", reason: "SESSION_LOG.md entry template markers were changed; manual merge required to add evidence disposition field" };
|
|
1993
|
-
}
|
|
1994
|
-
return {
|
|
1995
|
-
...base,
|
|
1996
|
-
action: "merge",
|
|
1997
|
-
reason: "insert SESSION_LOG evidence disposition field into Entry Template",
|
|
1998
|
-
mergedText: mergedLog
|
|
1999
|
-
};
|
|
2000
|
-
}
|
|
2447
|
+
if (command !== "upgrade") return { ...base, action: "skip", reason: "init preserves existing files" };
|
|
2448
|
+
if (targetRel === "START_NEXT_SESSION_PROMPT.txt" && command === "upgrade") {
|
|
2449
|
+
const mergedStartupGuidance = mergeLegacyFirstStartupGuidance(targetText, sourceText);
|
|
2450
|
+
if (mergedStartupGuidance && mergedStartupGuidance !== targetText) {
|
|
2451
|
+
return {
|
|
2452
|
+
...base,
|
|
2453
|
+
action: "merge",
|
|
2454
|
+
reason: "replace the exact legacy first-start chooser sentence without changing surrounding project state",
|
|
2455
|
+
mergedText: mergedStartupGuidance
|
|
2456
|
+
};
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2001
2459
|
if (command === "upgrade" && hasAnchorRepairMarkerDrift(targetText)) {
|
|
2002
2460
|
return { ...base, action: "conflict", reason: "legacy anchor repair block markers are incomplete or obsolete; manual semantic cleanup required before upgrade can safely continue" };
|
|
2003
2461
|
}
|
|
@@ -2010,20 +2468,21 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
|
|
|
2010
2468
|
return { ...base, ...semanticRepair };
|
|
2011
2469
|
}
|
|
2012
2470
|
return { ...base, action: "conflict", reason: "required Kit anchors are missing but no safe semantic repair path exists; upgrade stopped without appending naked anchor text" };
|
|
2013
|
-
}
|
|
2014
|
-
if (targetRel === "CLAUDE.md" || targetRel === "GEMINI.md") {
|
|
2015
|
-
if (
|
|
2016
|
-
return {
|
|
2017
|
-
}
|
|
2018
|
-
if (looksLikeExpandedKitBridge(targetRel, targetText)) {
|
|
2019
|
-
return {
|
|
2471
|
+
}
|
|
2472
|
+
if (targetRel === "CLAUDE.md" || targetRel === "GEMINI.md") {
|
|
2473
|
+
if (looksLikeExpandedKitBridge(targetRel, targetText)) {
|
|
2474
|
+
return {
|
|
2020
2475
|
...base,
|
|
2021
2476
|
action: "merge",
|
|
2022
2477
|
reason: `${targetRel} appears to be an expanded Kit bridge; restore short bridge so AGENTS.md remains the single source of truth`,
|
|
2023
|
-
mergedText: sourceText
|
|
2024
|
-
};
|
|
2025
|
-
}
|
|
2026
|
-
|
|
2478
|
+
mergedText: sourceText
|
|
2479
|
+
};
|
|
2480
|
+
}
|
|
2481
|
+
const bridgeFailure = bridgeTextFailure(targetRel, targetText);
|
|
2482
|
+
if (bridgeFailure) {
|
|
2483
|
+
return { ...base, action: "conflict", reason: `existing bridge is not an active one-hop route (${bridgeFailure})` };
|
|
2484
|
+
}
|
|
2485
|
+
}
|
|
2027
2486
|
return { ...base, action: "skip", reason: "preserve existing file" };
|
|
2028
2487
|
}
|
|
2029
2488
|
|
|
@@ -2066,7 +2525,90 @@ function mergeOnboardingScenarioALabel(targetText) {
|
|
|
2066
2525
|
);
|
|
2067
2526
|
return merged;
|
|
2068
2527
|
}
|
|
2069
|
-
|
|
2528
|
+
|
|
2529
|
+
function mergeOnboardingDecisionFirstPolicy(targetText, sourceText) {
|
|
2530
|
+
const legacySignalLine = "- equivalent Chinese user phrases such as \"新手\", \"教我用\", \"我剛安裝\", \"點開始\", \"開工\", \"能力\", or \"能做甚麼\"";
|
|
2531
|
+
const currentSignalBoundary = "- equivalent Chinese user phrases such as \"新手\", \"教我用\", \"我剛安裝\", \"點開始\", \"能力\", or \"能做甚麼\"\n\n### Continuity startup boundary\n\n`Start Agent Handoff` / \"開工\" starts continuity and reads the current handoff state; it is not an onboarding signal. If the same message or loaded state contains a concrete objective, infer the working scenario and begin the first safe action. Only when no executable objective remains after state reading should the AI ask one concise question or offer the guided onboarding path. Explicit requests such as \"新手,教我用\" enter onboarding directly.";
|
|
2532
|
+
let working = targetText;
|
|
2533
|
+
let startupBoundaryChanged = false;
|
|
2534
|
+
if (working.includes(legacySignalLine) && !working.includes("### Continuity startup boundary")) {
|
|
2535
|
+
working = working.replace(legacySignalLine, currentSignalBoundary);
|
|
2536
|
+
startupBoundaryChanged = true;
|
|
2537
|
+
}
|
|
2538
|
+
|
|
2539
|
+
const legacyStart = "### 2. Offer scenario choice before task execution";
|
|
2540
|
+
const legacyEnd = "### 5. Keep the first task small";
|
|
2541
|
+
const sourceStart = "### 2. Infer first; offer scenario choice only when needed";
|
|
2542
|
+
const sourceEnd = "### 5. Keep the first task small";
|
|
2543
|
+
const targetStartIndex = working.indexOf(legacyStart);
|
|
2544
|
+
const targetEndIndex = working.indexOf(legacyEnd);
|
|
2545
|
+
const sourceStartIndex = sourceText.indexOf(sourceStart);
|
|
2546
|
+
const sourceEndIndex = sourceText.indexOf(sourceEnd);
|
|
2547
|
+
if (targetStartIndex < 0 || targetEndIndex <= targetStartIndex) {
|
|
2548
|
+
return startupBoundaryChanged && working.includes("Infer when sufficient; ask only when unresolved") ? working : null;
|
|
2549
|
+
}
|
|
2550
|
+
if (sourceStartIndex < 0 || sourceEndIndex <= sourceStartIndex) return null;
|
|
2551
|
+
|
|
2552
|
+
const legacyDecisionBlock = working.slice(targetStartIndex, targetEndIndex);
|
|
2553
|
+
const trustedLegacyPhrases = [
|
|
2554
|
+
"When onboarding applies, the first visible response must combine the startup card and scenario chooser",
|
|
2555
|
+
"After the user picks a scenario, guide one small first task through five steps",
|
|
2556
|
+
"Do not run all five steps in one message"
|
|
2557
|
+
];
|
|
2558
|
+
if (!trustedLegacyPhrases.every((phrase) => legacyDecisionBlock.includes(phrase))) return null;
|
|
2559
|
+
|
|
2560
|
+
const replacements = [
|
|
2561
|
+
[
|
|
2562
|
+
"Use this transient pack for first-time Agent Handoff Kit users, vague first messages, or fresh-install sessions where the user has not yet chosen a working scenario.",
|
|
2563
|
+
"Use this transient pack for first-time Agent Handoff Kit users who request guidance, or when the user's first-task intent remains genuinely unresolved after reading the available project state."
|
|
2564
|
+
],
|
|
2565
|
+
[
|
|
2566
|
+
"- The first user message is short and vague.",
|
|
2567
|
+
"- The first user message is short and still genuinely vague after available project state is read."
|
|
2568
|
+
],
|
|
2569
|
+
[
|
|
2570
|
+
"- `SESSION_HANDOFF` Active Objective is empty and Session count is 1.",
|
|
2571
|
+
"- `SESSION_HANDOFF` Active Objective is empty and Session count is 1, and the user has not already supplied a concrete objective with enough material facts."
|
|
2572
|
+
],
|
|
2573
|
+
[
|
|
2574
|
+
"Each scenario keeps the same five-step rhythm. The model may adapt wording, but must preserve the intent, tone, and safety boundaries.",
|
|
2575
|
+
"Each scenario is a fallback guidance template, not a mandatory questionnaire. The model may skip answered steps, infer the route when evidence is sufficient, and adapt wording while preserving intent, tone, and safety boundaries."
|
|
2576
|
+
],
|
|
2577
|
+
[
|
|
2578
|
+
"Step E.1: ask for four facts: objective, existing material or tools, technical comfort level, and the first small result the user wants.",
|
|
2579
|
+
"Step E.1: use any facts already provided, then ask only for missing information that materially affects the first safe action. Do not ask about technical comfort unless it changes the delivery approach."
|
|
2580
|
+
],
|
|
2581
|
+
[
|
|
2582
|
+
"| Treating a vague first message as a specific task | The user may be trying to learn the workflow or choose a scenario. | Offer the A-F scenario chooser first. |",
|
|
2583
|
+
"| Treating a genuinely vague first message as a specific task | The user may be trying to learn the workflow or choose a scenario. | Offer the A-F scenario chooser only when the intent remains unresolved. |"
|
|
2584
|
+
],
|
|
2585
|
+
[
|
|
2586
|
+
"| Running all five steps without waiting | The user loses control of the walk-through. | Pause for confirmation at each step. |",
|
|
2587
|
+
"| Forcing the chooser or all five guided steps after the objective is already concrete | The user must repeat known information and the AI shifts technical work back to the user. | Infer the scenario, state the assumption, and begin the first safe action; ask only for missing facts or required risk approval. |"
|
|
2588
|
+
]
|
|
2589
|
+
];
|
|
2590
|
+
if (!replacements.every(([before]) => working.includes(before))) return null;
|
|
2591
|
+
|
|
2592
|
+
let merged = `${working.slice(0, targetStartIndex)}${sourceText.slice(sourceStartIndex, sourceEndIndex)}${working.slice(targetEndIndex)}`;
|
|
2593
|
+
for (const [before, after] of replacements) merged = merged.replace(before, after);
|
|
2594
|
+
return merged.includes("Infer when sufficient; ask only when unresolved")
|
|
2595
|
+
&& !merged.includes("Offer scenario choice before task execution")
|
|
2596
|
+
&& !merged.includes("Each scenario keeps the same five-step rhythm")
|
|
2597
|
+
? merged
|
|
2598
|
+
: null;
|
|
2599
|
+
}
|
|
2600
|
+
|
|
2601
|
+
function mergeLegacyFirstStartupGuidance(targetText, sourceText) {
|
|
2602
|
+
const legacySentence = "This is the first startup after installing Agent Handoff Kit. Load the onboarding guidance from dev/RULE_PACKS.md when appropriate. Help me choose the right working scenario, then guide me through the first task step by step.";
|
|
2603
|
+
if (!targetText.includes(legacySentence)) return targetText;
|
|
2604
|
+
const sourceSentence = sourceText.split(/\r?\n/).find((line) => (
|
|
2605
|
+
line.startsWith("This is the first startup after installing Agent Handoff Kit.")
|
|
2606
|
+
&& line.includes("If my objective and the available project facts are already concrete")
|
|
2607
|
+
&& line.includes("Offer the chooser only if my intent is genuinely unresolved")
|
|
2608
|
+
));
|
|
2609
|
+
return sourceSentence ? targetText.replace(legacySentence, sourceSentence) : null;
|
|
2610
|
+
}
|
|
2611
|
+
|
|
2070
2612
|
function mergeAgentGovernanceBridgeWorkflow(targetText, sourceText) {
|
|
2071
2613
|
const sourceRuleLine = sourceText.split(/\r?\n/).find((line) => line.startsWith("9. Governance bridge"));
|
|
2072
2614
|
const workflowMatch = sourceText.match(/\n## Governance Bridge Workflow[\s\S]*?(?=\n## Generated Artifact Governance Workflow|\n## Checks)/);
|
|
@@ -2174,18 +2716,18 @@ function isRequiredAnchorSemanticallyPlaced(rule, snippet, text) {
|
|
|
2174
2716
|
return rule.placement ? rule.placement(snippet, text) : true;
|
|
2175
2717
|
}
|
|
2176
2718
|
|
|
2177
|
-
function sessionLogAnchorPlacement(snippet, text) {
|
|
2178
|
-
if (snippet === "ack:section:session-log-preamble") return text
|
|
2179
|
-
if (snippet === "ack:section:session-log-entry-template") return text
|
|
2180
|
-
if (snippet === "
|
|
2181
|
-
|
|
2182
|
-
return sessionLogEntryTemplateContains(text, snippet);
|
|
2719
|
+
function sessionLogAnchorPlacement(snippet, text) {
|
|
2720
|
+
if (snippet === "ack:section:session-log-preamble") return countText(text, "ack:section:session-log-preamble") === 1;
|
|
2721
|
+
if (snippet === "ack:section:session-log-entry-template" || snippet === "## Entry Template") return Boolean(sessionLogEntryTemplateContract(text));
|
|
2722
|
+
if (snippet === "ack:log-entry:start" || snippet === "ack:log-entry:end") {
|
|
2723
|
+
return sessionLogEntryTemplateContains(text, snippet);
|
|
2183
2724
|
}
|
|
2184
2725
|
const preamble = [
|
|
2185
2726
|
"Record what actually happened in the session",
|
|
2186
|
-
"kept, summarized, or archived",
|
|
2187
|
-
"Do not remove validation evidence",
|
|
2188
|
-
"
|
|
2727
|
+
"kept, summarized, or archived",
|
|
2728
|
+
"Do not remove validation evidence",
|
|
2729
|
+
"full opening message never belongs in this log",
|
|
2730
|
+
"latest opening message",
|
|
2189
2731
|
"not current state"
|
|
2190
2732
|
];
|
|
2191
2733
|
if (preamble.includes(snippet)) return sessionLogPreambleContains(text, snippet);
|
|
@@ -2198,11 +2740,10 @@ function sessionLogPreambleContains(text, snippet) {
|
|
|
2198
2740
|
return snippetAppearsBeforeHeading(text, snippet, "## Entry Template");
|
|
2199
2741
|
}
|
|
2200
2742
|
|
|
2201
|
-
function sessionLogEntryTemplateContains(text, snippet) {
|
|
2202
|
-
const
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
}
|
|
2743
|
+
function sessionLogEntryTemplateContains(text, snippet) {
|
|
2744
|
+
const contract = sessionLogEntryTemplateContract(text);
|
|
2745
|
+
return Boolean(contract && contract.templateText.includes(snippet));
|
|
2746
|
+
}
|
|
2206
2747
|
|
|
2207
2748
|
function handoffContinuityAnchorPlacement(snippet, text) {
|
|
2208
2749
|
const suffixContinuityAnchors = [
|
|
@@ -2238,8 +2779,14 @@ function projectDecisionsAnchorPlacement(snippet, text) {
|
|
|
2238
2779
|
return true;
|
|
2239
2780
|
}
|
|
2240
2781
|
|
|
2241
|
-
function onboardingAnchorPlacement(snippet, text) {
|
|
2242
|
-
if (snippet === "
|
|
2782
|
+
function onboardingAnchorPlacement(snippet, text) {
|
|
2783
|
+
if (snippet === "Continuity startup boundary" || snippet === "starts continuity and reads the current handoff state; it is not an onboarding signal") {
|
|
2784
|
+
return snippetAppearsBetweenHeadings(text, snippet, "## Load When", "## Discipline");
|
|
2785
|
+
}
|
|
2786
|
+
if (snippet === "Infer when sufficient; ask only when unresolved") {
|
|
2787
|
+
return snippetAppearsBetweenHeadings(text, snippet, "## Discipline", "## Application Scenario Library");
|
|
2788
|
+
}
|
|
2789
|
+
if (snippet === "Application Scenario Library") {
|
|
2243
2790
|
return Boolean(textSectionBounds(text, "## Application Scenario Library", "## Cross-reference to guide.html"));
|
|
2244
2791
|
}
|
|
2245
2792
|
if (/^Scenario [A-F]\./.test(snippet)) {
|
|
@@ -2249,7 +2796,7 @@ function onboardingAnchorPlacement(snippet, text) {
|
|
|
2249
2796
|
}
|
|
2250
2797
|
|
|
2251
2798
|
function integrationsAnchorPlacement(snippet, text) {
|
|
2252
|
-
if (snippet === "Credential Separation Principle" || snippet === "External Tool Usage Verification Gate" || snippet === "External Tool Resource Lifecycle" || snippet === "do not invent" || snippet === "input schema" || snippet === "official documentation" || snippet === "Source-of-truth Architecture" || snippet === "Cross-session Lifecycle" || snippet === "Runtime-Controlled Tool Operation Variants" || snippet === "Tool Operation References" || snippet === "Do not guess Chrome, Playwright, or DevTools commands") {
|
|
2799
|
+
if (snippet === "Credential Separation Principle" || snippet === "External Tool Usage Verification Gate" || snippet === "External Tool Resource Lifecycle" || snippet === "do not invent" || snippet === "input schema" || snippet === "official documentation" || snippet === "Source-of-truth Architecture" || snippet === "Cross-session Lifecycle" || snippet === "Runtime-Controlled Tool Operation Variants" || snippet === "Tool Operation References" || snippet === "Do not guess Chrome, Playwright, or DevTools commands" || snippet === "Local HTML / app validation fallback" || snippet === "`file://` rejection alone is not enough evidence to stop") {
|
|
2253
2800
|
return snippetAppearsBetweenHeadings(text, snippet, "## Discipline", "## Rules");
|
|
2254
2801
|
}
|
|
2255
2802
|
if (snippet === "Connector-first default") {
|
|
@@ -2330,6 +2877,14 @@ const semanticAnchorRepairStrategies = {
|
|
|
2330
2877
|
mergedText: mergedCommunication
|
|
2331
2878
|
} : null;
|
|
2332
2879
|
},
|
|
2880
|
+
"dev/rules/onboarding.md": (targetText, sourceText) => {
|
|
2881
|
+
const mergedOnboarding = mergeOnboardingDecisionFirstPolicy(targetText, sourceText);
|
|
2882
|
+
return mergedOnboarding ? {
|
|
2883
|
+
action: "merge",
|
|
2884
|
+
reason: "restore decision-first onboarding in its trusted semantic sections",
|
|
2885
|
+
mergedText: mergedOnboarding
|
|
2886
|
+
} : null;
|
|
2887
|
+
},
|
|
2333
2888
|
"dev/rules/integrations.md": (targetText, sourceText, missing) => {
|
|
2334
2889
|
const mergedIntegrations = mergeIntegrationsSectionsByMissingAnchors(targetText, sourceText, missing);
|
|
2335
2890
|
return mergedIntegrations ? {
|
|
@@ -2427,6 +2982,222 @@ function mergeCommunicationNextStepDiscipline(targetText, sourceText, missing) {
|
|
|
2427
2982
|
return merged === targetText ? null : merged;
|
|
2428
2983
|
}
|
|
2429
2984
|
|
|
2985
|
+
function parseMarkdownH2Sections(text) {
|
|
2986
|
+
const sections = [];
|
|
2987
|
+
const linePattern = /.*(?:\r?\n|$)/g;
|
|
2988
|
+
let fenced = false;
|
|
2989
|
+
let fenceDelimiter = null;
|
|
2990
|
+
let inComment = false;
|
|
2991
|
+
let match;
|
|
2992
|
+
while ((match = linePattern.exec(text)) && match[0] !== "") {
|
|
2993
|
+
const raw = match[0];
|
|
2994
|
+
const line = raw.replace(/\r?\n$/, "");
|
|
2995
|
+
const trimmed = line.trim();
|
|
2996
|
+
if (inComment) {
|
|
2997
|
+
if (trimmed.includes("-->")) inComment = false;
|
|
2998
|
+
continue;
|
|
2999
|
+
}
|
|
3000
|
+
if (trimmed.startsWith("<!--")) {
|
|
3001
|
+
if (!trimmed.includes("-->")) inComment = true;
|
|
3002
|
+
continue;
|
|
3003
|
+
}
|
|
3004
|
+
const fence = trimmed.match(/^(`{3,}|~{3,})/);
|
|
3005
|
+
if (fence) {
|
|
3006
|
+
if (!fenced) {
|
|
3007
|
+
fenced = true;
|
|
3008
|
+
fenceDelimiter = fence[1][0];
|
|
3009
|
+
} else if (fence[1][0] === fenceDelimiter) {
|
|
3010
|
+
fenced = false;
|
|
3011
|
+
fenceDelimiter = null;
|
|
3012
|
+
}
|
|
3013
|
+
continue;
|
|
3014
|
+
}
|
|
3015
|
+
if (fenced) continue;
|
|
3016
|
+
const headingMatch = line.match(/^## ([^#].*?)\s*$/);
|
|
3017
|
+
if (headingMatch) sections.push({ title: headingMatch[1], start: match.index, end: text.length });
|
|
3018
|
+
}
|
|
3019
|
+
for (let index = 0; index < sections.length - 1; index += 1) {
|
|
3020
|
+
sections[index].end = sections[index + 1].start;
|
|
3021
|
+
}
|
|
3022
|
+
return sections;
|
|
3023
|
+
}
|
|
3024
|
+
|
|
3025
|
+
function uniqueSessionLogEntryTemplateSection(text) {
|
|
3026
|
+
const matches = parseMarkdownH2Sections(text).filter((section) => section.title === "Entry Template");
|
|
3027
|
+
return matches.length === 1 ? matches[0] : null;
|
|
3028
|
+
}
|
|
3029
|
+
|
|
3030
|
+
function sessionLogTemplateFence(text, section) {
|
|
3031
|
+
if (!section) return null;
|
|
3032
|
+
const sectionText = text.slice(section.start, section.end);
|
|
3033
|
+
const matches = [...sectionText.matchAll(/^````markdown\s*\r?\n([\s\S]*?)\r?\n````\s*$/gm)];
|
|
3034
|
+
if (matches.length !== 1) return null;
|
|
3035
|
+
const match = matches[0];
|
|
3036
|
+
const templateOffset = match.index + match[0].indexOf(match[1]);
|
|
3037
|
+
return {
|
|
3038
|
+
start: section.start + match.index,
|
|
3039
|
+
end: section.start + match.index + match[0].length,
|
|
3040
|
+
templateStart: section.start + templateOffset,
|
|
3041
|
+
templateEnd: section.start + templateOffset + match[1].length,
|
|
3042
|
+
templateText: match[1]
|
|
3043
|
+
};
|
|
3044
|
+
}
|
|
3045
|
+
|
|
3046
|
+
function sessionLogEntryTemplateContract(text) {
|
|
3047
|
+
const section = uniqueSessionLogEntryTemplateSection(text);
|
|
3048
|
+
if (!section) return null;
|
|
3049
|
+
const sectionMarker = "<!-- ack:section:session-log-entry-template -->";
|
|
3050
|
+
if (countText(text, sectionMarker) !== 1) return null;
|
|
3051
|
+
const markerIndex = text.indexOf(sectionMarker);
|
|
3052
|
+
if (markerIndex >= section.start || text.slice(markerIndex + sectionMarker.length, section.start).trim() !== "") return null;
|
|
3053
|
+
|
|
3054
|
+
const fence = sessionLogTemplateFence(text, section);
|
|
3055
|
+
if (!fence) return null;
|
|
3056
|
+
const sectionText = text.slice(section.start, section.end);
|
|
3057
|
+
const startMarker = "<!-- ack:log-entry:start -->";
|
|
3058
|
+
const endMarker = "<!-- ack:log-entry:end -->";
|
|
3059
|
+
if (countText(sectionText, startMarker) !== 1 || countText(sectionText, endMarker) !== 1) return null;
|
|
3060
|
+
if (countText(fence.templateText, startMarker) !== 1 || countText(fence.templateText, endMarker) !== 1) return null;
|
|
3061
|
+
const relativeStart = fence.templateText.indexOf(startMarker);
|
|
3062
|
+
const relativeEnd = fence.templateText.indexOf(endMarker);
|
|
3063
|
+
if (relativeStart >= relativeEnd) return null;
|
|
3064
|
+
return {
|
|
3065
|
+
...section,
|
|
3066
|
+
...fence,
|
|
3067
|
+
entryStart: fence.templateStart + relativeStart,
|
|
3068
|
+
entryEnd: fence.templateStart + relativeEnd + endMarker.length
|
|
3069
|
+
};
|
|
3070
|
+
}
|
|
3071
|
+
|
|
3072
|
+
function lcsLinePairs(left, right) {
|
|
3073
|
+
const rows = left.length + 1;
|
|
3074
|
+
const cols = right.length + 1;
|
|
3075
|
+
const table = Array.from({ length: rows }, () => new Uint16Array(cols));
|
|
3076
|
+
for (let i = left.length - 1; i >= 0; i -= 1) {
|
|
3077
|
+
for (let j = right.length - 1; j >= 0; j -= 1) {
|
|
3078
|
+
table[i][j] = left[i] === right[j]
|
|
3079
|
+
? table[i + 1][j + 1] + 1
|
|
3080
|
+
: Math.max(table[i + 1][j], table[i][j + 1]);
|
|
3081
|
+
}
|
|
3082
|
+
}
|
|
3083
|
+
const pairs = [];
|
|
3084
|
+
let i = 0;
|
|
3085
|
+
let j = 0;
|
|
3086
|
+
while (i < left.length && j < right.length) {
|
|
3087
|
+
if (left[i] === right[j]) {
|
|
3088
|
+
pairs.push([i, j]);
|
|
3089
|
+
i += 1;
|
|
3090
|
+
j += 1;
|
|
3091
|
+
} else if (table[i + 1][j] >= table[i][j + 1]) i += 1;
|
|
3092
|
+
else j += 1;
|
|
3093
|
+
}
|
|
3094
|
+
return pairs;
|
|
3095
|
+
}
|
|
3096
|
+
|
|
3097
|
+
function lineDiffHunks(base, changed) {
|
|
3098
|
+
const pairs = [...lcsLinePairs(base, changed), [base.length, changed.length]];
|
|
3099
|
+
const hunks = [];
|
|
3100
|
+
let baseCursor = 0;
|
|
3101
|
+
let changedCursor = 0;
|
|
3102
|
+
for (const [baseMatch, changedMatch] of pairs) {
|
|
3103
|
+
if (baseMatch > baseCursor || changedMatch > changedCursor) {
|
|
3104
|
+
hunks.push({ baseStart: baseCursor, baseEnd: baseMatch, added: changed.slice(changedCursor, changedMatch) });
|
|
3105
|
+
}
|
|
3106
|
+
baseCursor = baseMatch + 1;
|
|
3107
|
+
changedCursor = changedMatch + 1;
|
|
3108
|
+
}
|
|
3109
|
+
return hunks;
|
|
3110
|
+
}
|
|
3111
|
+
|
|
3112
|
+
function hunksOverlap(left, right) {
|
|
3113
|
+
const leftInsertion = left.baseStart === left.baseEnd;
|
|
3114
|
+
const rightInsertion = right.baseStart === right.baseEnd;
|
|
3115
|
+
if (leftInsertion && rightInsertion) return false;
|
|
3116
|
+
if (leftInsertion) return left.baseStart > right.baseStart && left.baseStart < right.baseEnd;
|
|
3117
|
+
if (rightInsertion) return right.baseStart > left.baseStart && right.baseStart < left.baseEnd;
|
|
3118
|
+
return left.baseStart < right.baseEnd && right.baseStart < left.baseEnd;
|
|
3119
|
+
}
|
|
3120
|
+
|
|
3121
|
+
function mapBaseBoundaryToChanged(base, changed, boundary) {
|
|
3122
|
+
if (boundary === 0) return 0;
|
|
3123
|
+
if (boundary === base.length) return changed.length;
|
|
3124
|
+
const pairs = lcsLinePairs(base, changed);
|
|
3125
|
+
const next = pairs.find(([baseIndex]) => baseIndex >= boundary);
|
|
3126
|
+
if (next) return next[1];
|
|
3127
|
+
const previous = [...pairs].reverse().find(([baseIndex]) => baseIndex < boundary);
|
|
3128
|
+
return previous ? previous[1] + 1 : null;
|
|
3129
|
+
}
|
|
3130
|
+
|
|
3131
|
+
function threeWayPreserveLocalChanges(baseText, localText, currentText) {
|
|
3132
|
+
if (localText.replace(/\r\n/g, "\n") === currentText.replace(/\r\n/g, "\n")) return localText;
|
|
3133
|
+
const baseHadFinalNewline = /\r?\n$/.test(baseText);
|
|
3134
|
+
const localHadFinalNewline = /\r?\n$/.test(localText);
|
|
3135
|
+
const base = baseText.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
|
|
3136
|
+
const local = localText.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
|
|
3137
|
+
const current = currentText.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
|
|
3138
|
+
const localHunks = lineDiffHunks(base, local);
|
|
3139
|
+
const upstreamHunks = lineDiffHunks(base, current);
|
|
3140
|
+
if (localHunks.some((localHunk) => upstreamHunks.some((upstreamHunk) => hunksOverlap(localHunk, upstreamHunk)))) return null;
|
|
3141
|
+
|
|
3142
|
+
const merged = [...current];
|
|
3143
|
+
const mapped = [];
|
|
3144
|
+
for (const hunk of localHunks) {
|
|
3145
|
+
const start = mapBaseBoundaryToChanged(base, current, hunk.baseStart);
|
|
3146
|
+
const end = mapBaseBoundaryToChanged(base, current, hunk.baseEnd);
|
|
3147
|
+
if (start == null || end == null || end < start) return null;
|
|
3148
|
+
mapped.push({ start, end, added: hunk.added });
|
|
3149
|
+
}
|
|
3150
|
+
for (const hunk of mapped.sort((a, b) => b.start - a.start)) merged.splice(hunk.start, hunk.end - hunk.start, ...hunk.added);
|
|
3151
|
+
const newline = localText.includes("\r\n") ? "\r\n" : "\n";
|
|
3152
|
+
return `${merged.join(newline)}${localHadFinalNewline || baseHadFinalNewline ? newline : ""}`;
|
|
3153
|
+
}
|
|
3154
|
+
|
|
3155
|
+
function isKnownV038ContinuityQuickFix(sourceRel, text) {
|
|
3156
|
+
const expected = knownV038ContinuityQuickFixHashes.get(sourceRel);
|
|
3157
|
+
if (!expected) return false;
|
|
3158
|
+
return sha256(Buffer.from(text.replace(/\r\n/g, "\n"), "utf8")) === expected;
|
|
3159
|
+
}
|
|
3160
|
+
|
|
3161
|
+
function uniqueH2Section(text, title) {
|
|
3162
|
+
const matches = parseMarkdownH2Sections(text).filter((section) => section.title === title);
|
|
3163
|
+
return matches.length === 1 ? matches[0] : null;
|
|
3164
|
+
}
|
|
3165
|
+
|
|
3166
|
+
function projectIndexGovernanceSectionsAreValid(text) {
|
|
3167
|
+
const installed = uniqueH2Section(text, "Installed Integrations");
|
|
3168
|
+
const toolRefs = uniqueH2Section(text, "Tool Operation References");
|
|
3169
|
+
const localQc = uniqueH2Section(text, "Local QC Commands");
|
|
3170
|
+
return Boolean(installed && toolRefs && localQc && installed.start < toolRefs.start && toolRefs.start < localQc.start);
|
|
3171
|
+
}
|
|
3172
|
+
|
|
3173
|
+
function mergeProjectIndexGovernanceSections(targetText, sourceText) {
|
|
3174
|
+
const targetSections = parseMarkdownH2Sections(targetText);
|
|
3175
|
+
const sourceSections = parseMarkdownH2Sections(sourceText);
|
|
3176
|
+
const requiredTitles = ["Installed Integrations", "Tool Operation References", "Local QC Commands"];
|
|
3177
|
+
const targetByTitle = new Map(requiredTitles.map((title) => [title, targetSections.filter((section) => section.title === title)]));
|
|
3178
|
+
const sourceByTitle = new Map(requiredTitles.map((title) => [title, sourceSections.filter((section) => section.title === title)]));
|
|
3179
|
+
if (requiredTitles.some((title) => sourceByTitle.get(title).length !== 1)) return null;
|
|
3180
|
+
if (targetByTitle.get("Local QC Commands").length !== 1) return null;
|
|
3181
|
+
if (targetByTitle.get("Installed Integrations").length > 1 || targetByTitle.get("Tool Operation References").length > 1) return null;
|
|
3182
|
+
|
|
3183
|
+
const installed = targetByTitle.get("Installed Integrations")[0];
|
|
3184
|
+
const toolRefs = targetByTitle.get("Tool Operation References")[0];
|
|
3185
|
+
const localQc = targetByTitle.get("Local QC Commands")[0];
|
|
3186
|
+
if ((installed && installed.start > localQc.start) || (toolRefs && toolRefs.start > localQc.start)) return null;
|
|
3187
|
+
if (installed && toolRefs && installed.start > toolRefs.start) return null;
|
|
3188
|
+
|
|
3189
|
+
const missing = requiredTitles.slice(0, 2).filter((title) => targetByTitle.get(title).length === 0);
|
|
3190
|
+
let merged = targetText;
|
|
3191
|
+
if (missing.length > 0) {
|
|
3192
|
+
const insertion = missing
|
|
3193
|
+
.map((title) => sourceText.slice(sourceByTitle.get(title)[0].start, sourceByTitle.get(title)[0].end).trimEnd())
|
|
3194
|
+
.join("\n\n");
|
|
3195
|
+
merged = `${targetText.slice(0, localQc.start).trimEnd()}\n\n${insertion}\n\n${targetText.slice(localQc.start)}`;
|
|
3196
|
+
}
|
|
3197
|
+
merged = mergeProjectIndexCredentialReferences(merged);
|
|
3198
|
+
return projectIndexGovernanceSectionsAreValid(merged) ? merged : null;
|
|
3199
|
+
}
|
|
3200
|
+
|
|
2430
3201
|
function mergeProjectIndexCredentialReferences(targetText) {
|
|
2431
3202
|
return targetText
|
|
2432
3203
|
.replace(
|
|
@@ -2525,7 +3296,8 @@ function mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing) {
|
|
|
2525
3296
|
{ snippet: "parser failure", number: "13" },
|
|
2526
3297
|
{ snippet: "Process termination and cache cleanup boundary", number: "14" },
|
|
2527
3298
|
{ snippet: "task-owned or agent-managed", number: "14" },
|
|
2528
|
-
{ snippet: "other-agent-owned", number: "14" }
|
|
3299
|
+
{ snippet: "other-agent-owned", number: "14" },
|
|
3300
|
+
{ snippet: "Short-lived localhost validation services", number: "15" }
|
|
2529
3301
|
];
|
|
2530
3302
|
for (const { snippet, number } of appendableRules) {
|
|
2531
3303
|
if (!remainingMissing.includes(snippet) || targetText.includes(snippet)) continue;
|
|
@@ -2594,7 +3366,7 @@ function mergeIntegrationsSectionsByMissingAnchors(targetText, sourceText, missi
|
|
|
2594
3366
|
changed = true;
|
|
2595
3367
|
}
|
|
2596
3368
|
|
|
2597
|
-
if (missing.some((snippet) => snippet === "External Tool Usage Verification Gate" || snippet === "External Tool Resource Lifecycle" || snippet === "other-agent-owned" || snippet === "do not invent" || snippet === "input schema" || snippet === "official documentation" || snippet === "Runtime-Controlled Tool Operation Variants" || snippet === "Tool Operation References" || snippet === "Do not guess Chrome, Playwright, or DevTools commands")) {
|
|
3369
|
+
if (missing.some((snippet) => snippet === "External Tool Usage Verification Gate" || snippet === "External Tool Resource Lifecycle" || snippet === "other-agent-owned" || snippet === "do not invent" || snippet === "input schema" || snippet === "official documentation" || snippet === "Runtime-Controlled Tool Operation Variants" || snippet === "Tool Operation References" || snippet === "Do not guess Chrome, Playwright, or DevTools commands" || snippet === "Local HTML / app validation fallback" || snippet === "`file://` rejection alone is not enough evidence to stop")) {
|
|
2598
3370
|
const withVerificationGate = mergeIntegrationsVerificationGateSection(merged, sourceText);
|
|
2599
3371
|
if (!withVerificationGate) return null;
|
|
2600
3372
|
merged = withVerificationGate;
|
|
@@ -2638,38 +3410,6 @@ function mergeIntegrationsVerificationGateSection(targetText, sourceText) {
|
|
|
2638
3410
|
return null;
|
|
2639
3411
|
}
|
|
2640
3412
|
|
|
2641
|
-
function isLegacyChineseIntegrationsPack(text) {
|
|
2642
|
-
return text.includes("# Integrations Pack")
|
|
2643
|
-
&& countText(text, "## Scope") === 1
|
|
2644
|
-
&& countText(text, "## Load When") === 1
|
|
2645
|
-
&& countText(text, "## Discipline") === 1
|
|
2646
|
-
&& countText(text, "## Rules") === 1
|
|
2647
|
-
&& countText(text, "## Checks") === 1
|
|
2648
|
-
&& countText(text, "## Closeout") === 1
|
|
2649
|
-
&& countText(text, "## Cross-reference") === 1
|
|
2650
|
-
&& (text.includes("機密分離原則") || text.includes("四類整合"))
|
|
2651
|
-
&& !text.includes("## Local Discipline")
|
|
2652
|
-
&& !text.includes("Duplicate ambiguous local heading")
|
|
2653
|
-
&& countText(text, "四類整合") <= 2;
|
|
2654
|
-
}
|
|
2655
|
-
|
|
2656
|
-
function isLegacyChineseOnboardingPack(text) {
|
|
2657
|
-
return text.includes("# Onboarding Pack")
|
|
2658
|
-
&& countText(text, "## Scope") === 1
|
|
2659
|
-
&& countText(text, "## Load When") === 1
|
|
2660
|
-
&& countText(text, "## Discipline") === 1
|
|
2661
|
-
&& countText(text, "## Application Scenario Library") === 1
|
|
2662
|
-
&& countText(text, "## Cross-reference to guide.html") === 1
|
|
2663
|
-
&& countText(text, "## Tone Discipline") === 1
|
|
2664
|
-
&& countText(text, "## Closeout") === 1
|
|
2665
|
-
&& text.includes("### Scenario A.")
|
|
2666
|
-
&& text.includes("### Scenario E.")
|
|
2667
|
-
&& (text.includes("明確 onboarding signal keywords") || text.includes("Scenario F. 審視已裝外部工具") || text.includes("Anti-pattern(不要做的事)"))
|
|
2668
|
-
&& !text.includes("### Local Scenario A")
|
|
2669
|
-
&& !text.includes("structurally ambiguous onboarding")
|
|
2670
|
-
&& !text.includes("## Local Discipline");
|
|
2671
|
-
}
|
|
2672
|
-
|
|
2673
3413
|
function hasTrustedSafetyPackShape(text) {
|
|
2674
3414
|
return text.includes("# Safety Pack")
|
|
2675
3415
|
&& text.includes("## Scope")
|
|
@@ -2701,10 +3441,10 @@ function safetyAnchorHasTrustedRuleShape(text, snippet) {
|
|
|
2701
3441
|
&& line.includes("Prefer native PowerShell cmdlets")
|
|
2702
3442
|
&& line.includes("do not compose filesystem modification commands across shells");
|
|
2703
3443
|
}
|
|
2704
|
-
if (snippet === "git reset --hard") {
|
|
2705
|
-
return line.includes("
|
|
2706
|
-
&& line.includes("
|
|
2707
|
-
&& line.includes("
|
|
3444
|
+
if (snippet === "git reset --hard") {
|
|
3445
|
+
return line.includes("Never run")
|
|
3446
|
+
&& line.includes("User request does not make these named commands permissible")
|
|
3447
|
+
&& line.includes("git clean -fdx");
|
|
2708
3448
|
}
|
|
2709
3449
|
if (snippet === "secret values") {
|
|
2710
3450
|
return line.includes("Do not print")
|
|
@@ -2784,15 +3524,73 @@ function textSectionBounds(text, startHeading, endHeading) {
|
|
|
2784
3524
|
return { start: startIndex, end: endIndex };
|
|
2785
3525
|
}
|
|
2786
3526
|
|
|
2787
|
-
function projectIndexTemplateVersion(text) {
|
|
3527
|
+
function projectIndexTemplateVersion(text) {
|
|
2788
3528
|
const bounds = textSectionBounds(text, "## Stack", "## Directory Map");
|
|
2789
3529
|
if (!bounds) return null;
|
|
2790
3530
|
const stack = text.slice(bounds.start, bounds.end);
|
|
2791
3531
|
const row = stack.match(/^\| Agent Handoff Kit template version \| ([\d.]+) \| [^|\n]+ \|$/m);
|
|
2792
|
-
return row ? row[1] : null;
|
|
2793
|
-
}
|
|
2794
|
-
|
|
2795
|
-
function
|
|
3532
|
+
return row ? row[1] : null;
|
|
3533
|
+
}
|
|
3534
|
+
|
|
3535
|
+
function migrateSessionHandoff(targetText, sourceText, context = {}) {
|
|
3536
|
+
if (countText(targetText, "## Next Session Opening Message") !== 1) return null;
|
|
3537
|
+
let merged = mergeLegacyFirstStartupGuidance(targetText, sourceText) ?? targetText;
|
|
3538
|
+
|
|
3539
|
+
if (!merged.includes("ack:field:lifecycle-conflicts-resolved")) {
|
|
3540
|
+
merged = mergeHandoffLifecycleField(merged);
|
|
3541
|
+
if (!merged) return null;
|
|
3542
|
+
}
|
|
3543
|
+
merged = ensureCurrentHandoffMigrationFields(merged);
|
|
3544
|
+
if (!merged) return null;
|
|
3545
|
+
if (isUpgradeFromOlderTemplate(context)
|
|
3546
|
+
&& isPlaceholderLifecycleFieldValue(fieldValueAfterMarker(merged, "lifecycle-conflicts-resolved"))
|
|
3547
|
+
&& hasSubstantiveHandoffState(merged)) {
|
|
3548
|
+
merged = reclassifyExistingHandoffLifecyclePlaceholder(merged);
|
|
3549
|
+
if (!merged) return null;
|
|
3550
|
+
}
|
|
3551
|
+
|
|
3552
|
+
if (!merged.includes("ack:field:first-use-guidance-state")) {
|
|
3553
|
+
const nextMarker = "<!-- ack:section:task-understanding-summary -->";
|
|
3554
|
+
if (!merged.includes(nextMarker)) return null;
|
|
3555
|
+
const field = "<!-- ack:field:first-use-guidance-state -->\n5. First-use guidance state: not_applicable — added by upgrade; prior use state is preserved and onboarding is not reactivated.\n\n";
|
|
3556
|
+
merged = merged.replace(nextMarker, `${field}${nextMarker}`);
|
|
3557
|
+
}
|
|
3558
|
+
|
|
3559
|
+
const archiveRule = mergeHandoffArchiveContinuityRule(merged, sourceText);
|
|
3560
|
+
if (!archiveRule) return null;
|
|
3561
|
+
merged = archiveRule;
|
|
3562
|
+
|
|
3563
|
+
const targetBounds = handoffSectionContentBounds(merged, "next-session-opening-message", "Next Session Opening Message");
|
|
3564
|
+
const sourceBounds = handoffSectionContentBounds(sourceText, "next-session-opening-message", "Next Session Opening Message");
|
|
3565
|
+
if (!targetBounds || !sourceBounds) return null;
|
|
3566
|
+
const targetSection = merged.slice(targetBounds.start, targetBounds.end);
|
|
3567
|
+
const sourceSection = sourceText.slice(sourceBounds.start, sourceBounds.end);
|
|
3568
|
+
const targetPrompt = targetSection.match(/```text\s*\r?\n([\s\S]*?)\r?\n```/);
|
|
3569
|
+
const sourcePrompt = sourceSection.match(/```text\s*\r?\n([\s\S]*?)\r?\n```/);
|
|
3570
|
+
if (!targetPrompt || !sourcePrompt) return null;
|
|
3571
|
+
const existingRoot = targetPrompt[1].match(/^Work in (.+?)\. Read AGENTS\.md,/m)?.[1] ?? "<absolute project root>";
|
|
3572
|
+
const currentPrompt = sourcePrompt[1].replace("<absolute project root>", existingRoot);
|
|
3573
|
+
const updatedSection = targetSection.replace(targetPrompt[0], `\`\`\`text\n${currentPrompt}\n\`\`\``);
|
|
3574
|
+
merged = `${merged.slice(0, targetBounds.start)}${updatedSection}${merged.slice(targetBounds.end)}`;
|
|
3575
|
+
|
|
3576
|
+
const temperatureRepair = repairHandoffCurrentStateEvidenceBoundary(merged);
|
|
3577
|
+
return temperatureRepair.text;
|
|
3578
|
+
}
|
|
3579
|
+
|
|
3580
|
+
function migrateSessionLog(targetText, sourceText) {
|
|
3581
|
+
let merged = mergeSessionLogTemplateContract(targetText, sourceText);
|
|
3582
|
+
if (!merged) return null;
|
|
3583
|
+
merged = mergeSessionLogEvidenceDispositionField(merged);
|
|
3584
|
+
if (!merged) return null;
|
|
3585
|
+
|
|
3586
|
+
const targetContract = sessionLogEntryTemplateContract(merged);
|
|
3587
|
+
const sourceContract = sessionLogEntryTemplateContract(sourceText);
|
|
3588
|
+
if (!targetContract || !sourceContract) return null;
|
|
3589
|
+
merged = `${merged.slice(0, targetContract.entryStart)}${sourceText.slice(sourceContract.entryStart, sourceContract.entryEnd)}${merged.slice(targetContract.entryEnd)}`;
|
|
3590
|
+
return merged;
|
|
3591
|
+
}
|
|
3592
|
+
|
|
3593
|
+
function mergeHandoffLifecycleField(targetText) {
|
|
2796
3594
|
const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
|
|
2797
3595
|
if (!targetText.includes(openingMarker)) return null;
|
|
2798
3596
|
|
|
@@ -2892,17 +3690,22 @@ function ensureHandoffStateReconciliationRules(targetText) {
|
|
|
2892
3690
|
return `${targetText.trimEnd()}\n\n${ruleBlock}`;
|
|
2893
3691
|
}
|
|
2894
3692
|
|
|
2895
|
-
function mergeSessionLogEvidenceDispositionField(targetText) {
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
if (
|
|
2899
|
-
const
|
|
2900
|
-
|
|
2901
|
-
}
|
|
2902
|
-
|
|
2903
|
-
|
|
2904
|
-
|
|
2905
|
-
|
|
3693
|
+
function mergeSessionLogEvidenceDispositionField(targetText) {
|
|
3694
|
+
const contract = sessionLogEntryTemplateContract(targetText);
|
|
3695
|
+
if (!contract) return null;
|
|
3696
|
+
if (contract.templateText.includes("- **Evidence disposition:**")) return targetText;
|
|
3697
|
+
const qcField = "- **QC:**";
|
|
3698
|
+
if (countText(contract.templateText, qcField) !== 1) return null;
|
|
3699
|
+
const withEvidenceTemplate = contract.templateText.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>`);
|
|
3700
|
+
return `${targetText.slice(0, contract.templateStart)}${withEvidenceTemplate}${targetText.slice(contract.templateEnd)}`;
|
|
3701
|
+
}
|
|
3702
|
+
|
|
3703
|
+
function mergeSessionLogTemplateContract(targetText, sourceText = null) {
|
|
3704
|
+
let merged = targetText;
|
|
3705
|
+
let changed = false;
|
|
3706
|
+
|
|
3707
|
+
const initialSection = uniqueSessionLogEntryTemplateSection(merged);
|
|
3708
|
+
if (!initialSection) return null;
|
|
2906
3709
|
|
|
2907
3710
|
if (!merged.includes("ack:section:session-log-preamble")) {
|
|
2908
3711
|
const titleMatch = /^# Session Log\s*$/m.exec(merged);
|
|
@@ -2917,13 +3720,19 @@ function mergeSessionLogTemplateContract(targetText, sourceText = null) {
|
|
|
2917
3720
|
}
|
|
2918
3721
|
}
|
|
2919
3722
|
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
3723
|
+
const sectionMarker = "<!-- ack:section:session-log-entry-template -->";
|
|
3724
|
+
const sectionMarkerCount = countText(merged, sectionMarker);
|
|
3725
|
+
if (sectionMarkerCount > 1) return null;
|
|
3726
|
+
if (sectionMarkerCount === 0) {
|
|
3727
|
+
const currentSection = uniqueSessionLogEntryTemplateSection(merged);
|
|
3728
|
+
if (!currentSection) return null;
|
|
3729
|
+
merged = `${merged.slice(0, currentSection.start)}${sectionMarker}\n\n${merged.slice(currentSection.start)}`;
|
|
3730
|
+
changed = true;
|
|
3731
|
+
} else {
|
|
3732
|
+
const currentSection = uniqueSessionLogEntryTemplateSection(merged);
|
|
3733
|
+
const markerIndex = merged.indexOf(sectionMarker);
|
|
3734
|
+
if (!currentSection || markerIndex >= currentSection.start || merged.slice(markerIndex + sectionMarker.length, currentSection.start).trim() !== "") return null;
|
|
3735
|
+
}
|
|
2927
3736
|
|
|
2928
3737
|
if (sourceText) {
|
|
2929
3738
|
const restored = restoreMissingSessionLogPreambleLines(merged, sourceText);
|
|
@@ -2933,32 +3742,30 @@ function mergeSessionLogTemplateContract(targetText, sourceText = null) {
|
|
|
2933
3742
|
}
|
|
2934
3743
|
}
|
|
2935
3744
|
|
|
2936
|
-
const
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
return changed ? merged : targetText;
|
|
2961
|
-
}
|
|
3745
|
+
const section = uniqueSessionLogEntryTemplateSection(merged);
|
|
3746
|
+
const fence = sessionLogTemplateFence(merged, section);
|
|
3747
|
+
if (!section || !fence) return null;
|
|
3748
|
+
const startMarker = "<!-- ack:log-entry:start -->";
|
|
3749
|
+
const endMarker = "<!-- ack:log-entry:end -->";
|
|
3750
|
+
const sectionText = merged.slice(section.start, section.end);
|
|
3751
|
+
if (countText(sectionText, startMarker) > 1 || countText(sectionText, endMarker) > 1) return null;
|
|
3752
|
+
let templateText = fence.templateText;
|
|
3753
|
+
if (!templateText.includes(startMarker)) {
|
|
3754
|
+
templateText = `${startMarker}\n${templateText}`;
|
|
3755
|
+
changed = true;
|
|
3756
|
+
}
|
|
3757
|
+
if (!templateText.includes(endMarker)) {
|
|
3758
|
+
templateText = `${templateText.trimEnd()}\n${endMarker}`;
|
|
3759
|
+
changed = true;
|
|
3760
|
+
}
|
|
3761
|
+
if (templateText !== fence.templateText) {
|
|
3762
|
+
merged = `${merged.slice(0, fence.templateStart)}${templateText}${merged.slice(fence.templateEnd)}`;
|
|
3763
|
+
}
|
|
3764
|
+
|
|
3765
|
+
if (!sessionLogEntryTemplateContract(merged)) return null;
|
|
3766
|
+
|
|
3767
|
+
return changed ? merged : targetText;
|
|
3768
|
+
}
|
|
2962
3769
|
|
|
2963
3770
|
function restoreMissingSessionLogPreambleLines(targetText, sourceText) {
|
|
2964
3771
|
const sourceEntryIndex = sourceText.search(/^## Entry Template\s*$/m);
|
|
@@ -2971,8 +3778,9 @@ function restoreMissingSessionLogPreambleLines(targetText, sourceText) {
|
|
|
2971
3778
|
const missingLines = [
|
|
2972
3779
|
"Record what actually happened in the session",
|
|
2973
3780
|
"kept, summarized, or archived",
|
|
2974
|
-
"Do not remove validation evidence",
|
|
2975
|
-
"
|
|
3781
|
+
"Do not remove validation evidence",
|
|
3782
|
+
"full opening message never belongs",
|
|
3783
|
+
"latest opening message",
|
|
2976
3784
|
"not current state"
|
|
2977
3785
|
].flatMap((snippet) => {
|
|
2978
3786
|
if (targetText.includes(snippet)) return [];
|
|
@@ -3008,50 +3816,58 @@ function mergeHandoffArchiveContinuityRule(targetText, sourceText) {
|
|
|
3008
3816
|
return null;
|
|
3009
3817
|
}
|
|
3010
3818
|
|
|
3011
|
-
function mergeRulePacksRows(targetText, sourceText) {
|
|
3012
|
-
const
|
|
3013
|
-
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
const
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
if (
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
|
|
3049
|
-
|
|
3050
|
-
|
|
3051
|
-
|
|
3052
|
-
]
|
|
3053
|
-
|
|
3054
|
-
|
|
3819
|
+
function mergeRulePacksRows(targetText, sourceText) {
|
|
3820
|
+
const sourceRows = sourceText.split(/\r?\n/).filter((line) => /^\|.*<!-- ack:route:[a-z0-9-]+ -->/.test(line));
|
|
3821
|
+
const sourceById = new Map(sourceRows.map((row) => [routeMarkerId(row), row]));
|
|
3822
|
+
if (sourceById.size === 0 || sourceById.size !== sourceRows.length) return null;
|
|
3823
|
+
|
|
3824
|
+
const lines = targetText.split(/\r?\n/);
|
|
3825
|
+
const headerIndexes = lines.map((line, index) => line.trim() === "| Task signal | Pack | Purpose |" ? index : -1).filter((index) => index >= 0);
|
|
3826
|
+
if (headerIndexes.length !== 1) return null;
|
|
3827
|
+
const tableStart = headerIndexes[0];
|
|
3828
|
+
if (!/^\|[-\s|]+\|$/.test(lines[tableStart + 1]?.trim() ?? "")) return null;
|
|
3829
|
+
let tableEnd = tableStart + 2;
|
|
3830
|
+
while (tableEnd < lines.length && lines[tableEnd].startsWith("|")) tableEnd += 1;
|
|
3831
|
+
|
|
3832
|
+
const seen = new Set();
|
|
3833
|
+
const localRows = [];
|
|
3834
|
+
const replacedRows = [];
|
|
3835
|
+
for (const row of lines.slice(tableStart + 2, tableEnd)) {
|
|
3836
|
+
const markedId = routeMarkerId(row);
|
|
3837
|
+
const legacyId = markedId ? null : knownOfficialLegacyRouteId(row);
|
|
3838
|
+
const id = markedId ?? legacyId;
|
|
3839
|
+
if (id && sourceById.has(id)) {
|
|
3840
|
+
if (seen.has(id)) return null;
|
|
3841
|
+
seen.add(id);
|
|
3842
|
+
replacedRows.push(sourceById.get(id));
|
|
3843
|
+
continue;
|
|
3844
|
+
}
|
|
3845
|
+
localRows.push(row);
|
|
3846
|
+
}
|
|
3847
|
+
|
|
3848
|
+
const missingOfficialRows = sourceRows.filter((row) => !seen.has(routeMarkerId(row)));
|
|
3849
|
+
const mergedTable = [lines[tableStart], lines[tableStart + 1], ...missingOfficialRows, ...replacedRows, ...localRows];
|
|
3850
|
+
const originalTable = lines.slice(tableStart, tableEnd);
|
|
3851
|
+
if (mergedTable.join("\n") === originalTable.join("\n")) return targetText;
|
|
3852
|
+
return [...lines.slice(0, tableStart), ...mergedTable, ...lines.slice(tableEnd)].join("\n");
|
|
3853
|
+
}
|
|
3854
|
+
|
|
3855
|
+
const knownOfficialLegacyRouteHashes = new Map([
|
|
3856
|
+
["f2c36ac687929b03891b37fe79aace2c806d9d5027c43b7d280c386574e44c14", "onboarding"],
|
|
3857
|
+
["3153da07fb53483eeb4a35cfff013f44c5a75d14b1a44ee536bcd85cbc3219c6", "governance-bridge"],
|
|
3858
|
+
["d3379dc2984fb0f2a8f122c4efbf131b2da320e66845d4c5f1945300431879f3", "long-term-governance"],
|
|
3859
|
+
["2011d8309aaa5d6cc76f7036e990355c472a5ed6ba81fcf8e0078b9a6c5f6ef1", "integration-use"],
|
|
3860
|
+
["3fc0717cc408dbe96e8925a07f6315448abb0f38106dbe844a098d7ab84d37cc", "runtime-tool"],
|
|
3861
|
+
["7cd99dbd30bbf7be9641f6a5fc7bf4c7cbe3efb3ab114fe1f19c254cd110612d", "resource-closeout"]
|
|
3862
|
+
]);
|
|
3863
|
+
|
|
3864
|
+
function routeMarkerId(row) {
|
|
3865
|
+
return row.match(/<!-- ack:route:([a-z0-9-]+) -->/)?.[1] ?? null;
|
|
3866
|
+
}
|
|
3867
|
+
|
|
3868
|
+
function knownOfficialLegacyRouteId(row) {
|
|
3869
|
+
return knownOfficialLegacyRouteHashes.get(sha256(Buffer.from(row.trim(), "utf8"))) ?? null;
|
|
3870
|
+
}
|
|
3055
3871
|
|
|
3056
3872
|
// R-031.2 v0.3.2+: Version alignment assessment for doctor "項目狀態速覽".
|
|
3057
3873
|
// Compares CLI version (running), root template metadata version (in dev/PROJECT_INDEX.md),
|
|
@@ -3167,22 +3983,23 @@ function printLastCloseout(result) {
|
|
|
3167
3983
|
// R-031.2 v0.3.2+: Project age assessment. Reads the oldest folder timestamp in
|
|
3168
3984
|
// dev/governance_migrations/ which records the first install date. Read-only; doctor
|
|
3169
3985
|
// remains side-effect-free (no new write logic).
|
|
3170
|
-
async function assessProjectAge(root) {
|
|
3171
|
-
const migrationsDir = path.join(root, "dev/governance_migrations");
|
|
3172
|
-
try {
|
|
3173
|
-
const entries = await readdir(migrationsDir);
|
|
3174
|
-
const
|
|
3175
|
-
|
|
3176
|
-
|
|
3177
|
-
|
|
3178
|
-
|
|
3179
|
-
|
|
3180
|
-
|
|
3181
|
-
|
|
3182
|
-
|
|
3183
|
-
|
|
3184
|
-
}
|
|
3185
|
-
}
|
|
3986
|
+
async function assessProjectAge(root) {
|
|
3987
|
+
const migrationsDir = path.join(root, "dev/governance_migrations");
|
|
3988
|
+
try {
|
|
3989
|
+
const entries = await readdir(migrationsDir);
|
|
3990
|
+
const dates = entries.map(parseMigrationDirectoryDate).filter(Boolean).sort();
|
|
3991
|
+
return { firstInstall: dates[0] ?? null };
|
|
3992
|
+
} catch {
|
|
3993
|
+
return { firstInstall: null };
|
|
3994
|
+
}
|
|
3995
|
+
}
|
|
3996
|
+
|
|
3997
|
+
function parseMigrationDirectoryDate(name) {
|
|
3998
|
+
const legacy = /^(\d{4})(\d{2})(\d{2})T\d{6}Z$/.exec(name);
|
|
3999
|
+
if (legacy) return `${legacy[1]}-${legacy[2]}-${legacy[3]}`;
|
|
4000
|
+
const transaction = /^(\d{4})-(\d{2})-(\d{2})T\d{2}-\d{2}-\d{2}-\d{3}Z-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.exec(name);
|
|
4001
|
+
return transaction ? `${transaction[1]}-${transaction[2]}-${transaction[3]}` : null;
|
|
4002
|
+
}
|
|
3186
4003
|
|
|
3187
4004
|
function printProjectAge(result) {
|
|
3188
4005
|
if (!result.firstInstall) {
|
|
@@ -3471,8 +4288,8 @@ function printInstallSummary(version, command, mode, root, counts) {
|
|
|
3471
4288
|
if (counts.conflicts > 0) {
|
|
3472
4289
|
console.log("🚀 下一步:把 migration report 或這段輸出貼給 AI,請它判斷衝突檔案怎樣處理;工具已停手,沒有覆寫 conflict 檔案。");
|
|
3473
4290
|
} else if (command === "upgrade") {
|
|
3474
|
-
console.log("🚀
|
|
3475
|
-
} else if (
|
|
4291
|
+
console.log("🚀 下一步:留意下方 migration committed 與 project health 的分開結果。");
|
|
4292
|
+
} else if (counts.skipped > 0) {
|
|
3476
4293
|
console.log("🚀 下一步:先看下方提示。若你原本已有 AGENTS.md 或其他 AI 規則,請先執行 upgrade --dry-run 補入口連接,再執行 doctor。");
|
|
3477
4294
|
} else {
|
|
3478
4295
|
console.log("🚀 下一步:不用再留在終端機。打開 AI 工具,啟動 Agent Handoff。");
|
|
@@ -3663,7 +4480,7 @@ function printCard(version, status, eyes) {
|
|
|
3663
4480
|
function printInstallNextSteps(root, conflictCount, mode = "first-install", skippedCount = 0) {
|
|
3664
4481
|
console.log("");
|
|
3665
4482
|
console.log("============================================================");
|
|
3666
|
-
if (
|
|
4483
|
+
if (skippedCount > 0) {
|
|
3667
4484
|
console.log("⚠️ 已補齊缺少檔案,但仍要檢查入口連接");
|
|
3668
4485
|
} else {
|
|
3669
4486
|
console.log("✅ 安裝完成:下一步請在 AI 對話中操作");
|
|
@@ -3675,7 +4492,7 @@ function printInstallNextSteps(root, conflictCount, mode = "first-install", skip
|
|
|
3675
4492
|
console.log("📋 下一步:把 migration report 或這段輸出貼給 AI,請它幫你判斷怎樣合併。");
|
|
3676
4493
|
console.log("");
|
|
3677
4494
|
}
|
|
3678
|
-
if (
|
|
4495
|
+
if (skippedCount > 0) {
|
|
3679
4496
|
console.log("你原本已有部分 AI 記憶檔,工具已保留它們,沒有覆寫。");
|
|
3680
4497
|
console.log("下一步先不要開始新任務;請在終端機執行以下預演,讓工具檢查能否安全補入口連接:");
|
|
3681
4498
|
console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run");
|
|
@@ -3698,8 +4515,9 @@ function printInstallNextSteps(root, conflictCount, mode = "first-install", skip
|
|
|
3698
4515
|
console.log(startupPathBootstrapPrompt(root));
|
|
3699
4516
|
console.log("------------------------------------------------------------");
|
|
3700
4517
|
console.log("");
|
|
3701
|
-
console.log("🚀 AI 會依 AGENTS.md
|
|
3702
|
-
console.log("
|
|
4518
|
+
console.log("🚀 AI 會依 AGENTS.md 先讀取權威交接狀態。START_NEXT_SESSION_PROMPT.txt 只是給尚未指向此資料夾的 AI 使用的生成鏡像。");
|
|
4519
|
+
console.log(" 已給出明確任務時,AI 直接開始第一個安全步驟;只有你要求教學或仍無可執行目標時才進入新手引導。");
|
|
4520
|
+
console.log(" 收工可說「Wrap up Agent Handoff」/「收工」;「開工,繼續 <任務>」會直接接力。");
|
|
3703
4521
|
console.log("============================================================");
|
|
3704
4522
|
}
|
|
3705
4523
|
|
|
@@ -3718,14 +4536,14 @@ function printUpgradeNextSteps(root, conflictCount) {
|
|
|
3718
4536
|
console.log("============================================================");
|
|
3719
4537
|
return;
|
|
3720
4538
|
}
|
|
3721
|
-
console.log("🛠️ Kit
|
|
4539
|
+
console.log("🛠️ Kit migration 已通過離線遷移驗收;下方 doctor 另行回報整體項目健康");
|
|
3722
4540
|
console.log("============================================================");
|
|
3723
4541
|
console.log("📋 如你正在進行中的工作對話已熟悉 Agent Handoff Kit,繼續使用原本的開工方式即可,無需重新做新手引導。");
|
|
3724
4542
|
console.log("");
|
|
3725
4543
|
console.log("💡 版本詳情不在升級流程內展開;如需要,可稍後查看 GitHub Release:");
|
|
3726
4544
|
console.log(" https://github.com/Adamchanadam/agent-handoff-kit/releases/latest");
|
|
3727
4545
|
console.log("");
|
|
3728
|
-
console.log("🩺
|
|
4546
|
+
console.log("🩺 下方會分開顯示 migration committed 與 project health;doctor 需要處理時,不會改寫已提交的遷移結果。");
|
|
3729
4547
|
console.log("============================================================");
|
|
3730
4548
|
}
|
|
3731
4549
|
|
|
@@ -3834,10 +4652,10 @@ Commands:
|
|
|
3834
4652
|
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.
|
|
3835
4653
|
例如 Claude Code、OpenAI Codex、Gemini CLI、Google Antigravity。
|
|
3836
4654
|
普通 web chat AI 若不能讀寫本機資料夾,並不適合使用本工具。
|
|
3837
|
-
AI
|
|
3838
|
-
|
|
3839
|
-
用「Wrap up Agent Handoff
|
|
3840
|
-
|
|
4655
|
+
AI 已在項目根目錄時,依 AGENTS.md 判斷意圖;只有接力、收工或依賴既有狀態的任務才讀交接狀態,
|
|
4656
|
+
不會再重讀 START_NEXT_SESSION_PROMPT.txt。第一次安裝只令新手引導可用,不會強制進入教學。
|
|
4657
|
+
用「Wrap up Agent Handoff」/「收工」保存交接;「<項目名> 開工」是明確接力。
|
|
4658
|
+
只有語句確實可能指現實工作、活動或其他語境時,AI 才問一條精簡確認問題。
|
|
3841
4659
|
|
|
3842
4660
|
終端機範例:
|
|
3843
4661
|
npx --yes @adamchanadam/agent-handoff-kit@latest init
|