@adamchanadam/agent-handoff-kit 0.3.50 → 0.3.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +4 -2
- package/README.md +4 -2
- package/bin/agent-handoff-kit.mjs +922 -131
- package/bin/migration-baselines/official-origin-catalog.json +376 -1
- package/bin/upgrade-inventory.mjs +63 -34
- package/package.json +1 -1
- package/runtime-core/AGENTS.core.md +6 -4
- package/runtime-core/SESSION_HANDOFF.md +1 -1
- package/runtime-core/START_NEXT_SESSION_PROMPT.txt +1 -1
|
@@ -10,7 +10,7 @@ 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 } from "./upgrade-inventory.mjs";
|
|
13
|
+
import { assertGate5FrozenSet, extractExplicitLocalReferences, freezeGate5Set, gate5SourceConservationItems } from "./upgrade-inventory.mjs";
|
|
14
14
|
import {
|
|
15
15
|
FORMAL_USER_RULES_ENTRY_ANCHOR,
|
|
16
16
|
USER_RULES_ROUTER_PATH,
|
|
@@ -44,6 +44,10 @@ const closeoutFinalizeTargets = new Set([
|
|
|
44
44
|
"dev/DOC_SYNC_REGISTRY.md",
|
|
45
45
|
"dev/PROJECT_DECISIONS.md"
|
|
46
46
|
]);
|
|
47
|
+
const directCloseoutStateTargets = Object.freeze([...closeoutFinalizeTargets].sort((left, right) => left.localeCompare(right)));
|
|
48
|
+
const directCloseoutStateTargetSet = new Set(directCloseoutStateTargets);
|
|
49
|
+
const canonicalSessionLogArchiveRoot = "dev/SESSION_LOG_archive";
|
|
50
|
+
const legacySessionLogArchiveRoot = "dev/session_log_archive";
|
|
47
51
|
const credentialLeakPatterns = [
|
|
48
52
|
{ pattern: /sk-ant-[A-Za-z0-9_-]{20,}/, label: "Anthropic API key" },
|
|
49
53
|
{ pattern: /\bsk-[A-Za-z0-9_-]{20,}/, label: "sk-prefixed token" },
|
|
@@ -604,6 +608,11 @@ async function main() {
|
|
|
604
608
|
return;
|
|
605
609
|
}
|
|
606
610
|
|
|
611
|
+
if (command === "reconcile-current-state") {
|
|
612
|
+
await runReconcileCurrentState(root, options, version);
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
|
|
607
616
|
throw new Error(`unknown command "${command}"`);
|
|
608
617
|
}
|
|
609
618
|
|
|
@@ -664,6 +673,131 @@ async function runFinalizeCloseout(root, version) {
|
|
|
664
673
|
console.log(`current-state digest: ${transaction.journal.currentStateWitness.currentStateDigest}`);
|
|
665
674
|
}
|
|
666
675
|
|
|
676
|
+
async function runReconcileCurrentState(root, options, version) {
|
|
677
|
+
await validateTransactionRoot(root, [], { createMissingRoot: false });
|
|
678
|
+
if (options.dryRun) await assertDryRunHasNoPendingTransaction(root);
|
|
679
|
+
else {
|
|
680
|
+
assertCurrentStateReconcileWriteIntent(options);
|
|
681
|
+
if (await recoverBoundCurrentStateReconciliation(root, options.manifest)) {
|
|
682
|
+
console.log("current-state reconciliation recovery completed; run a fresh dry-run before applying another reconciliation plan");
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
const candidate = await findCurrentStateReconciliationBase(root, version);
|
|
687
|
+
if (!candidate) {
|
|
688
|
+
console.log("current-state reconciliation: no stale source-conservation witness needs reconciliation");
|
|
689
|
+
if (options.dryRun) console.log("dry-run: no files written");
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
if (candidate.illegal.length > 0) {
|
|
693
|
+
throw new Error(`current-state reconciliation blocked: ${candidate.illegal.map((item) => `${item.path} (${item.reason})`).join(", ")}`);
|
|
694
|
+
}
|
|
695
|
+
if (candidate.reconcilable.length === 0) {
|
|
696
|
+
console.log("current-state reconciliation: current-state witness already matches project bytes");
|
|
697
|
+
if (options.dryRun) console.log("dry-run: no files written");
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
console.log(`current-state reconciliation plan: ${candidate.reconcilable.length} path(s)`);
|
|
701
|
+
console.log(`manifest sha256: ${candidate.manifestSha256}`);
|
|
702
|
+
for (const item of candidate.reconcilable) console.log(`- ${item.path}: ${item.reason}`);
|
|
703
|
+
if (options.dryRun) {
|
|
704
|
+
console.log("dry-run: no files written");
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
if (options.manifest !== candidate.manifestSha256) {
|
|
708
|
+
throw new Error("current-state reconciliation manifest mismatch before writes; no files written");
|
|
709
|
+
}
|
|
710
|
+
const verified = await findCurrentStateReconciliationBase(root, version);
|
|
711
|
+
if (!verified || verified.manifestSha256 !== candidate.manifestSha256 || JSON.stringify(verified.manifest) !== JSON.stringify(candidate.manifest)) {
|
|
712
|
+
throw new Error("current-state reconciliation manifest changed before transaction preparation; no files written");
|
|
713
|
+
}
|
|
714
|
+
await assertCurrentStateReconciliationVerifiedPlanStillCurrent(root, verified);
|
|
715
|
+
const transaction = await writeCurrentStateReconciliationJournal(root, version, verified);
|
|
716
|
+
if (!await journalMatchesCurrentState(root, transaction.journal)) {
|
|
717
|
+
throw new Error("post-reconciliation current-state readback failed; reconciliation journal retained for inspection");
|
|
718
|
+
}
|
|
719
|
+
transaction.journal.currentStateReadback = currentStateReadbackFromVerifiedProjectBytes(transaction.journal.currentStateWitness);
|
|
720
|
+
await writeSecureJson(transaction.journalPath, transaction.journal);
|
|
721
|
+
await writeCurrentStateReconciliationReport({ root, migrationDir: path.dirname(transaction.journalPath), journal: transaction.journal, reconciledPaths: candidate.reconcilable.map((item) => item.path) });
|
|
722
|
+
console.log(`current-state reconciled: bound ${candidate.reconcilable.length} current project path(s) without overwriting project files`);
|
|
723
|
+
console.log("project health: run upgrade/doctor next if this project predates the current Kit template");
|
|
724
|
+
console.log(`current-state digest: ${transaction.journal.currentStateWitness.currentStateDigest}`);
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
function assertCurrentStateReconcileWriteIntent(options) {
|
|
728
|
+
if (!options.yes || !options.manifest) {
|
|
729
|
+
throw new Error("current-state reconciliation requires --yes --manifest <dry-run manifest sha256>; no files written");
|
|
730
|
+
}
|
|
731
|
+
if (typeof options.manifest !== "string" || !/^[a-f0-9]{64}$/.test(options.manifest)) {
|
|
732
|
+
throw new Error("current-state reconciliation manifest must be a lowercase sha256 digest; no files written");
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
async function recoverBoundCurrentStateReconciliation(root, manifestSha256) {
|
|
737
|
+
const lockPath = path.join(root, "dev", "governance_migrations", ".upgrade.lock");
|
|
738
|
+
let rawLock;
|
|
739
|
+
try {
|
|
740
|
+
rawLock = await readFile(lockPath, "utf8");
|
|
741
|
+
} catch (error) {
|
|
742
|
+
if (error?.code === "ENOENT") return false;
|
|
743
|
+
throw new Error("current-state reconciliation recovery lock is unreadable or unsafe; no writes attempted");
|
|
744
|
+
}
|
|
745
|
+
let lock;
|
|
746
|
+
try {
|
|
747
|
+
lock = JSON.parse(rawLock);
|
|
748
|
+
} catch {
|
|
749
|
+
throw new Error("current-state reconciliation recovery lock is not bound to a verified reconciliation transaction; no writes attempted");
|
|
750
|
+
}
|
|
751
|
+
if (!lock || typeof lock !== "object" || Array.isArray(lock)
|
|
752
|
+
|| typeof lock.id !== "string" || !lock.id
|
|
753
|
+
|| typeof lock.journal !== "string" || !lock.journal
|
|
754
|
+
|| typeof lock.host !== "string" || !lock.host
|
|
755
|
+
|| !Number.isInteger(lock.pid) || lock.pid <= 0
|
|
756
|
+
|| lock.command !== "reconcile-current-state") {
|
|
757
|
+
throw new Error("current-state reconciliation recovery lock is not bound to reconcile-current-state; no writes attempted");
|
|
758
|
+
}
|
|
759
|
+
if (lock.host === hostname() && processIsAlive(lock.pid)) {
|
|
760
|
+
throw new Error(`another current-state reconciliation process is active (pid ${lock.pid}); no writes attempted`);
|
|
761
|
+
}
|
|
762
|
+
if (lock.host && lock.host !== hostname()) {
|
|
763
|
+
throw new Error(`current-state reconciliation recovery lock belongs to another host (${lock.host}); no writes attempted`);
|
|
764
|
+
}
|
|
765
|
+
const journalPath = path.resolve(root, lock.journal);
|
|
766
|
+
if (!isInside(root, journalPath)) throw new Error("current-state reconciliation recovery journal path escapes selected root; no writes attempted");
|
|
767
|
+
let journal;
|
|
768
|
+
try {
|
|
769
|
+
journal = JSON.parse(await readFile(journalPath, "utf8"));
|
|
770
|
+
} catch {
|
|
771
|
+
throw new Error("current-state reconciliation recovery lock has no readable durable journal; no writes attempted");
|
|
772
|
+
}
|
|
773
|
+
await validateRecoveryJournal(root, journal, journalPath, lock.id);
|
|
774
|
+
if (journal.command !== "reconcile-current-state" || journal.mode !== "source-state-reconciliation") {
|
|
775
|
+
throw new Error("current-state reconciliation recovery journal has no reconciliation authority; no writes attempted");
|
|
776
|
+
}
|
|
777
|
+
if (!["prepared", "committed"].includes(journal.state)) {
|
|
778
|
+
throw new Error("current-state reconciliation recovery journal is not in a recoverable state; no writes attempted");
|
|
779
|
+
}
|
|
780
|
+
if (journal.reconciliationManifestSha256 !== manifestSha256) {
|
|
781
|
+
throw new Error("current-state reconciliation recovery manifest digest does not match the CLI manifest; no writes attempted");
|
|
782
|
+
}
|
|
783
|
+
if (!journal.reconciliationManifest || typeof journal.reconciliationManifest !== "object" || Array.isArray(journal.reconciliationManifest)) {
|
|
784
|
+
throw new Error("current-state reconciliation recovery journal has no durable manifest; no writes attempted");
|
|
785
|
+
}
|
|
786
|
+
if (journal.reconciliationManifest.command !== "reconcile-current-state") {
|
|
787
|
+
throw new Error("current-state reconciliation recovery manifest has no reconciliation command authority; no writes attempted");
|
|
788
|
+
}
|
|
789
|
+
const durableManifestSha256 = sha256(Buffer.from(`${JSON.stringify(journal.reconciliationManifest)}\n`, "utf8"));
|
|
790
|
+
if (durableManifestSha256 !== manifestSha256) {
|
|
791
|
+
throw new Error("current-state reconciliation recovery durable manifest digest does not match the CLI manifest; no writes attempted");
|
|
792
|
+
}
|
|
793
|
+
const rootReal = await realpath(root);
|
|
794
|
+
if (journal.reconciliationManifest.root?.realpath !== rootReal) {
|
|
795
|
+
throw new Error("current-state reconciliation recovery manifest root does not match the selected root; no writes attempted");
|
|
796
|
+
}
|
|
797
|
+
await recoverInterruptedTransaction(root, { reconciliationManifestSha256: manifestSha256 });
|
|
798
|
+
return true;
|
|
799
|
+
}
|
|
800
|
+
|
|
667
801
|
function closeoutOutcome(value) {
|
|
668
802
|
return /^(complete|completed)\b/i.test((value ?? "").trim()) ? "complete" : "blocked";
|
|
669
803
|
}
|
|
@@ -706,10 +840,11 @@ function parseArgs(args) {
|
|
|
706
840
|
if (!command && !arg.startsWith("-")) {
|
|
707
841
|
command = arg;
|
|
708
842
|
continue;
|
|
709
|
-
}
|
|
710
|
-
if (arg === "--dry-run") options.dryRun = true;
|
|
711
|
-
else if (arg === "--yes" || arg === "-y") options.yes = true;
|
|
712
|
-
else if (arg === "--
|
|
843
|
+
}
|
|
844
|
+
if (arg === "--dry-run") options.dryRun = true;
|
|
845
|
+
else if (arg === "--yes" || arg === "-y") options.yes = true;
|
|
846
|
+
else if (arg === "--manifest") options.manifest = args[++i];
|
|
847
|
+
else if (arg === "--help" || arg === "-h") options.help = true;
|
|
713
848
|
else if (arg === "--root") options.root = args[++i];
|
|
714
849
|
else throw new Error(`unknown option "${arg}"`);
|
|
715
850
|
}
|
|
@@ -1316,12 +1451,7 @@ async function prepareTransaction(root, command, version, outputs, mode, plan, s
|
|
|
1316
1451
|
await mkdir(archiveBackupDir, { recursive: true });
|
|
1317
1452
|
await tightenPermissions(migrationsRoot, 0o700);
|
|
1318
1453
|
await tightenPermissions(migrationDir, 0o700);
|
|
1319
|
-
|
|
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();
|
|
1454
|
+
await publishTransactionLock(root, lockPath, { id, host: hostname(), pid: process.pid, journal: path.relative(root, journalPath), command });
|
|
1325
1455
|
|
|
1326
1456
|
const entries = [];
|
|
1327
1457
|
for (const output of outputs) {
|
|
@@ -1906,6 +2036,7 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
|
|
|
1906
2036
|
const seen = new Set();
|
|
1907
2037
|
const formalWitness = validateFormalUserRulesWitness(journal.formalUserRules);
|
|
1908
2038
|
const runtimeAcceptance = validateRuntimeAcceptance(journal.runtimeAcceptance);
|
|
2039
|
+
const zeroWriteReconciliation = journal.command === "reconcile-current-state" && journal.mode === "source-state-reconciliation";
|
|
1909
2040
|
const hasArchiveMigrationField = journal.archiveMigrations !== undefined;
|
|
1910
2041
|
const requiresArchiveBackup = journal.command === "upgrade" && hasArchiveMigrationField;
|
|
1911
2042
|
if (journal.archiveMigrations != null && !Array.isArray(journal.archiveMigrations)) throw new Error("upgrade journal archive migrations are invalid; no recovery writes attempted");
|
|
@@ -1924,30 +2055,31 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
|
|
|
1924
2055
|
const migrationsStats = await lstat(migrationsRoot).catch(() => null);
|
|
1925
2056
|
const migrationStats = await lstat(migrationDir).catch(() => null);
|
|
1926
2057
|
const journalStats = await lstat(journalPath).catch(() => null);
|
|
1927
|
-
const backupStats = await lstat(backupRoot).catch(() => null);
|
|
2058
|
+
const backupStats = await lstat(backupRoot).catch(() => null);
|
|
1928
2059
|
const stageStats = await lstat(stageRoot).catch(() => null);
|
|
1929
2060
|
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()
|
|
2061
|
+
if (!migrationsStats?.isDirectory() || migrationsStats.isSymbolicLink()
|
|
2062
|
+
|| !migrationStats?.isDirectory() || migrationStats.isSymbolicLink()
|
|
2063
|
+
|| !journalStats?.isFile() || journalStats.isSymbolicLink()
|
|
2064
|
+
|| (!zeroWriteReconciliation && (!backupStats?.isDirectory() || backupStats.isSymbolicLink()))
|
|
2065
|
+
|| (!zeroWriteReconciliation && (!stageStats?.isDirectory() || stageStats.isSymbolicLink()))
|
|
1935
2066
|
|| (requiresArchiveBackup && (!archiveBackupStats?.isDirectory() || archiveBackupStats.isSymbolicLink()))) {
|
|
1936
|
-
throw new Error("upgrade transaction directories or journal are missing or unsafe; no recovery writes attempted");
|
|
1937
|
-
}
|
|
2067
|
+
throw new Error("upgrade transaction directories or journal are missing or unsafe; no recovery writes attempted");
|
|
2068
|
+
}
|
|
1938
2069
|
const migrationsReal = await realpath(migrationsRoot);
|
|
1939
2070
|
const migrationReal = await realpath(migrationDir);
|
|
1940
2071
|
const journalReal = await realpath(journalPath);
|
|
1941
|
-
const backupRealRoot = await realpath(backupRoot);
|
|
1942
|
-
const stageRealRoot = await realpath(stageRoot);
|
|
2072
|
+
const backupRealRoot = zeroWriteReconciliation ? null : await realpath(backupRoot);
|
|
2073
|
+
const stageRealRoot = zeroWriteReconciliation ? null : await realpath(stageRoot);
|
|
1943
2074
|
const archiveBackupRealRoot = requiresArchiveBackup ? await realpath(archiveBackupRoot) : null;
|
|
1944
|
-
if (!isInside(rootReal, migrationsReal) || !isInside(migrationsReal, migrationReal)
|
|
1945
|
-
|| !isInside(migrationReal, journalReal)
|
|
1946
|
-
|| !
|
|
1947
|
-
|| !samePath(path.dirname(
|
|
2075
|
+
if (!isInside(rootReal, migrationsReal) || !isInside(migrationsReal, migrationReal)
|
|
2076
|
+
|| !isInside(migrationReal, journalReal)
|
|
2077
|
+
|| (!zeroWriteReconciliation && (!isInside(migrationReal, backupRealRoot) || !isInside(migrationReal, stageRealRoot)))
|
|
2078
|
+
|| !samePath(path.dirname(migrationReal), migrationsReal)
|
|
2079
|
+
|| (!zeroWriteReconciliation && (!samePath(path.dirname(backupRealRoot), migrationReal) || !samePath(path.dirname(stageRealRoot), migrationReal)))
|
|
1948
2080
|
|| (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
|
-
}
|
|
2081
|
+
throw new Error("upgrade transaction paths resolve outside the selected root or transaction; no recovery writes attempted");
|
|
2082
|
+
}
|
|
1951
2083
|
const validated = [];
|
|
1952
2084
|
const validHash = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
|
|
1953
2085
|
for (const entry of journal.entries) {
|
|
@@ -1974,25 +2106,34 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
|
|
|
1974
2106
|
if (error?.code !== "ENOENT") throw error;
|
|
1975
2107
|
}
|
|
1976
2108
|
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
if (
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
if (
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
2109
|
+
if (zeroWriteReconciliation && entry.beforeHash !== entry.afterHash) {
|
|
2110
|
+
throw new Error("current-state reconciliation journal cannot record project-content writes; no recovery writes attempted");
|
|
2111
|
+
}
|
|
2112
|
+
if (!zeroWriteReconciliation) {
|
|
2113
|
+
const stageAbs = path.resolve(stageRoot, entry.targetRel);
|
|
2114
|
+
const stageStats = await lstat(stageAbs).catch(() => null);
|
|
2115
|
+
if (!stageStats?.isFile() || stageStats.isSymbolicLink()) throw new Error("upgrade journal stage is missing or unsafe; no recovery writes attempted");
|
|
2116
|
+
const stageReal = await realpath(stageAbs);
|
|
2117
|
+
if (!isInside(stageRealRoot, stageReal)) throw new Error("upgrade journal stage resolves outside this transaction; no recovery writes attempted");
|
|
2118
|
+
if (sha256(await readFile(stageAbs)) !== entry.afterHash) throw new Error("upgrade journal stage hash does not match the recorded candidate; no recovery writes attempted");
|
|
2119
|
+
}
|
|
2120
|
+
|
|
2121
|
+
let backup = null;
|
|
2122
|
+
if (entry.existed) {
|
|
2123
|
+
if (zeroWriteReconciliation) {
|
|
2124
|
+
if (entry.backupRel !== null) throw new Error("current-state reconciliation journal must not record backup paths; no recovery writes attempted");
|
|
2125
|
+
} else {
|
|
2126
|
+
if (typeof entry.backupRel !== "string" || !entry.backupRel) throw new Error("upgrade journal backup path is missing; no recovery writes attempted");
|
|
2127
|
+
const backupAbs = path.resolve(root, entry.backupRel);
|
|
2128
|
+
const expectedBackup = path.resolve(backupRoot, entry.targetRel);
|
|
2129
|
+
if (!samePath(backupAbs, expectedBackup) || !isInside(backupRoot, backupAbs)) throw new Error("upgrade journal backup path is outside this transaction; no recovery writes attempted");
|
|
2130
|
+
const backupFileStats = await lstat(backupAbs).catch(() => null);
|
|
2131
|
+
if (!backupFileStats?.isFile() || backupFileStats.isSymbolicLink()) throw new Error("upgrade journal backup is missing or unsafe; no recovery writes attempted");
|
|
2132
|
+
const backupReal = await realpath(backupAbs);
|
|
2133
|
+
if (!isInside(backupRealRoot, backupReal)) throw new Error("upgrade journal backup resolves outside this transaction; no recovery writes attempted");
|
|
2134
|
+
backup = await readFile(backupAbs);
|
|
2135
|
+
if (sha256(backup) !== entry.beforeHash) throw new Error("upgrade journal backup hash does not match the recorded input; no recovery writes attempted");
|
|
2136
|
+
}
|
|
1996
2137
|
} else if (entry.backupRel !== null) {
|
|
1997
2138
|
throw new Error("upgrade journal has an unexpected backup for a created target; no recovery writes attempted");
|
|
1998
2139
|
}
|
|
@@ -2024,7 +2165,9 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
|
|
|
2024
2165
|
}
|
|
2025
2166
|
if (journal.currentStateWitness) {
|
|
2026
2167
|
const currentStateWitness = validateCurrentStateWitness(journal);
|
|
2027
|
-
validateCurrentStateReadback(journal.currentStateReadback, currentStateWitness
|
|
2168
|
+
validateCurrentStateReadback(journal.currentStateReadback, currentStateWitness, {
|
|
2169
|
+
allowProjectByteReader: zeroWriteReconciliation
|
|
2170
|
+
});
|
|
2028
2171
|
} else if (journal.currentStateReadback != null) {
|
|
2029
2172
|
throw new Error("shared current-state readback exists without a current-state witness; no recovery writes attempted");
|
|
2030
2173
|
}
|
|
@@ -2174,15 +2317,32 @@ async function removeArchiveSubsetNoClobber(root, migration, canonicalAbs, escro
|
|
|
2174
2317
|
}
|
|
2175
2318
|
}
|
|
2176
2319
|
|
|
2177
|
-
|
|
2178
|
-
const
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
lock
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2320
|
+
function assertRecoveryCallerMayHandleReconciliation(lock, journal, manifestSha256) {
|
|
2321
|
+
const involvesReconciliation = lock.command === "reconcile-current-state" || journal.command === "reconcile-current-state";
|
|
2322
|
+
if (!involvesReconciliation) return;
|
|
2323
|
+
if (typeof manifestSha256 !== "string" || !/^[a-f0-9]{64}$/.test(manifestSha256)
|
|
2324
|
+
|| lock.command !== "reconcile-current-state"
|
|
2325
|
+
|| journal.command !== "reconcile-current-state"
|
|
2326
|
+
|| journal.mode !== "source-state-reconciliation"
|
|
2327
|
+
|| journal.reconciliationManifestSha256 !== manifestSha256
|
|
2328
|
+
|| !journal.reconciliationManifest
|
|
2329
|
+
|| typeof journal.reconciliationManifest !== "object"
|
|
2330
|
+
|| Array.isArray(journal.reconciliationManifest)
|
|
2331
|
+
|| sha256(Buffer.from(`${JSON.stringify(journal.reconciliationManifest)}\n`, "utf8")) !== manifestSha256) {
|
|
2332
|
+
throw new Error("current-state reconciliation recovery requires reconcile-current-state --yes --manifest <freshly reviewed digest>; no automatic recovery attempted");
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
|
|
2336
|
+
async function recoverInterruptedTransaction(root, options = {}) {
|
|
2337
|
+
const lockPath = path.join(root, "dev", "governance_migrations", ".upgrade.lock");
|
|
2338
|
+
let lock;
|
|
2339
|
+
try {
|
|
2340
|
+
lock = JSON.parse(await readFile(lockPath, "utf8"));
|
|
2341
|
+
} catch (error) {
|
|
2342
|
+
if (error?.code === "ENOENT") return;
|
|
2343
|
+
if (await quarantineUnboundUnreadableLock(root, lockPath)) return;
|
|
2344
|
+
throw new Error("upgrade lock exists but is unreadable; no writes attempted");
|
|
2345
|
+
}
|
|
2186
2346
|
if (!lock || typeof lock !== "object" || Array.isArray(lock) || typeof lock.id !== "string" || typeof lock.journal !== "string"
|
|
2187
2347
|
|| typeof lock.host !== "string" || !Number.isInteger(lock.pid) || lock.pid <= 0) {
|
|
2188
2348
|
throw new Error("upgrade lock schema is invalid; no automatic recovery attempted");
|
|
@@ -2192,11 +2352,12 @@ async function recoverInterruptedTransaction(root) {
|
|
|
2192
2352
|
const journalPath = path.resolve(root, lock.journal ?? "");
|
|
2193
2353
|
if (!isInside(root, journalPath)) throw new Error("upgrade lock journal path escapes selected root");
|
|
2194
2354
|
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
|
-
}
|
|
2355
|
+
try {
|
|
2356
|
+
journal = JSON.parse(await readFile(journalPath, "utf8"));
|
|
2357
|
+
} catch {
|
|
2358
|
+
throw new Error("incomplete upgrade lock has no readable journal; no automatic recovery attempted");
|
|
2359
|
+
}
|
|
2360
|
+
assertRecoveryCallerMayHandleReconciliation(lock, journal, options.reconciliationManifestSha256);
|
|
2200
2361
|
await validateRecoveryJournal(root, journal, journalPath, lock.id);
|
|
2201
2362
|
if (journal.state === "committed") {
|
|
2202
2363
|
if (!journal.committedVersion) journal.committedVersion = journal.attemptedVersion;
|
|
@@ -2228,12 +2389,21 @@ async function recoverInterruptedTransaction(root) {
|
|
|
2228
2389
|
);
|
|
2229
2390
|
}
|
|
2230
2391
|
const migrationDir = path.dirname(journalPath);
|
|
2231
|
-
await writeSecureJson(journalPath, journal);
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2392
|
+
await writeSecureJson(journalPath, journal);
|
|
2393
|
+
if (journal.command === "reconcile-current-state") {
|
|
2394
|
+
const reconciledPaths = (journal.currentStateWitness?.sourceConservation?.entries ?? [])
|
|
2395
|
+
.filter((entry) => ["user-owned-reconciliation", "session-log-archive-reconciliation"].includes(entry.disposition))
|
|
2396
|
+
.map((entry) => entry.sourcePath);
|
|
2397
|
+
await writeCurrentStateReconciliationReport({ migrationDir, journal, reconciledPaths });
|
|
2398
|
+
} else {
|
|
2399
|
+
await writeTransactionReport({ id: journal.id, migrationDir, journal });
|
|
2400
|
+
}
|
|
2401
|
+
await unlinkIfExists(lockPath);
|
|
2402
|
+
console.log(journal.command === "reconcile-current-state"
|
|
2403
|
+
? "⚠️ recovered committed current-state reconciliation: reconciliation report was verified or rebuilt before planning this run"
|
|
2404
|
+
: "⚠️ recovered committed upgrade: migration report was verified or rebuilt before planning this run");
|
|
2405
|
+
return;
|
|
2406
|
+
}
|
|
2237
2407
|
if (journal.state === "rolled-back") {
|
|
2238
2408
|
await unlinkIfExists(lockPath);
|
|
2239
2409
|
return;
|
|
@@ -2241,10 +2411,39 @@ async function recoverInterruptedTransaction(root) {
|
|
|
2241
2411
|
const rollback = await rollbackTransaction(root, journal, journalPath, lock.id);
|
|
2242
2412
|
if (!rollback.ok) throw new Error(`interrupted upgrade has third-state edits: ${rollback.conflicts.join("; ")}`);
|
|
2243
2413
|
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
|
|
2414
|
+
console.log("⚠️ recovered interrupted upgrade: transaction-owned changes were safely rolled back before planning this run");
|
|
2415
|
+
}
|
|
2416
|
+
|
|
2417
|
+
async function quarantineUnboundUnreadableLock(root, lockPath) {
|
|
2418
|
+
let raw;
|
|
2419
|
+
try {
|
|
2420
|
+
raw = await readFile(lockPath, "utf8");
|
|
2421
|
+
} catch {
|
|
2422
|
+
return false;
|
|
2423
|
+
}
|
|
2424
|
+
const trimmed = raw.trim();
|
|
2425
|
+
if (!(trimmed === "" || trimmed === "{" || trimmed === "[")) return false;
|
|
2426
|
+
const migrationsRoot = path.join(root, "dev", "governance_migrations");
|
|
2427
|
+
const entries = await readdir(migrationsRoot, { withFileTypes: true }).catch(() => []);
|
|
2428
|
+
const activeStates = new Set(["prepared", "committing", "rollback-needed", "manual-recovery-required"]);
|
|
2429
|
+
for (const entry of entries) {
|
|
2430
|
+
if (!entry.isDirectory()) continue;
|
|
2431
|
+
const journalPath = path.join(migrationsRoot, entry.name, "transaction.json");
|
|
2432
|
+
let journal = null;
|
|
2433
|
+
try {
|
|
2434
|
+
journal = JSON.parse(await readFile(journalPath, "utf8"));
|
|
2435
|
+
} catch {
|
|
2436
|
+
continue;
|
|
2437
|
+
}
|
|
2438
|
+
if (activeStates.has(journal?.state)) return false;
|
|
2439
|
+
}
|
|
2440
|
+
const quarantinePath = path.join(migrationsRoot, `.upgrade.lock.unbound-${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}`);
|
|
2441
|
+
await rename(lockPath, quarantinePath);
|
|
2442
|
+
console.log("⚠️ recovered unbound incomplete upgrade lock: quarantined empty or partial lock before planning this run");
|
|
2443
|
+
return true;
|
|
2444
|
+
}
|
|
2445
|
+
|
|
2446
|
+
async function writeTransactionReport(transaction) {
|
|
2248
2447
|
const reportPath = path.join(transaction.migrationDir, "migration-report.md");
|
|
2249
2448
|
const lines = [
|
|
2250
2449
|
"# Agent Handoff Kit Migration Report",
|
|
@@ -2276,10 +2475,34 @@ async function writeTransactionReport(transaction) {
|
|
|
2276
2475
|
];
|
|
2277
2476
|
await writeFile(reportPath, `${lines.join("\n")}\n`, { mode: 0o600 });
|
|
2278
2477
|
await tightenPermissions(reportPath, 0o600);
|
|
2279
|
-
return reportPath;
|
|
2280
|
-
}
|
|
2281
|
-
|
|
2282
|
-
function
|
|
2478
|
+
return reportPath;
|
|
2479
|
+
}
|
|
2480
|
+
|
|
2481
|
+
async function writeCurrentStateReconciliationReport({ migrationDir, journal, reconciledPaths }) {
|
|
2482
|
+
const reportPath = path.join(migrationDir, "migration-report.md");
|
|
2483
|
+
const lines = [
|
|
2484
|
+
"# Agent Handoff Kit Current-State Reconciliation Report",
|
|
2485
|
+
"",
|
|
2486
|
+
`- Command: ${journal.command ?? "reconcile-current-state"}`,
|
|
2487
|
+
`- Attempted version: ${journal.attemptedVersion}`,
|
|
2488
|
+
`- Committed version: ${journal.committedVersion ?? "none"}`,
|
|
2489
|
+
`- Transaction state: ${journal.state}`,
|
|
2490
|
+
`- Supersedes current-state digest: ${(journal.supersedesCurrentStateDigests ?? []).join(", ")}`,
|
|
2491
|
+
`- Current-state digest: ${journal.currentStateWitness?.currentStateDigest ?? "none"}`,
|
|
2492
|
+
`- Reconciled paths: ${reconciledPaths.join(", ")}`,
|
|
2493
|
+
...(journal.reconciliationManifestSha256 ? [`- Reconciliation manifest sha256: ${journal.reconciliationManifestSha256}`] : []),
|
|
2494
|
+
"- Project files overwritten: none",
|
|
2495
|
+
"- Transaction-owned project content writes: none",
|
|
2496
|
+
"",
|
|
2497
|
+
"## Shared Current-State Witness",
|
|
2498
|
+
...renderCurrentStateWitnessReport(journal.currentStateWitness, journal.currentStateReadback)
|
|
2499
|
+
];
|
|
2500
|
+
await writeFile(reportPath, `${lines.join("\n")}\n`, { mode: 0o600 });
|
|
2501
|
+
await tightenPermissions(reportPath, 0o600);
|
|
2502
|
+
return reportPath;
|
|
2503
|
+
}
|
|
2504
|
+
|
|
2505
|
+
function decodeUtf8(buffer, relative) {
|
|
2283
2506
|
const bom = buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf;
|
|
2284
2507
|
const body = bom ? buffer.subarray(3) : buffer;
|
|
2285
2508
|
let text;
|
|
@@ -2393,11 +2616,25 @@ async function tightenPermissions(filePath, mode) {
|
|
|
2393
2616
|
try { await chmod(filePath, mode); } catch { /* best effort on platforms without POSIX modes */ }
|
|
2394
2617
|
}
|
|
2395
2618
|
|
|
2396
|
-
async function unlinkIfExists(filePath) {
|
|
2397
|
-
try { await unlink(filePath); } catch (error) { if (error?.code !== "ENOENT") throw error; }
|
|
2398
|
-
}
|
|
2399
|
-
|
|
2400
|
-
function
|
|
2619
|
+
async function unlinkIfExists(filePath) {
|
|
2620
|
+
try { await unlink(filePath); } catch (error) { if (error?.code !== "ENOENT") throw error; }
|
|
2621
|
+
}
|
|
2622
|
+
|
|
2623
|
+
async function publishTransactionLock(root, lockPath, lockRecord) {
|
|
2624
|
+
const lockDir = path.dirname(lockPath);
|
|
2625
|
+
const tempPath = path.join(lockDir, `.upgrade.lock.${lockRecord.id}.${process.pid}.${randomUUID()}.tmp`);
|
|
2626
|
+
await writeSecureJson(tempPath, lockRecord);
|
|
2627
|
+
try {
|
|
2628
|
+
await link(tempPath, lockPath);
|
|
2629
|
+
} catch (error) {
|
|
2630
|
+
await unlinkIfExists(tempPath).catch(() => {});
|
|
2631
|
+
if (error?.code === "EEXIST") throw new Error("another upgrade transaction or unresolved recovery lock is present");
|
|
2632
|
+
throw error;
|
|
2633
|
+
}
|
|
2634
|
+
await unlinkIfExists(tempPath);
|
|
2635
|
+
}
|
|
2636
|
+
|
|
2637
|
+
function processIsAlive(pid) {
|
|
2401
2638
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
2402
2639
|
try { process.kill(pid, 0); return true; } catch { return false; }
|
|
2403
2640
|
}
|
|
@@ -2417,11 +2654,14 @@ function stripMarkdownCommentsAndFences(text) {
|
|
|
2417
2654
|
return text.replace(/<!--[\s\S]*?-->/g, "").replace(/```[\s\S]*?```/g, "");
|
|
2418
2655
|
}
|
|
2419
2656
|
|
|
2420
|
-
function safeErrorLabel(error) {
|
|
2421
|
-
return String(error?.message ?? error).slice(0, 500);
|
|
2422
|
-
}
|
|
2423
|
-
|
|
2657
|
+
function safeErrorLabel(error) {
|
|
2658
|
+
return String(error?.message ?? error).slice(0, 500);
|
|
2659
|
+
}
|
|
2660
|
+
|
|
2424
2661
|
async function runDoctor(root, version, options = {}) {
|
|
2662
|
+
if (options.allowActiveTransaction !== true && await hasActiveTransactionLock(root)) {
|
|
2663
|
+
throw new Error("current-state recovery is pending; doctor refuses a partial transaction state");
|
|
2664
|
+
}
|
|
2425
2665
|
// The transaction journal is the existing shared acceptance authority. A
|
|
2426
2666
|
// preserved non-exact rule pack may intentionally retain older/user bytes;
|
|
2427
2667
|
// its missing current-template anchors are acceptable only when this same
|
|
@@ -2831,7 +3071,7 @@ async function createSourceConservation(root, outputs, archiveMigrations = []) {
|
|
|
2831
3071
|
sourcePrefix: `${migration.originalRel}/`,
|
|
2832
3072
|
targetPrefix: `${migration.canonicalRel}/`
|
|
2833
3073
|
}));
|
|
2834
|
-
const entries = frozen.
|
|
3074
|
+
const entries = gate5SourceConservationItems(frozen).map((item) => {
|
|
2835
3075
|
const output = outputByTarget.get(item.sourcePath) ?? null;
|
|
2836
3076
|
const rebind = pathRebindings.find((candidate) => item.sourcePath.startsWith(candidate.sourcePrefix)) ?? null;
|
|
2837
3077
|
const sourcePath = rebind
|
|
@@ -2919,7 +3159,7 @@ function validateCurrentStateWitnessValue(value) {
|
|
|
2919
3159
|
|| ![1, 2, 3].includes(value.schemaVersion)
|
|
2920
3160
|
|| !value.transaction || typeof value.transaction !== "object" || Array.isArray(value.transaction)
|
|
2921
3161
|
|| typeof value.transaction.id !== "string" || !value.transaction.id
|
|
2922
|
-
|| !["init", "upgrade", "finalize-closeout"].includes(value.transaction.command)
|
|
3162
|
+
|| !["init", "upgrade", "finalize-closeout", "reconcile-current-state"].includes(value.transaction.command)
|
|
2923
3163
|
|| typeof value.transaction.mode !== "string" || !value.transaction.mode
|
|
2924
3164
|
|| !isStableSemver(value.transaction.attemptedVersion ?? "")
|
|
2925
3165
|
|| !Array.isArray(value.entries) || value.entries.length === 0
|
|
@@ -2952,12 +3192,16 @@ function validateCurrentStateWitnessValue(value) {
|
|
|
2952
3192
|
...(formalWitness ? [...formalWitness.contentPaths] : [])
|
|
2953
3193
|
]);
|
|
2954
3194
|
const seenTargets = new Set();
|
|
3195
|
+
const zeroWriteReconciliation = value.transaction.command === "reconcile-current-state" && value.transaction.mode === "source-state-reconciliation";
|
|
2955
3196
|
for (const entry of value.entries) {
|
|
2956
3197
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)
|
|
2957
3198
|
|| typeof entry.targetRel !== "string" || !knownTargets.has(entry.targetRel) || seenTargets.has(entry.targetRel)
|
|
2958
3199
|
|| typeof entry.existed !== "boolean"
|
|
2959
3200
|
|| 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)
|
|
3201
|
+
|| (entry.existed && (typeof entry.beforeHash !== "string" || !/^[a-f0-9]{64}$/.test(entry.beforeHash)
|
|
3202
|
+
|| (zeroWriteReconciliation
|
|
3203
|
+
? entry.backupRel !== null || entry.beforeHash !== entry.afterHash
|
|
3204
|
+
: typeof entry.backupRel !== "string" || !entry.backupRel)))
|
|
2961
3205
|
|| (!entry.existed && (entry.beforeHash !== null || entry.backupRel !== null))) {
|
|
2962
3206
|
throw new Error("shared current-state entry witness is invalid; no recovery writes attempted");
|
|
2963
3207
|
}
|
|
@@ -3023,7 +3267,7 @@ function validateSourceConservation(value, { required = false } = {}) {
|
|
|
3023
3267
|
|| !Array.isArray(entry.sourceByteRanges) || entry.sourceByteRanges.length !== 1
|
|
3024
3268
|
|| entry.sourceByteRanges[0]?.start !== 0 || entry.sourceByteRanges[0]?.end !== entry.sourceWitness.bytes
|
|
3025
3269
|
|| 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)
|
|
3270
|
+
|| !["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
3271
|
|| !Array.isArray(entry.existingReaders)
|
|
3028
3272
|
|| entry.existingReaders.some((reader) => !reader || typeof reader !== "object" || Array.isArray(reader) || typeof reader.reader !== "string" || !reader.reader || typeof reader.via !== "string" || !reader.via)
|
|
3029
3273
|
|| typeof entry.priorityRelation !== "string" || !entry.priorityRelation
|
|
@@ -3031,8 +3275,8 @@ function validateSourceConservation(value, { required = false } = {}) {
|
|
|
3031
3275
|
|| !Array.isArray(entry.classifications) || entry.classifications.length === 0 || entry.classifications.some((classification) => typeof classification !== "string" || !classification)) {
|
|
3032
3276
|
throw new Error("shared current-state source conservation entry is invalid; no recovery writes attempted");
|
|
3033
3277
|
}
|
|
3034
|
-
if (["canonical-path-migration", "canonical-path-migration-closeout"].includes(entry.disposition)) {
|
|
3035
|
-
if (value.schemaVersion
|
|
3278
|
+
if (["canonical-path-migration", "canonical-path-migration-closeout", "session-log-archive-reconciliation"].includes(entry.disposition) && entry.sourceOriginPath !== undefined) {
|
|
3279
|
+
if (![2, 3].includes(value.schemaVersion) || !isSafeProjectRelative(entry.sourceOriginPath)
|
|
3036
3280
|
|| entry.sourceOriginPath === entry.sourcePath
|
|
3037
3281
|
|| !entry.sourceOriginPath.startsWith("dev/") || !entry.sourcePath.startsWith("dev/SESSION_LOG_archive/")) {
|
|
3038
3282
|
throw new Error("archive source-path rebinding is invalid; no recovery writes attempted");
|
|
@@ -3886,6 +4130,8 @@ async function classifyCurrentStateRebindMismatches(projectRoot, journal) {
|
|
|
3886
4130
|
const illegalNonCloseout = [];
|
|
3887
4131
|
for (const mismatch of mismatches) {
|
|
3888
4132
|
if (isCloseoutFinalizeTarget(mismatch.path)) continue;
|
|
4133
|
+
if (mismatch.kind === "source-conservation"
|
|
4134
|
+
&& sourceConservationEntryMayRetireAsUnreachableRootSource(mismatch.sourceConservationEntry)) continue;
|
|
3889
4135
|
if (await mismatchMatchesCurrentInstalledSource(projectRoot, mismatch)) continue;
|
|
3890
4136
|
illegalNonCloseout.push(mismatch);
|
|
3891
4137
|
}
|
|
@@ -3916,9 +4162,13 @@ async function findRestoredCurrentStateDigests(root, outputs, archiveMigrations
|
|
|
3916
4162
|
if (journal.state !== "committed" || !journal.currentStateWitness) continue;
|
|
3917
4163
|
await validateRecoveryJournal(root, journal, journalPath);
|
|
3918
4164
|
const priorWitness = validateCurrentStateWitness(journal);
|
|
3919
|
-
|
|
3920
|
-
|
|
3921
|
-
|
|
4165
|
+
const sourceConservationRebind = sourceConservationEntriesRebindPrior(priorWitness, replacement.sourceConservation, archiveMigrations, {
|
|
4166
|
+
allowArchiveState: sourceConservationHasArchiveReconciliation(priorWitness.sourceConservation)
|
|
4167
|
+
|| sourceConservationHasArchiveReconciliation(replacement.sourceConservation)
|
|
4168
|
+
});
|
|
4169
|
+
if ((await journalMatchesCurrentState(root, journal) && (!priorWitness.sourceConservation || sourceConservationRebind))
|
|
4170
|
+
|| await journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations, replacement.sourceConservation)
|
|
4171
|
+
|| sourceConservationRebind) {
|
|
3922
4172
|
if (!canSupersedeCurrentStateWitness(replacement, priorWitness)) continue;
|
|
3923
4173
|
restored.push(journal.currentStateWitness.currentStateDigest);
|
|
3924
4174
|
}
|
|
@@ -3939,14 +4189,70 @@ function currentStateWitnessCapability(value = {}) {
|
|
|
3939
4189
|
function canSupersedeCurrentStateWitness(replacement, priorWitness) {
|
|
3940
4190
|
const replacementCapability = currentStateWitnessCapability(replacement);
|
|
3941
4191
|
if (priorWitness.sourceConservation && !replacementCapability.sourceConservation) return false;
|
|
4192
|
+
const archiveAuthority = sourceConservationHasArchiveReconciliation(replacement.sourceConservation)
|
|
4193
|
+
|| sourceConservationHasArchiveReconciliation(priorWitness.sourceConservation);
|
|
3942
4194
|
if (Array.isArray(priorWitness.archiveMigrations) && priorWitness.archiveMigrations.length > 0
|
|
3943
4195
|
&& !replacementCapability.archiveMigrations
|
|
3944
|
-
&& !
|
|
4196
|
+
&& !sourceConservationEntriesRebindPrior(priorWitness, replacement.sourceConservation, [], { allowArchiveState: archiveAuthority })
|
|
4197
|
+
&& !(archiveAuthority && archiveMigrationHistoryIsRebound(priorWitness, replacement.sourceConservation))) {
|
|
3945
4198
|
return false;
|
|
3946
4199
|
}
|
|
3947
4200
|
return true;
|
|
3948
4201
|
}
|
|
3949
4202
|
|
|
4203
|
+
function sourceConservationHasArchiveReconciliation(sourceConservation) {
|
|
4204
|
+
return Boolean(sourceConservation?.entries?.some((entry) => entry.disposition === "session-log-archive-reconciliation"));
|
|
4205
|
+
}
|
|
4206
|
+
|
|
4207
|
+
function sourceConservationEntryMayRetireAsUnreachableRootSource(entry) {
|
|
4208
|
+
return Boolean(entry
|
|
4209
|
+
&& Array.isArray(entry.classifications)
|
|
4210
|
+
&& entry.classifications.length === 1
|
|
4211
|
+
&& entry.classifications[0] === "root-source"
|
|
4212
|
+
&& entry.disposition === "outside-known-kit-reachability"
|
|
4213
|
+
&& Array.isArray(entry.existingReaders)
|
|
4214
|
+
&& entry.existingReaders.length === 0
|
|
4215
|
+
&& entry.priorityRelation === "outside-known-kit-reachability"
|
|
4216
|
+
&& entry.effectDecision === "outside-known-kit-reachability");
|
|
4217
|
+
}
|
|
4218
|
+
|
|
4219
|
+
function sourceConservationEntryAcceptedMatches(entry, accepted) {
|
|
4220
|
+
return Boolean(accepted
|
|
4221
|
+
&& accepted.sha256 === entry.accepted?.sha256
|
|
4222
|
+
&& accepted.bytes === entry.accepted?.bytes);
|
|
4223
|
+
}
|
|
4224
|
+
|
|
4225
|
+
function sourceConservationEntryHasAcceptedCoverage(entry) {
|
|
4226
|
+
return Boolean(entry
|
|
4227
|
+
&& entry.accepted
|
|
4228
|
+
&& typeof entry.accepted.sha256 === "string"
|
|
4229
|
+
&& Number.isInteger(entry.accepted.bytes));
|
|
4230
|
+
}
|
|
4231
|
+
|
|
4232
|
+
function sourceConservationEntriesRebindPrior(priorWitness, replacementSourceConservation, archiveMigrations = [], options = {}) {
|
|
4233
|
+
if (!priorWitness.sourceConservation) return true;
|
|
4234
|
+
if (!replacementSourceConservation) return false;
|
|
4235
|
+
const replacementByPath = new Map(replacementSourceConservation.entries.map((entry) => [entry.sourcePath, entry]));
|
|
4236
|
+
const archiveRebindings = new Map();
|
|
4237
|
+
for (const migration of [...(priorWitness.archiveMigrations ?? []), ...archiveMigrations]) {
|
|
4238
|
+
for (const file of migration.snapshot.files ?? []) {
|
|
4239
|
+
archiveRebindings.set(`${migration.originalRel}/${file.path}`, `${migration.canonicalRel}/${file.path}`);
|
|
4240
|
+
}
|
|
4241
|
+
}
|
|
4242
|
+
return priorWitness.sourceConservation.entries.every((entry) => {
|
|
4243
|
+
const archiveState = sourceConservationEntryIsSessionLogArchive(entry)
|
|
4244
|
+
|| isSessionLogArchivePath(entry.sourcePath)
|
|
4245
|
+
|| (entry.sourceOriginPath && isSessionLogArchivePath(entry.sourceOriginPath));
|
|
4246
|
+
if (archiveState && options.allowArchiveState !== true) return false;
|
|
4247
|
+
if (sourceConservationEntryMayRetireAsUnreachableRootSource(entry)) return true;
|
|
4248
|
+
const replacement = replacementByPath.get(entry.sourcePath);
|
|
4249
|
+
if (sourceConservationEntryHasAcceptedCoverage(replacement)) return true;
|
|
4250
|
+
const reboundPath = archiveRebindings.get(entry.sourcePath);
|
|
4251
|
+
const rebound = reboundPath ? replacementByPath.get(reboundPath) : null;
|
|
4252
|
+
return sourceConservationEntryAcceptedMatches(entry, rebound?.accepted);
|
|
4253
|
+
});
|
|
4254
|
+
}
|
|
4255
|
+
|
|
3950
4256
|
function sourceConservationRebindsPrior(priorWitness, replacementSourceConservation) {
|
|
3951
4257
|
if (!replacementSourceConservation) return false;
|
|
3952
4258
|
const replacementByPath = new Map(replacementSourceConservation.entries.map((entry) => [entry.sourcePath, entry]));
|
|
@@ -3958,14 +4264,7 @@ function sourceConservationRebindsPrior(priorWitness, replacementSourceConservat
|
|
|
3958
4264
|
&& Number.isInteger(replacement.accepted.bytes);
|
|
3959
4265
|
});
|
|
3960
4266
|
if (!coversTransactionEntries) return false;
|
|
3961
|
-
|
|
3962
|
-
return priorWitness.sourceConservation.entries.every((entry) => {
|
|
3963
|
-
const replacement = replacementByPath.get(entry.sourcePath);
|
|
3964
|
-
return replacement
|
|
3965
|
-
&& replacement.accepted
|
|
3966
|
-
&& typeof replacement.accepted.sha256 === "string"
|
|
3967
|
-
&& Number.isInteger(replacement.accepted.bytes);
|
|
3968
|
-
});
|
|
4267
|
+
return sourceConservationEntriesRebindPrior(priorWitness, replacementSourceConservation);
|
|
3969
4268
|
}
|
|
3970
4269
|
|
|
3971
4270
|
function archiveMigrationHistoryIsRebound(priorWitness, replacementSourceConservation) {
|
|
@@ -3982,22 +4281,12 @@ function archiveMigrationHistoryIsRebound(priorWitness, replacementSourceConserv
|
|
|
3982
4281
|
}
|
|
3983
4282
|
}
|
|
3984
4283
|
}
|
|
3985
|
-
return
|
|
4284
|
+
return sourceConservationEntriesRebindPrior(priorWitness, replacementSourceConservation, [], { allowArchiveState: true });
|
|
3986
4285
|
}
|
|
3987
4286
|
|
|
3988
|
-
async function journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations = []) {
|
|
4287
|
+
async function journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations = [], replacementSourceConservation = null) {
|
|
3989
4288
|
const witness = validateCurrentStateWitness(journal);
|
|
3990
|
-
const
|
|
3991
|
-
for (const migration of archiveMigrations) {
|
|
3992
|
-
for (const file of migration.snapshot.files) {
|
|
3993
|
-
archiveRebindings.set(`${migration.originalRel}/${file.path}`, {
|
|
3994
|
-
sourcePath: `${migration.originalRel}/${file.path}`,
|
|
3995
|
-
reboundPath: `${migration.canonicalRel}/${file.path}`,
|
|
3996
|
-
sha256: file.sha256,
|
|
3997
|
-
bytes: file.bytes
|
|
3998
|
-
});
|
|
3999
|
-
}
|
|
4000
|
-
}
|
|
4289
|
+
const replacementByPath = new Map((replacementSourceConservation?.entries ?? []).map((entry) => [entry.sourcePath, entry]));
|
|
4001
4290
|
for (const entry of journal.entries) {
|
|
4002
4291
|
const replacement = outputWitnesses.get(entry.targetRel);
|
|
4003
4292
|
if (replacement) {
|
|
@@ -4013,11 +4302,13 @@ async function journalIsRestoredByOutputs(root, journal, outputWitnesses, archiv
|
|
|
4013
4302
|
if (replacement.sha256 !== entry.accepted.sha256 || replacement.bytes !== entry.accepted.bytes) return false;
|
|
4014
4303
|
continue;
|
|
4015
4304
|
}
|
|
4016
|
-
const
|
|
4017
|
-
if (
|
|
4018
|
-
if (
|
|
4305
|
+
const sourceReplacement = replacementByPath.get(entry.sourcePath);
|
|
4306
|
+
if (sourceReplacement) {
|
|
4307
|
+
if (!sourceConservationEntryHasAcceptedCoverage(sourceReplacement)) return false;
|
|
4019
4308
|
continue;
|
|
4020
4309
|
}
|
|
4310
|
+
if (sourceConservationEntryIsSessionLogArchive(entry) || isSessionLogArchivePath(entry.sourcePath)) return false;
|
|
4311
|
+
if (!sourceConservationEntryMayRetireAsUnreachableRootSource(entry)) return false;
|
|
4021
4312
|
const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
|
|
4022
4313
|
if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) return false;
|
|
4023
4314
|
}
|
|
@@ -4225,14 +4516,14 @@ async function currentStateMismatches(root, journal) {
|
|
|
4225
4516
|
for (const entry of witness.sourceConservation?.entries ?? []) {
|
|
4226
4517
|
const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
|
|
4227
4518
|
if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) {
|
|
4228
|
-
mismatches.set(entry.sourcePath, { path: entry.sourcePath, kind: "source-conservation" });
|
|
4519
|
+
mismatches.set(entry.sourcePath, { path: entry.sourcePath, kind: "source-conservation", sourceConservationEntry: entry });
|
|
4229
4520
|
}
|
|
4230
4521
|
}
|
|
4231
4522
|
if (witness.sourceConservation) {
|
|
4232
4523
|
const conserved = new Set(witness.sourceConservation.entries.map((entry) => entry.sourcePath));
|
|
4233
4524
|
const currentFrozen = await freezeGate5Set({ root });
|
|
4234
4525
|
assertGate5FrozenSet(currentFrozen);
|
|
4235
|
-
for (const item of currentFrozen
|
|
4526
|
+
for (const item of gate5SourceConservationItems(currentFrozen)) {
|
|
4236
4527
|
if (conserved.has(item.sourcePath) || isFinalizeJournalState(item.sourcePath)) continue;
|
|
4237
4528
|
mismatches.set(item.sourcePath, { path: item.sourcePath, kind: "new-source" });
|
|
4238
4529
|
}
|
|
@@ -4240,6 +4531,480 @@ async function currentStateMismatches(root, journal) {
|
|
|
4240
4531
|
return [...mismatches.values()].sort((left, right) => left.path.localeCompare(right.path));
|
|
4241
4532
|
}
|
|
4242
4533
|
|
|
4534
|
+
async function findCurrentStateReconciliationBase(root, version) {
|
|
4535
|
+
const migrationsRoot = path.join(root, "dev", "governance_migrations");
|
|
4536
|
+
let names;
|
|
4537
|
+
try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") return null; throw error; }
|
|
4538
|
+
const records = [];
|
|
4539
|
+
const superseded = new Set();
|
|
4540
|
+
for (const name of names) {
|
|
4541
|
+
if (name === ".upgrade.lock") continue;
|
|
4542
|
+
const journalPath = path.join(migrationsRoot, name, "transaction.json");
|
|
4543
|
+
try {
|
|
4544
|
+
const stats = await lstat(journalPath);
|
|
4545
|
+
if (!stats.isFile() || stats.isSymbolicLink()) continue;
|
|
4546
|
+
const journal = JSON.parse(await readFile(journalPath, "utf8"));
|
|
4547
|
+
if (journal.state !== "committed" || !journal.currentStateWitness) continue;
|
|
4548
|
+
await validateRecoveryJournal(root, journal, journalPath);
|
|
4549
|
+
const witness = validateCurrentStateWitness(journal);
|
|
4550
|
+
for (const digest of witness.transaction.supersedesCurrentStateDigests ?? []) superseded.add(digest);
|
|
4551
|
+
records.push({ journal, journalPath, witness, matches: await journalMatchesCurrentState(root, journal) });
|
|
4552
|
+
} catch (error) {
|
|
4553
|
+
if (error?.code !== "ENOENT") throw error;
|
|
4554
|
+
}
|
|
4555
|
+
}
|
|
4556
|
+
const stale = records
|
|
4557
|
+
.filter((record) => !record.matches && record.witness.sourceConservation && !superseded.has(record.witness.currentStateDigest));
|
|
4558
|
+
if (stale.length === 0) return null;
|
|
4559
|
+
if (stale.length > 1) {
|
|
4560
|
+
const digests = stale.map((record) => record.witness.currentStateDigest).join(", ");
|
|
4561
|
+
throw new Error(`current-state reconciliation refuses ambiguous stale source-conservation authorities: ${digests}`);
|
|
4562
|
+
}
|
|
4563
|
+
const currentFrozen = await freezeGate5Set({ root });
|
|
4564
|
+
assertGate5FrozenSet(currentFrozen);
|
|
4565
|
+
const classified = await classifyCurrentStateReconciliationMismatches(root, stale[0].journal, currentFrozen);
|
|
4566
|
+
const candidate = { ...stale[0], currentFrozen, ...classified };
|
|
4567
|
+
if (candidate.illegal.length > 0 || candidate.reconcilable.length === 0) return candidate;
|
|
4568
|
+
return await createCurrentStateReconciliationVerifiedPlan(root, version, candidate);
|
|
4569
|
+
}
|
|
4570
|
+
|
|
4571
|
+
async function classifyCurrentStateReconciliationMismatches(root, journal, currentFrozen) {
|
|
4572
|
+
const currentByPath = new Map(gate5SourceConservationItems(currentFrozen).map((item) => [item.sourcePath, item]));
|
|
4573
|
+
const mismatches = await currentStateMismatches(root, journal);
|
|
4574
|
+
const reconcilable = [];
|
|
4575
|
+
const archive = [];
|
|
4576
|
+
const illegal = [];
|
|
4577
|
+
const archiveQualification = await qualifySessionLogArchive(root, currentFrozen);
|
|
4578
|
+
for (const mismatch of mismatches) {
|
|
4579
|
+
if (isCloseoutFinalizeTarget(mismatch.path)) {
|
|
4580
|
+
reconcilable.push({ ...mismatch, reason: "legal closeout state readback" });
|
|
4581
|
+
continue;
|
|
4582
|
+
}
|
|
4583
|
+
if (mismatchIsSessionLogArchiveDelta(mismatch, currentByPath.get(mismatch.path))) {
|
|
4584
|
+
if (archiveQualification.ok) {
|
|
4585
|
+
archive.push({ ...mismatch, reason: "qualified session-log archive maintenance readback" });
|
|
4586
|
+
} else {
|
|
4587
|
+
illegal.push({ ...mismatch, reason: archiveQualification.reason });
|
|
4588
|
+
}
|
|
4589
|
+
continue;
|
|
4590
|
+
}
|
|
4591
|
+
if (mismatch.kind === "source-conservation"
|
|
4592
|
+
&& sourceConservationEntryMayReconcileAsUserOwnedFormal(mismatch.sourceConservationEntry, currentByPath.get(mismatch.path))) {
|
|
4593
|
+
reconcilable.push({ ...mismatch, reason: "user-owned formal source readback" });
|
|
4594
|
+
continue;
|
|
4595
|
+
}
|
|
4596
|
+
if (mismatch.kind === "new-source"
|
|
4597
|
+
&& gate5ItemMayReconcileAsUserOwnedFormal(currentByPath.get(mismatch.path))) {
|
|
4598
|
+
reconcilable.push({ ...mismatch, reason: "new user-owned formal source readback" });
|
|
4599
|
+
continue;
|
|
4600
|
+
}
|
|
4601
|
+
illegal.push({ ...mismatch, reason: currentStateReconciliationBlockReason(mismatch, currentByPath.get(mismatch.path)) });
|
|
4602
|
+
}
|
|
4603
|
+
return {
|
|
4604
|
+
mismatches,
|
|
4605
|
+
currentByPath,
|
|
4606
|
+
archive,
|
|
4607
|
+
archiveQualification,
|
|
4608
|
+
reconcilable: [...reconcilable, ...archive].sort((left, right) => left.path.localeCompare(right.path)),
|
|
4609
|
+
illegal
|
|
4610
|
+
};
|
|
4611
|
+
}
|
|
4612
|
+
|
|
4613
|
+
function mismatchIsSessionLogArchiveDelta(mismatch, currentItem) {
|
|
4614
|
+
return Boolean(isSessionLogArchivePath(mismatch.path)
|
|
4615
|
+
|| sourceConservationEntryIsSessionLogArchive(mismatch.sourceConservationEntry)
|
|
4616
|
+
|| (currentItem?.classifications ?? []).some((classification) => ["session-log-archive", "legacy-session-log-archive"].includes(classification)));
|
|
4617
|
+
}
|
|
4618
|
+
|
|
4619
|
+
async function qualifySessionLogArchive(root, currentFrozen) {
|
|
4620
|
+
const archiveCasing = await checkSessionLogArchiveCasing(root);
|
|
4621
|
+
if (!archiveCasing.ok) return { ok: false, reason: archiveCasing.finding, inventory: null };
|
|
4622
|
+
const archiveRoot = path.join(root, canonicalSessionLogArchiveRoot);
|
|
4623
|
+
const archiveStats = await lstat(archiveRoot).catch((error) => error?.code === "ENOENT" ? null : Promise.reject(error));
|
|
4624
|
+
if (!archiveStats) return { ok: false, reason: "canonical session-log archive root is missing", inventory: null };
|
|
4625
|
+
if (!archiveStats.isDirectory() || archiveStats.isSymbolicLink()) return { ok: false, reason: "canonical session-log archive root is not a safe real directory", inventory: null };
|
|
4626
|
+
const rootReal = await realpath(root);
|
|
4627
|
+
const archiveReal = await realpath(archiveRoot);
|
|
4628
|
+
if (!isInside(rootReal, archiveReal)) return { ok: false, reason: "canonical session-log archive root resolves outside selected root", inventory: null };
|
|
4629
|
+
const route = gate5SourceConservationItems(currentFrozen).find((item) => item.sourcePath === "dev/SESSION_LOG.md");
|
|
4630
|
+
if (!route
|
|
4631
|
+
|| sourceConservationEntryIsSessionLogArchive({ classifications: route.classifications })
|
|
4632
|
+
|| !Array.isArray(route.existingReaders)
|
|
4633
|
+
|| route.existingReaders.length === 0
|
|
4634
|
+
|| route.effect?.decision !== "preserve-existing-route-or-stop") {
|
|
4635
|
+
return { ok: false, reason: "current non-archive SESSION_LOG formal route is not mechanically verifiable", inventory: null };
|
|
4636
|
+
}
|
|
4637
|
+
const inventory = await inventorySessionLogArchiveTree(root, archiveRoot, archiveReal);
|
|
4638
|
+
const index = inventory.files.find((file) => file.path === "INDEX.md");
|
|
4639
|
+
if (!index) return { ok: false, reason: "session-log archive INDEX.md is missing", inventory };
|
|
4640
|
+
const indexText = await readFile(path.join(archiveRoot, "INDEX.md"), "utf8");
|
|
4641
|
+
const listed = extractArchiveIndexBatchList(indexText);
|
|
4642
|
+
if (listed.includes("INDEX.md")) return { ok: false, reason: "session-log archive INDEX.md must not self-reference", inventory };
|
|
4643
|
+
const duplicates = listed.filter((item, indexOfItem) => listed.indexOf(item) !== indexOfItem);
|
|
4644
|
+
if (duplicates.length > 0) return { ok: false, reason: `session-log archive INDEX.md has duplicate archive entries: ${[...new Set(duplicates)].join(", ")}`, inventory };
|
|
4645
|
+
const actualArchiveItems = inventory.files
|
|
4646
|
+
.map((file) => file.path)
|
|
4647
|
+
.filter((filePath) => filePath !== "INDEX.md")
|
|
4648
|
+
.sort((left, right) => left.localeCompare(right));
|
|
4649
|
+
const listedSorted = [...listed].sort((left, right) => left.localeCompare(right));
|
|
4650
|
+
if (JSON.stringify(actualArchiveItems) !== JSON.stringify(listedSorted)) {
|
|
4651
|
+
return {
|
|
4652
|
+
ok: false,
|
|
4653
|
+
reason: `session-log archive INDEX/list mismatch: listed=${listedSorted.join(", ") || "none"} actual=${actualArchiveItems.join(", ") || "none"}`,
|
|
4654
|
+
inventory
|
|
4655
|
+
};
|
|
4656
|
+
}
|
|
4657
|
+
return {
|
|
4658
|
+
ok: true,
|
|
4659
|
+
reason: "canonical session-log archive inventory and INDEX are bidirectionally verified",
|
|
4660
|
+
inventory: {
|
|
4661
|
+
...inventory,
|
|
4662
|
+
indexSha256: index.sha256,
|
|
4663
|
+
listedArchiveItems: listedSorted,
|
|
4664
|
+
inventorySha256: sha256(Buffer.from(`${JSON.stringify({
|
|
4665
|
+
root: canonicalSessionLogArchiveRoot,
|
|
4666
|
+
directories: inventory.directories,
|
|
4667
|
+
files: inventory.files,
|
|
4668
|
+
listedArchiveItems: listedSorted
|
|
4669
|
+
})}\n`, "utf8"))
|
|
4670
|
+
}
|
|
4671
|
+
};
|
|
4672
|
+
}
|
|
4673
|
+
|
|
4674
|
+
async function inventorySessionLogArchiveTree(root, archiveRoot, archiveReal) {
|
|
4675
|
+
const directories = [];
|
|
4676
|
+
const files = [];
|
|
4677
|
+
async function visit(currentAbs, relative) {
|
|
4678
|
+
const entries = await readdir(currentAbs, { withFileTypes: true });
|
|
4679
|
+
for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
|
|
4680
|
+
const childAbs = path.join(currentAbs, entry.name);
|
|
4681
|
+
const childRel = relative ? `${relative}/${entry.name}` : entry.name;
|
|
4682
|
+
const stats = await lstat(childAbs);
|
|
4683
|
+
if (stats.isSymbolicLink()) throw new Error(`${canonicalSessionLogArchiveRoot}/${childRel}: archive qualification rejects symbolic links, junctions, and reparse points`);
|
|
4684
|
+
const childReal = await realpath(childAbs);
|
|
4685
|
+
if (!isInside(archiveReal, childReal) || !isInside(root, childReal)) {
|
|
4686
|
+
throw new Error(`${canonicalSessionLogArchiveRoot}/${childRel}: archive item resolves outside the canonical archive root`);
|
|
4687
|
+
}
|
|
4688
|
+
if (stats.isDirectory()) {
|
|
4689
|
+
directories.push(childRel);
|
|
4690
|
+
await visit(childAbs, childRel);
|
|
4691
|
+
} else if (stats.isFile()) {
|
|
4692
|
+
const bytes = await readFile(childAbs);
|
|
4693
|
+
files.push({ path: childRel, sha256: sha256(bytes), bytes: bytes.length });
|
|
4694
|
+
} else {
|
|
4695
|
+
throw new Error(`${canonicalSessionLogArchiveRoot}/${childRel}: archive qualification accepts only regular files and directories`);
|
|
4696
|
+
}
|
|
4697
|
+
}
|
|
4698
|
+
}
|
|
4699
|
+
await visit(archiveRoot, "");
|
|
4700
|
+
return {
|
|
4701
|
+
root: canonicalSessionLogArchiveRoot,
|
|
4702
|
+
directories: directories.sort((left, right) => left.localeCompare(right)),
|
|
4703
|
+
files: files.sort((left, right) => left.path.localeCompare(right.path))
|
|
4704
|
+
};
|
|
4705
|
+
}
|
|
4706
|
+
|
|
4707
|
+
function extractArchiveIndexBatchList(indexText) {
|
|
4708
|
+
const matches = [...indexText.matchAll(/\b([A-Za-z0-9._-]*archive[A-Za-z0-9._-]*\.md)\b/gu)]
|
|
4709
|
+
.map((match) => match[1])
|
|
4710
|
+
.filter((name) => !name.includes("/") && !name.includes("\\"));
|
|
4711
|
+
return matches.sort((left, right) => left.localeCompare(right));
|
|
4712
|
+
}
|
|
4713
|
+
|
|
4714
|
+
async function createCurrentStateReconciliationVerifiedPlan(root, version, candidate) {
|
|
4715
|
+
const rootReal = await realpath(root);
|
|
4716
|
+
const activeWitness = validateCurrentStateWitness(candidate.journal);
|
|
4717
|
+
const currentByPath = new Map(gate5SourceConservationItems(candidate.currentFrozen).map((item) => [item.sourcePath, item]));
|
|
4718
|
+
const transactionEntries = [];
|
|
4719
|
+
for (const entry of activeWitness.entries) {
|
|
4720
|
+
const current = await readOptionalBuffer(path.join(root, entry.targetRel));
|
|
4721
|
+
if (!current) throw new Error(`${entry.targetRel}: cannot reconcile missing transaction target`);
|
|
4722
|
+
const witness = { sha256: sha256(current), bytes: current.length };
|
|
4723
|
+
transactionEntries.push({
|
|
4724
|
+
targetRel: entry.targetRel,
|
|
4725
|
+
existed: true,
|
|
4726
|
+
beforeHash: witness.sha256,
|
|
4727
|
+
afterHash: witness.sha256,
|
|
4728
|
+
backupRel: null,
|
|
4729
|
+
committed: false,
|
|
4730
|
+
witness
|
|
4731
|
+
});
|
|
4732
|
+
}
|
|
4733
|
+
const reconcilePaths = new Set(candidate.reconcilable.map((item) => item.path));
|
|
4734
|
+
const archiveReconcilePaths = new Set((candidate.archive ?? []).map((item) => item.path));
|
|
4735
|
+
const oldSourceByPath = new Map((activeWitness.sourceConservation?.entries ?? []).map((entry) => [entry.sourcePath, entry]));
|
|
4736
|
+
const sourceEntries = [];
|
|
4737
|
+
for (const item of gate5SourceConservationItems(candidate.currentFrozen).filter((entry) => !isFinalizeJournalState(entry.sourcePath))) {
|
|
4738
|
+
const entry = oldSourceByPath.get(item.sourcePath) ?? null;
|
|
4739
|
+
const current = await readOptionalBuffer(path.join(root, item.sourcePath));
|
|
4740
|
+
if (!current) throw new Error(`${item.sourcePath}: cannot reconcile missing source`);
|
|
4741
|
+
const currentWitness = { sha256: sha256(current), bytes: current.length };
|
|
4742
|
+
const priorAccepted = entry?.accepted ?? currentWitness;
|
|
4743
|
+
const changedFromPrior = currentWitness.sha256 !== priorAccepted.sha256 || currentWitness.bytes !== priorAccepted.bytes;
|
|
4744
|
+
const disposition = isCloseoutFinalizeTarget(item.sourcePath) && changedFromPrior
|
|
4745
|
+
? entry?.sourceOriginPath
|
|
4746
|
+
? "canonical-path-migration-closeout"
|
|
4747
|
+
: "closeout-state-finalize"
|
|
4748
|
+
: archiveReconcilePaths.has(item.sourcePath)
|
|
4749
|
+
? "session-log-archive-reconciliation"
|
|
4750
|
+
: reconcilePaths.has(item.sourcePath)
|
|
4751
|
+
? "user-owned-reconciliation"
|
|
4752
|
+
: entry?.disposition ?? (item.classifications.includes("transaction-state") ? "retained-historical-state" : "unchanged-source");
|
|
4753
|
+
sourceEntries.push({
|
|
4754
|
+
sourcePath: item.sourcePath,
|
|
4755
|
+
...(entry?.sourceOriginPath && ["canonical-path-migration", "canonical-path-migration-closeout", "session-log-archive-reconciliation"].includes(disposition) ? { sourceOriginPath: entry.sourceOriginPath } : {}),
|
|
4756
|
+
sourceWitness: currentWitness,
|
|
4757
|
+
accepted: currentWitness,
|
|
4758
|
+
sourceByteRanges: [{ start: 0, end: currentWitness.bytes, sha256: currentWitness.sha256 }],
|
|
4759
|
+
disposition,
|
|
4760
|
+
existingReaders: entry?.existingReaders ?? item.existingReaders.map((reader) => ({ reader: reader.reader, via: reader.via })),
|
|
4761
|
+
priorityRelation: entry?.priorityRelation ?? item.priorityConflict.relation,
|
|
4762
|
+
effectDecision: entry?.effectDecision ?? item.effect.decision,
|
|
4763
|
+
classifications: entry?.classifications ?? [...item.classifications]
|
|
4764
|
+
});
|
|
4765
|
+
}
|
|
4766
|
+
const deltas = [];
|
|
4767
|
+
for (const item of candidate.reconcilable) {
|
|
4768
|
+
const prior = item.sourceConservationEntry?.accepted ?? null;
|
|
4769
|
+
const currentWitness = sourceEntries.find((entry) => entry.sourcePath === item.path)?.accepted
|
|
4770
|
+
?? transactionEntries.find((entry) => entry.targetRel === item.path)?.witness
|
|
4771
|
+
?? { missing: true };
|
|
4772
|
+
const currentItem = currentByPath.get(item.path) ?? null;
|
|
4773
|
+
deltas.push({
|
|
4774
|
+
path: item.path,
|
|
4775
|
+
kind: item.kind,
|
|
4776
|
+
prior: prior ?? { missing: true },
|
|
4777
|
+
current: currentWitness,
|
|
4778
|
+
classification: currentItem?.classifications ?? item.sourceConservationEntry?.classifications ?? [],
|
|
4779
|
+
existingReaders: currentItem?.existingReaders ?? item.sourceConservationEntry?.existingReaders ?? [],
|
|
4780
|
+
priorityRelation: currentItem?.priorityConflict?.relation ?? item.sourceConservationEntry?.priorityRelation ?? null,
|
|
4781
|
+
effectDecision: currentItem?.effect?.decision ?? item.sourceConservationEntry?.effectDecision ?? null,
|
|
4782
|
+
reason: item.reason,
|
|
4783
|
+
authority: mismatchIsSessionLogArchiveDelta(item, currentItem) ? "session-log-archive-qualification" : "generic-formal-current-state-reconciliation",
|
|
4784
|
+
archiveQualification: mismatchIsSessionLogArchiveDelta(item, currentItem)
|
|
4785
|
+
? {
|
|
4786
|
+
ok: candidate.archiveQualification.ok,
|
|
4787
|
+
reason: candidate.archiveQualification.reason,
|
|
4788
|
+
inventorySha256: candidate.archiveQualification.inventory?.inventorySha256 ?? null
|
|
4789
|
+
}
|
|
4790
|
+
: null
|
|
4791
|
+
});
|
|
4792
|
+
}
|
|
4793
|
+
const manifest = {
|
|
4794
|
+
schemaVersion: 1,
|
|
4795
|
+
command: "reconcile-current-state",
|
|
4796
|
+
root: {
|
|
4797
|
+
selected: path.resolve(root),
|
|
4798
|
+
realpath: rootReal
|
|
4799
|
+
},
|
|
4800
|
+
toolVersion: version,
|
|
4801
|
+
activeWitness: {
|
|
4802
|
+
digest: activeWitness.currentStateDigest,
|
|
4803
|
+
command: activeWitness.transaction.command,
|
|
4804
|
+
attemptedVersion: activeWitness.transaction.attemptedVersion,
|
|
4805
|
+
schemaVersion: activeWitness.schemaVersion
|
|
4806
|
+
},
|
|
4807
|
+
supersededWitnessDigests: activeWitness.transaction.supersedesCurrentStateDigests ?? [],
|
|
4808
|
+
directCloseoutStateTargets,
|
|
4809
|
+
archiveInventory: candidate.archiveQualification.inventory
|
|
4810
|
+
? {
|
|
4811
|
+
root: canonicalSessionLogArchiveRoot,
|
|
4812
|
+
inventorySha256: candidate.archiveQualification.inventory.inventorySha256,
|
|
4813
|
+
indexSha256: candidate.archiveQualification.inventory.indexSha256,
|
|
4814
|
+
files: candidate.archiveQualification.inventory.files,
|
|
4815
|
+
directories: candidate.archiveQualification.inventory.directories,
|
|
4816
|
+
listedArchiveItems: candidate.archiveQualification.inventory.listedArchiveItems
|
|
4817
|
+
}
|
|
4818
|
+
: null,
|
|
4819
|
+
archiveQualification: {
|
|
4820
|
+
ok: candidate.archiveQualification.ok,
|
|
4821
|
+
reason: candidate.archiveQualification.reason
|
|
4822
|
+
},
|
|
4823
|
+
deltas: deltas.sort((left, right) => left.path.localeCompare(right.path))
|
|
4824
|
+
};
|
|
4825
|
+
return {
|
|
4826
|
+
...candidate,
|
|
4827
|
+
transactionEntries,
|
|
4828
|
+
sourceConservation: {
|
|
4829
|
+
schemaVersion: activeWitness.sourceConservation.schemaVersion,
|
|
4830
|
+
frozenSetSha256: candidate.currentFrozen.frozenSetSha256,
|
|
4831
|
+
entries: sourceEntries.sort((left, right) => left.sourcePath.localeCompare(right.sourcePath))
|
|
4832
|
+
},
|
|
4833
|
+
manifest,
|
|
4834
|
+
manifestSha256: sha256(Buffer.from(`${JSON.stringify(manifest)}\n`, "utf8"))
|
|
4835
|
+
};
|
|
4836
|
+
}
|
|
4837
|
+
|
|
4838
|
+
async function assertCurrentStateReconciliationVerifiedPlanStillCurrent(root, plan) {
|
|
4839
|
+
const activeWitness = validateCurrentStateWitness(plan.journal);
|
|
4840
|
+
if (activeWitness.currentStateDigest !== plan.manifest.activeWitness.digest) {
|
|
4841
|
+
throw new Error("current-state reconciliation active witness changed before writes; no files written");
|
|
4842
|
+
}
|
|
4843
|
+
for (const entry of plan.transactionEntries) {
|
|
4844
|
+
const current = await readOptionalBuffer(path.join(root, entry.targetRel));
|
|
4845
|
+
if (!current || sha256(current) !== entry.afterHash || current.length !== entry.witness.bytes) {
|
|
4846
|
+
throw new Error(`${entry.targetRel}: current-state reconciliation target changed before writes; no files written`);
|
|
4847
|
+
}
|
|
4848
|
+
}
|
|
4849
|
+
for (const entry of plan.sourceConservation.entries) {
|
|
4850
|
+
const current = await readOptionalBuffer(path.join(root, entry.sourcePath));
|
|
4851
|
+
if (!current || sha256(current) !== entry.accepted.sha256 || current.length !== entry.accepted.bytes) {
|
|
4852
|
+
throw new Error(`${entry.sourcePath}: current-state reconciliation source changed before writes; no files written`);
|
|
4853
|
+
}
|
|
4854
|
+
}
|
|
4855
|
+
}
|
|
4856
|
+
|
|
4857
|
+
function currentStateReconciliationBlockReason(mismatch, currentItem) {
|
|
4858
|
+
if (mismatch.kind === "transaction-entry") return "transaction entry is not a legal closeout target";
|
|
4859
|
+
if (installedFileContract(mismatch.path)) return "installed Kit contract remains fail-closed";
|
|
4860
|
+
if (isSessionLogArchivePath(mismatch.path)
|
|
4861
|
+
|| sourceConservationEntryIsSessionLogArchive(mismatch.sourceConservationEntry)
|
|
4862
|
+
|| currentItem?.classifications?.some((classification) => ["session-log-archive", "legacy-session-log-archive"].includes(classification))) {
|
|
4863
|
+
return "session-log archive state remains fail-closed until the canonical archive group qualifies";
|
|
4864
|
+
}
|
|
4865
|
+
if (currentItem?.classifications?.some((classification) => ["managed-contract", "transaction-state", "legacy-session-log-archive", "session-log-archive"].includes(classification))) {
|
|
4866
|
+
return "Kit-managed, transaction, or archive state remains fail-closed";
|
|
4867
|
+
}
|
|
4868
|
+
return "not a user-owned formally reachable reconciliation entry";
|
|
4869
|
+
}
|
|
4870
|
+
|
|
4871
|
+
function sourceConservationEntryMayReconcileAsUserOwnedFormal(entry, currentItem) {
|
|
4872
|
+
return Boolean(entry
|
|
4873
|
+
&& Array.isArray(entry.classifications)
|
|
4874
|
+
&& entry.classifications.includes("root-source")
|
|
4875
|
+
&& entry.classifications.includes("formal-reference")
|
|
4876
|
+
&& !entry.classifications.some((classification) => ["managed-contract", "transaction-state", "legacy-session-log-archive", "session-log-archive"].includes(classification))
|
|
4877
|
+
&& Array.isArray(entry.existingReaders)
|
|
4878
|
+
&& entry.existingReaders.length > 0
|
|
4879
|
+
&& entry.priorityRelation !== "outside-known-kit-reachability"
|
|
4880
|
+
&& entry.effectDecision === "preserve-existing-route-or-stop"
|
|
4881
|
+
&& gate5ItemMayReconcileAsUserOwnedFormal(currentItem));
|
|
4882
|
+
}
|
|
4883
|
+
|
|
4884
|
+
function gate5ItemMayReconcileAsUserOwnedFormal(item) {
|
|
4885
|
+
// `user-or-unknown` is deliberately not treated as ownership proof. It is
|
|
4886
|
+
// only the negative half of the authority test: the path is not an exact
|
|
4887
|
+
// installed Kit contract. Reconciliation still requires a formal reader,
|
|
4888
|
+
// preserve-or-stop effect, no managed/transaction/archive classification, and
|
|
4889
|
+
// a fresh whole-file readback before any current-state authority changes.
|
|
4890
|
+
return Boolean(item
|
|
4891
|
+
&& item.ownership === "user-or-unknown"
|
|
4892
|
+
&& Array.isArray(item.classifications)
|
|
4893
|
+
&& item.classifications.includes("root-source")
|
|
4894
|
+
&& item.classifications.includes("formal-reference")
|
|
4895
|
+
&& !item.classifications.some((classification) => ["managed-contract", "transaction-state", "legacy-session-log-archive", "session-log-archive"].includes(classification))
|
|
4896
|
+
&& Array.isArray(item.existingReaders)
|
|
4897
|
+
&& item.existingReaders.length > 0
|
|
4898
|
+
&& item.effect?.decision === "preserve-existing-route-or-stop"
|
|
4899
|
+
&& !installedFileContract(item.sourcePath)
|
|
4900
|
+
&& !isCloseoutFinalizeTarget(item.sourcePath)
|
|
4901
|
+
&& !isFinalizeJournalState(item.sourcePath));
|
|
4902
|
+
}
|
|
4903
|
+
|
|
4904
|
+
async function writeCurrentStateReconciliationJournal(root, version, candidate, options = {}) {
|
|
4905
|
+
const command = "reconcile-current-state";
|
|
4906
|
+
const mode = "source-state-reconciliation";
|
|
4907
|
+
const oldWitness = validateCurrentStateWitness(candidate.journal);
|
|
4908
|
+
const retainedArchiveMigrations = oldWitness.archiveMigrations ?? [];
|
|
4909
|
+
const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}`;
|
|
4910
|
+
const migrationsRoot = path.join(root, "dev", "governance_migrations");
|
|
4911
|
+
const migrationDir = path.join(migrationsRoot, id);
|
|
4912
|
+
const journalPath = path.join(migrationDir, "transaction.json");
|
|
4913
|
+
const lockPath = path.join(migrationsRoot, ".upgrade.lock");
|
|
4914
|
+
await mkdir(migrationDir, { recursive: true });
|
|
4915
|
+
await tightenPermissions(migrationsRoot, 0o700);
|
|
4916
|
+
await tightenPermissions(migrationDir, 0o700);
|
|
4917
|
+
|
|
4918
|
+
let journal = null;
|
|
4919
|
+
let lockCreated = false;
|
|
4920
|
+
let durableJournalPhase = null;
|
|
4921
|
+
try {
|
|
4922
|
+
journal = {
|
|
4923
|
+
id,
|
|
4924
|
+
command,
|
|
4925
|
+
mode,
|
|
4926
|
+
attemptedVersion: version,
|
|
4927
|
+
committedVersion: null,
|
|
4928
|
+
plannedSkips: 0,
|
|
4929
|
+
host: hostname(),
|
|
4930
|
+
pid: process.pid,
|
|
4931
|
+
state: "prepared",
|
|
4932
|
+
createdAt: new Date().toISOString(),
|
|
4933
|
+
committedAt: null,
|
|
4934
|
+
entries: candidate.transactionEntries.map(({ witness, ...entry }) => ({ ...entry })),
|
|
4935
|
+
formalUserRules: null,
|
|
4936
|
+
runtimeReadback: null,
|
|
4937
|
+
runtimeAcceptance: null,
|
|
4938
|
+
runtimeAcceptanceReadback: null,
|
|
4939
|
+
sourceConservation: candidate.sourceConservation,
|
|
4940
|
+
archiveMigrations: [],
|
|
4941
|
+
supersedesCurrentStateDigests: [oldWitness.currentStateDigest],
|
|
4942
|
+
currentStateWitness: null,
|
|
4943
|
+
currentStateReadback: null,
|
|
4944
|
+
reconciliationManifest: candidate.manifest,
|
|
4945
|
+
reconciliationManifestSha256: candidate.manifestSha256
|
|
4946
|
+
};
|
|
4947
|
+
await writeSecureJson(journalPath, journal);
|
|
4948
|
+
durableJournalPhase = "prepared";
|
|
4949
|
+
if (process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_RECONCILE_PREPARED_JOURNAL === "1") {
|
|
4950
|
+
throw new Error("QA generic failure after reconcile prepared journal");
|
|
4951
|
+
}
|
|
4952
|
+
|
|
4953
|
+
if (process.env.AGENT_HANDOFF_KIT_QA_CREATE_FOREIGN_RECONCILE_LOCK_BEFORE_LOCK === "1") {
|
|
4954
|
+
await publishTransactionLock(root, lockPath, {
|
|
4955
|
+
id: `qa-owner-${id}`,
|
|
4956
|
+
host: hostname(),
|
|
4957
|
+
pid: process.pid,
|
|
4958
|
+
journal: path.relative(root, journalPath),
|
|
4959
|
+
command: "qa-owner-lock"
|
|
4960
|
+
});
|
|
4961
|
+
}
|
|
4962
|
+
await publishTransactionLock(root, lockPath, { id, host: hostname(), pid: process.pid, journal: path.relative(root, journalPath), command });
|
|
4963
|
+
lockCreated = true;
|
|
4964
|
+
if (process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_RECONCILE_LOCK === "1"
|
|
4965
|
+
|| process.env.AGENT_HANDOFF_KIT_QA_INTERRUPT_AFTER_RECONCILE_LOCK === "1") {
|
|
4966
|
+
throw new Error("QA generic failure after reconcile lock with prepared journal");
|
|
4967
|
+
}
|
|
4968
|
+
|
|
4969
|
+
journal.entries = journal.entries.map((entry) => ({ ...entry, committed: true }));
|
|
4970
|
+
journal.state = "committed";
|
|
4971
|
+
journal.committedVersion = version;
|
|
4972
|
+
journal.committedAt = new Date().toISOString();
|
|
4973
|
+
journal.archiveMigrations = retainedArchiveMigrations;
|
|
4974
|
+
journal.currentStateWitness = createCurrentStateWitness(journal);
|
|
4975
|
+
await writeSecureJson(journalPath, journal);
|
|
4976
|
+
durableJournalPhase = "committed";
|
|
4977
|
+
if (process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_RECONCILE_COMMITTED_JOURNAL === "1"
|
|
4978
|
+
|| process.env.AGENT_HANDOFF_KIT_QA_INTERRUPT_AFTER_RECONCILE_JOURNAL_COMMIT === "1") {
|
|
4979
|
+
throw new Error("QA generic failure after committed reconcile journal");
|
|
4980
|
+
}
|
|
4981
|
+
if (!await journalMatchesCurrentState(root, journal)) {
|
|
4982
|
+
throw new Error("post-reconciliation current-state readback failed; reconciliation journal retained for inspection");
|
|
4983
|
+
}
|
|
4984
|
+
journal.currentStateReadback = currentStateReadbackFromVerifiedProjectBytes(journal.currentStateWitness);
|
|
4985
|
+
await writeSecureJson(journalPath, journal);
|
|
4986
|
+
await writeCurrentStateReconciliationReport({ root, migrationDir, journal, reconciledPaths: candidate.reconcilable.map((item) => item.path) });
|
|
4987
|
+
if (process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_RECONCILE_REPORT === "1") {
|
|
4988
|
+
throw new Error("QA generic failure after reconcile report");
|
|
4989
|
+
}
|
|
4990
|
+
if (process.env.AGENT_HANDOFF_KIT_QA_FAIL_BEFORE_RECONCILE_UNLOCK === "1") {
|
|
4991
|
+
throw new Error("QA generic failure before reconcile unlock");
|
|
4992
|
+
}
|
|
4993
|
+
await unlinkIfExists(lockPath);
|
|
4994
|
+
lockCreated = false;
|
|
4995
|
+
return { journalPath, journal };
|
|
4996
|
+
} catch (error) {
|
|
4997
|
+
if (lockCreated && durableJournalPhase) throw error;
|
|
4998
|
+
if (!lockCreated && durableJournalPhase === "prepared" && journal) {
|
|
4999
|
+
journal.state = "rolled-back";
|
|
5000
|
+
journal.rollbackAt = new Date().toISOString();
|
|
5001
|
+
journal.recoveryConflicts = [];
|
|
5002
|
+
await writeSecureJson(journalPath, journal).catch(() => {});
|
|
5003
|
+
}
|
|
5004
|
+
throw error;
|
|
5005
|
+
}
|
|
5006
|
+
}
|
|
5007
|
+
|
|
4243
5008
|
async function writeCloseoutFinalizeJournal(root, version, prior) {
|
|
4244
5009
|
const oldWitness = validateCurrentStateWitness(prior.journal);
|
|
4245
5010
|
const supersedesCurrentStateDigests = [...new Set([
|
|
@@ -4257,12 +5022,7 @@ async function writeCloseoutFinalizeJournal(root, version, prior) {
|
|
|
4257
5022
|
await mkdir(stageDir, { recursive: true });
|
|
4258
5023
|
await tightenPermissions(migrationsRoot, 0o700);
|
|
4259
5024
|
await tightenPermissions(migrationDir, 0o700);
|
|
4260
|
-
|
|
4261
|
-
if (error?.code === "EEXIST") throw new Error("another upgrade transaction or unresolved recovery lock is present");
|
|
4262
|
-
throw error;
|
|
4263
|
-
});
|
|
4264
|
-
await lock.writeFile(JSON.stringify({ id, host: hostname(), pid: process.pid, journal: path.relative(root, journalPath), command: "finalize-closeout" }, null, 2));
|
|
4265
|
-
await lock.close();
|
|
5025
|
+
await publishTransactionLock(root, lockPath, { id, host: hostname(), pid: process.pid, journal: path.relative(root, journalPath), command: "finalize-closeout" });
|
|
4266
5026
|
|
|
4267
5027
|
try {
|
|
4268
5028
|
const priorEntryByTarget = new Map(prior.journal.entries.map((entry) => [entry.targetRel, entry]));
|
|
@@ -4292,7 +5052,7 @@ async function writeCloseoutFinalizeJournal(root, version, prior) {
|
|
|
4292
5052
|
? {
|
|
4293
5053
|
schemaVersion: oldWitness.sourceConservation.schemaVersion,
|
|
4294
5054
|
frozenSetSha256: currentFrozen.frozenSetSha256,
|
|
4295
|
-
entries: await Promise.all(currentFrozen
|
|
5055
|
+
entries: await Promise.all(gate5SourceConservationItems(currentFrozen)
|
|
4296
5056
|
.filter((item) => !isFinalizeJournalState(item.sourcePath))
|
|
4297
5057
|
.map(async (item) => {
|
|
4298
5058
|
const entry = oldSourceByPath.get(item.sourcePath) ?? null;
|
|
@@ -4382,13 +5142,26 @@ async function writeJournalFile(base, targetRel, bytes) {
|
|
|
4382
5142
|
}
|
|
4383
5143
|
|
|
4384
5144
|
function isCloseoutFinalizeTarget(relative) {
|
|
4385
|
-
return
|
|
5145
|
+
return directCloseoutStateTargetSet.has(relative);
|
|
4386
5146
|
}
|
|
4387
5147
|
|
|
4388
5148
|
function isFinalizeJournalState(relative) {
|
|
4389
5149
|
return relative.startsWith("dev/governance_migrations/");
|
|
4390
5150
|
}
|
|
4391
5151
|
|
|
5152
|
+
function isSessionLogArchivePath(relative) {
|
|
5153
|
+
return relative === canonicalSessionLogArchiveRoot
|
|
5154
|
+
|| relative.startsWith(`${canonicalSessionLogArchiveRoot}/`)
|
|
5155
|
+
|| relative === legacySessionLogArchiveRoot
|
|
5156
|
+
|| relative.startsWith(`${legacySessionLogArchiveRoot}/`);
|
|
5157
|
+
}
|
|
5158
|
+
|
|
5159
|
+
function sourceConservationEntryIsSessionLogArchive(entry) {
|
|
5160
|
+
return Boolean(entry
|
|
5161
|
+
&& Array.isArray(entry.classifications)
|
|
5162
|
+
&& entry.classifications.some((classification) => ["session-log-archive", "legacy-session-log-archive"].includes(classification)));
|
|
5163
|
+
}
|
|
5164
|
+
|
|
4392
5165
|
async function checkRuntimeAcceptance(root, options = {}) {
|
|
4393
5166
|
const witness = options.expectedRuntimeAcceptance ?? null;
|
|
4394
5167
|
if (!witness) return { ok: true, checked: 0, finding: null, state: null };
|
|
@@ -4451,16 +5224,32 @@ function currentStateReadbackFromDoctorStates(witness, formalState, runtimeAccep
|
|
|
4451
5224
|
};
|
|
4452
5225
|
}
|
|
4453
5226
|
|
|
4454
|
-
function
|
|
5227
|
+
function currentStateReadbackFromVerifiedProjectBytes(witness) {
|
|
5228
|
+
const accepted = validateCurrentStateWitnessValue(witness);
|
|
5229
|
+
return {
|
|
5230
|
+
reader: "current-state project byte readback",
|
|
5231
|
+
currentStateDigest: accepted.currentStateDigest,
|
|
5232
|
+
sourceConservationEntryCount: accepted.sourceConservation?.entries.length ?? 0,
|
|
5233
|
+
formalUserRulesAcceptanceDigest: accepted.formalUserRules?.acceptanceDigest ?? null,
|
|
5234
|
+
runtimeAcceptanceDigest: accepted.runtimeAcceptance?.acceptanceDigest ?? null,
|
|
5235
|
+
formalUserRules: null,
|
|
5236
|
+
runtimeAcceptance: null
|
|
5237
|
+
};
|
|
5238
|
+
}
|
|
5239
|
+
|
|
5240
|
+
function validateCurrentStateReadback(value, witness, options = {}) {
|
|
4455
5241
|
if (value == null) return null;
|
|
5242
|
+
const projectByteReaderAllowed = options.allowProjectByteReader === true;
|
|
5243
|
+
const readerAllowed = value.reader === "doctor shared current-state witness check"
|
|
5244
|
+
|| (projectByteReaderAllowed && value.reader === "current-state project byte readback");
|
|
4456
5245
|
if (!value || typeof value !== "object" || Array.isArray(value)
|
|
4457
|
-
||
|
|
5246
|
+
|| !readerAllowed
|
|
4458
5247
|
|| value.currentStateDigest !== witness.currentStateDigest
|
|
4459
5248
|
|| (witness.sourceConservation && value.sourceConservationEntryCount !== witness.sourceConservation.entries.length)
|
|
4460
5249
|
|| (!witness.sourceConservation && value.sourceConservationEntryCount != null && value.sourceConservationEntryCount !== 0)
|
|
4461
5250
|
|| value.formalUserRulesAcceptanceDigest !== (witness.formalUserRules?.acceptanceDigest ?? null)
|
|
4462
5251
|
|| value.runtimeAcceptanceDigest !== (witness.runtimeAcceptance?.acceptanceDigest ?? null)) {
|
|
4463
|
-
throw new Error("shared current-state
|
|
5252
|
+
throw new Error("shared current-state readback is detached from the accepted witness; no recovery writes attempted");
|
|
4464
5253
|
}
|
|
4465
5254
|
return value;
|
|
4466
5255
|
}
|
|
@@ -8017,6 +8806,7 @@ Usage:
|
|
|
8017
8806
|
agent-handoff-kit doctor [--root <path>]
|
|
8018
8807
|
agent-handoff-kit closeout-status [--root <path>]
|
|
8019
8808
|
agent-handoff-kit finalize-closeout [--root <path>]
|
|
8809
|
+
agent-handoff-kit reconcile-current-state [--dry-run] [--yes] --manifest <sha256> [--root <path>]
|
|
8020
8810
|
|
|
8021
8811
|
Commands:
|
|
8022
8812
|
init Plan or install missing core files and rule packs.
|
|
@@ -8024,6 +8814,7 @@ Commands:
|
|
|
8024
8814
|
doctor Check required installed files.
|
|
8025
8815
|
closeout-status Render the state-bound closeout card after a full closeout.
|
|
8026
8816
|
finalize-closeout Bind legal post-upgrade closeout state edits before doctor.
|
|
8817
|
+
reconcile-current-state Bind intentional current-state source changes without overwriting project files.
|
|
8027
8818
|
|
|
8028
8819
|
中文速讀:
|
|
8029
8820
|
✅ 第一次用:先在項目資料夾執行 init。
|