@staix/agent-mem 0.35.0 → 0.37.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-mem",
3
- "version": "0.35.0",
3
+ "version": "0.37.0",
4
4
  "description": "Bounded project memory tools and seven deterministic capture hooks, without a resident worker.",
5
5
  "mcpServers": {
6
6
  "agent-mem": {
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.35.0. Requires Bun 1.4.2 or later; no runtime dependencies.
6
+ Version: 0.37.0. Requires Bun 1.4.2 or later; runtime dependencies: @staix/cli-output.
7
7
  <!-- /facts:version -->
8
8
 
9
9
  ## Quick start
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.35.0",
3
+ "version": "0.37.0",
4
4
  "description": "Curated, shared memory for coding agents: append-only logs, a derived index, tiers and a typed graph.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -11,6 +11,9 @@
11
11
  "engines": {
12
12
  "bun": ">=1.4.2"
13
13
  },
14
+ "dependencies": {
15
+ "@staix/cli-output": "0.1.3"
16
+ },
14
17
  "devDependencies": {
15
18
  "@staix/agent-console": "0.1.3",
16
19
  "@types/bun": "^1.3.0",
package/src/cli.ts CHANGED
@@ -69,7 +69,8 @@ import { buildNote, FAIL_TEMPLATE, hasFailLabel, noteAdd, parseFailTemplate, typ
69
69
  import { runEditor } from "./memory/editor.ts";
70
70
  import { doctorReport, doctorText } from "./memory/doctor.ts";
71
71
  import { statusText, type StatusView } from "./memory/status-text.ts";
72
- import { asciiMarkers, markerCell, paint, resolveColor, streamEnv, style, wrapReport, facts, label, PLAIN, type Style } from "./memory/style.ts";
72
+ import { asciiMarkers, errorLine, errorSpans, EXIT, markerCell, paint, resolveColor, streamEnv } from "@staix/cli-output";
73
+ import { style, wrapReport, facts, label, PLAIN, type Style } from "./memory/style.ts";
73
74
  import { endLikeSignal, nextSyncAt, readSyncState, recordSyncAttempt, remoteConfigured, syncDue, stopSignal, syncOutcome, usableState, SYNC_IF_DUE_DEADLINE_MS, type StopCause } from "./memory/sync-cadence.ts";
74
75
 
75
76
  const VERSION = (JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string }).version;
@@ -378,6 +379,8 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
378
379
  if (marked && error instanceof Error && error.message === AUDIT_SCORE_REFUSED) throw new Error(AUDIT_SCORE_REFUSED);
379
380
  // #288 step 3: checkpoint refusals are fixed cause-and-next-step strings with numbers only (no path, row or project).
380
381
  if (marked && error instanceof Error && error.name === "PlacementCheckpointError" && error instanceof (await import("./memory/sync-placement-checkpoint-person.ts")).PlacementCheckpointError) throw new Error(error.message);
382
+ // #578 Q3: a placement fence refusal is a fixed cause class and next step (no path, pid, row or project).
383
+ if (marked && error instanceof Error && error.name === "PlacementInventoryFenceError" && error instanceof (await import("./memory/sync-placement-activation-locks.ts")).PlacementInventoryFenceError) throw new Error(error.message);
381
384
  const recovery=marked?safeProfileLockMessage(error):undefined;if(recovery)throw new Error(recovery);
382
385
  // #520/#551: a placement refusal keeps its fixed data - the receipt case its target and remedy, every other case its
383
386
  // category, cause class and remedy - so a marked session prints that instead of the masked line. Every other placement
@@ -485,7 +488,10 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
485
488
  throw new AgentUsageError("Remote realm listing uses only --sync-placement --list-remote and optional --json.");
486
489
  if (options["--from-remote"] === true && options["--admit"] === undefined)
487
490
  throw new AgentUsageError("--from-remote requires --sync-placement --admit <project>.");
488
- if (options["--checkpoint"] === true) {
491
+ if (options["--checkpoint-on-bound"] !== undefined) {
492
+ if (modes.length || ["--checkpoint","--admit","--list-remote","--from-remote","--writer-root","--plan"].some(key=>options[key]!==undefined) || !["on","off"].includes(String(options["--checkpoint-on-bound"])))
493
+ throw new AgentUsageError("The sync-run checkpoint opt-in uses only --sync-placement --checkpoint-on-bound on|off, previewing by default and writing with --confirm.");
494
+ } else if (options["--checkpoint"] === true) {
489
495
  // #288 step 3: preview (default), --confirm --plan, --resume or --abandon; one mode at a time.
490
496
  const chosen = [options["--confirm"] === true, options["--resume"] === true, options["--abandon"] === true].filter(Boolean).length;
491
497
  if (options["--admit"] !== undefined || options["--list-remote"] === true || options["--from-remote"] === true || options["--apply"] === true || options["--dry-run"] === true || chosen > 1 || (options["--confirm"] === true) !== (options["--plan"] !== undefined)
@@ -618,6 +624,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
618
624
  const nextStep = "amem migrate --sync-placement --admit <project> --from-remote --dry-run";
619
625
  return options["--json"] === true ? JSON.stringify({ realms, nextStep }, null, 2) : `${realms.map(realm => `scope=${realm.scope} keyHash=${realm.keyHash}; next ${nextStep}`).join("\n") || "no remote-only placement realms"}`;
620
626
  }
627
+ if (options["--checkpoint-on-bound"] !== undefined) {
628
+ const { checkpointOnBoundOptInChange } = await import("./memory/sync-placement-opt-in.ts");
629
+ const r = checkpointOnBoundOptInChange(memoryHome(), options["--checkpoint-on-bound"] === "on", options["--confirm"] === true);
630
+ return options["--json"] === true ? JSON.stringify(r, null, 2) : r.text;
631
+ }
621
632
  if (options["--checkpoint"] === true) {
622
633
  const person = await import("./memory/sync-placement-checkpoint-person.ts");
623
634
  const writerRoots = repeated(argv, "--writer-root"), ownRoot = fileURLToPath(new URL("..", import.meta.url));
@@ -1470,7 +1481,8 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1470
1481
  if (!readActivePlacementBinding(syncHome, markers.profile, markers.shards)) throw Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
1471
1482
  }
1472
1483
  output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person: true, rankedSearch: !legacySearch, ...(identity.actor === "agent" ? { screenGraph: true } : {}), ...(explainSearch ? { explainSearch: true } : {}), project: boundProject(), open: sub === "sync" && placementWriters ? () => openShardStore({ memoryDir: syncHome, user: true, deferPromotions: true }) : 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),
1473
- 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
1484
+ // #578 Q2: the CLI sync (also --if-due) is eligible; the home opt-in still decides whether a checkpoint can run.
1485
+ sync: { ...(placementWriters ? { placementAttestation:placementWriters.attest, placementCheckpoint: true } : {}), ...(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
1474
1486
  onBridgeStatus: status => { receipt.bridgeStatus = status; },
1475
1487
  // #188: ids-only listing of nearby machine-local rows; policy-refused rows are neither listed nor counted.
1476
1488
  forgetNearby: note => forgetNearby({ base: memoryHome(), project: note.project, text: note.text, title: note.title, screen: value => configured.screenStandalone(value) }) }));
@@ -1525,7 +1537,7 @@ async function placementProgress(home: string, mode: string, context: CliContext
1525
1537
  return new SyncProgress({ sink: snapshot => { for (const index of live) try { parts[index]!(snapshot); } catch { live.delete(index); } } });
1526
1538
  }
1527
1539
  function outputStyle(context: CliContext, options: Record<string, string | boolean>): Style {
1528
- const color = resolveColor(typeof options["--color"] === "string" ? options["--color"] : undefined, streamEnv((context.stdoutTTY ?? process.stdout.isTTY) === true, context.env ?? process.env));
1540
+ const color = resolveColor(typeof options["--color"] === "string" ? options["--color"] : undefined, streamEnv((context.stdoutTTY ?? process.stdout.isTTY) === true, context.env ?? process.env), "amem");
1529
1541
  if (color instanceof Error) throw color;
1530
1542
  return style(options["--json"] !== true && color, asciiMarkers(context.env ?? process.env, options["--ascii"] === true));
1531
1543
  }
@@ -1562,7 +1574,7 @@ export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = P
1562
1574
 
1563
1575
  export function formatCliError(error: unknown, usage = false): string {
1564
1576
  if (error instanceof DecayApplyError || error instanceof CliPartialApplyError) return error.render();
1565
- const message = `amem: ${(error as Error).message}`;
1577
+ const message = errorLine("amem", String((error as Error).message), "", { tty: false })[0]!;
1566
1578
  return usage || (error as { exitCode?: number }).exitCode === 2 ? `${message}\nUsage: amem <command> [options]\nRun 'amem --help' for details.` : message;
1567
1579
  }
1568
1580
 
@@ -1578,11 +1590,13 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
1578
1590
  if (process.stderr.isTTY) {
1579
1591
  let options: Record<string, string | boolean> = {};
1580
1592
  try { options = parseCommand(argv).options; } catch { /* Invalid options still report their usage error. */ }
1581
- const color = resolveColor(typeof options["--color"] === "string" ? options["--color"] : undefined, streamEnv(true, process.env));
1593
+ const color = resolveColor(typeof options["--color"] === "string" ? options["--color"] : undefined, streamEnv(true, process.env), "amem");
1582
1594
  const ascii = asciiMarkers(process.env, options["--ascii"] === true);
1583
- prefix = `${paint("error", markerCell("fail", ascii), !argv.includes("--json") && color === true)} `;
1595
+ // ponytail: amem keeps the two-cell marker column; upgrade when errorSpans exposes that padding.
1596
+ const marker = errorSpans("amem", "", "", { tty: true, ascii })[0]![0]!;
1597
+ prefix = `${paint([{ ...marker, text: markerCell("fail", ascii) }], !argv.includes("--json") && color === true)} `;
1584
1598
  }
1585
- const code = (error as { exitCode?: number }).exitCode ?? ((error as Error).message.startsWith("usage:") ? 2 : 1);
1599
+ const code = (error as { exitCode?: number }).exitCode ?? ((error as Error).message.startsWith("usage:") ? EXIT.usage : EXIT.fail);
1586
1600
  console.error(prefix + formatCliError(error, code === 2)); process.exitCode = code;
1587
1601
  }
1588
1602
  if (personStop !== undefined) endLikeSignal(personStop); // after the report, with amem's own handlers already removed
@@ -137,6 +137,7 @@ export const COMMANDS: Record<string, CommandDefinition> = {
137
137
  "--from-remote": flag("Admit the named remote-only realm using the configured placement sync remote"),
138
138
  "--confirm": flag("Confirm the previewed realm admission abandonment"),
139
139
  "--checkpoint": flag("Person-reviewed placement checkpoint: preview by default, then --confirm --plan, --resume or --abandon"),
140
+ "--checkpoint-on-bound": { description: "Preview turning the home opt-in for a sync-run placement checkpoint on or off; --confirm writes it to amem.config.json", value: ["on", "off"] },
140
141
  "--plan": { description: "Saved --checkpoint --json preview to confirm", value: "path" },
141
142
  "--writer-root": { description: "Repeatable absolute amem install root in the complete local writer inventory", value: "path" },
142
143
  } },
@@ -231,12 +231,14 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
231
231
  const placement = r.placementPublication, placementText = placement ? `; placement ${placement.outcome}, ${placement.exported} exported, ${placement.withheld} withheld this attempt` : "";
232
232
  // #450: one line per activated realm (`user` or a key hash; never a project name).
233
233
  const realmLines = r.placementRealms?.length ? `\n${r.placementRealms.map(item => `realm ${item.realm === "user" ? "user" : item.realm.slice(0, 16)}: ${item.outcome}${item.publication ? ` (publication ${item.publication})` : ""}`).join("\n")}` : "";
234
- if (!r.ok) fail(`${names.memory} sync: ${r.error}${realmLines}`);
234
+ // #578 Q2: one counts-only line when this sync ran a placement checkpoint.
235
+ const checkpointLine = r.checkpoint ? `\nplacement checkpoint: window ${r.checkpoint.window}, objects ${r.checkpoint.objectsBefore} -> ${r.checkpoint.objectsAfter}` : "";
236
+ if (!r.ok) fail(`${names.memory} sync: ${r.error}${checkpointLine}${realmLines}`);
235
237
  if (r.pruneApplication) {
236
238
  const a = r.pruneApplication;
237
239
  return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries transported; ${a.proofComplete} prune proofs complete, ${a.projectionActive ?? "pending"} foreign projections active, ${a.nativeApplied ?? "pending"} native prunes applied, ${a.held} held${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}${realmLines}`;
238
240
  }
239
- return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries visible here${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}${realmLines}`;
241
+ return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries visible here${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}${checkpointLine}${realmLines}`;
240
242
  }
241
243
  case "dedupe": {
242
244
  const apply = rest.includes("--apply");
@@ -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", "privateRemotes", "review"] as const;
20
+ const MACHINE_KEYS = ["home", "denyPaths", "piiPatterns", "briefBytes", "excerptBytes", "capturePaths", "capture", "records", "privateRemotes", "review", "syncPlacement"] as const;
21
21
  const REPO_KEYS = ["denyPaths", "piiPatterns", "briefBytes", "excerptBytes", "capturePaths", "records"] as const;
22
22
 
23
23
  export interface AmemConfig {
@@ -38,6 +38,8 @@ export interface AmemConfig {
38
38
  capture: { capMb?: number; retentionDays?: number };
39
39
  /** Exact non-GitHub remote URLs the person attests are private (#420). A statement, not a check. Machine file only. */
40
40
  privateRemotes?: string[];
41
+ /** #578 Q2 (owner choice c): opt-in for a sync-run placement checkpoint at the journal-objects bound. Machine file only; absent means off. */
42
+ syncPlacement?: { checkpointOnBound?: boolean };
41
43
  }
42
44
  export interface ConfigSource { machine: string | null; repo: string | null }
43
45
  export interface LoadedConfig { config: AmemConfig; source: ConfigSource }
@@ -112,6 +114,14 @@ function parseFile(raw: unknown, label: string, keys: readonly string[]): Partia
112
114
  if (capMb !== undefined) out.capture.capMb = capMb;
113
115
  if (retentionDays !== undefined) out.capture.retentionDays = retentionDays;
114
116
  }
117
+ if (body.syncPlacement !== undefined) {
118
+ const value = body.syncPlacement;
119
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some(key => key !== "checkpointOnBound")
120
+ || ((value as Record<string, unknown>).checkpointOnBound !== undefined && typeof (value as Record<string, unknown>).checkpointOnBound !== "boolean"))
121
+ return fail(label, "syncPlacement takes only checkpointOnBound (a boolean)");
122
+ const on = (value as { checkpointOnBound?: boolean }).checkpointOnBound;
123
+ out.syncPlacement = on === undefined ? {} : { checkpointOnBound: on };
124
+ }
115
125
  if (body.review !== undefined) {
116
126
  if (!body.review || typeof body.review !== "object" || Array.isArray(body.review) || Object.keys(body.review).some(key => !["recheck_days", "unused_rendered", "unused_days"].includes(key))) return fail(label, "review takes only recheck_days, unused_rendered and unused_days");
117
127
  const rawReview = body.review as Record<string, unknown>;
@@ -177,6 +187,7 @@ export function loadAmemConfig(base: string, repoRoot?: string): LoadedConfig {
177
187
  if (machine?.review !== undefined) config.review = { ...machine.review };
178
188
  if (machine?.home !== undefined) config.home = machine.home;
179
189
  if (machine?.privateRemotes?.length) config.privateRemotes = machine.privateRemotes;
190
+ if (machine?.syncPlacement !== undefined) config.syncPlacement = { ...machine.syncPlacement };
180
191
  if (machine?.records !== undefined || repo?.records !== undefined) config.records = machine?.records !== false && repo?.records !== false;
181
192
  for (const key of ["briefBytes", "excerptBytes", "capturePaths"] as const) { const value = lower(machine?.[key], repo?.[key]); if (value !== undefined) config[key] = value; }
182
193
  return { config, source: { machine: machineRaw === undefined ? null : machinePath, repo: repoPath } };
@@ -199,3 +210,8 @@ export function configuredPolicyOptions(base: string, cwd?: string, options: Sta
199
210
  export function configuredPolicy(base: string, cwd?: string, options: StandalonePolicyOptions = {}): StandalonePolicy {
200
211
  return createStandalonePolicy(configuredPolicyOptions(base, cwd, options));
201
212
  }
213
+
214
+ /** #578 Q2: the home's opt-in for a sync-run placement checkpoint. The machine file only; a repository file cannot set it. */
215
+ export function checkpointOnBoundOptIn(base: string): boolean {
216
+ return loadAmemConfig(base).config.syncPlacement?.checkpointOnBound === true;
217
+ }
@@ -19,7 +19,8 @@ import { readSelector } from "./generation.ts";
19
19
  import { processLiveness, withGitTimeout } from "./platform.ts";
20
20
  import { endLikeSignal, STOP_SIGNALS } from "./sync-cadence.ts";
21
21
  import { boundRepoRoot } from "./repo-scope.ts";
22
- import { facts, label, paint, section, markerCell, PLAIN, singleLine, type Style } from "./style.ts";
22
+ import { markerCell, paint } from "@staix/cli-output";
23
+ import { facts, label, section, PLAIN, singleLine, type Style } from "./style.ts";
23
24
  import { aliasedKeys, shardDir } from "./shard.ts";
24
25
  import type { MemoryStore, View } from "./store.ts";
25
26
  import { nextSyncAt, readSyncState, remoteConfigured, syncDue, usableState } from "./sync-cadence.ts";
@@ -693,8 +694,8 @@ export function doctorText(report: DoctorReport, s: Style = PLAIN): string {
693
694
  if (item.hint) actions.push(`${name}: ${item.hint}`);
694
695
  if (name === "capture" && item.clis) for (const [cli, row] of Object.entries(item.clis as Record<string, { hint?: string }>)) if (row.hint) actions.push(`capture ${cli}: ${row.hint}`);
695
696
  }
696
- const lines = [`${paint("header", " amem Doctor", s.color)}: ${report.status === "ok" ? s.ok(report.status) : report.status === "attention" ? s.attention(report.status) : s.error(report.status)}${summary ? ` (${summary})` : ` (all ${entries.length} checks ok)`}`,
697
- ...(actions.length ? ["", section(s, "Attention"), ...actions.map(action => ` ${paint("accent", markerCell("next", s.ascii), s.color)} ${action}`)] : []),
697
+ const lines = [`${paint([{ role: "header", text: " amem Doctor" }], s.color)}: ${report.status === "ok" ? s.ok(report.status) : report.status === "attention" ? s.attention(report.status) : s.error(report.status)}${summary ? ` (${summary})` : ` (all ${entries.length} checks ok)`}`,
698
+ ...(actions.length ? ["", section(s, "Attention"), ...actions.map(action => ` ${paint([{ role: "accent", text: markerCell("next", s.ascii) }], s.color)} ${action}`)] : []),
698
699
  "", section(s, "Checks"), ` home: ${report.home.path} ${s.dim(`(${report.home.source})`)}`, ` project: ${report.project}`];
699
700
  const order: Record<SectionStatus, number> = { attention: 0, unavailable: 1, skipped: 2, ok: 3 };
700
701
  entries.sort((a, b) => order[a[1].status] - order[b[1].status]);
@@ -706,10 +707,10 @@ export function doctorText(report: DoctorReport, s: Style = PLAIN): string {
706
707
  }
707
708
  lines.push("", actions.length ? "Next actions: see Attention" : "Next actions: none");
708
709
  const counts = [
709
- ...(count("attention") ? [`${paint("warning", markerCell("warn", s.ascii), s.color)} ${count("attention")} warnings`] : []),
710
- ...(count("unavailable") ? [`${paint("hint", markerCell("unknown", s.ascii), s.color)} ${count("unavailable")} unknown`] : []),
711
- ...(count("skipped") ? [`${paint("hint", markerCell("absent", s.ascii), s.color)} ${count("skipped")} skipped`] : []),
712
- ...(count("ok") ? [`${paint("success", markerCell("ok", s.ascii), s.color)} ${count("ok")} ok`] : []),
710
+ ...(count("attention") ? [`${paint([{ role: "warning", text: markerCell("warn", s.ascii) }], s.color)} ${count("attention")} warnings`] : []),
711
+ ...(count("unavailable") ? [`${paint([{ role: "hint", text: markerCell("unknown", s.ascii) }], s.color)} ${count("unavailable")} unknown`] : []),
712
+ ...(count("skipped") ? [`${paint([{ role: "hint", text: markerCell("absent", s.ascii) }], s.color)} ${count("skipped")} skipped`] : []),
713
+ ...(count("ok") ? [`${paint([{ role: "success", text: markerCell("ok", s.ascii) }], s.color)} ${count("ok")} ok`] : []),
713
714
  ];
714
715
  if (counts.length) lines.push(counts.join(" "));
715
716
  return lines.join("\n");
@@ -1,4 +1,5 @@
1
- import { facts, label, markerCell, paint, section, PLAIN, type Style } from "./style.ts";
1
+ import { markerCell, paint } from "@staix/cli-output";
2
+ import { facts, label, section, PLAIN, type Style } from "./style.ts";
2
3
 
3
4
  /** The `amem status` object as the CLI builds it; `amem status --json` prints it unchanged. */
4
5
  export interface StatusView {
@@ -32,8 +33,8 @@ export function statusText(status: StatusView, s: Style = PLAIN): string {
32
33
  const { machine, repo, denyPaths, piiPatterns, ...limits } = status.config;
33
34
  const pendingCounts = facts(Object.fromEntries(Object.entries(status.pending).filter(([key]) => !key.endsWith("Ids"))));
34
35
  const lines = [
35
- `${paint("header", " amem Status", s.color)}: ${overall === "ok" ? s.ok(overall) : overall === "attention" ? s.attention(overall) : s.error(overall)}`,
36
- ...(warnings.length || actions.length ? ["", section(s, "Attention"), ...warnings.map(warning => ` ${s.attention(markerCell("warn", s.ascii))} ${warning}`), ...actions.map(action => ` ${paint("accent", markerCell("next", s.ascii), s.color)} ${action}`)] : []),
36
+ `${paint([{ role: "header", text: " amem Status" }], s.color)}: ${overall === "ok" ? s.ok(overall) : overall === "attention" ? s.attention(overall) : s.error(overall)}`,
37
+ ...(warnings.length || actions.length ? ["", section(s, "Attention"), ...warnings.map(warning => ` ${s.attention(markerCell("warn", s.ascii))} ${warning}`), ...actions.map(action => ` ${paint([{ role: "accent", text: markerCell("next", s.ascii) }], s.color)} ${action}`)] : []),
37
38
  "", section(s, "Memory"),
38
39
  ` home: ${status.home.path} ${s.dim(`(${status.home.source})`)}`,
39
40
  `${label(s, "ok")} policy: machine ${machine ?? "none (defaults)"}, repo ${repo ?? "none"}; ${denyPaths} deny paths, ${piiPatterns} PII patterns${facts(limits) ? `; ${facts(limits)}` : ""}`,
@@ -1,8 +1,10 @@
1
1
  /**
2
- * A tiny, dependency-free text style for person-facing CLI output (#125).
2
+ * Application-specific text helpers for person-facing CLI output (#125).
3
3
  * Color is decoration only: every caller also prints a textual label, so plain output carries the same facts.
4
4
  * JSON output never passes through this module.
5
5
  */
6
+ import { MARKERS, SECTION_MARKER, SGR_RESET, cellWidth, markerCell, paint, type MarkerName } from "@staix/cli-output";
7
+
6
8
  export interface Style {
7
9
  readonly color: boolean;
8
10
  readonly ascii: boolean;
@@ -13,57 +15,15 @@ export interface Style {
13
15
  bold(text: string): string;
14
16
  }
15
17
 
16
- /** Portable CLI output standard v1 vocabulary. */
17
- export type Role = "header" | "section" | "key" | "value" | "success" | "warning" | "error" | "hint" | "accent";
18
- const ESC = String.fromCharCode(27);
19
- export const SGR_RESET = `${ESC}[0m`;
20
- export const ROLE_SGR: Readonly<Record<Role, string>> = Object.freeze({
21
- header: `${ESC}[1;34m`, section: `${ESC}[1;35m`, key: `${ESC}[34m`, value: "",
22
- success: `${ESC}[1;32m`, warning: `${ESC}[1;33m`, error: `${ESC}[1;31m`,
23
- hint: `${ESC}[90m`, accent: `${ESC}[36m`,
24
- });
25
- export const MARKER_NAMES = ["ok", "fail", "warn", "absent", "unknown", "pending", "active", "next"] as const;
26
- export type MarkerName = (typeof MARKER_NAMES)[number];
27
- export const MARKERS: Readonly<Record<MarkerName, { glyph: string; ascii: string; role: Role }>> = Object.freeze({
28
- ok: { glyph: "✓", ascii: "ok", role: "success" }, fail: { glyph: "✗", ascii: "x", role: "error" },
29
- warn: { glyph: "⚠", ascii: "!", role: "warning" }, absent: { glyph: "-", ascii: "-", role: "hint" },
30
- unknown: { glyph: "?", ascii: "?", role: "hint" }, pending: { glyph: "~", ascii: "~", role: "hint" },
31
- active: { glyph: "*", ascii: "*", role: "success" }, next: { glyph: "→", ascii: "->", role: "accent" },
32
- });
33
- export const SECTION_MARKER = { glyph: "▸", ascii: ">" } as const;
34
- export const MARKER_COLUMN = 2;
35
- export const cellWidth = (text: string): number => Bun.stringWidth(text, { ambiguousIsNarrow: true });
36
- export function markerCell(name: MarkerName, ascii: boolean): string {
37
- const text = ascii ? MARKERS[name].ascii : MARKERS[name].glyph;
38
- return text + " ".repeat(Math.max(0, MARKER_COLUMN - cellWidth(text)));
39
- }
40
- export interface ColorEnv { isTTY: boolean; TERM?: string; NO_COLOR?: string; FORCE_COLOR?: string; CLICOLOR?: string; CLICOLOR_FORCE?: string }
41
- export function streamEnv(isTTY: boolean, env: Readonly<Record<string, string | undefined>> = process.env): ColorEnv {
42
- return { isTTY, TERM: env.TERM, NO_COLOR: env.NO_COLOR, FORCE_COLOR: env.FORCE_COLOR, CLICOLOR: env.CLICOLOR, CLICOLOR_FORCE: env.CLICOLOR_FORCE };
43
- }
44
- export function resolveColor(flag: string | undefined, env: ColorEnv): boolean | Error {
45
- if (flag === "always") return true;
46
- if (flag === "never") return false;
47
- if (flag !== undefined && flag !== "auto") return new Error("usage: amem <command> [--color=auto|always|never]");
48
- if (env.NO_COLOR) return false;
49
- if ((env.FORCE_COLOR && env.FORCE_COLOR !== "0") || (env.CLICOLOR_FORCE && env.CLICOLOR_FORCE !== "0")) return true;
50
- if (env.FORCE_COLOR === "0" || env.CLICOLOR === "0") return false;
51
- return env.isTTY && env.TERM !== "dumb";
52
- }
53
- export function asciiMarkers(env: Readonly<Record<string, string | undefined>> = process.env, flag = false): boolean {
54
- return flag || !/utf-?8/i.test(env.LC_ALL || env.LC_CTYPE || env.LANG || "");
55
- }
56
- export function paint(role: Role, text: string, color: boolean): string {
57
- return color && ROLE_SGR[role] ? `${ROLE_SGR[role]}${text}${SGR_RESET}` : text;
58
- }
59
18
  export function section(s: Style, name: string): string {
60
- return paint("section", `${s.ascii ? SECTION_MARKER.ascii : SECTION_MARKER.glyph} ${name}`, s.color);
19
+ return paint([{ role: "section", text: `${s.ascii ? SECTION_MARKER.ascii : SECTION_MARKER.glyph} ${name}` }], s.color);
61
20
  }
62
21
 
63
22
  /** Wrap report prose at a stream's requested width; a pipe without COLUMNS remains unwrapped. */
23
+ // ponytail: this renderer receives already-painted strings; migrate producers to structured spans under #590.
64
24
  export function wrapReport(text: string, width: number | undefined): string {
65
25
  if (!Number.isSafeInteger(width) || width === undefined || width < 20) return text;
66
- const ansi = new RegExp(`${ESC}\\[[0-9;]*m`, "g");
26
+ const ansi = new RegExp(`${SGR_RESET[0]}\\[[0-9;]*m`, "g");
67
27
  const measure = (value: string) => cellWidth(value.replace(ansi, ""));
68
28
  return text.split("\n").flatMap(line => {
69
29
  if (measure(line) <= width) return [line];
@@ -78,7 +38,7 @@ export function wrapReport(text: string, width: number | undefined): string {
78
38
  if (measure(row + spacing + word) <= width) { row += spacing + word; spacing = ""; continue; }
79
39
  row += spacing; spacing = "";
80
40
  // Long unbroken values are continued without truncation; --json retains their exact bytes.
81
- for (const part of word.match(new RegExp(`${ESC}\\[[0-9;]*m|.`, "gu")) ?? []) {
41
+ for (const part of word.match(new RegExp(`${SGR_RESET[0]}\\[[0-9;]*m|.`, "gu")) ?? []) {
82
42
  if (measure(row + part) > width) { result.push(row); row = continuation; }
83
43
  row += part;
84
44
  }
@@ -88,14 +48,9 @@ export function wrapReport(text: string, width: number | undefined): string {
88
48
  }).join("\n");
89
49
  }
90
50
 
91
- /** Default color decision for one stream, following the shared precedence table. */
92
- export function colorEnabled(env: Readonly<Record<string, string | undefined>>, isTTY: boolean | undefined): boolean {
93
- return resolveColor("auto", streamEnv(isTTY === true, env)) === true;
94
- }
95
-
96
51
  export function style(color: boolean, ascii = true): Style {
97
- return { color, ascii, ok: text => paint("success", text, color), attention: text => paint("warning", text, color),
98
- error: text => paint("error", text, color), dim: text => paint("hint", text, color), bold: text => paint("value", text, color) };
52
+ return { color, ascii, ok: text => paint([{ role: "success", text }], color), attention: text => paint([{ role: "warning", text }], color),
53
+ error: text => paint([{ role: "error", text }], color), dim: text => paint([{ role: "hint", text }], color), bold: text => paint([{ role: "value", text }], color) };
99
54
  }
100
55
  export const PLAIN: Style = style(false);
101
56
 
@@ -107,7 +62,7 @@ export function label(s: Style, state: "ok" | "attention" | "skipped" | "unavail
107
62
  const word = { ok: "OK", attention: "ATTENTION", skipped: "SKIPPED", unavailable: "UNAVAILABLE", error: "ERROR" }[state].padEnd(11);
108
63
  const marker: MarkerName = state === "ok" ? "ok" : state === "attention" ? "warn" : state === "skipped" ? "absent" : state === "unavailable" ? "unknown" : "fail";
109
64
  const text = `${markerCell(marker, s.ascii)} ${word}`;
110
- return ` ${paint(MARKERS[marker].role, text, s.color)}`;
65
+ return ` ${paint([{ role: MARKERS[marker].role, text }], s.color)}`;
111
66
  }
112
67
 
113
68
  /** "key value" pairs, leaving out zero, empty and null values; returns "" when nothing material is left. */
@@ -6,23 +6,39 @@ import { acquireMutation, type MutationHandle } from "./mutation.ts";
6
6
  import { generationSyncLock } from "./generation-sync.ts";
7
7
  import { assertNoLiveReaders } from "./reader-lease.ts";
8
8
  import { createPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
9
+ /** #578 Q1: a checkpoint fence never refuses for readers; its `busy` means a placement sync, admission or renewal holds a lock. */
10
+ export const PLACEMENT_CHECKPOINT_BUSY_MESSAGE = "Sync placement checkpoint is busy: a placement sync, admission or renewal holds its lock; wait for it to finish (amem sync --status shows recorded operations), then rerun the same checkpoint command.";
9
11
  export class PlacementInventoryFenceError extends Error{
10
- constructor(readonly causeClass:"readers"|"busy"){super(`Sync placement migration is ${causeClass}; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying.`);this.name="PlacementInventoryFenceError";}
12
+ constructor(readonly causeClass:"readers"|"busy",checkpoint=false){super(checkpoint&&causeClass==="busy"?PLACEMENT_CHECKPOINT_BUSY_MESSAGE:`Sync placement migration is ${causeClass}; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying.`);this.name="PlacementInventoryFenceError";}
11
13
  }
12
- function fail(cause:"readers"|"busy"):never{throw new PlacementInventoryFenceError(cause);}
13
- export async function withPlacementActivationFences<T>(home:string,directories:readonly string[],work:(mutation:MutationHandle,owner:ReturnType<typeof createPlacementActivationOwner>)=>Promise<T>):Promise<T> {
14
+ type FenceWork<T>=(mutation:MutationHandle,owner:ReturnType<typeof createPlacementActivationOwner>)=>Promise<T>;
15
+ async function withFences<T>(home:string,directories:readonly string[],options:{readers:boolean},work:FenceWork<T>):Promise<T> {
16
+ const fail=(cause:"readers"|"busy"):never=>{throw new PlacementInventoryFenceError(cause,!options.readers);};
14
17
  return withProfileLock(home,async()=>{
15
18
  const releases:(()=>void)[]=[];
16
19
  try {
17
20
  const transports=["shard-sync","shard-sync-placement"].map(name=>join(home,name)).filter(dir=>lstatSync(dir,{throwIfNoEntry:false})!==undefined);
18
21
  const dirs=[...new Set([home,...directories,...transports])].sort();let mutation:MutationHandle|undefined;
19
22
  for(const dir of dirs){
20
- try{assertNoLiveReaders(dir,{includeShards:true});}catch{fail("readers");}
21
- const handle=acquireMutation(dir);if(!handle)fail("busy");releases.push(handle);if(dir===home)mutation=handle;
23
+ if(options.readers){try{assertNoLiveReaders(dir,{includeShards:true});}catch{fail("readers");}}
24
+ const handle=acquireMutation(dir);if(!handle)fail("busy");releases.push(handle!);if(dir===home)mutation=handle!;
22
25
  }
23
26
  if(!mutation)fail("busy");
24
- for(const dir of [home,...transports]){const release=generationSyncLock(dir);if(!release)fail("busy");releases.push(release);}
25
- const owner=createPlacementActivationOwner(home,mutation);return await work(mutation,owner);
27
+ for(const dir of [home,...transports]){const release=generationSyncLock(dir);if(!release)fail("busy");releases.push(release!);}
28
+ const owner=createPlacementActivationOwner(home,mutation!);return await work(mutation!,owner);
26
29
  }finally{for(const release of releases.reverse())release();}
27
30
  });
28
31
  }
32
+ /** Activation, renewal and admission: every live reader lease refuses, as before. */
33
+ export function withPlacementActivationFences<T>(home:string,directories:readonly string[],work:FenceWork<T>):Promise<T> {
34
+ return withFences(home,directories,{readers:true},work);
35
+ }
36
+ /**
37
+ * #578 Q1: checkpoint confirm, resume and abandon exclude placement writers only (profile lock, every mutation and sync
38
+ * lock). Live curated readers keep running: the checkpoint writes only under `sync-placement-checkpoints/`, never the
39
+ * binding markers, and an extension-log reader fails closed (`checkpoint-pending`, then `changed`). The held profile
40
+ * lock still refuses new reader admission for the duration.
41
+ */
42
+ export function withPlacementCheckpointFences<T>(home:string,directories:readonly string[],work:FenceWork<T>):Promise<T> {
43
+ return withFences(home,directories,{readers:false},work);
44
+ }
@@ -4,6 +4,7 @@
4
4
  * person-written floor record (`amem formats raise` is the one writer).
5
5
  */
6
6
  import { randomBytes } from "node:crypto";
7
+ import { fileURLToPath } from "node:url";
7
8
  import { types } from "node:util";
8
9
  import { memoryPolicySnapshot } from "./policy.ts";
9
10
  import { realPath } from "./platform.ts";
@@ -20,11 +21,12 @@ import { readPlacementJournal, readPlacementPublicationMetadata, placementJourna
20
21
  import { publicationFileNames } from "./sync-placement-publication-plan.ts";
21
22
  import { PLACEMENT_CHECKPOINT_COMMAND, PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending, resolvePlacementWindow } from "./sync-placement-checkpoint-storage.ts";
22
23
  import { abandonPlacementCheckpoint, applyPlacementCheckpoint, planPlacementCheckpoint, resumePlacementCheckpoint, type PlacementCheckpointInput, type PlacementCheckpointPhase } from "./sync-placement-checkpoint.ts";
23
- import { PLACEMENT_CHECKPOINT_MIN_READER, validateCheckpointIntent, type CheckpointIntent } from "./sync-placement-checkpoint-format.ts";
24
- import { withPlacementActivationFences } from "./sync-placement-activation-locks.ts";
24
+ import { PLACEMENT_CHECKPOINT_LIMIT, PLACEMENT_CHECKPOINT_MIN_READER, validateCheckpointIntent, type CheckpointIntent } from "./sync-placement-checkpoint-format.ts";
25
+ import { withPlacementCheckpointFences } from "./sync-placement-activation-locks.ts";
25
26
  import { assertPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
26
27
  import { placementFenceDirectories } from "./sync-placement-writer-renewal.ts";
27
28
  import { initialPlacementWriterContext } from "../sync-placement-writer-context.ts";
29
+ import { readSetupWriterRoots, SetupWriterRootsError } from "../setup.ts";
28
30
  import { checkpointProspective, type CheckpointProspective } from "./sync-placement-checkpoint-prospective.ts";
29
31
  import { ShardHistoryError, type ShardHistoryCause } from "./shard-sync-history.ts";
30
32
 
@@ -185,7 +187,7 @@ export async function confirmPlacementCheckpoint(homeInput: string, value: unkno
185
187
  checkFloor(home, undefined, minReader); checkFloor(home, measured(home, opts.writerRoots, opts.ownRoot), minReader);
186
188
  const prospective = await checkpointHeadroom(home, intent);
187
189
  if (canonicalJSON(reviewedHeadroom(value)) !== canonicalJSON(prospective.headroom)) throw new PlacementCheckpointError("changed");
188
- return withPlacementActivationFences(home, placementFenceDirectories(home, a), async (mutation, owner) => {
190
+ return withPlacementCheckpointFences(home, placementFenceDirectories(home, a), async (mutation, owner) => {
189
191
  const now = active(home), roots = measured(home, opts.writerRoots, opts.ownRoot);
190
192
  if (canonicalJSON(now) !== canonicalJSON(a)) throw new PlacementCheckpointError("changed");
191
193
  prospective.assertCurrent();
@@ -205,7 +207,7 @@ export async function confirmPlacementCheckpoint(homeInput: string, value: unkno
205
207
  /** Resume completes only the frozen bytes of the recorded intent: metadata only, no fresh install, policy or source check. */
206
208
  export async function resumePlacementCheckpointPerson(homeInput: string): Promise<{ window: number; resumed: boolean; nextStep: string }> {
207
209
  const home = realPath(homeInput), a = active(home), epochHash = a.profile.placementHead;
208
- return withPlacementActivationFences(home, placementFenceDirectories(home, a), async (mutation, owner) => {
210
+ return withPlacementCheckpointFences(home, placementFenceDirectories(home, a), async (mutation, owner) => {
209
211
  try {
210
212
  const done = resumePlacementCheckpoint(home, epochHash, { mutation, assertCurrent: () => assertPlacementActivationOwner(owner) });
211
213
  return done ? { window: done.window, resumed: true, nextStep: "amem sync" } : { window: resolvePlacementWindow(home, epochHash).window, resumed: false, nextStep: "amem sync" };
@@ -219,7 +221,7 @@ export async function resumePlacementCheckpointPerson(homeInput: string): Promis
219
221
  /** Abandon removes only intent-owned staging before the first commit byte; after it, refuses and names resume. */
220
222
  export async function abandonPlacementCheckpointPerson(homeInput: string): Promise<{ removed: number; abandoned: boolean; nextStep: string }> {
221
223
  const home = realPath(homeInput), a = active(home), epochHash = a.profile.placementHead;
222
- return withPlacementActivationFences(home, placementFenceDirectories(home, a), async (mutation, owner) => {
224
+ return withPlacementCheckpointFences(home, placementFenceDirectories(home, a), async (mutation, owner) => {
223
225
  try {
224
226
  const pending = placementCheckpointPending(home, epochHash), done = abandonPlacementCheckpoint(home, epochHash, { mutation, assertCurrent: () => assertPlacementActivationOwner(owner) });
225
227
  return { removed: done.removed, abandoned: pending, nextStep: CHECKPOINT_PREVIEW };
@@ -229,3 +231,38 @@ export async function abandonPlacementCheckpointPerson(homeInput: string): Promi
229
231
  } finally { releasePlacementStorageCaches(); }
230
232
  });
231
233
  }
234
+
235
+ /** #578 Q2: the counts-only outcome of a sync-run checkpoint, or its refusal with a fixed cause and text. */
236
+ export type CheckpointOnBoundResult = { ok: true; window: number; objectsBefore: number; objectsAfter: number }
237
+ | { ok: false; cause: PlacementCheckpointCause | "pins" | "cap" | "fence"; message: string };
238
+ /**
239
+ * #578 Q2 (owner choice c): a sync-run checkpoint with an unchanged writer inventory, behind the home opt-in.
240
+ * The caller must already have released every placement lock its failed publication held (the transport's own finally),
241
+ * because the checkpoint fence takes the same mutation and sync locks again in this process.
242
+ * The root set is this package's own root (`import.meta.url`), every setup-receipt root and every effective root; it
243
+ * runs only when that set is exactly the effective inventory and the caller's attestation re-measures identical pins.
244
+ * Every other refusal comes from the person preview and confirm themselves (headroom, floors, obligations, history).
245
+ */
246
+ export async function checkpointOnBound(homeInput: string, attest: () => unknown, ownRoot = fileURLToPath(new URL("../..", import.meta.url))): Promise<CheckpointOnBoundResult> {
247
+ const refuse = (cause: Extract<CheckpointOnBoundResult, { ok: false }>["cause"], message: string): CheckpointOnBoundResult => ({ ok: false, cause, message });
248
+ const pins = "Sync-run placement checkpoint refused: the writer inventory changed or is incomplete; a person renews it with amem migrate --sync-placement --dry-run, then --apply.";
249
+ try {
250
+ const home = realPath(homeInput), effective = readEffectiveSyncPlacementWriters(home), roots = effective.roots;
251
+ if (!roots) return refuse("pins", pins);
252
+ let own: string; try { own = realPath(ownRoot); } catch { return refuse("pins", pins); }
253
+ const wanted = new Set([...roots, ...readSetupWriterRoots(home), own]);
254
+ if (wanted.size !== roots.length || ![...wanted].every(root => roots.includes(root))) return refuse("pins", pins);
255
+ try { attest(); } catch { return refuse("pins", pins); }
256
+ const window = resolvePlacementWindow(home, effective.epochHash);
257
+ if (window.window + 1 >= PLACEMENT_CHECKPOINT_LIMIT - 1)
258
+ return refuse("cap", `Sync-run placement checkpoint refused: window ${window.window + 1} would reach the last checkpoints of this epoch; a person decides it with ${CHECKPOINT_PREVIEW}.`);
259
+ const preview = await previewPlacementCheckpoint(home, { writerRoots: roots, ownRoot: own });
260
+ const done = await confirmPlacementCheckpoint(home, preview, { writerRoots: roots, ownRoot: own });
261
+ return { ok: true, window: done.window, objectsBefore: preview.currentObjects, objectsAfter: readPlacementJournal(home, effective.epochHash).objects };
262
+ } catch (error) {
263
+ if (error instanceof PlacementCheckpointError) return refuse(error.causeClass, `Sync-run placement checkpoint refused: ${error.message}`);
264
+ if (error instanceof Error && error.name === "PlacementInventoryFenceError") return refuse("fence", error.message);
265
+ if (error instanceof SetupWriterRootsError) return refuse("pins", pins);
266
+ return refuse("changed", "Sync-run placement checkpoint refused: placement state changed or could not be read; run the checkpoint preview.");
267
+ } finally { releasePlacementStorageCaches(); }
268
+ }
@@ -12,7 +12,8 @@ import { captureInspectionJournal, inspectRetainedPublicationHistories, Placemen
12
12
  import { ShardHistoryError } from "./shard-sync-history.ts";
13
13
  import { createPlacementRecord, SyncPlacementJournalError, PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, type PlacementRealm } from "./sync-placement-journal-format.ts";
14
14
  import { materializePlacementRows, verifiedPlacementPrunes } from "./sync-placement-materialize.ts";
15
- import { planPlacementPublicationAsync, publicationBytes, publicationFileNames } from "./sync-placement-publication-plan.ts";
15
+ import { planPlacementPublicationAsync, planPlacementPublicationV2Async, placementDecisionReuseEnabled, publicationBytes, publicationFileNames } from "./sync-placement-publication-plan.ts";
16
+ import { placementDecisionOwners } from "./sync-placement-journal-storage.ts";
16
17
  import { placementPublicationEventSteps } from "./sync-placement-publication-events.ts";
17
18
  import { drainSteps } from "./sync-placement-yield.ts";
18
19
  import { outboundPolicyEvaluator } from "./sync-screen.ts";
@@ -128,11 +129,13 @@ export async function checkpointProspective(home: string): Promise<{ value: Chec
128
129
  policyHash: source.base.policyHash, remoteHash: objects.remoteHash, journal: { sequence: journal.journal.sequence, headHash: journal.journal.headHash },
129
130
  createdUnixSeconds: Math.floor(now / 1000), policySnapshotUnixMs: now, targets: materialized.plannedTargets, reservedRecords: 0, reservedRecordBytes: [] as number[] };
130
131
  const items = { sources: source.prefixes, decisions: materialized.decisions, objects: materialized.objects };
131
- let bundle = await planPlacementPublicationAsync(body, items);
132
+ const v2 = placementDecisionReuseEnabled(home);
133
+ const owners = v2 ? await placementDecisionOwners(home, body.epochHash, body.journal.sequence, body.targets.map(target => target.realm)) : [];
134
+ let bundle = v2 ? await planPlacementPublicationV2Async(body, items, owners) : await planPlacementPublicationAsync(body, items);
132
135
  const scheduled = drainSteps(placementPublicationEventSteps(bundle, journal.projection, old));
133
136
  let head = body.journal.headHash;
134
137
  const lengths = scheduled.events.map((event, index) => { const record = createPlacementRecord(body.epochHash, body.journal.sequence + index + 1, head, event); head = record.seal; return publicationBytes(record).length; });
135
- bundle = await planPlacementPublicationAsync({ ...body, reservedRecords: lengths.length, reservedRecordBytes: lengths }, items);
138
+ bundle = v2 ? await planPlacementPublicationV2Async({ ...body, reservedRecords: lengths.length, reservedRecordBytes: lengths }, items, owners) : await planPlacementPublicationAsync({ ...body, reservedRecords: lengths.length, reservedRecordBytes: lengths }, items);
136
139
  const changed = bundle.root.targets.some((target, index) => target.publish && target.commit !== heads[index]);
137
140
  if (scheduled.events.length || changed) {
138
141
  const candidate = { slots: publicationFileNames(bundle.root).length, reservedJournalChunks: reserve(lengths) };
@@ -70,6 +70,8 @@ export interface PlacementInventoryPorts {
70
70
  close(store: MemoryStore): void;
71
71
  /** Runs one unchanged two-target placement publication over the given opened stores. */
72
72
  publish(primary: MemoryStore, targets: readonly MemoryStore[], opts: SyncOptions): Promise<SyncResult>;
73
+ /** #578 Q2: present only for an opted-in, eligible caller; runs one checkpoint after a journal-objects refusal. */
74
+ checkpointOnBound?(): Promise<import("./sync-placement-checkpoint-person.ts").CheckpointOnBoundResult>;
73
75
  }
74
76
 
75
77
  function sum(results: readonly SyncResult[]): Pick<SyncResult, "entries" | "pushed"> & { exported: number; withheld: number } {
@@ -131,19 +133,30 @@ export async function syncPlacementInventory(home: string, opts: SyncOptions, po
131
133
  progress?.deferFinish(true); report(0);
132
134
  let completed = 0;
133
135
  const results: SyncResult[] = [];
134
- let stopped: SyncResult | undefined;
135
- for (const [index, batch] of batches.entries()) {
136
- if (!batch.length) continue;
137
- if (stopped) { for (const realm of batch) realms.push({ realm: label(realm), outcome: "not-run" }); continue; }
138
- if (opts.signal?.aborted) { stopped = { ok: false, pushed: false, entries: 0, error: "stopped", failure: { cause: "stopped" } }; for (const realm of batch) realms.push({ realm: label(realm), outcome: "not-run" }); continue; }
136
+ let stopped: SyncResult | undefined, checkpoint: SyncResult["checkpoint"], checkpointTried = false;
137
+ const attempt = async (batch: InventoryRealm[]): Promise<SyncResult> => {
139
138
  const stores: MemoryStore[] = [];
140
- let result: SyncResult;
141
139
  try {
142
140
  for (const realm of batch) stores.push(ports.open(realm));
143
- result = await ports.publish(stores[0]!, stores, opts);
141
+ return await ports.publish(stores[0]!, stores, opts);
144
142
  } catch (error) {
145
- result = { ok: false, pushed: false, entries: 0, error: (error as Error).message, failure: { cause: "unavailable" } };
143
+ return { ok: false, pushed: false, entries: 0, error: (error as Error).message, failure: { cause: "unavailable" } };
146
144
  } finally { for (const store of stores.reverse()) try { ports.close(store); } catch { /* preserve the publication result */ } }
145
+ };
146
+ for (const [index, batch] of batches.entries()) {
147
+ if (!batch.length) continue;
148
+ if (stopped) { for (const realm of batch) realms.push({ realm: label(realm), outcome: "not-run" }); continue; }
149
+ if (opts.signal?.aborted) { stopped = { ok: false, pushed: false, entries: 0, error: "stopped", failure: { cause: "stopped" } }; for (const realm of batch) realms.push({ realm: label(realm), outcome: "not-run" }); continue; }
150
+ let result = await attempt(batch);
151
+ // #578 Q2: by here the publication has returned, so its transport released every mutation and sync lock it took
152
+ // (sync-placement-transport.ts finally) and `attempt` closed the stores it opened. The checkpoint fence takes those
153
+ // same locks again in this process; running it any earlier would wait on our own locks until busy_timeout.
154
+ if (!result.ok && !checkpointTried && ports.checkpointOnBound && result.placementPublication?.bound?.kind === "journal-objects") {
155
+ checkpointTried = true;
156
+ const ran = await ports.checkpointOnBound();
157
+ if (ran.ok) { checkpoint = { window: ran.window, objectsBefore: ran.objectsBefore, objectsAfter: ran.objectsAfter }; result = await attempt(batch); }
158
+ else result = { ...result, error: [result.error, ran.message].filter(Boolean).join(" "), failure: { cause: "checkpoint-refused" } };
159
+ }
147
160
  results.push(result);
148
161
  const outcome: PlacementRealmOutcome = result.ok ? result.placementPublication?.outcome ?? "not-needed" : result.placementPublication?.outcome === "unknown" ? "unknown" : "failed";
149
162
  for (const realm of batch) realms.push({ realm: label(realm), outcome, publication: index + 1 });
@@ -157,7 +170,7 @@ export async function syncPlacementInventory(home: string, opts: SyncOptions, po
157
170
  else progress?.finish("succeeded");
158
171
  const totals = sum(results), last = stopped ?? results.at(-1);
159
172
  const base: SyncResult = last ? { ...last } : { ok: true, pushed: false, entries: 0 };
160
- return { ...base, ok: !stopped, pushed: totals.pushed, entries: totals.entries,
173
+ return { ...base, ok: !stopped, pushed: totals.pushed, entries: totals.entries, ...(checkpoint ? { checkpoint } : {}),
161
174
  ...(base.placementPublication ? { placementPublication: { ...base.placementPublication, exported: totals.exported, withheld: totals.withheld } } : {}),
162
175
  ...(stopped?.error !== undefined ? { error: stopped.error } : {}), ...(held.length ? { warning: [base.warning, ...held.map(realm => localKeyOptInMessage(realm.key))].filter(Boolean).join(" ") } : {}), placementRealms: realms };
163
176
  }
@@ -10,9 +10,9 @@ import { validatePlacementPlan, type SyncPlacementActivationPlan } from "./sync-
10
10
  import { validatePlacementProfile, validatePlacementShards } from "./sync-placement-format.ts";
11
11
  import { PLACEMENT_ACTIVE_FENCE_SCHEMA, PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS, PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, PLACEMENT_JOURNAL_ROOT_MAX_BYTES,
12
12
  SyncPlacementJournalError, createPlacementRecord, placementEpochHash, validatePlacementActiveFence, validatePlacementEpoch, validatePlacementEvent, validatePlacementRecord,
13
- type PlacementActiveFence, type PlacementEpoch, type PlacementEvent, type PlacementRecord, type SyncPlacementJournalErrorCode } from "./sync-placement-journal-format.ts";
14
- import { validatePlacementPublicationRoot, validatePlacementPublicationBundle, validatePlacementPublicationFact, publicationFileNames,
15
- PLACEMENT_PUBLICATION_RECORD_MAX_BYTES, type PlacementPublicationRoot, type PlacementPublicationBundle, type PlacementPublicationFact } from "./sync-placement-publication-plan.ts";
13
+ type PlacementActiveFence, type PlacementEpoch, type PlacementEvent, type PlacementRealm, type PlacementRecord, type SyncPlacementJournalErrorCode } from "./sync-placement-journal-format.ts";
14
+ import { validatePlacementPublicationRoot, validatePlacementPublicationBundle, validatePlacementPublicationFact, decodePlacementPublicationChunk, publicationFileNames, placementDecisionReuseEnabled, PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA,
15
+ PLACEMENT_PUBLICATION_RECORD_MAX_BYTES, type PlacementPublicationRoot, type PlacementPublicationChunkDescriptor, type PlacementDecisionOwner, type PlacementPublicationBundle, type PlacementPublicationFact } from "./sync-placement-publication-plan.ts";
16
16
  import { PlacementProjection } from "./sync-placement-projection.ts";
17
17
  import { WRITER_RENEWAL_INTENT_FILE, WRITER_RENEWAL_INTENT_MAX_BYTES, WRITER_COMMIT_LOG, writerHistoryFileLimit, writerRevisionFile } from "./sync-placement-writer-revision-format.ts";
18
18
  import { isWriterRenewalIntentTempName } from "./sync-placement-writer-history.ts";
@@ -20,6 +20,7 @@ import { PLACEMENT_BATCH_INTENT_MAX_BYTES, planPlacementBatchIntent, validatePla
20
20
  import { formatFloorAtLeast } from "./formats.ts";
21
21
  import { resolvePlacementWindow, placementWindowToken, releasePlacementCheckpointCaches, type ResolvedPlacementWindow } from "./sync-placement-checkpoint-storage.ts";
22
22
  import { isCheckpointSealedName, PLACEMENT_CHECKPOINT_MANIFEST_MAX_BYTES, type CheckpointMember } from "./sync-placement-checkpoint-format.ts";
23
+ import { cooperativeYield, type CooperativeYield } from "./sync-placement-yield.ts";
23
24
 
24
25
  export type PlacementStoragePhase = "epoch-written" | "epoch-fsync" | "activation-written" | "activation-fsync" | "fence-written" | "fence-fsync"
25
26
  | "intent-written" | "intent-fsync" | "chunk-written" | "chunk-fsync" | "intent-cleared"
@@ -523,6 +524,45 @@ export interface PlacementPublicationStored {
523
524
  }
524
525
  /** Validated plan bundle keyed by the stat stamps of epoch.json, the root and every plan chunk (#420); same ceiling as journalPrefix. */
525
526
  let publicationBundle: { key: string; bundle: PlacementPublicationBundle } | undefined;
527
+ function publicationFacts(dir: string, stem: string, root: PlacementPublicationRoot, archived?: readonly CheckpointMember[]): Pick<PlacementPublicationStored, "phase" | "facts" | "pending" | "pendingPhase"> {
528
+ const facts: PlacementPublicationFact[] = []; let phase: PlacementPublicationStored["phase"] = "prepared", pending = false, absent = false; let pendingPhase: PlacementPublicationFact["phase"] | undefined;
529
+ for (const [index, suffix] of ["artifact", "intent", "receipt"].entries()) {
530
+ const bytes = readOwned(join(dir, stem + suffix + ".json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
531
+ if (bytes === undefined) fail("corrupt");
532
+ if (archived) { const member = archived.find(value => value.name === stem + suffix + ".json"); if (!member || member.size !== bytes.length || member.sha256 !== digest(bytes)) fail("corrupt"); }
533
+ if (!bytes.length) { absent = true; continue; }
534
+ if (absent && (suffix !== "receipt" || pendingPhase)) fail("corrupt");
535
+ if (bytes.at(-1) !== 10) { pending = true; pendingPhase = (["artifact-built", "publication-intent", "completed"] as const)[index]; absent = true; continue; }
536
+ const fact = decode(bytes, validatePlacementPublicationFact), previous = facts.at(-1)?.seal ?? root.seal;
537
+ if (fact.attemptHash !== root.seal || fact.previousHash !== previous || fact.phase !== (["artifact-built", "publication-intent", "completed"] as const)[index]) fail("corrupt");
538
+ const intentFact = facts.find(fact => fact.phase === "publication-intent");
539
+ if (fact.phase === "publication-intent" && (fact.artifactFactHash !== previous || fact.policyHash !== root.policyHash || fact.policyCheckUnixMs !== root.policySnapshotUnixMs)
540
+ || fact.phase === "completed" && (fact.intentFactHash !== (intentFact?.seal ?? null) || fact.journal.sequence < root.journal.sequence || fact.journal.sequence > root.journal.sequence + root.reservedRecords
541
+ || fact.outcome === "committed" && (!intentFact || fact.journal.sequence !== root.journal.sequence + root.reservedRecords))) fail("corrupt");
542
+ facts.push(fact); phase = fact.phase;
543
+ }
544
+ return { phase, facts, pending, ...(pendingPhase ? { pendingPhase } : {}) };
545
+ }
546
+ function referencedDecision(p: Paths, root: PlacementPublicationRoot, descriptor: PlacementPublicationChunkDescriptor) {
547
+ const attempt = descriptor.ownerAttemptHash!;
548
+ const archived = p.window.catalog.get(attempt), dir = archived?.dir ?? p.dir, stem = `publication-${attempt}-`;
549
+ const rootBytes = readOwned(join(dir, stem + "root.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
550
+ if (archived) { const member = archived.members.find(value => value.name === stem + "root.json"); if (!member || !rootBytes || member.size !== rootBytes.length || member.sha256 !== digest(rootBytes)) fail("corrupt"); }
551
+ const owner = decode(rootBytes, validatePlacementPublicationRoot);
552
+ if (owner.seal !== attempt || owner.schema !== PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA || owner.epochHash !== root.epochHash || owner.generation !== root.generation || owner.homeHash !== root.homeHash || owner.journal.sequence >= root.journal.sequence) fail("corrupt");
553
+ const allowed = new Set(publicationFileNames(owner));
554
+ if (archived && [...allowed].some(name => !archived.members.some(member => member.name === name))) fail("corrupt");
555
+ const facts = publicationFacts(dir, stem, owner, archived?.members), completed = facts.facts.find(fact => fact.phase === "completed");
556
+ if (facts.phase !== "completed" || facts.pending || !completed || completed.outcome !== "committed" || completed.journal.sequence > root.journal.sequence) fail("corrupt");
557
+ const matches = owner.chunks.filter(c => c.kind === "decisions" && !c.ownerAttemptHash && c.bucket === descriptor.bucket && c.hash === descriptor.hash && c.count === descriptor.count && c.bytes === descriptor.bytes);
558
+ if (matches.length !== 1) fail("corrupt");
559
+ const match = matches[0]!, name = `${stem}chunk-${String(match.index).padStart(5, "0")}.json`;
560
+ if (archived && !archived.members.some(member => member.name === name && member.sha256 === match.hash && member.size === match.bytes)) fail("corrupt");
561
+ const bytes = readOwned(join(dir, name), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES);
562
+ if (!bytes || bytes.length !== match.bytes || digest(bytes) !== match.hash) fail("corrupt");
563
+ const chunk = decodePlacementPublicationChunk(owner, match, decode(bytes, value => value));
564
+ return { ...chunk, index: descriptor.index };
565
+ }
526
566
  function publicationRead(p: Paths, attemptHash: string): PlacementPublicationStored {
527
567
  // #288: a completed publication frozen by a checkpoint resolves through the sealed catalog, never the live window.
528
568
  // Its members were content-verified by the resolver, so their sealed hashes stand in for the live stat stamps.
@@ -532,35 +572,24 @@ function publicationRead(p: Paths, attemptHash: string): PlacementPublicationSto
532
572
  : new Map([...inventory(p).files].map(([name, stat]) => [name, stamp(stat)]));
533
573
  const keyOf = (found: Map<string, string>) => canonicalJSON([dir, attemptHash, epochMetadataStamp(p), [...found].filter(([name]) => name === stem + "root.json" || name.startsWith(stem + "chunk-"))]);
534
574
  const key = keyOf(files);
535
- let bundle = publicationBundle?.key === key ? publicationBundle.bundle : undefined;
575
+ let bundle = publicationBundle?.key === key && publicationBundle.bundle.root.schema !== PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA ? publicationBundle.bundle : undefined;
536
576
  if (!bundle) {
537
577
  const root = decode(readOwned(join(dir, stem + "root.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementPublicationRoot);
578
+ if (root.schema === PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA && !placementDecisionReuseEnabled(p.home)) fail("corrupt");
538
579
  const epoch = decode(readOwned(join(p.epochDir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
539
580
  if (root.seal !== attemptHash || root.epochHash !== p.hash || root.generation !== epoch.generation || root.homeHash !== epoch.homeHash) fail("corrupt");
540
- const chunks = root.chunks.map(c => decode(readOwned(join(dir, `${stem}chunk-${String(c.index).padStart(5, "0")}.json`), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES), value => value));
581
+ const chunks = root.chunks.map(c => {
582
+ if (!c.ownerAttemptHash) return decodePlacementPublicationChunk(root, c, decode(readOwned(join(dir, `${stem}chunk-${String(c.index).padStart(5, "0")}.json`), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES), value => value));
583
+ return referencedDecision(p, root, c);
584
+ });
541
585
  bundle = freeze(validatePlacementPublicationBundle({ root, chunks }));
542
586
  const after = archived ? files : new Map([...inventory(p).files].map(([name, stat]) => [name, stamp(stat)]));
543
- if (keyOf(after) === key) publicationBundle = { key, bundle }; // Never cache bytes read across a concurrent change.
587
+ if (root.schema !== PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA && keyOf(after) === key) publicationBundle = { key, bundle }; // Never cache bytes read across a concurrent change.
544
588
  }
545
589
  const root = bundle.root, allowed = new Set(publicationFileNames(root));
546
590
  for (const name of files.keys()) if (name.startsWith(stem) && !allowed.has(name)) fail("corrupt");
547
591
  if (archived && [...allowed].some(name => !files.has(name))) fail("corrupt");
548
- const facts: PlacementPublicationFact[] = []; let phase: PlacementPublicationStored["phase"] = "prepared", pending = false, absent = false; let pendingPhase: PlacementPublicationFact["phase"] | undefined;
549
- for (const [index, suffix] of ["artifact", "intent", "receipt"].entries()) {
550
- const bytes = readOwned(join(dir, stem + suffix + ".json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
551
- if (bytes === undefined) fail("corrupt"); // Every future phase slot was reserved before root acknowledgement.
552
- if (!bytes.length) { absent = true; continue; }
553
- if (absent && (suffix !== "receipt" || pendingPhase)) fail("corrupt");
554
- if (bytes.at(-1) !== 10) { pending = true; pendingPhase = (["artifact-built", "publication-intent", "completed"] as const)[index]; absent = true; continue; }
555
- const fact = decode(bytes, validatePlacementPublicationFact), previous = facts.at(-1)?.seal ?? root.seal;
556
- if (fact.attemptHash !== attemptHash || fact.previousHash !== previous || fact.phase !== (["artifact-built", "publication-intent", "completed"] as const)[index]) fail("corrupt");
557
- const intentFact = facts.find(fact => fact.phase === "publication-intent");
558
- if (fact.phase === "publication-intent" && (fact.artifactFactHash !== previous || fact.policyHash !== root.policyHash || fact.policyCheckUnixMs !== root.policySnapshotUnixMs)
559
- || fact.phase === "completed" && (fact.intentFactHash !== (intentFact?.seal ?? null) || fact.journal.sequence < root.journal.sequence || fact.journal.sequence > root.journal.sequence + root.reservedRecords
560
- || fact.outcome === "committed" && (!intentFact || fact.journal.sequence !== root.journal.sequence + root.reservedRecords))) fail("corrupt");
561
- facts.push(fact); phase = fact.phase;
562
- }
563
- return { bundle, phase, facts, pending, ...(pendingPhase ? { pendingPhase } : {}) };
592
+ return { bundle, ...publicationFacts(dir, stem, root, archived?.members) };
564
593
  }
565
594
  function publicationRoots(p: Paths): string[] {
566
595
  const names = [...inventory(p).files.keys()].filter(publicationName), roots = names.filter(n => n.endsWith("-root.json"));
@@ -711,6 +740,43 @@ export function capturePlacementPublicationMetadata<T>(home: string, epochHash:
711
740
  export function readPlacementPublicationMetadata<T>(home: string, epochHash: string, work: (io: PlacementPublicationMetadataIO) => T): T {
712
741
  return capturePlacementPublicationMetadata(home, epochHash, work).value;
713
742
  }
743
+ export interface PlacementDecisionCandidate { root: PlacementPublicationRoot; facts: readonly PlacementPublicationFact[]; phase: PlacementPublicationStored["phase"]; pending: boolean }
744
+ /** Windows are newest first; the loader reads only roots and phase facts, never chunks. */
745
+ export async function latestDecisionOwners(windows: readonly (readonly string[])[], beforeSequence: number, targets: readonly PlacementRealm[], load: (attempt: string) => PlacementDecisionCandidate, pause: CooperativeYield = cooperativeYield()): Promise<PlacementDecisionOwner[]> {
746
+ const targetKey = canonicalJSON(targets.map(realm => canonicalJSON(realm)).sort());
747
+ for (const attempts of windows) {
748
+ let latest: PlacementDecisionCandidate | undefined, sequence = -1, ambiguous = false;
749
+ for (const attempt of attempts) {
750
+ await pause();
751
+ const candidate = load(attempt), root = candidate.root, completed = candidate.facts.find(fact => fact.phase === "completed");
752
+ if (candidate.phase !== "completed" || candidate.pending || !completed || completed.outcome !== "committed" || completed.journal.sequence > beforeSequence || root.journal.sequence >= beforeSequence || root.schema !== PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA
753
+ || canonicalJSON(root.targets.map(target => canonicalJSON(target.realm)).sort()) !== targetKey) continue;
754
+ if (completed.journal.sequence > sequence) { latest = candidate; sequence = completed.journal.sequence; ambiguous = false; }
755
+ else if (completed.journal.sequence === sequence && latest?.root.seal !== root.seal) ambiguous = true;
756
+ }
757
+ if (ambiguous) return [];
758
+ if (latest) return latest.root.chunks.flatMap(chunk => chunk.kind === "decisions" && typeof chunk.bucket === "string" ? [{ bucket: chunk.bucket, hash: chunk.hash, count: chunk.count, bytes: chunk.bytes, ownerAttemptHash: chunk.ownerAttemptHash ?? latest!.root.seal }] : []);
759
+ }
760
+ return [];
761
+ }
762
+ /** Candidate discovery validates root and receipt only; staging re-verifies each chosen physical chunk. */
763
+ export async function placementDecisionOwners(home: string, epochHash: string, beforeSequence: number, targets: readonly PlacementRealm[]): Promise<PlacementDecisionOwner[]> {
764
+ const p = protectedIO(() => paths(home, epochHash)), before = protectedIO(() => inventory(p).token), pause = cooperativeYield();
765
+ const grouped = new Map<number, string[]>();
766
+ for (const [attempt, entry] of p.window.catalog) { await pause(); const group = grouped.get(entry.window) ?? []; group.push(attempt); grouped.set(entry.window, group); }
767
+ const live = protectedIO(() => [...inventory(p).files.keys()].flatMap(name => /^publication-([a-f0-9]{64})-root\.json$/.exec(name)?.[1] ?? []));
768
+ grouped.set(p.window.window, live);
769
+ const epoch = protectedIO(() => decode(readOwned(join(p.epochDir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch));
770
+ const result = await latestDecisionOwners([...grouped].sort(([a], [b]) => b - a).map(([, attempts]) => attempts), beforeSequence, targets, attempt => protectedIO(() => {
771
+ const archived = p.window.catalog.get(attempt), dir = archived?.dir ?? p.dir, stem = `publication-${attempt}-`, bytes = readOwned(join(dir, stem + "root.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
772
+ if (archived) { const member = archived.members.find(value => value.name === stem + "root.json"); if (!member || !bytes || member.size !== bytes.length || member.sha256 !== digest(bytes)) fail("corrupt"); }
773
+ const root = decode(bytes, validatePlacementPublicationRoot);
774
+ if (root.seal !== attempt || root.epochHash !== epochHash || root.generation !== epoch.generation || root.homeHash !== epoch.homeHash) fail("corrupt");
775
+ return { root, ...publicationFacts(dir, stem, root, archived?.members) };
776
+ }), pause);
777
+ protectedIO(() => { if (inventory(p).token !== before) fail("changed"); });
778
+ return result;
779
+ }
714
780
  function assertPublicationActive(p: Paths): void {
715
781
  const epoch = decode(readOwned(join(p.epochDir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
716
782
  const profile = decode(readOwned(join(p.home, "profile.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementProfile);
@@ -0,0 +1,40 @@
1
+ /**
2
+ * #578 Q2 (owner choice c): the person-facing writer of the home opt-in for a sync-run placement checkpoint.
3
+ * `amem migrate --sync-placement --checkpoint-on-bound on|off` previews by default; `--confirm` read-modify-writes the
4
+ * machine `amem.config.json` in the memory home, preserving every other key, atomically and with mode 0600. A file that
5
+ * does not parse, or that the config reader refuses, is never rewritten. Hand-editing `syncPlacement.checkpointOnBound`
6
+ * stays valid; this command is only the reviewed way to change it. No actor gate (#431).
7
+ */
8
+ import { closeSync, constants, fsyncSync, lstatSync, openSync, readFileSync, renameSync, writeSync } from "node:fs";
9
+ import { randomBytes } from "node:crypto";
10
+ import { dirname, join } from "node:path";
11
+ import { loadAmemConfig, machineConfigPath } from "./config.ts";
12
+
13
+ export interface CheckpointOnBoundOptInChange { file: string; current: boolean; target: boolean; written: boolean; text: string }
14
+
15
+ export function checkpointOnBoundOptInChange(home: string, target: boolean, confirm: boolean): CheckpointOnBoundOptInChange {
16
+ const file = machineConfigPath(home);
17
+ // The reader is the validator: an unknown key, a bad value, a link or an oversized file refuses before anything is written.
18
+ const current = loadAmemConfig(home).config.syncPlacement?.checkpointOnBound === true;
19
+ const command = `amem migrate --sync-placement --checkpoint-on-bound ${target ? "on" : "off"} --confirm`;
20
+ if (!confirm) return { file, current, target, written: false,
21
+ text: `sync-run placement checkpoint opt-in: ${current ? "on" : "off"} -> ${target ? "on" : "off"} in ${file}; preview only, run ${command} to write it` };
22
+ if (current === target) return { file, current, target, written: false, text: `sync-run placement checkpoint opt-in: already ${target ? "on" : "off"}; nothing written` };
23
+ let body: Record<string, unknown> = {};
24
+ const stat = lstatSync(file, { throwIfNoEntry: false });
25
+ if (stat) {
26
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
27
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(`${file}: is not a JSON object; nothing written`);
28
+ body = parsed as Record<string, unknown>;
29
+ if (typeof body.home === "string") throw new Error(`${file}: names a home, so it is only a pointer; set the opt-in in that home's config; nothing written`);
30
+ }
31
+ const prior = body.syncPlacement && typeof body.syncPlacement === "object" && !Array.isArray(body.syncPlacement) ? body.syncPlacement as Record<string, unknown> : {};
32
+ const next = { ...body, syncPlacement: { ...prior, checkpointOnBound: target } };
33
+ const temp = join(dirname(file), `.amem.config.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
34
+ const fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
35
+ try { writeSync(fd, JSON.stringify(next, null, 2) + "\n"); fsyncSync(fd); } finally { closeSync(fd); }
36
+ renameSync(temp, file);
37
+ // Re-read through the validator so a written file is always one the reader accepts.
38
+ if (loadAmemConfig(home).config.syncPlacement?.checkpointOnBound !== target) throw new Error(`${file}: the written opt-in did not read back`);
39
+ return { file, current, target, written: true, text: `sync-run placement checkpoint opt-in: ${target ? "on" : "off"} written to ${file}` };
40
+ }
@@ -2,11 +2,17 @@
2
2
  import { types } from "node:util";
3
3
  import { createHash } from "node:crypto";
4
4
  import { canonicalJSON, hashJSON } from "./generation.ts";
5
+ import { readFormatFloors, formatVersionBelow } from "./formats.ts";
5
6
  import { validatePlacementKey, placementKeyId, SyncPlacementJournalError, PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS,
6
7
  PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, PLACEMENT_JOURNAL_ROOT_MAX_BYTES, type PlacementKey, type PlacementRealm, type PlacementHoldReason } from "./sync-placement-journal-format.ts";
7
8
  import { drainSteps, drainStepsAsync, type CooperativeYield } from "./sync-placement-yield.ts";
8
9
 
9
10
  export const PLACEMENT_PUBLICATION_PLAN_SCHEMA = "agent-mem.sync-placement-publication-plan/v1";
11
+ export const PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA = "agent-mem.sync-placement-publication-plan/v2";
12
+ export const PLACEMENT_DECISION_CHUNK_V2_SCHEMA = "agent-mem.sync-placement-decision-chunk/v2";
13
+ export function placementDecisionReuseEnabled(home: string): boolean {
14
+ return !!readFormatFloors(home)?.some(floor => floor.surface === "home" && !formatVersionBelow(floor.minReader, "0.36.0"));
15
+ }
10
16
  export const PLACEMENT_PUBLICATION_CHUNK_SCHEMA = "agent-mem.sync-placement-publication-chunk/v1";
11
17
  export const PLACEMENT_PUBLICATION_FACT_SCHEMA = "agent-mem.sync-placement-publication-fact/v1";
12
18
  /** Closed hold/outcome events fit this bound; reserve future journal capacity before any publication effect. */
@@ -25,11 +31,12 @@ export interface PlacementPublicationTarget {
25
31
  }
26
32
  export type PlacementPublicationChunkKind = "sources" | "decisions" | "objects";
27
33
  export interface PlacementPublicationChunk { schema: typeof PLACEMENT_PUBLICATION_CHUNK_SCHEMA; kind: PlacementPublicationChunkKind; index: number; items: (PlacementPublicationSource | PlacementPublicationDecision | PlacementPublicationObject)[] }
34
+ export interface PlacementPublicationChunkDescriptor { kind: PlacementPublicationChunkKind; index: number; hash: string; count: number; bytes: number; bucket?: string | null; ownerAttemptHash?: string | null }
28
35
  export interface PlacementPublicationRoot {
29
- schema: typeof PLACEMENT_PUBLICATION_PLAN_SCHEMA; epochHash: string; generation: string; homeHash: string; contextHash: string;
36
+ schema: typeof PLACEMENT_PUBLICATION_PLAN_SCHEMA | typeof PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA; epochHash: string; generation: string; homeHash: string; contextHash: string;
30
37
  markerHash: string; sourceHash: string; aliasesHash: string; policyHash: string; remoteHash: string;
31
38
  journal: { sequence: number; headHash: string }; reservedRecords: number; reservedRecordBytes: number[]; createdUnixSeconds: number; policySnapshotUnixMs: number;
32
- targets: PlacementPublicationTarget[]; chunks: { kind: PlacementPublicationChunkKind; index: number; hash: string; count: number; bytes: number }[]; seal: string;
39
+ targets: PlacementPublicationTarget[]; chunks: PlacementPublicationChunkDescriptor[]; seal: string;
33
40
  }
34
41
  export interface PlacementPublicationBundle { root: PlacementPublicationRoot; chunks: PlacementPublicationChunk[] }
35
42
  export type PlacementPublicationFact = {
@@ -42,6 +49,38 @@ const kinds: readonly PlacementPublicationChunkKind[] = ["sources", "decisions",
42
49
  const fail = (code: "invalid" | "bound" | "corrupt" = "invalid"): never => { throw new SyncPlacementJournalError(code); };
43
50
  export const publicationBytes = (value: unknown): Buffer => Buffer.from(canonicalJSON(value) + "\n");
44
51
  export const publicationHash = (bytes: Uint8Array): string => createHash("sha256").update(bytes).digest("hex");
52
+ export interface PlacementDecisionLeaf { bucket: string; items: PlacementPublicationDecision[] }
53
+ /** Stable hash-prefix leaves for v2 decisions; insertion only affects its leaf unless it must split. */
54
+ export function partitionPlacementDecisions(decisions: readonly PlacementPublicationDecision[]): PlacementDecisionLeaf[] {
55
+ return drainSteps(partitionPlacementDecisionSteps(decisions));
56
+ }
57
+ function* partitionPlacementDecisionSteps(decisions: readonly PlacementPublicationDecision[]): Generator<void, PlacementDecisionLeaf[], void> {
58
+ const entries: { id: string; bits: string; decision: PlacementPublicationDecision }[] = [];
59
+ for (const [index, value] of array(decisions, PLACEMENT_JOURNAL_MAX_RECORDS).entries()) {
60
+ if (index && index % 64 === 0) yield;
61
+ const decision = item("decisions", value) as PlacementPublicationDecision;
62
+ const id = placementKeyId(decision.key);
63
+ const bits = [...id].map(digit => parseInt(digit, 16).toString(2).padStart(4, "0")).join("");
64
+ entries.push({ id, bits, decision });
65
+ }
66
+ entries.sort((a, b) => a.id.localeCompare(b.id));
67
+ if (new Set(entries.map(entry => entry.id)).size !== entries.length) return fail();
68
+ const leaves: PlacementDecisionLeaf[] = [];
69
+ const split = function* (prefix: string, values: typeof entries): Generator<void, void, void> {
70
+ if (!values.length) return;
71
+ yield;
72
+ const items = values.map(value => value.decision);
73
+ const bytes = publicationBytes({ schema: PLACEMENT_DECISION_CHUNK_V2_SCHEMA, bucket: prefix, items });
74
+ if (bytes.length <= PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) {
75
+ leaves.push({ bucket: prefix, items }); return;
76
+ }
77
+ if (prefix.length >= 256) return fail("bound");
78
+ yield* split(prefix + "0", values.filter(value => value.bits[prefix.length] === "0"));
79
+ yield* split(prefix + "1", values.filter(value => value.bits[prefix.length] === "1"));
80
+ };
81
+ yield* split("", entries);
82
+ return leaves;
83
+ }
45
84
  function hex(value: unknown, size = 64): value is string { return typeof value === "string" && value.length === size && /^[a-f0-9]+$/.test(value); }
46
85
  function number(value: unknown, maximum = Number.MAX_SAFE_INTEGER): value is number { return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= maximum; }
47
86
  /** Descriptor-only shallow access keeps multi-chunk inputs bounded without the policy snapshot's 4096-node ceiling. */
@@ -94,15 +133,32 @@ function item(kind: PlacementPublicationChunkKind, input: unknown): PlacementPub
94
133
  return { targetIndex: v.targetIndex, type: v.type as PlacementPublicationObject["type"], path: v.path as string | null, oid: v.oid, sha256: v.sha256, size: v.size };
95
134
  }
96
135
  export function validatePlacementPublicationChunk(input: unknown): PlacementPublicationChunk {
136
+ return validatePublicationChunk(input, PLACEMENT_JOURNAL_CHUNK_MAX_BYTES);
137
+ }
138
+ function validatePublicationChunk(input: unknown, maximum: number): PlacementPublicationChunk {
97
139
  const v = object(input, ["schema", "kind", "index", "items"]);
98
140
  if (v.schema !== PLACEMENT_PUBLICATION_CHUNK_SCHEMA || !kinds.includes(v.kind as PlacementPublicationChunkKind) || !number(v.index, PLACEMENT_JOURNAL_MAX_OBJECTS - 1)) return fail();
99
141
  const items = array(v.items, PLACEMENT_JOURNAL_MAX_RECORDS).map(x => item(v.kind as PlacementPublicationChunkKind, x)); if (!items.length) return fail();
100
- return bounded({ schema: PLACEMENT_PUBLICATION_CHUNK_SCHEMA, kind: v.kind as PlacementPublicationChunkKind, index: v.index, items }, PLACEMENT_JOURNAL_CHUNK_MAX_BYTES);
142
+ return bounded({ schema: PLACEMENT_PUBLICATION_CHUNK_SCHEMA, kind: v.kind as PlacementPublicationChunkKind, index: v.index, items }, maximum);
143
+ }
144
+ /** V2 decision content is independent of its position in a publication. */
145
+ export function placementPublicationChunkBytes(root: PlacementPublicationRoot, chunk: PlacementPublicationChunk): Buffer {
146
+ const descriptor = root.chunks[chunk.index];
147
+ if (!descriptor || descriptor.kind !== chunk.kind) return fail();
148
+ return root.schema === PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA && chunk.kind === "decisions"
149
+ ? publicationBytes({ schema: PLACEMENT_DECISION_CHUNK_V2_SCHEMA, bucket: descriptor.bucket, items: chunk.items })
150
+ : publicationBytes(chunk);
151
+ }
152
+ export function decodePlacementPublicationChunk(root: PlacementPublicationRoot, descriptor: PlacementPublicationChunkDescriptor, value: unknown): PlacementPublicationChunk {
153
+ if (root.schema !== PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA || descriptor.kind !== "decisions") return validatePlacementPublicationChunk(value);
154
+ const v = object(value, ["schema", "bucket", "items"]);
155
+ if (v.schema !== PLACEMENT_DECISION_CHUNK_V2_SCHEMA || v.bucket !== descriptor.bucket) return fail("corrupt");
156
+ return validatePublicationChunk({ schema: PLACEMENT_PUBLICATION_CHUNK_SCHEMA, kind: "decisions", index: descriptor.index, items: v.items }, PLACEMENT_JOURNAL_CHUNK_MAX_BYTES + 256);
101
157
  }
102
158
  function normalizedRoot(input: unknown, checkSeal = true): PlacementPublicationRoot {
103
159
  const keys = ["schema", "epochHash", "generation", "homeHash", "contextHash", "markerHash", "sourceHash", "aliasesHash", "policyHash", "remoteHash", "journal", "reservedRecords", "reservedRecordBytes", "createdUnixSeconds", "policySnapshotUnixMs", "targets", "chunks", "seal"];
104
160
  const v = object(input, keys);
105
- if (v.schema !== PLACEMENT_PUBLICATION_PLAN_SCHEMA || !hex(v.generation, 32) || ![v.epochHash, v.homeHash, v.contextHash, v.markerHash, v.sourceHash, v.aliasesHash, v.policyHash, v.remoteHash, v.seal].every(x => hex(x))
161
+ if (![PLACEMENT_PUBLICATION_PLAN_SCHEMA, PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA].includes(v.schema as string) || !hex(v.generation, 32) || ![v.epochHash, v.homeHash, v.contextHash, v.markerHash, v.sourceHash, v.aliasesHash, v.policyHash, v.remoteHash, v.seal].every(x => hex(x))
106
162
  || !number(v.reservedRecords, PLACEMENT_JOURNAL_MAX_RECORDS) || !number(v.createdUnixSeconds) || !number(v.policySnapshotUnixMs)) return fail();
107
163
  const reservedRecordBytes = array(v.reservedRecordBytes, PLACEMENT_JOURNAL_MAX_RECORDS);
108
164
  if (reservedRecordBytes.length !== v.reservedRecords || reservedRecordBytes.some(x => !number(x, PLACEMENT_PUBLICATION_RECORD_MAX_BYTES) || x < 1)) return fail();
@@ -119,27 +175,42 @@ function normalizedRoot(input: unknown, checkSeal = true): PlacementPublicationR
119
175
  if (!targets.length || new Set(targets.map(t => canonicalJSON(t.realm))).size !== targets.length || new Set(targets.map(t => t.refHash)).size !== targets.length) return fail();
120
176
  let lastKind = 0;
121
177
  const chunks = array(v.chunks, PLACEMENT_JOURNAL_MAX_OBJECTS - 1).map((x, index) => {
122
- const c = object(x, ["kind", "index", "hash", "count", "bytes"]), kindIndex = kinds.indexOf(c.kind as PlacementPublicationChunkKind);
178
+ const v2 = v.schema === PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA;
179
+ const c = object(x, v2 ? ["kind", "index", "hash", "count", "bytes", "bucket", "ownerAttemptHash"] : ["kind", "index", "hash", "count", "bytes"]), kindIndex = kinds.indexOf(c.kind as PlacementPublicationChunkKind);
123
180
  if (kindIndex < lastKind || kindIndex < 0 || c.index !== index || !hex(c.hash) || !number(c.count, PLACEMENT_JOURNAL_MAX_RECORDS) || c.count < 1 || !number(c.bytes, PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) || c.bytes < 1) return fail();
124
- lastKind = kindIndex; return { kind: c.kind as PlacementPublicationChunkKind, index, hash: c.hash, count: c.count, bytes: c.bytes };
181
+ if (v2 && (c.kind === "decisions" ? typeof c.bucket !== "string" || !/^[01]{0,256}$/.test(c.bucket) : c.bucket !== null || c.ownerAttemptHash !== null)) return fail();
182
+ if (v2 && c.ownerAttemptHash !== null && !hex(c.ownerAttemptHash)) return fail();
183
+ lastKind = kindIndex; return { kind: c.kind as PlacementPublicationChunkKind, index, hash: c.hash, count: c.count, bytes: c.bytes,
184
+ ...(v2 ? { bucket: c.bucket as string | null, ownerAttemptHash: c.ownerAttemptHash as string | null } : {}) };
125
185
  });
186
+ if (v.schema === PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA) {
187
+ const buckets = chunks.filter(c => c.kind === "decisions").map(c => c.bucket!);
188
+ if (buckets.some((bucket, i) => typeof bucket !== "string" || buckets.some((other, j) => i !== j && other!.startsWith(bucket)))) return fail();
189
+ if (chunks.some(chunk => chunk.ownerAttemptHash === v.seal)) return fail("corrupt");
190
+ }
126
191
  const normalized = { ...v, journal, targets, chunks, reservedRecordBytes } as unknown as PlacementPublicationRoot;
127
192
  const { seal, ...body } = normalized; if (checkSeal && hashJSON(body) !== seal) return fail("corrupt");
128
193
  return bounded(normalized, PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
129
194
  }
130
195
  export function validatePlacementPublicationRoot(input: unknown): PlacementPublicationRoot { return normalizedRoot(input); }
131
196
  export function validatePlacementPublicationBundle(input: unknown): PlacementPublicationBundle {
132
- const v = object(input, ["root", "chunks"]), root = validatePlacementPublicationRoot(v.root), chunks = array(v.chunks, PLACEMENT_JOURNAL_MAX_OBJECTS - 1).map(validatePlacementPublicationChunk);
197
+ const v = object(input, ["root", "chunks"]), root = validatePlacementPublicationRoot(v.root), chunks = array(v.chunks, PLACEMENT_JOURNAL_MAX_OBJECTS - 1).map((chunk, index) =>
198
+ root.schema === PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA && root.chunks[index]?.kind === "decisions" ? validatePublicationChunk(chunk, PLACEMENT_JOURNAL_CHUNK_MAX_BYTES + 256) : validatePlacementPublicationChunk(chunk));
133
199
  if (chunks.length !== root.chunks.length) return fail("corrupt");
134
200
  let sourceBytes = 0; const totals = { sources: 0, decisions: 0, objects: 0 }, seen = new Set<string>();
135
201
  for (const [index, chunk] of chunks.entries()) {
136
- const expected = root.chunks[index]!, bytes = publicationBytes(chunk);
202
+ const expected = root.chunks[index]!, bytes = placementPublicationChunkBytes(root, chunk);
137
203
  if (chunk.index !== index || chunk.kind !== expected.kind || chunk.items.length !== expected.count || bytes.length !== expected.bytes || publicationHash(bytes) !== expected.hash) return fail("corrupt");
138
204
  totals[chunk.kind] += chunk.items.length; if (totals[chunk.kind] > PLACEMENT_JOURNAL_MAX_RECORDS) return fail("bound");
139
205
  for (const row of chunk.items) {
140
206
  let identity: string;
141
207
  if (chunk.kind === "sources") { const s = row as PlacementPublicationSource; sourceBytes += s.byteLength; identity = canonicalJSON([s.realm, s.source, s.pathHash]); }
142
- else if (chunk.kind === "decisions") { const d = row as PlacementPublicationDecision; identity = canonicalJSON([d.key.realm, d.key.id]); }
208
+ else if (chunk.kind === "decisions") { const d = row as PlacementPublicationDecision; identity = canonicalJSON([d.key.realm, d.key.id]);
209
+ if (root.schema === PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA) {
210
+ const bits = [...placementKeyId(d.key)].map(digit => parseInt(digit, 16).toString(2).padStart(4, "0")).join("");
211
+ if (!bits.startsWith(expected.bucket!)) return fail("corrupt");
212
+ }
213
+ }
143
214
  else { const o = row as PlacementPublicationObject; if (o.targetIndex >= root.targets.length || !root.targets[o.targetIndex]!.publish) return fail(); identity = canonicalJSON([o.targetIndex, o.type, o.path]); }
144
215
  const key = chunk.kind + identity; if (seen.has(key)) return fail(); seen.add(key);
145
216
  }
@@ -159,6 +230,40 @@ export async function planPlacementPublicationAsync(input: Omit<PlacementPublica
159
230
  }, yieldPoint?: CooperativeYield): Promise<PlacementPublicationBundle> {
160
231
  return await drainStepsAsync(planSteps(input, items), yieldPoint);
161
232
  }
233
+ export interface PlacementDecisionOwner { bucket: string; hash: string; count: number; bytes: number; ownerAttemptHash: string }
234
+ /** Build a v2 plan using only content-exact, already verified physical owners. */
235
+ export function planPlacementPublicationV2(input: Omit<PlacementPublicationRoot, "schema" | "chunks" | "seal">, items: {
236
+ sources: readonly PlacementPublicationSource[]; decisions: readonly PlacementPublicationDecision[]; objects: readonly PlacementPublicationObject[];
237
+ }, owners: readonly PlacementDecisionOwner[]): PlacementPublicationBundle {
238
+ return buildPlacementPublicationV2(planPlacementPublication(input, items), items, owners);
239
+ }
240
+ export async function planPlacementPublicationV2Async(input: Omit<PlacementPublicationRoot, "schema" | "chunks" | "seal">, items: {
241
+ sources: readonly PlacementPublicationSource[]; decisions: readonly PlacementPublicationDecision[]; objects: readonly PlacementPublicationObject[];
242
+ }, owners: readonly PlacementDecisionOwner[], yieldPoint?: CooperativeYield): Promise<PlacementPublicationBundle> {
243
+ const original = await planPlacementPublicationAsync(input, items, yieldPoint);
244
+ const decisions = array(object(items, kinds).decisions, PLACEMENT_JOURNAL_MAX_RECORDS) as PlacementPublicationDecision[];
245
+ const leaves = await drainStepsAsync(partitionPlacementDecisionSteps(decisions), yieldPoint);
246
+ return buildPlacementPublicationV2(original, items, owners, leaves);
247
+ }
248
+ function buildPlacementPublicationV2(original: PlacementPublicationBundle, items: {
249
+ sources: readonly PlacementPublicationSource[]; decisions: readonly PlacementPublicationDecision[]; objects: readonly PlacementPublicationObject[];
250
+ }, owners: readonly PlacementDecisionOwner[], partition?: PlacementDecisionLeaf[]): PlacementPublicationBundle {
251
+ const sources = original.chunks.filter(chunk => chunk.kind === "sources"), objects = original.chunks.filter(chunk => chunk.kind === "objects");
252
+ const decisions = array(object(items, kinds).decisions, PLACEMENT_JOURNAL_MAX_RECORDS) as PlacementPublicationDecision[];
253
+ const leaves = partition ?? partitionPlacementDecisions(decisions);
254
+ const chunks: PlacementPublicationChunk[] = [...sources, ...leaves.map(leaf => ({ schema: PLACEMENT_PUBLICATION_CHUNK_SCHEMA as typeof PLACEMENT_PUBLICATION_CHUNK_SCHEMA, kind: "decisions" as const, index: 0, items: leaf.items })), ...objects]
255
+ .map((chunk, index) => ({ ...chunk, index }));
256
+ const descriptors: PlacementPublicationChunkDescriptor[] = chunks.map((chunk, index) => {
257
+ const bucket = chunk.kind === "decisions" ? leaves[index - sources.length]!.bucket : null;
258
+ const bytes = chunk.kind === "decisions" ? publicationBytes({ schema: PLACEMENT_DECISION_CHUNK_V2_SCHEMA, bucket, items: chunk.items }) : publicationBytes(chunk);
259
+ const hash = publicationHash(bytes);
260
+ const owner = chunk.kind === "decisions" ? owners.find(candidate => candidate.bucket === bucket && candidate.hash === hash && candidate.bytes === bytes.length && candidate.count === chunk.items.length && hex(candidate.ownerAttemptHash)) : undefined;
261
+ return { kind: chunk.kind, index, hash, count: chunk.items.length, bytes: bytes.length, bucket, ownerAttemptHash: owner?.ownerAttemptHash ?? null };
262
+ });
263
+ const { schema: _schema, chunks: _chunks, seal: _seal, ...body } = original.root;
264
+ const rootBody = { ...body, schema: PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA, chunks: descriptors };
265
+ return validatePlacementPublicationBundle({ root: { ...rootBody, seal: hashJSON(rootBody) }, chunks });
266
+ }
162
267
  /** Items between step boundaries: at most 64 canonicalized chunk items per uninterrupted stretch. */
163
268
  const STEP_ITEMS = 64;
164
269
  function* planSteps(input: Omit<PlacementPublicationRoot, "schema" | "chunks" | "seal">, items: {
@@ -208,5 +313,5 @@ function normalizedFact(input: unknown, checkSeal = true): PlacementPublicationF
208
313
  export function validatePlacementPublicationFact(input: unknown): PlacementPublicationFact { return normalizedFact(input); }
209
314
  export function publicationFileNames(root: PlacementPublicationRoot): string[] {
210
315
  const stem = `publication-${root.seal}-`;
211
- return [`${stem}root.json`, ...root.chunks.map(c => `${stem}chunk-${String(c.index).padStart(5, "0")}.json`), `${stem}artifact.json`, `${stem}intent.json`, `${stem}receipt.json`];
316
+ return [`${stem}root.json`, ...root.chunks.filter(c => !c.ownerAttemptHash).map(c => `${stem}chunk-${String(c.index).padStart(5, "0")}.json`), `${stem}artifact.json`, `${stem}intent.json`, `${stem}receipt.json`];
212
317
  }
@@ -2,7 +2,7 @@
2
2
  import { canonicalJSON } from "./generation.ts";
3
3
  import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
4
4
  import { withPlacementPublicationMetadata, readPlacementPublicationMetadata, type PlacementStorageOptions, type PlacementPublicationStored } from "./sync-placement-journal-storage.ts";
5
- import { validatePlacementPublicationBundle, createPlacementPublicationFact, publicationFileNames, publicationBytes,
5
+ import { validatePlacementPublicationBundle, createPlacementPublicationFact, publicationFileNames, publicationBytes, placementPublicationChunkBytes, placementDecisionReuseEnabled, PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA,
6
6
  type PlacementPublicationBundle, type PlacementPublicationPhase, type PlacementPublicationFact } from "./sync-placement-publication-plan.ts";
7
7
 
8
8
  function fail(code: "invalid" | "pending" | "conflict" | "changed" = "invalid"): never { throw new SyncPlacementJournalError(code); }
@@ -11,6 +11,7 @@ const validHash = (value: string) => typeof value === "string" && value.length =
11
11
  /** No timestamp expiry or eviction: retained plans remain charged to the epoch's shared 256-object inventory. */
12
12
  export function preparePlacementPublication(home: string, input: PlacementPublicationBundle, opts: PlacementStorageOptions): { attemptHash: string } {
13
13
  const bundle = validatePlacementPublicationBundle(input), root = bundle.root, names = publicationFileNames(root);
14
+ if (root.schema === PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA && !placementDecisionReuseEnabled(home)) throw new Error("Decision chunk reuse requires a home format floor of 0.36.0; upgrade all writers, preview amem formats raise home 0.36.0, then confirm the approved command.");
14
15
  const required = readPlacementPublicationMetadata(home, root.epochHash, io => [...names, ...io.reservedJournalNames(root)]);
15
16
  return withPlacementPublicationMetadata(home, root.epochHash, opts, required, io => {
16
17
  const journal = io.journal();
@@ -22,12 +23,22 @@ export function preparePlacementPublication(home: string, input: PlacementPublic
22
23
  const other = io.publication(match[1]!); if (other.phase !== "completed" || other.pending) fail("pending");
23
24
  }
24
25
  for (const name of io.names()) if (name.startsWith(own) && !names.includes(name)) fail("conflict");
26
+ const verifyReferences = () => {
27
+ for (const descriptor of root.chunks) if (descriptor.ownerAttemptHash) {
28
+ const owner = io.publication(descriptor.ownerAttemptHash), completed = owner.facts.find(fact => fact.phase === "completed");
29
+ if (owner.phase !== "completed" || owner.pending || !completed || completed.outcome !== "committed" || completed.journal.sequence > root.journal.sequence || owner.bundle.root.journal.sequence >= root.journal.sequence) fail("changed");
30
+ const found = owner.bundle.root.chunks.filter(c => c.kind === "decisions" && !c.ownerAttemptHash && c.bucket === descriptor.bucket && c.hash === descriptor.hash && c.count === descriptor.count && c.bytes === descriptor.bytes);
31
+ if (found.length !== 1 || !placementPublicationChunkBytes(owner.bundle.root, owner.bundle.chunks[found[0]!.index]!).equals(placementPublicationChunkBytes(root, bundle.chunks[descriptor.index]!))) fail("changed");
32
+ }
33
+ };
34
+ verifyReferences();
25
35
  // Reserve every future phase file physically. A later journal append cannot consume these object slots.
26
36
  for (const suffix of ["artifact", "intent", "receipt"]) {
27
37
  const name = `${own}${suffix}.json`;
28
38
  if (io.read(name) === undefined) io.complete(name, Buffer.alloc(0), "publication-slot-written", "publication-slot-fsync");
29
39
  }
30
- for (const chunk of bundle.chunks) io.complete(`${own}chunk-${String(chunk.index).padStart(5, "0")}.json`, publicationBytes(chunk), "publication-chunk-written", "publication-chunk-fsync");
40
+ for (const chunk of bundle.chunks) if (!root.chunks[chunk.index]!.ownerAttemptHash) io.complete(`${own}chunk-${String(chunk.index).padStart(5, "0")}.json`, placementPublicationChunkBytes(root, chunk), "publication-chunk-written", "publication-chunk-fsync");
41
+ verifyReferences();
31
42
  // The root is the final durability acknowledgement: all chunks and all reserved slots precede its fsync.
32
43
  io.complete(`${own}root.json`, publicationBytes(root), "publication-root-written", "publication-root-fsync");
33
44
  io.check(); const done = io.publication(root.seal);
@@ -20,10 +20,10 @@ import type { PlannedGitObject } from "./sync-placement-git.ts";
20
20
  import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, SyncPlacementFormatError } from "./sync-placement-format.ts";
21
21
  import { PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS, createPlacementRecord, placementKeyId, type PlacementEvent, type PlacementRealm, type PlacementRecord } from "./sync-placement-journal-format.ts";
22
22
  import { rebuildPlacementProjection, type PlacementProjection } from "./sync-placement-projection.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
+ import { readPlacementJournal, readPlacementWriterJournalAnchors, placementWriterJournalToken, appendPlacementEvent, appendPlacementEvents, releasePlacementStorageCaches, ensurePlacementPublicationDurability, readPlacementPublicationMetadata, placementDecisionOwners, placementJournalObjectComposition, placementJournalObjectCompositionText, type PlacementJournalObjectComposition, type PlacementJournalRead, type PlacementStorageOptions } from "./sync-placement-journal-storage.ts";
24
24
  import { formatFloorAtLeast } from "./formats.ts";
25
25
  import { preparePlacementPublication, readPlacementPublication, recordPlacementPublicationPhase, type PlacementPublicationRead } from "./sync-placement-publication-storage.ts";
26
- import { planPlacementPublication, planPlacementPublicationAsync, publicationBytes, publicationFileNames, type PlacementPublicationBundle, type PlacementPublicationDecision, type PlacementPublicationObject } from "./sync-placement-publication-plan.ts";
26
+ import { planPlacementPublication, planPlacementPublicationAsync, planPlacementPublicationV2Async, placementDecisionReuseEnabled, PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA, publicationBytes, publicationFileNames, type PlacementPublicationBundle, type PlacementPublicationDecision, type PlacementPublicationSource, type PlacementPublicationObject } from "./sync-placement-publication-plan.ts";
27
27
  import { placementPublicationEventSteps } from "./sync-placement-publication-events.ts";
28
28
  import { ShardHistoryAuditor, type ShardHistory } from "./shard-sync-history.ts";
29
29
  import { ShardSyncApplications } from "./shard-sync-applications.ts";
@@ -470,7 +470,10 @@ class PlacementTransport {
470
470
  sourceHash:capture.context.sourceHash,aliasesHash:capture.context.aliasesHash,policyHash:capture.context.policyHash,remoteHash:digest(this.url),
471
471
  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[]};
472
472
  const planPause=cooperativeYield();
473
- let bundle=await planPlacementPublicationAsync(body,{sources:capture.prefixes,decisions,objects},planPause);
473
+ const v2 = frozen ? frozen.root.schema === PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA : placementDecisionReuseEnabled(this.home);
474
+ const owners = v2 ? frozen ? frozen.root.chunks.filter(c => c.kind === "decisions" && c.ownerAttemptHash && typeof c.bucket === "string").map(c => ({ bucket: c.bucket!, hash: c.hash, count: c.count, bytes: c.bytes, ownerAttemptHash: c.ownerAttemptHash! })) : await placementDecisionOwners(this.home, this.epochHash, body.journal.sequence, body.targets.map(target => target.realm)) : [];
475
+ const items = {sources:capture.prefixes,decisions,objects};
476
+ let bundle=v2 ? await planPlacementPublicationV2Async(body,items,owners,planPause) : await planPlacementPublicationAsync(body,items,planPause);
474
477
  await yieldTurn(); // #462: planning is pure; each step gets its own turn
475
478
  let scheduled=await this.eventsAsync(bundle,projection,old,planPause);
476
479
  await yieldTurn();
@@ -480,7 +483,7 @@ class PlacementTransport {
480
483
  const lengths:number[]=[],pause=cooperativeYield();
481
484
  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);}
482
485
  await yieldTurn();
483
- bundle=await planPlacementPublicationAsync({...body,reservedRecords:lengths.length,reservedRecordBytes:lengths},{sources:capture.prefixes,decisions,objects},planPause);
486
+ bundle=v2 ? await planPlacementPublicationV2Async({...body,reservedRecords:lengths.length,reservedRecordBytes:lengths},items,owners,planPause) : await planPlacementPublicationAsync({...body,reservedRecords:lengths.length,reservedRecordBytes:lengths},items,planPause);
484
487
  await yieldTurn();
485
488
  scheduled=await this.eventsAsync(bundle,projection,old,planPause);
486
489
  if(frozen&&canonicalJSON(bundle)!==canonicalJSON(frozen))refuse();
@@ -733,7 +736,17 @@ class PlacementTransport {
733
736
  const material=await this.materialize(retained?.bundle.root.createdUnixSeconds??Math.floor(Date.now()/1000),frontier,retained?.bundle);
734
737
  const changed=material.bundle.root.targets.some((target,index)=>target.publish&&target.commit!==(this.targets[index]!.remote??null));
735
738
  // Nothing durable exists for a fresh attempt yet: an epoch without room for this plan refuses here, typed.
736
- await yieldTurn();if(!retained&&(material.events.length||changed))this.assertPlanCapacity(material.bundle);
739
+ await yieldTurn();if(!retained&&(material.events.length||changed)) {
740
+ try { this.assertPlanCapacity(material.bundle); }
741
+ catch (error) {
742
+ if (!(error instanceof PlacementSyncBoundError) || error.bound.kind !== "journal-objects" || material.bundle.root.schema !== PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA) throw error;
743
+ const {schema:_schema,chunks:_chunks,seal:_seal,...body} = material.bundle.root;
744
+ const byKind = (kind: "sources" | "decisions" | "objects") => material.bundle.chunks.filter(chunk => chunk.kind === kind).flatMap(chunk => chunk.items);
745
+ const fallback = planPlacementPublication(body, {sources:byKind("sources") as PlacementPublicationSource[], decisions:byKind("decisions") as PlacementPublicationDecision[], objects:byKind("objects") as PlacementPublicationObject[]});
746
+ this.assertPlanCapacity(fallback); material.bundle = fallback;
747
+ Object.assign(material, this.events(fallback, material.projection, material.old));
748
+ }
749
+ }
737
750
  this.current=material;this.attemptHash=material.bundle.root.seal;
738
751
  await yieldTurn();const applications=await this.applicationCoordinator();await applications.prepare();
739
752
  if(!retained&&!material.events.length&&!changed&&!this.importsNeeded()){this.attemptHash=undefined;return this.result(true,"not-needed");}
@@ -8,7 +8,7 @@ import { memoryGitArgv, memoryGitEnv, memoryGitSync, processLiveness, processSig
8
8
  import { acquireMutation } from "./mutation.ts";
9
9
  import type { MemoryStore } from "./store.ts";
10
10
  import { syncGenerationMemory } from "./generation-sync.ts";
11
- import { loadAmemConfig } from "./config.ts";
11
+ import { checkpointOnBoundOptIn, loadAmemConfig } from "./config.ts";
12
12
  import { memoryHome } from "./home.ts";
13
13
  import { outboundScreen, screenOutboundRows, screenOwnSegment, type RowScreen } from "./sync-screen.ts";
14
14
  import { shardSyncBinding } from "./sync-binding.ts";
@@ -28,7 +28,7 @@ export type Visibility = "public" | "private" | "unknown";
28
28
  * parsing `error` text. `bound` carries its numbers in `placementPublication.bound`; `refusal` carries its fixed
29
29
  * category; `unavailable` is any other refusal before an attempt (activation, inventory or I/O).
30
30
  */
31
- export const SYNC_FAILURE_CAUSES = ["bound", "refusal", "unknown-outcome", "writer-renewal", "remote", "stopped", "unavailable", "checkpoint-pending"] as const;
31
+ export const SYNC_FAILURE_CAUSES = ["bound", "refusal", "unknown-outcome", "writer-renewal", "remote", "stopped", "unavailable", "checkpoint-pending", "checkpoint-refused"] as const;
32
32
  export type SyncFailureCause = typeof SYNC_FAILURE_CAUSES[number];
33
33
  export interface SyncResult { ok: boolean; pushed: boolean; entries: number; warning?: string; error?: string;
34
34
  /** #462: set on every failed placement sync; absent on success and on the legacy transports. */
@@ -43,6 +43,8 @@ export interface SyncResult { ok: boolean; pushed: boolean; entries: number; war
43
43
  journalObjects?: PlacementJournalObjectComposition;
44
44
  /** #426: the fixed category and phase of a refusal before any publication attempt; no path, row or secret. */
45
45
  refusal?: { category: PlacementRefusalCategory; phase: SyncProgressPhase } };
46
+ /** #578 Q2: set only when this call ran a sync-run placement checkpoint at the journal-objects bound; numbers only. */
47
+ checkpoint?: { window: number; objectsBefore: number; objectsAfter: number };
46
48
  pruneApplication?: {transport:"durable"|"unconfirmed";proofComplete:number;projectionActive:number|null;nativeApplied:number|null;held:number;phase:"preflight"|"prepared"|"active"|"complete"};
47
49
  }
48
50
 
@@ -257,6 +259,12 @@ export interface SyncOptions {
257
259
  policyVersion?: () => string;
258
260
  /** A stopping hub aborts: the running git step is killed and the sync ends without touching the store. */
259
261
  signal?: AbortSignal;
262
+ /**
263
+ * #578 Q2: this caller may run a placement checkpoint when the next publication refuses the journal-objects bound.
264
+ * Effective only with the home's `syncPlacement.checkpointOnBound` opt-in and a `placementAttestation` port. The CLI
265
+ * `amem sync` (including `--if-due`) and a library host may set it; hooks, `amem mcp` and capture never do.
266
+ */
267
+ placementCheckpoint?: boolean;
260
268
  }
261
269
 
262
270
  export { shardSyncBinding, shardSyncSourceBinding } from "./sync-binding.ts";
@@ -291,6 +299,8 @@ export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Pr
291
299
  open: realm => reuse(realm) ?? (() => { const fresh = openShardStore({ memoryDir: home, deferPromotions: true, ...(realm.scope === "user" ? { user: true } : { project: realm.key }) }); opened.add(fresh); return fresh; })(),
292
300
  close: item => { if (opened.delete(item)) item.close(); },
293
301
  publish: (primary, targets, options) => syncPlacementMemory(primary, options, undefined, undefined, undefined, targets),
302
+ ...(opts.placementCheckpoint === true && opts.placementAttestation && checkpointOnBoundOptIn(home)
303
+ ? { checkpointOnBound: async () => (await import("./sync-placement-checkpoint-person.ts")).checkpointOnBound(home, opts.placementAttestation!) } : {}),
294
304
  });
295
305
  }
296
306
  if (opts.signal?.aborted) return { ok: false, pushed: false, entries: 0, error: "stopped" };