@adamchanadam/agent-handoff-kit 0.3.52 → 0.3.53

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.
@@ -10,7 +10,17 @@ import { fileURLToPath } from "node:url";
10
10
  import { assessPromptMirrorRoot, assessPromptMirrorTexts, extractOpeningMessage } from "./prompt-mirror-core.mjs";
11
11
  import { freshInstallMappings, installedFileContract, installedMappings, requiredInstalledTargets, upgradeStateMappings, upgradeStateTargets } from "./installed-file-contract.mjs";
12
12
  import { getArtifactBoundManagedSegment, getOfficialBaseline, identifyOfficialOrigin, loadOfficialOriginCatalog } from "./official-origin-catalog.mjs";
13
- import { assertGate5FrozenSet, extractExplicitLocalReferences, freezeGate5Set, gate5SourceConservationItems } from "./upgrade-inventory.mjs";
13
+ import {
14
+ assertGate5FrozenSet,
15
+ extractExplicitLocalReferences,
16
+ freezeGate5Set,
17
+ gate5SourceConservationItems,
18
+ markdownVisibleLinesOutsideHiddenBlocks,
19
+ materializeProjectIndexTemplateVersion,
20
+ parseProjectIndexTemplateVersion,
21
+ projectIndexTemplateVersionRow,
22
+ readProjectIndexTemplateVersion
23
+ } from "./upgrade-inventory.mjs";
14
24
  import {
15
25
  FORMAL_USER_RULES_ENTRY_ANCHOR,
16
26
  USER_RULES_ROUTER_PATH,
@@ -48,7 +58,7 @@ const directCloseoutStateTargets = Object.freeze([...closeoutFinalizeTargets].so
48
58
  const directCloseoutStateTargetSet = new Set(directCloseoutStateTargets);
49
59
  const canonicalSessionLogArchiveRoot = "dev/SESSION_LOG_archive";
50
60
  const legacySessionLogArchiveRoot = "dev/session_log_archive";
51
- const credentialLeakPatterns = [
61
+ const credentialLeakPatterns = [
52
62
  { pattern: /sk-ant-[A-Za-z0-9_-]{20,}/, label: "Anthropic API key" },
53
63
  { pattern: /\bsk-[A-Za-z0-9_-]{20,}/, label: "sk-prefixed token" },
54
64
  { pattern: /\bntn_[A-Za-z0-9_-]{40,}/, label: "Notion token" },
@@ -60,8 +70,10 @@ const credentialLeakPatterns = [
60
70
  { pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}/, label: "GitHub fine-grained token" },
61
71
  { pattern: /\bsl\.[A-Za-z0-9_-]{50,}/, label: "Dropbox token" },
62
72
  { pattern: /\bAKIA[A-Z0-9]{16}/, label: "AWS access key" },
63
- { pattern: /\bAIza[A-Za-z0-9_-]{35}/, label: "Google API key" }
64
- ];
73
+ { pattern: /\bAIza[A-Za-z0-9_-]{35}/, label: "Google API key" }
74
+ ];
75
+ const projectIndexTemplateVersionMetadataReason = "update only the unique real PROJECT_INDEX Stack template-version row while preserving every other PROJECT_INDEX byte";
76
+ const projectIndexTemplateVersionMetadataTransition = "project-index-template-version";
65
77
 
66
78
  // Exact v0.3.38 continuity quick-fix packs observed in real projects before the
67
79
  // product migration shipped. They contain no project-specific state. Matching
@@ -442,15 +454,9 @@ const schemaChecks = [
442
454
  // to verify the section is structurally present.
443
455
  tableHeader("Check", "Command", "Run before", "Last verified"),
444
456
  tableHeader("Change type", "Likely files", "Required checks"),
445
- // R-030 v0.3.0+: Installed Integrations subsection table headers
446
- tableHeader("Tool", "Project Usage", "Access Scope", "Specific Instance", "Credential Reference (no value)", "Declared", "Last Verified"),
447
- tableHeader("Server", "Source", "Project Usage", "Credential Reference (no value)", "Declared", "Last Verified"),
448
- tableHeader("Name", "Bundle Content (Skills + MCP + hooks)", "When Triggered", "Last Verified"),
449
- tableHeader("Name", "Source", "When Triggered", "Last Verified"),
450
- tableHeader("Layer", "Surface (specific instance)", "Role", "Write Direction"),
451
- tableHeader("Tool / operation", "Reference path or URL", "Required before", "Source and version/date", "Scope and known limits", "Last verified")
452
- ]
453
- },
457
+ tableHeader("Tool / operation", "Reference path or URL", "Required before", "Source and version/date", "Scope and known limits", "Last verified")
458
+ ]
459
+ },
454
460
  {
455
461
  target: "dev/DOC_SYNC_REGISTRY.md",
456
462
  label: "doc sync registry status vocabulary",
@@ -856,20 +862,11 @@ function parseArgs(args) {
856
862
  // row is stale relative to current CLI version. Used by plan-time no-op detection
857
863
  // guard to ensure metadata-only stale roots still trigger the upgrade ceremony
858
864
  // (otherwise plan-time short-circuit returns before inject can run).
859
- async function needsProjectIndexVersionInject(root, command, version) {
860
- if (command !== "upgrade") return false;
861
- try {
862
- const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
863
- const text = await readFile(indexPath, "utf8");
864
- const m = text.match(/\| Agent Handoff Kit template version \| ([\d.]+) \|/);
865
- if (m && isStableSemver(m[1]) && compareSemver(m[1], version) < 0) {
866
- return true;
867
- }
868
- } catch {
869
- // ignore — silent if PROJECT_INDEX missing or unreadable
870
- }
871
- return false;
872
- }
865
+ async function needsProjectIndexVersionInject(root, command, version) {
866
+ if (command !== "upgrade") return false;
867
+ const installedVersion = await readProjectIndexTemplateVersion(root);
868
+ return Boolean(installedVersion && compareSemver(installedVersion, version) < 0);
869
+ }
873
870
 
874
871
  async function runInstall(command, root, options, version) {
875
872
  // Guard the selected root before reading or recovering any persisted
@@ -883,7 +880,7 @@ async function runInstall(command, root, options, version) {
883
880
  return;
884
881
  }
885
882
  }
886
- const installedVersion = await readInstalledTemplateVersion(root);
883
+ const installedVersion = await readProjectIndexTemplateVersion(root);
887
884
  if (command === "upgrade" && installedVersion && compareSemver(installedVersion, version) > 0) {
888
885
  console.log(`selected root: ${root}`);
889
886
  console.log(`status: blocked`);
@@ -902,7 +899,7 @@ async function runInstall(command, root, options, version) {
902
899
  if (command === "upgrade") {
903
900
  let acceptedCurrentState = null;
904
901
  try {
905
- acceptedCurrentState = await loadCommittedCurrentStateWitness(root);
902
+ acceptedCurrentState = await loadCommittedCurrentStateWitness(root, { allowHistoricalEdgeRetirement: true });
906
903
  } catch (error) {
907
904
  if (!String(error?.message ?? error).includes("doctor refuses an unbound success state")) throw error;
908
905
  await assertUnboundCurrentStateMayAttemptUpgradeRebind(root, error);
@@ -986,26 +983,21 @@ async function runInstall(command, root, options, version) {
986
983
  return;
987
984
  }
988
985
 
986
+ let transactionPreflight = null;
989
987
  if (planConflictCount === 0) {
990
- candidateOutputs ??= await buildTransactionOutputs(command, root, plan, version);
991
- const credentialFindings = await detectInstalledCredentialFindings(root);
992
- if (credentialFindings.length > 0) {
993
- plan.push({
994
- targetRel: "transaction preflight",
995
- action: "conflict",
996
- reason: `existing governance contains ${credentialFindings.length} possible credential value(s); remove and rotate them before upgrade`
997
- });
998
- } else {
999
- try {
1000
- await validateTransactionOverlay(root, candidateOutputs);
1001
- } catch (error) {
1002
- plan.push({
1003
- targetRel: "transaction preflight",
1004
- action: "conflict",
1005
- reason: safeErrorLabel(error)
1006
- });
1007
- }
1008
- }
988
+ try {
989
+ transactionPreflight = await buildInstallTransactionPreflight(command, root, plan, version, {
990
+ candidateOutputs,
991
+ sourceConservationRebind
992
+ });
993
+ candidateOutputs = transactionPreflight.outputs;
994
+ } catch (error) {
995
+ plan.push({
996
+ targetRel: "transaction preflight",
997
+ action: "conflict",
998
+ reason: safeErrorLabel(error)
999
+ });
1000
+ }
1009
1001
  }
1010
1002
 
1011
1003
  printPlan(command, root, mode, plan, version, options.dryRun, installedVersion);
@@ -1034,71 +1026,31 @@ async function runInstall(command, root, options, version) {
1034
1026
  }
1035
1027
  }
1036
1028
 
1037
- await executeInstallTransaction(command, root, mode, plan, version, candidateOutputs, { sourceConservationRebind });
1029
+ await executeInstallTransaction(command, root, mode, plan, version, transactionPreflight, { sourceConservationRebind });
1038
1030
  }
1039
1031
 
1040
- async function readInstalledTemplateVersion(root) {
1041
- try {
1042
- const text = await readFile(path.join(root, "dev/PROJECT_INDEX.md"), "utf8");
1043
- const match = text.match(/\| Agent Handoff Kit template version \| ([\d.]+) \|/);
1044
- return match && isStableSemver(match[1]) ? match[1] : null;
1045
- } catch {
1046
- return null;
1047
- }
1048
- }
1049
-
1050
- async function executeInstallTransaction(command, root, mode, plan, version, candidateOutputs = null, options = {}) {
1051
- const outputs = candidateOutputs ?? await buildTransactionOutputs(command, root, plan, version);
1052
- if (outputs.length === 0) {
1053
- const health = await assessUpgradeNoopHealth(root, version);
1054
- printUpgradeNoopShortCircuit(version, health);
1032
+ async function executeInstallTransaction(command, root, mode, plan, version, candidatePreflight = null, options = {}) {
1033
+ const preflight = candidatePreflight ?? await buildInstallTransactionPreflight(command, root, plan, version, options);
1034
+ const outputs = preflight.outputs;
1035
+ if (outputs.length === 0) {
1036
+ const health = await assessUpgradeNoopHealth(root, version);
1037
+ printUpgradeNoopShortCircuit(version, health);
1055
1038
  if (!health.ok) process.exitCode = 1;
1056
1039
  return;
1057
1040
  }
1058
1041
 
1059
- const credentialFindings = await detectInstalledCredentialFindings(root);
1060
- if (credentialFindings.length > 0) {
1061
- console.log("⛔ 升級已停止:待備份的治理檔疑似含有 credential value。");
1062
- console.log("機密值不會顯示或複製;請先移除並輪換機密,再重跑 upgrade。");
1063
- for (const finding of credentialFindings) console.log(`blocked ${finding.relative}:${finding.line} (${finding.label})`);
1064
- process.exitCode = 1;
1065
- return;
1066
- }
1067
-
1068
- // Run the same deterministic acceptance gate used by dry-run before creating
1069
- // a lock, stage, backup, journal, or migration directory.
1070
- await validateTransactionOverlay(root, outputs);
1071
1042
  // The user has confirmed writes. Create and revalidate a missing root only
1072
1043
  // now, immediately before transaction artifacts are prepared.
1073
1044
  await validateTransactionRoot(root, plan, { createMissingRoot: true });
1074
- // Gate 5 does not introduce a second state owner. When this existing
1075
- // transaction already has a runtime acceptance, bind the pre-transaction
1076
- // root-source witness into the same current-state digest before the journal
1077
- // directory itself is created.
1078
- const archiveMigrations = command === "upgrade"
1079
- ? await prepareArchiveCasingMigrations(root)
1080
- : [];
1081
- const sourceConservationAuthority = command === "upgrade"
1082
- ? await hasCommittedSourceConservationAuthority(root)
1083
- : false;
1084
- if (options.sourceConservationRebind === true) {
1085
- for (const output of outputs) delete output.runtimeAcceptance;
1045
+ const transaction = await prepareTransaction(root, command, version, outputs, mode, plan, preflight.sourceConservation, preflight.supersedesCurrentStateDigests, preflight.archiveMigrations);
1046
+ try {
1047
+ await injectBeforeLockRevalidationDrift(root, transaction.journal);
1048
+ await assertPreparedTransactionPreflightStillCurrent(root, transaction, preflight, plan, { sourceConservationRebind: options.sourceConservationRebind === true });
1049
+ } catch (error) {
1050
+ await abortPreparedTransactionBeforeTargetWrites(root, transaction, error);
1051
+ throw error;
1086
1052
  }
1087
- const runtimeAcceptance = command === "upgrade" && options.sourceConservationRebind !== true ? resolveRuntimeAcceptance(outputs) : null;
1088
- const sourceConservation = command === "upgrade" && (
1089
- runtimeAcceptance || sourceConservationAuthority
1090
- )
1091
- ? await createSourceConservation(root, outputs, archiveMigrations)
1092
- : null;
1093
- // A repair may restore the exact bytes of a prior committed state. Keep the
1094
- // causal replacement relation inside the existing sealed journal so ordinary
1095
- // doctor can select the freshly read-back transaction without falling back
1096
- // to mtime or a separate current-state registry.
1097
- const supersedesCurrentStateDigests = command === "upgrade"
1098
- ? await findRestoredCurrentStateDigests(root, outputs, archiveMigrations, { sourceConservation, archiveMigrations })
1099
- : [];
1100
- const transaction = await prepareTransaction(root, command, version, outputs, mode, plan, sourceConservation, supersedesCurrentStateDigests, archiveMigrations);
1101
- try {
1053
+ try {
1102
1054
  transaction.journal.state = "committing";
1103
1055
  await writeSecureJson(transaction.journalPath, transaction.journal);
1104
1056
 
@@ -1231,11 +1183,147 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
1231
1183
  for (const conflict of rollback.conflicts) console.log(`blocked ${conflict}`);
1232
1184
  }
1233
1185
  throw error;
1234
- }
1235
- }
1236
-
1237
- async function detectInstalledCredentialFindings(root) {
1238
- const credentialInputs = [];
1186
+ }
1187
+ }
1188
+
1189
+ async function buildInstallTransactionPreflight(command, root, plan, version, options = {}) {
1190
+ const outputs = options.candidateOutputs ?? await buildTransactionOutputs(command, root, plan, version, {
1191
+ allowActiveTransaction: options.allowActiveTransaction === true
1192
+ });
1193
+ if (outputs.length === 0) {
1194
+ return Object.freeze({
1195
+ outputs,
1196
+ archiveMigrations: Object.freeze([]),
1197
+ sourceConservation: null,
1198
+ supersedesCurrentStateDigests: Object.freeze([]),
1199
+ identity: installTransactionPreflightIdentity({ command, version, outputs })
1200
+ });
1201
+ }
1202
+
1203
+ const credentialFindings = await detectInstalledCredentialFindings(root);
1204
+ if (credentialFindings.length > 0) {
1205
+ throw new Error(`existing governance contains ${credentialFindings.length} possible credential value(s); remove and rotate them before upgrade`);
1206
+ }
1207
+
1208
+ await validateTransactionOverlay(root, outputs);
1209
+ const archiveMigrations = command === "upgrade"
1210
+ ? await prepareArchiveCasingMigrations(root)
1211
+ : [];
1212
+ if (options.sourceConservationRebind === true) {
1213
+ for (const output of outputs) delete output.runtimeAcceptance;
1214
+ }
1215
+ const runtimeAcceptance = command === "upgrade" && options.sourceConservationRebind !== true ? resolveRuntimeAcceptance(outputs) : null;
1216
+ const sourceConservationAuthority = command === "upgrade"
1217
+ ? await hasCommittedSourceConservationAuthority(root)
1218
+ : false;
1219
+ const sourceConservation = command === "upgrade" && (
1220
+ runtimeAcceptance || sourceConservationAuthority
1221
+ )
1222
+ ? await createSourceConservation(root, outputs, archiveMigrations, {
1223
+ excludeInFlightTransactionId: options.excludeInFlightTransactionId ?? null
1224
+ })
1225
+ : null;
1226
+ const supersedesCurrentStateDigests = command === "upgrade"
1227
+ ? await findRestoredCurrentStateDigests(root, outputs, archiveMigrations, { sourceConservation, archiveMigrations })
1228
+ : [];
1229
+ const identity = installTransactionPreflightIdentity({
1230
+ command,
1231
+ version,
1232
+ outputs,
1233
+ archiveMigrations,
1234
+ sourceConservation,
1235
+ supersedesCurrentStateDigests,
1236
+ sourceConservationRebind: options.sourceConservationRebind === true
1237
+ });
1238
+ return Object.freeze({
1239
+ outputs,
1240
+ archiveMigrations: Object.freeze(archiveMigrations),
1241
+ sourceConservation,
1242
+ supersedesCurrentStateDigests: Object.freeze(supersedesCurrentStateDigests),
1243
+ identity
1244
+ });
1245
+ }
1246
+
1247
+ function installTransactionPreflightIdentity({ command, version, outputs = [], archiveMigrations = [], sourceConservation = null, supersedesCurrentStateDigests = [], sourceConservationRebind = false }) {
1248
+ const body = {
1249
+ schemaVersion: 1,
1250
+ command,
1251
+ version,
1252
+ sourceConservationRebind,
1253
+ outputs: outputs.map((output) => ({
1254
+ targetRel: output.targetRel,
1255
+ existed: Boolean(output.before),
1256
+ beforeHash: output.beforeHash,
1257
+ afterHash: output.afterHash,
1258
+ bytes: output.after.length,
1259
+ reason: output.reason ?? null
1260
+ })),
1261
+ archiveMigrations: archiveMigrations.map(archiveMigrationWitness),
1262
+ sourceConservation: normalizeSourceConservationForPreflightIdentity(sourceConservation),
1263
+ supersedesCurrentStateDigests
1264
+ };
1265
+ return sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8"));
1266
+ }
1267
+
1268
+ function normalizeSourceConservationForPreflightIdentity(sourceConservation) {
1269
+ if (!sourceConservation) return null;
1270
+ return {
1271
+ schemaVersion: sourceConservation.schemaVersion,
1272
+ entries: sourceConservation.entries
1273
+ };
1274
+ }
1275
+
1276
+ async function assertPreparedTransactionPreflightStillCurrent(root, transaction, expected, plan, options = {}) {
1277
+ let actual;
1278
+ try {
1279
+ actual = await buildInstallTransactionPreflight(
1280
+ transaction.journal.command,
1281
+ root,
1282
+ plan,
1283
+ transaction.journal.attemptedVersion,
1284
+ {
1285
+ allowActiveTransaction: true,
1286
+ sourceConservationRebind: options.sourceConservationRebind === true,
1287
+ excludeInFlightTransactionId: transaction.id
1288
+ }
1289
+ );
1290
+ } catch (error) {
1291
+ throw new Error(`transaction pre-replace preflight identity drifted under lock; no target replacement attempted: ${safeErrorLabel(error)}`);
1292
+ }
1293
+ if (actual.identity !== expected.identity) {
1294
+ throw new Error("transaction pre-replace preflight identity drifted under lock; no target replacement attempted");
1295
+ }
1296
+ }
1297
+
1298
+ async function abortPreparedTransactionBeforeTargetWrites(root, transaction, error) {
1299
+ if (transaction.journal.state !== "prepared" || transaction.journal.entries.some((entry) => entry.committed)
1300
+ || (transaction.journal.archiveMigrations ?? []).some((migration) => migration.state !== "prepared")) {
1301
+ throw new Error("pre-replace abort is only valid for a prepared transaction with no committed entries or archive relocation");
1302
+ }
1303
+ transaction.journal.state = "rolled-back";
1304
+ transaction.journal.error = safeErrorLabel(error);
1305
+ transaction.journal.rollbackAt = new Date().toISOString();
1306
+ transaction.journal.recoveryConflicts = [];
1307
+ await writeSecureJson(transaction.journalPath, transaction.journal);
1308
+ await unlinkIfExists(transaction.lockPath);
1309
+ console.log("⚠️ migration rolled back:lock-time preflight drifted before target replacement; no target bytes were replaced.");
1310
+ }
1311
+
1312
+ async function injectBeforeLockRevalidationDrift(root, journal) {
1313
+ const targetRel = process.env.AGENT_HANDOFF_KIT_QA_MUTATE_BEFORE_LOCK_REVALIDATION;
1314
+ if (!targetRel) return;
1315
+ const encoded = process.env.AGENT_HANDOFF_KIT_QA_MUTATE_BEFORE_LOCK_REVALIDATION_BASE64;
1316
+ if (!encoded) throw new Error("QA before-lock-revalidation drift payload is missing");
1317
+ if (!journal.entries.some((entry) => entry.targetRel === targetRel)) {
1318
+ throw new Error(`QA before-lock-revalidation target is not part of this transaction: ${targetRel}`);
1319
+ }
1320
+ const targetAbs = path.resolve(root, targetRel);
1321
+ if (!isInside(root, targetAbs)) throw new Error("QA before-lock-revalidation target escaped root");
1322
+ await writeFile(targetAbs, Buffer.from(encoded, "base64"), { mode: 0o600 });
1323
+ }
1324
+
1325
+ async function detectInstalledCredentialFindings(root) {
1326
+ const credentialInputs = [];
1239
1327
  for (const relative of requiredTargets) {
1240
1328
  const buffer = await readOptionalBuffer(path.join(root, relative));
1241
1329
  if (buffer) credentialInputs.push({ relative, text: decodeUtf8(buffer, relative).text });
@@ -1243,19 +1331,39 @@ async function detectInstalledCredentialFindings(root) {
1243
1331
  return detectCredentialValues(credentialInputs);
1244
1332
  }
1245
1333
 
1246
- async function buildTransactionOutputs(command, root, plan, version) {
1334
+ async function buildTransactionOutputs(command, root, plan, version, options = {}) {
1247
1335
  const byTarget = new Map();
1248
1336
  for (const item of plan) {
1249
1337
  if (item.action !== "create" && item.action !== "merge" && item.action !== "preserve") continue;
1250
1338
  const before = await readOptionalBuffer(item.targetAbs);
1251
1339
  let afterText = null;
1252
1340
  let after = null;
1341
+ let projectIndexVersionMetadataMerge = false;
1253
1342
  if (item.action === "preserve") {
1254
1343
  if (!before) throw new Error(`${item.targetRel}: preserved transaction item disappeared before preparation`);
1255
- after = Buffer.from(before);
1344
+ if (command === "upgrade" && item.targetRel === "dev/PROJECT_INDEX.md") {
1345
+ const originalText = decodeUtf8(before, item.targetRel).text;
1346
+ const materializedText = materializeProjectIndexTemplateVersion(originalText, version);
1347
+ if (materializedText !== originalText) {
1348
+ after = Buffer.from(materializedText, "utf8");
1349
+ projectIndexVersionMetadataMerge = true;
1350
+ }
1351
+ else after = Buffer.from(before);
1352
+ } else {
1353
+ after = Buffer.from(before);
1354
+ }
1256
1355
  } else if (item.action === "create") {
1257
1356
  const sourceText = await readTemplateSource(command, item.sourceRel, item.targetRel, item.sourceAbs);
1258
1357
  afterText = item.targetRel === "AGENTS.md" ? mergeManagedBlock("", sourceText) : sourceText;
1358
+ } else if (item.action === "merge" && item.targetRel === "dev/PROJECT_INDEX.md" && item.metadataTransition === projectIndexTemplateVersionMetadataTransition) {
1359
+ if (!before) throw new Error(`${item.targetRel}: template-version metadata transition disappeared before preparation`);
1360
+ const originalText = decodeUtf8(before, item.targetRel).text;
1361
+ const materializedText = materializeProjectIndexTemplateVersion(originalText, version);
1362
+ if (materializedText !== originalText) {
1363
+ after = Buffer.from(materializedText, "utf8");
1364
+ projectIndexVersionMetadataMerge = true;
1365
+ }
1366
+ else after = Buffer.from(before);
1259
1367
  } else {
1260
1368
  afterText = item.mergedText;
1261
1369
  after = item.mergedBytes ? Buffer.from(item.mergedBytes) : null;
@@ -1267,17 +1375,17 @@ async function buildTransactionOutputs(command, root, plan, version) {
1267
1375
  const userRulesEntry = await readFile(path.join(packageRoot, "runtime-core", "USER_RULES_ENTRY.md"), "utf8");
1268
1376
  afterText = `${afterText.trimEnd()}\n\n${userRulesEntry.trim()}\n`;
1269
1377
  }
1270
- if (afterText != null) afterText = afterText.replaceAll("<absolute project root>", root);
1378
+ if (afterText != null && !projectIndexVersionMetadataMerge) afterText = afterText.replaceAll("<absolute project root>", root);
1271
1379
  byTarget.set(item.targetRel, {
1272
1380
  targetRel: item.targetRel,
1273
1381
  targetAbs: item.targetAbs,
1274
1382
  before,
1275
1383
  after,
1276
1384
  afterText,
1277
- ...(item.action === "preserve" ? { forceTransaction: true } : {}),
1278
- ...(item.action === "preserve" ? { preservedRuntimeItem: item.preservedRuntimeItem } : {}),
1385
+ ...(item.action === "preserve" && !projectIndexVersionMetadataMerge ? { forceTransaction: true } : {}),
1386
+ ...(item.action === "preserve" && !projectIndexVersionMetadataMerge ? { preservedRuntimeItem: item.preservedRuntimeItem } : {}),
1279
1387
  ...(item.managedSegmentRuntimeItem ? { managedSegmentRuntimeItem: item.managedSegmentRuntimeItem } : {}),
1280
- reason: item.reason ?? item.action
1388
+ reason: projectIndexVersionMetadataMerge ? projectIndexTemplateVersionMetadataReason : item.reason ?? item.action
1281
1389
  });
1282
1390
  }
1283
1391
 
@@ -1287,12 +1395,17 @@ async function buildTransactionOutputs(command, root, plan, version) {
1287
1395
  if (!indexOutput && (command === "upgrade" || await exists(indexAbs))) {
1288
1396
  const before = await readOptionalBuffer(indexAbs);
1289
1397
  if (before) indexOutput = { targetRel: indexRel, targetAbs: indexAbs, before, afterText: decodeUtf8(before, indexRel).text, reason: "template version metadata" };
1290
- }
1398
+ }
1291
1399
  if (indexOutput?.afterText != null) {
1292
- const updated = indexOutput.afterText.replace(/\| Agent Handoff Kit template version \| [\d.]+ \|/, `| Agent Handoff Kit template version | ${version} |`);
1293
- indexOutput.afterText = updated;
1294
- byTarget.set(indexRel, indexOutput);
1295
- }
1400
+ const materializedText = materializeProjectIndexTemplateVersion(indexOutput.afterText, version);
1401
+ if (materializedText !== indexOutput.afterText) {
1402
+ indexOutput.after = Buffer.from(materializedText, "utf8");
1403
+ indexOutput.afterText = null;
1404
+ } else {
1405
+ indexOutput.afterText = materializedText;
1406
+ }
1407
+ byTarget.set(indexRel, indexOutput);
1408
+ }
1296
1409
 
1297
1410
  const handoffRel = "dev/SESSION_HANDOFF.md";
1298
1411
  const promptRel = "START_NEXT_SESSION_PROMPT.txt";
@@ -1323,7 +1436,9 @@ async function buildTransactionOutputs(command, root, plan, version) {
1323
1436
  }
1324
1437
  }
1325
1438
 
1326
- await synchronizeFormalUserRulesTransactionState(command, root, byTarget, version);
1439
+ await synchronizeFormalUserRulesTransactionState(command, root, byTarget, version, {
1440
+ allowActiveTransaction: options.allowActiveTransaction === true
1441
+ });
1327
1442
 
1328
1443
  const outputs = [];
1329
1444
  for (const item of byTarget.values()) {
@@ -1342,9 +1457,22 @@ async function buildTransactionOutputs(command, root, plan, version) {
1342
1457
  }
1343
1458
 
1344
1459
  function reconcilePlanWithTransactionOutputs(plan, outputs) {
1345
- const outputTargets = new Set(outputs.map((item) => item.targetRel));
1460
+ const outputByTarget = new Map(outputs.map((item) => [item.targetRel, item]));
1346
1461
  for (const item of plan) {
1347
- if (!["create", "merge", "preserve"].includes(item.action) || outputTargets.has(item.targetRel)) continue;
1462
+ const output = outputByTarget.get(item.targetRel);
1463
+ if (
1464
+ item.action === "preserve"
1465
+ && item.targetRel === "dev/PROJECT_INDEX.md"
1466
+ && output?.reason === projectIndexTemplateVersionMetadataReason
1467
+ && output.beforeHash !== output.afterHash
1468
+ ) {
1469
+ item.action = "merge";
1470
+ item.reason = output.reason;
1471
+ item.metadataTransition = projectIndexTemplateVersionMetadataTransition;
1472
+ delete item.preservedRuntimeItem;
1473
+ continue;
1474
+ }
1475
+ if (!["create", "merge", "preserve"].includes(item.action) || output) continue;
1348
1476
  // Planning formal state transitions before rendering their canonical
1349
1477
  // acceptance is necessary for safety. Once the in-memory comparison proves
1350
1478
  // no bytes would change, do not present that transition as a write.
@@ -1353,7 +1481,7 @@ function reconcilePlanWithTransactionOutputs(plan, outputs) {
1353
1481
  }
1354
1482
  }
1355
1483
 
1356
- async function synchronizeFormalUserRulesTransactionState(command, root, byTarget, version) {
1484
+ async function synchronizeFormalUserRulesTransactionState(command, root, byTarget, version, options = {}) {
1357
1485
  const routerOutput = byTarget.get(USER_RULES_ROUTER_PATH);
1358
1486
  if (!routerOutput) return;
1359
1487
 
@@ -1362,7 +1490,7 @@ async function synchronizeFormalUserRulesTransactionState(command, root, byTarge
1362
1490
  // The old formal reader is the sole authority for whether a prior router
1363
1491
  // is eligible for transition. A path, title, or directory never grants
1364
1492
  // this authority.
1365
- prior = await readFormalUserRules({ root });
1493
+ prior = await readFormalUserRules({ root, allowActiveTransaction: options.allowActiveTransaction === true });
1366
1494
  }
1367
1495
 
1368
1496
  let agentOutput = byTarget.get("AGENTS.md");
@@ -1465,7 +1593,7 @@ async function prepareTransaction(root, command, version, outputs, mode, plan, s
1465
1593
  await writeFile(backupPath, output.before, { mode: 0o600 });
1466
1594
  backupRel = path.relative(root, backupPath);
1467
1595
  }
1468
- entries.push({ targetRel: output.targetRel, existed: Boolean(output.before), beforeHash: output.beforeHash, afterHash: output.afterHash, backupRel, committed: false });
1596
+ entries.push({ targetRel: output.targetRel, existed: Boolean(output.before), beforeHash: output.beforeHash, afterHash: output.afterHash, backupRel, committed: false, reason: output.reason ?? null });
1469
1597
  }
1470
1598
  const journal = {
1471
1599
  id,
@@ -2459,7 +2587,7 @@ async function writeTransactionReport(transaction) {
2459
2587
  "",
2460
2588
  "## Actions",
2461
2589
  "",
2462
- ...transaction.journal.entries.map((entry) => `- ${entry.existed ? "merge" : "create"}: ${entry.targetRel}; backup=${entry.backupRel ?? "none"}; committed=${entry.committed}`),
2590
+ ...transaction.journal.entries.map((entry) => `- ${entry.existed ? "merge" : "create"}: ${entry.targetRel}${entry.reason ? ` - ${entry.reason}` : ""}; backup=${entry.backupRel ?? "none"}; committed=${entry.committed}`),
2463
2591
  "",
2464
2592
  `- Planned skips: ${transaction.journal.plannedSkips ?? "unknown"}`,
2465
2593
  "- Conflicts: 0",
@@ -2872,24 +3000,7 @@ async function runDoctor(root, version, options = {}) {
2872
3000
  return "failed";
2873
3001
  }
2874
3002
 
2875
- const artifactResult = await checkGeneratedMarkdownGovernance(root);
2876
- console.log(`\ngenerated markdown governance checks: ${artifactResult.checked}`);
2877
- console.log(`${artifactResult.ok ? "ok" : "missing"} dev/PROJECT_INDEX.md (generated Markdown registration; other formats require human review)`);
2878
- if (!artifactResult.ok) {
2879
- for (const finding of artifactResult.findings) {
2880
- console.log(` missing: ${finding}`);
2881
- }
2882
- printDoctorSummary(version, root, "needs-fix", {
2883
- checked: rows.length + currentStateResult.checked + anchorRows.length + schemaRows.length + userRulesResult.checked + runtimeAcceptanceResult.checked + researchTraceResult.checked + temperatureResult.checked + artifactResult.checked,
2884
- failedKind: "generated markdown governance checks",
2885
- failedCount: artifactResult.findings.length,
2886
- nextStep: "把新生成或新修改的 Markdown 登記到 dev/PROJECT_INDEX.md,或在 SESSION_LOG / task summary 以同一紀錄精確標成 draft、temporary 或 one-time evidence;如內容重複,先合併到單一真源。其他持久格式須由 AI 另作人工治理核對。"
2887
- });
2888
- process.exitCode = 1;
2889
- return "failed";
2890
- }
2891
-
2892
- const mirrorRows = await checkPromptMirror(root);
3003
+ const mirrorRows = await checkPromptMirror(root);
2893
3004
  const mirrorBlockingFailures = mirrorRows.filter((row) => !row.ok && row.reason !== "convenience copy differs from dev/SESSION_HANDOFF.md");
2894
3005
  const mirrorWarnings = mirrorRows.filter((row) => !row.ok && row.reason === "convenience copy differs from dev/SESSION_HANDOFF.md");
2895
3006
  console.log(`\nprompt mirror checks: ${mirrorRows.length}`);
@@ -2961,7 +3072,7 @@ async function runDoctor(root, version, options = {}) {
2961
3072
  const overallHealthy = credentialResult.ok;
2962
3073
  if (overallHealthy && !options.silentCard) printCard(version, "doctor ready", "o.o");
2963
3074
  printDoctorSummary(version, root, overallHealthy ? "healthy" : "needs-attention", {
2964
- checked: rows.length + currentStateResult.checked + anchorRows.length + schemaRows.length + userRulesResult.checked + runtimeAcceptanceResult.checked + researchTraceResult.checked + temperatureResult.checked + artifactResult.checked + mirrorRows.length + 2,
3075
+ checked: rows.length + currentStateResult.checked + anchorRows.length + schemaRows.length + userRulesResult.checked + runtimeAcceptanceResult.checked + researchTraceResult.checked + temperatureResult.checked + mirrorRows.length + 2,
2965
3076
  failedKind: !credentialResult.ok ? "credential leak" : null,
2966
3077
  failedCount: !credentialResult.ok ? credentialResult.findings.length : 0,
2967
3078
  warningKind: mirrorWarnings.length > 0 ? "prompt mirror warning" : null,
@@ -3059,7 +3170,7 @@ function resolveRuntimeAcceptance(outputs) {
3059
3170
  return validateRuntimeAcceptance(witnesses[0]);
3060
3171
  }
3061
3172
 
3062
- async function createSourceConservation(root, outputs, archiveMigrations = []) {
3173
+ async function createSourceConservation(root, outputs, archiveMigrations = [], options = {}) {
3063
3174
  // `freezeGate5Set` is an existing read-only discovery witness. Reuse it
3064
3175
  // here rather than creating a registry, pointer, or component authority.
3065
3176
  // Its ordered source records become one component of the journal's existing
@@ -3068,10 +3179,20 @@ async function createSourceConservation(root, outputs, archiveMigrations = []) {
3068
3179
  assertGate5FrozenSet(frozen);
3069
3180
  const outputByTarget = new Map(outputs.map((item) => [item.targetRel, item]));
3070
3181
  const pathRebindings = archiveMigrations.map((migration) => ({
3182
+ originalRel: migration.originalRel,
3183
+ canonicalRel: migration.canonicalRel,
3071
3184
  sourcePrefix: `${migration.originalRel}/`,
3072
3185
  targetPrefix: `${migration.canonicalRel}/`
3073
3186
  }));
3074
- const entries = gate5SourceConservationItems(frozen).map((item) => {
3187
+ const excludedInFlightTransactionStatePath = options.excludeInFlightTransactionId
3188
+ ? `dev/governance_migrations/${options.excludeInFlightTransactionId}/transaction.json`
3189
+ : null;
3190
+ const sourceItems = gate5SourceConservationItems(frozen).filter((item) => {
3191
+ if (!excludedInFlightTransactionStatePath) return true;
3192
+ return !(item.sourcePath === excludedInFlightTransactionStatePath && item.classifications.includes("transaction-state"));
3193
+ });
3194
+ const entriesByPath = new Map();
3195
+ for (const item of sourceItems) {
3075
3196
  const output = outputByTarget.get(item.sourcePath) ?? null;
3076
3197
  const rebind = pathRebindings.find((candidate) => item.sourcePath.startsWith(candidate.sourcePrefix)) ?? null;
3077
3198
  const sourcePath = rebind
@@ -3092,7 +3213,7 @@ async function createSourceConservation(root, outputs, archiveMigrations = []) {
3092
3213
  : item.priorityConflict.status === "not-applicable-outside-known-kit-reachability"
3093
3214
  ? "outside-known-kit-reachability"
3094
3215
  : "unchanged-source";
3095
- return Object.freeze({
3216
+ const entry = Object.freeze({
3096
3217
  sourcePath,
3097
3218
  ...(rebind ? { sourceOriginPath: item.sourcePath } : {}),
3098
3219
  sourceWitness,
@@ -3106,7 +3227,19 @@ async function createSourceConservation(root, outputs, archiveMigrations = []) {
3106
3227
  effectDecision: item.effect.decision,
3107
3228
  classifications: Object.freeze([...item.classifications])
3108
3229
  });
3109
- });
3230
+ const record = { entry, sourceItemPath: item.sourcePath, rebind };
3231
+ const existing = entriesByPath.get(entry.sourcePath);
3232
+ if (!existing) {
3233
+ entriesByPath.set(entry.sourcePath, record);
3234
+ } else if (sourceConservationArchiveAliasCollisionMayCoalesce(existing, record)) {
3235
+ entriesByPath.set(entry.sourcePath, record.rebind ? record : existing);
3236
+ } else {
3237
+ throw new Error(`${entry.sourcePath}: source conservation rebind collision; no recovery writes attempted`);
3238
+ }
3239
+ }
3240
+ const entries = [...entriesByPath.values()]
3241
+ .map((record) => record.entry)
3242
+ .sort((left, right) => left.sourcePath.localeCompare(right.sourcePath));
3110
3243
  return Object.freeze({
3111
3244
  schemaVersion: archiveMigrations.length > 0 ? 2 : 1,
3112
3245
  frozenSetSha256: frozen.frozenSetSha256,
@@ -3114,6 +3247,42 @@ async function createSourceConservation(root, outputs, archiveMigrations = []) {
3114
3247
  });
3115
3248
  }
3116
3249
 
3250
+ function sourceConservationArchiveAliasCollisionMayCoalesce(left, right) {
3251
+ if (Boolean(left.rebind) === Boolean(right.rebind)) return false;
3252
+ const migrated = left.rebind ? left : right;
3253
+ const alias = left.rebind ? right : left;
3254
+ const suffix = migrated.sourceItemPath.slice(migrated.rebind.sourcePrefix.length);
3255
+ if (!suffix
3256
+ || migrated.sourceItemPath !== `${migrated.rebind.originalRel}/${suffix}`
3257
+ || migrated.entry.sourceOriginPath !== migrated.sourceItemPath
3258
+ || migrated.entry.sourcePath !== `${migrated.rebind.canonicalRel}/${suffix}`
3259
+ || alias.sourceItemPath !== migrated.entry.sourcePath
3260
+ || alias.entry.sourcePath !== migrated.entry.sourcePath
3261
+ || alias.entry.sourceOriginPath !== undefined
3262
+ || migrated.entry.disposition !== "canonical-path-migration"
3263
+ || alias.entry.disposition !== "unchanged-source") {
3264
+ return false;
3265
+ }
3266
+ return sameByteWitness(migrated.entry.sourceWitness, alias.entry.sourceWitness)
3267
+ && sameByteWitness(migrated.entry.accepted, alias.entry.accepted)
3268
+ && JSON.stringify(migrated.entry.sourceByteRanges) === JSON.stringify(alias.entry.sourceByteRanges)
3269
+ && JSON.stringify(migrated.entry.existingReaders) === JSON.stringify(alias.entry.existingReaders)
3270
+ && migrated.entry.priorityRelation === alias.entry.priorityRelation
3271
+ && migrated.entry.effectDecision === alias.entry.effectDecision
3272
+ && archiveAliasClassificationsMayCoalesce(migrated.entry.classifications, alias.entry.classifications);
3273
+ }
3274
+
3275
+ function archiveAliasClassificationsMayCoalesce(migrated, alias) {
3276
+ const migratedSet = new Set(migrated);
3277
+ const aliasSet = new Set(alias);
3278
+ return migratedSet.size === 2
3279
+ && aliasSet.size === 2
3280
+ && migratedSet.has("root-source")
3281
+ && migratedSet.has("legacy-session-log-archive")
3282
+ && aliasSet.has("root-source")
3283
+ && aliasSet.has("session-log-archive");
3284
+ }
3285
+
3117
3286
  function currentStateWitnessBody(journal) {
3118
3287
  const transaction = {
3119
3288
  id: journal.id,
@@ -3547,8 +3716,7 @@ async function directAgentsEntryWitness(root, bytes, outputByTarget = null) {
3547
3716
 
3548
3717
  function directFormalAgentReferences(text) {
3549
3718
  return extractExplicitLocalReferences(text).filter((reference) => (
3550
- reference.via === "markdown-link"
3551
- || (reference.via === "inline-code-path" && Boolean(installedFileContract(reference.path)))
3719
+ Boolean(installedFileContract(reference.path))
3552
3720
  ));
3553
3721
  }
3554
3722
 
@@ -3643,8 +3811,10 @@ async function directRulePacksEntryWitness(root, agentsBytes, routerBytes, outpu
3643
3811
  for (let index = headerIndexes[0] + 2; index < lines.length && lines[index].startsWith("|"); index += 1) {
3644
3812
  const cells = lines[index].split("|").slice(1, -1).map((cell) => cell.trim());
3645
3813
  if (cells.length !== 3) throw new Error("RULE_PACKS.md has an invalid active routing row");
3646
- const targets = [...cells[1].matchAll(/`([^`\r\n]+)`/g)].map((match) => match[1].trim()).filter(Boolean);
3647
- if (targets.length === 0) throw new Error("RULE_PACKS.md active routing row has no readable target");
3814
+ const targets = [...cells[1].matchAll(/`([^`\r\n]+)`/g)]
3815
+ .map((match) => match[1].trim())
3816
+ .filter((targetRel) => installedFileContract(targetRel)?.strategy === "rule-pack");
3817
+ if (targets.length === 0) continue;
3648
3818
  for (const targetRel of targets) {
3649
3819
  const bytes = outputByTarget?.get(targetRel)?.after ?? await readRuntimeAcceptanceBytes(root, targetRel);
3650
3820
  routes.push(Object.freeze({
@@ -3656,7 +3826,7 @@ async function directRulePacksEntryWitness(root, agentsBytes, routerBytes, outpu
3656
3826
  }));
3657
3827
  }
3658
3828
  }
3659
- if (routes.length === 0) throw new Error("RULE_PACKS.md active routing table has no readable targets");
3829
+ if (routes.length === 0) throw new Error("RULE_PACKS.md active routing table has no installed rule-pack contract targets");
3660
3830
  return Object.freeze({
3661
3831
  reader: "AGENTS.md",
3662
3832
  via: "direct-rule-packs-entry",
@@ -4008,7 +4178,7 @@ async function hasActiveTransactionLock(root) {
4008
4178
  }
4009
4179
  }
4010
4180
 
4011
- async function loadCommittedCurrentStateWitness(root) {
4181
+ async function loadCommittedCurrentStateWitness(root, options = {}) {
4012
4182
  const migrationsRoot = path.join(root, "dev", "governance_migrations");
4013
4183
  let names;
4014
4184
  try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") return null; throw error; }
@@ -4023,7 +4193,10 @@ async function loadCommittedCurrentStateWitness(root) {
4023
4193
  if (journal.state !== "committed" || !journal.currentStateWitness) continue;
4024
4194
  await validateRecoveryJournal(root, journal, journalPath);
4025
4195
  const witness = validateCurrentStateWitness(journal);
4026
- records.push({ journal, journalPath, witness, matches: await journalMatchesCurrentState(root, journal) });
4196
+ const matches = options.allowHistoricalEdgeRetirement === true
4197
+ ? await journalMatchesCurrentStateForHistoricalRebind(root, journal)
4198
+ : await journalMatchesCurrentState(root, journal);
4199
+ records.push({ journal, journalPath, witness, matches });
4027
4200
  } catch (error) {
4028
4201
  if (error?.code !== "ENOENT") throw error;
4029
4202
  }
@@ -4076,7 +4249,7 @@ async function hasCommittedSourceConservationAuthority(root) {
4076
4249
  const journal = JSON.parse(await readFile(journalPath, "utf8"));
4077
4250
  if (journal.state !== "committed" || !journal.currentStateWitness) continue;
4078
4251
  await validateRecoveryJournal(root, journal, journalPath);
4079
- records.push({ journal, journalPath, witness: validateCurrentStateWitness(journal), matches: await journalMatchesCurrentState(root, journal) });
4252
+ records.push({ journal, journalPath, witness: validateCurrentStateWitness(journal), matches: await journalMatchesCurrentStateForHistoricalRebind(root, journal) });
4080
4253
  } catch (error) {
4081
4254
  if (error?.code !== "ENOENT") throw error;
4082
4255
  }
@@ -4110,7 +4283,7 @@ async function assertUnboundCurrentStateMayAttemptUpgradeRebind(root, cause) {
4110
4283
  const journal = JSON.parse(await readFile(journalPath, "utf8"));
4111
4284
  if (journal.state !== "committed" || !journal.currentStateWitness) continue;
4112
4285
  await validateRecoveryJournal(root, journal, journalPath);
4113
- records.push({ journal, journalPath, witness: validateCurrentStateWitness(journal), matches: await journalMatchesCurrentState(root, journal) });
4286
+ records.push({ journal, journalPath, witness: validateCurrentStateWitness(journal), matches: await journalMatchesCurrentStateForHistoricalRebind(root, journal) });
4114
4287
  } catch (error) {
4115
4288
  if (error?.code !== "ENOENT") throw error;
4116
4289
  }
@@ -4126,12 +4299,10 @@ async function assertUnboundCurrentStateMayAttemptUpgradeRebind(root, cause) {
4126
4299
  }
4127
4300
 
4128
4301
  async function classifyCurrentStateRebindMismatches(projectRoot, journal) {
4129
- const mismatches = await currentStateMismatches(projectRoot, journal);
4302
+ const mismatches = await currentStateMismatches(projectRoot, journal, { allowHistoricalEdgeRetirement: true });
4130
4303
  const illegalNonCloseout = [];
4131
4304
  for (const mismatch of mismatches) {
4132
4305
  if (isCloseoutFinalizeTarget(mismatch.path)) continue;
4133
- if (mismatch.kind === "source-conservation"
4134
- && sourceConservationEntryMayRetireAsUnreachableRootSource(mismatch.sourceConservationEntry)) continue;
4135
4306
  if (await mismatchMatchesCurrentInstalledSource(projectRoot, mismatch)) continue;
4136
4307
  illegalNonCloseout.push(mismatch);
4137
4308
  }
@@ -4166,9 +4337,10 @@ async function findRestoredCurrentStateDigests(root, outputs, archiveMigrations
4166
4337
  allowArchiveState: sourceConservationHasArchiveReconciliation(priorWitness.sourceConservation)
4167
4338
  || sourceConservationHasArchiveReconciliation(replacement.sourceConservation)
4168
4339
  });
4169
- if ((await journalMatchesCurrentState(root, journal) && (!priorWitness.sourceConservation || sourceConservationRebind))
4340
+ if (sourceConservationRebind
4341
+ || (await journalMatchesCurrentState(root, journal) && (!priorWitness.sourceConservation || sourceConservationRebind))
4170
4342
  || await journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations, replacement.sourceConservation)
4171
- || sourceConservationRebind) {
4343
+ ) {
4172
4344
  if (!canSupersedeCurrentStateWitness(replacement, priorWitness)) continue;
4173
4345
  restored.push(journal.currentStateWitness.currentStateDigest);
4174
4346
  }
@@ -4204,16 +4376,49 @@ function sourceConservationHasArchiveReconciliation(sourceConservation) {
4204
4376
  return Boolean(sourceConservation?.entries?.some((entry) => entry.disposition === "session-log-archive-reconciliation"));
4205
4377
  }
4206
4378
 
4207
- function sourceConservationEntryMayRetireAsUnreachableRootSource(entry) {
4208
- return Boolean(entry
4209
- && Array.isArray(entry.classifications)
4210
- && entry.classifications.length === 1
4211
- && entry.classifications[0] === "root-source"
4212
- && entry.disposition === "outside-known-kit-reachability"
4213
- && Array.isArray(entry.existingReaders)
4214
- && entry.existingReaders.length === 0
4379
+ function canRetireHistoricalEdge(entry, currentTypedProtection = null) {
4380
+ if (!entry || currentTypedProtection) return false;
4381
+ if (!isSafeProjectRelative(entry.sourcePath)) return false;
4382
+ if (installedFileContract(entry.sourcePath)
4383
+ || directStatefulTargets.has(entry.sourcePath)
4384
+ || sourceConservationEntryIsTransactionRegistryJournal(entry)
4385
+ || sourceConservationEntryIsSessionLogArchive(entry)
4386
+ || isSessionLogArchivePath(entry.sourcePath)
4387
+ || entry.sourcePath === USER_RULES_ROUTER_PATH
4388
+ || isFormalUserRulesContentPath(entry.sourcePath)) {
4389
+ return false;
4390
+ }
4391
+ if (!Array.isArray(entry.classifications) || !entry.classifications.includes("root-source")) return false;
4392
+ if (entry.classifications.some((classification) => [
4393
+ "managed-contract",
4394
+ "legacy-session-log-archive",
4395
+ "session-log-archive",
4396
+ "formal-user-rules-router",
4397
+ "formal-user-rule-content"
4398
+ ].includes(classification))) {
4399
+ return false;
4400
+ }
4401
+ const outsideKnownKitReachability = entry.disposition === "outside-known-kit-reachability"
4215
4402
  && entry.priorityRelation === "outside-known-kit-reachability"
4216
- && entry.effectDecision === "outside-known-kit-reachability");
4403
+ && entry.effectDecision === "outside-known-kit-reachability"
4404
+ && Array.isArray(entry.existingReaders)
4405
+ && entry.existingReaders.length === 0;
4406
+ const genericFormalReference = entry.classifications.includes("formal-reference")
4407
+ && entry.effectDecision === "preserve-existing-route-or-stop"
4408
+ && Array.isArray(entry.existingReaders)
4409
+ && entry.existingReaders.length > 0;
4410
+ const nonRegistryTransactionArtifact = entry.classifications.includes("transaction-state")
4411
+ && entry.disposition === "retained-historical-state"
4412
+ && entry.priorityRelation === "no-verified-reader"
4413
+ && entry.effectDecision === "unresolved"
4414
+ && Array.isArray(entry.existingReaders)
4415
+ && entry.existingReaders.length === 0;
4416
+ return outsideKnownKitReachability || genericFormalReference || nonRegistryTransactionArtifact;
4417
+ }
4418
+
4419
+ function sourceConservationEntryIsTransactionRegistryJournal(entry) {
4420
+ return Boolean(entry
4421
+ && /^dev\/governance_migrations\/[^/]+\/transaction\.json$/u.test(entry.sourcePath));
4217
4422
  }
4218
4423
 
4219
4424
  function sourceConservationEntryAcceptedMatches(entry, accepted) {
@@ -4244,8 +4449,8 @@ function sourceConservationEntriesRebindPrior(priorWitness, replacementSourceCon
4244
4449
  || isSessionLogArchivePath(entry.sourcePath)
4245
4450
  || (entry.sourceOriginPath && isSessionLogArchivePath(entry.sourceOriginPath));
4246
4451
  if (archiveState && options.allowArchiveState !== true) return false;
4247
- if (sourceConservationEntryMayRetireAsUnreachableRootSource(entry)) return true;
4248
4452
  const replacement = replacementByPath.get(entry.sourcePath);
4453
+ if (canRetireHistoricalEdge(entry, replacement)) return true;
4249
4454
  if (sourceConservationEntryHasAcceptedCoverage(replacement)) return true;
4250
4455
  const reboundPath = archiveRebindings.get(entry.sourcePath);
4251
4456
  const rebound = reboundPath ? replacementByPath.get(reboundPath) : null;
@@ -4308,7 +4513,7 @@ async function journalIsRestoredByOutputs(root, journal, outputWitnesses, archiv
4308
4513
  continue;
4309
4514
  }
4310
4515
  if (sourceConservationEntryIsSessionLogArchive(entry) || isSessionLogArchivePath(entry.sourcePath)) return false;
4311
- if (!sourceConservationEntryMayRetireAsUnreachableRootSource(entry)) return false;
4516
+ if (canRetireHistoricalEdge(entry, sourceReplacement)) continue;
4312
4517
  const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
4313
4518
  if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) return false;
4314
4519
  }
@@ -4366,6 +4571,32 @@ async function journalMatchesCurrentState(root, journal) {
4366
4571
  return true;
4367
4572
  }
4368
4573
 
4574
+ async function journalMatchesCurrentStateForHistoricalRebind(root, journal) {
4575
+ const witness = validateCurrentStateWitness(journal);
4576
+ if (!witness.sourceConservation) return await journalMatchesCurrentState(root, journal);
4577
+ const currentFrozen = await freezeGate5Set({ root });
4578
+ assertGate5FrozenSet(currentFrozen);
4579
+ const currentTypedByPath = new Map(gate5SourceConservationItems(currentFrozen).map((item) => [item.sourcePath, item]));
4580
+ const plan = journal.entries.map((entry) => ({
4581
+ action: "merge",
4582
+ targetRel: entry.targetRel,
4583
+ targetAbs: path.join(root, entry.targetRel)
4584
+ }));
4585
+ await validateTransactionRoot(root, plan, { createMissingRoot: false });
4586
+ for (const entry of journal.entries) {
4587
+ const bytes = await readOptionalBuffer(path.join(root, entry.targetRel));
4588
+ if (!bytes || sha256(bytes) !== entry.afterHash) return false;
4589
+ }
4590
+ for (const entry of witness.sourceConservation?.entries ?? []) {
4591
+ if (canRetireHistoricalEdge(entry, currentTypedByPath.get(entry.sourcePath))) {
4592
+ continue;
4593
+ }
4594
+ const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
4595
+ if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) return false;
4596
+ }
4597
+ return true;
4598
+ }
4599
+
4369
4600
  async function findCloseoutFinalizeBase(root) {
4370
4601
  const migrationsRoot = path.join(root, "dev", "governance_migrations");
4371
4602
  let names;
@@ -4390,14 +4621,15 @@ async function findCloseoutFinalizeBase(root) {
4390
4621
  const records = [];
4391
4622
  for (const item of inspected) {
4392
4623
  const witness = validateCurrentStateWitness(item.journal);
4393
- const mismatches = await currentStateMismatches(root, item.journal);
4624
+ const isSuperseded = superseded.has(witness.currentStateDigest);
4625
+ const mismatches = await currentStateMismatches(root, item.journal, { allowHistoricalEdgeRetirement: isSuperseded });
4394
4626
  const closeoutOnly = mismatches.every((mismatch) => isCloseoutFinalizeTarget(mismatch.path));
4395
4627
  records.push({
4396
4628
  ...item,
4397
4629
  witness,
4398
4630
  mismatches,
4399
4631
  closeoutOnly,
4400
- isSuperseded: superseded.has(witness.currentStateDigest),
4632
+ isSuperseded,
4401
4633
  additionalSupersedes: []
4402
4634
  });
4403
4635
  }
@@ -4506,14 +4738,22 @@ function withAdditionalCloseoutSupersedes(base, current) {
4506
4738
  };
4507
4739
  }
4508
4740
 
4509
- async function currentStateMismatches(root, journal) {
4741
+ async function currentStateMismatches(root, journal, options = {}) {
4510
4742
  const witness = validateCurrentStateWitness(journal);
4511
4743
  const mismatches = new Map();
4744
+ let currentFrozen = null;
4745
+ let currentTypedByPath = null;
4746
+ if (witness.sourceConservation) {
4747
+ currentFrozen = await freezeGate5Set({ root });
4748
+ assertGate5FrozenSet(currentFrozen);
4749
+ currentTypedByPath = new Map(gate5SourceConservationItems(currentFrozen).map((item) => [item.sourcePath, item]));
4750
+ }
4512
4751
  for (const entry of journal.entries) {
4513
4752
  const bytes = await readOptionalBuffer(path.join(root, entry.targetRel));
4514
4753
  if (!bytes || sha256(bytes) !== entry.afterHash) mismatches.set(entry.targetRel, { path: entry.targetRel, kind: "transaction-entry" });
4515
4754
  }
4516
4755
  for (const entry of witness.sourceConservation?.entries ?? []) {
4756
+ if (options.allowHistoricalEdgeRetirement === true && canRetireHistoricalEdge(entry, currentTypedByPath.get(entry.sourcePath))) continue;
4517
4757
  const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
4518
4758
  if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) {
4519
4759
  mismatches.set(entry.sourcePath, { path: entry.sourcePath, kind: "source-conservation", sourceConservationEntry: entry });
@@ -4521,8 +4761,6 @@ async function currentStateMismatches(root, journal) {
4521
4761
  }
4522
4762
  if (witness.sourceConservation) {
4523
4763
  const conserved = new Set(witness.sourceConservation.entries.map((entry) => entry.sourcePath));
4524
- const currentFrozen = await freezeGate5Set({ root });
4525
- assertGate5FrozenSet(currentFrozen);
4526
4764
  for (const item of gate5SourceConservationItems(currentFrozen)) {
4527
4765
  if (conserved.has(item.sourcePath) || isFinalizeJournalState(item.sourcePath)) continue;
4528
4766
  mismatches.set(item.sourcePath, { path: item.sourcePath, kind: "new-source" });
@@ -4588,16 +4826,6 @@ async function classifyCurrentStateReconciliationMismatches(root, journal, curre
4588
4826
  }
4589
4827
  continue;
4590
4828
  }
4591
- if (mismatch.kind === "source-conservation"
4592
- && sourceConservationEntryMayReconcileAsUserOwnedFormal(mismatch.sourceConservationEntry, currentByPath.get(mismatch.path))) {
4593
- reconcilable.push({ ...mismatch, reason: "user-owned formal source readback" });
4594
- continue;
4595
- }
4596
- if (mismatch.kind === "new-source"
4597
- && gate5ItemMayReconcileAsUserOwnedFormal(currentByPath.get(mismatch.path))) {
4598
- reconcilable.push({ ...mismatch, reason: "new user-owned formal source readback" });
4599
- continue;
4600
- }
4601
4829
  illegal.push({ ...mismatch, reason: currentStateReconciliationBlockReason(mismatch, currentByPath.get(mismatch.path)) });
4602
4830
  }
4603
4831
  return {
@@ -4627,12 +4855,8 @@ async function qualifySessionLogArchive(root, currentFrozen) {
4627
4855
  const archiveReal = await realpath(archiveRoot);
4628
4856
  if (!isInside(rootReal, archiveReal)) return { ok: false, reason: "canonical session-log archive root resolves outside selected root", inventory: null };
4629
4857
  const route = gate5SourceConservationItems(currentFrozen).find((item) => item.sourcePath === "dev/SESSION_LOG.md");
4630
- if (!route
4631
- || sourceConservationEntryIsSessionLogArchive({ classifications: route.classifications })
4632
- || !Array.isArray(route.existingReaders)
4633
- || route.existingReaders.length === 0
4634
- || route.effect?.decision !== "preserve-existing-route-or-stop") {
4635
- return { ok: false, reason: "current non-archive SESSION_LOG formal route is not mechanically verifiable", inventory: null };
4858
+ if (!sessionLogCloseoutRouteIsTypedKitContract(route)) {
4859
+ return { ok: false, reason: "current non-archive SESSION_LOG closeout contract is not mechanically verifiable", inventory: null };
4636
4860
  }
4637
4861
  const inventory = await inventorySessionLogArchiveTree(root, archiveRoot, archiveReal);
4638
4862
  const index = inventory.files.find((file) => file.path === "INDEX.md");
@@ -4671,6 +4895,15 @@ async function qualifySessionLogArchive(root, currentFrozen) {
4671
4895
  };
4672
4896
  }
4673
4897
 
4898
+ function sessionLogCloseoutRouteIsTypedKitContract(route) {
4899
+ return Boolean(route
4900
+ && route.sourcePath === "dev/SESSION_LOG.md"
4901
+ && directCloseoutStateTargetSet.has(route.sourcePath)
4902
+ && route.packageContract?.targetRel === "dev/SESSION_LOG.md"
4903
+ && route.classifications?.includes("managed-contract")
4904
+ && !sourceConservationEntryIsSessionLogArchive({ classifications: route.classifications }));
4905
+ }
4906
+
4674
4907
  async function inventorySessionLogArchiveTree(root, archiveRoot, archiveReal) {
4675
4908
  const directories = [];
4676
4909
  const files = [];
@@ -4730,7 +4963,6 @@ async function createCurrentStateReconciliationVerifiedPlan(root, version, candi
4730
4963
  witness
4731
4964
  });
4732
4965
  }
4733
- const reconcilePaths = new Set(candidate.reconcilable.map((item) => item.path));
4734
4966
  const archiveReconcilePaths = new Set((candidate.archive ?? []).map((item) => item.path));
4735
4967
  const oldSourceByPath = new Map((activeWitness.sourceConservation?.entries ?? []).map((entry) => [entry.sourcePath, entry]));
4736
4968
  const sourceEntries = [];
@@ -4747,9 +4979,7 @@ async function createCurrentStateReconciliationVerifiedPlan(root, version, candi
4747
4979
  : "closeout-state-finalize"
4748
4980
  : archiveReconcilePaths.has(item.sourcePath)
4749
4981
  ? "session-log-archive-reconciliation"
4750
- : reconcilePaths.has(item.sourcePath)
4751
- ? "user-owned-reconciliation"
4752
- : entry?.disposition ?? (item.classifications.includes("transaction-state") ? "retained-historical-state" : "unchanged-source");
4982
+ : entry?.disposition ?? (item.classifications.includes("transaction-state") ? "retained-historical-state" : "unchanged-source");
4753
4983
  sourceEntries.push({
4754
4984
  sourcePath: item.sourcePath,
4755
4985
  ...(entry?.sourceOriginPath && ["canonical-path-migration", "canonical-path-migration-closeout", "session-log-archive-reconciliation"].includes(disposition) ? { sourceOriginPath: entry.sourceOriginPath } : {}),
@@ -4780,7 +5010,7 @@ async function createCurrentStateReconciliationVerifiedPlan(root, version, candi
4780
5010
  priorityRelation: currentItem?.priorityConflict?.relation ?? item.sourceConservationEntry?.priorityRelation ?? null,
4781
5011
  effectDecision: currentItem?.effect?.decision ?? item.sourceConservationEntry?.effectDecision ?? null,
4782
5012
  reason: item.reason,
4783
- authority: mismatchIsSessionLogArchiveDelta(item, currentItem) ? "session-log-archive-qualification" : "generic-formal-current-state-reconciliation",
5013
+ authority: mismatchIsSessionLogArchiveDelta(item, currentItem) ? "session-log-archive-qualification" : "legal-closeout-state-finalize",
4784
5014
  archiveQualification: mismatchIsSessionLogArchiveDelta(item, currentItem)
4785
5015
  ? {
4786
5016
  ok: candidate.archiveQualification.ok,
@@ -4865,40 +5095,7 @@ function currentStateReconciliationBlockReason(mismatch, currentItem) {
4865
5095
  if (currentItem?.classifications?.some((classification) => ["managed-contract", "transaction-state", "legacy-session-log-archive", "session-log-archive"].includes(classification))) {
4866
5096
  return "Kit-managed, transaction, or archive state remains fail-closed";
4867
5097
  }
4868
- return "not a user-owned formally reachable reconciliation entry";
4869
- }
4870
-
4871
- function sourceConservationEntryMayReconcileAsUserOwnedFormal(entry, currentItem) {
4872
- return Boolean(entry
4873
- && Array.isArray(entry.classifications)
4874
- && entry.classifications.includes("root-source")
4875
- && entry.classifications.includes("formal-reference")
4876
- && !entry.classifications.some((classification) => ["managed-contract", "transaction-state", "legacy-session-log-archive", "session-log-archive"].includes(classification))
4877
- && Array.isArray(entry.existingReaders)
4878
- && entry.existingReaders.length > 0
4879
- && entry.priorityRelation !== "outside-known-kit-reachability"
4880
- && entry.effectDecision === "preserve-existing-route-or-stop"
4881
- && gate5ItemMayReconcileAsUserOwnedFormal(currentItem));
4882
- }
4883
-
4884
- function gate5ItemMayReconcileAsUserOwnedFormal(item) {
4885
- // `user-or-unknown` is deliberately not treated as ownership proof. It is
4886
- // only the negative half of the authority test: the path is not an exact
4887
- // installed Kit contract. Reconciliation still requires a formal reader,
4888
- // preserve-or-stop effect, no managed/transaction/archive classification, and
4889
- // a fresh whole-file readback before any current-state authority changes.
4890
- return Boolean(item
4891
- && item.ownership === "user-or-unknown"
4892
- && Array.isArray(item.classifications)
4893
- && item.classifications.includes("root-source")
4894
- && item.classifications.includes("formal-reference")
4895
- && !item.classifications.some((classification) => ["managed-contract", "transaction-state", "legacy-session-log-archive", "session-log-archive"].includes(classification))
4896
- && Array.isArray(item.existingReaders)
4897
- && item.existingReaders.length > 0
4898
- && item.effect?.decision === "preserve-existing-route-or-stop"
4899
- && !installedFileContract(item.sourcePath)
4900
- && !isCloseoutFinalizeTarget(item.sourcePath)
4901
- && !isFinalizeJournalState(item.sourcePath));
5098
+ return "not a legal closeout or qualified session-log archive reconciliation entry";
4902
5099
  }
4903
5100
 
4904
5101
  async function writeCurrentStateReconciliationJournal(root, version, candidate, options = {}) {
@@ -5338,129 +5535,7 @@ async function checkResearchDecisionTrace(root) {
5338
5535
  return { ok: findings.length === 0, checked: 1, findings };
5339
5536
  }
5340
5537
 
5341
- async function checkGeneratedMarkdownGovernance(root) {
5342
- let indexText = "";
5343
- let logText = "";
5344
- let handoffText = "";
5345
- try {
5346
- indexText = await readFile(path.join(root, "dev/PROJECT_INDEX.md"), "utf8");
5347
- } catch {
5348
- return { ok: false, checked: 1, findings: ["dev/PROJECT_INDEX.md unreadable; cannot verify generated Markdown governance"] };
5349
- }
5350
- try {
5351
- logText = await readFile(path.join(root, "dev/SESSION_LOG.md"), "utf8");
5352
- } catch {
5353
- logText = "";
5354
- }
5355
- try {
5356
- handoffText = await readFile(path.join(root, "dev/SESSION_HANDOFF.md"), "utf8");
5357
- } catch {
5358
- handoffText = "";
5359
- }
5360
-
5361
- const markdownFiles = await listMarkdownFiles(root);
5362
- const findings = [];
5363
- for (const rel of markdownFiles) {
5364
- if (!isGeneratedArtifactCandidate(rel)) continue;
5365
- if (isArtifactGoverned(rel, { indexText, logText, handoffText })) continue;
5366
- findings.push(`${rel} is not registered in dev/PROJECT_INDEX.md and is not explicitly classified as draft / temporary / one-time evidence`);
5367
- }
5368
-
5369
- return { ok: findings.length === 0, checked: 1, findings };
5370
- }
5371
-
5372
- async function listMarkdownFiles(root) {
5373
- const results = [];
5374
- async function walk(dir) {
5375
- let entries = [];
5376
- try {
5377
- entries = await readdir(dir, { withFileTypes: true });
5378
- } catch {
5379
- return;
5380
- }
5381
- for (const entry of entries) {
5382
- if (entry.name === ".git" || entry.name === "node_modules") continue;
5383
- const full = path.join(dir, entry.name);
5384
- if (entry.isDirectory()) {
5385
- await walk(full);
5386
- continue;
5387
- }
5388
- if (!entry.isFile() || !entry.name.toLowerCase().endsWith(".md")) continue;
5389
- results.push(path.relative(root, full).split(path.sep).join("/"));
5390
- }
5391
- }
5392
- await walk(root);
5393
- return results.sort();
5394
- }
5395
-
5396
- function isGeneratedArtifactCandidate(rel) {
5397
- const normalized = rel.replaceAll("\\", "/");
5398
- const lower = normalized.toLowerCase();
5399
- const kitManaged = new Set([
5400
- "agents.md",
5401
- "claude.md",
5402
- "gemini.md",
5403
- "readme.md",
5404
- "dev/session_handoff.md",
5405
- "dev/session_log.md",
5406
- "dev/project_index.md",
5407
- "dev/doc_sync_registry.md",
5408
- "dev/rule_packs.md",
5409
- "dev/project_decisions.md"
5410
- ]);
5411
- if (kitManaged.has(lower)) return false;
5412
- if (lower.startsWith("dev/rules/")) return false;
5413
- if (lower.startsWith("dev/governance_migrations/")) return false;
5414
- if (lower.startsWith("dev/session_log_archive/")) return false;
5415
- if (lower.startsWith("docs/")) return true;
5416
- if (lower.startsWith("outputs/")) return true;
5417
- if (lower.startsWith("output/")) return true;
5418
- if (lower.startsWith("research/")) return true;
5419
- if (lower.startsWith("references/")) return true;
5420
- if (lower.startsWith("reference/")) return true;
5421
- if (lower.startsWith("runbooks/")) return true;
5422
- if (lower.startsWith("specs/")) return true;
5423
- if (lower.startsWith("requirements/")) return true;
5424
- return !normalized.includes("/");
5425
- }
5426
-
5427
- function isArtifactGoverned(rel, { indexText, logText, handoffText }) {
5428
- const normalized = rel.replaceAll("\\", "/");
5429
- if (projectIndexRegistersExactPath(indexText, normalized)) return true;
5430
- return textExplicitlyClassifiesExactArtifact(logText, normalized)
5431
- || textExplicitlyClassifiesExactArtifact(handoffText, normalized);
5432
- }
5433
-
5434
- function projectIndexRegistersExactPath(indexText, normalized) {
5435
- const active = stripMarkdownCommentsAndFences(indexText);
5436
- for (const line of active.split(/\r?\n/)) {
5437
- if (!line.trim().startsWith("|")) continue;
5438
- const cells = line.split("|").slice(1, -1);
5439
- for (const rawCell of cells) {
5440
- const cell = rawCell.trim().replace(/^`([^`]+)`$/, "$1");
5441
- if (cell === normalized) return true;
5442
- const link = /^\[[^\]]*\]\(([^)]+)\)$/.exec(cell);
5443
- if (link && link[1].replace(/^<|>$/g, "") === normalized) return true;
5444
- }
5445
- }
5446
- return false;
5447
- }
5448
-
5449
- function textExplicitlyClassifiesExactArtifact(text, normalized) {
5450
- const active = stripMarkdownCommentsAndFences(text);
5451
- const escaped = normalized.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5452
- const exactPath = new RegExp(`(?:^|[\\s\`|([<])${escaped}(?=$|[\\s\`|)\\]>.,;:])`, "i");
5453
- const label = /(draft|temporary|one-time evidence|non-authoritative|not source of truth|草稿|臨時|暫存|一次性|非真源|非權威)/i;
5454
- const markdownPath = /(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.md\b/gi;
5455
- for (const line of active.split(/\r?\n/)) {
5456
- if (!exactPath.test(line) || !label.test(line)) continue;
5457
- const paths = new Set((line.match(markdownPath) ?? []).map((item) => item.replaceAll("\\", "/").toLowerCase()));
5458
- if (paths.size === 1 && paths.has(normalized.toLowerCase())) return true;
5459
- }
5460
- return false;
5461
- }
5462
-
5463
- function stripFencedCodeBlocks(text) {
5538
+ function stripFencedCodeBlocks(text) {
5464
5539
  return text.replace(/```[\s\S]*?```/g, "");
5465
5540
  }
5466
5541
 
@@ -5685,7 +5760,7 @@ function printDoctorSummary(version, root, mode, details) {
5685
5760
  }
5686
5761
  } else {
5687
5762
  console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
5688
- 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 真源不同。"}`);
5763
+ console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : details.failedKind === "research decision trace checks" ? "研究導向決策缺少可追溯來源鏈。" : details.failedKind === "handoff temperature boundary checks" ? "當前交接內容混入一次性或歷史證據。" : "下次開工提示副本與 handoff 真源不同。"}`);
5689
5764
  }
5690
5765
  console.log("");
5691
5766
  console.log(`📦 版本:v${version}`);
@@ -6205,14 +6280,7 @@ function requiresHistoricalBaselineProof(context) {
6205
6280
  }
6206
6281
 
6207
6282
  async function readRootTemplateVersion(root) {
6208
- try {
6209
- const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
6210
- const text = await readFile(indexPath, "utf8");
6211
- const m = text.match(/\| Agent Handoff Kit template version \| ([\d.]+) \|/);
6212
- return m?.[1] ?? null;
6213
- } catch {
6214
- return null;
6215
- }
6283
+ return await readProjectIndexTemplateVersion(root);
6216
6284
  }
6217
6285
 
6218
6286
  function findArtifactBoundManagedCoreSegment(bytes, artifactSegment) {
@@ -6377,6 +6445,15 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
6377
6445
  catalog: context.officialCatalog
6378
6446
  });
6379
6447
  if (baselineRecord?.state === "present") {
6448
+ const projectIndexGovernanceCurrent = targetRel === "dev/PROJECT_INDEX.md"
6449
+ ? mergeProjectIndexGovernanceSections(targetText, sourceText) === targetText
6450
+ : true;
6451
+ if (targetRel === "dev/PROJECT_INDEX.md" && !projectIndexGovernanceCurrent) {
6452
+ // PROJECT_INDEX metadata-only transition is safe only after the
6453
+ // existing governance section owner says the structure is current.
6454
+ // Older exact or CRLF-only indexes that still need section migration
6455
+ // must continue to the normal PROJECT_INDEX merge/replacement path.
6456
+ } else {
6380
6457
  return {
6381
6458
  ...base,
6382
6459
  action: "preserve",
@@ -6391,6 +6468,7 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
6391
6468
  ? "dev/SESSION_LOG.md is not exact official package content; preserve its complete original bytes and AGENTS direct formal reader in the same transaction acceptance/readback"
6392
6469
  : `${targetRel} has no exact historical raw-byte identity after root/version initialization; preserve its complete original bytes and direct formal reader/effect in the same transaction acceptance/readback`
6393
6470
  };
6471
+ }
6394
6472
  }
6395
6473
  }
6396
6474
  if (command === "upgrade" && directStatefulTargets.has(targetRel) && isUncatalogedHistoricalBaseline(context)) {
@@ -6407,11 +6485,30 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
6407
6485
  reason: `${targetRel} is non-exact historical state with no catalog raw-byte identity; root metadata is not replacement authority, so preserve complete bytes and direct formal reader/effect in the same transaction acceptance/readback`
6408
6486
  };
6409
6487
  }
6488
+ if (targetRel === "dev/PROJECT_INDEX.md" && command === "upgrade") {
6489
+ const mergedProjectIndex = mergeProjectIndexGovernanceSections(targetText, sourceText);
6490
+ if (!mergedProjectIndex) {
6491
+ return {
6492
+ ...base,
6493
+ action: "conflict",
6494
+ reason: "PROJECT_INDEX.md must contain unique real H2 governance sections in the expected order; inline or fenced lookalikes are not sections"
6495
+ };
6496
+ }
6497
+ if (mergedProjectIndex !== targetText) {
6498
+ return {
6499
+ ...base,
6500
+ action: "merge",
6501
+ reason: "insert the missing Installed Integrations and Tool Operation References H2 sections while preserving all existing project content",
6502
+ mergedText: mergedProjectIndex
6503
+ };
6504
+ }
6505
+ return { ...base, action: "skip", reason: "PROJECT_INDEX.md governance sections current and structurally unique" };
6506
+ }
6410
6507
  const officialOrigin = command === "upgrade" ? trustedOfficialOrigin(targetRel, context) : null;
6411
- if (officialOrigin) {
6412
- return {
6413
- ...base,
6414
- action: "merge",
6508
+ if (officialOrigin) {
6509
+ return {
6510
+ ...base,
6511
+ action: "merge",
6415
6512
  reason: `replace raw-exact official historical ${targetRel} with the current Kit file`,
6416
6513
  mergedText: sourceText
6417
6514
  };
@@ -6468,26 +6565,7 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
6468
6565
  }
6469
6566
  return { ...base, action: "skip", reason: "official marked routes current; local rows preserved" };
6470
6567
  }
6471
- if (targetRel === "dev/PROJECT_INDEX.md" && command === "upgrade") {
6472
- const mergedProjectIndex = mergeProjectIndexGovernanceSections(targetText, sourceText);
6473
- if (!mergedProjectIndex) {
6474
- return {
6475
- ...base,
6476
- action: "conflict",
6477
- reason: "PROJECT_INDEX.md must contain unique real H2 governance sections in the expected order; inline or fenced lookalikes are not sections"
6478
- };
6479
- }
6480
- if (mergedProjectIndex !== targetText) {
6481
- return {
6482
- ...base,
6483
- action: "merge",
6484
- reason: "insert or normalize the unique Installed Integrations and Tool Operation References H2 sections while preserving all existing project content",
6485
- mergedText: mergedProjectIndex
6486
- };
6487
- }
6488
- return { ...base, action: "skip", reason: "PROJECT_INDEX.md governance sections current and structurally unique" };
6489
- }
6490
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
6568
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
6491
6569
  const migratedHandoff = migrateSessionHandoff(targetText, sourceText, context);
6492
6570
  if (!migratedHandoff) {
6493
6571
  return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md lacks unique trusted state/opening boundaries; migration stopped without replacing project state" };
@@ -6873,7 +6951,7 @@ function handoffContinuityAnchorPlacement(snippet, text) {
6873
6951
  }
6874
6952
 
6875
6953
  function projectIndexAnchorPlacement(snippet, text) {
6876
- if (snippet === "Agent Handoff Kit template version") return Boolean(projectIndexTemplateVersion(text));
6954
+ if (snippet === "Agent Handoff Kit template version") return Boolean(parseProjectIndexTemplateVersion(text));
6877
6955
  return true;
6878
6956
  }
6879
6957
 
@@ -7055,10 +7133,10 @@ function mergeProjectDecisionsPreamble(targetText, sourceText, missing) {
7055
7133
  return insertSourcePreambleBeforeHeading(targetText, sourceText, "## Evolution Timeline");
7056
7134
  }
7057
7135
 
7058
- function mergeProjectIndexTemplateVersionRow(targetText, sourceText) {
7059
- if (projectIndexTemplateVersion(targetText)) return targetText;
7060
- const sourceRow = sourceText.match(/^\| Agent Handoff Kit template version \| [\d.]+ \| [^|\n]+ \|$/m)?.[0];
7061
- if (!sourceRow) return null;
7136
+ function mergeProjectIndexTemplateVersionRow(targetText, sourceText) {
7137
+ if (parseProjectIndexTemplateVersion(targetText)) return targetText;
7138
+ const sourceRow = projectIndexTemplateVersionRow(sourceText);
7139
+ if (!sourceRow) return null;
7062
7140
  const lines = targetText.split(/\r?\n/);
7063
7141
  const stackIndex = lines.findIndex((line) => line.trim() === "## Stack");
7064
7142
  if (stackIndex < 0) return null;
@@ -7097,44 +7175,16 @@ function mergeCommunicationNextStepDiscipline(targetText, sourceText, missing) {
7097
7175
  return merged === targetText ? null : merged;
7098
7176
  }
7099
7177
 
7100
- function parseMarkdownH2Sections(text) {
7101
- const sections = [];
7102
- const linePattern = /.*(?:\r?\n|$)/g;
7103
- let fenced = false;
7104
- let fenceDelimiter = null;
7105
- let inComment = false;
7106
- let match;
7107
- while ((match = linePattern.exec(text)) && match[0] !== "") {
7108
- const raw = match[0];
7109
- const line = raw.replace(/\r?\n$/, "");
7110
- const trimmed = line.trim();
7111
- if (inComment) {
7112
- if (trimmed.includes("-->")) inComment = false;
7113
- continue;
7114
- }
7115
- if (trimmed.startsWith("<!--")) {
7116
- if (!trimmed.includes("-->")) inComment = true;
7117
- continue;
7118
- }
7119
- const fence = trimmed.match(/^(`{3,}|~{3,})/);
7120
- if (fence) {
7121
- if (!fenced) {
7122
- fenced = true;
7123
- fenceDelimiter = fence[1][0];
7124
- } else if (fence[1][0] === fenceDelimiter) {
7125
- fenced = false;
7126
- fenceDelimiter = null;
7127
- }
7128
- continue;
7129
- }
7130
- if (fenced) continue;
7131
- const headingMatch = line.match(/^## ([^#].*?)\s*$/);
7132
- if (headingMatch) sections.push({ title: headingMatch[1], start: match.index, end: text.length });
7133
- }
7134
- for (let index = 0; index < sections.length - 1; index += 1) {
7135
- sections[index].end = sections[index + 1].start;
7136
- }
7137
- return sections;
7178
+ function parseMarkdownH2Sections(text) {
7179
+ const sections = [];
7180
+ for (const line of markdownVisibleLinesOutsideHiddenBlocks(text)) {
7181
+ const headingMatch = /^## ([^#].*?)\s*$/u.exec(line.text);
7182
+ if (headingMatch) sections.push({ title: headingMatch[1], start: line.start, end: String(text).length });
7183
+ }
7184
+ for (let index = 0; index < sections.length - 1; index += 1) {
7185
+ sections[index].end = sections[index + 1].start;
7186
+ }
7187
+ return sections;
7138
7188
  }
7139
7189
 
7140
7190
  function uniqueSessionLogEntryTemplateSection(text) {
@@ -7296,100 +7346,30 @@ function mergeProjectIndexGovernanceSections(targetText, sourceText) {
7296
7346
  if ((installed && installed.start > localQc.start) || (toolRefs && toolRefs.start > localQc.start)) return null;
7297
7347
  if (installed && toolRefs && installed.start > toolRefs.start) return null;
7298
7348
 
7299
- const missing = requiredTitles.slice(0, 2).filter((title) => targetByTitle.get(title).length === 0);
7300
- let merged = targetText;
7301
- if (missing.length > 0) {
7302
- const insertion = missing
7303
- .map((title) => sourceText.slice(sourceByTitle.get(title)[0].start, sourceByTitle.get(title)[0].end).trimEnd())
7304
- .join("\n\n");
7305
- merged = `${targetText.slice(0, localQc.start).trimEnd()}\n\n${insertion}\n\n${targetText.slice(localQc.start)}`;
7306
- }
7307
- merged = mergeProjectIndexCredentialReferences(merged);
7308
- return projectIndexGovernanceSectionsAreValid(merged) ? merged : null;
7309
- }
7310
-
7311
- function mergeProjectIndexCredentialReferences(targetText) {
7312
- return targetText
7313
- .replace(
7314
- /`via` column 紀律:每行 External Sources 必引用 `## Installed Integrations`[^\r\n]*/,
7315
- "`via` column discipline: every External Sources row must reference an entry name under `## Installed Integrations`, such as `Notion Connector` or `Google Drive Connector`, so the access path is explicit. Sources without a declared integration use `manual paste`. Doctor and release QA enforce cross-section consistency."
7316
- )
7317
- .replace(
7318
- /⚠️ \*\*機密分離原則\*\*:本 section 只記錄[^\r\n]*/,
7319
- "**Credential Separation Principle**: this section records only project usage and public reference coordinates such as Notion database names, URLs, or folder paths. It must never record API keys, OAuth tokens, or credential values. Credentials belong in AI runtime secure storage, OS credential stores, tool configuration, or user-managed secret stores. If an environment variable is used, record only the variable name, never the value. Before writing this section, self-check that no credential value is being persisted. Doctor scans this section, `SESSION_HANDOFF`, and `SESSION_LOG` for common credential prefixes such as `sk-`, `ntn_`, `ya29.`, `xoxp-`, `ghp_`, `sl.`, `AKIA`, and `AIza`."
7320
- )
7321
- .replace(
7322
- /用途:新 AI session 開工讀本 section 知道[^\r\n]*/,
7323
- "Purpose: a new AI session reads this section to understand declared external-tool capabilities and their project roles. Declarations persist across sessions. Every entry must include `Declared` and `Last Verified` fields so stale capability assumptions can be detected."
7324
- )
7325
- .replace("### Connectors(Anthropic 官方 vetted)", "### Connectors")
7326
- .replace("### MCPs(community / custom)", "### MCPs")
7327
- .replace("### Plugins(Claude Code plugin bundle)", "### Plugins")
7328
- .replace("### Skills(SKILL.md instruction set)", "### Skills")
7329
- .replace("### Source-of-truth Architecture(多層持久化組合)", "### Source-of-truth Architecture")
7330
- .replace(
7331
- /當項目用多個整合構成 source-of-truth 架構[^\r\n]*/,
7332
- "When a project uses several integrations as a source-of-truth system, for example Notion index + local primary sources + Google Drive reference mirror, this table records each layer's role so agents do not cross write boundaries."
7333
- )
7334
- .replace(
7335
- "| TBD | TBD(譬如 DB Index 記真源 path / 持久化參考檔儲存) | read / read+write | TBD(譬如 DB 名 + URL / folder path) | TBD(譬如 `AI tool secure storage` / `OS credential store`) | TBD | TBD |",
7336
- "| TBD | TBD, for example an index of source paths or persistent reference storage | read / read+write | TBD, for example database name + URL or folder path | TBD, for example `AI tool secure storage` / `OS credential store` | TBD | TBD |"
7337
- )
7338
- .replace(
7339
- "| TBD | TBD(譬如 GitHub repo URL) | TBD | TBD(譬如 `tool config + env var name only` / `user-managed secret store`) | TBD | TBD |",
7340
- "| TBD | TBD, for example GitHub repository URL | TBD | TBD, for example `tool config + env var name only` / `user-managed secret store` | TBD | TBD |"
7341
- )
7342
- .replace(
7343
- "| TBD | TBD(譬如 plugin bundle / user-level install) | TBD | TBD |",
7344
- "| TBD | TBD, for example plugin bundle or user-level install | TBD | TBD |"
7345
- )
7346
- .replace(
7347
- "| 真源(source of truth) | TBD(譬如 本機 `~/project/reference/`) | 原始可審計 reference 內容 | 用戶手動置入;AI 不直接寫入 |",
7348
- "| Source of truth | TBD, for example local `~/project/reference/` | Original auditable reference content | User-controlled placement; agent does not write directly unless explicitly authorized |"
7349
- )
7350
- .replace(
7351
- "| Index | TBD(譬如 Notion DB「Project Index」) | 登記每份真源檔 metadata + 摘要 + tag | AI 經 Connector 直接讀寫 |",
7352
- "| Index | TBD, for example Notion database `Project Index` | Metadata, summaries, and tags for each source file | Agent may read/write through a verified Connector |"
7353
- )
7354
- .replace(
7355
- "| 持久化參考檔(mirror) | TBD(譬如 Drive folder「Project Reference/」) | 防本機 disk failure / 跨裝置 access | 用戶手動同步;AI 唔自動 push |",
7356
- "| Persistent mirror | TBD, for example Drive folder `Project Reference/` | Backup or cross-device reference mirror | User-controlled sync by default; agent does not push automatically |"
7357
- )
7358
- .replace(
7359
- "| Working draft | TBD(譬如 本機 `~/project/output/`) | AI 寫 task output | AI 直接 read + write 本機 |",
7360
- "| Working draft | TBD, for example local `~/project/output/` | Agent task output | Agent may read and write local files under normal safety rules |"
7361
- )
7362
- .replace(
7363
- "Credential 應由 AI 工具自身 secure storage 管理(譬如 Claude Desktop Extensions 嘅 OS Keychain / Claude Code MCP config)。",
7364
- "Credential 應由 AI 工具自身 secure storage / OS credential store / tool config / user-managed secret store 管理;若使用 env,只可記錄 env var name,不可讀取、貼出或保存 value。"
7365
- )
7366
- .replaceAll(
7367
- "Credential Location",
7368
- "Credential Reference(no value)"
7369
- )
7370
- .replaceAll(
7371
- "Credential Reference(no value)",
7372
- "Credential Reference (no value)"
7373
- )
7374
- .replaceAll(
7375
- "Bundle Content(Skills + MCP + hooks)",
7376
- "Bundle Content (Skills + MCP + hooks)"
7377
- )
7378
- .replaceAll(
7379
- "Surface(具體 instance)",
7380
- "Surface (specific instance)"
7381
- )
7382
- .replace(
7383
- "`Claude Desktop Extensions`",
7384
- "`AI tool secure storage` / `OS credential store`"
7385
- )
7386
- .replace(
7387
- "`Claude Code MCP config + env var`",
7388
- "`tool config + env var name only` / `user-managed secret store`"
7389
- );
7390
- }
7391
-
7392
- function mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing) {
7349
+ const missing = requiredTitles.slice(0, 2).filter((title) => targetByTitle.get(title).length === 0);
7350
+ let merged = targetText;
7351
+ if (missing.length > 0) {
7352
+ const newline = targetText.includes("\r\n") ? "\r\n" : "\n";
7353
+ const insertion = missing
7354
+ .map((title) => sourceText
7355
+ .slice(sourceByTitle.get(title)[0].start, sourceByTitle.get(title)[0].end)
7356
+ .replace(/\r\n|\r|\n/g, newline)
7357
+ .trimEnd())
7358
+ .join(`${newline}${newline}`);
7359
+ const prefix = targetText.slice(0, localQc.start);
7360
+ const hasExistingBlankLineBeforeInsertion = /(?:\r\n|\r|\n)(?:[ \t]*(?:\r\n|\r|\n))+$/u.test(prefix);
7361
+ const hasExistingLineBreakBeforeInsertion = /(?:\r\n|\r|\n)$/u.test(prefix);
7362
+ const beforeInsertion = hasExistingBlankLineBeforeInsertion
7363
+ ? ""
7364
+ : hasExistingLineBreakBeforeInsertion
7365
+ ? newline
7366
+ : `${newline}${newline}`;
7367
+ merged = `${prefix}${beforeInsertion}${insertion}${newline}${newline}${targetText.slice(localQc.start)}`;
7368
+ }
7369
+ return projectIndexGovernanceSectionsAreValid(merged) ? merged : null;
7370
+ }
7371
+
7372
+ function mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing) {
7393
7373
  if (!hasTrustedSafetyPackShape(targetText)) return null;
7394
7374
  const targetBounds = sectionBounds(targetText, "## Rules", "## Checks");
7395
7375
  const sourceBounds = sectionBounds(sourceText, "## Rules", "## Checks");
@@ -7634,15 +7614,7 @@ function textSectionBounds(text, startHeading, endHeading) {
7634
7614
  return { start: startIndex, end: endIndex };
7635
7615
  }
7636
7616
 
7637
- function projectIndexTemplateVersion(text) {
7638
- const bounds = textSectionBounds(text, "## Stack", "## Directory Map");
7639
- if (!bounds) return null;
7640
- const stack = text.slice(bounds.start, bounds.end);
7641
- const row = stack.match(/^\| Agent Handoff Kit template version \| ([\d.]+) \| [^|\n]+ \|$/m);
7642
- return row ? row[1] : null;
7643
- }
7644
-
7645
- function migrateSessionHandoff(targetText, sourceText, context = {}) {
7617
+ function migrateSessionHandoff(targetText, sourceText, context = {}) {
7646
7618
  if (countText(targetText, "## Next Session Opening Message") !== 1) return null;
7647
7619
  let merged = mergeLegacyFirstStartupGuidance(targetText, sourceText) ?? targetText;
7648
7620
 
@@ -7991,7 +7963,7 @@ async function assessVersionAlignment(root, cliVersion, options = {}) {
7991
7963
  let rootVersion = null;
7992
7964
  try {
7993
7965
  const text = await readFile(indexPath, "utf8");
7994
- rootVersion = projectIndexTemplateVersion(text);
7966
+ rootVersion = parseProjectIndexTemplateVersion(text);
7995
7967
  } catch {
7996
7968
  // file missing or unreadable; rootVersion stays null
7997
7969
  }