@adamchanadam/agent-handoff-kit 0.3.48 → 0.3.50
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 +353 -66
- package/bin/migration-baselines/official-origin-catalog.json +361 -1
- package/bin/official-origin-catalog.mjs +16 -16
- package/bin/upgrade-inventory.mjs +33 -33
- 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/runtime-core/PROJECT_INDEX.md +1 -1
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.50`. 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.50`。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">
|
|
@@ -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);
|
|
@@ -873,13 +882,14 @@ async function runInstall(command, root, options, version) {
|
|
|
873
882
|
return;
|
|
874
883
|
}
|
|
875
884
|
|
|
876
|
-
if (plan.some((item) => item.action === "conflict")) {
|
|
877
|
-
console.log("");
|
|
878
|
-
console.log("⛔ 升級預檢發現 conflict;治理目標檔、版本與 migration artifact 均沒有寫入。");
|
|
879
|
-
console.log("
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
885
|
+
if (plan.some((item) => item.action === "conflict")) {
|
|
886
|
+
console.log("");
|
|
887
|
+
console.log("⛔ 升級預檢發現 conflict;治理目標檔、版本與 migration artifact 均沒有寫入。");
|
|
888
|
+
console.log("📌 舊 migration stage、已回滾報告或版本列只屬證據,不代表目前交易。");
|
|
889
|
+
console.log(conflictRepairNextStepLine());
|
|
890
|
+
process.exitCode = 1;
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
883
893
|
|
|
884
894
|
if (!options.yes) {
|
|
885
895
|
const ok = await confirmWrite();
|
|
@@ -889,8 +899,8 @@ async function runInstall(command, root, options, version) {
|
|
|
889
899
|
}
|
|
890
900
|
}
|
|
891
901
|
|
|
892
|
-
await executeInstallTransaction(command, root, mode, plan, version, candidateOutputs);
|
|
893
|
-
}
|
|
902
|
+
await executeInstallTransaction(command, root, mode, plan, version, candidateOutputs, { sourceConservationRebind });
|
|
903
|
+
}
|
|
894
904
|
|
|
895
905
|
async function readInstalledTemplateVersion(root) {
|
|
896
906
|
try {
|
|
@@ -902,7 +912,7 @@ async function readInstalledTemplateVersion(root) {
|
|
|
902
912
|
}
|
|
903
913
|
}
|
|
904
914
|
|
|
905
|
-
async function executeInstallTransaction(command, root, mode, plan, version, candidateOutputs = null) {
|
|
915
|
+
async function executeInstallTransaction(command, root, mode, plan, version, candidateOutputs = null, options = {}) {
|
|
906
916
|
const outputs = candidateOutputs ?? await buildTransactionOutputs(command, root, plan, version);
|
|
907
917
|
if (outputs.length === 0) {
|
|
908
918
|
const health = await assessUpgradeNoopHealth(root, version);
|
|
@@ -933,7 +943,16 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
|
|
|
933
943
|
const archiveMigrations = command === "upgrade"
|
|
934
944
|
? await prepareArchiveCasingMigrations(root)
|
|
935
945
|
: [];
|
|
936
|
-
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
|
+
)
|
|
937
956
|
? await createSourceConservation(root, outputs, archiveMigrations)
|
|
938
957
|
: null;
|
|
939
958
|
// A repair may restore the exact bytes of a prior committed state. Keep the
|
|
@@ -941,7 +960,7 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
|
|
|
941
960
|
// doctor can select the freshly read-back transaction without falling back
|
|
942
961
|
// to mtime or a separate current-state registry.
|
|
943
962
|
const supersedesCurrentStateDigests = command === "upgrade"
|
|
944
|
-
? await findRestoredCurrentStateDigests(root, outputs, archiveMigrations)
|
|
963
|
+
? await findRestoredCurrentStateDigests(root, outputs, archiveMigrations, { sourceConservation, archiveMigrations })
|
|
945
964
|
: [];
|
|
946
965
|
const transaction = await prepareTransaction(root, command, version, outputs, mode, plan, sourceConservation, supersedesCurrentStateDigests, archiveMigrations);
|
|
947
966
|
try {
|
|
@@ -994,6 +1013,7 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
|
|
|
994
1013
|
const doctorStatus = await runDoctor(root, version, {
|
|
995
1014
|
silentCard: true,
|
|
996
1015
|
context: "post-transaction-project-health",
|
|
1016
|
+
skipVersionRegistryLookup: true,
|
|
997
1017
|
allowActiveTransaction: true,
|
|
998
1018
|
expectedCurrentStateWitness: transaction.journal.currentStateWitness,
|
|
999
1019
|
captureFormalUserRules: (state) => { formalRuntimeState = state; },
|
|
@@ -2185,6 +2205,7 @@ async function recoverInterruptedTransaction(root) {
|
|
|
2185
2205
|
const doctorStatus = await runDoctor(root, journal.committedVersion, {
|
|
2186
2206
|
silentCard: true,
|
|
2187
2207
|
context: "recovered-committed-transaction-health",
|
|
2208
|
+
skipVersionRegistryLookup: true,
|
|
2188
2209
|
allowActiveTransaction: true,
|
|
2189
2210
|
expectedCurrentStateWitness: journal.currentStateWitness,
|
|
2190
2211
|
captureFormalUserRules: (state) => { formalRuntimeState = state; },
|
|
@@ -3747,8 +3768,7 @@ async function loadCommittedCurrentStateWitness(root) {
|
|
|
3747
3768
|
const migrationsRoot = path.join(root, "dev", "governance_migrations");
|
|
3748
3769
|
let names;
|
|
3749
3770
|
try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") return null; throw error; }
|
|
3750
|
-
const
|
|
3751
|
-
const staleSourceConservation = [];
|
|
3771
|
+
const records = [];
|
|
3752
3772
|
for (const name of names) {
|
|
3753
3773
|
if (name === ".upgrade.lock") continue;
|
|
3754
3774
|
const journalPath = path.join(migrationsRoot, name, "transaction.json");
|
|
@@ -3758,30 +3778,129 @@ async function loadCommittedCurrentStateWitness(root) {
|
|
|
3758
3778
|
const journal = JSON.parse(await readFile(journalPath, "utf8"));
|
|
3759
3779
|
if (journal.state !== "committed" || !journal.currentStateWitness) continue;
|
|
3760
3780
|
await validateRecoveryJournal(root, journal, journalPath);
|
|
3761
|
-
|
|
3762
|
-
|
|
3781
|
+
const witness = validateCurrentStateWitness(journal);
|
|
3782
|
+
records.push({ journal, journalPath, witness, matches: await journalMatchesCurrentState(root, journal) });
|
|
3763
3783
|
} catch (error) {
|
|
3764
3784
|
if (error?.code !== "ENOENT") throw error;
|
|
3765
3785
|
}
|
|
3766
3786
|
}
|
|
3767
|
-
|
|
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) {
|
|
3768
3794
|
throw new Error("committed Gate 5 current-state source witness no longer matches project bytes; doctor refuses an unbound success state");
|
|
3769
3795
|
}
|
|
3796
|
+
const candidates = records.filter((record) => record.matches);
|
|
3770
3797
|
if (candidates.length === 0) return null;
|
|
3771
3798
|
// A later repair can deliberately restore the exact bytes of an earlier
|
|
3772
3799
|
// state. Its sealed supersession link is the only permitted tie-breaker:
|
|
3773
3800
|
// filesystem timestamps remain untrusted and an unlinked tie stays fatal.
|
|
3774
|
-
const
|
|
3775
|
-
journal.currentStateWitness.transaction.supersedesCurrentStateDigests ?? []
|
|
3776
|
-
)));
|
|
3777
|
-
const currentCandidates = candidates.filter(({ journal }) => !superseded.has(journal.currentStateWitness.currentStateDigest));
|
|
3801
|
+
const currentCandidates = candidates.filter(({ witness }) => !superseded.has(witness.currentStateDigest));
|
|
3778
3802
|
if (currentCandidates.length !== 1) {
|
|
3779
3803
|
throw new Error("multiple committed journals match the current filesystem state; doctor refuses ambiguous current-state authority");
|
|
3780
3804
|
}
|
|
3781
3805
|
return validateCurrentStateWitness(currentCandidates[0].journal);
|
|
3782
3806
|
}
|
|
3783
3807
|
|
|
3784
|
-
|
|
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 (await mismatchMatchesCurrentInstalledSource(projectRoot, mismatch)) continue;
|
|
3890
|
+
illegalNonCloseout.push(mismatch);
|
|
3891
|
+
}
|
|
3892
|
+
return { mismatches, illegalNonCloseout };
|
|
3893
|
+
}
|
|
3894
|
+
|
|
3895
|
+
async function mismatchMatchesCurrentInstalledSource(projectRoot, mismatch) {
|
|
3896
|
+
const contract = installedFileContract(mismatch.path);
|
|
3897
|
+
if (!contract || contract.strategy === "managed-core") return false;
|
|
3898
|
+
const current = await readOptionalBuffer(path.join(projectRoot, mismatch.path));
|
|
3899
|
+
const source = await readOptionalBuffer(path.join(packageRoot, contract.sourceRel));
|
|
3900
|
+
return Boolean(current && source && current.length === source.length && sha256(current) === sha256(source));
|
|
3901
|
+
}
|
|
3902
|
+
|
|
3903
|
+
async function findRestoredCurrentStateDigests(root, outputs, archiveMigrations = [], replacement = {}) {
|
|
3785
3904
|
const migrationsRoot = path.join(root, "dev", "governance_migrations");
|
|
3786
3905
|
let names;
|
|
3787
3906
|
try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") return []; throw error; }
|
|
@@ -3796,8 +3915,11 @@ async function findRestoredCurrentStateDigests(root, outputs, archiveMigrations
|
|
|
3796
3915
|
const journal = JSON.parse(await readFile(journalPath, "utf8"));
|
|
3797
3916
|
if (journal.state !== "committed" || !journal.currentStateWitness) continue;
|
|
3798
3917
|
await validateRecoveryJournal(root, journal, journalPath);
|
|
3918
|
+
const priorWitness = validateCurrentStateWitness(journal);
|
|
3799
3919
|
if (await journalMatchesCurrentState(root, journal)
|
|
3800
|
-
|| await journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations)
|
|
3920
|
+
|| await journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations)
|
|
3921
|
+
|| sourceConservationRebindsPrior(priorWitness, replacement.sourceConservation)) {
|
|
3922
|
+
if (!canSupersedeCurrentStateWitness(replacement, priorWitness)) continue;
|
|
3801
3923
|
restored.push(journal.currentStateWitness.currentStateDigest);
|
|
3802
3924
|
}
|
|
3803
3925
|
} catch (error) {
|
|
@@ -3807,6 +3929,62 @@ async function findRestoredCurrentStateDigests(root, outputs, archiveMigrations
|
|
|
3807
3929
|
return [...new Set(restored)].sort((left, right) => left.localeCompare(right));
|
|
3808
3930
|
}
|
|
3809
3931
|
|
|
3932
|
+
function currentStateWitnessCapability(value = {}) {
|
|
3933
|
+
return {
|
|
3934
|
+
sourceConservation: Boolean(value.sourceConservation),
|
|
3935
|
+
archiveMigrations: Array.isArray(value.archiveMigrations) && value.archiveMigrations.length > 0
|
|
3936
|
+
};
|
|
3937
|
+
}
|
|
3938
|
+
|
|
3939
|
+
function canSupersedeCurrentStateWitness(replacement, priorWitness) {
|
|
3940
|
+
const replacementCapability = currentStateWitnessCapability(replacement);
|
|
3941
|
+
if (priorWitness.sourceConservation && !replacementCapability.sourceConservation) return false;
|
|
3942
|
+
if (Array.isArray(priorWitness.archiveMigrations) && priorWitness.archiveMigrations.length > 0
|
|
3943
|
+
&& !replacementCapability.archiveMigrations
|
|
3944
|
+
&& !archiveMigrationHistoryIsRebound(priorWitness, replacement.sourceConservation)) {
|
|
3945
|
+
return false;
|
|
3946
|
+
}
|
|
3947
|
+
return true;
|
|
3948
|
+
}
|
|
3949
|
+
|
|
3950
|
+
function sourceConservationRebindsPrior(priorWitness, replacementSourceConservation) {
|
|
3951
|
+
if (!replacementSourceConservation) return false;
|
|
3952
|
+
const replacementByPath = new Map(replacementSourceConservation.entries.map((entry) => [entry.sourcePath, entry]));
|
|
3953
|
+
const coversTransactionEntries = priorWitness.entries.every((entry) => {
|
|
3954
|
+
const replacement = replacementByPath.get(entry.targetRel);
|
|
3955
|
+
return replacement
|
|
3956
|
+
&& replacement.accepted
|
|
3957
|
+
&& typeof replacement.accepted.sha256 === "string"
|
|
3958
|
+
&& Number.isInteger(replacement.accepted.bytes);
|
|
3959
|
+
});
|
|
3960
|
+
if (!coversTransactionEntries) return false;
|
|
3961
|
+
if (!priorWitness.sourceConservation) return true;
|
|
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
|
+
});
|
|
3969
|
+
}
|
|
3970
|
+
|
|
3971
|
+
function archiveMigrationHistoryIsRebound(priorWitness, replacementSourceConservation) {
|
|
3972
|
+
if (!replacementSourceConservation || !Array.isArray(priorWitness.archiveMigrations) || priorWitness.archiveMigrations.length === 0) return false;
|
|
3973
|
+
const replacementByPath = new Map(replacementSourceConservation.entries.map((entry) => [entry.sourcePath, entry]));
|
|
3974
|
+
for (const migration of priorWitness.archiveMigrations) {
|
|
3975
|
+
for (const file of migration.snapshot.files ?? []) {
|
|
3976
|
+
const conserved = replacementByPath.get(`${migration.canonicalRel}/${file.path}`);
|
|
3977
|
+
if (!conserved
|
|
3978
|
+
|| !conserved.accepted
|
|
3979
|
+
|| conserved.accepted.sha256 !== file.sha256
|
|
3980
|
+
|| conserved.accepted.bytes !== file.bytes) {
|
|
3981
|
+
return false;
|
|
3982
|
+
}
|
|
3983
|
+
}
|
|
3984
|
+
}
|
|
3985
|
+
return sourceConservationRebindsPrior(priorWitness, replacementSourceConservation);
|
|
3986
|
+
}
|
|
3987
|
+
|
|
3810
3988
|
async function journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations = []) {
|
|
3811
3989
|
const witness = validateCurrentStateWitness(journal);
|
|
3812
3990
|
const archiveRebindings = new Map();
|
|
@@ -3918,23 +4096,123 @@ async function findCloseoutFinalizeBase(root) {
|
|
|
3918
4096
|
if (error?.code !== "ENOENT") throw error;
|
|
3919
4097
|
}
|
|
3920
4098
|
}
|
|
3921
|
-
const
|
|
3922
|
-
const illegal = [];
|
|
4099
|
+
const records = [];
|
|
3923
4100
|
for (const item of inspected) {
|
|
3924
|
-
|
|
4101
|
+
const witness = validateCurrentStateWitness(item.journal);
|
|
3925
4102
|
const mismatches = await currentStateMismatches(root, item.journal);
|
|
3926
|
-
|
|
3927
|
-
|
|
3928
|
-
|
|
4103
|
+
const closeoutOnly = mismatches.every((mismatch) => isCloseoutFinalizeTarget(mismatch.path));
|
|
4104
|
+
records.push({
|
|
4105
|
+
...item,
|
|
4106
|
+
witness,
|
|
4107
|
+
mismatches,
|
|
4108
|
+
closeoutOnly,
|
|
4109
|
+
isSuperseded: superseded.has(witness.currentStateDigest),
|
|
4110
|
+
additionalSupersedes: []
|
|
4111
|
+
});
|
|
3929
4112
|
}
|
|
4113
|
+
const current = records.filter((item) => !item.isSuperseded);
|
|
4114
|
+
const illegal = current.filter((item) => item.mismatches.length > 0 && !item.closeoutOnly);
|
|
3930
4115
|
if (illegal.length > 0) return illegal.sort((left, right) => right.mismatches.length - left.mismatches.length)[0];
|
|
3931
|
-
|
|
3932
|
-
|
|
3933
|
-
|
|
3934
|
-
|
|
4116
|
+
|
|
4117
|
+
const staleStrong = current.filter((item) => item.mismatches.length > 0 && item.closeoutOnly && item.witness.sourceConservation);
|
|
4118
|
+
const unsupportedStale = current.filter((item) => item.mismatches.length > 0 && item.closeoutOnly && !item.witness.sourceConservation);
|
|
4119
|
+
if (staleStrong.length > 0 && unsupportedStale.length > 0) {
|
|
4120
|
+
const digests = [...staleStrong, ...unsupportedStale].map(({ witness }) => witness.currentStateDigest).join(", ");
|
|
4121
|
+
throw new Error(`multiple closeout-finalize stale witness authorities exist: ${digests}`);
|
|
4122
|
+
}
|
|
4123
|
+
if (staleStrong.length > 1) {
|
|
4124
|
+
const digests = staleStrong.map(({ witness }) => witness.currentStateDigest).join(", ");
|
|
3935
4125
|
throw new Error(`multiple closeout-finalize candidate witnesses are stale: ${digests}`);
|
|
3936
4126
|
}
|
|
3937
|
-
|
|
4127
|
+
if (staleStrong.length === 1) {
|
|
4128
|
+
return withAdditionalCloseoutSupersedes(staleStrong[0], current);
|
|
4129
|
+
}
|
|
4130
|
+
|
|
4131
|
+
if (unsupportedStale.length > 0) {
|
|
4132
|
+
if (unsupportedStale.length > 1) {
|
|
4133
|
+
const digests = unsupportedStale.map(({ witness }) => witness.currentStateDigest).join(", ");
|
|
4134
|
+
throw new Error(`multiple closeout-finalize unsupported stale witnesses exist: ${digests}`);
|
|
4135
|
+
}
|
|
4136
|
+
const bridged = closeoutFinalizeBridgeCandidates(records, unsupportedStale);
|
|
4137
|
+
if (bridged.length === 1) return withAdditionalCloseoutSupersedes(bridged[0], current);
|
|
4138
|
+
if (bridged.length > 1) {
|
|
4139
|
+
const digests = bridged.map(({ witness }) => witness.currentStateDigest).join(", ");
|
|
4140
|
+
throw new Error(`multiple closeout-finalize source-conservation bridge witnesses are stale: ${digests}`);
|
|
4141
|
+
}
|
|
4142
|
+
const digests = unsupportedStale.map(({ witness }) => witness.currentStateDigest).join(", ");
|
|
4143
|
+
throw new Error(`post-upgrade current-state witness is stale but lacks source-conservation evidence for closeout finalize: ${digests}`);
|
|
4144
|
+
}
|
|
4145
|
+
|
|
4146
|
+
const matching = current.filter((item) => item.mismatches.length === 0);
|
|
4147
|
+
if (matching.length > 1) {
|
|
4148
|
+
const digests = matching.map(({ witness }) => witness.currentStateDigest).join(", ");
|
|
4149
|
+
throw new Error(`multiple committed journals match the current filesystem state; finalize-closeout refuses ambiguous current-state authority: ${digests}`);
|
|
4150
|
+
}
|
|
4151
|
+
return matching[0] ?? null;
|
|
4152
|
+
}
|
|
4153
|
+
|
|
4154
|
+
function closeoutFinalizeBridgeCandidates(records, unsupportedStale) {
|
|
4155
|
+
const byDigest = new Map(records.map((item) => [item.witness.currentStateDigest, item]));
|
|
4156
|
+
const candidates = new Map();
|
|
4157
|
+
for (const unsupported of unsupportedStale) {
|
|
4158
|
+
const traced = traceCloseoutFinalizeBridge(unsupported, byDigest);
|
|
4159
|
+
for (const candidate of traced) {
|
|
4160
|
+
const existing = candidates.get(candidate.strong.witness.currentStateDigest) ?? { ...candidate.strong, additionalSupersedes: [] };
|
|
4161
|
+
existing.additionalSupersedes.push(...candidate.weakChain);
|
|
4162
|
+
candidates.set(candidate.strong.witness.currentStateDigest, existing);
|
|
4163
|
+
}
|
|
4164
|
+
}
|
|
4165
|
+
return [...candidates.values()];
|
|
4166
|
+
}
|
|
4167
|
+
|
|
4168
|
+
function traceCloseoutFinalizeBridge(start, byDigest) {
|
|
4169
|
+
const candidates = new Map();
|
|
4170
|
+
const visit = (record, weakChain, pathStack) => {
|
|
4171
|
+
const digest = record.witness.currentStateDigest;
|
|
4172
|
+
if (pathStack.includes(digest)) {
|
|
4173
|
+
throw new Error(`cycle in closeout-finalize supersession chain: ${[...pathStack, digest].join(", ")}`);
|
|
4174
|
+
}
|
|
4175
|
+
if (record.mismatches.length > 0 && !record.closeoutOnly) {
|
|
4176
|
+
throw new Error(`non-closeout drift in closeout-finalize supersession chain: ${record.mismatches.map((item) => item.path).join(", ")}`);
|
|
4177
|
+
}
|
|
4178
|
+
if (record.witness.sourceConservation) {
|
|
4179
|
+
if (record.mismatches.length === 0) {
|
|
4180
|
+
throw new Error(`closeout-finalize source-conservation bridge is not stale: ${digest}`);
|
|
4181
|
+
}
|
|
4182
|
+
candidates.set(digest, { strong: record, weakChain });
|
|
4183
|
+
return;
|
|
4184
|
+
}
|
|
4185
|
+
const supersedes = record.witness.transaction.supersedesCurrentStateDigests ?? [];
|
|
4186
|
+
if (supersedes.length === 0) {
|
|
4187
|
+
throw new Error(`post-upgrade current-state witness is stale but has no source-conservation bridge: ${digest}`);
|
|
4188
|
+
}
|
|
4189
|
+
if (supersedes.length > 1) {
|
|
4190
|
+
throw new Error(`branching closeout-finalize supersession chain: ${digest} -> ${supersedes.join(", ")}`);
|
|
4191
|
+
}
|
|
4192
|
+
for (const supersededDigest of supersedes) {
|
|
4193
|
+
const next = byDigest.get(supersededDigest);
|
|
4194
|
+
if (!next) {
|
|
4195
|
+
throw new Error(`missing closeout-finalize supersession link: ${digest} -> ${supersededDigest}`);
|
|
4196
|
+
}
|
|
4197
|
+
visit(next, [...weakChain, digest], [...pathStack, digest]);
|
|
4198
|
+
}
|
|
4199
|
+
};
|
|
4200
|
+
visit(start, [], []);
|
|
4201
|
+
return [...candidates.values()];
|
|
4202
|
+
}
|
|
4203
|
+
|
|
4204
|
+
function withAdditionalCloseoutSupersedes(base, current) {
|
|
4205
|
+
const additional = current
|
|
4206
|
+
.filter((item) => item.witness.currentStateDigest !== base.witness.currentStateDigest)
|
|
4207
|
+
.filter((item) => !item.witness.sourceConservation)
|
|
4208
|
+
.filter((item) => item.mismatches.length === 0 || item.closeoutOnly)
|
|
4209
|
+
.map((item) => item.witness.currentStateDigest);
|
|
4210
|
+
return {
|
|
4211
|
+
...base,
|
|
4212
|
+
additionalSupersedes: [...new Set([...(base.additionalSupersedes ?? []), ...additional])]
|
|
4213
|
+
.filter((digest) => digest !== base.witness.currentStateDigest)
|
|
4214
|
+
.sort((left, right) => left.localeCompare(right))
|
|
4215
|
+
};
|
|
3938
4216
|
}
|
|
3939
4217
|
|
|
3940
4218
|
async function currentStateMismatches(root, journal) {
|
|
@@ -3964,6 +4242,10 @@ async function currentStateMismatches(root, journal) {
|
|
|
3964
4242
|
|
|
3965
4243
|
async function writeCloseoutFinalizeJournal(root, version, prior) {
|
|
3966
4244
|
const oldWitness = validateCurrentStateWitness(prior.journal);
|
|
4245
|
+
const supersedesCurrentStateDigests = [...new Set([
|
|
4246
|
+
oldWitness.currentStateDigest,
|
|
4247
|
+
...(prior.additionalSupersedes ?? [])
|
|
4248
|
+
])].sort((left, right) => left.localeCompare(right));
|
|
3967
4249
|
const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}`;
|
|
3968
4250
|
const migrationsRoot = path.join(root, "dev", "governance_migrations");
|
|
3969
4251
|
const migrationDir = path.join(migrationsRoot, id);
|
|
@@ -4058,7 +4340,7 @@ async function writeCloseoutFinalizeJournal(root, version, prior) {
|
|
|
4058
4340
|
runtimeAcceptanceReadback: null,
|
|
4059
4341
|
sourceConservation,
|
|
4060
4342
|
archiveMigrations: oldWitness.archiveMigrations ?? [],
|
|
4061
|
-
supersedesCurrentStateDigests
|
|
4343
|
+
supersedesCurrentStateDigests,
|
|
4062
4344
|
currentStateWitness: null,
|
|
4063
4345
|
currentStateReadback: null
|
|
4064
4346
|
};
|
|
@@ -4070,7 +4352,7 @@ async function writeCloseoutFinalizeJournal(root, version, prior) {
|
|
|
4070
4352
|
"",
|
|
4071
4353
|
`- Command: finalize-closeout`,
|
|
4072
4354
|
`- Attempted version: ${version}`,
|
|
4073
|
-
`- Supersedes current-state digest: ${
|
|
4355
|
+
`- Supersedes current-state digest: ${supersedesCurrentStateDigests.join(", ")}`,
|
|
4074
4356
|
`- Current-state digest: ${journal.currentStateWitness.currentStateDigest}`,
|
|
4075
4357
|
`- Finalized paths: ${prior.mismatches.map((item) => item.path).join(", ") || "none"}`,
|
|
4076
4358
|
""
|
|
@@ -7346,8 +7628,8 @@ function ensureHandoffCloseoutOutcomeFields(targetText) {
|
|
|
7346
7628
|
return targetText.replace(openingMarker, `${fields}${openingMarker}`);
|
|
7347
7629
|
}
|
|
7348
7630
|
|
|
7349
|
-
function planIntroFor(command, mode, isDryRun) {
|
|
7350
|
-
const prefix = isDryRun ? "📋 預演結果:這次不會寫入檔案。" : "📋 寫入前確認:工具準備這樣處理目前資料夾。";
|
|
7631
|
+
function planIntroFor(command, mode, isDryRun) {
|
|
7632
|
+
const prefix = isDryRun ? "📋 預演結果:這次不會寫入檔案。" : "📋 寫入前確認:工具準備這樣處理目前資料夾。";
|
|
7351
7633
|
if (command === "init" && mode === "first-install") {
|
|
7352
7634
|
return `${prefix} 目前資料夾未見 Kit 檔案;工具會建立交接文件、AI 入口檔與工作規則。沒有既有檔案會被覆寫。`;
|
|
7353
7635
|
}
|
|
@@ -7356,12 +7638,17 @@ function planIntroFor(command, mode, isDryRun) {
|
|
|
7356
7638
|
}
|
|
7357
7639
|
if (command === "upgrade") {
|
|
7358
7640
|
return `${prefix} 工具會檢查既有 Kit 檔案;能安全合併才合併,不能判斷時會停手並列為 conflict。`;
|
|
7359
|
-
}
|
|
7360
|
-
return `${prefix} create 代表建立缺少檔案;merge 代表先備份再合併;skip 代表保留既有檔案;conflict 代表工具零寫入停手並提供技術證據。`;
|
|
7361
|
-
}
|
|
7362
|
-
|
|
7363
|
-
|
|
7364
|
-
|
|
7641
|
+
}
|
|
7642
|
+
return `${prefix} create 代表建立缺少檔案;merge 代表先備份再合併;skip 代表保留既有檔案;conflict 代表工具零寫入停手並提供技術證據。`;
|
|
7643
|
+
}
|
|
7644
|
+
|
|
7645
|
+
function conflictRepairNextStepLine(icon = "📋", suffix = "") {
|
|
7646
|
+
const suffixText = suffix ? ` ${suffix}` : "";
|
|
7647
|
+
return `${icon} 下一步:你不用判斷技術差異,也不要重裝或整檔覆寫。請回到能讀寫這個資料夾的 AI,讓 AI 依這段輸出、本地檔案與正式來源做授權合併;合併後重新執行 upgrade --dry-run,再用 doctor 與 hash 讀回驗收。未知本地 hash 只作內容 witness,不代表 Kit 可以理解或覆寫。只有能證明這是 Kit 誤判未改動的正式舊檔時,才把版本、來源與 hash 證據回報 Kit maintainer。${suffixText}`;
|
|
7648
|
+
}
|
|
7649
|
+
|
|
7650
|
+
// R-026 CLI Output Contract: install/upgrade 完成必含四項(版本/模式/剛完成/下一步)。
|
|
7651
|
+
function printInstallSummary(version, command, mode, root, counts) {
|
|
7365
7652
|
console.log(`\n✅ created: ${counts.created}`);
|
|
7366
7653
|
console.log(`🔀 merged: ${counts.merged}`);
|
|
7367
7654
|
console.log(`⏭️ skipped existing: ${counts.skipped}`);
|
|
@@ -7370,10 +7657,10 @@ function printInstallSummary(version, command, mode, root, counts) {
|
|
|
7370
7657
|
if (counts.reportRel) console.log(`📄 migration report: ${counts.reportRel}`);
|
|
7371
7658
|
console.log("");
|
|
7372
7659
|
console.log(`📦 版本:v${version}`);
|
|
7373
|
-
console.log(`🛠️ 模式:${mode}`);
|
|
7374
|
-
console.log(`🔎 剛完成:${command} 命令;create ${counts.created} / merge ${counts.merged} / skip ${counts.skipped} / conflict ${counts.conflicts}。`);
|
|
7660
|
+
console.log(`🛠️ 模式:${mode}`);
|
|
7661
|
+
console.log(`🔎 剛完成:${command} 命令;create ${counts.created} / merge ${counts.merged} / skip ${counts.skipped} / conflict ${counts.conflicts}。`);
|
|
7375
7662
|
if (counts.conflicts > 0) {
|
|
7376
|
-
console.log("🚀
|
|
7663
|
+
console.log(conflictRepairNextStepLine("🚀", "工具已停手,沒有覆寫 conflict 檔案。"));
|
|
7377
7664
|
} else if (command === "upgrade") {
|
|
7378
7665
|
console.log("🚀 下一步:本次提交已先經同一輪正式 doctor 讀回;請留意下方提交與健康結果。");
|
|
7379
7666
|
} else if (counts.skipped > 0) {
|
|
@@ -7399,11 +7686,11 @@ function printDryRunExplanation(command, mode, plan) {
|
|
|
7399
7686
|
}
|
|
7400
7687
|
console.log("✅ 沒有發現 conflict。請按你剛才預演的命令去掉 --dry-run 後正式執行。");
|
|
7401
7688
|
return;
|
|
7402
|
-
}
|
|
7403
|
-
console.log(`⚠️ 技術核對未完成:有 ${conflicts.length} 個既有檔案,工具目前不能證明可安全合併。`);
|
|
7404
|
-
console.log("⚠️ 這不是檔案壞掉,也沒有覆寫你的檔案。");
|
|
7405
|
-
console.log(
|
|
7406
|
-
}
|
|
7689
|
+
}
|
|
7690
|
+
console.log(`⚠️ 技術核對未完成:有 ${conflicts.length} 個既有檔案,工具目前不能證明可安全合併。`);
|
|
7691
|
+
console.log("⚠️ 這不是檔案壞掉,也沒有覆寫你的檔案。");
|
|
7692
|
+
console.log(conflictRepairNextStepLine());
|
|
7693
|
+
}
|
|
7407
7694
|
|
|
7408
7695
|
async function confirmWrite() {
|
|
7409
7696
|
const rl = createInterface({ input, output });
|
|
@@ -7578,12 +7865,12 @@ function printInstallNextSteps(root, conflictCount, mode = "first-install", skip
|
|
|
7578
7865
|
console.log("✅ 安裝完成:下一步請在 AI 對話中操作");
|
|
7579
7866
|
}
|
|
7580
7867
|
console.log("============================================================");
|
|
7581
|
-
if (conflictCount > 0) {
|
|
7582
|
-
console.log("⚠️ 狀態:有既有檔案未能證明可安全合併。");
|
|
7583
|
-
console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
|
|
7584
|
-
console.log(
|
|
7585
|
-
console.log("");
|
|
7586
|
-
}
|
|
7868
|
+
if (conflictCount > 0) {
|
|
7869
|
+
console.log("⚠️ 狀態:有既有檔案未能證明可安全合併。");
|
|
7870
|
+
console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
|
|
7871
|
+
console.log(conflictRepairNextStepLine());
|
|
7872
|
+
console.log("");
|
|
7873
|
+
}
|
|
7587
7874
|
if (skippedCount > 0) {
|
|
7588
7875
|
console.log("你原本已有部分 AI 記憶檔,工具已保留它們,沒有覆寫。");
|
|
7589
7876
|
console.log("下一步先不要開始新任務;請在終端機執行以下預演,讓工具檢查能否安全補入口連接:");
|
|
@@ -7621,13 +7908,13 @@ function printUpgradeNextSteps(root, conflictCount) {
|
|
|
7621
7908
|
console.log("============================================================");
|
|
7622
7909
|
if (conflictCount > 0) {
|
|
7623
7910
|
console.log("⚠️ 升級未完成:有檔案未能證明可安全合併");
|
|
7624
|
-
console.log("============================================================");
|
|
7625
|
-
console.log("⚠️ 狀態:工具已保守停手,沒有建立目前交易或覆寫檔案。");
|
|
7626
|
-
console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
|
|
7627
|
-
console.log(
|
|
7628
|
-
console.log("============================================================");
|
|
7629
|
-
return;
|
|
7630
|
-
}
|
|
7911
|
+
console.log("============================================================");
|
|
7912
|
+
console.log("⚠️ 狀態:工具已保守停手,沒有建立目前交易或覆寫檔案。");
|
|
7913
|
+
console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
|
|
7914
|
+
console.log(conflictRepairNextStepLine());
|
|
7915
|
+
console.log("============================================================");
|
|
7916
|
+
return;
|
|
7917
|
+
}
|
|
7631
7918
|
console.log("🛠️ Kit migration 已通過離線遷移驗收;已由正式 doctor 的同輪讀回確認提交與健康使用同一狀態");
|
|
7632
7919
|
console.log("============================================================");
|
|
7633
7920
|
console.log("📋 如你正在進行中的工作對話已熟悉 Agent Handoff Kit,繼續使用原本的開工方式即可,無需重新做新手引導。");
|