@adamchanadam/agent-handoff-kit 0.3.51 → 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,
@@ -44,7 +54,11 @@ const closeoutFinalizeTargets = new Set([
44
54
  "dev/DOC_SYNC_REGISTRY.md",
45
55
  "dev/PROJECT_DECISIONS.md"
46
56
  ]);
47
- const credentialLeakPatterns = [
57
+ const directCloseoutStateTargets = Object.freeze([...closeoutFinalizeTargets].sort((left, right) => left.localeCompare(right)));
58
+ const directCloseoutStateTargetSet = new Set(directCloseoutStateTargets);
59
+ const canonicalSessionLogArchiveRoot = "dev/SESSION_LOG_archive";
60
+ const legacySessionLogArchiveRoot = "dev/session_log_archive";
61
+ const credentialLeakPatterns = [
48
62
  { pattern: /sk-ant-[A-Za-z0-9_-]{20,}/, label: "Anthropic API key" },
49
63
  { pattern: /\bsk-[A-Za-z0-9_-]{20,}/, label: "sk-prefixed token" },
50
64
  { pattern: /\bntn_[A-Za-z0-9_-]{40,}/, label: "Notion token" },
@@ -56,8 +70,10 @@ const credentialLeakPatterns = [
56
70
  { pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}/, label: "GitHub fine-grained token" },
57
71
  { pattern: /\bsl\.[A-Za-z0-9_-]{50,}/, label: "Dropbox token" },
58
72
  { pattern: /\bAKIA[A-Z0-9]{16}/, label: "AWS access key" },
59
- { pattern: /\bAIza[A-Za-z0-9_-]{35}/, label: "Google API key" }
60
- ];
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";
61
77
 
62
78
  // Exact v0.3.38 continuity quick-fix packs observed in real projects before the
63
79
  // product migration shipped. They contain no project-specific state. Matching
@@ -438,15 +454,9 @@ const schemaChecks = [
438
454
  // to verify the section is structurally present.
439
455
  tableHeader("Check", "Command", "Run before", "Last verified"),
440
456
  tableHeader("Change type", "Likely files", "Required checks"),
441
- // R-030 v0.3.0+: Installed Integrations subsection table headers
442
- tableHeader("Tool", "Project Usage", "Access Scope", "Specific Instance", "Credential Reference (no value)", "Declared", "Last Verified"),
443
- tableHeader("Server", "Source", "Project Usage", "Credential Reference (no value)", "Declared", "Last Verified"),
444
- tableHeader("Name", "Bundle Content (Skills + MCP + hooks)", "When Triggered", "Last Verified"),
445
- tableHeader("Name", "Source", "When Triggered", "Last Verified"),
446
- tableHeader("Layer", "Surface (specific instance)", "Role", "Write Direction"),
447
- tableHeader("Tool / operation", "Reference path or URL", "Required before", "Source and version/date", "Scope and known limits", "Last verified")
448
- ]
449
- },
457
+ tableHeader("Tool / operation", "Reference path or URL", "Required before", "Source and version/date", "Scope and known limits", "Last verified")
458
+ ]
459
+ },
450
460
  {
451
461
  target: "dev/DOC_SYNC_REGISTRY.md",
452
462
  label: "doc sync registry status vocabulary",
@@ -604,6 +614,11 @@ async function main() {
604
614
  return;
605
615
  }
606
616
 
617
+ if (command === "reconcile-current-state") {
618
+ await runReconcileCurrentState(root, options, version);
619
+ return;
620
+ }
621
+
607
622
  throw new Error(`unknown command "${command}"`);
608
623
  }
609
624
 
@@ -664,6 +679,131 @@ async function runFinalizeCloseout(root, version) {
664
679
  console.log(`current-state digest: ${transaction.journal.currentStateWitness.currentStateDigest}`);
665
680
  }
666
681
 
682
+ async function runReconcileCurrentState(root, options, version) {
683
+ await validateTransactionRoot(root, [], { createMissingRoot: false });
684
+ if (options.dryRun) await assertDryRunHasNoPendingTransaction(root);
685
+ else {
686
+ assertCurrentStateReconcileWriteIntent(options);
687
+ if (await recoverBoundCurrentStateReconciliation(root, options.manifest)) {
688
+ console.log("current-state reconciliation recovery completed; run a fresh dry-run before applying another reconciliation plan");
689
+ return;
690
+ }
691
+ }
692
+ const candidate = await findCurrentStateReconciliationBase(root, version);
693
+ if (!candidate) {
694
+ console.log("current-state reconciliation: no stale source-conservation witness needs reconciliation");
695
+ if (options.dryRun) console.log("dry-run: no files written");
696
+ return;
697
+ }
698
+ if (candidate.illegal.length > 0) {
699
+ throw new Error(`current-state reconciliation blocked: ${candidate.illegal.map((item) => `${item.path} (${item.reason})`).join(", ")}`);
700
+ }
701
+ if (candidate.reconcilable.length === 0) {
702
+ console.log("current-state reconciliation: current-state witness already matches project bytes");
703
+ if (options.dryRun) console.log("dry-run: no files written");
704
+ return;
705
+ }
706
+ console.log(`current-state reconciliation plan: ${candidate.reconcilable.length} path(s)`);
707
+ console.log(`manifest sha256: ${candidate.manifestSha256}`);
708
+ for (const item of candidate.reconcilable) console.log(`- ${item.path}: ${item.reason}`);
709
+ if (options.dryRun) {
710
+ console.log("dry-run: no files written");
711
+ return;
712
+ }
713
+ if (options.manifest !== candidate.manifestSha256) {
714
+ throw new Error("current-state reconciliation manifest mismatch before writes; no files written");
715
+ }
716
+ const verified = await findCurrentStateReconciliationBase(root, version);
717
+ if (!verified || verified.manifestSha256 !== candidate.manifestSha256 || JSON.stringify(verified.manifest) !== JSON.stringify(candidate.manifest)) {
718
+ throw new Error("current-state reconciliation manifest changed before transaction preparation; no files written");
719
+ }
720
+ await assertCurrentStateReconciliationVerifiedPlanStillCurrent(root, verified);
721
+ const transaction = await writeCurrentStateReconciliationJournal(root, version, verified);
722
+ if (!await journalMatchesCurrentState(root, transaction.journal)) {
723
+ throw new Error("post-reconciliation current-state readback failed; reconciliation journal retained for inspection");
724
+ }
725
+ transaction.journal.currentStateReadback = currentStateReadbackFromVerifiedProjectBytes(transaction.journal.currentStateWitness);
726
+ await writeSecureJson(transaction.journalPath, transaction.journal);
727
+ await writeCurrentStateReconciliationReport({ root, migrationDir: path.dirname(transaction.journalPath), journal: transaction.journal, reconciledPaths: candidate.reconcilable.map((item) => item.path) });
728
+ console.log(`current-state reconciled: bound ${candidate.reconcilable.length} current project path(s) without overwriting project files`);
729
+ console.log("project health: run upgrade/doctor next if this project predates the current Kit template");
730
+ console.log(`current-state digest: ${transaction.journal.currentStateWitness.currentStateDigest}`);
731
+ }
732
+
733
+ function assertCurrentStateReconcileWriteIntent(options) {
734
+ if (!options.yes || !options.manifest) {
735
+ throw new Error("current-state reconciliation requires --yes --manifest <dry-run manifest sha256>; no files written");
736
+ }
737
+ if (typeof options.manifest !== "string" || !/^[a-f0-9]{64}$/.test(options.manifest)) {
738
+ throw new Error("current-state reconciliation manifest must be a lowercase sha256 digest; no files written");
739
+ }
740
+ }
741
+
742
+ async function recoverBoundCurrentStateReconciliation(root, manifestSha256) {
743
+ const lockPath = path.join(root, "dev", "governance_migrations", ".upgrade.lock");
744
+ let rawLock;
745
+ try {
746
+ rawLock = await readFile(lockPath, "utf8");
747
+ } catch (error) {
748
+ if (error?.code === "ENOENT") return false;
749
+ throw new Error("current-state reconciliation recovery lock is unreadable or unsafe; no writes attempted");
750
+ }
751
+ let lock;
752
+ try {
753
+ lock = JSON.parse(rawLock);
754
+ } catch {
755
+ throw new Error("current-state reconciliation recovery lock is not bound to a verified reconciliation transaction; no writes attempted");
756
+ }
757
+ if (!lock || typeof lock !== "object" || Array.isArray(lock)
758
+ || typeof lock.id !== "string" || !lock.id
759
+ || typeof lock.journal !== "string" || !lock.journal
760
+ || typeof lock.host !== "string" || !lock.host
761
+ || !Number.isInteger(lock.pid) || lock.pid <= 0
762
+ || lock.command !== "reconcile-current-state") {
763
+ throw new Error("current-state reconciliation recovery lock is not bound to reconcile-current-state; no writes attempted");
764
+ }
765
+ if (lock.host === hostname() && processIsAlive(lock.pid)) {
766
+ throw new Error(`another current-state reconciliation process is active (pid ${lock.pid}); no writes attempted`);
767
+ }
768
+ if (lock.host && lock.host !== hostname()) {
769
+ throw new Error(`current-state reconciliation recovery lock belongs to another host (${lock.host}); no writes attempted`);
770
+ }
771
+ const journalPath = path.resolve(root, lock.journal);
772
+ if (!isInside(root, journalPath)) throw new Error("current-state reconciliation recovery journal path escapes selected root; no writes attempted");
773
+ let journal;
774
+ try {
775
+ journal = JSON.parse(await readFile(journalPath, "utf8"));
776
+ } catch {
777
+ throw new Error("current-state reconciliation recovery lock has no readable durable journal; no writes attempted");
778
+ }
779
+ await validateRecoveryJournal(root, journal, journalPath, lock.id);
780
+ if (journal.command !== "reconcile-current-state" || journal.mode !== "source-state-reconciliation") {
781
+ throw new Error("current-state reconciliation recovery journal has no reconciliation authority; no writes attempted");
782
+ }
783
+ if (!["prepared", "committed"].includes(journal.state)) {
784
+ throw new Error("current-state reconciliation recovery journal is not in a recoverable state; no writes attempted");
785
+ }
786
+ if (journal.reconciliationManifestSha256 !== manifestSha256) {
787
+ throw new Error("current-state reconciliation recovery manifest digest does not match the CLI manifest; no writes attempted");
788
+ }
789
+ if (!journal.reconciliationManifest || typeof journal.reconciliationManifest !== "object" || Array.isArray(journal.reconciliationManifest)) {
790
+ throw new Error("current-state reconciliation recovery journal has no durable manifest; no writes attempted");
791
+ }
792
+ if (journal.reconciliationManifest.command !== "reconcile-current-state") {
793
+ throw new Error("current-state reconciliation recovery manifest has no reconciliation command authority; no writes attempted");
794
+ }
795
+ const durableManifestSha256 = sha256(Buffer.from(`${JSON.stringify(journal.reconciliationManifest)}\n`, "utf8"));
796
+ if (durableManifestSha256 !== manifestSha256) {
797
+ throw new Error("current-state reconciliation recovery durable manifest digest does not match the CLI manifest; no writes attempted");
798
+ }
799
+ const rootReal = await realpath(root);
800
+ if (journal.reconciliationManifest.root?.realpath !== rootReal) {
801
+ throw new Error("current-state reconciliation recovery manifest root does not match the selected root; no writes attempted");
802
+ }
803
+ await recoverInterruptedTransaction(root, { reconciliationManifestSha256: manifestSha256 });
804
+ return true;
805
+ }
806
+
667
807
  function closeoutOutcome(value) {
668
808
  return /^(complete|completed)\b/i.test((value ?? "").trim()) ? "complete" : "blocked";
669
809
  }
@@ -706,10 +846,11 @@ function parseArgs(args) {
706
846
  if (!command && !arg.startsWith("-")) {
707
847
  command = arg;
708
848
  continue;
709
- }
710
- if (arg === "--dry-run") options.dryRun = true;
711
- else if (arg === "--yes" || arg === "-y") options.yes = true;
712
- else if (arg === "--help" || arg === "-h") options.help = true;
849
+ }
850
+ if (arg === "--dry-run") options.dryRun = true;
851
+ else if (arg === "--yes" || arg === "-y") options.yes = true;
852
+ else if (arg === "--manifest") options.manifest = args[++i];
853
+ else if (arg === "--help" || arg === "-h") options.help = true;
713
854
  else if (arg === "--root") options.root = args[++i];
714
855
  else throw new Error(`unknown option "${arg}"`);
715
856
  }
@@ -721,20 +862,11 @@ function parseArgs(args) {
721
862
  // row is stale relative to current CLI version. Used by plan-time no-op detection
722
863
  // guard to ensure metadata-only stale roots still trigger the upgrade ceremony
723
864
  // (otherwise plan-time short-circuit returns before inject can run).
724
- async function needsProjectIndexVersionInject(root, command, version) {
725
- if (command !== "upgrade") return false;
726
- try {
727
- const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
728
- const text = await readFile(indexPath, "utf8");
729
- const m = text.match(/\| Agent Handoff Kit template version \| ([\d.]+) \|/);
730
- if (m && isStableSemver(m[1]) && compareSemver(m[1], version) < 0) {
731
- return true;
732
- }
733
- } catch {
734
- // ignore — silent if PROJECT_INDEX missing or unreadable
735
- }
736
- return false;
737
- }
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
+ }
738
870
 
739
871
  async function runInstall(command, root, options, version) {
740
872
  // Guard the selected root before reading or recovering any persisted
@@ -748,7 +880,7 @@ async function runInstall(command, root, options, version) {
748
880
  return;
749
881
  }
750
882
  }
