@staix/agent-mem 0.26.2 → 0.26.3
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 +4 -1
- package/package.json +1 -1
- package/src/cli.ts +31 -1
- package/src/commands-table.ts +3 -1
- package/src/memory/config.ts +11 -1
- package/src/memory/shard-sync-history.ts +5 -1
- package/src/memory/sync-placement-active.ts +21 -0
- package/src/memory/sync-placement-bound.ts +39 -0
- package/src/memory/sync-placement-capture.ts +2 -1
- package/src/memory/sync-placement-dependencies.ts +6 -4
- package/src/memory/sync-placement-journal-storage.ts +70 -15
- package/src/memory/sync-placement-materialize.ts +20 -9
- package/src/memory/sync-placement-projection.ts +10 -1
- package/src/memory/sync-placement-publication-plan.ts +4 -2
- package/src/memory/sync-placement-transport.ts +100 -41
- package/src/memory/sync-progress.ts +192 -0
- package/src/memory/sync.ts +14 -3
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Curated memory with append-only JSONL logs, a derived SQLite index, short- and long-term tiers, a typed graph, goals with leases, and git sync between machines. Extracted from [agent-hub](https://github.com/STAIxBWLB/agent-hub), with compatible storage and entry IDs.
|
|
4
4
|
|
|
5
5
|
<!-- facts:version -->
|
|
6
|
-
Version: 0.26.
|
|
6
|
+
Version: 0.26.3. Requires Bun 1.4.2 or later; no runtime dependencies.
|
|
7
7
|
<!-- /facts:version -->
|
|
8
8
|
|
|
9
9
|
## Quick start
|
|
@@ -114,6 +114,7 @@ The machine-local file `amem.config.json` in the memory home (see `amem status`
|
|
|
114
114
|
- `denyPaths`: substrings of a path that are never captured and that decline any note, candidate or MCP answer naming them. `piiPatterns`: case-insensitive literal substrings (never regular expressions) that decline a value and redact a capture excerpt. Each list holds up to 64 entries of up to 256 bytes.
|
|
115
115
|
- `records`: optional boolean, enabled by default. `false` disables the static native SessionStart instruction and new Claude, Codex, Pi and Kimi `Record` extraction; a repository may disable it but cannot re-enable a machine opt-out. See [assistant records](#assistant-records-313).
|
|
116
116
|
- `briefBytes`, `excerptBytes`, `capturePaths` can only lower the built-in ceilings (the 1200-byte SessionStart context, 2000-character capture excerpt, 32 captured paths). `capture.capMb` and `capture.retentionDays` are the lowest layer of the capture size and retention bounds: a shard's own `config.json` and the home's `capture-config.json` still override them.
|
|
117
|
+
- `privateRemotes`: up to 16 exact remote URLs of a self-hosted Git server that you state are private. `amem sync` (all forms) and repository promotion treat an exact match as a private remote; any other non-GitHub URL stays unknown and is refused. It is your statement, not a check: amem cannot see who can read that server. GitHub URLs are always asked of GitHub (listing one is an error), a URL with a password is an error, and only the home's own file may carry this key.
|
|
117
118
|
- A file with an unknown key, a bad value, a link, or more than 64 KiB is an error that names the file. An unreadable policy is never treated as no policy.
|
|
118
119
|
- `<private>...</private>` spans are dropped before anything else reads the text, at every write boundary (capture, MCP candidates and work lists, notes, goals, promotion and import), so they are never screened, counted or stored. Tags match like HTML (case-insensitive, with attributes or spaces, and `<private/>` opens a span); an unclosed span drops the rest of the text.
|
|
119
120
|
|
|
@@ -618,6 +619,8 @@ amem migrate --sync-placement --abandon --json
|
|
|
618
619
|
|
|
619
620
|
Dry-run shows root versions/pins and safe policy counts, never row text or patterns, and writes nothing. Initial writer errors name the root category and cause, with upgrade/setup instructions. If a pre-marker interruption retained an intent and its inputs changed, person `--abandon` removes only its owned initial metadata so a fresh preview/apply can follow. It cannot remove a v3 marker, active fence or journal history. After apply, choose the private remote on the first v3 sync (`amem sync --remote <private-git-url>`); ordinary and cadence sync then read the immutable root locator and measure the installs afresh. Allowed originals can publish while declined originals remain in the local append-only history, with counts in the sync receipt. No writer roots need to be repeated on sync.
|
|
620
621
|
|
|
622
|
+
A long first sync reports its phase, row counters and last progress on stderr when stderr is a terminal (`--progress json` for one versioned event per line, `--progress off` to silence it); stdout and `--json` output are unchanged. From another terminal, `amem sync --status` shows running, finished or interrupted operations without opening memory or taking a lock. One sync covers the selected project plus the user overlay. Activation and first sync share a 64 MiB/20000-row source envelope; a refusal names its phase, bound kind, limit and observed size.
|
|
623
|
+
|
|
621
624
|
On an active home, the same dry-run/apply commands explicitly renew the writer inventory on its existing epoch (#282). Declare the complete new 0.22.0-or-later roots after updating host pins and managed setup receipts. Ordinary and cadence sync then locate the new inventory and measure it afresh; original activation data, holds and prior receipts are unchanged. Pending publication or source-recovery work must first be finished with the inventoried install, for example after `dot ai rollback amem` or restoring the host's previous pin.
|
|
622
625
|
|
|
623
626
|
An interrupted renewal resumes only its exact intent. Before commit append starts, person `--abandon` can discard its unpublished metadata; after the first commit-log byte, only forward resume is supported. Unpublished intent staging requires explicit `--abandon`, then a fresh dry-run; it is never cleaned automatically. Compatible ordinary reads remain available while only renewal metadata is pending. After a crash, a retained `profile.lock` still blocks new reader admission until person `--resume` or, before commit append, `--abandon`. Never edit activation files, downgrade markers or start another epoch to discard a hold. See the [renewal contract](docs/contracts.md#same-epoch-writer-inventory-renewal-282). Real-home renewal and release remain separately authorized person operations.
|
package/package.json
CHANGED
package/src/cli.ts
CHANGED
|
@@ -83,6 +83,8 @@ export interface CliContext {
|
|
|
83
83
|
/** Whether stdout is a terminal, for the real stdout only (default `process.stdout.isTTY`). */
|
|
84
84
|
stdoutTTY?: boolean;
|
|
85
85
|
edit?: (initial: string) => string | Promise<string>;
|
|
86
|
+
/** Where `sync --progress` writes (default process.stderr) and whether that is a terminal; fixtures stand in for both. */
|
|
87
|
+
stderr?: (text: string) => void; stderrTTY?: boolean;
|
|
86
88
|
/** Test seam: the `sync --if-due` deadline in milliseconds (the CLI always uses 30 seconds). */
|
|
87
89
|
syncDeadlineMs?: number;
|
|
88
90
|
/** Called with the signal name when a person's signal ended `sync --if-due`, after its handlers are removed. `main` re-raises it once the output is written; absent, nothing happens. */
|
|
@@ -1072,6 +1074,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1072
1074
|
// configured remote, nothing when the schedule or the failure backoff says it is not due (`--force` skips that), and it stops a running git step after 30 seconds.
|
|
1073
1075
|
const ifDue = sub === "sync" && options["--if-due"] === true, syncHome = memoryHome();
|
|
1074
1076
|
if (options["--force"] === true && !ifDue) throw new Error("--force only applies with sync --if-due");
|
|
1077
|
+
if (sub === "sync" && options["--status"] === true) {
|
|
1078
|
+
// #418: read-only status from the telemetry sidecars; no realm, lock, proof, journal or schedule is touched.
|
|
1079
|
+
if (Object.keys(options).some(name => name !== "--status" && name !== "--json")) throw new Error("sync --status takes only --json");
|
|
1080
|
+
const { readSyncStatus, renderSyncStatus } = await import("./memory/sync-progress.ts"), report = readSyncStatus(syncHome);
|
|
1081
|
+
return options["--json"] ? JSON.stringify(report, null, 2) : renderSyncStatus(report);
|
|
1082
|
+
}
|
|
1075
1083
|
if (sub === "sync") { assertFormatFloor(syncHome, "sync"); const refusal = placementRuntimeRefusal(syncHome); if (refusal) throw new Error("amem sync: " + refusal); }
|
|
1076
1084
|
if (ifDue) {
|
|
1077
1085
|
if (options["--remote"] === undefined && !remoteConfigured(syncHome)) return options["--json"] ? JSON.stringify({ ok: true, skipped: "no sync remote configured" }) : "no sync remote configured: nothing to do";
|
|
@@ -1091,6 +1099,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1091
1099
|
if (args[index] === "--capture-days") { captureArgs.add(index); captureArgs.add(index + 1); }
|
|
1092
1100
|
else if (args[index]?.startsWith("--capture-days=")) captureArgs.add(index);
|
|
1093
1101
|
}
|
|
1102
|
+
// `sync --progress` is the CLI's own rendering choice; the raw command, which hosts share, never sees it.
|
|
1103
|
+
if (sub === "sync") for (let index = 0; index < args.length; index++) {
|
|
1104
|
+
if (args[index] === "--progress") { captureArgs.add(index); captureArgs.add(index + 1); }
|
|
1105
|
+
else if (args[index]?.startsWith("--progress=")) captureArgs.add(index);
|
|
1106
|
+
}
|
|
1094
1107
|
// --filter and --explain select standalone CLI behavior; hosts keep their existing raw command arguments.
|
|
1095
1108
|
const legacySearch = options["--filter"] === true;
|
|
1096
1109
|
const explainSearch = sub === "search" && options["--explain"] === true;
|
|
@@ -1098,23 +1111,28 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1098
1111
|
const memoryArgs = captureImport && !options["--json"] ? [...syncArgs, "--json"] : syncArgs;
|
|
1099
1112
|
let output: string;
|
|
1100
1113
|
let placementWriters: import("./sync-placement-writer-context.ts").PlacementWriterContext | undefined;
|
|
1114
|
+
let progress: import("./memory/sync-progress.ts").SyncProgress | undefined;
|
|
1101
1115
|
const stop = ifDue ? stopSignal(context.syncDeadlineMs ?? SYNC_IF_DUE_DEADLINE_MS, process) : undefined;
|
|
1102
1116
|
try {
|
|
1103
1117
|
if (sub === "sync" && (readPlacementRuntimeMarkers(syncHome).profile as { publicationFormat?:string } | undefined)?.publicationFormat === "agent-mem.sync-placement/v1") {
|
|
1104
1118
|
const { activePlacementWriterContext } = await import("./sync-placement-writer-context.ts");
|
|
1119
|
+
progress = await placementProgress(syncHome, typeof options["--progress"] === "string" ? options["--progress"] as string : "auto", context);
|
|
1105
1120
|
placementWriters = activePlacementWriterContext(syncHome,fileURLToPath(new URL("..",import.meta.url)));
|
|
1106
1121
|
}
|
|
1107
1122
|
output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person: identity.actor === "person", rankedSearch: identity.actor === "person" && !legacySearch, ...(explainSearch ? { explainSearch: true } : {}), project: boundProject(), open, readable: notes => identity.actor === "person" ? notes : notes.filter(view => view.project === boundProject() && policyOf().screenStandalone(view)), stale: createRecallStalenessProbe({ cwd: recallRoot ?? cwd, rootConfirmed, policy: () => configured }), outputReady: notes => outputReady(notes.map(view => view.id)), importPolicy: () => text => configured.declinesPersonal(text),
|
|
1108
|
-
sync: { ...(placementWriters ? { placementAttestation:placementWriters.attest } : {}), screen: row => configured.screenStandalone(row), policyVersion: () => JSON.stringify(configuredPolicyOptions(memoryHome(), policyCwd)), ...(stop ? { signal: stop.signal } : {}) }, // the repository-narrowed policy binds what sync publishes too
|
|
1123
|
+
sync: { ...(placementWriters ? { placementAttestation:placementWriters.attest } : {}), ...(progress ? { progress } : {}), screen: row => configured.screenStandalone(row), policyVersion: () => JSON.stringify(configuredPolicyOptions(memoryHome(), policyCwd)), ...(stop ? { signal: stop.signal } : {}) }, // the repository-narrowed policy binds what sync publishes too
|
|
1109
1124
|
onBridgeStatus: status => { receipt.bridgeStatus = status; },
|
|
1110
1125
|
// #188: ids-only listing of nearby machine-local rows; policy-refused rows are neither listed nor counted.
|
|
1111
1126
|
forgetNearby: note => forgetNearby({ base: memoryHome(), project: note.project, text: note.text, title: note.title, screen: value => configured.screenStandalone(value) }) }));
|
|
1112
1127
|
} catch (error) {
|
|
1128
|
+
if (sub === "sync") progress?.finish(stop?.cause() ? "cancelled" : "failed", stop?.cause() ? "cancelled" : "unavailable");
|
|
1113
1129
|
if (sub === "sync") stampSync((error as Error).message, stop?.cause());
|
|
1114
1130
|
if (sub === "sync" && placementWriters?.lastRefusal) throw Error(`${placementWriters.lastRefusal.message} ${(error as Error).message}`);
|
|
1115
1131
|
throw error;
|
|
1116
1132
|
}
|
|
1117
1133
|
finally {
|
|
1134
|
+
// A run that never reached the transport's receipt (an early refusal) must not stay "running".
|
|
1135
|
+
progress?.finish("failed", "unavailable");
|
|
1118
1136
|
stop?.dispose();
|
|
1119
1137
|
// A run its person ended ends like that signal (130, 143, 129, 131), as `amem doctor` does, also when `--json` reports it as a result instead of an error: the caller decides when.
|
|
1120
1138
|
const ended = stop?.cause() === "person" ? stop.signalName() : undefined;
|
|
@@ -1144,6 +1162,18 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
1144
1162
|
}
|
|
1145
1163
|
|
|
1146
1164
|
/** Color for human output only on an interactive stdout without NO_COLOR or TERM=dumb (#125). */
|
|
1165
|
+
/**
|
|
1166
|
+
* #418: one reporter per placement sync. The private sidecar backs `sync --status` in every mode; stderr gets human
|
|
1167
|
+
* lines or versioned JSON events. Each part fails alone and silently: telemetry never fails or alters the sync.
|
|
1168
|
+
*/
|
|
1169
|
+
async function placementProgress(home: string, mode: string, context: CliContext): Promise<import("./memory/sync-progress.ts").SyncProgress> {
|
|
1170
|
+
const { SyncProgress, renderSyncProgress, syncProgressSidecar } = await import("./memory/sync-progress.ts");
|
|
1171
|
+
const write = context.stderr ?? ((text: string) => { process.stderr.write(text); });
|
|
1172
|
+
const render = mode === "json" ? "json" : mode === "human" || mode === "auto" && (context.stderrTTY ?? process.stderr.isTTY) ? "human" : undefined;
|
|
1173
|
+
const parts = [syncProgressSidecar(home), ...(render ? [(snapshot: import("./memory/sync-progress.ts").SyncProgressSnapshot) => write((render === "json" ? JSON.stringify(snapshot) : renderSyncProgress(snapshot)) + "\n")] : [])];
|
|
1174
|
+
const live = new Set(parts.keys());
|
|
1175
|
+
return new SyncProgress({ sink: snapshot => { for (const index of live) try { parts[index]!(snapshot); } catch { live.delete(index); } } });
|
|
1176
|
+
}
|
|
1147
1177
|
function outputStyle(context: CliContext): Style { return style(colorEnabled(context.env ?? process.env, context.stdoutTTY ?? process.stdout.isTTY)); }
|
|
1148
1178
|
|
|
1149
1179
|
/** Native ingest remains capture-only and agent-reachable; this formats only its returned receipt. */
|
package/src/commands-table.ts
CHANGED
|
@@ -83,7 +83,9 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
83
83
|
rebuild: { description: "Rebuild the derived index", options: json, mutates: true },
|
|
84
84
|
dedupe: { description: "Preview duplicate reconciliation", options: { ...json, "--apply": flag("Append reconciliation operations") }, mutates: "apply" },
|
|
85
85
|
sync: { description: "Sync a private remote (--if-due: only when the schedule and the failure backoff allow it; --force ignores both)", options: { ...json, ...policy, "--remote": text("Private git URL"),
|
|
86
|
-
"--if-due": flag("Sync only when due (hourly after a success, 15 minutes doubling to a day after failures); stops after 30 seconds"), "--force": flag("With --if-due: ignore the schedule and the backoff")
|
|
86
|
+
"--if-due": flag("Sync only when due (hourly after a success, 15 minutes doubling to a day after failures); stops after 30 seconds"), "--force": flag("With --if-due: ignore the schedule and the backoff"),
|
|
87
|
+
"--progress": { description: "Placement sync progress on stderr: auto (human lines when stderr is a terminal, otherwise none), human, json (one versioned event per line) or off; stdout is unchanged", value: ["auto", "human", "json", "off"] },
|
|
88
|
+
"--status": flag("Read-only: show recorded placement sync operations (running, finished or interrupted) and exit; opens no memory, takes no lock") }, mutates: true, policyFree: true },
|
|
87
89
|
machine: { description: "Show or label this machine", options: { ...json, "--label": text("Machine label") }, mutates: "label" },
|
|
88
90
|
import: { description: "Import external memory", options: { ...json, ...policy, "--db": { description: "SQLite database file", value: "path" }, "--limit": text("Maximum observations"), "--restart": flag("Restart import cursor"), "--capture-days": text("Import recent claude-mem observations and summaries into capture") }, mutates: true, policyFree: true,
|
|
89
91
|
commands: {
|
package/src/memory/config.ts
CHANGED
|
@@ -17,7 +17,7 @@ export const CONFIG_FILE = "amem.config.json";
|
|
|
17
17
|
export const REPO_CONFIG_DIR = ".amem";
|
|
18
18
|
export const REPO_CONFIG_FILE = "config";
|
|
19
19
|
const MAX_CONFIG_BYTES = 64 * 1024;
|
|
20
|
-
const MACHINE_KEYS = ["home", "denyPaths", "piiPatterns", "briefBytes", "excerptBytes", "capturePaths", "capture", "records"] as const;
|
|
20
|
+
const MACHINE_KEYS = ["home", "denyPaths", "piiPatterns", "briefBytes", "excerptBytes", "capturePaths", "capture", "records", "privateRemotes"] as const;
|
|
21
21
|
const REPO_KEYS = ["denyPaths", "piiPatterns", "briefBytes", "excerptBytes", "capturePaths", "records"] as const;
|
|
22
22
|
|
|
23
23
|
export interface AmemConfig {
|
|
@@ -35,6 +35,8 @@ export interface AmemConfig {
|
|
|
35
35
|
capturePaths?: number;
|
|
36
36
|
/** The capture tier's own R6 bounds. Machine file only (a repository cannot widen the machine's disk use). */
|
|
37
37
|
capture: { capMb?: number; retentionDays?: number };
|
|
38
|
+
/** Exact non-GitHub remote URLs the person attests are private (#420). A statement, not a check. Machine file only. */
|
|
39
|
+
privateRemotes?: string[];
|
|
38
40
|
}
|
|
39
41
|
export interface ConfigSource { machine: string | null; repo: string | null }
|
|
40
42
|
export interface LoadedConfig { config: AmemConfig; source: ConfigSource }
|
|
@@ -93,6 +95,13 @@ function parseFile(raw: unknown, label: string, keys: readonly string[]): Partia
|
|
|
93
95
|
if (beside.length) return fail(label, `names a home, so it is only a pointer; put ${beside.join(", ")} in ${join(body.home, CONFIG_FILE)}`);
|
|
94
96
|
out.home = body.home;
|
|
95
97
|
}
|
|
98
|
+
if (body.privateRemotes !== undefined) {
|
|
99
|
+
const remotes = listOf(body.privateRemotes, "privateRemotes", label);
|
|
100
|
+
if (remotes.length > 16) return fail(label, "privateRemotes names more than 16 remotes");
|
|
101
|
+
// GitHub visibility is always asked of GitHub; a URL carrying a password would put a secret in the policy file.
|
|
102
|
+
for (const url of remotes) if (/^\s*(?:[a-z][a-z0-9+.-]*:\/\/)?(?:[^@/]*@)?github\.com(?:[:/]|$)/i.test(url) || /\/\/[^/@]*:[^/@]*@/.test(url)) return fail(label, "privateRemotes lists a GitHub URL or a URL with a password; GitHub visibility is asked of GitHub, and credentials never belong in this file");
|
|
103
|
+
out.privateRemotes = remotes;
|
|
104
|
+
}
|
|
96
105
|
if (body.capture !== undefined) {
|
|
97
106
|
const capture = body.capture;
|
|
98
107
|
if (!capture || typeof capture !== "object" || Array.isArray(capture) || Object.keys(capture).some(key => !["capMb", "retentionDays"].includes(key))) return fail(label, "capture takes only capMb and retentionDays");
|
|
@@ -155,6 +164,7 @@ export function loadAmemConfig(base: string, repoRoot?: string): LoadedConfig {
|
|
|
155
164
|
if (piiPatterns.length > 64) fail(machinePath, "piiPatterns and the repository's piiPatterns name more than 64 entries together");
|
|
156
165
|
const config: AmemConfig = { denyPaths, piiPatterns, capture: { ...(machine?.capture ?? {}) } };
|
|
157
166
|
if (machine?.home !== undefined) config.home = machine.home;
|
|
167
|
+
if (machine?.privateRemotes?.length) config.privateRemotes = machine.privateRemotes;
|
|
158
168
|
if (machine?.records !== undefined || repo?.records !== undefined) config.records = machine?.records !== false && repo?.records !== false;
|
|
159
169
|
for (const key of ["briefBytes", "excerptBytes", "capturePaths"] as const) { const value = lower(machine?.[key], repo?.[key]); if (value !== undefined) config[key] = value; }
|
|
160
170
|
return { config, source: { machine: machineRaw === undefined ? null : machinePath, repo: repoPath } };
|
|
@@ -69,6 +69,8 @@ export class ShardHistoryAuditor {
|
|
|
69
69
|
readonly #origins = new Map<string, ShardHistoryOrigin>();
|
|
70
70
|
readonly #manifestOrigins = new Map<string, { commit: string; blob: string }>();
|
|
71
71
|
readonly #parents = new Map<string, string[]>();
|
|
72
|
+
/** Root tree of each hash-verified commit: a commit object is immutable, so an audited commit is not re-read (#420). */
|
|
73
|
+
readonly #roots = new Map<string, string>();
|
|
72
74
|
#running = false;
|
|
73
75
|
constructor(options: ShardHistoryAuditorOptions) {
|
|
74
76
|
this.#ref = shardSyncRef(options.realm);
|
|
@@ -217,7 +219,9 @@ export class ShardHistoryAuditor {
|
|
|
217
219
|
for (const line of lines) {
|
|
218
220
|
const [commit, ...parents] = line.split(" ");
|
|
219
221
|
if (!oid(commit) || parents.some(parent => !oid(parent)) || seen.has(commit)) return fail(); seen.add(commit);
|
|
220
|
-
const
|
|
222
|
+
const known = this.#roots.get(commit), verifiedRoot = !this.#options.object ? undefined
|
|
223
|
+
: known !== undefined && canonicalJSON(this.#parents.get(commit)) === canonicalJSON(parents) ? known : await this.#commit(commit, parents);
|
|
224
|
+
if (verifiedRoot !== undefined) this.#roots.set(commit, verifiedRoot);
|
|
221
225
|
if (this.#audited.has(commit)) { if (commit === tip) latest = await this.#tree(commit, verifiedRoot); continue; }
|
|
222
226
|
const current = await this.#tree(commit, verifiedRoot);
|
|
223
227
|
for (const parent of parents) {
|
|
@@ -35,10 +35,30 @@ export function assertPlacementViewAdvance(home: string, activation: SyncPlaceme
|
|
|
35
35
|
if (old !== undefined && !chain.commitments.includes(old)) fail();
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Last verified binding keyed by the lstat stamps of every object the full read checks (#420). A sync calls this several
|
|
40
|
+
* times per fence check; an unchanged stamp is the same identity the full read already accepts between its own reads.
|
|
41
|
+
* ponytail: one entry per process; drop it if a same-size rewrite inside one timestamp tick must be caught across calls.
|
|
42
|
+
*/
|
|
43
|
+
const freeze = <T>(value: T): T => { if (value && typeof value === "object" && !Object.isFrozen(value)) { for (const inner of Object.values(value)) freeze(inner); Object.freeze(value); } return value; };
|
|
44
|
+
let bindingMemo: { key: string; value: Pick<ActivePlacementBinding, "epoch" | "activation"> } | undefined;
|
|
38
45
|
/** No mutation/reader registration/index open. Missing preparation is distinct from malformed retained evidence. */
|
|
39
46
|
export function readActivePlacementBinding(homeInput: string, profileInput: unknown, shardsInput: unknown): ActivePlacementBinding | undefined {
|
|
40
47
|
const profile = validatePlacementProfile(profileInput), shards = validatePlacementShards(shardsInput, profile);
|
|
41
48
|
const home = realPath(homeInput), root = lstatSync(home, { bigint: true }); owned(root, true);
|
|
49
|
+
const stampKey = () => {
|
|
50
|
+
const dir = join(home, "sync-placement", "epochs", profile.placementHead), stamps: string[] = [];
|
|
51
|
+
for (const [file, isDir] of [[home, true], [join(home, "sync-placement"), true], [join(home, "sync-placement", "epochs"), true], [dir, true], [join(dir, "epoch.json"), false],
|
|
52
|
+
[join(dir, "activation.json"), false], [join(home, "sync-placement", "active.json"), false], [join(home, "profile.json"), false], [join(home, "shards.json"), false]] as const) {
|
|
53
|
+
const st = lstatSync(file, { bigint: true, throwIfNoEntry: false }); if (!st) return undefined; owned(st, isDir);
|
|
54
|
+
stamps.push([st.dev, st.ino, st.size, st.mtimeNs, st.ctimeNs].map(String).join(":"));
|
|
55
|
+
}
|
|
56
|
+
return canonicalJSON([home, canonicalJSON(profile), canonicalJSON(shards), stamps]);
|
|
57
|
+
}, memoKey = stampKey();
|
|
58
|
+
if (memoKey !== undefined && bindingMemo?.key === memoKey) {
|
|
59
|
+
assertPlacementViewAdvance(home, bindingMemo.value.activation, profile, shards);
|
|
60
|
+
return { profile, shards, epoch: bindingMemo.value.epoch, activation: bindingMemo.value.activation };
|
|
61
|
+
}
|
|
42
62
|
const checks: (() => void)[] = [() => { const now = lstatSync(home, { bigint: true }); owned(now, true); if (now.dev !== root.dev || now.ino !== root.ino) fail(); }];
|
|
43
63
|
const directory = (dir: string): boolean => {
|
|
44
64
|
const s = lstatSync(dir, { bigint: true, throwIfNoEntry: false }); if (!s) return false; owned(s, true);
|
|
@@ -71,5 +91,6 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
|
|
|
71
91
|
if (read(join(home, "profile.json"))?.text !== canonicalJSON(profile) + "\n" || read(join(home, "shards.json"))?.text !== canonicalJSON(shards) + "\n") fail();
|
|
72
92
|
assertPlacementViewAdvance(home, activation, profile, shards);
|
|
73
93
|
for (const check of checks) check();
|
|
94
|
+
if (memoKey !== undefined && stampKey() === memoKey) bindingMemo = { key: memoKey, value: { epoch: freeze(epoch), activation: freeze(activation) } };
|
|
74
95
|
return { profile, shards, epoch, activation };
|
|
75
96
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Placement sync size contract and its privacy-safe refusal receipt (#419). Numbers only: no row, path or policy text. */
|
|
2
|
+
import { types } from "node:util";
|
|
3
|
+
import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* One source envelope from activation to first sync: home-wide capture, the selected-source prefixes a publication
|
|
7
|
+
* plan binds, and the canonical rows materialization admits (selected sources plus verified incoming rows) share
|
|
8
|
+
* 64 MiB and 20000 rows. Journal limits are separate and unchanged (20000 records and 256 objects per epoch).
|
|
9
|
+
*/
|
|
10
|
+
export const PLACEMENT_SOURCE_MAX_BYTES = 64 * 1024 * 1024, PLACEMENT_SOURCE_MAX_ROWS = 20000;
|
|
11
|
+
|
|
12
|
+
export type PlacementSyncBoundPhase = "source-capture" | "materialization" | "publication-plan";
|
|
13
|
+
const KINDS = ["source-bytes", "source-rows", "journal-records", "journal-objects", "bytes", "rows", "source-files", "metadata-bytes", "row-bytes", "retained-identities"] as const;
|
|
14
|
+
export type PlacementSyncBoundKind = typeof KINDS[number];
|
|
15
|
+
export interface PlacementSyncBound { phase: PlacementSyncBoundPhase; kind: PlacementSyncBoundKind; limit: number; observed: number }
|
|
16
|
+
|
|
17
|
+
const phases: Record<PlacementSyncBoundPhase, string> = { "source-capture": "source capture", materialization: "materialization", "publication-plan": "publication planning" };
|
|
18
|
+
export function placementSyncBoundMessage(bound: PlacementSyncBound): string {
|
|
19
|
+
const remedy = bound.kind === "journal-records" || bound.kind === "journal-objects"
|
|
20
|
+
? "The active epoch journal cannot hold this publication; retain the inputs and report this bound."
|
|
21
|
+
: "Retain the inputs and report this bound; no row was omitted to fit.";
|
|
22
|
+
return `Placement sync refused before any publication attempt: ${phases[bound.phase]} exceeds its supported ${bound.kind} bound (observed ${bound.observed}, limit ${bound.limit}). No source, selector, epoch, journal or remote ref was changed. ${remedy}`;
|
|
23
|
+
}
|
|
24
|
+
/** Expected input refusal before a publication attempt exists. Code stays "bound" for existing callers. */
|
|
25
|
+
export class PlacementSyncBoundError extends SyncPlacementJournalError {
|
|
26
|
+
constructor(readonly bound: PlacementSyncBound) { super("bound"); this.message = placementSyncBoundMessage(bound); this.name = "PlacementSyncBoundError"; }
|
|
27
|
+
}
|
|
28
|
+
/** Only allowlisted own data properties of a journal bound error become a receipt; any other exception yields none. */
|
|
29
|
+
export function placementSyncBoundReceipt(error: unknown): PlacementSyncBound | undefined {
|
|
30
|
+
try {
|
|
31
|
+
if (!error || typeof error !== "object" || types.isProxy(error) || !(error instanceof SyncPlacementJournalError)) return undefined;
|
|
32
|
+
const own = (object: object, key: string): unknown => Object.getOwnPropertyDescriptor(object, key)?.value;
|
|
33
|
+
const raw = own(error, "bound"); if (own(error, "code") !== "bound" || !raw || typeof raw !== "object" || types.isProxy(raw)) return undefined;
|
|
34
|
+
const kind = own(raw, "kind"), limit = own(raw, "limit"), observed = own(raw, "observed"), phase = own(raw, "phase") ?? "source-capture";
|
|
35
|
+
if (typeof kind !== "string" || !(KINDS as readonly string[]).includes(kind) || typeof phase !== "string" || !Object.hasOwn(phases, phase)
|
|
36
|
+
|| typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 0 || typeof observed !== "number" || !Number.isSafeInteger(observed) || observed < 0) return undefined;
|
|
37
|
+
return { phase: phase as PlacementSyncBoundPhase, kind: kind as PlacementSyncBoundKind, limit, observed };
|
|
38
|
+
} catch { return undefined; }
|
|
39
|
+
}
|
|
@@ -23,9 +23,10 @@ import { activationSourceMarkers, assertPlacementActivationOwner, type Placement
|
|
|
23
23
|
import { readEffectiveSyncPlacementWriters, writerBoundPlacementContextHash, writerInventoryEvidence, type EffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
|
|
24
24
|
import { SharedWriterRevisionError } from "./sync-placement-writer-revision-format.ts";
|
|
25
25
|
import { inspectionBoundReceipt, type InspectionBound } from "./inspection-bound.ts";
|
|
26
|
+
import { PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_SOURCE_MAX_ROWS } from "./sync-placement-bound.ts";
|
|
26
27
|
|
|
27
28
|
/** Home-wide source capture ceilings. Every file is read twice (bytes, then a stable recheck), so the read budget is 2x. */
|
|
28
|
-
export const PLACEMENT_CAPTURE_MAX_SOURCE_BYTES =
|
|
29
|
+
export const PLACEMENT_CAPTURE_MAX_SOURCE_BYTES = PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_CAPTURE_MAX_ROWS = PLACEMENT_SOURCE_MAX_ROWS;
|
|
29
30
|
/** Source capture refusal before any effect. Code stays "bound" for existing callers; the message names the phase and bound. */
|
|
30
31
|
export class PlacementSourceBoundError extends SyncPlacementJournalError {
|
|
31
32
|
constructor(readonly bound?: InspectionBound) {
|
|
@@ -6,6 +6,7 @@ import { validatePruneRow } from "./prune.ts";
|
|
|
6
6
|
import { SUGGESTED } from "./store.ts";
|
|
7
7
|
import { placementKeyId, validatePlacementKey, type PlacementKey, type PlacementRealm } from "./sync-placement-journal-format.ts";
|
|
8
8
|
import type { OutboundVerdict, SyncPolicyCategory } from "./sync-screen.ts";
|
|
9
|
+
import { PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_SOURCE_MAX_ROWS } from "./sync-placement-bound.ts";
|
|
9
10
|
|
|
10
11
|
export interface DependencySource {
|
|
11
12
|
key: PlacementKey; row: unknown; sourcePlacement: "local" | "synced"; policy: OutboundVerdict; held: boolean;
|
|
@@ -85,11 +86,12 @@ function preflight(raw: unknown): void {
|
|
|
85
86
|
const source = descriptors(sources.own[String(i)]!.value), row = source.row;
|
|
86
87
|
if (!row || !("value" in row)) return fail();
|
|
87
88
|
bytes += size(row.value, 0) + 1;
|
|
88
|
-
if (bytes >
|
|
89
|
+
if (bytes > PLACEMENT_SOURCE_MAX_BYTES) fail();
|
|
89
90
|
}
|
|
90
91
|
for (const key of ["publicEndpoints", "verifiedPrunes"]) if (fields[key]) arrayFields(fields[key]!.value, 20000);
|
|
91
92
|
}
|
|
92
|
-
/** ponytail: descriptor-only JSON safety stops at
|
|
93
|
+
/** ponytail: descriptor-only JSON safety stops at depth 64, one million nodes and twice the 64 MiB source envelope
|
|
94
|
+
* (selected rows plus already-public endpoint evidence, which never exceeds the rows it backs; #419, 16 MiB before 0.26.3).
|
|
93
95
|
* A reviewed chunked endpoint interface is required before larger proofs can enter this compiler. */
|
|
94
96
|
function copyInput(value: unknown): unknown {
|
|
95
97
|
let bytes = 0, nodes = 0;
|
|
@@ -98,7 +100,7 @@ function copyInput(value: unknown): unknown {
|
|
|
98
100
|
if (++nodes > 1_000_000 || depth > 64) fail();
|
|
99
101
|
if (v === null || typeof v === "boolean") { bytes += 5; return v; }
|
|
100
102
|
if (typeof v === "number") { if (!Number.isFinite(v)) fail(); bytes += 24; return v; }
|
|
101
|
-
if (typeof v === "string") { bytes += Buffer.byteLength(v); if (bytes >
|
|
103
|
+
if (typeof v === "string") { bytes += Buffer.byteLength(v); if (bytes > 2 * PLACEMENT_SOURCE_MAX_BYTES) fail(); return v; }
|
|
102
104
|
if (!v || typeof v !== "object" || types.isProxy(v) || seen.has(v) || Object.getOwnPropertySymbols(v).length) fail();
|
|
103
105
|
const array = Array.isArray(v), proto = Object.getPrototypeOf(v);
|
|
104
106
|
if (array ? proto !== Array.prototype : proto !== Object.prototype && proto !== null) fail();
|
|
@@ -168,7 +170,7 @@ function compile(raw: PlacementDependencyInput): DependencyDecision[] {
|
|
|
168
170
|
const key = validatePlacementKey(item.key), row = object(item.row), id = placementKeyId(key);
|
|
169
171
|
if (!selected.has(realmId(key.realm)) || row.id !== key.id || hashJSON(row) !== key.rowHash) fail();
|
|
170
172
|
if (hashes.has(key.id) && hashes.get(key.id) !== key.rowHash) fail(); hashes.set(key.id, key.rowHash);
|
|
171
|
-
if (output && (sourceBytes += Buffer.byteLength(canonicalJSON(row) + "\n")) >
|
|
173
|
+
if (output && (sourceBytes += Buffer.byteLength(canonicalJSON(row) + "\n")) > PLACEMENT_SOURCE_MAX_BYTES + PLACEMENT_SOURCE_MAX_ROWS) fail();
|
|
172
174
|
let policy: OutboundVerdict = { ok: true };
|
|
173
175
|
if (output) {
|
|
174
176
|
const verdict = object(item.policy); keys(verdict, ["ok"], ["category"]);
|
|
@@ -119,15 +119,36 @@ function intent(value: unknown, epochHash: string): Intent {
|
|
|
119
119
|
|| input.lineHash !== digest(line(record)) || input.prefixBytes + line(record).length > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) return fail();
|
|
120
120
|
return { schema: input.schema, epochHash, record, chunk: input.chunk, prefixBytes: input.prefixBytes, prefixHash: input.prefixHash, lineHash: input.lineHash };
|
|
121
121
|
}
|
|
122
|
+
const stamp = (stat: BigIntStats) => [String(stat.dev), String(stat.ino), String(stat.size), String(stat.mtimeNs), String(stat.ctimeNs)].join(":");
|
|
123
|
+
const freeze = <T>(value: T): T => { if (value && typeof value === "object" && !Object.isFrozen(value)) { for (const inner of Object.values(value)) freeze(inner); Object.freeze(value); } return value; };
|
|
124
|
+
/**
|
|
125
|
+
* Decoded journal prefix (every chunk but the last) keyed by directory and the stat stamps of epoch.json and those chunks (#420).
|
|
126
|
+
* Appends only grow the last chunk or add a new one, so a sync re-decodes at most one 64 KiB chunk per snapshot instead of
|
|
127
|
+
* the whole journal. A changed stamp is a miss and the chunk is read and decoded again; the end-of-snapshot token check still runs.
|
|
128
|
+
* ponytail: one entry per process and stat stamps as identity (the same trust the token check already gives an unchanged file);
|
|
129
|
+
* keep a content digest per chunk if an in-place same-size rewrite inside one timestamp tick must be caught.
|
|
130
|
+
*/
|
|
131
|
+
let journalPrefix: { key: string; count: number; records: PlacementRecord[]; chunks: Chunk[]; projection: PlacementProjection } | undefined;
|
|
132
|
+
/** Decoded last chunk, matched by its bytes: a grown last chunk decodes only the appended suffix (#420). */
|
|
133
|
+
let journalTail: { key: string; name: string; bytes: Buffer; records: PlacementRecord[]; projection: PlacementProjection } | undefined;
|
|
134
|
+
/** Whole snapshot for an unchanged inventory token (every file snapshot reads is in it). Callers get fresh arrays and a projection clone. */
|
|
135
|
+
let journalSnapshot: { token: string; value: Snapshot } | undefined;
|
|
136
|
+
/** Drop every decoded journal/publication memo; a sync calls this when it ends so a resident host never keeps a journal's records. */
|
|
137
|
+
export function releasePlacementStorageCaches(): void { journalPrefix = undefined; journalTail = undefined; journalSnapshot = undefined; publicationBundle = undefined; reservationRoot = undefined; }
|
|
138
|
+
// Records are frozen and shared (the bulk); every small mutable field is a fresh copy, so a caller's mutation never reaches the memo.
|
|
139
|
+
const detachSnapshot = (value: Snapshot): Snapshot => ({ ...value, records: value.records.map(freeze), chunks: value.chunks.map(chunk => ({ ...chunk })), projection: value.projection.clone(),
|
|
140
|
+
epoch: structuredClone(value.epoch), activation: structuredClone(value.activation),
|
|
141
|
+
...(value.intent ? { intent: structuredClone(value.intent) } : {}), ...(value.pendingRecord ? { pendingRecord: structuredClone(value.pendingRecord) } : {}) });
|
|
122
142
|
function snapshot(p: Paths): Snapshot {
|
|
123
143
|
const before = inventory(p);
|
|
144
|
+
if (journalSnapshot?.token === canonicalJSON([p.dir, before.token])) return detachSnapshot(journalSnapshot.value);
|
|
124
145
|
const epoch = decode(readOwned(join(p.dir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
|
|
125
146
|
if (placementEpochHash(epoch) !== p.hash) return fail("conflict");
|
|
126
147
|
const plan = decode(readOwned(join(p.dir, "activation.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), value => activation(epoch, p.hash, value));
|
|
127
148
|
const pendingBytes = readOwned(join(p.dir, "append-intent.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
|
|
128
149
|
const intentPending = pendingBytes !== undefined && (!pendingBytes.length || pendingBytes.at(-1) !== 10);
|
|
129
150
|
const pending = pendingBytes && !intentPending ? decode(pendingBytes, value => intent(value, p.hash)) : undefined;
|
|
130
|
-
|
|
151
|
+
let projection = new PlacementProjection(epoch); const records: PlacementRecord[] = [], chunks: Chunk[] = [];
|
|
131
152
|
const apply = (bytes: Buffer) => {
|
|
132
153
|
let start = 0;
|
|
133
154
|
while (start < bytes.length) {
|
|
@@ -137,7 +158,13 @@ function snapshot(p: Paths): Snapshot {
|
|
|
137
158
|
}
|
|
138
159
|
};
|
|
139
160
|
const chunkNames = [...before.files.keys()].filter(name => /^records-\d{5}\.jsonl$/.test(name));
|
|
161
|
+
const prefixKey = (count: number) => canonicalJSON([p.dir, stamp(before.files.get("epoch.json")!), chunkNames.slice(0, count).map(name => [name, stamp(before.files.get(name)!)])]);
|
|
162
|
+
const cached = journalPrefix && journalPrefix.count < chunkNames.length && journalPrefix.key === prefixKey(journalPrefix.count) ? journalPrefix : undefined;
|
|
163
|
+
let prefix: typeof journalPrefix, tail: typeof journalTail;
|
|
164
|
+
if (cached) { projection = cached.projection.clone(); records.push(...cached.records); chunks.push(...cached.chunks); }
|
|
140
165
|
for (const [index, name] of chunkNames.entries()) {
|
|
166
|
+
if (index < (cached?.count ?? 0)) continue;
|
|
167
|
+
if (index > 0 && index === chunkNames.length - 1) prefix = { key: prefixKey(index), count: index, records: records.map(freeze), chunks: [...chunks], projection: projection.clone() };
|
|
141
168
|
if (name !== `records-${String(index).padStart(5, "0")}.jsonl`) fail();
|
|
142
169
|
const bytes = readOwned(join(p.dir, name), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES)!;
|
|
143
170
|
chunks.push({ name, size: bytes.length, hash: digest(bytes) });
|
|
@@ -148,7 +175,14 @@ function snapshot(p: Paths): Snapshot {
|
|
|
148
175
|
const suffix = bytes.subarray(pending.prefixBytes), expected = line(pending.record);
|
|
149
176
|
if (suffix.length > expected.length || !expected.subarray(0, suffix.length).equals(suffix)) fail();
|
|
150
177
|
if (suffix.length === expected.length) apply(suffix);
|
|
151
|
-
} else {
|
|
178
|
+
} else {
|
|
179
|
+
if (!bytes.length) fail();
|
|
180
|
+
const last = index === chunkNames.length - 1, known = last ? journalTail : undefined;
|
|
181
|
+
if (known && known.key === prefixKey(index) && known.name === name && bytes.length >= known.bytes.length && bytes.subarray(0, known.bytes.length).equals(known.bytes)) {
|
|
182
|
+
projection = known.projection.clone(); records.length = 0; records.push(...known.records); apply(bytes.subarray(known.bytes.length));
|
|
183
|
+
} else apply(bytes);
|
|
184
|
+
if (last) tail = { key: prefixKey(index), name, bytes: Buffer.from(bytes), records: records.map(freeze), projection: projection.clone() };
|
|
185
|
+
}
|
|
152
186
|
}
|
|
153
187
|
if (pending) {
|
|
154
188
|
const found = chunkNames.includes(pending.chunk);
|
|
@@ -167,7 +201,11 @@ function snapshot(p: Paths): Snapshot {
|
|
|
167
201
|
if ((records.length > 0 || pendingBytes !== undefined) && (!activeFence || fencePending || activeFence.epochHash !== p.hash
|
|
168
202
|
|| activeFence.homeHash !== epoch.homeHash || activeFence.generation !== epoch.generation)) fail();
|
|
169
203
|
if (inventory(p).token !== before.token) fail("changed");
|
|
170
|
-
|
|
204
|
+
if (prefix) journalPrefix = prefix;
|
|
205
|
+
if (tail) journalTail = tail;
|
|
206
|
+
const result: Snapshot = { epoch, activation: plan, records, projection, headHash: projection.headHash, sequence: projection.sequence, objects: before.files.size + 1 + before.renewalObjects, pending: !!pending || intentPending || fencePending, chunks, intentPending, fencePending, ...(pending ? { pendingRecordSequence: pending.record.sequence, pendingRecord: validatePlacementRecord(pending.record) } : {}), ...(pending ? { intent: pending } : {}) };
|
|
207
|
+
journalSnapshot = { token: canonicalJSON([p.dir, before.token]), value: detachSnapshot(result) };
|
|
208
|
+
return result;
|
|
171
209
|
}
|
|
172
210
|
export function readPlacementJournal(home: string, epochHash: string): PlacementJournalRead {
|
|
173
211
|
return protectedIO(() => {
|
|
@@ -349,14 +387,23 @@ export interface PlacementPublicationStored {
|
|
|
349
387
|
bundle: PlacementPublicationBundle; phase: "prepared" | "artifact-built" | "publication-intent" | "completed";
|
|
350
388
|
facts: PlacementPublicationFact[]; pending: boolean; pendingPhase?: PlacementPublicationFact["phase"];
|
|
351
389
|
}
|
|
390
|
+
/** Validated plan bundle keyed by the stat stamps of epoch.json, the root and every plan chunk (#420); same ceiling as journalPrefix. */
|
|
391
|
+
let publicationBundle: { key: string; bundle: PlacementPublicationBundle } | undefined;
|
|
352
392
|
function publicationRead(p: Paths, attemptHash: string): PlacementPublicationStored {
|
|
353
|
-
const stem = `publication-${attemptHash}-`,
|
|
354
|
-
const
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
393
|
+
const stem = `publication-${attemptHash}-`, files = inventory(p).files;
|
|
394
|
+
const keyOf = (found: Map<string, BigIntStats>) => canonicalJSON([p.dir, attemptHash, [...found].filter(([name]) => name === "epoch.json" || name === stem + "root.json" || name.startsWith(stem + "chunk-")).map(([name, stat]) => [name, stamp(stat)])]);
|
|
395
|
+
const key = keyOf(files);
|
|
396
|
+
let bundle = publicationBundle?.key === key ? publicationBundle.bundle : undefined;
|
|
397
|
+
if (!bundle) {
|
|
398
|
+
const root = decode(readOwned(join(p.dir, stem + "root.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementPublicationRoot);
|
|
399
|
+
const epoch = decode(readOwned(join(p.dir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
|
|
400
|
+
if (root.seal !== attemptHash || root.epochHash !== p.hash || root.generation !== epoch.generation || root.homeHash !== epoch.homeHash) fail("corrupt");
|
|
401
|
+
const chunks = root.chunks.map(c => decode(readOwned(join(p.dir, `${stem}chunk-${String(c.index).padStart(5, "0")}.json`), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES), value => value));
|
|
402
|
+
bundle = freeze(validatePlacementPublicationBundle({ root, chunks }));
|
|
403
|
+
if (keyOf(inventory(p).files) === key) publicationBundle = { key, bundle }; // Never cache bytes read across a concurrent change.
|
|
404
|
+
}
|
|
405
|
+
const root = bundle.root, allowed = new Set(publicationFileNames(root));
|
|
406
|
+
for (const name of files.keys()) if (name.startsWith(stem) && !allowed.has(name)) fail("corrupt");
|
|
360
407
|
const facts: PlacementPublicationFact[] = []; let phase: PlacementPublicationStored["phase"] = "prepared", pending = false, absent = false; let pendingPhase: PlacementPublicationFact["phase"] | undefined;
|
|
361
408
|
for (const [index, suffix] of ["artifact", "intent", "receipt"].entries()) {
|
|
362
409
|
const bytes = readOwned(join(p.dir, stem + suffix + ".json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
|
|
@@ -409,12 +456,20 @@ function reservedPublicationJournalNames(p: Paths): string[] {
|
|
|
409
456
|
for (const root of complete) names.push(...placementPublicationReservedJournalNames(root, read, sizes));
|
|
410
457
|
return names;
|
|
411
458
|
}
|
|
459
|
+
/** A complete (newline-terminated) root is immutable: keep the last decoded one by its stat stamp (#420), same ceiling as journalPrefix. */
|
|
460
|
+
let reservationRoot: { key: string; root: PlacementPublicationRoot } | undefined;
|
|
412
461
|
function publicationRootsForReservation(p: Paths): PlacementPublicationRoot[] {
|
|
413
|
-
const roots: PlacementPublicationRoot[] = [];
|
|
414
|
-
for (const name of
|
|
415
|
-
const
|
|
416
|
-
|
|
417
|
-
|
|
462
|
+
const roots: PlacementPublicationRoot[] = [], files = inventory(p).files;
|
|
463
|
+
for (const [name, stat] of files) if (/^publication-[a-f0-9]{64}-root\.json$/.test(name)) {
|
|
464
|
+
const key = canonicalJSON([p.dir, name, stamp(stat)]);
|
|
465
|
+
let root = reservationRoot?.key === key ? reservationRoot.root : undefined;
|
|
466
|
+
if (!root) {
|
|
467
|
+
const bytes = readOwned(join(p.dir, name), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
|
|
468
|
+
if (!bytes?.length || bytes.at(-1) !== 10) continue;
|
|
469
|
+
root = freeze(decode(bytes, validatePlacementPublicationRoot));
|
|
470
|
+
const now = state(join(p.dir, name)); if (now && stamp(now) === stamp(stat)) reservationRoot = { key, root };
|
|
471
|
+
}
|
|
472
|
+
const receiptBytes = readOwned(join(p.dir, `publication-${root.seal}-receipt.json`), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
|
|
418
473
|
if (receiptBytes?.length && receiptBytes.at(-1) === 10) {
|
|
419
474
|
const read = publicationRead(p, root.seal); if (read.phase === "completed" && !read.pending) continue;
|
|
420
475
|
}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
/** Shared internal row materialization. All source/transport authority and effect boundaries belong to the caller. */
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
3
|
import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
4
|
-
import {
|
|
4
|
+
import type { OutboundVerdict } from "./sync-screen.ts";
|
|
5
|
+
import { PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_SOURCE_MAX_ROWS, PlacementSyncBoundError } from "./sync-placement-bound.ts";
|
|
5
6
|
import type { PlacementCapture } from "./sync-placement-capture.ts";
|
|
6
7
|
import { compilePlacementDependencies, type DependencySource, type VerifiedDependencyEndpoint } from "./sync-placement-dependencies.ts";
|
|
7
8
|
import { compilePlacementGitObjects, type PlannedGitObject } from "./sync-placement-git.ts";
|
|
8
9
|
import { PLACEMENT_DESCRIPTOR_SCHEMA, PLACEMENT_FORMAT } from "./sync-placement-format.ts";
|
|
9
|
-
import { placementKeyId,
|
|
10
|
+
import { placementKeyId, type PlacementKey, type PlacementRealm } from "./sync-placement-journal-format.ts";
|
|
10
11
|
import type { PlacementProjection } from "./sync-placement-projection.ts";
|
|
11
12
|
import type { PlacementPublicationBundle, PlacementPublicationDecision, PlacementPublicationObject, PlacementPublicationTarget } from "./sync-placement-publication-plan.ts";
|
|
12
13
|
import type { ShardHistory } from "./shard-sync-history.ts";
|
|
@@ -26,6 +27,8 @@ export interface PlacementMaterializeInput {
|
|
|
26
27
|
readTree(index: number, head: string): Promise<string>;
|
|
27
28
|
publisherLineages(index: number, rows: readonly PruneRow[]): ReadonlyMap<string, PublicPruneLineage>;
|
|
28
29
|
createdUnixSeconds: number; frozen?: PlacementPublicationBundle;
|
|
30
|
+
/** Advisory telemetry only (#418): phase names and unit counts, never a row, key or verdict detail. */
|
|
31
|
+
progress?: { phase(name: "policy-evaluation" | "dependency-decisions" | "artifact-construction", unit?: "rows", total?: number): void; advance(): void };
|
|
29
32
|
}
|
|
30
33
|
export interface PlacementMaterializeTargetResult { candidate: ShardHistory; objects: PlannedGitObject[]; commit?: string }
|
|
31
34
|
export interface PlacementMaterializeResult {
|
|
@@ -54,26 +57,33 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
|
|
|
54
57
|
const {capture,projection,old,frozen,createdUnixSeconds}=input;
|
|
55
58
|
const workTargets = input.targets.map(target => ({...target,objects:[] as PlannedGitObject[],commit:undefined as string|undefined,candidate:undefined as ShardHistory|undefined}));
|
|
56
59
|
const sources: DependencySource[] = [], blocked = new Set<string>(), verified = input.verifiedPrunes;
|
|
57
|
-
|
|
58
|
-
|
|
60
|
+
// Collect every selected original first: size admission below is pure and precedes the first policy evaluation
|
|
61
|
+
// (and its writer proofs), so an unsupported source set refuses before any expensive per-row work (#419).
|
|
62
|
+
const admitted: Omit<DependencySource, "policy">[] = [], seenSources = new Set<string>();
|
|
59
63
|
const prunedByTarget = new Map(workTargets.map(target => [target, target.pruned]));
|
|
60
64
|
for (const source of capture.rows.values()) {
|
|
61
65
|
const target = workTargets.find(target => sameRealm(physical(target), source.key.realm)); if (!target) refuse();
|
|
62
66
|
const pruned = prunedByTarget.get(target)!.has(source.key.id) && !target.fetched.has(source.key.id);
|
|
63
67
|
if (pruned) blocked.add(placementKeyId(source.key));
|
|
64
|
-
|
|
68
|
+
seenSources.add(placementKeyId(source.key)); admitted.push({ key: source.key, row: source.row, sourcePlacement: source.sourcePlacement, held: !!projection.get(source.key)?.held || !!pruned });
|
|
65
69
|
}
|
|
66
70
|
for (const target of workTargets) for (const row of target.localPrunes.values()) {
|
|
67
|
-
const key = keyFor(target,row)
|
|
68
|
-
|
|
71
|
+
const key = keyFor(target,row), id = placementKeyId(key); if (seenSources.has(id)) continue;
|
|
72
|
+
seenSources.add(id); admitted.push({ key, row, sourcePlacement: "synced", held: !!projection.get(key)?.held });
|
|
69
73
|
}
|
|
70
74
|
// Incoming verified occurrences are selected immutable originals too. Classify them before import so a private
|
|
71
75
|
// remote goal cannot temporarily authorize a new dependent, and exposure/holds are durable in this same attempt.
|
|
72
|
-
const seenSources=new Set(sources.map(source=>placementKeyId(source.key)));
|
|
73
76
|
for(const [index,target]of workTargets.entries())for(const row of old[index]?.rows.values()??[])if(row.op!=="prune"||row.generation===target.generation){
|
|
74
77
|
const key=keyFor(target,row),id=placementKeyId(key);if(seenSources.has(id))continue;seenSources.add(id);
|
|
75
|
-
|
|
78
|
+
admitted.push({key,row,sourcePlacement:"synced",held:!!projection.get(key)?.held});
|
|
76
79
|
}
|
|
80
|
+
// Source size, not outbound size: local and declined rows count too, because their decisions are bound in the plan.
|
|
81
|
+
if (admitted.length > PLACEMENT_SOURCE_MAX_ROWS) throw new PlacementSyncBoundError({ phase: "materialization", kind: "source-rows", limit: PLACEMENT_SOURCE_MAX_ROWS, observed: admitted.length });
|
|
82
|
+
let sourceBytes = 0; for (const source of admitted) sourceBytes += Buffer.byteLength(canonicalJSON(source.row));
|
|
83
|
+
if (sourceBytes > PLACEMENT_SOURCE_MAX_BYTES) throw new PlacementSyncBoundError({ phase: "materialization", kind: "source-bytes", limit: PLACEMENT_SOURCE_MAX_BYTES, observed: sourceBytes });
|
|
84
|
+
input.progress?.phase("policy-evaluation", "rows", admitted.length);
|
|
85
|
+
for (const source of admitted) { sources.push({ ...source, policy: input.evaluate(source.row) }); input.progress?.advance(); }
|
|
86
|
+
input.progress?.phase("dependency-decisions");
|
|
77
87
|
// Strong endpoints are already in sources and current holds cannot be bypassed by past publication. Only
|
|
78
88
|
// deletion/prune exceptions need a second verified occurrence fact; do not duplicate every historical body.
|
|
79
89
|
const publicNeeded=new Set<string>();
|
|
@@ -126,6 +136,7 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
|
|
|
126
136
|
}
|
|
127
137
|
}
|
|
128
138
|
target.objects=[];
|
|
139
|
+
if(pass===0&&index===0)input.progress?.phase("artifact-construction");
|
|
129
140
|
if(publish){
|
|
130
141
|
const previous=old[index]&&target.remote?{tree:await input.readTree(index,frozen?.root.targets[index]?.expectedRemoteHead??target.remote!),commit:frozen?.root.targets[index]?.expectedRemoteHead??target.remote!}:undefined;
|
|
131
142
|
const objects=compilePlacementGitObjects(files,frozen?.root.targets[index]?.expectedRemoteHead??target.remote??null,createdUnixSeconds,previous);target.objects=objects.objects;target.commit=objects.commit;
|
|
@@ -17,12 +17,21 @@ const identity = (key: PlacementKey) => canonicalJSON([key.realm, key.id]);
|
|
|
17
17
|
/** Data projection only. Journal fields and committed-outcome syntax are not person or remote-proof credentials. */
|
|
18
18
|
export class PlacementProjection {
|
|
19
19
|
readonly #epochHash: string;
|
|
20
|
+
readonly #epoch: PlacementEpoch;
|
|
20
21
|
#sequence = 0;
|
|
21
22
|
#headHash: string;
|
|
22
23
|
readonly #states = new Map<string, PlacementProjectedState>();
|
|
23
24
|
readonly #rowHashes = new Map<string, string>();
|
|
24
25
|
readonly #requests = new Map<string, PlacementRecord>();
|
|
25
|
-
constructor(epoch: PlacementEpoch) { this.#epochHash = placementEpochHash(
|
|
26
|
+
constructor(epoch: PlacementEpoch) { this.#epoch = validatePlacementEpoch(epoch); this.#epochHash = placementEpochHash(this.#epoch); this.#headHash = this.#epochHash; }
|
|
27
|
+
/** Independent copy: stored states and records are never mutated in place (apply copies, readers get copies), so sharing them is safe. */
|
|
28
|
+
clone(): PlacementProjection {
|
|
29
|
+
const out = new PlacementProjection(this.#epoch); out.#sequence = this.#sequence; out.#headHash = this.#headHash;
|
|
30
|
+
for (const [key, value] of this.#states) out.#states.set(key, value);
|
|
31
|
+
for (const [key, value] of this.#rowHashes) out.#rowHashes.set(key, value);
|
|
32
|
+
for (const [key, value] of this.#requests) out.#requests.set(key, value);
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
26
35
|
get epochHash(): string { return this.#epochHash; }
|
|
27
36
|
get sequence(): number { return this.#sequence; }
|
|
28
37
|
get headHash(): string { return this.#headHash; }
|