@adamchanadam/agent-handoff-kit 0.3.49 → 0.3.51
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 +1 -1
- package/README.md +1 -1
- package/bin/agent-handoff-kit.mjs +366 -37
- package/bin/migration-baselines/official-origin-catalog.json +376 -1
- package/bin/upgrade-inventory.mjs +63 -34
- package/package.json +1 -1
- package/packs/closeout.md +5 -3
- package/packs/integrations.md +7 -4
- package/packs/knowledge.md +1 -1
- package/runtime-core/AGENTS.core.md +2 -2
package/README.en.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[繁體中文](README.md) · [Getting started](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-intro.en.html) · [Practical guide](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-guide.en.html) · [AI install page](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-ai-install.en.html)
|
|
4
4
|
|
|
5
|
-
Source package version: `v0.3.
|
|
5
|
+
Source package version: `v0.3.51`. npm `@latest` and GitHub Release are verified by post-publish readback.
|
|
6
6
|
|
|
7
7
|
<p align="center">
|
|
8
8
|
<img src="https://raw.githubusercontent.com/Adamchanadam/agent-handoff-kit/main/images/agent-handoff-kit-promo-30s.gif" alt="Agent Handoff Kit overview animation" width="720">
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
English: [README.en.md](README.en.md) · [Getting started](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-intro.en.html) · [Practical guide](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-guide.en.html) · [AI install page](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-ai-install.en.html)
|
|
4
4
|
|
|
5
|
-
原始碼套件版本:`v0.3.
|
|
5
|
+
原始碼套件版本:`v0.3.51`。npm `@latest` 與 GitHub Release 以發佈後讀回為準。
|
|
6
6
|
|
|
7
7
|
<p align="center">
|
|
8
8
|
<img src="https://raw.githubusercontent.com/Adamchanadam/agent-handoff-kit/main/images/agent-handoff-kit-promo-30s.gif" alt="Agent Handoff Kit 功能簡介動畫" width="720">
|
|
@@ -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,
|
|
@@ -656,6 +656,7 @@ async function runFinalizeCloseout(root, version) {
|
|
|
656
656
|
const doctorStatus = await runDoctor(root, version, {
|
|
657
657
|
silentCard: true,
|
|
658
658
|
context: "post-closeout-finalize-health",
|
|
659
|
+
skipVersionRegistryLookup: true,
|
|
659
660
|
expectedCurrentStateWitness: transaction.journal.currentStateWitness
|
|
660
661
|
});
|
|
661
662
|
if (doctorStatus !== "passed") throw new Error("post-closeout finalize doctor failed; finalize journal retained for inspection");
|
|
@@ -762,8 +763,16 @@ async function runInstall(command, root, options, version) {
|
|
|
762
763
|
// The only no-op authority here is the already committed whole current-state
|
|
763
764
|
// witness, freshly revalidated against every accepted byte, reader, route,
|
|
764
765
|
// priority, and effect by both loaders below.
|
|
766
|
+
let sourceConservationRebind = false;
|
|
765
767
|
if (command === "upgrade") {
|
|
766
|
-
|
|
768
|
+
let acceptedCurrentState = null;
|
|
769
|
+
try {
|
|
770
|
+
acceptedCurrentState = await loadCommittedCurrentStateWitness(root);
|
|
771
|
+
} catch (error) {
|
|
772
|
+
if (!String(error?.message ?? error).includes("doctor refuses an unbound success state")) throw error;
|
|
773
|
+
await assertUnboundCurrentStateMayAttemptUpgradeRebind(root, error);
|
|
774
|
+
sourceConservationRebind = true;
|
|
775
|
+
}
|
|
767
776
|
if (acceptedCurrentState?.transaction?.command === "upgrade"
|
|
768
777
|
&& acceptedCurrentState.transaction.attemptedVersion === version) {
|
|
769
778
|
const noOpHealth = await assessUpgradeNoopHealth(root, version);
|
|
@@ -890,8 +899,8 @@ async function runInstall(command, root, options, version) {
|
|
|
890
899
|
}
|
|
891
900
|
}
|
|
892
901
|
|
|
893
|
-
await executeInstallTransaction(command, root, mode, plan, version, candidateOutputs);
|
|
894
|
-
}
|
|
902
|
+
await executeInstallTransaction(command, root, mode, plan, version, candidateOutputs, { sourceConservationRebind });
|
|
903
|
+
}
|
|
895
904
|
|
|
896
905
|
async function readInstalledTemplateVersion(root) {
|
|
897
906
|
try {
|
|
@@ -903,7 +912,7 @@ async function readInstalledTemplateVersion(root) {
|
|
|
903
912
|
}
|
|
904
913
|
}
|
|
905
914
|
|
|
906
|
-
async function executeInstallTransaction(command, root, mode, plan, version, candidateOutputs = null) {
|
|
915
|
+
async function executeInstallTransaction(command, root, mode, plan, version, candidateOutputs = null, options = {}) {
|
|
907
916
|
const outputs = candidateOutputs ?? await buildTransactionOutputs(command, root, plan, version);
|
|
908
917
|
if (outputs.length === 0) {
|
|
909
918
|
const health = await assessUpgradeNoopHealth(root, version);
|
|
@@ -934,7 +943,16 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
|
|
|
934
943
|
const archiveMigrations = command === "upgrade"
|
|
935
944
|
? await prepareArchiveCasingMigrations(root)
|
|
936
945
|
: [];
|
|
937
|
-
const
|
|
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;
|
|
951
|
+
}
|
|
952
|
+
const runtimeAcceptance = command === "upgrade" && options.sourceConservationRebind !== true ? resolveRuntimeAcceptance(outputs) : null;
|
|
953
|
+
const sourceConservation = command === "upgrade" && (
|
|
954
|
+
runtimeAcceptance || sourceConservationAuthority
|
|
955
|
+
)
|
|
938
956
|
? await createSourceConservation(root, outputs, archiveMigrations)
|
|
939
957
|
: null;
|
|
940
958
|
// A repair may restore the exact bytes of a prior committed state. Keep the
|
|
@@ -942,7 +960,7 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
|
|
|
942
960
|
// doctor can select the freshly read-back transaction without falling back
|
|
943
961
|
// to mtime or a separate current-state registry.
|
|
944
962
|
const supersedesCurrentStateDigests = command === "upgrade"
|
|
945
|
-
? await findRestoredCurrentStateDigests(root, outputs, archiveMigrations)
|
|
963
|
+
? await findRestoredCurrentStateDigests(root, outputs, archiveMigrations, { sourceConservation, archiveMigrations })
|
|
946
964
|
: [];
|
|
947
965
|
const transaction = await prepareTransaction(root, command, version, outputs, mode, plan, sourceConservation, supersedesCurrentStateDigests, archiveMigrations);
|
|
948
966
|
try {
|
|
@@ -995,6 +1013,7 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
|
|
|
995
1013
|
const doctorStatus = await runDoctor(root, version, {
|
|
996
1014
|
silentCard: true,
|
|
997
1015
|
context: "post-transaction-project-health",
|
|
1016
|
+
skipVersionRegistryLookup: true,
|
|
998
1017
|
allowActiveTransaction: true,
|
|
999
1018
|
expectedCurrentStateWitness: transaction.journal.currentStateWitness,
|
|
1000
1019
|
captureFormalUserRules: (state) => { formalRuntimeState = state; },
|
|
@@ -2186,6 +2205,7 @@ async function recoverInterruptedTransaction(root) {
|
|
|
2186
2205
|
const doctorStatus = await runDoctor(root, journal.committedVersion, {
|
|
2187
2206
|
silentCard: true,
|
|
2188
2207
|
context: "recovered-committed-transaction-health",
|
|
2208
|
+
skipVersionRegistryLookup: true,
|
|
2189
2209
|
allowActiveTransaction: true,
|
|
2190
2210
|
expectedCurrentStateWitness: journal.currentStateWitness,
|
|
2191
2211
|
captureFormalUserRules: (state) => { formalRuntimeState = state; },
|
|
@@ -2811,7 +2831,7 @@ async function createSourceConservation(root, outputs, archiveMigrations = []) {
|
|
|
2811
2831
|
sourcePrefix: `${migration.originalRel}/`,
|
|
2812
2832
|
targetPrefix: `${migration.canonicalRel}/`
|
|
2813
2833
|
}));
|
|
2814
|
-
const entries = frozen.
|
|
2834
|
+
const entries = gate5SourceConservationItems(frozen).map((item) => {
|
|
2815
2835
|
const output = outputByTarget.get(item.sourcePath) ?? null;
|
|
2816
2836
|
const rebind = pathRebindings.find((candidate) => item.sourcePath.startsWith(candidate.sourcePrefix)) ?? null;
|
|
2817
2837
|
const sourcePath = rebind
|
|
@@ -3748,8 +3768,7 @@ async function loadCommittedCurrentStateWitness(root) {
|
|
|
3748
3768
|
const migrationsRoot = path.join(root, "dev", "governance_migrations");
|
|
3749
3769
|
let names;
|
|
3750
3770
|
try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") return null; throw error; }
|
|
3751
|
-
const
|
|
3752
|
-
const staleSourceConservation = [];
|
|
3771
|
+
const records = [];
|
|
3753
3772
|
for (const name of names) {
|
|
3754
3773
|
if (name === ".upgrade.lock") continue;
|
|
3755
3774
|
const journalPath = path.join(migrationsRoot, name, "transaction.json");
|
|
@@ -3759,30 +3778,131 @@ async function loadCommittedCurrentStateWitness(root) {
|
|
|
3759
3778
|
const journal = JSON.parse(await readFile(journalPath, "utf8"));
|
|
3760
3779
|
if (journal.state !== "committed" || !journal.currentStateWitness) continue;
|
|
3761
3780
|
await validateRecoveryJournal(root, journal, journalPath);
|
|
3762
|
-
|
|
3763
|
-
|
|
3781
|
+
const witness = validateCurrentStateWitness(journal);
|
|
3782
|
+
records.push({ journal, journalPath, witness, matches: await journalMatchesCurrentState(root, journal) });
|
|
3764
3783
|
} catch (error) {
|
|
3765
3784
|
if (error?.code !== "ENOENT") throw error;
|
|
3766
3785
|
}
|
|
3767
3786
|
}
|
|
3768
|
-
|
|
3787
|
+
const superseded = effectiveCurrentStateSupersededDigests(records);
|
|
3788
|
+
const staleSourceConservation = records.filter((record) => (
|
|
3789
|
+
!record.matches
|
|
3790
|
+
&& record.witness.sourceConservation
|
|
3791
|
+
&& !superseded.has(record.witness.currentStateDigest)
|
|
3792
|
+
));
|
|
3793
|
+
if (staleSourceConservation.length > 0) {
|
|
3769
3794
|
throw new Error("committed Gate 5 current-state source witness no longer matches project bytes; doctor refuses an unbound success state");
|
|
3770
3795
|
}
|
|
3796
|
+
const candidates = records.filter((record) => record.matches);
|
|
3771
3797
|
if (candidates.length === 0) return null;
|
|
3772
3798
|
// A later repair can deliberately restore the exact bytes of an earlier
|
|
3773
3799
|
// state. Its sealed supersession link is the only permitted tie-breaker:
|
|
3774
3800
|
// filesystem timestamps remain untrusted and an unlinked tie stays fatal.
|
|
3775
|
-
const
|
|
3776
|
-
journal.currentStateWitness.transaction.supersedesCurrentStateDigests ?? []
|
|
3777
|
-
)));
|
|
3778
|
-
const currentCandidates = candidates.filter(({ journal }) => !superseded.has(journal.currentStateWitness.currentStateDigest));
|
|
3801
|
+
const currentCandidates = candidates.filter(({ witness }) => !superseded.has(witness.currentStateDigest));
|
|
3779
3802
|
if (currentCandidates.length !== 1) {
|
|
3780
3803
|
throw new Error("multiple committed journals match the current filesystem state; doctor refuses ambiguous current-state authority");
|
|
3781
3804
|
}
|
|
3782
3805
|
return validateCurrentStateWitness(currentCandidates[0].journal);
|
|
3783
3806
|
}
|
|
3784
3807
|
|
|
3785
|
-
|
|
3808
|
+
function effectiveCurrentStateSupersededDigests(records) {
|
|
3809
|
+
const byDigest = new Map(records.map((record) => [record.witness.currentStateDigest, record]));
|
|
3810
|
+
const superseded = new Set();
|
|
3811
|
+
for (const record of records) {
|
|
3812
|
+
for (const digest of record.witness.transaction.supersedesCurrentStateDigests ?? []) {
|
|
3813
|
+
const prior = byDigest.get(digest);
|
|
3814
|
+
if (!prior) continue;
|
|
3815
|
+
if (canSupersedeCurrentStateWitness(record.witness, prior.witness)) superseded.add(digest);
|
|
3816
|
+
}
|
|
3817
|
+
}
|
|
3818
|
+
return superseded;
|
|
3819
|
+
}
|
|
3820
|
+
|
|
3821
|
+
async function hasCommittedSourceConservationAuthority(root) {
|
|
3822
|
+
const migrationsRoot = path.join(root, "dev", "governance_migrations");
|
|
3823
|
+
let names;
|
|
3824
|
+
try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") return false; throw error; }
|
|
3825
|
+
const records = [];
|
|
3826
|
+
for (const name of names) {
|
|
3827
|
+
if (name === ".upgrade.lock") continue;
|
|
3828
|
+
const journalPath = path.join(migrationsRoot, name, "transaction.json");
|
|
3829
|
+
try {
|
|
3830
|
+
const stats = await lstat(journalPath);
|
|
3831
|
+
if (!stats.isFile() || stats.isSymbolicLink()) continue;
|
|
3832
|
+
const journal = JSON.parse(await readFile(journalPath, "utf8"));
|
|
3833
|
+
if (journal.state !== "committed" || !journal.currentStateWitness) continue;
|
|
3834
|
+
await validateRecoveryJournal(root, journal, journalPath);
|
|
3835
|
+
records.push({ journal, journalPath, witness: validateCurrentStateWitness(journal), matches: await journalMatchesCurrentState(root, journal) });
|
|
3836
|
+
} catch (error) {
|
|
3837
|
+
if (error?.code !== "ENOENT") throw error;
|
|
3838
|
+
}
|
|
3839
|
+
}
|
|
3840
|
+
const superseded = effectiveCurrentStateSupersededDigests(records);
|
|
3841
|
+
let hasSourceConservation = false;
|
|
3842
|
+
for (const record of records) {
|
|
3843
|
+
if (!record.witness.sourceConservation || superseded.has(record.witness.currentStateDigest)) continue;
|
|
3844
|
+
hasSourceConservation = true;
|
|
3845
|
+
if (record.matches) continue;
|
|
3846
|
+
const { illegalNonCloseout } = await classifyCurrentStateRebindMismatches(root, record.journal);
|
|
3847
|
+
if (illegalNonCloseout.length > 0) {
|
|
3848
|
+
throw new Error(`conflict: non-closeout drift blocks upgrade source-conservation rebind: ${illegalNonCloseout.map((item) => item.path).join(", ")}`);
|
|
3849
|
+
}
|
|
3850
|
+
}
|
|
3851
|
+
if (hasSourceConservation) return true;
|
|
3852
|
+
return false;
|
|
3853
|
+
}
|
|
3854
|
+
|
|
3855
|
+
async function assertUnboundCurrentStateMayAttemptUpgradeRebind(root, cause) {
|
|
3856
|
+
const migrationsRoot = path.join(root, "dev", "governance_migrations");
|
|
3857
|
+
let names;
|
|
3858
|
+
try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") throw cause; throw error; }
|
|
3859
|
+
const records = [];
|
|
3860
|
+
for (const name of names) {
|
|
3861
|
+
if (name === ".upgrade.lock") continue;
|
|
3862
|
+
const journalPath = path.join(migrationsRoot, name, "transaction.json");
|
|
3863
|
+
try {
|
|
3864
|
+
const stats = await lstat(journalPath);
|
|
3865
|
+
if (!stats.isFile() || stats.isSymbolicLink()) continue;
|
|
3866
|
+
const journal = JSON.parse(await readFile(journalPath, "utf8"));
|
|
3867
|
+
if (journal.state !== "committed" || !journal.currentStateWitness) continue;
|
|
3868
|
+
await validateRecoveryJournal(root, journal, journalPath);
|
|
3869
|
+
records.push({ journal, journalPath, witness: validateCurrentStateWitness(journal), matches: await journalMatchesCurrentState(root, journal) });
|
|
3870
|
+
} catch (error) {
|
|
3871
|
+
if (error?.code !== "ENOENT") throw error;
|
|
3872
|
+
}
|
|
3873
|
+
}
|
|
3874
|
+
const superseded = effectiveCurrentStateSupersededDigests(records);
|
|
3875
|
+
for (const record of records) {
|
|
3876
|
+
if (record.matches || !record.witness.sourceConservation || superseded.has(record.witness.currentStateDigest)) continue;
|
|
3877
|
+
const { mismatches, illegalNonCloseout } = await classifyCurrentStateRebindMismatches(root, record.journal);
|
|
3878
|
+
if (illegalNonCloseout.length > 0) throw cause;
|
|
3879
|
+
const managedCore = mismatches.filter((mismatch) => installedFileContract(mismatch.path)?.strategy === "managed-core");
|
|
3880
|
+
if (managedCore.length > 0) throw cause;
|
|
3881
|
+
}
|
|
3882
|
+
}
|
|
3883
|
+
|
|
3884
|
+
async function classifyCurrentStateRebindMismatches(projectRoot, journal) {
|
|
3885
|
+
const mismatches = await currentStateMismatches(projectRoot, journal);
|
|
3886
|
+
const illegalNonCloseout = [];
|
|
3887
|
+
for (const mismatch of mismatches) {
|
|
3888
|
+
if (isCloseoutFinalizeTarget(mismatch.path)) continue;
|
|
3889
|
+
if (mismatch.kind === "source-conservation"
|
|
3890
|
+
&& sourceConservationEntryMayRetireAsUnreachableRootSource(mismatch.sourceConservationEntry)) continue;
|
|
3891
|
+
if (await mismatchMatchesCurrentInstalledSource(projectRoot, mismatch)) continue;
|
|
3892
|
+
illegalNonCloseout.push(mismatch);
|
|
3893
|
+
}
|
|
3894
|
+
return { mismatches, illegalNonCloseout };
|
|
3895
|
+
}
|
|
3896
|
+
|
|
3897
|
+
async function mismatchMatchesCurrentInstalledSource(projectRoot, mismatch) {
|
|
3898
|
+
const contract = installedFileContract(mismatch.path);
|
|
3899
|
+
if (!contract || contract.strategy === "managed-core") return false;
|
|
3900
|
+
const current = await readOptionalBuffer(path.join(projectRoot, mismatch.path));
|
|
3901
|
+
const source = await readOptionalBuffer(path.join(packageRoot, contract.sourceRel));
|
|
3902
|
+
return Boolean(current && source && current.length === source.length && sha256(current) === sha256(source));
|
|
3903
|
+
}
|
|
3904
|
+
|
|
3905
|
+
async function findRestoredCurrentStateDigests(root, outputs, archiveMigrations = [], replacement = {}) {
|
|
3786
3906
|
const migrationsRoot = path.join(root, "dev", "governance_migrations");
|
|
3787
3907
|
let names;
|
|
3788
3908
|
try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") return []; throw error; }
|
|
@@ -3797,8 +3917,12 @@ async function findRestoredCurrentStateDigests(root, outputs, archiveMigrations
|
|
|
3797
3917
|
const journal = JSON.parse(await readFile(journalPath, "utf8"));
|
|
3798
3918
|
if (journal.state !== "committed" || !journal.currentStateWitness) continue;
|
|
3799
3919
|
await validateRecoveryJournal(root, journal, journalPath);
|
|
3800
|
-
|
|
3801
|
-
|
|
3920
|
+
const priorWitness = validateCurrentStateWitness(journal);
|
|
3921
|
+
const sourceConservationRebind = sourceConservationEntriesRebindPrior(priorWitness, replacement.sourceConservation, archiveMigrations);
|
|
3922
|
+
if ((await journalMatchesCurrentState(root, journal) && (!priorWitness.sourceConservation || sourceConservationRebind))
|
|
3923
|
+
|| await journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations, replacement.sourceConservation)
|
|
3924
|
+
|| sourceConservationRebind) {
|
|
3925
|
+
if (!canSupersedeCurrentStateWitness(replacement, priorWitness)) continue;
|
|
3802
3926
|
restored.push(journal.currentStateWitness.currentStateDigest);
|
|
3803
3927
|
}
|
|
3804
3928
|
} catch (error) {
|
|
@@ -3808,8 +3932,103 @@ async function findRestoredCurrentStateDigests(root, outputs, archiveMigrations
|
|
|
3808
3932
|
return [...new Set(restored)].sort((left, right) => left.localeCompare(right));
|
|
3809
3933
|
}
|
|
3810
3934
|
|
|
3811
|
-
|
|
3935
|
+
function currentStateWitnessCapability(value = {}) {
|
|
3936
|
+
return {
|
|
3937
|
+
sourceConservation: Boolean(value.sourceConservation),
|
|
3938
|
+
archiveMigrations: Array.isArray(value.archiveMigrations) && value.archiveMigrations.length > 0
|
|
3939
|
+
};
|
|
3940
|
+
}
|
|
3941
|
+
|
|
3942
|
+
function canSupersedeCurrentStateWitness(replacement, priorWitness) {
|
|
3943
|
+
const replacementCapability = currentStateWitnessCapability(replacement);
|
|
3944
|
+
if (priorWitness.sourceConservation && !replacementCapability.sourceConservation) return false;
|
|
3945
|
+
if (Array.isArray(priorWitness.archiveMigrations) && priorWitness.archiveMigrations.length > 0
|
|
3946
|
+
&& !replacementCapability.archiveMigrations
|
|
3947
|
+
&& !archiveMigrationHistoryIsRebound(priorWitness, replacement.sourceConservation)) {
|
|
3948
|
+
return false;
|
|
3949
|
+
}
|
|
3950
|
+
return true;
|
|
3951
|
+
}
|
|
3952
|
+
|
|
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
|
|
3961
|
+
&& entry.priorityRelation === "outside-known-kit-reachability"
|
|
3962
|
+
&& entry.effectDecision === "outside-known-kit-reachability");
|
|
3963
|
+
}
|
|
3964
|
+
|
|
3965
|
+
function sourceConservationEntryAcceptedMatches(entry, accepted) {
|
|
3966
|
+
return Boolean(accepted
|
|
3967
|
+
&& accepted.sha256 === entry.accepted?.sha256
|
|
3968
|
+
&& accepted.bytes === entry.accepted?.bytes);
|
|
3969
|
+
}
|
|
3970
|
+
|
|
3971
|
+
function sourceConservationEntryHasAcceptedCoverage(entry) {
|
|
3972
|
+
return Boolean(entry
|
|
3973
|
+
&& entry.accepted
|
|
3974
|
+
&& typeof entry.accepted.sha256 === "string"
|
|
3975
|
+
&& Number.isInteger(entry.accepted.bytes));
|
|
3976
|
+
}
|
|
3977
|
+
|
|
3978
|
+
function sourceConservationEntriesRebindPrior(priorWitness, replacementSourceConservation, archiveMigrations = []) {
|
|
3979
|
+
if (!priorWitness.sourceConservation) return true;
|
|
3980
|
+
if (!replacementSourceConservation) return false;
|
|
3981
|
+
const replacementByPath = new Map(replacementSourceConservation.entries.map((entry) => [entry.sourcePath, entry]));
|
|
3982
|
+
const archiveRebindings = new Map();
|
|
3983
|
+
for (const migration of [...(priorWitness.archiveMigrations ?? []), ...archiveMigrations]) {
|
|
3984
|
+
for (const file of migration.snapshot.files ?? []) {
|
|
3985
|
+
archiveRebindings.set(`${migration.originalRel}/${file.path}`, `${migration.canonicalRel}/${file.path}`);
|
|
3986
|
+
}
|
|
3987
|
+
}
|
|
3988
|
+
return priorWitness.sourceConservation.entries.every((entry) => {
|
|
3989
|
+
if (sourceConservationEntryMayRetireAsUnreachableRootSource(entry)) return true;
|
|
3990
|
+
const replacement = replacementByPath.get(entry.sourcePath);
|
|
3991
|
+
if (sourceConservationEntryHasAcceptedCoverage(replacement)) return true;
|
|
3992
|
+
const reboundPath = archiveRebindings.get(entry.sourcePath);
|
|
3993
|
+
const rebound = reboundPath ? replacementByPath.get(reboundPath) : null;
|
|
3994
|
+
return sourceConservationEntryAcceptedMatches(entry, rebound?.accepted);
|
|
3995
|
+
});
|
|
3996
|
+
}
|
|
3997
|
+
|
|
3998
|
+
function sourceConservationRebindsPrior(priorWitness, replacementSourceConservation) {
|
|
3999
|
+
if (!replacementSourceConservation) return false;
|
|
4000
|
+
const replacementByPath = new Map(replacementSourceConservation.entries.map((entry) => [entry.sourcePath, entry]));
|
|
4001
|
+
const coversTransactionEntries = priorWitness.entries.every((entry) => {
|
|
4002
|
+
const replacement = replacementByPath.get(entry.targetRel);
|
|
4003
|
+
return replacement
|
|
4004
|
+
&& replacement.accepted
|
|
4005
|
+
&& typeof replacement.accepted.sha256 === "string"
|
|
4006
|
+
&& Number.isInteger(replacement.accepted.bytes);
|
|
4007
|
+
});
|
|
4008
|
+
if (!coversTransactionEntries) return false;
|
|
4009
|
+
return sourceConservationEntriesRebindPrior(priorWitness, replacementSourceConservation);
|
|
4010
|
+
}
|
|
4011
|
+
|
|
4012
|
+
function archiveMigrationHistoryIsRebound(priorWitness, replacementSourceConservation) {
|
|
4013
|
+
if (!replacementSourceConservation || !Array.isArray(priorWitness.archiveMigrations) || priorWitness.archiveMigrations.length === 0) return false;
|
|
4014
|
+
const replacementByPath = new Map(replacementSourceConservation.entries.map((entry) => [entry.sourcePath, entry]));
|
|
4015
|
+
for (const migration of priorWitness.archiveMigrations) {
|
|
4016
|
+
for (const file of migration.snapshot.files ?? []) {
|
|
4017
|
+
const conserved = replacementByPath.get(`${migration.canonicalRel}/${file.path}`);
|
|
4018
|
+
if (!conserved
|
|
4019
|
+
|| !conserved.accepted
|
|
4020
|
+
|| conserved.accepted.sha256 !== file.sha256
|
|
4021
|
+
|| conserved.accepted.bytes !== file.bytes) {
|
|
4022
|
+
return false;
|
|
4023
|
+
}
|
|
4024
|
+
}
|
|
4025
|
+
}
|
|
4026
|
+
return sourceConservationEntriesRebindPrior(priorWitness, replacementSourceConservation);
|
|
4027
|
+
}
|
|
4028
|
+
|
|
4029
|
+
async function journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations = [], replacementSourceConservation = null) {
|
|
3812
4030
|
const witness = validateCurrentStateWitness(journal);
|
|
4031
|
+
const replacementByPath = new Map((replacementSourceConservation?.entries ?? []).map((entry) => [entry.sourcePath, entry]));
|
|
3813
4032
|
const archiveRebindings = new Map();
|
|
3814
4033
|
for (const migration of archiveMigrations) {
|
|
3815
4034
|
for (const file of migration.snapshot.files) {
|
|
@@ -3836,11 +4055,17 @@ async function journalIsRestoredByOutputs(root, journal, outputWitnesses, archiv
|
|
|
3836
4055
|
if (replacement.sha256 !== entry.accepted.sha256 || replacement.bytes !== entry.accepted.bytes) return false;
|
|
3837
4056
|
continue;
|
|
3838
4057
|
}
|
|
4058
|
+
const sourceReplacement = replacementByPath.get(entry.sourcePath);
|
|
4059
|
+
if (sourceReplacement) {
|
|
4060
|
+
if (!sourceConservationEntryHasAcceptedCoverage(sourceReplacement)) return false;
|
|
4061
|
+
continue;
|
|
4062
|
+
}
|
|
3839
4063
|
const archiveRebinding = archiveRebindings.get(entry.sourcePath);
|
|
3840
4064
|
if (archiveRebinding) {
|
|
3841
4065
|
if (archiveRebinding.sha256 !== entry.accepted.sha256 || archiveRebinding.bytes !== entry.accepted.bytes) return false;
|
|
3842
4066
|
continue;
|
|
3843
4067
|
}
|
|
4068
|
+
if (!sourceConservationEntryMayRetireAsUnreachableRootSource(entry)) return false;
|
|
3844
4069
|
const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
|
|
3845
4070
|
if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) return false;
|
|
3846
4071
|
}
|
|
@@ -3919,23 +4144,123 @@ async function findCloseoutFinalizeBase(root) {
|
|
|
3919
4144
|
if (error?.code !== "ENOENT") throw error;
|
|
3920
4145
|
}
|
|
3921
4146
|
}
|
|
3922
|
-
const
|
|
3923
|
-
const illegal = [];
|
|
4147
|
+
const records = [];
|
|
3924
4148
|
for (const item of inspected) {
|
|
3925
|
-
|
|
4149
|
+
const witness = validateCurrentStateWitness(item.journal);
|
|
3926
4150
|
const mismatches = await currentStateMismatches(root, item.journal);
|
|
3927
|
-
|
|
3928
|
-
|
|
3929
|
-
|
|
4151
|
+
const closeoutOnly = mismatches.every((mismatch) => isCloseoutFinalizeTarget(mismatch.path));
|
|
4152
|
+
records.push({
|
|
4153
|
+
...item,
|
|
4154
|
+
witness,
|
|
4155
|
+
mismatches,
|
|
4156
|
+
closeoutOnly,
|
|
4157
|
+
isSuperseded: superseded.has(witness.currentStateDigest),
|
|
4158
|
+
additionalSupersedes: []
|
|
4159
|
+
});
|
|
3930
4160
|
}
|
|
4161
|
+
const current = records.filter((item) => !item.isSuperseded);
|
|
4162
|
+
const illegal = current.filter((item) => item.mismatches.length > 0 && !item.closeoutOnly);
|
|
3931
4163
|
if (illegal.length > 0) return illegal.sort((left, right) => right.mismatches.length - left.mismatches.length)[0];
|
|
3932
|
-
|
|
3933
|
-
|
|
3934
|
-
|
|
3935
|
-
|
|
4164
|
+
|
|
4165
|
+
const staleStrong = current.filter((item) => item.mismatches.length > 0 && item.closeoutOnly && item.witness.sourceConservation);
|
|
4166
|
+
const unsupportedStale = current.filter((item) => item.mismatches.length > 0 && item.closeoutOnly && !item.witness.sourceConservation);
|
|
4167
|
+
if (staleStrong.length > 0 && unsupportedStale.length > 0) {
|
|
4168
|
+
const digests = [...staleStrong, ...unsupportedStale].map(({ witness }) => witness.currentStateDigest).join(", ");
|
|
4169
|
+
throw new Error(`multiple closeout-finalize stale witness authorities exist: ${digests}`);
|
|
4170
|
+
}
|
|
4171
|
+
if (staleStrong.length > 1) {
|
|
4172
|
+
const digests = staleStrong.map(({ witness }) => witness.currentStateDigest).join(", ");
|
|
3936
4173
|
throw new Error(`multiple closeout-finalize candidate witnesses are stale: ${digests}`);
|
|
3937
4174
|
}
|
|
3938
|
-
|
|
4175
|
+
if (staleStrong.length === 1) {
|
|
4176
|
+
return withAdditionalCloseoutSupersedes(staleStrong[0], current);
|
|
4177
|
+
}
|
|
4178
|
+
|
|
4179
|
+
if (unsupportedStale.length > 0) {
|
|
4180
|
+
if (unsupportedStale.length > 1) {
|
|
4181
|
+
const digests = unsupportedStale.map(({ witness }) => witness.currentStateDigest).join(", ");
|
|
4182
|
+
throw new Error(`multiple closeout-finalize unsupported stale witnesses exist: ${digests}`);
|
|
4183
|
+
}
|
|
4184
|
+
const bridged = closeoutFinalizeBridgeCandidates(records, unsupportedStale);
|
|
4185
|
+
if (bridged.length === 1) return withAdditionalCloseoutSupersedes(bridged[0], current);
|
|
4186
|
+
if (bridged.length > 1) {
|
|
4187
|
+
const digests = bridged.map(({ witness }) => witness.currentStateDigest).join(", ");
|
|
4188
|
+
throw new Error(`multiple closeout-finalize source-conservation bridge witnesses are stale: ${digests}`);
|
|
4189
|
+
}
|
|
4190
|
+
const digests = unsupportedStale.map(({ witness }) => witness.currentStateDigest).join(", ");
|
|
4191
|
+
throw new Error(`post-upgrade current-state witness is stale but lacks source-conservation evidence for closeout finalize: ${digests}`);
|
|
4192
|
+
}
|
|
4193
|
+
|
|
4194
|
+
const matching = current.filter((item) => item.mismatches.length === 0);
|
|
4195
|
+
if (matching.length > 1) {
|
|
4196
|
+
const digests = matching.map(({ witness }) => witness.currentStateDigest).join(", ");
|
|
4197
|
+
throw new Error(`multiple committed journals match the current filesystem state; finalize-closeout refuses ambiguous current-state authority: ${digests}`);
|
|
4198
|
+
}
|
|
4199
|
+
return matching[0] ?? null;
|
|
4200
|
+
}
|
|
4201
|
+
|
|
4202
|
+
function closeoutFinalizeBridgeCandidates(records, unsupportedStale) {
|
|
4203
|
+
const byDigest = new Map(records.map((item) => [item.witness.currentStateDigest, item]));
|
|
4204
|
+
const candidates = new Map();
|
|
4205
|
+
for (const unsupported of unsupportedStale) {
|
|
4206
|
+
const traced = traceCloseoutFinalizeBridge(unsupported, byDigest);
|
|
4207
|
+
for (const candidate of traced) {
|
|
4208
|
+
const existing = candidates.get(candidate.strong.witness.currentStateDigest) ?? { ...candidate.strong, additionalSupersedes: [] };
|
|
4209
|
+
existing.additionalSupersedes.push(...candidate.weakChain);
|
|
4210
|
+
candidates.set(candidate.strong.witness.currentStateDigest, existing);
|
|
4211
|
+
}
|
|
4212
|
+
}
|
|
4213
|
+
return [...candidates.values()];
|
|
4214
|
+
}
|
|
4215
|
+
|
|
4216
|
+
function traceCloseoutFinalizeBridge(start, byDigest) {
|
|
4217
|
+
const candidates = new Map();
|
|
4218
|
+
const visit = (record, weakChain, pathStack) => {
|
|
4219
|
+
const digest = record.witness.currentStateDigest;
|
|
4220
|
+
if (pathStack.includes(digest)) {
|
|
4221
|
+
throw new Error(`cycle in closeout-finalize supersession chain: ${[...pathStack, digest].join(", ")}`);
|
|
4222
|
+
}
|
|
4223
|
+
if (record.mismatches.length > 0 && !record.closeoutOnly) {
|
|
4224
|
+
throw new Error(`non-closeout drift in closeout-finalize supersession chain: ${record.mismatches.map((item) => item.path).join(", ")}`);
|
|
4225
|
+
}
|
|
4226
|
+
if (record.witness.sourceConservation) {
|
|
4227
|
+
if (record.mismatches.length === 0) {
|
|
4228
|
+
throw new Error(`closeout-finalize source-conservation bridge is not stale: ${digest}`);
|
|
4229
|
+
}
|
|
4230
|
+
candidates.set(digest, { strong: record, weakChain });
|
|
4231
|
+
return;
|
|
4232
|
+
}
|
|
4233
|
+
const supersedes = record.witness.transaction.supersedesCurrentStateDigests ?? [];
|
|
4234
|
+
if (supersedes.length === 0) {
|
|
4235
|
+
throw new Error(`post-upgrade current-state witness is stale but has no source-conservation bridge: ${digest}`);
|
|
4236
|
+
}
|
|
4237
|
+
if (supersedes.length > 1) {
|
|
4238
|
+
throw new Error(`branching closeout-finalize supersession chain: ${digest} -> ${supersedes.join(", ")}`);
|
|
4239
|
+
}
|
|
4240
|
+
for (const supersededDigest of supersedes) {
|
|
4241
|
+
const next = byDigest.get(supersededDigest);
|
|
4242
|
+
if (!next) {
|
|
4243
|
+
throw new Error(`missing closeout-finalize supersession link: ${digest} -> ${supersededDigest}`);
|
|
4244
|
+
}
|
|
4245
|
+
visit(next, [...weakChain, digest], [...pathStack, digest]);
|
|
4246
|
+
}
|
|
4247
|
+
};
|
|
4248
|
+
visit(start, [], []);
|
|
4249
|
+
return [...candidates.values()];
|
|
4250
|
+
}
|
|
4251
|
+
|
|
4252
|
+
function withAdditionalCloseoutSupersedes(base, current) {
|
|
4253
|
+
const additional = current
|
|
4254
|
+
.filter((item) => item.witness.currentStateDigest !== base.witness.currentStateDigest)
|
|
4255
|
+
.filter((item) => !item.witness.sourceConservation)
|
|
4256
|
+
.filter((item) => item.mismatches.length === 0 || item.closeoutOnly)
|
|
4257
|
+
.map((item) => item.witness.currentStateDigest);
|
|
4258
|
+
return {
|
|
4259
|
+
...base,
|
|
4260
|
+
additionalSupersedes: [...new Set([...(base.additionalSupersedes ?? []), ...additional])]
|
|
4261
|
+
.filter((digest) => digest !== base.witness.currentStateDigest)
|
|
4262
|
+
.sort((left, right) => left.localeCompare(right))
|
|
4263
|
+
};
|
|
3939
4264
|
}
|
|
3940
4265
|
|
|
3941
4266
|
async function currentStateMismatches(root, journal) {
|
|
@@ -3948,14 +4273,14 @@ async function currentStateMismatches(root, journal) {
|
|
|
3948
4273
|
for (const entry of witness.sourceConservation?.entries ?? []) {
|
|
3949
4274
|
const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
|
|
3950
4275
|
if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) {
|
|
3951
|
-
mismatches.set(entry.sourcePath, { path: entry.sourcePath, kind: "source-conservation" });
|
|
4276
|
+
mismatches.set(entry.sourcePath, { path: entry.sourcePath, kind: "source-conservation", sourceConservationEntry: entry });
|
|
3952
4277
|
}
|
|
3953
4278
|
}
|
|
3954
4279
|
if (witness.sourceConservation) {
|
|
3955
4280
|
const conserved = new Set(witness.sourceConservation.entries.map((entry) => entry.sourcePath));
|
|
3956
4281
|
const currentFrozen = await freezeGate5Set({ root });
|
|
3957
4282
|
assertGate5FrozenSet(currentFrozen);
|
|
3958
|
-
for (const item of currentFrozen
|
|
4283
|
+
for (const item of gate5SourceConservationItems(currentFrozen)) {
|
|
3959
4284
|
if (conserved.has(item.sourcePath) || isFinalizeJournalState(item.sourcePath)) continue;
|
|
3960
4285
|
mismatches.set(item.sourcePath, { path: item.sourcePath, kind: "new-source" });
|
|
3961
4286
|
}
|
|
@@ -3965,6 +4290,10 @@ async function currentStateMismatches(root, journal) {
|
|
|
3965
4290
|
|
|
3966
4291
|
async function writeCloseoutFinalizeJournal(root, version, prior) {
|
|
3967
4292
|
const oldWitness = validateCurrentStateWitness(prior.journal);
|
|
4293
|
+
const supersedesCurrentStateDigests = [...new Set([
|
|
4294
|
+
oldWitness.currentStateDigest,
|
|
4295
|
+
...(prior.additionalSupersedes ?? [])
|
|
4296
|
+
])].sort((left, right) => left.localeCompare(right));
|
|
3968
4297
|
const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}`;
|
|
3969
4298
|
const migrationsRoot = path.join(root, "dev", "governance_migrations");
|
|
3970
4299
|
const migrationDir = path.join(migrationsRoot, id);
|
|
@@ -4011,7 +4340,7 @@ async function writeCloseoutFinalizeJournal(root, version, prior) {
|
|
|
4011
4340
|
? {
|
|
4012
4341
|
schemaVersion: oldWitness.sourceConservation.schemaVersion,
|
|
4013
4342
|
frozenSetSha256: currentFrozen.frozenSetSha256,
|
|
4014
|
-
entries: await Promise.all(currentFrozen
|
|
4343
|
+
entries: await Promise.all(gate5SourceConservationItems(currentFrozen)
|
|
4015
4344
|
.filter((item) => !isFinalizeJournalState(item.sourcePath))
|
|
4016
4345
|
.map(async (item) => {
|
|
4017
4346
|
const entry = oldSourceByPath.get(item.sourcePath) ?? null;
|
|
@@ -4059,7 +4388,7 @@ async function writeCloseoutFinalizeJournal(root, version, prior) {
|
|
|
4059
4388
|
runtimeAcceptanceReadback: null,
|
|
4060
4389
|
sourceConservation,
|
|
4061
4390
|
archiveMigrations: oldWitness.archiveMigrations ?? [],
|
|
4062
|
-
supersedesCurrentStateDigests
|
|
4391
|
+
supersedesCurrentStateDigests,
|
|
4063
4392
|
currentStateWitness: null,
|
|
4064
4393
|
currentStateReadback: null
|
|
4065
4394
|
};
|
|
@@ -4071,7 +4400,7 @@ async function writeCloseoutFinalizeJournal(root, version, prior) {
|
|
|
4071
4400
|
"",
|
|
4072
4401
|
`- Command: finalize-closeout`,
|
|
4073
4402
|
`- Attempted version: ${version}`,
|
|
4074
|
-
`- Supersedes current-state digest: ${
|
|
4403
|
+
`- Supersedes current-state digest: ${supersedesCurrentStateDigests.join(", ")}`,
|
|
4075
4404
|
`- Current-state digest: ${journal.currentStateWitness.currentStateDigest}`,
|
|
4076
4405
|
`- Finalized paths: ${prior.mismatches.map((item) => item.path).join(", ") || "none"}`,
|
|
4077
4406
|
""
|