751
- const installedVersion = await readInstalledTemplateVersion(root);
883
+ const installedVersion = await readProjectIndexTemplateVersion(root);
752
884
  if (command === "upgrade" && installedVersion && compareSemver(installedVersion, version) > 0) {
753
885
  console.log(`selected root: ${root}`);
754
886
  console.log(`status: blocked`);
@@ -767,7 +899,7 @@ async function runInstall(command, root, options, version) {
767
899
  if (command === "upgrade") {
768
900
  let acceptedCurrentState = null;
769
901
  try {
770
- acceptedCurrentState = await loadCommittedCurrentStateWitness(root);
902
+ acceptedCurrentState = await loadCommittedCurrentStateWitness(root, { allowHistoricalEdgeRetirement: true });
771
903
  } catch (error) {
772
904
  if (!String(error?.message ?? error).includes("doctor refuses an unbound success state")) throw error;
773
905
  await assertUnboundCurrentStateMayAttemptUpgradeRebind(root, error);
@@ -851,26 +983,21 @@ async function runInstall(command, root, options, version) {
851
983
  return;
852
984
  }
853
985
 
986
+ let transactionPreflight = null;
854
987
  if (planConflictCount === 0) {
855
- candidateOutputs ??= await buildTransactionOutputs(command, root, plan, version);
856
- const credentialFindings = await detectInstalledCredentialFindings(root);
857
- if (credentialFindings.length > 0) {
858
- plan.push({
859
- targetRel: "transaction preflight",
860
- action: "conflict",
861
- reason: `existing governance contains ${credentialFindings.length} possible credential value(s); remove and rotate them before upgrade`
862
- });
863
- } else {
864
- try {
865
- await validateTransactionOverlay(root, candidateOutputs);
866
- } catch (error) {
867
- plan.push({
868
- targetRel: "transaction preflight",
869
- action: "conflict",
870
- reason: safeErrorLabel(error)
871
- });
872
- }
873
- }
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
+ }
874
1001
  }
875
1002
 
876
1003
  printPlan(command, root, mode, plan, version, options.dryRun, installedVersion);
@@ -899,71 +1026,31 @@ async function runInstall(command, root, options, version) {
899
1026
  }
900
1027
  }
901
1028
 
902
- await executeInstallTransaction(command, root, mode, plan, version, candidateOutputs, { sourceConservationRebind });
1029
+ await executeInstallTransaction(command, root, mode, plan, version, transactionPreflight, { sourceConservationRebind });
903
1030
  }
904
1031
 
905
- async function readInstalledTemplateVersion(root) {
906
- try {
907
- const text = await readFile(path.join(root, "dev/PROJECT_INDEX.md"), "utf8");
908
- const match = text.match(/\| Agent Handoff Kit template version \| ([\d.]+) \|/);
909
- return match && isStableSemver(match[1]) ? match[1] : null;
910
- } catch {
911
- return null;
912
- }
913
- }
914
-
915
- async function executeInstallTransaction(command, root, mode, plan, version, candidateOutputs = null, options = {}) {
916
- const outputs = candidateOutputs ?? await buildTransactionOutputs(command, root, plan, version);
917
- if (outputs.length === 0) {
918
- const health = await assessUpgradeNoopHealth(root, version);
919
- 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);
920
1038
  if (!health.ok) process.exitCode = 1;
921
1039
  return;
922
1040
  }
923
1041
 
924
- const credentialFindings = await detectInstalledCredentialFindings(root);
925
- if (credentialFindings.length > 0) {
926
- console.log("⛔ 升級已停止:待備份的治理檔疑似含有 credential value。");
927
- console.log("機密值不會顯示或複製;請先移除並輪換機密,再重跑 upgrade。");
928
- for (const finding of credentialFindings) console.log(`blocked ${finding.relative}:${finding.line} (${finding.label})`);
929
- process.exitCode = 1;
930
- return;
931
- }
932
-
933
- // Run the same deterministic acceptance gate used by dry-run before creating
934
- // a lock, stage, backup, journal, or migration directory.
935
- await validateTransactionOverlay(root, outputs);
936
1042
  // The user has confirmed writes. Create and revalidate a missing root only
937
1043
  // now, immediately before transaction artifacts are prepared.
938
1044
  await validateTransactionRoot(root, plan, { createMissingRoot: true });
939
- // Gate 5 does not introduce a second state owner. When this existing
940
- // transaction already has a runtime acceptance, bind the pre-transaction
941
- // root-source witness into the same current-state digest before the journal
942
- // directory itself is created.
943
- const archiveMigrations = command === "upgrade"
944
- ? await prepareArchiveCasingMigrations(root)
945
- : [];
946
- const sourceConservationAuthority = command === "upgrade"
947
- ? await hasCommittedSourceConservationAuthority(root)
948
- : false;
949
- if (options.sourceConservationRebind === true) {
950
- 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;
951
1052
  }
952
- const runtimeAcceptance = command === "upgrade" && options.sourceConservationRebind !== true ? resolveRuntimeAcceptance(outputs) : null;
953
- const sourceConservation = command === "upgrade" && (
954
- runtimeAcceptance || sourceConservationAuthority
955
- )
956
- ? await createSourceConservation(root, outputs, archiveMigrations)
957
- : null;
958
- // A repair may restore the exact bytes of a prior committed state. Keep the
959
- // causal replacement relation inside the existing sealed journal so ordinary
960
- // doctor can select the freshly read-back transaction without falling back
961
- // to mtime or a separate current-state registry.
962
- const supersedesCurrentStateDigests = command === "upgrade"
963
- ? await findRestoredCurrentStateDigests(root, outputs, archiveMigrations, { sourceConservation, archiveMigrations })
964
- : [];
965
- const transaction = await prepareTransaction(root, command, version, outputs, mode, plan, sourceConservation, supersedesCurrentStateDigests, archiveMigrations);
966
- try {
1053
+ try {
967
1054
  transaction.journal.state = "committing";
968
1055
  await writeSecureJson(transaction.journalPath, transaction.journal);
969
1056
 
@@ -1096,11 +1183,147 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
1096
1183
  for (const conflict of rollback.conflicts) console.log(`blocked ${conflict}`);
1097
1184
  }
1098
1185
  throw error;
1099
- }
1100
- }
1101
-
1102
- async function detectInstalledCredentialFindings(root) {
1103
- 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 = [];
1104
1327
  for (const relative of requiredTargets) {
1105
1328
  const buffer = await readOptionalBuffer(path.join(root, relative));
1106
1329
  if (buffer) credentialInputs.push({ relative, text: decodeUtf8(buffer, relative).text });
@@ -1108,19 +1331,39 @@ async function detectInstalledCredentialFindings(root) {
1108
1331
  return detectCredentialValues(credentialInputs);
1109
1332
  }
1110
1333
 
1111
- async function buildTransactionOutputs(command, root, plan, version) {
1334
+ async function buildTransactionOutputs(command, root, plan, version, options = {}) {
1112
1335
  const byTarget = new Map();
1113
1336
  for (const item of plan) {
1114
1337
  if (item.action !== "create" && item.action !== "merge" && item.action !== "preserve") continue;
1115
1338
  const before = await readOptionalBuffer(item.targetAbs);
1116
1339
  let afterText = null;
1117
1340
  let after = null;
1341
+ let projectIndexVersionMetadataMerge = false;
1118
1342
  if (item.action === "preserve") {
1119
1343
  if (!before) throw new Error(`${item.targetRel}: preserved transaction item disappeared before preparation`);
1120
- 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
+ }
1121
1355
  } else if (item.action === "create") {
1122
1356
  const sourceText = await readTemplateSource(command, item.sourceRel, item.targetRel, item.sourceAbs);
1123
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);
1124
1367
  } else {
1125
1368
  afterText = item.mergedText;
1126
1369
  after = item.mergedBytes ? Buffer.from(item.mergedBytes) : null;
@@ -1132,17 +1375,17 @@ async function buildTransactionOutputs(command, root, plan, version) {
1132
1375
  const userRulesEntry = await readFile(path.join(packageRoot, "runtime-core", "USER_RULES_ENTRY.md"), "utf8");
1133
1376
  afterText = `${afterText.trimEnd()}\n\n${userRulesEntry.trim()}\n`;
1134
1377
  }
1135
- if (afterText != null) afterText = afterText.replaceAll("<absolute project root>", root);
1378
+ if (afterText != null && !projectIndexVersionMetadataMerge) afterText = afterText.replaceAll("<absolute project root>", root);
1136
1379
  byTarget.set(item.targetRel, {
1137
1380
  targetRel: item.targetRel,
1138
1381
  targetAbs: item.targetAbs,
1139
1382
  before,
1140
1383
  after,
1141
1384
  afterText,
1142
- ...(item.action === "preserve" ? { forceTransaction: true } : {}),
1143
- ...(item.action === "preserve" ? { preservedRuntimeItem: item.preservedRuntimeItem } : {}),
1385
+ ...(item.action === "preserve" && !projectIndexVersionMetadataMerge ? { forceTransaction: true } : {}),
1386
+ ...(item.action === "preserve" && !projectIndexVersionMetadataMerge ? { preservedRuntimeItem: item.preservedRuntimeItem } : {}),
1144
1387
  ...(item.managedSegmentRuntimeItem ? { managedSegmentRuntimeItem: item.managedSegmentRuntimeItem } : {}),
1145
- reason: item.reason ?? item.action
1388
+ reason: projectIndexVersionMetadataMerge ? projectIndexTemplateVersionMetadataReason : item.reason ?? item.action
1146
1389
  });
1147
1390
  }
1148
1391
 
@@ -1152,12 +1395,17 @@ async function buildTransactionOutputs(command, root, plan, version) {
1152
1395
  if (!indexOutput && (command === "upgrade" || await exists(indexAbs))) {
1153
1396
  const before = await readOptionalBuffer(indexAbs);
1154
1397
  if (before) indexOutput = { targetRel: indexRel, targetAbs: indexAbs, before, afterText: decodeUtf8(before, indexRel).text, reason: "template version metadata" };
1155
- }
1398
+ }
1156
1399
  if (indexOutput?.afterText != null) {
1157
- const updated = indexOutput.afterText.replace(/\| Agent Handoff Kit template version \| [\d.]+ \|/, `| Agent Handoff Kit template version | ${version} |`);
1158
- indexOutput.afterText = updated;
1159
- byTarget.set(indexRel, indexOutput);
1160
- }
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
+ }
1161
1409
 
1162
1410
  const handoffRel = "dev/SESSION_HANDOFF.md";
1163
1411
  const promptRel = "START_NEXT_SESSION_PROMPT.txt";
@@ -1188,7 +1436,9 @@ async function buildTransactionOutputs(command, root, plan, version) {
1188
1436
  }
1189
1437
  }
1190
1438
 
1191
- await synchronizeFormalUserRulesTransactionState(command, root, byTarget, version);
1439
+ await synchronizeFormalUserRulesTransactionState(command, root, byTarget, version, {
1440
+ allowActiveTransaction: options.allowActiveTransaction === true
1441
+ });
1192
1442
 
1193
1443
  const outputs = [];
1194
1444
  for (const item of byTarget.values()) {
@@ -1207,9 +1457,22 @@ async function buildTransactionOutputs(command, root, plan, version) {
1207
1457
  }
1208
1458
 
1209
1459
  function reconcilePlanWithTransactionOutputs(plan, outputs) {
1210
- const outputTargets = new Set(outputs.map((item) => item.targetRel));
1460
+ const outputByTarget = new Map(outputs.map((item) => [item.targetRel, item]));
1211
1461
  for (const item of plan) {
1212
- 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;
1213
1476
  // Planning formal state transitions before rendering their canonical
1214
1477
  // acceptance is necessary for safety. Once the in-memory comparison proves
1215
1478
  // no bytes would change, do not present that transition as a write.
@@ -1218,7 +1481,7 @@ function reconcilePlanWithTransactionOutputs(plan, outputs) {
1218
1481
  }
1219
1482
  }
1220
1483
 
1221
- async function synchronizeFormalUserRulesTransactionState(command, root, byTarget, version) {
1484
+ async function synchronizeFormalUserRulesTransactionState(command, root, byTarget, version, options = {}) {
1222
1485
  const routerOutput = byTarget.get(USER_RULES_ROUTER_PATH);
1223
1486
  if (!routerOutput) return;
1224
1487
 
@@ -1227,7 +1490,7 @@ async function synchronizeFormalUserRulesTransactionState(command, root, byTarge
1227
1490
  // The old formal reader is the sole authority for whether a prior router
1228
1491
  // is eligible for transition. A path, title, or directory never grants
1229
1492
  // this authority.
1230
- prior = await readFormalUserRules({ root });
1493
+ prior = await readFormalUserRules({ root, allowActiveTransaction: options.allowActiveTransaction === true });
1231
1494
  }
1232
1495
 
1233
1496
  let agentOutput = byTarget.get("AGENTS.md");
@@ -1316,12 +1579,7 @@ async function prepareTransaction(root, command, version, outputs, mode, plan, s
1316
1579
  await mkdir(archiveBackupDir, { recursive: true });
1317
1580
  await tightenPermissions(migrationsRoot, 0o700);
1318
1581
  await tightenPermissions(migrationDir, 0o700);
1319
- const lock = await open(lockPath, "wx", 0o600).catch((error) => {
1320
- if (error?.code === "EEXIST") throw new Error("another upgrade transaction or unresolved recovery lock is present");
1321
- throw error;
1322
- });
1323
- await lock.writeFile(JSON.stringify({ id, host: hostname(), pid: process.pid, journal: path.relative(root, journalPath) }, null, 2));
1324
- await lock.close();
1582
+ await publishTransactionLock(root, lockPath, { id, host: hostname(), pid: process.pid, journal: path.relative(root, journalPath), command });
1325
1583
 
1326
1584
  const entries = [];
1327
1585
  for (const output of outputs) {
@@ -1335,7 +1593,7 @@ async function prepareTransaction(root, command, version, outputs, mode, plan, s
1335
1593
  await writeFile(backupPath, output.before, { mode: 0o600 });
1336
1594
  backupRel = path.relative(root, backupPath);
1337
1595
  }
1338
- 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 });
1339
1597
  }
1340
1598
  const journal = {
1341
1599
  id,
@@ -1906,6 +2164,7 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
1906
2164
  const seen = new Set();
1907
2165
  const formalWitness = validateFormalUserRulesWitness(journal.formalUserRules);
1908
2166
  const runtimeAcceptance = validateRuntimeAcceptance(journal.runtimeAcceptance);
2167
+ const zeroWriteReconciliation = journal.command === "reconcile-current-state" && journal.mode === "source-state-reconciliation";
1909
2168
  const hasArchiveMigrationField = journal.archiveMigrations !== undefined;
1910
2169
  const requiresArchiveBackup = journal.command === "upgrade" && hasArchiveMigrationField;
1911
2170
  if (journal.archiveMigrations != null && !Array.isArray(journal.archiveMigrations)) throw new Error("upgrade journal archive migrations are invalid; no recovery writes attempted");
@@ -1924,30 +2183,31 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
1924
2183
  const migrationsStats = await lstat(migrationsRoot).catch(() => null);
1925
2184
  const migrationStats = await lstat(migrationDir).catch(() => null);
1926
2185
  const journalStats = await lstat(journalPath).catch(() => null);
1927
- const backupStats = await lstat(backupRoot).catch(() => null);
2186
+ const backupStats = await lstat(backupRoot).catch(() => null);
1928
2187
  const stageStats = await lstat(stageRoot).catch(() => null);
1929
2188
  const archiveBackupStats = requiresArchiveBackup ? await lstat(archiveBackupRoot).catch(() => null) : null;
1930
- if (!migrationsStats?.isDirectory() || migrationsStats.isSymbolicLink()
1931
- || !migrationStats?.isDirectory() || migrationStats.isSymbolicLink()
1932
- || !journalStats?.isFile() || journalStats.isSymbolicLink()
1933
- || !backupStats?.isDirectory() || backupStats.isSymbolicLink()
1934
- || !stageStats?.isDirectory() || stageStats.isSymbolicLink()
2189
+ if (!migrationsStats?.isDirectory() || migrationsStats.isSymbolicLink()
2190
+ || !migrationStats?.isDirectory() || migrationStats.isSymbolicLink()
2191
+ || !journalStats?.isFile() || journalStats.isSymbolicLink()
2192
+ || (!zeroWriteReconciliation && (!backupStats?.isDirectory() || backupStats.isSymbolicLink()))
2193
+ || (!zeroWriteReconciliation && (!stageStats?.isDirectory() || stageStats.isSymbolicLink()))
1935
2194
  || (requiresArchiveBackup && (!archiveBackupStats?.isDirectory() || archiveBackupStats.isSymbolicLink()))) {
1936
- throw new Error("upgrade transaction directories or journal are missing or unsafe; no recovery writes attempted");
1937
- }
2195
+ throw new Error("upgrade transaction directories or journal are missing or unsafe; no recovery writes attempted");
2196
+ }
1938
2197
  const migrationsReal = await realpath(migrationsRoot);
1939
2198
  const migrationReal = await realpath(migrationDir);
1940
2199
  const journalReal = await realpath(journalPath);
1941
- const backupRealRoot = await realpath(backupRoot);
1942
- const stageRealRoot = await realpath(stageRoot);
2200
+ const backupRealRoot = zeroWriteReconciliation ? null : await realpath(backupRoot);
2201
+ const stageRealRoot = zeroWriteReconciliation ? null : await realpath(stageRoot);
1943
2202
  const archiveBackupRealRoot = requiresArchiveBackup ? await realpath(archiveBackupRoot) : null;
1944
- if (!isInside(rootReal, migrationsReal) || !isInside(migrationsReal, migrationReal)
1945
- || !isInside(migrationReal, journalReal) || !isInside(migrationReal, backupRealRoot) || !isInside(migrationReal, stageRealRoot)
1946
- || !samePath(path.dirname(migrationReal), migrationsReal)
1947
- || !samePath(path.dirname(backupRealRoot), migrationReal) || !samePath(path.dirname(stageRealRoot), migrationReal)
2203
+ if (!isInside(rootReal, migrationsReal) || !isInside(migrationsReal, migrationReal)
2204
+ || !isInside(migrationReal, journalReal)
2205
+ || (!zeroWriteReconciliation && (!isInside(migrationReal, backupRealRoot) || !isInside(migrationReal, stageRealRoot)))
2206
+ || !samePath(path.dirname(migrationReal), migrationsReal)
2207
+ || (!zeroWriteReconciliation && (!samePath(path.dirname(backupRealRoot), migrationReal) || !samePath(path.dirname(stageRealRoot), migrationReal)))
1948
2208
  || (requiresArchiveBackup && !samePath(path.dirname(archiveBackupRealRoot), migrationReal))) {
1949
- throw new Error("upgrade transaction paths resolve outside the selected root or transaction; no recovery writes attempted");
1950
- }
2209
+ throw new Error("upgrade transaction paths resolve outside the selected root or transaction; no recovery writes attempted");
2210
+ }
1951
2211
  const validated = [];
1952
2212
  const validHash = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
1953
2213
  for (const entry of journal.entries) {
@@ -1974,25 +2234,34 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
1974
2234
  if (error?.code !== "ENOENT") throw error;
1975
2235
  }
1976
2236
 
1977
- const stageAbs = path.resolve(stageRoot, entry.targetRel);
1978
- const stageStats = await lstat(stageAbs).catch(() => null);
1979
- if (!stageStats?.isFile() || stageStats.isSymbolicLink()) throw new Error("upgrade journal stage is missing or unsafe; no recovery writes attempted");
1980
- const stageReal = await realpath(stageAbs);
1981
- if (!isInside(stageRealRoot, stageReal)) throw new Error("upgrade journal stage resolves outside this transaction; no recovery writes attempted");
1982
- if (sha256(await readFile(stageAbs)) !== entry.afterHash) throw new Error("upgrade journal stage hash does not match the recorded candidate; no recovery writes attempted");
1983
-
1984
- let backup = null;
1985
- if (entry.existed) {
1986
- if (typeof entry.backupRel !== "string" || !entry.backupRel) throw new Error("upgrade journal backup path is missing; no recovery writes attempted");
1987
- const backupAbs = path.resolve(root, entry.backupRel);
1988
- const expectedBackup = path.resolve(backupRoot, entry.targetRel);
1989
- if (!samePath(backupAbs, expectedBackup) || !isInside(backupRoot, backupAbs)) throw new Error("upgrade journal backup path is outside this transaction; no recovery writes attempted");
1990
- const backupFileStats = await lstat(backupAbs).catch(() => null);
1991
- if (!backupFileStats?.isFile() || backupFileStats.isSymbolicLink()) throw new Error("upgrade journal backup is missing or unsafe; no recovery writes attempted");
1992
- const backupReal = await realpath(backupAbs);
1993
- if (!isInside(backupRealRoot, backupReal)) throw new Error("upgrade journal backup resolves outside this transaction; no recovery writes attempted");
1994
- backup = await readFile(backupAbs);
1995
- if (sha256(backup) !== entry.beforeHash) throw new Error("upgrade journal backup hash does not match the recorded input; no recovery writes attempted");
2237
+ if (zeroWriteReconciliation && entry.beforeHash !== entry.afterHash) {
2238
+ throw new Error("current-state reconciliation journal cannot record project-content writes; no recovery writes attempted");
2239
+ }
2240
+ if (!zeroWriteReconciliation) {
2241
+ const stageAbs = path.resolve(stageRoot, entry.targetRel);
2242
+ const stageStats = await lstat(stageAbs).catch(() => null);
2243
+ if (!stageStats?.isFile() || stageStats.isSymbolicLink()) throw new Error("upgrade journal stage is missing or unsafe; no recovery writes attempted");
2244
+ const stageReal = await realpath(stageAbs);
2245
+ if (!isInside(stageRealRoot, stageReal)) throw new Error("upgrade journal stage resolves outside this transaction; no recovery writes attempted");
2246
+ if (sha256(await readFile(stageAbs)) !== entry.afterHash) throw new Error("upgrade journal stage hash does not match the recorded candidate; no recovery writes attempted");
2247
+ }
2248
+
2249
+ let backup = null;
2250
+ if (entry.existed) {
2251
+ if (zeroWriteReconciliation) {
2252
+ if (entry.backupRel !== null) throw new Error("current-state reconciliation journal must not record backup paths; no recovery writes attempted");
2253
+ } else {
2254
+ if (typeof entry.backupRel !== "string" || !entry.backupRel) throw new Error("upgrade journal backup path is missing; no recovery writes attempted");
2255
+ const backupAbs = path.resolve(root, entry.backupRel);
2256
+ const expectedBackup = path.resolve(backupRoot, entry.targetRel);
2257
+ if (!samePath(backupAbs, expectedBackup) || !isInside(backupRoot, backupAbs)) throw new Error("upgrade journal backup path is outside this transaction; no recovery writes attempted");
2258
+ const backupFileStats = await lstat(backupAbs).catch(() => null);
2259
+ if (!backupFileStats?.isFile() || backupFileStats.isSymbolicLink()) throw new Error("upgrade journal backup is missing or unsafe; no recovery writes attempted");
2260
+ const backupReal = await realpath(backupAbs);
2261
+ if (!isInside(backupRealRoot, backupReal)) throw new Error("upgrade journal backup resolves outside this transaction; no recovery writes attempted");
2262
+ backup = await readFile(backupAbs);
2263
+ if (sha256(backup) !== entry.beforeHash) throw new Error("upgrade journal backup hash does not match the recorded input; no recovery writes attempted");
2264
+ }
1996
2265
  } else if (entry.backupRel !== null) {
1997
2266
  throw new Error("upgrade journal has an unexpected backup for a created target; no recovery writes attempted");
1998
2267
  }
@@ -2024,7 +2293,9 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
2024
2293
  }
2025
2294
  if (journal.currentStateWitness) {
2026
2295
  const currentStateWitness = validateCurrentStateWitness(journal);
2027
- validateCurrentStateReadback(journal.currentStateReadback, currentStateWitness);
2296
+ validateCurrentStateReadback(journal.currentStateReadback, currentStateWitness, {
2297
+ allowProjectByteReader: zeroWriteReconciliation
2298
+ });
2028
2299
  } else if (journal.currentStateReadback != null) {
2029
2300
  throw new Error("shared current-state readback exists without a current-state witness; no recovery writes attempted");
2030
2301
  }
@@ -2174,15 +2445,32 @@ async function removeArchiveSubsetNoClobber(root, migration, canonicalAbs, escro
2174
2445
  }
2175
2446
  }
2176
2447
 
2177
- async function recoverInterruptedTransaction(root) {
2178
- const lockPath = path.join(root, "dev", "governance_migrations", ".upgrade.lock");
2179
- let lock;
2180
- try {
2181
- lock = JSON.parse(await readFile(lockPath, "utf8"));
2182
- } catch (error) {
2183
- if (error?.code === "ENOENT") return;
2184
- throw new Error("upgrade lock exists but is unreadable; no writes attempted");
2185
- }
2448
+ function assertRecoveryCallerMayHandleReconciliation(lock, journal, manifestSha256) {
2449
+ const involvesReconciliation = lock.command === "reconcile-current-state" || journal.command === "reconcile-current-state";
2450
+ if (!involvesReconciliation) return;
2451
+ if (typeof manifestSha256 !== "string" || !/^[a-f0-9]{64}$/.test(manifestSha256)
2452
+ || lock.command !== "reconcile-current-state"
2453
+ || journal.command !== "reconcile-current-state"
2454
+ || journal.mode !== "source-state-reconciliation"
2455
+ || journal.reconciliationManifestSha256 !== manifestSha256
2456
+ || !journal.reconciliationManifest
2457
+ || typeof journal.reconciliationManifest !== "object"
2458
+ || Array.isArray(journal.reconciliationManifest)
2459
+ || sha256(Buffer.from(`${JSON.stringify(journal.reconciliationManifest)}\n`, "utf8")) !== manifestSha256) {
2460
+ throw new Error("current-state reconciliation recovery requires reconcile-current-state --yes --manifest <freshly reviewed digest>; no automatic recovery attempted");
2461
+ }
2462
+ }
2463
+
2464
+ async function recoverInterruptedTransaction(root, options = {}) {
2465
+ const lockPath = path.join(root, "dev", "governance_migrations", ".upgrade.lock");
2466
+ let lock;
2467
+ try {
2468
+ lock = JSON.parse(await readFile(lockPath, "utf8"));
2469
+ } catch (error) {
2470
+ if (error?.code === "ENOENT") return;
2471
+ if (await quarantineUnboundUnreadableLock(root, lockPath)) return;
2472
+ throw new Error("upgrade lock exists but is unreadable; no writes attempted");
2473
+ }
2186
2474
  if (!lock || typeof lock !== "object" || Array.isArray(lock) || typeof lock.id !== "string" || typeof lock.journal !== "string"
2187
2475
  || typeof lock.host !== "string" || !Number.isInteger(lock.pid) || lock.pid <= 0) {
2188
2476
  throw new Error("upgrade lock schema is invalid; no automatic recovery attempted");
@@ -2192,11 +2480,12 @@ async function recoverInterruptedTransaction(root) {
2192
2480
  const journalPath = path.resolve(root, lock.journal ?? "");
2193
2481
  if (!isInside(root, journalPath)) throw new Error("upgrade lock journal path escapes selected root");
2194
2482
  let journal;
2195
- try {
2196
- journal = JSON.parse(await readFile(journalPath, "utf8"));
2197
- } catch {
2198
- throw new Error("incomplete upgrade lock has no readable journal; no automatic recovery attempted");
2199
- }
2483
+ try {
2484
+ journal = JSON.parse(await readFile(journalPath, "utf8"));
2485
+ } catch {
2486
+ throw new Error("incomplete upgrade lock has no readable journal; no automatic recovery attempted");
2487
+ }
2488
+ assertRecoveryCallerMayHandleReconciliation(lock, journal, options.reconciliationManifestSha256);
2200
2489
  await validateRecoveryJournal(root, journal, journalPath, lock.id);
2201
2490
  if (journal.state === "committed") {
2202
2491
  if (!journal.committedVersion) journal.committedVersion = journal.attemptedVersion;
@@ -2228,12 +2517,21 @@ async function recoverInterruptedTransaction(root) {
2228
2517
  );
2229
2518
  }
2230
2519
  const migrationDir = path.dirname(journalPath);
2231
- await writeSecureJson(journalPath, journal);
2232
- await writeTransactionReport({ id: journal.id, migrationDir, journal });
2233
- await unlinkIfExists(lockPath);
2234
- console.log("⚠️ recovered committed upgrade: migration report was verified or rebuilt before planning this run");
2235
- return;
2236
- }
2520
+ await writeSecureJson(journalPath, journal);
2521
+ if (journal.command === "reconcile-current-state") {
2522
+ const reconciledPaths = (journal.currentStateWitness?.sourceConservation?.entries ?? [])
2523
+ .filter((entry) => ["user-owned-reconciliation", "session-log-archive-reconciliation"].includes(entry.disposition))
2524
+ .map((entry) => entry.sourcePath);
2525
+ await writeCurrentStateReconciliationReport({ migrationDir, journal, reconciledPaths });
2526
+ } else {
2527
+ await writeTransactionReport({ id: journal.id, migrationDir, journal });
2528
+ }
2529
+ await unlinkIfExists(lockPath);
2530
+ console.log(journal.command === "reconcile-current-state"
2531
+ ? "⚠️ recovered committed current-state reconciliation: reconciliation report was verified or rebuilt before planning this run"
2532
+ : "⚠️ recovered committed upgrade: migration report was verified or rebuilt before planning this run");
2533
+ return;
2534
+ }
2237
2535
  if (journal.state === "rolled-back") {
2238
2536
  await unlinkIfExists(lockPath);
2239
2537
  return;
@@ -2241,10 +2539,39 @@ async function recoverInterruptedTransaction(root) {
2241
2539
  const rollback = await rollbackTransaction(root, journal, journalPath, lock.id);
2242
2540
  if (!rollback.ok) throw new Error(`interrupted upgrade has third-state edits: ${rollback.conflicts.join("; ")}`);
2243
2541
  await unlinkIfExists(lockPath);
2244
- console.log("⚠️ recovered interrupted upgrade: transaction-owned changes were safely rolled back before planning this run");
2245
- }
2246
-
2247
- async function writeTransactionReport(transaction) {
2542
+ console.log("⚠️ recovered interrupted upgrade: transaction-owned changes were safely rolled back before planning this run");
2543
+ }
2544
+
2545
+ async function quarantineUnboundUnreadableLock(root, lockPath) {
2546
+ let raw;
2547
+ try {
2548
+ raw = await readFile(lockPath, "utf8");
2549
+ } catch {
2550
+ return false;
2551
+ }
2552
+ const trimmed = raw.trim();
2553
+ if (!(trimmed === "" || trimmed === "{" || trimmed === "[")) return false;
2554
+ const migrationsRoot = path.join(root, "dev", "governance_migrations");
2555
+ const entries = await readdir(migrationsRoot, { withFileTypes: true }).catch(() => []);
2556
+ const activeStates = new Set(["prepared", "committing", "rollback-needed", "manual-recovery-required"]);
2557
+ for (const entry of entries) {
2558
+ if (!entry.isDirectory()) continue;
2559
+ const journalPath = path.join(migrationsRoot, entry.name, "transaction.json");
2560
+ let journal = null;
2561
+ try {
2562
+ journal = JSON.parse(await readFile(journalPath, "utf8"));
2563
+ } catch {
2564
+ continue;
2565
+ }
2566
+ if (activeStates.has(journal?.state)) return false;
2567
+ }
2568
+ const quarantinePath = path.join(migrationsRoot, `.upgrade.lock.unbound-${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}`);
2569
+ await rename(lockPath, quarantinePath);
2570
+ console.log("⚠️ recovered unbound incomplete upgrade lock: quarantined empty or partial lock before planning this run");
2571
+ return true;
2572
+ }
2573
+
2574
+ async function writeTransactionReport(transaction) {
2248
2575
  const reportPath = path.join(transaction.migrationDir, "migration-report.md");
2249
2576
  const lines = [
2250
2577
  "# Agent Handoff Kit Migration Report",
@@ -2260,7 +2587,7 @@ async function writeTransactionReport(transaction) {
2260
2587
  "",
2261
2588
  "## Actions",
2262
2589
  "",
2263
- ...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}`),
2264
2591
  "",
2265
2592
  `- Planned skips: ${transaction.journal.plannedSkips ?? "unknown"}`,
2266
2593
  "- Conflicts: 0",
@@ -2276,10 +2603,34 @@ async function writeTransactionReport(transaction) {
2276
2603
  ];
2277
2604
  await writeFile(reportPath, `${lines.join("\n")}\n`, { mode: 0o600 });
2278
2605
  await tightenPermissions(reportPath, 0o600);
2279
- return reportPath;
2280
- }
2281
-
2282
- function decodeUtf8(buffer, relative) {
2606
+ return reportPath;
2607
+ }
2608
+
2609
+ async function writeCurrentStateReconciliationReport({ migrationDir, journal, reconciledPaths }) {
2610
+ const reportPath = path.join(migrationDir, "migration-report.md");
2611
+ const lines = [
2612
+ "# Agent Handoff Kit Current-State Reconciliation Report",
2613
+ "",
2614
+ `- Command: ${journal.command ?? "reconcile-current-state"}`,
2615
+ `- Attempted version: ${journal.attemptedVersion}`,
2616
+ `- Committed version: ${journal.committedVersion ?? "none"}`,
2617
+ `- Transaction state: ${journal.state}`,
2618
+ `- Supersedes current-state digest: ${(journal.supersedesCurrentStateDigests ?? []).join(", ")}`,
2619
+ `- Current-state digest: ${journal.currentStateWitness?.currentStateDigest ?? "none"}`,
2620
+ `- Reconciled paths: ${reconciledPaths.join(", ")}`,
2621
+ ...(journal.reconciliationManifestSha256 ? [`- Reconciliation manifest sha256: ${journal.reconciliationManifestSha256}`] : []),
2622
+ "- Project files overwritten: none",
2623
+ "- Transaction-owned project content writes: none",
2624
+ "",
2625
+ "## Shared Current-State Witness",
2626
+ ...renderCurrentStateWitnessReport(journal.currentStateWitness, journal.currentStateReadback)
2627
+ ];
2628
+ await writeFile(reportPath, `${lines.join("\n")}\n`, { mode: 0o600 });
2629
+ await tightenPermissions(reportPath, 0o600);
2630
+ return reportPath;
2631
+ }
2632
+
2633
+ function decodeUtf8(buffer, relative) {
2283
2634
  const bom = buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf;
2284
2635
  const body = bom ? buffer.subarray(3) : buffer;
2285
2636
  let text;
@@ -2393,11 +2744,25 @@ async function tightenPermissions(filePath, mode) {
2393
2744
  try { await chmod(filePath, mode); } catch { /* best effort on platforms without POSIX modes */ }
2394
2745
  }
2395
2746
 
2396
- async function unlinkIfExists(filePath) {
2397
- try { await unlink(filePath); } catch (error) { if (error?.code !== "ENOENT") throw error; }
2398
- }
2399
-
2400
- function processIsAlive(pid) {
2747
+ async function unlinkIfExists(filePath) {
2748
+ try { await unlink(filePath); } catch (error) { if (error?.code !== "ENOENT") throw error; }
2749
+ }
2750
+
2751
+ async function publishTransactionLock(root, lockPath, lockRecord) {
2752
+ const lockDir = path.dirname(lockPath);
2753
+ const tempPath = path.join(lockDir, `.upgrade.lock.${lockRecord.id}.${process.pid}.${randomUUID()}.tmp`);
2754
+ await writeSecureJson(tempPath, lockRecord);
2755
+ try {
2756
+ await link(tempPath, lockPath);
2757
+ } catch (error) {
2758
+ await unlinkIfExists(tempPath).catch(() => {});
2759
+ if (error?.code === "EEXIST") throw new Error("another upgrade transaction or unresolved recovery lock is present");
2760
+ throw error;
2761
+ }
2762
+ await unlinkIfExists(tempPath);
2763
+ }
2764
+
2765
+ function processIsAlive(pid) {
2401
2766
  if (!Number.isInteger(pid) || pid <= 0) return false;
2402
2767
  try { process.kill(pid, 0); return true; } catch { return false; }
2403
2768
  }
@@ -2417,11 +2782,14 @@ function stripMarkdownCommentsAndFences(text) {
2417
2782
  return text.replace(/<!--[\s\S]*?-->/g, "").replace(/```[\s\S]*?```/g, "");
2418
2783
  }
2419
2784
 
2420
- function safeErrorLabel(error) {
2421
- return String(error?.message ?? error).slice(0, 500);
2422
- }
2423
-
2785
+ function safeErrorLabel(error) {
2786
+ return String(error?.message ?? error).slice(0, 500);
2787
+ }
2788
+
2424
2789
  async function runDoctor(root, version, options = {}) {
2790
+ if (options.allowActiveTransaction !== true && await hasActiveTransactionLock(root)) {
2791
+ throw new Error("current-state recovery is pending; doctor refuses a partial transaction state");
2792
+ }
2425
2793
  // The transaction journal is the existing shared acceptance authority. A
2426
2794
  // preserved non-exact rule pack may intentionally retain older/user bytes;
2427
2795
  // its missing current-template anchors are acceptable only when this same
@@ -2632,24 +3000,7 @@ async function runDoctor(root, version, options = {}) {
2632
3000
  return "failed";
2633
3001
  }
2634
3002
 
2635
- const artifactResult = await checkGeneratedMarkdownGovernance(root);
2636
- console.log(`\ngenerated markdown governance checks: ${artifactResult.checked}`);
2637
- console.log(`${artifactResult.ok ? "ok" : "missing"} dev/PROJECT_INDEX.md (generated Markdown registration; other formats require human review)`);
2638
- if (!artifactResult.ok) {
2639
- for (const finding of artifactResult.findings) {
2640
- console.log(` missing: ${finding}`);
2641
- }
2642
- printDoctorSummary(version, root, "needs-fix", {
2643
- checked: rows.length + currentStateResult.checked + anchorRows.length + schemaRows.length + userRulesResult.checked + runtimeAcceptanceResult.checked + researchTraceResult.checked + temperatureResult.checked + artifactResult.checked,
2644
- failedKind: "generated markdown governance checks",
2645
- failedCount: artifactResult.findings.length,
2646
- nextStep: "把新生成或新修改的 Markdown 登記到 dev/PROJECT_INDEX.md,或在 SESSION_LOG / task summary 以同一紀錄精確標成 draft、temporary 或 one-time evidence;如內容重複,先合併到單一真源。其他持久格式須由 AI 另作人工治理核對。"
2647
- });
2648
- process.exitCode = 1;
2649
- return "failed";
2650
- }
2651
-
2652
- const mirrorRows = await checkPromptMirror(root);
3003
+ const mirrorRows = await checkPromptMirror(root);
2653
3004
  const mirrorBlockingFailures = mirrorRows.filter((row) => !row.ok && row.reason !== "convenience copy differs from dev/SESSION_HANDOFF.md");
2654
3005
  const mirrorWarnings = mirrorRows.filter((row) => !row.ok && row.reason === "convenience copy differs from dev/SESSION_HANDOFF.md");
2655
3006
  console.log(`\nprompt mirror checks: ${mirrorRows.length}`);
@@ -2721,7 +3072,7 @@ async function runDoctor(root, version, options = {}) {
2721
3072
  const overallHealthy = credentialResult.ok;
2722
3073
  if (overallHealthy && !options.silentCard) printCard(version, "doctor ready", "o.o");
2723
3074
  printDoctorSummary(version, root, overallHealthy ? "healthy" : "needs-attention", {
2724
- 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,
2725
3076
  failedKind: !credentialResult.ok ? "credential leak" : null,
2726
3077
  failedCount: !credentialResult.ok ? credentialResult.findings.length : 0,
2727
3078
  warningKind: mirrorWarnings.length > 0 ? "prompt mirror warning" : null,
@@ -2819,7 +3170,7 @@ function resolveRuntimeAcceptance(outputs) {
2819
3170
  return validateRuntimeAcceptance(witnesses[0]);
2820
3171
  }
2821
3172
 
2822
- async function createSourceConservation(root, outputs, archiveMigrations = []) {
3173
+ async function createSourceConservation(root, outputs, archiveMigrations = [], options = {}) {
2823
3174
  // `freezeGate5Set` is an existing read-only discovery witness. Reuse it
2824
3175
  // here rather than creating a registry, pointer, or component authority.
2825
3176
  // Its ordered source records become one component of the journal's existing
@@ -2828,10 +3179,20 @@ async function createSourceConservation(root, outputs, archiveMigrations = []) {
2828
3179
  assertGate5FrozenSet(frozen);
2829
3180
  const outputByTarget = new Map(outputs.map((item) => [item.targetRel, item]));
2830
3181
  const pathRebindings = archiveMigrations.map((migration) => ({
3182
+ originalRel: migration.originalRel,
3183
+ canonicalRel: migration.canonicalRel,
2831
3184
  sourcePrefix: `${migration.originalRel}/`,
2832
3185
  targetPrefix: `${migration.canonicalRel}/`
2833
3186
  }));
2834
- 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) {
2835
3196
  const output = outputByTarget.get(item.sourcePath) ?? null;
2836
3197
  const rebind = pathRebindings.find((candidate) => item.sourcePath.startsWith(candidate.sourcePrefix)) ?? null;
2837
3198
  const sourcePath = rebind
@@ -2852,7 +3213,7 @@ async function createSourceConservation(root, outputs, archiveMigrations = []) {
2852
3213
  : item.priorityConflict.status === "not-applicable-outside-known-kit-reachability"
2853
3214
  ? "outside-known-kit-reachability"
2854
3215
  : "unchanged-source";
2855
- return Object.freeze({
3216
+ const entry = Object.freeze({
2856
3217
  sourcePath,
2857
3218
  ...(rebind ? { sourceOriginPath: item.sourcePath } : {}),
2858
3219
  sourceWitness,
@@ -2866,7 +3227,19 @@ async function createSourceConservation(root, outputs, archiveMigrations = []) {
2866
3227
  effectDecision: item.effect.decision,
2867
3228
  classifications: Object.freeze([...item.classifications])
2868
3229
  });
2869
- });
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));
2870
3243
  return Object.freeze({
2871
3244
  schemaVersion: archiveMigrations.length > 0 ? 2 : 1,
2872
3245
  frozenSetSha256: frozen.frozenSetSha256,
@@ -2874,6 +3247,42 @@ async function createSourceConservation(root, outputs, archiveMigrations = []) {
2874
3247
  });
2875
3248
  }
2876
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
+
2877
3286
  function currentStateWitnessBody(journal) {
2878
3287
  const transaction = {
2879
3288
  id: journal.id,
@@ -2919,7 +3328,7 @@ function validateCurrentStateWitnessValue(value) {
2919
3328
  || ![1, 2, 3].includes(value.schemaVersion)
2920
3329
  || !value.transaction || typeof value.transaction !== "object" || Array.isArray(value.transaction)
2921
3330
  || typeof value.transaction.id !== "string" || !value.transaction.id
2922
- || !["init", "upgrade", "finalize-closeout"].includes(value.transaction.command)
3331
+ || !["init", "upgrade", "finalize-closeout", "reconcile-current-state"].includes(value.transaction.command)
2923
3332
  || typeof value.transaction.mode !== "string" || !value.transaction.mode
2924
3333
  || !isStableSemver(value.transaction.attemptedVersion ?? "")
2925
3334
  || !Array.isArray(value.entries) || value.entries.length === 0
@@ -2952,12 +3361,16 @@ function validateCurrentStateWitnessValue(value) {
2952
3361
  ...(formalWitness ? [...formalWitness.contentPaths] : [])
2953
3362
  ]);
2954
3363
  const seenTargets = new Set();
3364
+ const zeroWriteReconciliation = value.transaction.command === "reconcile-current-state" && value.transaction.mode === "source-state-reconciliation";
2955
3365
  for (const entry of value.entries) {
2956
3366
  if (!entry || typeof entry !== "object" || Array.isArray(entry)
2957
3367
  || typeof entry.targetRel !== "string" || !knownTargets.has(entry.targetRel) || seenTargets.has(entry.targetRel)
2958
3368
  || typeof entry.existed !== "boolean"
2959
3369
  || typeof entry.afterHash !== "string" || !/^[a-f0-9]{64}$/.test(entry.afterHash)
2960
- || (entry.existed && (typeof entry.beforeHash !== "string" || !/^[a-f0-9]{64}$/.test(entry.beforeHash) || typeof entry.backupRel !== "string" || !entry.backupRel))
3370
+ || (entry.existed && (typeof entry.beforeHash !== "string" || !/^[a-f0-9]{64}$/.test(entry.beforeHash)
3371
+ || (zeroWriteReconciliation
3372
+ ? entry.backupRel !== null || entry.beforeHash !== entry.afterHash
3373
+ : typeof entry.backupRel !== "string" || !entry.backupRel)))
2961
3374
  || (!entry.existed && (entry.beforeHash !== null || entry.backupRel !== null))) {
2962
3375
  throw new Error("shared current-state entry witness is invalid; no recovery writes attempted");
2963
3376
  }
@@ -3023,7 +3436,7 @@ function validateSourceConservation(value, { required = false } = {}) {
3023
3436
  || !Array.isArray(entry.sourceByteRanges) || entry.sourceByteRanges.length !== 1
3024
3437
  || entry.sourceByteRanges[0]?.start !== 0 || entry.sourceByteRanges[0]?.end !== entry.sourceWitness.bytes
3025
3438
  || entry.sourceByteRanges[0]?.sha256 !== entry.sourceWitness.sha256
3026
- || !["preserve", "transaction-output", "unchanged-source", "retained-historical-state", "outside-known-kit-reachability", "closeout-state-finalize", "canonical-path-migration", "canonical-path-migration-closeout"].includes(entry.disposition)
3439
+ || !["preserve", "transaction-output", "unchanged-source", "retained-historical-state", "outside-known-kit-reachability", "closeout-state-finalize", "canonical-path-migration", "canonical-path-migration-closeout", "user-owned-reconciliation", "session-log-archive-reconciliation"].includes(entry.disposition)
3027
3440
  || !Array.isArray(entry.existingReaders)
3028
3441
  || entry.existingReaders.some((reader) => !reader || typeof reader !== "object" || Array.isArray(reader) || typeof reader.reader !== "string" || !reader.reader || typeof reader.via !== "string" || !reader.via)
3029
3442
  || typeof entry.priorityRelation !== "string" || !entry.priorityRelation
@@ -3031,8 +3444,8 @@ function validateSourceConservation(value, { required = false } = {}) {
3031
3444
  || !Array.isArray(entry.classifications) || entry.classifications.length === 0 || entry.classifications.some((classification) => typeof classification !== "string" || !classification)) {
3032
3445
  throw new Error("shared current-state source conservation entry is invalid; no recovery writes attempted");
3033
3446
  }
3034
- if (["canonical-path-migration", "canonical-path-migration-closeout"].includes(entry.disposition)) {
3035
- if (value.schemaVersion !== 2 || !isSafeProjectRelative(entry.sourceOriginPath)
3447
+ if (["canonical-path-migration", "canonical-path-migration-closeout", "session-log-archive-reconciliation"].includes(entry.disposition) && entry.sourceOriginPath !== undefined) {
3448
+ if (![2, 3].includes(value.schemaVersion) || !isSafeProjectRelative(entry.sourceOriginPath)
3036
3449
  || entry.sourceOriginPath === entry.sourcePath
3037
3450
  || !entry.sourceOriginPath.startsWith("dev/") || !entry.sourcePath.startsWith("dev/SESSION_LOG_archive/")) {
3038
3451
  throw new Error("archive source-path rebinding is invalid; no recovery writes attempted");
@@ -3303,8 +3716,7 @@ async function directAgentsEntryWitness(root, bytes, outputByTarget = null) {
3303
3716
 
3304
3717
  function directFormalAgentReferences(text) {
3305
3718
  return extractExplicitLocalReferences(text).filter((reference) => (
3306
- reference.via === "markdown-link"
3307
- || (reference.via === "inline-code-path" && Boolean(installedFileContract(reference.path)))
3719
+ Boolean(installedFileContract(reference.path))
3308
3720
  ));
3309
3721
  }
3310
3722
 
@@ -3399,8 +3811,10 @@ async function directRulePacksEntryWitness(root, agentsBytes, routerBytes, outpu
3399
3811
  for (let index = headerIndexes[0] + 2; index < lines.length && lines[index].startsWith("|"); index += 1) {
3400
3812
  const cells = lines[index].split("|").slice(1, -1).map((cell) => cell.trim());
3401
3813
  if (cells.length !== 3) throw new Error("RULE_PACKS.md has an invalid active routing row");
3402
- const targets = [...cells[1].matchAll(/`([^`\r\n]+)`/g)].map((match) => match[1].trim()).filter(Boolean);
3403
- 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;
3404
3818
  for (const targetRel of targets) {
3405
3819
  const bytes = outputByTarget?.get(targetRel)?.after ?? await readRuntimeAcceptanceBytes(root, targetRel);
3406
3820
  routes.push(Object.freeze({
@@ -3412,7 +3826,7 @@ async function directRulePacksEntryWitness(root, agentsBytes, routerBytes, outpu
3412
3826
  }));
3413
3827
  }
3414
3828
  }
3415
- 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");
3416
3830
  return Object.freeze({
3417
3831
  reader: "AGENTS.md",
3418
3832
  via: "direct-rule-packs-entry",
@@ -3764,7 +4178,7 @@ async function hasActiveTransactionLock(root) {
3764
4178
  }
3765
4179
  }
3766
4180
 
3767
- async function loadCommittedCurrentStateWitness(root) {
4181
+ async function loadCommittedCurrentStateWitness(root, options = {}) {
3768
4182
  const migrationsRoot = path.join(root, "dev", "governance_migrations");
3769
4183
  let names;
3770
4184
  try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") return null; throw error; }
@@ -3779,7 +4193,10 @@ async function loadCommittedCurrentStateWitness(root) {
3779
4193
  if (journal.state !== "committed" || !journal.currentStateWitness) continue;
3780
4194
  await validateRecoveryJournal(root, journal, journalPath);
3781
4195
  const witness = validateCurrentStateWitness(journal);
3782
- 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 });
3783
4200
  } catch (error) {
3784
4201
  if (error?.code !== "ENOENT") throw error;
3785
4202
  }
@@ -3832,7 +4249,7 @@ async function hasCommittedSourceConservationAuthority(root) {
3832
4249
  const journal = JSON.parse(await readFile(journalPath, "utf8"));
3833
4250
  if (journal.state !== "committed" || !journal.currentStateWitness) continue;
3834
4251
  await validateRecoveryJournal(root, journal, journalPath);
3835
- 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) });
3836
4253
  } catch (error) {
3837
4254
  if (error?.code !== "ENOENT") throw error;
3838
4255
  }
@@ -3866,7 +4283,7 @@ async function assertUnboundCurrentStateMayAttemptUpgradeRebind(root, cause) {
3866
4283
  const journal = JSON.parse(await readFile(journalPath, "utf8"));
3867
4284
  if (journal.state !== "committed" || !journal.currentStateWitness) continue;
3868
4285
  await validateRecoveryJournal(root, journal, journalPath);
3869
- 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) });
3870
4287
  } catch (error) {
3871
4288
  if (error?.code !== "ENOENT") throw error;
3872
4289
  }
@@ -3882,12 +4299,10 @@ async function assertUnboundCurrentStateMayAttemptUpgradeRebind(root, cause) {
3882
4299
  }
3883
4300
 
3884
4301
  async function classifyCurrentStateRebindMismatches(projectRoot, journal) {
3885
- const mismatches = await currentStateMismatches(projectRoot, journal);
4302
+ const mismatches = await currentStateMismatches(projectRoot, journal, { allowHistoricalEdgeRetirement: true });
3886
4303
  const illegalNonCloseout = [];
3887
4304
  for (const mismatch of mismatches) {
3888
4305
  if (isCloseoutFinalizeTarget(mismatch.path)) continue;
3889
- if (mismatch.kind === "source-conservation"
3890
- && sourceConservationEntryMayRetireAsUnreachableRootSource(mismatch.sourceConservationEntry)) continue;
3891
4306
  if (await mismatchMatchesCurrentInstalledSource(projectRoot, mismatch)) continue;
3892
4307
  illegalNonCloseout.push(mismatch);
3893
4308
  }
@@ -3918,10 +4333,14 @@ async function findRestoredCurrentStateDigests(root, outputs, archiveMigrations
3918
4333
  if (journal.state !== "committed" || !journal.currentStateWitness) continue;
3919
4334
  await validateRecoveryJournal(root, journal, journalPath);
3920
4335
  const priorWitness = validateCurrentStateWitness(journal);
3921
- const sourceConservationRebind = sourceConservationEntriesRebindPrior(priorWitness, replacement.sourceConservation, archiveMigrations);
3922
- if ((await journalMatchesCurrentState(root, journal) && (!priorWitness.sourceConservation || sourceConservationRebind))
4336
+ const sourceConservationRebind = sourceConservationEntriesRebindPrior(priorWitness, replacement.sourceConservation, archiveMigrations, {
4337
+ allowArchiveState: sourceConservationHasArchiveReconciliation(priorWitness.sourceConservation)
4338
+ || sourceConservationHasArchiveReconciliation(replacement.sourceConservation)
4339
+ });
4340
+ if (sourceConservationRebind
4341
+ || (await journalMatchesCurrentState(root, journal) && (!priorWitness.sourceConservation || sourceConservationRebind))
3923
4342
  || await journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations, replacement.sourceConservation)
3924
- || sourceConservationRebind) {
4343
+ ) {
3925
4344
  if (!canSupersedeCurrentStateWitness(replacement, priorWitness)) continue;
3926
4345
  restored.push(journal.currentStateWitness.currentStateDigest);
3927
4346
  }
@@ -3942,24 +4361,64 @@ function currentStateWitnessCapability(value = {}) {
3942
4361
  function canSupersedeCurrentStateWitness(replacement, priorWitness) {
3943
4362
  const replacementCapability = currentStateWitnessCapability(replacement);
3944
4363
  if (priorWitness.sourceConservation && !replacementCapability.sourceConservation) return false;
4364
+ const archiveAuthority = sourceConservationHasArchiveReconciliation(replacement.sourceConservation)
4365
+ || sourceConservationHasArchiveReconciliation(priorWitness.sourceConservation);
3945
4366
  if (Array.isArray(priorWitness.archiveMigrations) && priorWitness.archiveMigrations.length > 0
3946
4367
  && !replacementCapability.archiveMigrations
3947
- && !archiveMigrationHistoryIsRebound(priorWitness, replacement.sourceConservation)) {
4368
+ && !sourceConservationEntriesRebindPrior(priorWitness, replacement.sourceConservation, [], { allowArchiveState: archiveAuthority })
4369
+ && !(archiveAuthority && archiveMigrationHistoryIsRebound(priorWitness, replacement.sourceConservation))) {
3948
4370
  return false;
3949
4371
  }
3950
4372
  return true;
3951
4373
  }
3952
4374
 
3953
- function sourceConservationEntryMayRetireAsUnreachableRootSource(entry) {
3954
- return Boolean(entry
3955
- && Array.isArray(entry.classifications)
3956
- && entry.classifications.length === 1
3957
- && entry.classifications[0] === "root-source"
3958
- && entry.disposition === "outside-known-kit-reachability"
3959
- && Array.isArray(entry.existingReaders)
3960
- && entry.existingReaders.length === 0
4375
+ function sourceConservationHasArchiveReconciliation(sourceConservation) {
4376
+ return Boolean(sourceConservation?.entries?.some((entry) => entry.disposition === "session-log-archive-reconciliation"));
4377
+ }
4378
+
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"
3961
4402
  && entry.priorityRelation === "outside-known-kit-reachability"
3962
- && 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));
3963
4422
  }
3964
4423
 
3965
4424
  function sourceConservationEntryAcceptedMatches(entry, accepted) {
@@ -3975,7 +4434,7 @@ function sourceConservationEntryHasAcceptedCoverage(entry) {
3975
4434
  && Number.isInteger(entry.accepted.bytes));
3976
4435
  }
3977
4436
 
3978
- function sourceConservationEntriesRebindPrior(priorWitness, replacementSourceConservation, archiveMigrations = []) {
4437
+ function sourceConservationEntriesRebindPrior(priorWitness, replacementSourceConservation, archiveMigrations = [], options = {}) {
3979
4438
  if (!priorWitness.sourceConservation) return true;
3980
4439
  if (!replacementSourceConservation) return false;
3981
4440
  const replacementByPath = new Map(replacementSourceConservation.entries.map((entry) => [entry.sourcePath, entry]));
@@ -3986,8 +4445,12 @@ function sourceConservationEntriesRebindPrior(priorWitness, replacementSourceCon
3986
4445
  }
3987
4446
  }
3988
4447
  return priorWitness.sourceConservation.entries.every((entry) => {
3989
- if (sourceConservationEntryMayRetireAsUnreachableRootSource(entry)) return true;
4448
+ const archiveState = sourceConservationEntryIsSessionLogArchive(entry)
4449
+ || isSessionLogArchivePath(entry.sourcePath)
4450
+ || (entry.sourceOriginPath && isSessionLogArchivePath(entry.sourceOriginPath));
4451
+ if (archiveState && options.allowArchiveState !== true) return false;
3990
4452
  const replacement = replacementByPath.get(entry.sourcePath);
4453
+ if (canRetireHistoricalEdge(entry, replacement)) return true;
3991
4454
  if (sourceConservationEntryHasAcceptedCoverage(replacement)) return true;
3992
4455
  const reboundPath = archiveRebindings.get(entry.sourcePath);
3993
4456
  const rebound = reboundPath ? replacementByPath.get(reboundPath) : null;
@@ -4023,23 +4486,12 @@ function archiveMigrationHistoryIsRebound(priorWitness, replacementSourceConserv
4023
4486
  }
4024
4487
  }
4025
4488
  }
4026
- return sourceConservationEntriesRebindPrior(priorWitness, replacementSourceConservation);
4489
+ return sourceConservationEntriesRebindPrior(priorWitness, replacementSourceConservation, [], { allowArchiveState: true });
4027
4490
  }
4028
4491
 
4029
4492
  async function journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations = [], replacementSourceConservation = null) {
4030
4493
  const witness = validateCurrentStateWitness(journal);
4031
4494
  const replacementByPath = new Map((replacementSourceConservation?.entries ?? []).map((entry) => [entry.sourcePath, entry]));
4032
- const archiveRebindings = new Map();
4033
- for (const migration of archiveMigrations) {
4034
- for (const file of migration.snapshot.files) {
4035
- archiveRebindings.set(`${migration.originalRel}/${file.path}`, {
4036
- sourcePath: `${migration.originalRel}/${file.path}`,
4037
- reboundPath: `${migration.canonicalRel}/${file.path}`,
4038
- sha256: file.sha256,
4039
- bytes: file.bytes
4040
- });
4041
- }
4042
- }
4043
4495
  for (const entry of journal.entries) {
4044
4496
  const replacement = outputWitnesses.get(entry.targetRel);
4045
4497
  if (replacement) {
@@ -4060,12 +4512,8 @@ async function journalIsRestoredByOutputs(root, journal, outputWitnesses, archiv
4060
4512
  if (!sourceConservationEntryHasAcceptedCoverage(sourceReplacement)) return false;
4061
4513
  continue;
4062
4514
  }
4063
- const archiveRebinding = archiveRebindings.get(entry.sourcePath);
4064
- if (archiveRebinding) {
4065
- if (archiveRebinding.sha256 !== entry.accepted.sha256 || archiveRebinding.bytes !== entry.accepted.bytes) return false;
4066
- continue;
4067
- }
4068
- if (!sourceConservationEntryMayRetireAsUnreachableRootSource(entry)) return false;
4515
+ if (sourceConservationEntryIsSessionLogArchive(entry) || isSessionLogArchivePath(entry.sourcePath)) return false;
4516
+ if (canRetireHistoricalEdge(entry, sourceReplacement)) continue;
4069
4517
  const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
4070
4518
  if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) return false;
4071
4519
  }
@@ -4104,8 +4552,31 @@ async function checkCurrentStateWitness(root, witness) {
4104
4552
  }
4105
4553
  }
4106
4554
 
4107
- async function journalMatchesCurrentState(root, journal) {
4555
+ async function journalMatchesCurrentState(root, journal) {
4556
+ const witness = validateCurrentStateWitness(journal);
4557
+ const plan = journal.entries.map((entry) => ({
4558
+ action: "merge",
4559
+ targetRel: entry.targetRel,
4560
+ targetAbs: path.join(root, entry.targetRel)
4561
+ }));
4562
+ await validateTransactionRoot(root, plan, { createMissingRoot: false });
4563
+ for (const entry of journal.entries) {
4564
+ const bytes = await readOptionalBuffer(path.join(root, entry.targetRel));
4565
+ if (!bytes || sha256(bytes) !== entry.afterHash) return false;
4566
+ }
4567
+ for (const entry of witness.sourceConservation?.entries ?? []) {
4568
+ const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
4569
+ if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) return false;
4570
+ }
4571
+ return true;
4572
+ }
4573
+
4574
+ async function journalMatchesCurrentStateForHistoricalRebind(root, journal) {
4108
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]));
4109
4580
  const plan = journal.entries.map((entry) => ({
4110
4581
  action: "merge",
4111
4582
  targetRel: entry.targetRel,
@@ -4117,6 +4588,9 @@ async function journalMatchesCurrentState(root, journal) {
4117
4588
  if (!bytes || sha256(bytes) !== entry.afterHash) return false;
4118
4589
  }
4119
4590
  for (const entry of witness.sourceConservation?.entries ?? []) {
4591
+ if (canRetireHistoricalEdge(entry, currentTypedByPath.get(entry.sourcePath))) {
4592
+ continue;
4593
+ }
4120
4594
  const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
4121
4595
  if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) return false;
4122
4596
  }
@@ -4147,14 +4621,15 @@ async function findCloseoutFinalizeBase(root) {
4147
4621
  const records = [];
4148
4622
  for (const item of inspected) {
4149
4623
  const witness = validateCurrentStateWitness(item.journal);
4150
- const mismatches = await currentStateMismatches(root, item.journal);
4624
+ const isSuperseded = superseded.has(witness.currentStateDigest);
4625
+ const mismatches = await currentStateMismatches(root, item.journal, { allowHistoricalEdgeRetirement: isSuperseded });
4151
4626
  const closeoutOnly = mismatches.every((mismatch) => isCloseoutFinalizeTarget(mismatch.path));
4152
4627
  records.push({
4153
4628
  ...item,
4154
4629
  witness,
4155
4630
  mismatches,
4156
4631
  closeoutOnly,
4157
- isSuperseded: superseded.has(witness.currentStateDigest),
4632
+ isSuperseded,
4158
4633
  additionalSupersedes: []
4159
4634
  });
4160
4635
  }
@@ -4263,14 +4738,22 @@ function withAdditionalCloseoutSupersedes(base, current) {
4263
4738
  };
4264
4739
  }
4265
4740
 
4266
- async function currentStateMismatches(root, journal) {
4741
+ async function currentStateMismatches(root, journal, options = {}) {
4267
4742
  const witness = validateCurrentStateWitness(journal);
4268
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
+ }
4269
4751
  for (const entry of journal.entries) {
4270
4752
  const bytes = await readOptionalBuffer(path.join(root, entry.targetRel));
4271
4753
  if (!bytes || sha256(bytes) !== entry.afterHash) mismatches.set(entry.targetRel, { path: entry.targetRel, kind: "transaction-entry" });
4272
4754
  }
4273
4755
  for (const entry of witness.sourceConservation?.entries ?? []) {
4756
+ if (options.allowHistoricalEdgeRetirement === true && canRetireHistoricalEdge(entry, currentTypedByPath.get(entry.sourcePath))) continue;
4274
4757
  const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
4275
4758
  if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) {
4276
4759
  mismatches.set(entry.sourcePath, { path: entry.sourcePath, kind: "source-conservation", sourceConservationEntry: entry });
@@ -4278,8 +4761,6 @@ async function currentStateMismatches(root, journal) {
4278
4761
  }
4279
4762
  if (witness.sourceConservation) {
4280
4763
  const conserved = new Set(witness.sourceConservation.entries.map((entry) => entry.sourcePath));
4281
- const currentFrozen = await freezeGate5Set({ root });
4282
- assertGate5FrozenSet(currentFrozen);
4283
4764
  for (const item of gate5SourceConservationItems(currentFrozen)) {
4284
4765
  if (conserved.has(item.sourcePath) || isFinalizeJournalState(item.sourcePath)) continue;
4285
4766
  mismatches.set(item.sourcePath, { path: item.sourcePath, kind: "new-source" });
@@ -4288,6 +4769,439 @@ async function currentStateMismatches(root, journal) {
4288
4769
  return [...mismatches.values()].sort((left, right) => left.path.localeCompare(right.path));
4289
4770
  }
4290
4771
 
4772
+ async function findCurrentStateReconciliationBase(root, version) {
4773
+ const migrationsRoot = path.join(root, "dev", "governance_migrations");
4774
+ let names;
4775
+ try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") return null; throw error; }
4776
+ const records = [];
4777
+ const superseded = new Set();
4778
+ for (const name of names) {
4779
+ if (name === ".upgrade.lock") continue;
4780
+ const journalPath = path.join(migrationsRoot, name, "transaction.json");
4781
+ try {
4782
+ const stats = await lstat(journalPath);
4783
+ if (!stats.isFile() || stats.isSymbolicLink()) continue;
4784
+ const journal = JSON.parse(await readFile(journalPath, "utf8"));
4785
+ if (journal.state !== "committed" || !journal.currentStateWitness) continue;
4786
+ await validateRecoveryJournal(root, journal, journalPath);
4787
+ const witness = validateCurrentStateWitness(journal);
4788
+ for (const digest of witness.transaction.supersedesCurrentStateDigests ?? []) superseded.add(digest);
4789
+ records.push({ journal, journalPath, witness, matches: await journalMatchesCurrentState(root, journal) });
4790
+ } catch (error) {
4791
+ if (error?.code !== "ENOENT") throw error;
4792
+ }
4793
+ }
4794
+ const stale = records
4795
+ .filter((record) => !record.matches && record.witness.sourceConservation && !superseded.has(record.witness.currentStateDigest));
4796
+ if (stale.length === 0) return null;
4797
+ if (stale.length > 1) {
4798
+ const digests = stale.map((record) => record.witness.currentStateDigest).join(", ");
4799
+ throw new Error(`current-state reconciliation refuses ambiguous stale source-conservation authorities: ${digests}`);
4800
+ }
4801
+ const currentFrozen = await freezeGate5Set({ root });
4802
+ assertGate5FrozenSet(currentFrozen);
4803
+ const classified = await classifyCurrentStateReconciliationMismatches(root, stale[0].journal, currentFrozen);
4804
+ const candidate = { ...stale[0], currentFrozen, ...classified };
4805
+ if (candidate.illegal.length > 0 || candidate.reconcilable.length === 0) return candidate;
4806
+ return await createCurrentStateReconciliationVerifiedPlan(root, version, candidate);
4807
+ }
4808
+
4809
+ async function classifyCurrentStateReconciliationMismatches(root, journal, currentFrozen) {
4810
+ const currentByPath = new Map(gate5SourceConservationItems(currentFrozen).map((item) => [item.sourcePath, item]));
4811
+ const mismatches = await currentStateMismatches(root, journal);
4812
+ const reconcilable = [];
4813
+ const archive = [];
4814
+ const illegal = [];
4815
+ const archiveQualification = await qualifySessionLogArchive(root, currentFrozen);
4816
+ for (const mismatch of mismatches) {
4817
+ if (isCloseoutFinalizeTarget(mismatch.path)) {
4818
+ reconcilable.push({ ...mismatch, reason: "legal closeout state readback" });
4819
+ continue;
4820
+ }
4821
+ if (mismatchIsSessionLogArchiveDelta(mismatch, currentByPath.get(mismatch.path))) {
4822
+ if (archiveQualification.ok) {
4823
+ archive.push({ ...mismatch, reason: "qualified session-log archive maintenance readback" });
4824
+ } else {
4825
+ illegal.push({ ...mismatch, reason: archiveQualification.reason });
4826
+ }
4827
+ continue;
4828
+ }
4829
+ illegal.push({ ...mismatch, reason: currentStateReconciliationBlockReason(mismatch, currentByPath.get(mismatch.path)) });
4830
+ }
4831
+ return {
4832
+ mismatches,
4833
+ currentByPath,
4834
+ archive,
4835
+ archiveQualification,
4836
+ reconcilable: [...reconcilable, ...archive].sort((left, right) => left.path.localeCompare(right.path)),
4837
+ illegal
4838
+ };
4839
+ }
4840
+
4841
+ function mismatchIsSessionLogArchiveDelta(mismatch, currentItem) {
4842
+ return Boolean(isSessionLogArchivePath(mismatch.path)
4843
+ || sourceConservationEntryIsSessionLogArchive(mismatch.sourceConservationEntry)
4844
+ || (currentItem?.classifications ?? []).some((classification) => ["session-log-archive", "legacy-session-log-archive"].includes(classification)));
4845
+ }
4846
+
4847
+ async function qualifySessionLogArchive(root, currentFrozen) {
4848
+ const archiveCasing = await checkSessionLogArchiveCasing(root);
4849
+ if (!archiveCasing.ok) return { ok: false, reason: archiveCasing.finding, inventory: null };
4850
+ const archiveRoot = path.join(root, canonicalSessionLogArchiveRoot);
4851
+ const archiveStats = await lstat(archiveRoot).catch((error) => error?.code === "ENOENT" ? null : Promise.reject(error));
4852
+ if (!archiveStats) return { ok: false, reason: "canonical session-log archive root is missing", inventory: null };
4853
+ if (!archiveStats.isDirectory() || archiveStats.isSymbolicLink()) return { ok: false, reason: "canonical session-log archive root is not a safe real directory", inventory: null };
4854
+ const rootReal = await realpath(root);
4855
+ const archiveReal = await realpath(archiveRoot);
4856
+ if (!isInside(rootReal, archiveReal)) return { ok: false, reason: "canonical session-log archive root resolves outside selected root", inventory: null };
4857
+ const route = gate5SourceConservationItems(currentFrozen).find((item) => item.sourcePath === "dev/SESSION_LOG.md");
4858
+ if (!sessionLogCloseoutRouteIsTypedKitContract(route)) {
4859
+ return { ok: false, reason: "current non-archive SESSION_LOG closeout contract is not mechanically verifiable", inventory: null };
4860
+ }
4861
+ const inventory = await inventorySessionLogArchiveTree(root, archiveRoot, archiveReal);
4862
+ const index = inventory.files.find((file) => file.path === "INDEX.md");
4863
+ if (!index) return { ok: false, reason: "session-log archive INDEX.md is missing", inventory };
4864
+ const indexText = await readFile(path.join(archiveRoot, "INDEX.md"), "utf8");
4865
+ const listed = extractArchiveIndexBatchList(indexText);
4866
+ if (listed.includes("INDEX.md")) return { ok: false, reason: "session-log archive INDEX.md must not self-reference", inventory };
4867
+ const duplicates = listed.filter((item, indexOfItem) => listed.indexOf(item) !== indexOfItem);
4868
+ if (duplicates.length > 0) return { ok: false, reason: `session-log archive INDEX.md has duplicate archive entries: ${[...new Set(duplicates)].join(", ")}`, inventory };
4869
+ const actualArchiveItems = inventory.files
4870
+ .map((file) => file.path)
4871
+ .filter((filePath) => filePath !== "INDEX.md")
4872
+ .sort((left, right) => left.localeCompare(right));
4873
+ const listedSorted = [...listed].sort((left, right) => left.localeCompare(right));
4874
+ if (JSON.stringify(actualArchiveItems) !== JSON.stringify(listedSorted)) {
4875
+ return {
4876
+ ok: false,
4877
+ reason: `session-log archive INDEX/list mismatch: listed=${listedSorted.join(", ") || "none"} actual=${actualArchiveItems.join(", ") || "none"}`,
4878
+ inventory
4879
+ };
4880
+ }
4881
+ return {
4882
+ ok: true,
4883
+ reason: "canonical session-log archive inventory and INDEX are bidirectionally verified",
4884
+ inventory: {
4885
+ ...inventory,
4886
+ indexSha256: index.sha256,
4887
+ listedArchiveItems: listedSorted,
4888
+ inventorySha256: sha256(Buffer.from(`${JSON.stringify({
4889
+ root: canonicalSessionLogArchiveRoot,
4890
+ directories: inventory.directories,
4891
+ files: inventory.files,
4892
+ listedArchiveItems: listedSorted
4893
+ })}\n`, "utf8"))
4894
+ }
4895
+ };
4896
+ }
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
+
4907
+ async function inventorySessionLogArchiveTree(root, archiveRoot, archiveReal) {
4908
+ const directories = [];
4909
+ const files = [];
4910
+ async function visit(currentAbs, relative) {
4911
+ const entries = await readdir(currentAbs, { withFileTypes: true });
4912
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
4913
+ const childAbs = path.join(currentAbs, entry.name);
4914
+ const childRel = relative ? `${relative}/${entry.name}` : entry.name;
4915
+ const stats = await lstat(childAbs);
4916
+ if (stats.isSymbolicLink()) throw new Error(`${canonicalSessionLogArchiveRoot}/${childRel}: archive qualification rejects symbolic links, junctions, and reparse points`);
4917
+ const childReal = await realpath(childAbs);
4918
+ if (!isInside(archiveReal, childReal) || !isInside(root, childReal)) {
4919
+ throw new Error(`${canonicalSessionLogArchiveRoot}/${childRel}: archive item resolves outside the canonical archive root`);
4920
+ }
4921
+ if (stats.isDirectory()) {
4922
+ directories.push(childRel);
4923
+ await visit(childAbs, childRel);
4924
+ } else if (stats.isFile()) {
4925
+ const bytes = await readFile(childAbs);
4926
+ files.push({ path: childRel, sha256: sha256(bytes), bytes: bytes.length });
4927
+ } else {
4928
+ throw new Error(`${canonicalSessionLogArchiveRoot}/${childRel}: archive qualification accepts only regular files and directories`);
4929
+ }
4930
+ }
4931
+ }
4932
+ await visit(archiveRoot, "");
4933
+ return {
4934
+ root: canonicalSessionLogArchiveRoot,
4935
+ directories: directories.sort((left, right) => left.localeCompare(right)),
4936
+ files: files.sort((left, right) => left.path.localeCompare(right.path))
4937
+ };
4938
+ }
4939
+
4940
+ function extractArchiveIndexBatchList(indexText) {
4941
+ const matches = [...indexText.matchAll(/\b([A-Za-z0-9._-]*archive[A-Za-z0-9._-]*\.md)\b/gu)]
4942
+ .map((match) => match[1])
4943
+ .filter((name) => !name.includes("/") && !name.includes("\\"));
4944
+ return matches.sort((left, right) => left.localeCompare(right));
4945
+ }
4946
+
4947
+ async function createCurrentStateReconciliationVerifiedPlan(root, version, candidate) {
4948
+ const rootReal = await realpath(root);
4949
+ const activeWitness = validateCurrentStateWitness(candidate.journal);
4950
+ const currentByPath = new Map(gate5SourceConservationItems(candidate.currentFrozen).map((item) => [item.sourcePath, item]));
4951
+ const transactionEntries = [];
4952
+ for (const entry of activeWitness.entries) {
4953
+ const current = await readOptionalBuffer(path.join(root, entry.targetRel));
4954
+ if (!current) throw new Error(`${entry.targetRel}: cannot reconcile missing transaction target`);
4955
+ const witness = { sha256: sha256(current), bytes: current.length };
4956
+ transactionEntries.push({
4957
+ targetRel: entry.targetRel,
4958
+ existed: true,
4959
+ beforeHash: witness.sha256,
4960
+ afterHash: witness.sha256,
4961
+ backupRel: null,
4962
+ committed: false,
4963
+ witness
4964
+ });
4965
+ }
4966
+ const archiveReconcilePaths = new Set((candidate.archive ?? []).map((item) => item.path));
4967
+ const oldSourceByPath = new Map((activeWitness.sourceConservation?.entries ?? []).map((entry) => [entry.sourcePath, entry]));
4968
+ const sourceEntries = [];
4969
+ for (const item of gate5SourceConservationItems(candidate.currentFrozen).filter((entry) => !isFinalizeJournalState(entry.sourcePath))) {
4970
+ const entry = oldSourceByPath.get(item.sourcePath) ?? null;
4971
+ const current = await readOptionalBuffer(path.join(root, item.sourcePath));
4972
+ if (!current) throw new Error(`${item.sourcePath}: cannot reconcile missing source`);
4973
+ const currentWitness = { sha256: sha256(current), bytes: current.length };
4974
+ const priorAccepted = entry?.accepted ?? currentWitness;
4975
+ const changedFromPrior = currentWitness.sha256 !== priorAccepted.sha256 || currentWitness.bytes !== priorAccepted.bytes;
4976
+ const disposition = isCloseoutFinalizeTarget(item.sourcePath) && changedFromPrior
4977
+ ? entry?.sourceOriginPath
4978
+ ? "canonical-path-migration-closeout"
4979
+ : "closeout-state-finalize"
4980
+ : archiveReconcilePaths.has(item.sourcePath)
4981
+ ? "session-log-archive-reconciliation"
4982
+ : entry?.disposition ?? (item.classifications.includes("transaction-state") ? "retained-historical-state" : "unchanged-source");
4983
+ sourceEntries.push({
4984
+ sourcePath: item.sourcePath,
4985
+ ...(entry?.sourceOriginPath && ["canonical-path-migration", "canonical-path-migration-closeout", "session-log-archive-reconciliation"].includes(disposition) ? { sourceOriginPath: entry.sourceOriginPath } : {}),
4986
+ sourceWitness: currentWitness,
4987
+ accepted: currentWitness,
4988
+ sourceByteRanges: [{ start: 0, end: currentWitness.bytes, sha256: currentWitness.sha256 }],
4989
+ disposition,
4990
+ existingReaders: entry?.existingReaders ?? item.existingReaders.map((reader) => ({ reader: reader.reader, via: reader.via })),
4991
+ priorityRelation: entry?.priorityRelation ?? item.priorityConflict.relation,
4992
+ effectDecision: entry?.effectDecision ?? item.effect.decision,
4993
+ classifications: entry?.classifications ?? [...item.classifications]
4994
+ });
4995
+ }
4996
+ const deltas = [];
4997
+ for (const item of candidate.reconcilable) {
4998
+ const prior = item.sourceConservationEntry?.accepted ?? null;
4999
+ const currentWitness = sourceEntries.find((entry) => entry.sourcePath === item.path)?.accepted
5000
+ ?? transactionEntries.find((entry) => entry.targetRel === item.path)?.witness
5001
+ ?? { missing: true };
5002
+ const currentItem = currentByPath.get(item.path) ?? null;
5003
+ deltas.push({
5004
+ path: item.path,
5005
+ kind: item.kind,
5006
+ prior: prior ?? { missing: true },
5007
+ current: currentWitness,
5008
+ classification: currentItem?.classifications ?? item.sourceConservationEntry?.classifications ?? [],
5009
+ existingReaders: currentItem?.existingReaders ?? item.sourceConservationEntry?.existingReaders ?? [],
5010
+ priorityRelation: currentItem?.priorityConflict?.relation ?? item.sourceConservationEntry?.priorityRelation ?? null,
5011
+ effectDecision: currentItem?.effect?.decision ?? item.sourceConservationEntry?.effectDecision ?? null,
5012
+ reason: item.reason,
5013
+ authority: mismatchIsSessionLogArchiveDelta(item, currentItem) ? "session-log-archive-qualification" : "legal-closeout-state-finalize",
5014
+ archiveQualification: mismatchIsSessionLogArchiveDelta(item, currentItem)
5015
+ ? {
5016
+ ok: candidate.archiveQualification.ok,
5017
+ reason: candidate.archiveQualification.reason,
5018
+ inventorySha256: candidate.archiveQualification.inventory?.inventorySha256 ?? null
5019
+ }
5020
+ : null
5021
+ });
5022
+ }
5023
+ const manifest = {
5024
+ schemaVersion: 1,
5025
+ command: "reconcile-current-state",
5026
+ root: {
5027
+ selected: path.resolve(root),
5028
+ realpath: rootReal
5029
+ },
5030
+ toolVersion: version,
5031
+ activeWitness: {
5032
+ digest: activeWitness.currentStateDigest,
5033
+ command: activeWitness.transaction.command,
5034
+ attemptedVersion: activeWitness.transaction.attemptedVersion,
5035
+ schemaVersion: activeWitness.schemaVersion
5036
+ },
5037
+ supersededWitnessDigests: activeWitness.transaction.supersedesCurrentStateDigests ?? [],
5038
+ directCloseoutStateTargets,
5039
+ archiveInventory: candidate.archiveQualification.inventory
5040
+ ? {
5041
+ root: canonicalSessionLogArchiveRoot,
5042
+ inventorySha256: candidate.archiveQualification.inventory.inventorySha256,
5043
+ indexSha256: candidate.archiveQualification.inventory.indexSha256,
5044
+ files: candidate.archiveQualification.inventory.files,
5045
+ directories: candidate.archiveQualification.inventory.directories,
5046
+ listedArchiveItems: candidate.archiveQualification.inventory.listedArchiveItems
5047
+ }
5048
+ : null,
5049
+ archiveQualification: {
5050
+ ok: candidate.archiveQualification.ok,
5051
+ reason: candidate.archiveQualification.reason
5052
+ },
5053
+ deltas: deltas.sort((left, right) => left.path.localeCompare(right.path))
5054
+ };
5055
+ return {
5056
+ ...candidate,
5057
+ transactionEntries,
5058
+ sourceConservation: {
5059
+ schemaVersion: activeWitness.sourceConservation.schemaVersion,
5060
+ frozenSetSha256: candidate.currentFrozen.frozenSetSha256,
5061
+ entries: sourceEntries.sort((left, right) => left.sourcePath.localeCompare(right.sourcePath))
5062
+ },
5063
+ manifest,
5064
+ manifestSha256: sha256(Buffer.from(`${JSON.stringify(manifest)}\n`, "utf8"))
5065
+ };
5066
+ }
5067
+
5068
+ async function assertCurrentStateReconciliationVerifiedPlanStillCurrent(root, plan) {
5069
+ const activeWitness = validateCurrentStateWitness(plan.journal);
5070
+ if (activeWitness.currentStateDigest !== plan.manifest.activeWitness.digest) {
5071
+ throw new Error("current-state reconciliation active witness changed before writes; no files written");
5072
+ }
5073
+ for (const entry of plan.transactionEntries) {
5074
+ const current = await readOptionalBuffer(path.join(root, entry.targetRel));
5075
+ if (!current || sha256(current) !== entry.afterHash || current.length !== entry.witness.bytes) {
5076
+ throw new Error(`${entry.targetRel}: current-state reconciliation target changed before writes; no files written`);
5077
+ }
5078
+ }
5079
+ for (const entry of plan.sourceConservation.entries) {
5080
+ const current = await readOptionalBuffer(path.join(root, entry.sourcePath));
5081
+ if (!current || sha256(current) !== entry.accepted.sha256 || current.length !== entry.accepted.bytes) {
5082
+ throw new Error(`${entry.sourcePath}: current-state reconciliation source changed before writes; no files written`);
5083
+ }
5084
+ }
5085
+ }
5086
+
5087
+ function currentStateReconciliationBlockReason(mismatch, currentItem) {
5088
+ if (mismatch.kind === "transaction-entry") return "transaction entry is not a legal closeout target";
5089
+ if (installedFileContract(mismatch.path)) return "installed Kit contract remains fail-closed";
5090
+ if (isSessionLogArchivePath(mismatch.path)
5091
+ || sourceConservationEntryIsSessionLogArchive(mismatch.sourceConservationEntry)
5092
+ || currentItem?.classifications?.some((classification) => ["session-log-archive", "legacy-session-log-archive"].includes(classification))) {
5093
+ return "session-log archive state remains fail-closed until the canonical archive group qualifies";
5094
+ }
5095
+ if (currentItem?.classifications?.some((classification) => ["managed-contract", "transaction-state", "legacy-session-log-archive", "session-log-archive"].includes(classification))) {
5096
+ return "Kit-managed, transaction, or archive state remains fail-closed";
5097
+ }
5098
+ return "not a legal closeout or qualified session-log archive reconciliation entry";
5099
+ }
5100
+
5101
+ async function writeCurrentStateReconciliationJournal(root, version, candidate, options = {}) {
5102
+ const command = "reconcile-current-state";
5103
+ const mode = "source-state-reconciliation";
5104
+ const oldWitness = validateCurrentStateWitness(candidate.journal);
5105
+ const retainedArchiveMigrations = oldWitness.archiveMigrations ?? [];
5106
+ const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}`;
5107
+ const migrationsRoot = path.join(root, "dev", "governance_migrations");
5108
+ const migrationDir = path.join(migrationsRoot, id);
5109
+ const journalPath = path.join(migrationDir, "transaction.json");
5110
+ const lockPath = path.join(migrationsRoot, ".upgrade.lock");
5111
+ await mkdir(migrationDir, { recursive: true });
5112
+ await tightenPermissions(migrationsRoot, 0o700);
5113
+ await tightenPermissions(migrationDir, 0o700);
5114
+
5115
+ let journal = null;
5116
+ let lockCreated = false;
5117
+ let durableJournalPhase = null;
5118
+ try {
5119
+ journal = {
5120
+ id,
5121
+ command,
5122
+ mode,
5123
+ attemptedVersion: version,
5124
+ committedVersion: null,
5125
+ plannedSkips: 0,
5126
+ host: hostname(),
5127
+ pid: process.pid,
5128
+ state: "prepared",
5129
+ createdAt: new Date().toISOString(),
5130
+ committedAt: null,
5131
+ entries: candidate.transactionEntries.map(({ witness, ...entry }) => ({ ...entry })),
5132
+ formalUserRules: null,
5133
+ runtimeReadback: null,
5134
+ runtimeAcceptance: null,
5135
+ runtimeAcceptanceReadback: null,
5136
+ sourceConservation: candidate.sourceConservation,
5137
+ archiveMigrations: [],
5138
+ supersedesCurrentStateDigests: [oldWitness.currentStateDigest],
5139
+ currentStateWitness: null,
5140
+ currentStateReadback: null,
5141
+ reconciliationManifest: candidate.manifest,
5142
+ reconciliationManifestSha256: candidate.manifestSha256
5143
+ };
5144
+ await writeSecureJson(journalPath, journal);
5145
+ durableJournalPhase = "prepared";
5146
+ if (process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_RECONCILE_PREPARED_JOURNAL === "1") {
5147
+ throw new Error("QA generic failure after reconcile prepared journal");
5148
+ }
5149
+
5150
+ if (process.env.AGENT_HANDOFF_KIT_QA_CREATE_FOREIGN_RECONCILE_LOCK_BEFORE_LOCK === "1") {
5151
+ await publishTransactionLock(root, lockPath, {
5152
+ id: `qa-owner-${id}`,
5153
+ host: hostname(),
5154
+ pid: process.pid,
5155
+ journal: path.relative(root, journalPath),
5156
+ command: "qa-owner-lock"
5157
+ });
5158
+ }
5159
+ await publishTransactionLock(root, lockPath, { id, host: hostname(), pid: process.pid, journal: path.relative(root, journalPath), command });
5160
+ lockCreated = true;
5161
+ if (process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_RECONCILE_LOCK === "1"
5162
+ || process.env.AGENT_HANDOFF_KIT_QA_INTERRUPT_AFTER_RECONCILE_LOCK === "1") {
5163
+ throw new Error("QA generic failure after reconcile lock with prepared journal");
5164
+ }
5165
+
5166
+ journal.entries = journal.entries.map((entry) => ({ ...entry, committed: true }));
5167
+ journal.state = "committed";
5168
+ journal.committedVersion = version;
5169
+ journal.committedAt = new Date().toISOString();
5170
+ journal.archiveMigrations = retainedArchiveMigrations;
5171
+ journal.currentStateWitness = createCurrentStateWitness(journal);
5172
+ await writeSecureJson(journalPath, journal);
5173
+ durableJournalPhase = "committed";
5174
+ if (process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_RECONCILE_COMMITTED_JOURNAL === "1"
5175
+ || process.env.AGENT_HANDOFF_KIT_QA_INTERRUPT_AFTER_RECONCILE_JOURNAL_COMMIT === "1") {
5176
+ throw new Error("QA generic failure after committed reconcile journal");
5177
+ }
5178
+ if (!await journalMatchesCurrentState(root, journal)) {
5179
+ throw new Error("post-reconciliation current-state readback failed; reconciliation journal retained for inspection");
5180
+ }
5181
+ journal.currentStateReadback = currentStateReadbackFromVerifiedProjectBytes(journal.currentStateWitness);
5182
+ await writeSecureJson(journalPath, journal);
5183
+ await writeCurrentStateReconciliationReport({ root, migrationDir, journal, reconciledPaths: candidate.reconcilable.map((item) => item.path) });
5184
+ if (process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_RECONCILE_REPORT === "1") {
5185
+ throw new Error("QA generic failure after reconcile report");
5186
+ }
5187
+ if (process.env.AGENT_HANDOFF_KIT_QA_FAIL_BEFORE_RECONCILE_UNLOCK === "1") {
5188
+ throw new Error("QA generic failure before reconcile unlock");
5189
+ }
5190
+ await unlinkIfExists(lockPath);
5191
+ lockCreated = false;
5192
+ return { journalPath, journal };
5193
+ } catch (error) {
5194
+ if (lockCreated && durableJournalPhase) throw error;
5195
+ if (!lockCreated && durableJournalPhase === "prepared" && journal) {
5196
+ journal.state = "rolled-back";
5197
+ journal.rollbackAt = new Date().toISOString();
5198
+ journal.recoveryConflicts = [];
5199
+ await writeSecureJson(journalPath, journal).catch(() => {});
5200
+ }
5201
+ throw error;
5202
+ }
5203
+ }
5204
+
4291
5205
  async function writeCloseoutFinalizeJournal(root, version, prior) {
4292
5206
  const oldWitness = validateCurrentStateWitness(prior.journal);
4293
5207
  const supersedesCurrentStateDigests = [...new Set([
@@ -4305,12 +5219,7 @@ async function writeCloseoutFinalizeJournal(root, version, prior) {
4305
5219
  await mkdir(stageDir, { recursive: true });
4306
5220
  await tightenPermissions(migrationsRoot, 0o700);
4307
5221
  await tightenPermissions(migrationDir, 0o700);
4308
- const lock = await open(lockPath, "wx", 0o600).catch((error) => {
4309
- if (error?.code === "EEXIST") throw new Error("another upgrade transaction or unresolved recovery lock is present");
4310
- throw error;
4311
- });
4312
- await lock.writeFile(JSON.stringify({ id, host: hostname(), pid: process.pid, journal: path.relative(root, journalPath), command: "finalize-closeout" }, null, 2));
4313
- await lock.close();
5222
+ await publishTransactionLock(root, lockPath, { id, host: hostname(), pid: process.pid, journal: path.relative(root, journalPath), command: "finalize-closeout" });
4314
5223
 
4315
5224
  try {
4316
5225
  const priorEntryByTarget = new Map(prior.journal.entries.map((entry) => [entry.targetRel, entry]));
@@ -4430,13 +5339,26 @@ async function writeJournalFile(base, targetRel, bytes) {
4430
5339
  }
4431
5340
 
4432
5341
  function isCloseoutFinalizeTarget(relative) {
4433
- return closeoutFinalizeTargets.has(relative) || relative.startsWith("dev/SESSION_LOG_archive/");
5342
+ return directCloseoutStateTargetSet.has(relative);
4434
5343
  }
4435
5344
 
4436
5345
  function isFinalizeJournalState(relative) {
4437
5346
  return relative.startsWith("dev/governance_migrations/");
4438
5347
  }
4439
5348
 
5349
+ function isSessionLogArchivePath(relative) {
5350
+ return relative === canonicalSessionLogArchiveRoot
5351
+ || relative.startsWith(`${canonicalSessionLogArchiveRoot}/`)
5352
+ || relative === legacySessionLogArchiveRoot
5353
+ || relative.startsWith(`${legacySessionLogArchiveRoot}/`);
5354
+ }
5355
+
5356
+ function sourceConservationEntryIsSessionLogArchive(entry) {
5357
+ return Boolean(entry
5358
+ && Array.isArray(entry.classifications)
5359
+ && entry.classifications.some((classification) => ["session-log-archive", "legacy-session-log-archive"].includes(classification)));
5360
+ }
5361
+
4440
5362
  async function checkRuntimeAcceptance(root, options = {}) {
4441
5363
  const witness = options.expectedRuntimeAcceptance ?? null;
4442
5364
  if (!witness) return { ok: true, checked: 0, finding: null, state: null };
@@ -4499,16 +5421,32 @@ function currentStateReadbackFromDoctorStates(witness, formalState, runtimeAccep
4499
5421
  };
4500
5422
  }
4501
5423
 
4502
- function validateCurrentStateReadback(value, witness) {
5424
+ function currentStateReadbackFromVerifiedProjectBytes(witness) {
5425
+ const accepted = validateCurrentStateWitnessValue(witness);
5426
+ return {
5427
+ reader: "current-state project byte readback",
5428
+ currentStateDigest: accepted.currentStateDigest,
5429
+ sourceConservationEntryCount: accepted.sourceConservation?.entries.length ?? 0,
5430
+ formalUserRulesAcceptanceDigest: accepted.formalUserRules?.acceptanceDigest ?? null,
5431
+ runtimeAcceptanceDigest: accepted.runtimeAcceptance?.acceptanceDigest ?? null,
5432
+ formalUserRules: null,
5433
+ runtimeAcceptance: null
5434
+ };
5435
+ }
5436
+
5437
+ function validateCurrentStateReadback(value, witness, options = {}) {
4503
5438
  if (value == null) return null;
5439
+ const projectByteReaderAllowed = options.allowProjectByteReader === true;
5440
+ const readerAllowed = value.reader === "doctor shared current-state witness check"
5441
+ || (projectByteReaderAllowed && value.reader === "current-state project byte readback");
4504
5442
  if (!value || typeof value !== "object" || Array.isArray(value)
4505
- || value.reader !== "doctor shared current-state witness check"
5443
+ || !readerAllowed
4506
5444
  || value.currentStateDigest !== witness.currentStateDigest
4507
5445
  || (witness.sourceConservation && value.sourceConservationEntryCount !== witness.sourceConservation.entries.length)
4508
5446
  || (!witness.sourceConservation && value.sourceConservationEntryCount != null && value.sourceConservationEntryCount !== 0)
4509
5447
  || value.formalUserRulesAcceptanceDigest !== (witness.formalUserRules?.acceptanceDigest ?? null)
4510
5448
  || value.runtimeAcceptanceDigest !== (witness.runtimeAcceptance?.acceptanceDigest ?? null)) {
4511
- throw new Error("shared current-state doctor readback is detached from the accepted witness; no recovery writes attempted");
5449
+ throw new Error("shared current-state readback is detached from the accepted witness; no recovery writes attempted");
4512
5450
  }
4513
5451
  return value;
4514
5452
  }
@@ -4597,129 +5535,7 @@ async function checkResearchDecisionTrace(root) {
4597
5535
  return { ok: findings.length === 0, checked: 1, findings };
4598
5536
  }
4599
5537
 
4600
- async function checkGeneratedMarkdownGovernance(root) {
4601
- let indexText = "";
4602
- let logText = "";
4603
- let handoffText = "";
4604
- try {
4605
- indexText = await readFile(path.join(root, "dev/PROJECT_INDEX.md"), "utf8");
4606
- } catch {
4607
- return { ok: false, checked: 1, findings: ["dev/PROJECT_INDEX.md unreadable; cannot verify generated Markdown governance"] };
4608
- }
4609
- try {
4610
- logText = await readFile(path.join(root, "dev/SESSION_LOG.md"), "utf8");
4611
- } catch {
4612
- logText = "";
4613
- }
4614
- try {
4615
- handoffText = await readFile(path.join(root, "dev/SESSION_HANDOFF.md"), "utf8");
4616
- } catch {
4617
- handoffText = "";
4618
- }
4619
-
4620
- const markdownFiles = await listMarkdownFiles(root);
4621
- const findings = [];
4622
- for (const rel of markdownFiles) {
4623
- if (!isGeneratedArtifactCandidate(rel)) continue;
4624
- if (isArtifactGoverned(rel, { indexText, logText, handoffText })) continue;
4625
- findings.push(`${rel} is not registered in dev/PROJECT_INDEX.md and is not explicitly classified as draft / temporary / one-time evidence`);
4626
- }
4627
-
4628
- return { ok: findings.length === 0, checked: 1, findings };
4629
- }
4630
-
4631
- async function listMarkdownFiles(root) {
4632
- const results = [];
4633
- async function walk(dir) {
4634
- let entries = [];
4635
- try {
4636
- entries = await readdir(dir, { withFileTypes: true });
4637
- } catch {
4638
- return;
4639
- }
4640
- for (const entry of entries) {
4641
- if (entry.name === ".git" || entry.name === "node_modules") continue;
4642
- const full = path.join(dir, entry.name);
4643
- if (entry.isDirectory()) {
4644
- await walk(full);
4645
- continue;
4646
- }
4647
- if (!entry.isFile() || !entry.name.toLowerCase().endsWith(".md")) continue;
4648
- results.push(path.relative(root, full).split(path.sep).join("/"));
4649
- }
4650
- }
4651
- await walk(root);
4652
- return results.sort();
4653
- }
4654
-
4655
- function isGeneratedArtifactCandidate(rel) {
4656
- const normalized = rel.replaceAll("\\", "/");
4657
- const lower = normalized.toLowerCase();
4658
- const kitManaged = new Set([
4659
- "agents.md",
4660
- "claude.md",
4661
- "gemini.md",
4662
- "readme.md",
4663
- "dev/session_handoff.md",
4664
- "dev/session_log.md",
4665
- "dev/project_index.md",
4666
- "dev/doc_sync_registry.md",
4667
- "dev/rule_packs.md",
4668
- "dev/project_decisions.md"
4669
- ]);
4670
- if (kitManaged.has(lower)) return false;
4671
- if (lower.startsWith("dev/rules/")) return false;
4672
- if (lower.startsWith("dev/governance_migrations/")) return false;
4673
- if (lower.startsWith("dev/session_log_archive/")) return false;
4674
- if (lower.startsWith("docs/")) return true;
4675
- if (lower.startsWith("outputs/")) return true;
4676
- if (lower.startsWith("output/")) return true;
4677
- if (lower.startsWith("research/")) return true;
4678
- if (lower.startsWith("references/")) return true;
4679
- if (lower.startsWith("reference/")) return true;
4680
- if (lower.startsWith("runbooks/")) return true;
4681
- if (lower.startsWith("specs/")) return true;
4682
- if (lower.startsWith("requirements/")) return true;
4683
- return !normalized.includes("/");
4684
- }
4685
-
4686
- function isArtifactGoverned(rel, { indexText, logText, handoffText }) {
4687
- const normalized = rel.replaceAll("\\", "/");
4688
- if (projectIndexRegistersExactPath(indexText, normalized)) return true;
4689
- return textExplicitlyClassifiesExactArtifact(logText, normalized)
4690
- || textExplicitlyClassifiesExactArtifact(handoffText, normalized);
4691
- }
4692
-
4693
- function projectIndexRegistersExactPath(indexText, normalized) {
4694
- const active = stripMarkdownCommentsAndFences(indexText);
4695
- for (const line of active.split(/\r?\n/)) {
4696
- if (!line.trim().startsWith("|")) continue;
4697
- const cells = line.split("|").slice(1, -1);
4698
- for (const rawCell of cells) {
4699
- const cell = rawCell.trim().replace(/^`([^`]+)`$/, "$1");
4700
- if (cell === normalized) return true;
4701
- const link = /^\[[^\]]*\]\(([^)]+)\)$/.exec(cell);
4702
- if (link && link[1].replace(/^<|>$/g, "") === normalized) return true;
4703
- }
4704
- }
4705
- return false;
4706
- }
4707
-
4708
- function textExplicitlyClassifiesExactArtifact(text, normalized) {
4709
- const active = stripMarkdownCommentsAndFences(text);
4710
- const escaped = normalized.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4711
- const exactPath = new RegExp(`(?:^|[\\s\`|([<])${escaped}(?=$|[\\s\`|)\\]>.,;:])`, "i");
4712
- const label = /(draft|temporary|one-time evidence|non-authoritative|not source of truth|草稿|臨時|暫存|一次性|非真源|非權威)/i;
4713
- const markdownPath = /(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.md\b/gi;
4714
- for (const line of active.split(/\r?\n/)) {
4715
- if (!exactPath.test(line) || !label.test(line)) continue;
4716
- const paths = new Set((line.match(markdownPath) ?? []).map((item) => item.replaceAll("\\", "/").toLowerCase()));
4717
- if (paths.size === 1 && paths.has(normalized.toLowerCase())) return true;
4718
- }
4719
- return false;
4720
- }
4721
-
4722
- function stripFencedCodeBlocks(text) {
5538
+ function stripFencedCodeBlocks(text) {
4723
5539
  return text.replace(/```[\s\S]*?```/g, "");
4724
5540
  }
4725
5541
 
@@ -4944,7 +5760,7 @@ function printDoctorSummary(version, root, mode, details) {
4944
5760
  }
4945
5761
  } else {
4946
5762
  console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
4947
- 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 真源不同。"}`);
4948
5764
  }
4949
5765
  console.log("");
4950
5766
  console.log(`📦 版本:v${version}`);
@@ -5464,14 +6280,7 @@ function requiresHistoricalBaselineProof(context) {
5464
6280
  }
5465
6281
 
5466
6282
  async function readRootTemplateVersion(root) {
5467
- try {
5468
- const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
5469
- const text = await readFile(indexPath, "utf8");
5470
- const m = text.match(/\| Agent Handoff Kit template version \| ([\d.]+) \|/);
5471
- return m?.[1] ?? null;
5472
- } catch {
5473
- return null;
5474
- }
6283
+ return await readProjectIndexTemplateVersion(root);
5475
6284
  }
5476
6285
 
5477
6286
  function findArtifactBoundManagedCoreSegment(bytes, artifactSegment) {
@@ -5636,6 +6445,15 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
5636
6445
  catalog: context.officialCatalog
5637
6446
  });
5638
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 {
5639
6457
  return {
5640
6458
  ...base,
5641
6459
  action: "preserve",
@@ -5650,6 +6468,7 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
5650
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"
5651
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`
5652
6470
  };
6471
+ }
5653
6472
  }
5654
6473
  }
5655
6474
  if (command === "upgrade" && directStatefulTargets.has(targetRel) && isUncatalogedHistoricalBaseline(context)) {
@@ -5666,11 +6485,30 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
5666
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`
5667
6486
  };
5668
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
+ }
5669
6507
  const officialOrigin = command === "upgrade" ? trustedOfficialOrigin(targetRel, context) : null;
5670
- if (officialOrigin) {
5671
- return {
5672
- ...base,
5673
- action: "merge",
6508
+ if (officialOrigin) {
6509
+ return {
6510
+ ...base,
6511
+ action: "merge",
5674
6512
  reason: `replace raw-exact official historical ${targetRel} with the current Kit file`,
5675
6513
  mergedText: sourceText
5676
6514
  };
@@ -5727,26 +6565,7 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
5727
6565
  }
5728
6566
  return { ...base, action: "skip", reason: "official marked routes current; local rows preserved" };
5729
6567
  }
5730
- if (targetRel === "dev/PROJECT_INDEX.md" && command === "upgrade") {
5731
- const mergedProjectIndex = mergeProjectIndexGovernanceSections(targetText, sourceText);
5732
- if (!mergedProjectIndex) {
5733
- return {
5734
- ...base,
5735
- action: "conflict",
5736
- reason: "PROJECT_INDEX.md must contain unique real H2 governance sections in the expected order; inline or fenced lookalikes are not sections"
5737
- };
5738
- }
5739
- if (mergedProjectIndex !== targetText) {
5740
- return {
5741
- ...base,
5742
- action: "merge",
5743
- reason: "insert or normalize the unique Installed Integrations and Tool Operation References H2 sections while preserving all existing project content",
5744
- mergedText: mergedProjectIndex
5745
- };
5746
- }
5747
- return { ...base, action: "skip", reason: "PROJECT_INDEX.md governance sections current and structurally unique" };
5748
- }
5749
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
6568
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
5750
6569
  const migratedHandoff = migrateSessionHandoff(targetText, sourceText, context);
5751
6570
  if (!migratedHandoff) {
5752
6571
  return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md lacks unique trusted state/opening boundaries; migration stopped without replacing project state" };
@@ -6132,7 +6951,7 @@ function handoffContinuityAnchorPlacement(snippet, text) {
6132
6951
  }
6133
6952
 
6134
6953
  function projectIndexAnchorPlacement(snippet, text) {
6135
- if (snippet === "Agent Handoff Kit template version") return Boolean(projectIndexTemplateVersion(text));
6954
+ if (snippet === "Agent Handoff Kit template version") return Boolean(parseProjectIndexTemplateVersion(text));
6136
6955
  return true;
6137
6956
  }
6138
6957
 
@@ -6314,10 +7133,10 @@ function mergeProjectDecisionsPreamble(targetText, sourceText, missing) {
6314
7133
  return insertSourcePreambleBeforeHeading(targetText, sourceText, "## Evolution Timeline");
6315
7134
  }
6316
7135
 
6317
- function mergeProjectIndexTemplateVersionRow(targetText, sourceText) {
6318
- if (projectIndexTemplateVersion(targetText)) return targetText;
6319
- const sourceRow = sourceText.match(/^\| Agent Handoff Kit template version \| [\d.]+ \| [^|\n]+ \|$/m)?.[0];
6320
- 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;
6321
7140
  const lines = targetText.split(/\r?\n/);
6322
7141
  const stackIndex = lines.findIndex((line) => line.trim() === "## Stack");
6323
7142
  if (stackIndex < 0) return null;
@@ -6356,44 +7175,16 @@ function mergeCommunicationNextStepDiscipline(targetText, sourceText, missing) {
6356
7175
  return merged === targetText ? null : merged;
6357
7176
  }
6358
7177
 
6359
- function parseMarkdownH2Sections(text) {
6360
- const sections = [];
6361
- const linePattern = /.*(?:\r?\n|$)/g;
6362
- let fenced = false;
6363
- let fenceDelimiter = null;
6364
- let inComment = false;
6365
- let match;
6366
- while ((match = linePattern.exec(text)) && match[0] !== "") {
6367
- const raw = match[0];
6368
- const line = raw.replace(/\r?\n$/, "");
6369
- const trimmed = line.trim();
6370
- if (inComment) {
6371
- if (trimmed.includes("-->")) inComment = false;
6372
- continue;
6373
- }
6374
- if (trimmed.startsWith("<!--")) {
6375
- if (!trimmed.includes("-->")) inComment = true;
6376
- continue;
6377
- }
6378
- const fence = trimmed.match(/^(`{3,}|~{3,})/);
6379
- if (fence) {
6380
- if (!fenced) {
6381
- fenced = true;
6382
- fenceDelimiter = fence[1][0];
6383
- } else if (fence[1][0] === fenceDelimiter) {
6384
- fenced = false;
6385
- fenceDelimiter = null;
6386
- }
6387
- continue;
6388
- }
6389
- if (fenced) continue;
6390
- const headingMatch = line.match(/^## ([^#].*?)\s*$/);
6391
- if (headingMatch) sections.push({ title: headingMatch[1], start: match.index, end: text.length });
6392
- }
6393
- for (let index = 0; index < sections.length - 1; index += 1) {
6394
- sections[index].end = sections[index + 1].start;
6395
- }
6396
- 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;
6397
7188
  }
6398
7189
 
6399
7190
  function uniqueSessionLogEntryTemplateSection(text) {
@@ -6555,100 +7346,30 @@ function mergeProjectIndexGovernanceSections(targetText, sourceText) {
6555
7346
  if ((installed && installed.start > localQc.start) || (toolRefs && toolRefs.start > localQc.start)) return null;
6556
7347
  if (installed && toolRefs && installed.start > toolRefs.start) return null;
6557
7348
 
6558
- const missing = requiredTitles.slice(0, 2).filter((title) => targetByTitle.get(title).length === 0);
6559
- let merged = targetText;
6560
- if (missing.length > 0) {
6561
- const insertion = missing
6562
- .map((title) => sourceText.slice(sourceByTitle.get(title)[0].start, sourceByTitle.get(title)[0].end).trimEnd())
6563
- .join("\n\n");
6564
- merged = `${targetText.slice(0, localQc.start).trimEnd()}\n\n${insertion}\n\n${targetText.slice(localQc.start)}`;
6565
- }
6566
- merged = mergeProjectIndexCredentialReferences(merged);
6567
- return projectIndexGovernanceSectionsAreValid(merged) ? merged : null;
6568
- }
6569
-
6570
- function mergeProjectIndexCredentialReferences(targetText) {
6571
- return targetText
6572
- .replace(
6573
- /`via` column 紀律:每行 External Sources 必引用 `## Installed Integrations`[^\r\n]*/,
6574
- "`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."
6575
- )
6576
- .replace(
6577
- /⚠️ \*\*機密分離原則\*\*:本 section 只記錄[^\r\n]*/,
6578
- "**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`."
6579
- )
6580
- .replace(
6581
- /用途:新 AI session 開工讀本 section 知道[^\r\n]*/,
6582
- "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."
6583
- )
6584
- .replace("### Connectors(Anthropic 官方 vetted)", "### Connectors")
6585
- .replace("### MCPs(community / custom)", "### MCPs")
6586
- .replace("### Plugins(Claude Code plugin bundle)", "### Plugins")
6587
- .replace("### Skills(SKILL.md instruction set)", "### Skills")
6588
- .replace("### Source-of-truth Architecture(多層持久化組合)", "### Source-of-truth Architecture")
6589
- .replace(
6590
- /當項目用多個整合構成 source-of-truth 架構[^\r\n]*/,
6591
- "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."
6592
- )
6593
- .replace(
6594
- "| TBD | TBD(譬如 DB Index 記真源 path / 持久化參考檔儲存) | read / read+write | TBD(譬如 DB 名 + URL / folder path) | TBD(譬如 `AI tool secure storage` / `OS credential store`) | TBD | TBD |",
6595
- "| 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 |"
6596
- )
6597
- .replace(
6598
- "| TBD | TBD(譬如 GitHub repo URL) | TBD | TBD(譬如 `tool config + env var name only` / `user-managed secret store`) | TBD | TBD |",
6599
- "| TBD | TBD, for example GitHub repository URL | TBD | TBD, for example `tool config + env var name only` / `user-managed secret store` | TBD | TBD |"
6600
- )
6601
- .replace(
6602
- "| TBD | TBD(譬如 plugin bundle / user-level install) | TBD | TBD |",
6603
- "| TBD | TBD, for example plugin bundle or user-level install | TBD | TBD |"
6604
- )
6605
- .replace(
6606
- "| 真源(source of truth) | TBD(譬如 本機 `~/project/reference/`) | 原始可審計 reference 內容 | 用戶手動置入;AI 不直接寫入 |",
6607
- "| Source of truth | TBD, for example local `~/project/reference/` | Original auditable reference content | User-controlled placement; agent does not write directly unless explicitly authorized |"
6608
- )
6609
- .replace(
6610
- "| Index | TBD(譬如 Notion DB「Project Index」) | 登記每份真源檔 metadata + 摘要 + tag | AI 經 Connector 直接讀寫 |",
6611
- "| Index | TBD, for example Notion database `Project Index` | Metadata, summaries, and tags for each source file | Agent may read/write through a verified Connector |"
6612
- )
6613
- .replace(
6614
- "| 持久化參考檔(mirror) | TBD(譬如 Drive folder「Project Reference/」) | 防本機 disk failure / 跨裝置 access | 用戶手動同步;AI 唔自動 push |",
6615
- "| 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 |"
6616
- )
6617
- .replace(
6618
- "| Working draft | TBD(譬如 本機 `~/project/output/`) | AI 寫 task output | AI 直接 read + write 本機 |",
6619
- "| Working draft | TBD, for example local `~/project/output/` | Agent task output | Agent may read and write local files under normal safety rules |"
6620
- )
6621
- .replace(
6622
- "Credential 應由 AI 工具自身 secure storage 管理(譬如 Claude Desktop Extensions 嘅 OS Keychain / Claude Code MCP config)。",
6623
- "Credential 應由 AI 工具自身 secure storage / OS credential store / tool config / user-managed secret store 管理;若使用 env,只可記錄 env var name,不可讀取、貼出或保存 value。"
6624
- )
6625
- .replaceAll(
6626
- "Credential Location",
6627
- "Credential Reference(no value)"
6628
- )
6629
- .replaceAll(
6630
- "Credential Reference(no value)",
6631
- "Credential Reference (no value)"
6632
- )
6633
- .replaceAll(
6634
- "Bundle Content(Skills + MCP + hooks)",
6635
- "Bundle Content (Skills + MCP + hooks)"
6636
- )
6637
- .replaceAll(
6638
- "Surface(具體 instance)",
6639
- "Surface (specific instance)"
6640
- )
6641
- .replace(
6642
- "`Claude Desktop Extensions`",
6643
- "`AI tool secure storage` / `OS credential store`"
6644
- )
6645
- .replace(
6646
- "`Claude Code MCP config + env var`",
6647
- "`tool config + env var name only` / `user-managed secret store`"
6648
- );
6649
- }
6650
-
6651
- 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) {
6652
7373
  if (!hasTrustedSafetyPackShape(targetText)) return null;
6653
7374
  const targetBounds = sectionBounds(targetText, "## Rules", "## Checks");
6654
7375
  const sourceBounds = sectionBounds(sourceText, "## Rules", "## Checks");
@@ -6893,15 +7614,7 @@ function textSectionBounds(text, startHeading, endHeading) {
6893
7614
  return { start: startIndex, end: endIndex };
6894
7615
  }
6895
7616
 
6896
- function projectIndexTemplateVersion(text) {
6897
- const bounds = textSectionBounds(text, "## Stack", "## Directory Map");
6898
- if (!bounds) return null;
6899
- const stack = text.slice(bounds.start, bounds.end);
6900
- const row = stack.match(/^\| Agent Handoff Kit template version \| ([\d.]+) \| [^|\n]+ \|$/m);
6901
- return row ? row[1] : null;
6902
- }
6903
-
6904
- function migrateSessionHandoff(targetText, sourceText, context = {}) {
7617
+ function migrateSessionHandoff(targetText, sourceText, context = {}) {
6905
7618
  if (countText(targetText, "## Next Session Opening Message") !== 1) return null;
6906
7619
  let merged = mergeLegacyFirstStartupGuidance(targetText, sourceText) ?? targetText;
6907
7620
 
@@ -7250,7 +7963,7 @@ async function assessVersionAlignment(root, cliVersion, options = {}) {
7250
7963
  let rootVersion = null;
7251
7964
  try {
7252
7965
  const text = await readFile(indexPath, "utf8");
7253
- rootVersion = projectIndexTemplateVersion(text);
7966
+ rootVersion = parseProjectIndexTemplateVersion(text);
7254
7967
  } catch {
7255
7968
  // file missing or unreadable; rootVersion stays null
7256
7969
  }
@@ -8065,6 +8778,7 @@ Usage:
8065
8778
  agent-handoff-kit doctor [--root <path>]
8066
8779
  agent-handoff-kit closeout-status [--root <path>]
8067
8780
  agent-handoff-kit finalize-closeout [--root <path>]
8781
+ agent-handoff-kit reconcile-current-state [--dry-run] [--yes] --manifest <sha256> [--root <path>]
8068
8782
 
8069
8783
  Commands:
8070
8784
  init Plan or install missing core files and rule packs.
@@ -8072,6 +8786,7 @@ Commands:
8072
8786
  doctor Check required installed files.
8073
8787
  closeout-status Render the state-bound closeout card after a full closeout.
8074
8788
  finalize-closeout Bind legal post-upgrade closeout state edits before doctor.
8789
+ reconcile-current-state Bind intentional current-state source changes without overwriting project files.
8075
8790
 
8076
8791
  中文速讀:
8077
8792
  ✅ 第一次用:先在項目資料夾執行 init。