@staix/agent-mem 0.28.2 → 0.30.0
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/.claude-plugin/plugin.json +1 -1
- package/README.md +17 -11
- package/package.json +3 -2
- package/src/brief-work.ts +142 -0
- package/src/cli.ts +97 -17
- package/src/commands-table.ts +6 -0
- package/src/mcp-memory.ts +37 -9
- package/src/memory/bridge.ts +26 -1
- package/src/memory/capacity.ts +5 -2
- package/src/memory/catalog.ts +10 -1
- package/src/memory/commands.ts +5 -3
- package/src/memory/curated-cache-state.ts +10 -7
- package/src/memory/doctor.ts +32 -26
- package/src/memory/formats.ts +4 -3
- package/src/memory/generation-index.ts +79 -17
- package/src/memory/index-file.ts +2 -2
- package/src/memory/intent-brief.ts +34 -6
- package/src/memory/metrics.ts +174 -14
- package/src/memory/shard-bridge.ts +18 -6
- package/src/memory/shard-sync-format.ts +18 -0
- package/src/memory/shard-sync-history.ts +6 -0
- package/src/memory/shard-sync.ts +52 -4
- package/src/memory/shard.ts +33 -13
- package/src/memory/store.ts +147 -41
- package/src/memory/sync-placement-bound.ts +21 -4
- package/src/memory/sync-placement-cache.ts +16 -1
- package/src/memory/sync-placement-capture.ts +67 -19
- package/src/memory/sync-placement-checkpoint-format.ts +199 -0
- package/src/memory/sync-placement-checkpoint-person.ts +209 -0
- package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
- package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
- package/src/memory/sync-placement-checkpoint.ts +234 -0
- package/src/memory/sync-placement-dependencies.ts +42 -9
- package/src/memory/sync-placement-effective-writers.ts +12 -6
- package/src/memory/sync-placement-git.ts +17 -7
- package/src/memory/sync-placement-guard.ts +52 -1
- package/src/memory/sync-placement-inspection-evidence.ts +1 -1
- package/src/memory/sync-placement-inventory.ts +141 -0
- package/src/memory/sync-placement-journal-format.ts +4 -1
- package/src/memory/sync-placement-journal-storage.ts +148 -28
- package/src/memory/sync-placement-journal.ts +13 -4
- package/src/memory/sync-placement-materialize.ts +47 -22
- package/src/memory/sync-placement-projection.ts +7 -1
- package/src/memory/sync-placement-publication-events.ts +42 -0
- package/src/memory/sync-placement-publication-plan.ts +26 -5
- package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
- package/src/memory/sync-placement-realm-admission.ts +352 -0
- package/src/memory/sync-placement-realm-attribution.ts +23 -0
- package/src/memory/sync-placement-realm-discovery.ts +42 -0
- package/src/memory/sync-placement-realm-effective.ts +71 -0
- package/src/memory/sync-placement-realm-extension-format.ts +66 -0
- package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
- package/src/memory/sync-placement-realm-intent-format.ts +55 -0
- package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
- package/src/memory/sync-placement-realm-pending.ts +27 -0
- package/src/memory/sync-placement-realm-proof.ts +131 -0
- package/src/memory/sync-placement-realm-torn.ts +26 -0
- package/src/memory/sync-placement-remote-admission.ts +190 -0
- package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
- package/src/memory/sync-placement-remote-materialization.ts +49 -0
- package/src/memory/sync-placement-remote-refusal.ts +21 -0
- package/src/memory/sync-placement-remote-stage.ts +275 -0
- package/src/memory/sync-placement-transport.ts +268 -79
- package/src/memory/sync-placement-writer-history.ts +75 -17
- package/src/memory/sync-placement-writer-renewal.ts +18 -10
- package/src/memory/sync-placement-writer-revision-format.ts +16 -13
- package/src/memory/sync-placement-yield.ts +44 -0
- package/src/memory/sync-progress.ts +47 -6
- package/src/memory/sync.ts +26 -1
- package/src/memory/work-lists.ts +129 -9
- package/src/session-brief.ts +34 -1
- package/src/sync-placement-writer-context.ts +5 -5
- package/src/ui/plugin.ts +1 -1
|
@@ -1,41 +1,50 @@
|
|
|
1
1
|
/** Activated placement transport. The public sync entrypoint owns dispatch; this module never activates a profile. */
|
|
2
2
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
-
import { constants, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, rmSync, writeSync } from "node:fs";
|
|
3
|
+
import { constants, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, rmSync, writeSync, type BigIntStats } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { canonicalJSON, hashJSON, readSelector } from "./generation.ts";
|
|
6
6
|
import { generationSyncLock } from "./generation-sync.ts";
|
|
7
|
-
import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncOptions, type SyncResult } from "./sync.ts";
|
|
7
|
+
import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncFailureCause, type SyncOptions, type SyncResult } from "./sync.ts";
|
|
8
8
|
import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
9
9
|
import { isLocalKey, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
|
|
10
10
|
import { memoryPolicySnapshot } from "./policy.ts";
|
|
11
11
|
import { outboundPolicyEvaluator } from "./sync-screen.ts";
|
|
12
12
|
import { readActivePlacementBinding } from "./sync-placement-active.ts";
|
|
13
13
|
import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
|
|
14
|
-
import {
|
|
14
|
+
import { captureSyncPlacementContextAsync, placementCaptureContextHash, previewSyncPlacementSources, type PlacementCapture, type PlacementPendingSource } from "./sync-placement-capture.ts";
|
|
15
15
|
import { readEffectiveSyncPlacementWriters, type EffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
|
|
16
16
|
import { SharedWriterRevisionError } from "./sync-placement-writer-revision-format.ts";
|
|
17
17
|
import { types } from "node:util";
|
|
18
|
+
import { RemoteRealmRefusal, type RemoteRealmCause } from "./sync-placement-remote-refusal.ts";
|
|
18
19
|
import type { PlannedGitObject } from "./sync-placement-git.ts";
|
|
19
|
-
import { PLACEMENT_FORMAT } from "./sync-placement-format.ts";
|
|
20
|
-
import { PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS, createPlacementRecord, placementKeyId, type PlacementEvent, type PlacementRealm, type
|
|
20
|
+
import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, SyncPlacementFormatError } from "./sync-placement-format.ts";
|
|
21
|
+
import { PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS, createPlacementRecord, placementKeyId, type PlacementEvent, type PlacementRealm, type PlacementRecord } from "./sync-placement-journal-format.ts";
|
|
21
22
|
import { rebuildPlacementProjection, type PlacementProjection } from "./sync-placement-projection.ts";
|
|
22
|
-
import { readPlacementJournal, appendPlacementEvent, appendPlacementEvents, releasePlacementStorageCaches, ensurePlacementPublicationDurability, readPlacementPublicationMetadata, type PlacementJournalRead, type PlacementStorageOptions } from "./sync-placement-journal-storage.ts";
|
|
23
|
+
import { readPlacementJournal, readPlacementWriterJournalAnchors, placementWriterJournalToken, appendPlacementEvent, appendPlacementEvents, releasePlacementStorageCaches, ensurePlacementPublicationDurability, readPlacementPublicationMetadata, placementJournalObjectComposition, placementJournalObjectCompositionText, type PlacementJournalObjectComposition, type PlacementJournalRead, type PlacementStorageOptions } from "./sync-placement-journal-storage.ts";
|
|
23
24
|
import { formatFloorAtLeast } from "./formats.ts";
|
|
24
25
|
import { preparePlacementPublication, readPlacementPublication, recordPlacementPublicationPhase, type PlacementPublicationRead } from "./sync-placement-publication-storage.ts";
|
|
25
|
-
import { planPlacementPublication, publicationBytes, publicationFileNames, type PlacementPublicationBundle, type PlacementPublicationDecision, type PlacementPublicationObject } from "./sync-placement-publication-plan.ts";
|
|
26
|
+
import { planPlacementPublication, planPlacementPublicationAsync, publicationBytes, publicationFileNames, type PlacementPublicationBundle, type PlacementPublicationDecision, type PlacementPublicationObject } from "./sync-placement-publication-plan.ts";
|
|
27
|
+
import { placementPublicationEventSteps } from "./sync-placement-publication-events.ts";
|
|
26
28
|
import { ShardHistoryAuditor, type ShardHistory } from "./shard-sync-history.ts";
|
|
27
29
|
import { ShardSyncApplications } from "./shard-sync-applications.ts";
|
|
28
|
-
import {
|
|
30
|
+
import { ShardSourceChangedError, shardSourceRowsAsync, shardProvePrunes, shardImportRows, shardSelectorRetention, shardInstallHold, shardHoldWarning, type ShardSyncApplicationTarget } from "./shard-sync.ts";
|
|
29
31
|
import { shardSyncRef, SHARD_PACK_MAX_BYTES } from "./shard-sync-format.ts";
|
|
30
32
|
import { assertPublisherBoundary, ensurePublisherBoundary, publisherPruneLineages } from "./prune-publisher-lineage.ts";
|
|
31
33
|
import type { MemoryStore } from "./store.ts";
|
|
32
34
|
import type { PruneRow } from "./prune.ts";
|
|
33
35
|
import { materializePlacementRows, verifiedPlacementPrunes } from "./sync-placement-materialize.ts";
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
36
|
+
import { cooperativeYield, drainSteps, drainStepsAsync, PLACEMENT_APPEND_SLICE, yieldTurn, type CooperativeYield } from "./sync-placement-yield.ts";
|
|
37
|
+
import { placementCacheConfigStamp, placementCacheRootStamp, placementCacheTreePrivate, validatePlacementCacheConfig } from "./sync-placement-cache.ts";
|
|
38
|
+
import { PlacementSyncBoundError, placementSyncBoundDetail, placementSyncBoundMessage, placementSyncBoundReceipt, type PlacementSyncBound } from "./sync-placement-bound.ts";
|
|
39
|
+
import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending } from "./sync-placement-checkpoint-storage.ts";
|
|
36
40
|
import type { SyncProgress, SyncProgressPhase } from "./sync-progress.ts";
|
|
37
41
|
import { PlacementSyncRefusal, placementRefusalCategoryOf, placementRefusalMessage, type PlacementRefusalCategory } from "./sync-placement-refusal.ts";
|
|
38
42
|
import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
|
|
43
|
+
import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
|
|
44
|
+
import { listRemotePlacementRealms, REMOTE_REALM_ADVERTISEMENT_BYTES, type RemoteOnlyRealm } from "./sync-placement-realm-discovery.ts";
|
|
45
|
+
import { realPath } from "./platform.ts";
|
|
46
|
+
import { createRemoteAdoption, REMOTE_ADOPTION_SCHEMA, validateRemoteAdoption, type RemoteAdoption } from "./sync-placement-remote-adoption-format.ts";
|
|
47
|
+
import { remoteStagedPacks, selectRemoteMaterialization, type RemoteStagedPack } from "./sync-placement-remote-materialization.ts";
|
|
39
48
|
|
|
40
49
|
/**
|
|
41
50
|
* #417 proof scope. A complete proof (full writer-install measurement, source, policy and selector recheck) is taken
|
|
@@ -54,10 +63,20 @@ const oid = (v: unknown): v is string => typeof v === "string" && v.length === 4
|
|
|
54
63
|
const sameRealm = (a: PlacementRealm, b: PlacementRealm) => canonicalJSON(a) === canonicalJSON(b);
|
|
55
64
|
const physical = (target: Target): PlacementRealm => target.realm.scope === "user" ? { scope: "user" } : { scope: "project", keyHash: digest(target.realm.key) };
|
|
56
65
|
function refuse(category: PlacementRefusalCategory = "other"): never { throw new PlacementSyncRefusal(category); }
|
|
66
|
+
function remoteRefusal(error: unknown, fallback: RemoteRealmCause = "other"): never {
|
|
67
|
+
if (error instanceof RemoteRealmRefusal) throw error;
|
|
68
|
+
if (error instanceof SyncPlacementFormatError || error instanceof Error && error.message === "sync placement activation metadata unavailable or changed; inspect the retained activation before continuing") throw new RemoteRealmRefusal("epoch");
|
|
69
|
+
const category = placementRefusalCategoryOf(error) ?? classifyPlacementError(error);
|
|
70
|
+
const cause: RemoteRealmCause = category === "lock" ? "lock" : category === "epoch" ? "epoch"
|
|
71
|
+
: category === "remote" ? "remote" : category === "size-bound" ? "bound"
|
|
72
|
+
: category === "source-selection" || category === "policy" || category === "writer-pin" ? "drift" : fallback;
|
|
73
|
+
throw new RemoteRealmRefusal(cause);
|
|
74
|
+
}
|
|
57
75
|
/** #426: map a foreign error to a category by its class and allowlisted code only, never by its message text. */
|
|
58
76
|
export function classifyPlacementError(error: unknown): PlacementRefusalCategory | undefined {
|
|
59
77
|
try {
|
|
60
78
|
if (!error || typeof error !== "object" || types.isProxy(error)) return undefined;
|
|
79
|
+
if (error instanceof ShardSourceChangedError) return "source-selection";
|
|
61
80
|
if (error instanceof SharedWriterRevisionError) return "writer-pin";
|
|
62
81
|
if (error instanceof SyncPlacementJournalError) { const code = Object.getOwnPropertyDescriptor(error, "code")?.value; return code === "bound" ? "size-bound" : code === "changed" ? "source-selection" : "epoch"; }
|
|
63
82
|
const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
|
|
@@ -68,8 +87,147 @@ export function classifyPlacementError(error: unknown): PlacementRefusalCategory
|
|
|
68
87
|
function directory(file: string): void { const s = lstatSync(file); if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid?.() || (s.mode & 0o077) !== 0) refuse(); }
|
|
69
88
|
function emptyHistory(): ShardHistory { return { rows: new Map(), files: new Map(), origins: new Map(), manifests: new Map(), version: "v3" }; }
|
|
70
89
|
/** Internal phase observer is a fault seam, not part of SyncOptions or the package barrel. */
|
|
71
|
-
export async function syncPlacementMemory(store: MemoryStore, opts: SyncOptions = {}, phase?: Phase, testOnlyError?: (error:unknown)=>void, testOnlyClock?: () => number): Promise<SyncResult> {
|
|
72
|
-
return new PlacementTransport(store, opts, phase, testOnlyError, testOnlyClock).run();
|
|
90
|
+
export async function syncPlacementMemory(store: MemoryStore, opts: SyncOptions = {}, phase?: Phase, testOnlyError?: (error:unknown)=>void, testOnlyClock?: () => number, targets?: readonly MemoryStore[]): Promise<SyncResult> {
|
|
91
|
+
return new PlacementTransport(store, opts, phase, testOnlyError, testOnlyClock, targets).run();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
type RemoteReadOptions = Pick<SyncOptions, "signal" | "visibility">;
|
|
95
|
+
/** Shared configured-remote proof for discovery and audited read-only preview. */
|
|
96
|
+
async function configuredRemoteContext(homeInput: string, opts: RemoteReadOptions, requireVisibility = true) {
|
|
97
|
+
// Git tracing can write an arbitrary file outside the sync cache, which a read-only listing must not do.
|
|
98
|
+
if (Object.entries(process.env).some(([name, value]) => name.startsWith("GIT_TRACE") && !!value)) throw new RemoteRealmRefusal("environment");
|
|
99
|
+
const home = realPath(homeInput), markers = readPlacementRuntimeMarkers(home);
|
|
100
|
+
if (!markers.profile || typeof markers.profile !== "object" || Object.getOwnPropertyDescriptor(markers.profile, "schema")?.value !== PLACEMENT_PROFILE_SCHEMA) return refuse("epoch");
|
|
101
|
+
const active = readActivePlacementBinding(home, markers.profile, markers.shards);
|
|
102
|
+
if (!active) return refuse("epoch");
|
|
103
|
+
const inventory = readEffectiveRealmInventory(home, active), root = join(home, "shard-sync-placement"), cache = join(root, "objects.git");
|
|
104
|
+
let rootStamp: string, configStamp: string, initial: BigIntStats;
|
|
105
|
+
try { rootStamp = placementCacheRootStamp(home); configStamp = placementCacheConfigStamp(cache); initial = lstatSync(cache, { bigint: true }); }
|
|
106
|
+
catch { throw new RemoteRealmRefusal("cache"); }
|
|
107
|
+
if (!initial.isDirectory() || initial.isSymbolicLink() || initial.uid !== BigInt(process.getuid?.() ?? -1) || (initial.mode & 0o077n) !== 0n) throw new RemoteRealmRefusal("cache");
|
|
108
|
+
if (!placementCacheTreePrivate(cache)) throw new RemoteRealmRefusal("cache");
|
|
109
|
+
const forbidden = ["commondir", "shallow", "info/grafts", "objects/info/alternates", "objects/info/http-alternates", "config.worktree"];
|
|
110
|
+
try { if (forbidden.some(name => lstatSync(join(cache, name), { throwIfNoEntry: false }) !== undefined)) throw new RemoteRealmRefusal("cache"); }
|
|
111
|
+
catch { throw new RemoteRealmRefusal("cache"); }
|
|
112
|
+
const check = () => {
|
|
113
|
+
let stat: BigIntStats; try { stat = lstatSync(cache, { bigint: true }); } catch { throw new RemoteRealmRefusal("cache"); }
|
|
114
|
+
const nowMarkers = readPlacementRuntimeMarkers(home), now = readActivePlacementBinding(home, nowMarkers.profile, nowMarkers.shards);
|
|
115
|
+
if (!now || canonicalJSON(now.profile) !== canonicalJSON(active.profile) || canonicalJSON(now.shards) !== canonicalJSON(active.shards)) return refuse("source-selection");
|
|
116
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== initial.dev || stat.ino !== initial.ino
|
|
117
|
+
|| !cacheUnchanged()) throw new RemoteRealmRefusal("cache");
|
|
118
|
+
try { inventory.assertCurrent(); } catch { return refuse("source-selection"); }
|
|
119
|
+
};
|
|
120
|
+
const cacheUnchanged = () => { try { return placementCacheRootStamp(home) === rootStamp && placementCacheConfigStamp(cache) === configStamp && !forbidden.some(name => lstatSync(join(cache, name), { throwIfNoEntry: false }) !== undefined); } catch { return false; } };
|
|
121
|
+
const args = (values: string[]) => ["--no-replace-objects", "--git-dir", cache, "-c", "maintenance.auto=false", "-c", "gc.auto=0", "-c", "core.commitGraph=false", ...values];
|
|
122
|
+
check();
|
|
123
|
+
const config = await generationSyncGitBytes(root, args(["config", "--local", "--no-includes", "--null", "--list"]), opts.signal, undefined, 65536);
|
|
124
|
+
check(); if (config.code !== 0) throw new RemoteRealmRefusal("cache");
|
|
125
|
+
let settings: ReadonlyMap<string, string>; try { settings = validatePlacementCacheConfig(new TextDecoder("utf-8", { fatal: true }).decode(config.out)); } catch { throw new RemoteRealmRefusal("cache"); }
|
|
126
|
+
const url = settings.get("remote.origin.url");
|
|
127
|
+
if (settings.get("core.bare") !== "true" || settings.has("remote.origin.pushurl") && settings.get("remote.origin.pushurl") !== url) throw new RemoteRealmRefusal("cache");
|
|
128
|
+
if (!url || url.length > 4096 || url.startsWith("-") || /[\r\n\0]/.test(url)) return refuse("remote");
|
|
129
|
+
if (requireVisibility && await (opts.visibility ?? remoteVisibility)(url) !== "private") return refuse("remote");
|
|
130
|
+
check();
|
|
131
|
+
return { home, active, inventory, root, cache, url, args, check };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Read only the configured placement remote; discovery never initializes a cache or adopts a realm. */
|
|
135
|
+
export async function discoverRemotePlacementRealms(homeInput: string, opts: RemoteReadOptions = {}): Promise<RemoteOnlyRealm[]> {
|
|
136
|
+
try {
|
|
137
|
+
const context = await configuredRemoteContext(homeInput, opts);
|
|
138
|
+
const realms = await listRemotePlacementRealms(context.inventory, async () => {
|
|
139
|
+
const advertised = await generationSyncGitBytes(context.root, context.args(["ls-remote", "--refs", context.url, "refs/heads/amem/p/*"]), opts.signal, undefined, REMOTE_REALM_ADVERTISEMENT_BYTES);
|
|
140
|
+
context.check(); if (advertised.code !== 0) return refuse("remote");
|
|
141
|
+
return advertised.out;
|
|
142
|
+
});
|
|
143
|
+
context.check(); return realms;
|
|
144
|
+
} catch (error) { return remoteRefusal(error); }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Recheck the reviewed head and configured remote immediately before staging publication. */
|
|
148
|
+
export async function assertRemoteAdoptionCurrent(homeInput: string, project: string, plan: RemoteAdoption, opts: RemoteReadOptions = {}): Promise<void> {
|
|
149
|
+
try {
|
|
150
|
+
plan = validateRemoteAdoption(plan);
|
|
151
|
+
const ctx = await configuredRemoteContext(homeInput, opts), key = createHash("sha256").update(project).digest("hex");
|
|
152
|
+
if (key !== plan.keyHash || ctx.active.epoch.homeHash !== plan.homeHash || ctx.active.profile.placementHead !== plan.epochHash
|
|
153
|
+
|| ctx.active.epoch.generation !== plan.generation || createHash("sha256").update(ctx.url).digest("hex") !== plan.remoteHash) return refuse("source-selection");
|
|
154
|
+
const ref = shardSyncRef({ scope: "project", key: project }), result = await generationSyncGitBytes(ctx.root,
|
|
155
|
+
ctx.args(["ls-remote", "--refs", ctx.url, ref]), opts.signal, undefined, 256);
|
|
156
|
+
ctx.check(); if (result.code !== 0 || new TextDecoder("utf-8", { fatal: true }).decode(result.out) !== `${plan.remoteHead}\t${ref}\n`) return refuse("remote");
|
|
157
|
+
} catch (error) { return remoteRefusal(error); }
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export interface PreparedRemoteRealm { plan: RemoteAdoption; packs: RemoteStagedPack[] }
|
|
161
|
+
async function auditRemoteHistory(ctx: Awaited<ReturnType<typeof configuredRemoteContext>>, project: string, head: string, opts: RemoteReadOptions): Promise<ShardHistory> {
|
|
162
|
+
const gitBytes = async (args: string[], max: number) => { ctx.check(); const result = await generationSyncGitBytes(ctx.root, ctx.args(args), opts.signal, undefined, max); ctx.check(); if (result.code !== 0) return refuse("remote"); return Buffer.from(result.out); };
|
|
163
|
+
const auditor = new ShardHistoryAuditor({ realm: { scope: "project", key: project }, generation: ctx.active.epoch.generation, placement: true, publicPrune: true,
|
|
164
|
+
git: async args => { ctx.check(); const result = await generationSyncGit(ctx.root, ctx.args(args), opts.signal); ctx.check(); if (result.code !== 0) return refuse("remote"); return result.out; },
|
|
165
|
+
blob: async (oid, path) => gitBytes(["cat-file", "blob", oid], path === "shard.json" || path.startsWith("prune-witnesses/") ? 65536 : SHARD_PACK_MAX_BYTES),
|
|
166
|
+
object: async (oid, type) => {
|
|
167
|
+
const bytes = await gitBytes(["cat-file", type, oid], type === "commit" ? 65536 : SHARD_PACK_MAX_BYTES);
|
|
168
|
+
if (createHash("sha1").update(`${type} ${bytes.length}\0`).update(bytes).digest("hex") !== oid) return refuse("remote"); return bytes;
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
return auditor.history(head);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Reconstruct frozen pack bytes from the existing cache without contacting the remote. */
|
|
175
|
+
export async function recoverRemoteStagedPacks(homeInput: string, project: string, plan: RemoteAdoption): Promise<RemoteStagedPack[]> {
|
|
176
|
+
try {
|
|
177
|
+
plan = validateRemoteAdoption(plan);
|
|
178
|
+
const ctx = await configuredRemoteContext(homeInput, {}, false), key = createHash("sha256").update(project).digest("hex");
|
|
179
|
+
if (key !== plan.keyHash || ctx.active.epoch.homeHash !== plan.homeHash || ctx.active.profile.placementHead !== plan.epochHash
|
|
180
|
+
|| ctx.active.epoch.generation !== plan.generation || createHash("sha256").update(ctx.url).digest("hex") !== plan.remoteHash) return refuse("source-selection");
|
|
181
|
+
const selection = selectRemoteMaterialization(await auditRemoteHistory(ctx, project, plan.remoteHead, {})), packs = remoteStagedPacks(selection);
|
|
182
|
+
if (selection.omitted !== plan.omitted || canonicalJSON(packs.map(pack => ({ name: pack.name, bytes: pack.bytes.length }))) !== canonicalJSON(plan.packs)) return refuse("source-selection");
|
|
183
|
+
ctx.check(); return packs;
|
|
184
|
+
} catch (error) { return remoteRefusal(error, "staging"); }
|
|
185
|
+
}
|
|
186
|
+
/** Fetch and audit one explicitly named remote-only realm into the existing private cache, never the live shard. */
|
|
187
|
+
export async function prepareRemotePlacementRealm(homeInput: string, project: string, opts: RemoteReadOptions = {}): Promise<PreparedRemoteRealm> {
|
|
188
|
+
let releaseRoot: (() => void) | undefined, releaseSync: (() => void) | undefined, incoming: string | undefined;
|
|
189
|
+
let context: Awaited<ReturnType<typeof configuredRemoteContext>> | undefined;
|
|
190
|
+
try {
|
|
191
|
+
if (!project || Buffer.byteLength(project) > 400 || /[\r\n\0]/.test(project)) return refuse("source-selection");
|
|
192
|
+
context = await configuredRemoteContext(homeInput, opts);
|
|
193
|
+
const ctx = context, keyHash = createHash("sha256").update(project).digest("hex");
|
|
194
|
+
// Ref names use only 16 hex characters; a prefix already bound to another full key is never adopted as a new realm.
|
|
195
|
+
if (ctx.inventory.realms.some(realm => realm.scope === "project" && realm.keyHash.slice(0, 16) === keyHash.slice(0, 16))) return refuse("source-selection");
|
|
196
|
+
const ref = shardSyncRef({ scope: "project", key: project }), source = previewSyncPlacementSources(ctx.home);
|
|
197
|
+
const writers = readEffectiveSyncPlacementWriters(ctx.home), journalToken = placementWriterJournalToken(ctx.home, ctx.active.profile.placementHead);
|
|
198
|
+
const journal = readPlacementWriterJournalAnchors(ctx.home, ctx.active.profile.placementHead);
|
|
199
|
+
const journalHead = journal.sequence ? journal.records[journal.sequence - 1]!.seal : ctx.active.profile.placementHead;
|
|
200
|
+
const check = () => {
|
|
201
|
+
ctx.check();
|
|
202
|
+
try { writers.assertCurrent(); if (placementWriterJournalToken(ctx.home, ctx.active.profile.placementHead) !== journalToken) return refuse("source-selection"); source.assertSourcesUnchanged(); }
|
|
203
|
+
catch { return refuse("source-selection"); }
|
|
204
|
+
ctx.check();
|
|
205
|
+
};
|
|
206
|
+
check(); releaseRoot = acquireMutation(ctx.root); if (!releaseRoot) return refuse("lock");
|
|
207
|
+
releaseSync = generationSyncLock(ctx.root); if (!releaseSync) return refuse("lock");
|
|
208
|
+
const gitBytes = async (args: string[], max: number) => { check(); const result = await generationSyncGitBytes(ctx.root, ctx.args(args), opts.signal, undefined, max); check(); if (result.code !== 0) return refuse("remote"); return Buffer.from(result.out); };
|
|
209
|
+
const advertised = await gitBytes(["ls-remote", "--refs", ctx.url, ref], 256);
|
|
210
|
+
const match = /^([a-f0-9]{40})\t([^\n]+)\n$/.exec(advertised.toString("utf8"));
|
|
211
|
+
if (!match || match[2] !== ref) return refuse("remote");
|
|
212
|
+
const head = match[1]!; incoming = `refs/amem/placement-incoming/${randomBytes(16).toString("hex")}`;
|
|
213
|
+
await gitBytes(["fetch", "-q", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", ctx.url, `${ref}:${incoming}`], 65536);
|
|
214
|
+
const fetched = (await gitBytes(["rev-parse", "--verify", incoming], 128)).toString("utf8").trim(); if (fetched !== head) return refuse("remote");
|
|
215
|
+
const history = await auditRemoteHistory(ctx, project, head, opts), selection = selectRemoteMaterialization(history), packs = remoteStagedPacks(selection);
|
|
216
|
+
if (!(await gitBytes(["ls-remote", "--refs", ctx.url, ref], 256)).equals(advertised)) return refuse("remote");
|
|
217
|
+
check();
|
|
218
|
+
const plan = createRemoteAdoption({ schema: REMOTE_ADOPTION_SCHEMA, homeHash: ctx.active.epoch.homeHash, epochHash: ctx.active.profile.placementHead,
|
|
219
|
+
generation: ctx.active.epoch.generation, keyHash, remoteHash: createHash("sha256").update(ctx.url).digest("hex"), remoteHead: head,
|
|
220
|
+
sourceHash: source.base.sourceHash, policyHash: source.base.policyHash, aliasesHash: source.base.aliasesHash,
|
|
221
|
+
writerHash: writers.revisionHash, inventoryHead: ctx.inventory.extensionHead, journalSequence: journal.sequence, journalHead, omitted: selection.omitted,
|
|
222
|
+
packs: packs.map(pack => ({ name: pack.name, bytes: pack.bytes.length })) });
|
|
223
|
+
check(); return { plan, packs };
|
|
224
|
+
} catch (error) { return remoteRefusal(error); }
|
|
225
|
+
finally {
|
|
226
|
+
if (context && incoming) try {
|
|
227
|
+
context.check(); await generationSyncGit(context.root, context.args(["update-ref", "--no-deref", "-d", incoming]), undefined);
|
|
228
|
+
} catch { /* no authoritative state uses this private cache ref */ }
|
|
229
|
+
releaseSync?.(); releaseRoot?.();
|
|
230
|
+
}
|
|
73
231
|
}
|
|
74
232
|
class PlacementTransport {
|
|
75
233
|
readonly store: MemoryStore; readonly opts: SyncOptions; readonly phase?: Phase; readonly testOnlyError?: (error:unknown)=>void; readonly home: string; readonly root: string; readonly cache: string;
|
|
@@ -79,8 +237,13 @@ class PlacementTransport {
|
|
|
79
237
|
machineId = ""; url = ""; revision = ""; accepted = false; factual = false; attempted = false; lastPolicyCheckUnixMs?: number; lastPolicyHash?: string; policyCheckSource?: "live"|"durable-intent"; attemptHash?: string;
|
|
80
238
|
evaluator?: ReturnType<typeof outboundPolicyEvaluator>; applications?: ShardSyncApplications; current?: Materialized; recovered = false;
|
|
81
239
|
writerInventory?:EffectiveSyncPlacementWriters;
|
|
240
|
+
/** #462: a closed cause the catch block identified before `result` derives the rest. */
|
|
241
|
+
failureCause?: SyncFailureCause;
|
|
82
242
|
readonly clock: () => number; readonly progress?: SyncProgress; provedAt?: number; bound?: PlacementSyncBound; capturedPolicyVersion?: string;
|
|
83
|
-
|
|
243
|
+
/** #288 step 1: the journal-objects bound's own composition, numbers only, set where the bound is measured. */
|
|
244
|
+
journalObjects?: PlacementJournalObjectComposition;
|
|
245
|
+
readonly selected?: readonly MemoryStore[];
|
|
246
|
+
constructor(store: MemoryStore, opts: SyncOptions, phase?: Phase, testOnlyError?: (error:unknown)=>void, clock: () => number = () => performance.now(), selected?: readonly MemoryStore[]) { this.selected=selected; this.clock=clock; this.progress=opts.progress; this.testOnlyError=testOnlyError; this.store = store; this.opts = opts; this.phase = phase; this.home = store.profile.home; this.root = join(this.home, "shard-sync-placement"); this.cache = join(this.root, "objects.git"); }
|
|
84
247
|
attest(): void {
|
|
85
248
|
if (!this.opts.placementAttestation || this.opts.screen && !this.opts.policyVersion) refuse("policy");
|
|
86
249
|
const value = memoryPolicySnapshot(this.opts.placementAttestation());
|
|
@@ -141,7 +304,7 @@ class PlacementTransport {
|
|
|
141
304
|
}
|
|
142
305
|
async independent(): Promise<boolean> {
|
|
143
306
|
if (!existsSync(this.cache)) return false; directory(this.cache); const initial=lstatSync(this.cache);
|
|
144
|
-
|
|
307
|
+
if (!placementCacheTreePrivate(this.cache)) refuse();
|
|
145
308
|
if (existsSync(join(this.cache, "commondir")) || existsSync(join(this.cache, "objects", "info", "http-alternates")) || existsSync(join(this.cache, "objects", "info", "alternates")) || existsSync(join(this.cache, "shallow")) || existsSync(join(this.cache, "info", "grafts"))) refuse();
|
|
146
309
|
if (await this.required(["rev-parse", "--is-bare-repository"]) !== "true" || await this.required(["rev-parse", "--show-object-format"]) !== "sha1" || (await this.git(["config", "--get", "core.worktree"])).code !== 1) refuse();
|
|
147
310
|
if((await this.git(["config","--get","extensions.partialClone"])).code !== 1
|
|
@@ -152,10 +315,14 @@ class PlacementTransport {
|
|
|
152
315
|
async initialize(): Promise<void> {
|
|
153
316
|
const markers = readPlacementRuntimeMarkers(this.home), active = readActivePlacementBinding(this.home, markers.profile, markers.shards);
|
|
154
317
|
if (!active || this.store.profile.publicationFormat !== PLACEMENT_FORMAT || this.store.profile.placementHead !== active.profile.placementHead) refuse("epoch");
|
|
155
|
-
this.epochHash = active.profile.placementHead; this.machineId = active.shards.machine.id; this.revision = readSelector(this.home).revision; this.journal = readPlacementJournal(this.home, this.epochHash);
|
|
156
|
-
|
|
318
|
+
this.epochHash = active.profile.placementHead; this.machineId = active.shards.machine.id; this.revision = readSelector(this.home).revision; this.journal = readPlacementJournal(this.home, this.epochHash);
|
|
319
|
+
await yieldTurn(); // #462: no lock is held yet; each heavy read gets its own macrotask
|
|
320
|
+
this.writerInventory=readEffectiveSyncPlacementWriters(this.home);await yieldTurn();this.attest();
|
|
321
|
+
// #450: an inventory driver passes at most two explicitly opened realms (one unchanged publication plan); otherwise the store's own pair.
|
|
322
|
+
const opened = this.selected ?? this.store.openedSyncTargets();
|
|
157
323
|
if (!opened.length || opened.length > 2 || !opened.includes(this.store) || opened.some(item => item.profile.home !== this.home || !item.profile.sharded || !item.profile.generation
|
|
158
|
-
||
|
|
324
|
+
|| item.profile.generation !== this.store.profile.generation
|
|
325
|
+
|| !this.selected && !item.profile.shardUser && item.profile.shardKey !== this.store.profile.shardKey)) refuse("source-selection");
|
|
159
326
|
for (const item of opened) {
|
|
160
327
|
const realm = item.profile.shardUser ? { scope: "user" as const } : { scope: "project" as const, key: item.profile.shardKey! };
|
|
161
328
|
const target = { store: item, realm, generation: item.profile.generation!, rows: new Map(), fetched: new Set(), sources: [], pending: [], origins: new Map(), holds: [], manifests: new Map(), eligible: new Set(), registered: [], objects: [], localPrunes: new Map() } as unknown as Target;
|
|
@@ -170,7 +337,7 @@ class PlacementTransport {
|
|
|
170
337
|
this.url = this.opts.remote ?? await this.required(["remote", "get-url", "origin"]);
|
|
171
338
|
if (!this.url || this.url.length > 4096 || this.url.startsWith("-") || /[\r\n\0]/.test(this.url)) refuse("remote");
|
|
172
339
|
if (await this.call(() => (this.opts.visibility ?? remoteVisibility)(this.url)) !== "private") refuse("remote");
|
|
173
|
-
this.prove(); // a host callout ends any reusable proof
|
|
340
|
+
await yieldTurn(); this.prove(); // a host callout ends any reusable proof
|
|
174
341
|
if (!existsSync(this.root)) mkdirSync(this.root, { mode: 0o700 });
|
|
175
342
|
const transport = acquireMutation(this.root); if (!transport) refuse("lock"); this.rootMutation=transport; this.releases.push(transport);
|
|
176
343
|
const sync = generationSyncLock(this.root); if (!sync) refuse("lock"); this.releases.push(sync);
|
|
@@ -178,7 +345,9 @@ class PlacementTransport {
|
|
|
178
345
|
const handle = acquireMutation(dir); if (!handle) refuse("lock"); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
|
|
179
346
|
for (const target of this.targets) if (target.store.dir === dir) target.mutation = handle;
|
|
180
347
|
}
|
|
181
|
-
|
|
348
|
+
// #450: each explicitly selected realm tracks and republishes its own curated cache.
|
|
349
|
+
const curated = (this.selected ?? [this.store]).map(item => item.beginCuratedCacheUpdate());
|
|
350
|
+
this.releaseCurated = () => { for (const release of curated.reverse()) release(); };
|
|
182
351
|
this.journal = readPlacementJournal(this.home, this.epochHash); this.revision = readSelector(this.home).revision; this.attest();
|
|
183
352
|
if (!existing) await this.required(["init", "--bare", "--template=", "--object-format=sha1", "-q", this.cache]);
|
|
184
353
|
if (!await this.independent()) refuse();
|
|
@@ -222,23 +391,25 @@ class PlacementTransport {
|
|
|
222
391
|
target.manifests = new Map(target.remoteHistory.manifests); target.eligible = new Set([...target.manifests.values()].filter(item => item.eligible).map(item => item.row.id));
|
|
223
392
|
}
|
|
224
393
|
}
|
|
225
|
-
preflight(mergeLocal = true): void {
|
|
394
|
+
async preflight(mergeLocal = true): Promise<void> {
|
|
395
|
+
// #462: the collector yields inside the wire round trip, then re-proves the source metadata it exported.
|
|
396
|
+
const pause = cooperativeYield();
|
|
226
397
|
for (const target of this.targets) {
|
|
227
|
-
const source =
|
|
398
|
+
const source = await shardSourceRowsAsync(target.store, target.realm, pause); target.sources = source.sources; target.pending = source.pending;
|
|
228
399
|
target.localPrunes = new Map([...source.rows.filter((row): row is PruneRow => row.op === "prune"), ...source.pending.map(item => item.row)].map(row => [row.id,row]));
|
|
229
400
|
if (mergeLocal) for (const row of source.rows) { const old = target.rows.get(row.id); if (old && hashJSON(old) !== hashJSON(row)) refuse(); target.rows.set(row.id, row); }
|
|
230
401
|
}
|
|
231
402
|
shardProvePrunes(this.targets);
|
|
232
403
|
}
|
|
233
|
-
startCapture(): void {
|
|
404
|
+
async startCapture(): Promise<void> {
|
|
234
405
|
const pending: PlacementPendingSource[] = this.targets.flatMap(target => target.pending.filter(item => !item.unclaimed).map(item => ({ realm: physical(target),
|
|
235
406
|
pathHash: digest(`log/${item.row.machine}.jsonl`), offset: item.offset, prefixHash: item.prefixHash, line: item.line })));
|
|
236
407
|
this.capturedPolicyVersion = this.opts.policyVersion?.();
|
|
237
|
-
this.capture =
|
|
408
|
+
this.capture = await captureSyncPlacementContextAsync(this.home, { attest: this.opts.placementAttestation!, ...(this.opts.policyVersion ? { policyVersion: this.opts.policyVersion } : {}) }, this.targets.map(physical), pending);
|
|
238
409
|
if (this.capture.activeHead !== this.epochHash || this.capture.context.homeHash !== this.journal.epoch.homeHash
|
|
239
410
|
|| canonicalJSON(this.capture.context.writers) !== canonicalJSON(this.writerInventory?.writers)
|
|
240
411
|
|| !!this.writerInventory?.revisionSequence&&this.capture.writerInventory?.revisionHash!==this.writerInventory.revisionHash) refuse("source-selection");
|
|
241
|
-
this.prove();
|
|
412
|
+
await yieldTurn(); this.prove(); // #462: the complete proof that closes capture runs in its own turn; it is the same proof
|
|
242
413
|
}
|
|
243
414
|
async applicationCoordinator(): Promise<ShardSyncApplications> {
|
|
244
415
|
if (!this.homeMutation) refuse();
|
|
@@ -296,46 +467,29 @@ class PlacementTransport {
|
|
|
296
467
|
const body={epochHash:this.epochHash,generation:this.journal.epoch.generation,homeHash:capture.context.homeHash,contextHash:placementCaptureContextHash(capture),markerHash:capture.markerHash,
|
|
297
468
|
sourceHash:capture.context.sourceHash,aliasesHash:capture.context.aliasesHash,policyHash:capture.context.policyHash,remoteHash:digest(this.url),
|
|
298
469
|
journal:frozen?.root.journal??{sequence:frontier.sequence,headHash:frontier.headHash},createdUnixSeconds,policySnapshotUnixMs:frozen?.root.policySnapshotUnixMs??this.lastPolicyCheckUnixMs??Date.now(),targets,reservedRecords:0,reservedRecordBytes:[] as number[]};
|
|
299
|
-
|
|
300
|
-
let
|
|
470
|
+
const planPause=cooperativeYield();
|
|
471
|
+
let bundle=await planPlacementPublicationAsync(body,{sources:capture.prefixes,decisions,objects},planPause);
|
|
472
|
+
await yieldTurn(); // #462: planning is pure; each step gets its own turn
|
|
473
|
+
let scheduled=await this.eventsAsync(bundle,projection,old,planPause);
|
|
474
|
+
await yieldTurn();
|
|
301
475
|
if(!frozen&&body.journal.sequence+scheduled.events.length>PLACEMENT_JOURNAL_MAX_RECORDS)
|
|
302
476
|
throw new PlacementSyncBoundError({phase:"publication-plan",kind:"journal-records",limit:PLACEMENT_JOURNAL_MAX_RECORDS,observed:body.journal.sequence+scheduled.events.length});
|
|
303
477
|
let head=body.journal.headHash;
|
|
304
|
-
const lengths=
|
|
305
|
-
|
|
306
|
-
|
|
478
|
+
const lengths:number[]=[],pause=cooperativeYield();
|
|
479
|
+
for(const [index,event]of scheduled.events.entries()){await pause();const record=createPlacementRecord(this.epochHash,body.journal.sequence+index+1,head,event);head=record.seal;lengths.push(publicationBytes(record).length);}
|
|
480
|
+
await yieldTurn();
|
|
481
|
+
bundle=await planPlacementPublicationAsync({...body,reservedRecords:lengths.length,reservedRecordBytes:lengths},{sources:capture.prefixes,decisions,objects},planPause);
|
|
482
|
+
await yieldTurn();
|
|
483
|
+
scheduled=await this.eventsAsync(bundle,projection,old,planPause);
|
|
307
484
|
if(frozen&&canonicalJSON(bundle)!==canonicalJSON(frozen))refuse();
|
|
308
485
|
return{bundle,decisions,projection,old,...scheduled,exported:scheduled.events.filter(event=>event.kind==="publication-ambiguous").length,withheld:decisions.filter(decision=>!decision.eligible).length};
|
|
309
486
|
}
|
|
310
487
|
events(bundle:PlacementPublicationBundle,projection:PlacementProjection,old:(ShardHistory|undefined)[]):{events:PlacementEvent[];preCount:number;holdCount:number}{
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
effectHash:hashJSON({attempt:root.seal,context:root.contextHash,key:decision.key,kind,commit:commit??null})};
|
|
317
|
-
if(kind==="hold"){
|
|
318
|
-
const reason=decision.reason;
|
|
319
|
-
const hold:PlacementHoldReason=reason==="secret"||reason==="personal-data"||reason==="deny-path"||reason==="private-or-invalid"||reason==="host"||reason==="person-local"?reason:"related-local";
|
|
320
|
-
return{...base,kind,reason:hold};
|
|
321
|
-
}
|
|
322
|
-
const index=root.targets.findIndex(target=>sameRealm(target.realm,decision.key.realm));if(index<0)refuse();
|
|
323
|
-
const outcome={attemptHash:root.seal,remoteHash:root.remoteHash,refHash:root.targets[index]!.refHash};
|
|
324
|
-
if(kind==="publication-ambiguous")return{...base,kind,outcome};
|
|
325
|
-
if(kind!=="publication-committed"||!commit)refuse();
|
|
326
|
-
return{...base,kind,outcome:{...outcome,commit,proofHash:hashJSON({attempt:root.seal,key:decision.key,commit,remote:root.remoteHash,ref:root.targets[index]!.refHash})}};
|
|
327
|
-
};
|
|
328
|
-
for(const decision of decisions){
|
|
329
|
-
const state=projection.get(decision.key);
|
|
330
|
-
const index=root.targets.findIndex(target=>sameRealm(target.realm,decision.key.realm)),target=root.targets[index];if(!target)refuse();
|
|
331
|
-
const original=old[index]?.rows.get(decision.key.id),published=original&&hashJSON(original)===decision.key.rowHash;
|
|
332
|
-
if(decision.hold)holds.push(make(decision,"hold"));
|
|
333
|
-
if(published&&state?.exposure!=="published"&&target.expectedRemoteHead)known.push(make(decision,"publication-committed",target.expectedRemoteHead));
|
|
334
|
-
if(decision.eligible&&target.publish&&!published){
|
|
335
|
-
ambiguous.push(make(decision,"publication-ambiguous"));committed.push(make(decision,"publication-committed",target.commit!));
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
return{events:[...holds,...known,...ambiguous,...committed],preCount:holds.length+known.length+ambiguous.length,holdCount:holds.length};
|
|
488
|
+
return drainSteps(placementPublicationEventSteps(bundle,projection,old));
|
|
489
|
+
}
|
|
490
|
+
/** #470: the same schedule, awaiting the caller's event loop between decisions; the event order is identical. */
|
|
491
|
+
eventsAsync(bundle:PlacementPublicationBundle,projection:PlacementProjection,old:(ShardHistory|undefined)[],pause?:CooperativeYield):Promise<{events:PlacementEvent[];preCount:number;holdCount:number}>{
|
|
492
|
+
return drainStepsAsync(placementPublicationEventSteps(bundle,projection,old),pause);
|
|
339
493
|
}
|
|
340
494
|
async frozenOld(bundle:PlacementPublicationBundle):(Promise<(ShardHistory|undefined)[]>){
|
|
341
495
|
const values:(ShardHistory|undefined)[]=[];
|
|
@@ -345,25 +499,36 @@ class PlacementTransport {
|
|
|
345
499
|
}
|
|
346
500
|
return values;
|
|
347
501
|
}
|
|
348
|
-
appendThrough(bundle:PlacementPublicationBundle,events:PlacementEvent[],count:number,factual=false):void{
|
|
502
|
+
async appendThrough(bundle:PlacementPublicationBundle,events:PlacementEvent[],count:number,factual=false):Promise<void>{
|
|
349
503
|
const root=bundle.root;let read=readPlacementJournal(this.home,this.epochHash),head=root.journal.headHash;
|
|
350
|
-
const records:PlacementRecord[]=[];
|
|
504
|
+
const records:PlacementRecord[]=[],pause=cooperativeYield();
|
|
351
505
|
for(const [index,event]of events.entries()){
|
|
506
|
+
await pause();
|
|
352
507
|
const record=createPlacementRecord(this.epochHash,root.journal.sequence+index+1,head,event);head=record.seal;records.push(record);
|
|
353
508
|
}
|
|
354
509
|
this.enter(factual?"acknowledgment":"journal","records",count);
|
|
355
510
|
const consumed=read.sequence-root.journal.sequence;
|
|
356
511
|
if(consumed<0||consumed>root.reservedRecords)refuse();
|
|
357
|
-
for(let index=0;index<Math.min(consumed,records.length);index++)
|
|
512
|
+
for(let index=0;index<Math.min(consumed,records.length);index++){
|
|
513
|
+
await pause();
|
|
358
514
|
if(canonicalJSON(read.records[root.journal.sequence+index])!==canonicalJSON(records[index]))refuse();
|
|
515
|
+
}
|
|
516
|
+
// #462: the journal this function compared must still be the journal it appends to after the yields above.
|
|
517
|
+
{const now=readPlacementJournal(this.home,this.epochHash);if(now.sequence!==read.sequence||now.headHash!==read.headHash||now.pending!==read.pending)refuse();read=now;}
|
|
359
518
|
if(read.pendingBatch){
|
|
360
519
|
const index=read.sequence-root.journal.sequence, end=index+read.pendingBatch.count;
|
|
361
520
|
if(read.pendingBatch.attemptHash!==root.seal || end>count || end>events.length)refuse();
|
|
362
521
|
appendPlacementEvents(this.home,this.epochHash,events.slice(index,end),read.headHash,this.storage(factual));read=readPlacementJournal(this.home,this.epochHash);
|
|
363
522
|
}else if(read.pending&&!read.pendingRecord&&formatFloorAtLeast(this.home,"sync","0.28.0")){
|
|
364
523
|
const index=read.sequence-root.journal.sequence;
|
|
365
|
-
|
|
366
|
-
|
|
524
|
+
// The storage writer compares the saved bytes against the exact canonical intent before writing.
|
|
525
|
+
// Try the current bounded batch and the unsliced batch used by older writers, in that order. A torn intent
|
|
526
|
+
// precedes every record write, so a prefix shared by both can safely complete the first slice and continue.
|
|
527
|
+
const ends=[Math.min(count,index+PLACEMENT_APPEND_SLICE),count];
|
|
528
|
+
for(const end of new Set(ends)) {
|
|
529
|
+
try { appendPlacementEvents(this.home,this.epochHash,events.slice(index,end),read.headHash,this.storage(factual));read=readPlacementJournal(this.home,this.epochHash);break; }
|
|
530
|
+
catch(error){ if(!(error instanceof SyncPlacementJournalError)||error.code!=="conflict")throw error; }
|
|
531
|
+
}
|
|
367
532
|
}
|
|
368
533
|
if(read.pending){
|
|
369
534
|
const sequence=read.pendingRecordSequence??read.sequence+1, index=sequence-root.journal.sequence-1;
|
|
@@ -374,9 +539,18 @@ class PlacementTransport {
|
|
|
374
539
|
this.progress?.advance(Math.max(0,Math.min(count,read.sequence-root.journal.sequence)));
|
|
375
540
|
const next=read.sequence-root.journal.sequence;
|
|
376
541
|
if(next<count&&formatFloorAtLeast(this.home,"sync","0.28.0")){
|
|
377
|
-
|
|
542
|
+
// #462: the same records in order, as consecutive atomic batches with a macrotask turn between them. A crash between
|
|
543
|
+
// batches leaves a durable prefix, which the `consumed` path above already resumes exactly as recorded.
|
|
544
|
+
for(let at=next;at<count;at+=PLACEMENT_APPEND_SLICE){
|
|
545
|
+
if(at>next)await yieldTurn();
|
|
546
|
+
const end=Math.min(count,at+PLACEMENT_APPEND_SLICE),from=readPlacementJournal(this.home,this.epochHash);
|
|
547
|
+
if(from.sequence!==root.journal.sequence+at)refuse();
|
|
548
|
+
appendPlacementEvents(this.home,this.epochHash,events.slice(at,end),from.headHash,this.storage(factual));this.progress?.advance(end-at);
|
|
549
|
+
}
|
|
550
|
+
return;
|
|
378
551
|
}
|
|
379
552
|
for(let index=next;index<count;index++){
|
|
553
|
+
await pause();
|
|
380
554
|
const record=records[index];if(!record)refuse();appendPlacementEvent(this.home,this.epochHash,events[index]!,record.previousHash,this.storage(factual));this.progress?.advance();
|
|
381
555
|
}
|
|
382
556
|
}
|
|
@@ -419,8 +593,8 @@ class PlacementTransport {
|
|
|
419
593
|
const old=await this.frozenOld(read.bundle),schedule=this.events(read.bundle,projection,old);
|
|
420
594
|
const sequence=before.pendingBatch ? before.sequence+before.pendingBatch.count : before.pendingRecordSequence??before.sequence+1;
|
|
421
595
|
if(!before.pendingRecord&&schedule.events[sequence-root.journal.sequence-1]?.kind!=="hold")refuse();
|
|
422
|
-
this.appendThrough(read.bundle,schedule.events,Math.max(holds.length,sequence-root.journal.sequence),true);
|
|
423
|
-
}else this.appendThrough(read.bundle,holds,holds.length,true);
|
|
596
|
+
await this.appendThrough(read.bundle,schedule.events,Math.max(holds.length,sequence-root.journal.sequence),true);
|
|
597
|
+
}else await this.appendThrough(read.bundle,holds,holds.length,true);
|
|
424
598
|
if(read.pendingPhase==="artifact-built"){
|
|
425
599
|
const guard=await this.installedObjectGuard(read.bundle);guard();
|
|
426
600
|
recordPlacementPublicationPhase(this.home,this.epochHash,root.seal,"artifact-built",{exportHash:hashJSON(root.targets.map(target=>target.exportSetHash))},this.storage(true));
|
|
@@ -451,7 +625,7 @@ class PlacementTransport {
|
|
|
451
625
|
}
|
|
452
626
|
async finish(material:Materialized,recovery=false):Promise<SyncResult>{
|
|
453
627
|
this.factual=true;this.recovered=recovery;const root=material.bundle.root;
|
|
454
|
-
await this.observe("before-ack");this.appendThrough(material.bundle,material.events,material.events.length,true);await this.observe("acknowledged");this.metadata();
|
|
628
|
+
await this.observe("before-ack");await this.appendThrough(material.bundle,material.events,material.events.length,true);await this.observe("acknowledged");this.metadata();
|
|
455
629
|
for (const [index,target] of this.targets.entries()) {
|
|
456
630
|
const planned = root.targets[index]!;
|
|
457
631
|
const head = planned.publish ? planned.commit : target.remote;
|
|
@@ -460,7 +634,7 @@ class PlacementTransport {
|
|
|
460
634
|
target.rows = new Map(actual.rows); target.fetched = new Set(actual.rows.keys()); target.origins = new Map(actual.origins);
|
|
461
635
|
} else { target.rows.clear(); target.fetched.clear(); target.candidate = emptyHistory(); }
|
|
462
636
|
}
|
|
463
|
-
this.preflight(false);this.enter("import");
|
|
637
|
+
await this.preflight(false);this.enter("import");
|
|
464
638
|
const applications=await this.applicationCoordinator();await applications.prepare();
|
|
465
639
|
for(const target of this.targets)for(const hold of target.holds)shardInstallHold(this.root,hold);
|
|
466
640
|
await applications.install();
|
|
@@ -497,8 +671,11 @@ class PlacementTransport {
|
|
|
497
671
|
});
|
|
498
672
|
}
|
|
499
673
|
result(ok:boolean,outcome:"committed"|"unknown"|"not-needed",error?:string):SyncResult{
|
|
500
|
-
|
|
501
|
-
|
|
674
|
+
// #462: a closed cause on every failure; the most specific known fact wins.
|
|
675
|
+
const cause:SyncFailureCause|undefined=ok?undefined:this.opts.signal?.aborted?"stopped":this.bound?"bound":outcome==="unknown"?"unknown-outcome":this.failureCause??(this.refusal?"refusal":"unavailable");
|
|
676
|
+
return{ok,pushed:this.accepted&&(this.attempted||this.recovered&&!!this.current?.bundle.root.targets.some(target=>target.publish)),entries:this.current?.exported??0,...(error?{error}:{}),
|
|
677
|
+
...(cause?{failure:{cause,...(cause==="refusal"&&this.refusal?{category:this.refusal}:{})}}:{}),...(this.applications?{pruneApplication:{...this.applications.application}}:{}),
|
|
678
|
+
placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),...(this.journalObjects?{journalObjects:this.journalObjects}:{}),...(this.refusal?{refusal:{category:this.refusal,phase:this.phaseNow}}:{}),withheld:this.current?.withheld??0,exported:this.current?.exported??0,
|
|
502
679
|
...(this.lastPolicyHash?{lastPolicyHash:this.lastPolicyHash}:{}),...(this.lastPolicyCheckUnixMs!==undefined?{lastPolicyCheckUnixMs:this.lastPolicyCheckUnixMs,policyCheckSource:this.policyCheckSource??(this.recovered?"durable-intent" as const:"live" as const)}:{}),
|
|
503
680
|
policyCeiling:"last-positive-check-before-in-flight-push",...(this.recovered?{recovered:true}:{})}};
|
|
504
681
|
}
|
|
@@ -513,8 +690,16 @@ class PlacementTransport {
|
|
|
513
690
|
}
|
|
514
691
|
/** Object slots the plan and its reserved journal chunks need, checked before the first durable plan byte. */
|
|
515
692
|
assertPlanCapacity(bundle:PlacementPublicationBundle):void{
|
|
516
|
-
|
|
517
|
-
|
|
693
|
+
// The refusal's own report (#288 step 1): the same inputs the count uses, split by what holds each object.
|
|
694
|
+
let composition:PlacementJournalObjectComposition|undefined;
|
|
695
|
+
const objects=readPlacementPublicationMetadata(this.home,this.epochHash,io=>{
|
|
696
|
+
const planned=publicationFileNames(bundle.root),reserved=io.reservedJournalNames(bundle.root),names=io.names();
|
|
697
|
+
composition=placementJournalObjectComposition({names:[...names,...planned,...reserved],plan:{root:bundle.root,reserved}});
|
|
698
|
+
return new Set([...names,...planned,...reserved]).size+1;
|
|
699
|
+
});
|
|
700
|
+
if(composition)this.journalObjects=composition;
|
|
701
|
+
if(objects>PLACEMENT_JOURNAL_MAX_OBJECTS)throw new PlacementSyncBoundError({phase:"publication-plan",kind:"journal-objects",limit:PLACEMENT_JOURNAL_MAX_OBJECTS,observed:objects},
|
|
702
|
+
composition&&placementJournalObjectCompositionText(composition));
|
|
518
703
|
}
|
|
519
704
|
async execute():Promise<SyncResult>{
|
|
520
705
|
try{
|
|
@@ -534,7 +719,7 @@ class PlacementTransport {
|
|
|
534
719
|
}
|
|
535
720
|
}
|
|
536
721
|
this.enter("source-capture");
|
|
537
|
-
try { this.preflight();for(const target of this.targets)if(existsSync(join(target.store.dir,"local",`publisher-boundary-${this.machineId}.json`)))assertPublisherBoundary(target.store.profile,target.mutation!);this.startCapture(); }
|
|
722
|
+
try { await yieldTurn();await this.preflight();for(const target of this.targets)if(existsSync(join(target.store.dir,"local",`publisher-boundary-${this.machineId}.json`)))assertPublisherBoundary(target.store.profile,target.mutation!);await yieldTurn();await this.startCapture(); }
|
|
538
723
|
catch(error) { if(retained)return await this.terminalUnknown(retained);if(placementSyncBoundReceipt(error))throw error;throw new PlacementSyncRefusal(placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other"); }
|
|
539
724
|
if(retained){
|
|
540
725
|
const root=retained.bundle.root;
|
|
@@ -546,13 +731,13 @@ class PlacementTransport {
|
|
|
546
731
|
const material=await this.materialize(retained?.bundle.root.createdUnixSeconds??Math.floor(Date.now()/1000),frontier,retained?.bundle);
|
|
547
732
|
const changed=material.bundle.root.targets.some((target,index)=>target.publish&&target.commit!==(this.targets[index]!.remote??null));
|
|
548
733
|
// Nothing durable exists for a fresh attempt yet: an epoch without room for this plan refuses here, typed.
|
|
549
|
-
if(!retained&&(material.events.length||changed))this.assertPlanCapacity(material.bundle);
|
|
734
|
+
await yieldTurn();if(!retained&&(material.events.length||changed))this.assertPlanCapacity(material.bundle);
|
|
550
735
|
this.current=material;this.attemptHash=material.bundle.root.seal;
|
|
551
|
-
const applications=await this.applicationCoordinator();await applications.prepare();
|
|
736
|
+
await yieldTurn();const applications=await this.applicationCoordinator();await applications.prepare();
|
|
552
737
|
if(!retained&&!material.events.length&&!changed&&!this.importsNeeded()){this.attemptHash=undefined;return this.result(true,"not-needed");}
|
|
553
|
-
if(!retained){await this.observe("before-plan-fsync");this.prove();preparePlacementPublication(this.home,material.bundle,this.storage());await this.observe("plan-fsynced");this.prove();}
|
|
738
|
+
if(!retained){await this.observe("before-plan-fsync");await yieldTurn();this.prove();preparePlacementPublication(this.home,material.bundle,this.storage());await this.observe("plan-fsynced");await yieldTurn();this.prove();}
|
|
554
739
|
// One mutation batch: a complete proof on each side, fence checks (and at most 1 s of proof reuse) per record.
|
|
555
|
-
this.prove();this.appendThrough(material.bundle,material.events,material.preCount);this.prove();
|
|
740
|
+
this.prove();await this.appendThrough(material.bundle,material.events,material.preCount);this.prove();
|
|
556
741
|
await this.materializeObjects(material.bundle);
|
|
557
742
|
let read=readPlacementPublication(this.home,this.epochHash,material.bundle.root.seal);
|
|
558
743
|
const artifact=read.facts.find(fact=>fact.phase==="artifact-built");if(!artifact)refuse();
|
|
@@ -572,15 +757,19 @@ class PlacementTransport {
|
|
|
572
757
|
this.factual=true;return await this.finish(material);
|
|
573
758
|
}catch(error){
|
|
574
759
|
try { this.testOnlyError?.(error); } catch { /* Test observers never alter production results. */ }
|
|
760
|
+
// #288 step 3: a started checkpoint pauses every placement effect with its own cause and next step.
|
|
761
|
+
if(this.epochHash&&placementCheckpointPending(this.home,this.epochHash)){this.failureCause="checkpoint-pending";return this.result(false,this.attemptHash?"unknown":"not-needed",PLACEMENT_CHECKPOINT_PENDING_MESSAGE);}
|
|
575
762
|
if(error&&typeof error==="object"&&!types.isProxy(error)&&error instanceof SharedWriterRevisionError){
|
|
576
763
|
const code=Object.getOwnPropertyDescriptor(error,"code")?.value;
|
|
577
|
-
if(code==="staging"||code==="pending")return this.result(false,this.attemptHash?"unknown":"not-needed",new SharedWriterRevisionError(code).message);
|
|
764
|
+
if(code==="staging"||code==="pending"){this.failureCause="writer-renewal";return this.result(false,this.attemptHash?"unknown":"not-needed",new SharedWriterRevisionError(code).message);}
|
|
578
765
|
}
|
|
579
766
|
// #419: an expected size refusal before any attempt exists keeps its phase, kind, limit and observed value.
|
|
580
767
|
const bound=this.attemptHash||this.journal?.publicationReservation?undefined:placementSyncBoundReceipt(error);
|
|
581
|
-
|
|
768
|
+
// #288 step 1: the bound's own numbers-only clause is rebuilt from the receipt for the receipt's fields, so the
|
|
769
|
+
// thrown error's detail is carried over explicitly; the result's error is what the person reads.
|
|
770
|
+
if(bound){this.bound=bound;const detail=placementSyncBoundDetail(error);return this.result(false,"not-needed",placementSyncBoundMessage(bound)+(detail?` ${detail}`:""));}
|
|
582
771
|
if(this.attemptHash)return this.result(false,"unknown","Placement sync stopped with a retained attempt that may have published; recheck its exact receipts before another publication.");
|
|
583
|
-
if (error && typeof error === "object" && !types.isProxy(error) && error instanceof PlacementRealmRefusal && error.origin === "remote") return this.result(false, "not-needed", error.message);
|
|
772
|
+
if (error && typeof error === "object" && !types.isProxy(error) && error instanceof PlacementRealmRefusal && error.origin === "remote") { this.failureCause = "remote"; return this.result(false, "not-needed", error.message); }
|
|
584
773
|
// #426: name the failing check by a fixed category and the phase; never the error's own text, which may carry a path.
|
|
585
774
|
this.refusal=placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other";
|
|
586
775
|
return this.result(false,"not-needed",placementRefusalMessage(this.refusal,this.phaseNow));
|