@staix/agent-mem 0.30.0 → 0.32.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,3 +1,6 @@
1
+ import { readActivePlacementBinding } from "./sync-placement-active.ts";
2
+ import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
3
+ import { PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA } from "./sync-placement-format.ts";
1
4
  import { createHash, randomBytes } from "node:crypto";
2
5
  import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
3
6
  import { dirname, join, relative } from "node:path";
@@ -469,7 +472,17 @@ const refusalSummary = (value: ShardMigrationCounts) => {
469
472
  const removalEvidence = (journal: ShardJournal | undefined) => journal?.deadLeasesRemoved?.length ? { deadLeasesRemoved: journal.deadLeasesRemoved } : {};
470
473
 
471
474
  export function shardMigrationStatus(memoryDir: string): { active: boolean; generation?: string; phase?: "captured" | "active"; pending: ShardMigrationCounts; deadLeasesRemoved?: DeadLeaseRemoval[]; refusals?: string[] } {
472
- const dir = existsSync(memoryDir) ? realPath(memoryDir) : canonicalPath(memoryDir), journal = readJournal(dir, true);
475
+ const dir = existsSync(memoryDir) ? realPath(memoryDir) : canonicalPath(memoryDir);
476
+ const marker = readProfileJSON(join(dir, JOURNAL)) as { schema?: unknown } | undefined;
477
+ // Probe only the profile schema: a legacy malformed selector keeps its original status path.
478
+ let profileSchema: unknown;
479
+ try { profileSchema = (readProfileJSON(join(dir, "profile.json")) as { schema?: unknown } | undefined)?.schema; } catch { /* Legacy status never read this selector. */ }
480
+ let journal: ShardJournal | undefined;
481
+ if (marker?.schema === PLACEMENT_SHARDS_SCHEMA || profileSchema === PLACEMENT_PROFILE_SCHEMA) {
482
+ const markers = readPlacementRuntimeMarkers(dir), active = readActivePlacementBinding(dir, markers.profile, markers.shards);
483
+ if (!active) throw new Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
484
+ journal = { ...active.shards, schema: SHARDED_V2_SCHEMA };
485
+ } else journal = readJournal(dir, true);
473
486
  if (!journal) return { active: false, pending: emptyCounts() };
474
487
  const plan = route(capture(dir, journal.generation, journal), journal.sources, true);
475
488
  return { active: journal.phase === "active", phase: journal.phase, generation: journal.generation, pending: counts(plan), ...refusalSummary(plan), ...removalEvidence(journal) };
@@ -5,7 +5,7 @@ import { assertPlacementRuntime, doctorScratchBinding, doctorScratchInventory, S
5
5
  import { assertNoPublicPruneIntent, readPublicPruneView } from "./public-prune-view.ts";
6
6
  import { indexFileName } from "./index-file.ts";
7
7
  import { createHash, randomBytes } from "node:crypto";
8
- import { existsSync, linkSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
+ import { existsSync, linkSync, lstatSync, mkdirSync, opendirSync, readFileSync, rmSync, writeFileSync, type Dir } from "node:fs";
9
9
  import { join } from "node:path";
10
10
  import { canonicalJSON, generationDescriptor, hashJSON, readProfileJSON, readSelector, validGeneration, PROFILE_LOCK_TIMEOUT_MS, type BoundProfile, type GenerationSeal } from "./generation.ts";
11
11
  import { SHARD_SCHEMA, resolveAlias } from "./aliases.ts";
@@ -35,6 +35,17 @@ export function shardKeyHash(key: string): string {
35
35
  /** A key in the no-remote path-hash form (`chain@hash8`) is this machine's only; the catalog flags it. */
36
36
  export const isLocalKey = (key: string): boolean => /.+@[0-9a-f]{8}$/.test(key);
37
37
 
38
+ /**
39
+ * #525: why a project realm is outside the activated inventory. The class comes from the realm's own evidence, never
40
+ * from its key form alone: a restored curated realm can be GitHub-keyed and unadmitted, and an absent curated marker
41
+ * only means capture *might* be the case. `unverified` answers whenever a check could not run safely.
42
+ */
43
+ export type PlacementRealmGap = "local-key" | "capture-only" | "no-memory" | "curated-unadmitted" | "unverified";
44
+
45
+ export function localKeyOptInMessage(key: string): string {
46
+ return `Local project ${JSON.stringify(key)} requires an explicit amem sync --remote <url> opt-in, or run amem project archive with that project key.`;
47
+ }
48
+
38
49
  export function shardDir(base: string, key: string): string {
39
50
  return join(base, "projects", shardKeyHash(key));
40
51
  }
@@ -154,12 +165,25 @@ export function readShardedSelection(memoryDir: string): ShardedSelection {
154
165
  }catch(error){if(safeProfileLockMessage(error))throw error;throw profileLockRecoveryError(memoryDir)??error;}
155
166
  }
156
167
 
168
+ /** #525: each class carries its own next step. No path, project name or key appears here; the key hash stays the identifier. */
169
+ function realmGapRemedy(gap: PlacementRealmGap | undefined): string {
170
+ const admit = "admit it with amem migrate --sync-placement --admit <project> --dry-run, then --apply";
171
+ switch (gap) {
172
+ // Admission alone does not publish a local-key realm: sync needs an explicit remote opt-in per invocation.
173
+ case "local-key": return `class=local-key; to keep it, ${admit} when you want curated memory, then give sync an explicit remote opt-in with amem sync --remote <url>; otherwise remove it with amem project archive <project>`;
174
+ case "capture-only": return `class=capture-only; it holds capture rows and no curated memory, so capture stays readable; ${admit} if you want curated memory for it`;
175
+ case "no-memory": return `class=no-memory; it holds no captured rows and no curated notes yet; ${admit} if you want curated memory for it, or remove it with amem project archive <project>`;
176
+ case "curated-unadmitted": return `class=curated-unadmitted; it holds curated notes that are not part of the activated inventory, and ${admit} opens them`;
177
+ case "unverified": return "class=unverified; neither its curated state nor the activated inventory could be verified safely; have the person inspect the home before changing anything";
178
+ default: return admit;
179
+ }
180
+ }
181
+
157
182
  /** Bounded identifiers only, safe to surface without exposing a project key or row. */
158
183
  export class PlacementRealmRefusal extends Error {
159
- constructor(readonly scope: "user" | "project", readonly keyHash: string | undefined, readonly origin: "cwd binding" | "remote" | "local binding") {
184
+ constructor(readonly scope: "user" | "project", readonly keyHash: string | undefined, readonly origin: "cwd binding" | "remote" | "local binding", readonly gap?: PlacementRealmGap) {
160
185
  // A same-epoch extension record describes a project realm only, so the user realm is fixed by activation and has no admission command.
161
- const next = scope === "user" ? "the user realm is fixed at activation; review it with amem migrate --sync-placement --dry-run"
162
- : "admit it with amem migrate --sync-placement --admit <project> --dry-run, then --apply";
186
+ const next = scope === "user" ? "the user realm is fixed at activation; review it with amem migrate --sync-placement --dry-run" : realmGapRemedy(gap);
163
187
  super(`sync placement realm is outside the activated inventory: scope=${scope}${keyHash ? ` keyHash=${keyHash}` : ""}; origin=${origin}; ${next}`);
164
188
  }
165
189
  }
@@ -198,7 +222,7 @@ export function assertCuratedShardPaths(memoryDir: string, opts: { project?: str
198
222
  // An appended same-epoch extension is part of the inventory a curated write may open (#448); a realm it does not name stays refused.
199
223
  const inventory = scratch ? doctorScratchInventory(memoryDir) : active ? readEffectiveRealmInventory(memoryDir, active) : undefined;
200
224
  if (!inventory?.realms.some(realm => opts.user ? realm.scope === "user" : realm.scope === "project" && realm.keyHash === keyHash))
201
- throw new PlacementRealmRefusal(opts.user ? "user" : "project", keyHash, origin);
225
+ throw new PlacementRealmRefusal(opts.user ? "user" : "project", keyHash, origin, opts.user ? undefined : placementRealmGap(memoryDir, opts.project!, inventoryView(inventory)));
202
226
  inventory.assertCurrent();
203
227
  recheckInventory = inventory.assertCurrent;
204
228
  }
@@ -206,6 +230,118 @@ export function assertCuratedShardPaths(memoryDir: string, opts: { project?: str
206
230
  recheckInventory?.();
207
231
  }
208
232
 
233
+ type RealmInventory = ReturnType<typeof readEffectiveRealmInventory>;
234
+
235
+ function inventoryView(inventory: RealmInventory | undefined): PlacementRealmView | undefined {
236
+ return inventory
237
+ ? { kind: "inventory", admitted: keyHash => inventory.realms.some(realm => realm.scope === "project" && realm.keyHash === keyHash), assertCurrent: inventory.assertCurrent }
238
+ : undefined;
239
+ }
240
+
241
+ /**
242
+ * #525: the activated inventory as the console sees it, built the way the curated preflight builds it. `undefined` means a
243
+ * placement-v3 home whose proof could not be established, where no class may be claimed. A home that is not placement-v3
244
+ * gates no curated open, so it answers `none` and nothing is marked.
245
+ */
246
+ export type PlacementRealmView = { readonly kind: "none" } | { readonly kind: "inventory"; admitted(keyHash: string): boolean; assertCurrent(): void };
247
+
248
+ export function placementRealmView(base: string): PlacementRealmView | undefined {
249
+ let selector: { schema?: unknown } | undefined;
250
+ try { selector = readProfileJSON(join(base, "profile.json")) as { schema?: unknown } | undefined; } catch { return undefined; }
251
+ if (selector?.schema !== "agent-mem.profile/v3") return { kind: "none" };
252
+ // No fallback to `none` here: a malformed v3 home is unproved, not ungated.
253
+ try {
254
+ const scratch = doctorScratchBinding(base);
255
+ const active = scratch ?? readActivePlacementBinding(base, selector, readProfileJSON(join(base, "shards.json")));
256
+ return inventoryView(scratch ? doctorScratchInventory(base) : active ? readEffectiveRealmInventory(base, active) : undefined);
257
+ } catch { return undefined; }
258
+ }
259
+
260
+ /**
261
+ * #525: why this project realm is outside the activated inventory, from the realm's own evidence. The key form decides only
262
+ * the local-key class; capture is proved by a machine-scope capture store and curated memory by its seal or generation record,
263
+ * so an absent curated marker never implies capture. Anything unreadable or incompletely scanned stays `unverified` rather
264
+ * than guessed.
265
+ */
266
+ export function placementRealmGap(base: string, key: string, view: PlacementRealmView | undefined): PlacementRealmGap | undefined {
267
+ if (view?.kind === "none") return undefined;
268
+ if (!view) return "unverified";
269
+ if (view.admitted(createHash("sha256").update(key).digest("hex"))) return undefined;
270
+ if (isLocalKey(key)) return "local-key";
271
+ // Never follow a linked projects/ or shard directory while deriving a class: evidence behind a link is not this home's.
272
+ // ponytail: a same-user parent replacement between this lstat and the marker reads is not fenced; descriptor-relative opens are the upgrade.
273
+ for (const dir of [join(base, "projects"), shardDir(base, key)]) {
274
+ try { const stat = lstatSync(dir); if (stat.isSymbolicLink() || !stat.isDirectory()) return "unverified"; }
275
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") break; return "unverified"; }
276
+ }
277
+ const curated = curatedMarker(base, key);
278
+ if (curated === "present") return "curated-unadmitted";
279
+ if (curated === "unreadable") return "unverified";
280
+ const capture = captureMarker(base, key);
281
+ if (capture === "unreadable" || capture === "incomplete") return "unverified";
282
+ return capture === "present" ? "capture-only" : "no-memory";
283
+ }
284
+
285
+ /**
286
+ * One owned regular file, never followed: `present` only for a regular file of this user without group or world write, and
287
+ * `unreadable` for a link, a foreign or loosened file, a platform that cannot name the owner, and any error but a missing one.
288
+ */
289
+ function ownedFileState(path: string): "present" | "absent" | "unreadable" {
290
+ try {
291
+ const stat = lstatSync(path), uid = process.getuid?.();
292
+ return uid !== undefined && !stat.isSymbolicLink() && stat.isFile() && stat.uid === uid && (stat.mode & 0o022) === 0 ? "present" : "unreadable";
293
+ } catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? "absent" : "unreadable"; }
294
+ }
295
+
296
+ /** The curated marker is the seal or the generation record. Neither is opened, so a malformed one still reads as presence. */
297
+ function curatedMarker(base: string, key: string): "present" | "absent" | "unreadable" {
298
+ const dir = shardDir(base, key);
299
+ const states = ["generation.json", "generation-seal.json"].map(name => ownedFileState(join(dir, name)));
300
+ if (states.includes("present")) return "present";
301
+ return states.includes("unreadable") ? "unreadable" : "absent";
302
+ }
303
+
304
+ /** Machine-scope entries one shard may hold and still be scanned completely; at most one more entry than this is read. */
305
+ // ponytail: ceiling is 64 machine entries; a shard with more and no store in the scanned prefix reads unverified. Upgrade: a full streaming scan or a per-shard capture index.
306
+ const MACHINE_SCAN_LIMIT = 64;
307
+
308
+ /**
309
+ * #525: capture is proved by a machine-scope capture store, never inferred from an absent curated marker. Every entry the
310
+ * listing yields counts toward the bound, so a directory full of stray names cannot make the scan unbounded; a shard with
311
+ * more entries, or with an entry that is not a plain directory (a link could hold the store elsewhere), cannot establish
312
+ * absence and answers `incomplete` or `unreadable`. A store found inside the scanned prefix still proves capture.
313
+ */
314
+ function captureMarker(base: string, key: string): "present" | "absent" | "unreadable" | "incomplete" {
315
+ const root = join(shardDir(base, key), "machine");
316
+ try { const stat = lstatSync(root); if (stat.isSymbolicLink() || !stat.isDirectory()) return "unreadable"; }
317
+ catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? "absent" : "unreadable"; }
318
+ let handle: Dir;
319
+ try { handle = opendirSync(root); } catch { return "unreadable"; }
320
+ const names: string[] = [];
321
+ let seen = 0, unsafe = false, overflow = false;
322
+ try {
323
+ for (;;) {
324
+ if (seen > MACHINE_SCAN_LIMIT) { overflow = true; break; }
325
+ const entry = handle.readSync();
326
+ if (!entry) break;
327
+ seen++;
328
+ // Only a plain directory is a machine scope; a link or any other entry leaves the store unproved.
329
+ if (!entry.isDirectory()) { unsafe = true; continue; }
330
+ names.push(entry.name);
331
+ }
332
+ } catch { return "unreadable"; }
333
+ finally { try { handle.closeSync(); } catch { /* already closed */ } }
334
+ // Sorted, so "the scanned prefix" is a fact about the names rather than the filesystem's listing order.
335
+ let unreadable = unsafe;
336
+ for (const name of names.sort().slice(0, MACHINE_SCAN_LIMIT)) {
337
+ const state = ownedFileState(join(root, name, "capture.db"));
338
+ if (state === "present") return "present";
339
+ if (state === "unreadable") unreadable = true;
340
+ }
341
+ if (unreadable) return "unreadable";
342
+ return overflow ? "incomplete" : "absent";
343
+ }
344
+
209
345
  /** Open one already-sealed shard without consulting the legacy home or the catalog. */
210
346
  export function resolveShardProfile(memoryDir: string, opts: { project?: string; user?: boolean }, origin?: "cwd binding" | "remote" | "local binding"): BoundProfile {
211
347
  if (opts.user === true && opts.project !== undefined || opts.user !== true && !opts.project) throw new Error("choose exactly one project or the user shard");
@@ -1,4 +1,4 @@
1
- import { facts, label, PLAIN, type Style } from "./style.ts";
1
+ import { facts, label, markerCell, paint, section, PLAIN, type Style } from "./style.ts";
2
2
 
3
3
  /** The `amem status` object as the CLI builds it; `amem status --json` prints it unchanged. */
4
4
  export interface StatusView {
@@ -32,15 +32,15 @@ export function statusText(status: StatusView, s: Style = PLAIN): string {
32
32
  const { machine, repo, denyPaths, piiPatterns, ...limits } = status.config;
33
33
  const pendingCounts = facts(Object.fromEntries(Object.entries(status.pending).filter(([key]) => !key.endsWith("Ids"))));
34
34
  const lines = [
35
- `${s.bold("amem status:")} ${overall === "ok" ? s.ok(overall) : overall === "attention" ? s.attention(overall) : s.error(overall)}`,
36
- `home ${status.home.path} ${s.dim(`(${status.home.source})`)}`,
37
- "",
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}`)] : []),
37
+ "", section(s, "Memory"),
38
+ ` home: ${status.home.path} ${s.dim(`(${status.home.source})`)}`,
38
39
  `${label(s, "ok")} policy: machine ${machine ?? "none (defaults)"}, repo ${repo ?? "none"}; ${denyPaths} deny paths, ${piiPatterns} PII patterns${facts(limits) ? `; ${facts(limits)}` : ""}`,
39
40
  `${label(s, candidateState)} candidates: ${candidateLine}`,
40
41
  `${label(s, migrationState)} layout: ${status.active ? `shards active${status.generation ? ` (generation ${status.generation.slice(0, 8)})` : ""}` : status.phase ? `shard migration ${status.phase}${interrupted ? ", not active" : ""}` : "single home"}; ${pendingCounts ? `pending ${pendingCounts}` : "no pending old-layout appends"}`,
41
42
  ...(status.deadLeasesRemoved?.length ? [` ${s.dim(`${status.deadLeasesRemoved.length} dead reader leases removed`)}`] : []),
42
- ...(warnings.length ? ["", "Warnings:", ...warnings.map(warning => ` - ${s.attention(warning)}`)] : []),
43
- "", actions.length ? "Next actions:" : "Next actions: none", ...actions.map(action => ` - ${action}`),
43
+ "", actions.length ? "Next actions: see Attention" : "Next actions: none",
44
44
  s.dim("Full report: amem status --json; health checks: amem doctor"),
45
45
  ];
46
46
  return lines.join("\n");
@@ -206,6 +206,8 @@ export type PromotionScreen = (v: View) => "promote" | "keep" | "skip";
206
206
  * went) wait for a process that has one; a person's explicit promote goes through.
207
207
  */
208
208
  export interface StoreOptions { home?: string; memoryDir?: string; ttlMs?: number; now?: () => number; log?: (line: string) => void; screen?: PromotionScreen; deferPromotions?: boolean; profile?: ProfileInput;
209
+ /** A trusted host's processSignature(process.pid) for this process, measured outside a sandbox that cannot run ps. */
210
+ readerLeaseSignature?: string;
209
211
  /** #15 T5: `openShardStore` refuses a project the person archived or forgot unless the caller says `ignore` (the catalog, `--include-archived` reads and export do, on purpose). */
210
212
  lifecycle?: "enforce" | "ignore";
211
213
  /** #27: read the `aliases` keys' curated rows as part of the `canonical` project (CLI and MCP only); the library default reads the raw key. Rows are presented under `canonical`. */
@@ -279,7 +281,7 @@ export class MemoryStore {
279
281
  this.screen = opts.screen;
280
282
  this.deferPromotions = opts.deferPromotions ?? false;
281
283
  // Announce before opening derived handles or reading rows; failed admission leaks no database handles.
282
- if (!bootstrap || bootstrap.authoring === true) this.releaseReaderLease = registerReaderLease(this.profile.home, this.profile.sharded ? {scope:"shard"} : {});
284
+ if (!bootstrap || bootstrap.authoring === true) this.releaseReaderLease = registerReaderLease(this.profile.home, { ...(this.profile.sharded ? { scope: "shard" as const } : {}), ...(opts.readerLeaseSignature === undefined ? {} : { signature: opts.readerLeaseSignature }) });
283
285
  let openedDb: Database | undefined, openedMutation: Database | undefined, openedSearch: SearchIndex | undefined;
284
286
  try {
285
287
  const indexFile = join(this.dir, indexFileName(!!this.profile.foreignPruneFormat));
@@ -1950,7 +1952,7 @@ export function openShardStore(opts: StoreOptions & { project?: string; user?: b
1950
1952
  // Lifecycle refusal must remain before admission creates any lease/fence file.
1951
1953
  if (opts.user !== true && opts.lifecycle !== "ignore") assertProjectActive(home, opts.project!);
1952
1954
  readShardedSelection(home); // validate the floor before any lazy shard initialization
1953
- const admission = registerReaderLease(home, {scope:"shard"});
1955
+ const admission = registerReaderLease(home, {scope:"shard", ...(opts.readerLeaseSignature === undefined ? {} : { signature: opts.readerLeaseSignature })});
1954
1956
  try {
1955
1957
  const dir = opts.user === true ? userShardDir(home) : shardDir(home, opts.project!);
1956
1958
  const missing = !existsSync(join(dir, "generation.json"));
@@ -5,6 +5,7 @@
5
5
  */
6
6
  export interface Style {
7
7
  readonly color: boolean;
8
+ readonly ascii: boolean;
8
9
  ok(text: string): string;
9
10
  attention(text: string): string;
10
11
  error(text: string): string;
@@ -12,14 +13,89 @@ export interface Style {
12
13
  bold(text: string): string;
13
14
  }
14
15
 
15
- /** Color only for an interactive stdout, and never with NO_COLOR (any value, per no-color.org) or TERM=dumb. */
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
+ export function section(s: Style, name: string): string {
60
+ return paint("section", `${s.ascii ? SECTION_MARKER.ascii : SECTION_MARKER.glyph} ${name}`, s.color);
61
+ }
62
+
63
+ /** Wrap report prose at a stream's requested width; a pipe without COLUMNS remains unwrapped. */
64
+ export function wrapReport(text: string, width: number | undefined): string {
65
+ if (!Number.isSafeInteger(width) || width === undefined || width < 20) return text;
66
+ const ansi = new RegExp(`${ESC}\\[[0-9;]*m`, "g");
67
+ const measure = (value: string) => cellWidth(value.replace(ansi, ""));
68
+ return text.split("\n").flatMap(line => {
69
+ if (measure(line) <= width) return [line];
70
+ const indent = line.match(/^ */)?.[0] ?? "", continuation = " ";
71
+ const words = line.slice(indent.length).match(/\S+|\s+/g) ?? [];
72
+ const result: string[] = [];
73
+ let row = indent;
74
+ let spacing = "";
75
+ for (const word of words) {
76
+ if (/^\s+$/.test(word)) { spacing = word; continue; }
77
+ if (measure(row + spacing + word) > width && row.trim()) { result.push(row); row = continuation; spacing = ""; }
78
+ if (measure(row + spacing + word) <= width) { row += spacing + word; spacing = ""; continue; }
79
+ row += spacing; spacing = "";
80
+ // 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")) ?? []) {
82
+ if (measure(row + part) > width) { result.push(row); row = continuation; }
83
+ row += part;
84
+ }
85
+ }
86
+ if (row.trim()) result.push(row);
87
+ return result;
88
+ }).join("\n");
89
+ }
90
+
91
+ /** Default color decision for one stream, following the shared precedence table. */
16
92
  export function colorEnabled(env: Readonly<Record<string, string | undefined>>, isTTY: boolean | undefined): boolean {
17
- return isTTY === true && env.NO_COLOR === undefined && env.TERM !== "dumb";
93
+ return resolveColor("auto", streamEnv(isTTY === true, env)) === true;
18
94
  }
19
95
 
20
- const wrap = (on: boolean, open: number, close: number) => (text: string) => on ? `\x1b[${open}m${text}\x1b[${close}m` : text;
21
- export function style(color: boolean): Style {
22
- return { color, ok: wrap(color, 32, 39), attention: wrap(color, 33, 39), error: wrap(color, 31, 39), dim: wrap(color, 2, 22), bold: wrap(color, 1, 22) };
96
+ 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) };
23
99
  }
24
100
  export const PLAIN: Style = style(false);
25
101
 
@@ -29,7 +105,9 @@ export const singleLine = (text: string): string => text.replace(/[\p{Cc}\p{Cf}\
29
105
  /** Status label, padded so the columns line up; the word is always present. */
30
106
  export function label(s: Style, state: "ok" | "attention" | "skipped" | "unavailable" | "error"): string {
31
107
  const word = { ok: "OK", attention: "ATTENTION", skipped: "SKIPPED", unavailable: "UNAVAILABLE", error: "ERROR" }[state].padEnd(11);
32
- return state === "ok" ? s.ok(word) : state === "attention" ? s.attention(word) : state === "skipped" ? s.dim(word) : s.error(word);
108
+ const marker: MarkerName = state === "ok" ? "ok" : state === "attention" ? "warn" : state === "skipped" ? "absent" : state === "unavailable" ? "unknown" : "fail";
109
+ const text = `${markerCell(marker, s.ascii)} ${word}`;
110
+ return ` ${paint(MARKERS[marker].role, text, s.color)}`;
33
111
  }
34
112
 
35
113
  /** "key value" pairs, leaving out zero, empty and null values; returns "" when nothing material is left. */
@@ -18,9 +18,9 @@ import { readPlacementJournal } from "./sync-placement-journal-storage.ts";
18
18
  import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending } from "./sync-placement-checkpoint-storage.ts";
19
19
  import { readPlacementPublication } from "./sync-placement-publication-storage.ts";
20
20
  import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
21
- import { readShardDescriptor, shardDir, userShardDir } from "./shard.ts";
21
+ import { isLocalKey, localKeyOptInMessage, readShardDescriptor, shardDir, userShardDir } from "./shard.ts";
22
22
  import { projectState } from "./lifecycle.ts";
23
- import type { PlacementRealm } from "./sync-placement-journal-format.ts";
23
+ import { SyncPlacementJournalError, type PlacementRealm } from "./sync-placement-journal-format.ts";
24
24
  import type { SyncOptions, SyncResult } from "./sync.ts";
25
25
  import type { MemoryStore } from "./store.ts";
26
26
 
@@ -29,7 +29,7 @@ const PUBLICATION_TARGETS = 2;
29
29
 
30
30
  /** One activated realm with its local key (the project key is resolved from the local descriptor; user has none). */
31
31
  export type InventoryRealm = { scope: "user" } | { scope: "project"; key: string; keyHash: string };
32
- export type PlacementRealmOutcome = "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive";
32
+ export type PlacementRealmOutcome = "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive" | "held";
33
33
  /** Per-realm receipt: identifiers only (the user realm or the full key hash), never a project name, row or path. */
34
34
  export interface PlacementRealmResult { realm: "user" | string; outcome: PlacementRealmOutcome; publication?: number }
35
35
 
@@ -86,22 +86,44 @@ function retainedRealms(home: string): string[] | undefined {
86
86
  return readPlacementPublication(home, active.profile.placementHead, reservation.attemptHash).bundle.root.targets.map(target => label(target.realm));
87
87
  }
88
88
 
89
+ /** #492: one retained-journal refusal reads as the run's own failure. `unavailable` is the closed vocabulary's term for
90
+ * a refusal before an attempt (activation, inventory or I/O); a checkpoint's own cause keeps it, as it already does above.
91
+ */
92
+ function journalRefusal(error: unknown): (SyncResult & { placementRealms: PlacementRealmResult[] }) | undefined {
93
+ if (!error || typeof error !== "object" || !(error instanceof SyncPlacementJournalError)) return undefined;
94
+ const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
95
+ return { ok: false, pushed: false, entries: 0, error: error.message,
96
+ failure: { cause: code === "checkpoint-pending" ? "checkpoint-pending" : "unavailable" }, placementRealms: [] };
97
+ }
98
+
89
99
  export async function syncPlacementInventory(home: string, opts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
90
- // #288 step 3: a started checkpoint pauses every placement effect before any journal read, with its own cause and next step.
91
- const markers = readPlacementRuntimeMarkers(home), binding = readActivePlacementBinding(home, markers.profile, markers.shards);
92
- if (binding && placementCheckpointPending(home, binding.profile.placementHead))
93
- return { ok: false, pushed: false, entries: 0, error: PLACEMENT_CHECKPOINT_PENDING_MESSAGE, failure: { cause: "checkpoint-pending" }, placementRealms: [] };
94
- const { local, missing, inactive } = placementInventory(home);
95
- const retained = retainedRealms(home);
100
+ let local: InventoryRealm[], missing: string[], inactive: string[], retained: string[] | undefined;
101
+ try {
102
+ // #288 step 3: a started checkpoint pauses every placement effect before any journal read, with its own cause and next step.
103
+ const markers = readPlacementRuntimeMarkers(home), binding = readActivePlacementBinding(home, markers.profile, markers.shards);
104
+ if (binding && placementCheckpointPending(home, binding.profile.placementHead))
105
+ return { ok: false, pushed: false, entries: 0, error: PLACEMENT_CHECKPOINT_PENDING_MESSAGE, failure: { cause: "checkpoint-pending" }, placementRealms: [] };
106
+ ({ local, missing, inactive } = placementInventory(home));
107
+ retained = retainedRealms(home);
108
+ } catch (error) {
109
+ // #492: the inventory is the retained epoch's first reader, so its refusal there (an unknown epoch member, a torn
110
+ // chunk) is answered as this run's own failure before any effect, never thrown past the caller's result shape.
111
+ const refused = journalRefusal(error); if (refused) return refused; throw error;
112
+ }
113
+ const held = opts.remote === undefined ? local.filter((realm): realm is Extract<InventoryRealm, { scope: "project" }> => realm.scope === "project" && isLocalKey(realm.key)) : [];
114
+ const resumed = retained;
115
+ const retainedHeld = held.find(realm => resumed?.includes(label(realm)));
116
+ if (retainedHeld) return { ok: false, pushed: false, entries: 0, error: `Retained publication cannot resume. ${localKeyOptInMessage(retainedHeld.key)}`, failure: { cause: "unavailable" }, placementRealms: [{ realm: label(retainedHeld), outcome: "held" }] };
117
+ local = local.filter(realm => !held.includes(realm as Extract<InventoryRealm, { scope: "project" }>));
96
118
  let order = local;
97
- if (retained) {
119
+ if (resumed) {
98
120
  // The retained plan names its own realms; it runs first, exactly as recorded, then the rest in the usual order.
99
- const first = retained.map(name => local.find(realm => label(realm) === name));
121
+ const first = resumed.map(name => local.find(realm => label(realm) === name));
100
122
  if (first.some(realm => !realm)) throw new Error("a retained placement publication names a realm without a local curated shard; inspect it before continuing");
101
- order = [...first as InventoryRealm[], ...local.filter(realm => !retained.includes(label(realm)))];
123
+ order = [...first as InventoryRealm[], ...local.filter(realm => !resumed.includes(label(realm)))];
102
124
  }
103
- const batches = retained ? [order.slice(0, retained.length), ...placementInventoryBatches(order.slice(retained.length))] : placementInventoryBatches(order);
104
- const realms: PlacementRealmResult[] = [...missing.map(realm => ({ realm, outcome: "not-local" as const })), ...inactive.map(realm => ({ realm, outcome: "inactive" as const }))];
125
+ const batches = resumed ? [order.slice(0, resumed.length), ...placementInventoryBatches(order.slice(resumed.length))] : placementInventoryBatches(order);
126
+ const realms: PlacementRealmResult[] = [...missing.map(realm => ({ realm, outcome: "not-local" as const })), ...inactive.map(realm => ({ realm, outcome: "inactive" as const })), ...held.map(realm => ({ realm: label(realm), outcome: "held" as const }))];
105
127
  const progress = opts.progress, total = batches.filter(batch => batch.length).length;
106
128
  // One reporter for the whole run: each publication reports its phases, but only this driver reports the terminal state.
107
129
  const report = (completed: number) => progress?.inventory({ publications: total, completed, realms: order.length,
@@ -137,5 +159,5 @@ export async function syncPlacementInventory(home: string, opts: SyncOptions, po
137
159
  const base: SyncResult = last ? { ...last } : { ok: true, pushed: false, entries: 0 };
138
160
  return { ...base, ok: !stopped, pushed: totals.pushed, entries: totals.entries,
139
161
  ...(base.placementPublication ? { placementPublication: { ...base.placementPublication, exported: totals.exported, withheld: totals.withheld } } : {}),
140
- ...(stopped?.error !== undefined ? { error: stopped.error } : {}), placementRealms: realms };
162
+ ...(stopped?.error !== undefined ? { error: stopped.error } : {}), ...(held.length ? { warning: [base.warning, ...held.map(realm => localKeyOptInMessage(realm.key))].filter(Boolean).join(" ") } : {}), placementRealms: realms };
141
163
  }
@@ -6,7 +6,7 @@ import { canonicalJSON, hashJSON, readSelector } from "./generation.ts";
6
6
  import { generationSyncLock } from "./generation-sync.ts";
7
7
  import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncFailureCause, type SyncOptions, type SyncResult } from "./sync.ts";
8
8
  import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
9
- import { isLocalKey, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
9
+ import { isLocalKey, localKeyOptInMessage, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
10
10
  import { memoryPolicySnapshot } from "./policy.ts";
11
11
  import { outboundPolicyEvaluator } from "./sync-screen.ts";
12
12
  import { readActivePlacementBinding } from "./sync-placement-active.ts";
@@ -63,6 +63,7 @@ const oid = (v: unknown): v is string => typeof v === "string" && v.length === 4
63
63
  const sameRealm = (a: PlacementRealm, b: PlacementRealm) => canonicalJSON(a) === canonicalJSON(b);
64
64
  const physical = (target: Target): PlacementRealm => target.realm.scope === "user" ? { scope: "user" } : { scope: "project", keyHash: digest(target.realm.key) };
65
65
  function refuse(category: PlacementRefusalCategory = "other"): never { throw new PlacementSyncRefusal(category); }
66
+ class LocalKeyOptInRefusal extends Error {}
66
67
  function remoteRefusal(error: unknown, fallback: RemoteRealmCause = "other"): never {
67
68
  if (error instanceof RemoteRealmRefusal) throw error;
68
69
  if (error instanceof SyncPlacementFormatError || error instanceof Error && error.message === "sync placement activation metadata unavailable or changed; inspect the retained activation before continuing") throw new RemoteRealmRefusal("epoch");
@@ -330,7 +331,8 @@ class PlacementTransport {
330
331
  git: args => this.required(args), blob: (object, path) => this.blob(object, path), object: (oid,type) => this.rawHistoryObject(oid,type) }); this.targets.push(target);
331
332
  }
332
333
  if (new Set(this.targets.map(target => shardSyncRef(target.realm))).size !== this.targets.length) refuse("source-selection");
333
- if (this.targets.some(target => target.realm.scope === "project" && isLocalKey(target.realm.key)) && this.opts.remote === undefined) refuse("remote");
334
+ const local = this.targets.find(target => target.realm.scope === "project" && isLocalKey(target.realm.key));
335
+ if (local?.realm.scope === "project" && this.opts.remote === undefined) throw new LocalKeyOptInRefusal(localKeyOptInMessage(local.realm.key));
334
336
  if (existsSync(this.root)) placementCacheRootStamp(this.home);
335
337
  const existing = existsSync(this.root) ? await this.independent() : false;
336
338
  if (!existing && !this.opts.remote) refuse("remote");
@@ -770,6 +772,7 @@ class PlacementTransport {
770
772
  if(bound){this.bound=bound;const detail=placementSyncBoundDetail(error);return this.result(false,"not-needed",placementSyncBoundMessage(bound)+(detail?` ${detail}`:""));}
771
773
  if(this.attemptHash)return this.result(false,"unknown","Placement sync stopped with a retained attempt that may have published; recheck its exact receipts before another publication.");
772
774
  if (error && typeof error === "object" && !types.isProxy(error) && error instanceof PlacementRealmRefusal && error.origin === "remote") { this.failureCause = "remote"; return this.result(false, "not-needed", error.message); }
775
+ if (error instanceof LocalKeyOptInRefusal) { this.failureCause = "unavailable"; return this.result(false, "not-needed", error.message); }
773
776
  // #426: name the failing check by a fixed category and the phase; never the error's own text, which may carry a path.
774
777
  this.refusal=placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other";
775
778
  return this.result(false,"not-needed",placementRefusalMessage(this.refusal,this.phaseNow));
@@ -26,7 +26,7 @@ export interface SyncProgressCounts { permitted: number; local: number; declined
26
26
  export interface SyncProgressInventory { publications: number; completed: number; realms: number;
27
27
  /** Per-realm outcomes in run order: `user` or the 16-hex shard key hash, never a name. At most 32; `truncated` marks more. */
28
28
  outcomes?: { realm: string; outcome: SyncRealmOutcome }[]; truncated?: boolean }
29
- export const SYNC_REALM_OUTCOMES = ["committed", "not-needed", "unknown", "failed", "not-run", "not-local", "inactive"] as const;
29
+ export const SYNC_REALM_OUTCOMES = ["committed", "not-needed", "unknown", "failed", "not-run", "not-local", "inactive", "held"] as const;
30
30
  export type SyncRealmOutcome = typeof SYNC_REALM_OUTCOMES[number];
31
31
  const MAX_REALM_OUTCOMES = 32;
32
32
  const realmLabel = (value: unknown): value is string => typeof value === "string" && (value === "user" || /^[a-f0-9]{16}$/.test(value));
@@ -34,7 +34,7 @@ export interface SyncResult { ok: boolean; pushed: boolean; entries: number; war
34
34
  /** #462: set on every failed placement sync; absent on success and on the legacy transports. */
35
35
  failure?: { cause: SyncFailureCause; category?: PlacementRefusalCategory };
36
36
  /** #450: per-realm outcomes of a whole-inventory placement sync, in run order (`user` or the full realm key hash). */
37
- placementRealms?: { realm: string; outcome: "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive"; publication?: number }[];
37
+ placementRealms?: { realm: string; outcome: "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive" | "held"; publication?: number }[];
38
38
  placementPublication?: { attemptHash?: string; outcome: "committed" | "unknown" | "not-needed"; withheld: number; exported: number;
39
39
  lastPolicyHash?: string; lastPolicyCheckUnixMs?: number; policyCheckSource?: "live" | "durable-intent"; policyCeiling: "last-positive-check-before-in-flight-push"; recovered?: boolean;
40
40
  /** #419: an expected size refusal before any publication attempt; numbers only. */
@@ -8,6 +8,20 @@ const entry = (id: string): string => { const normalized = id.replace(/^mem:/, "
8
8
  const projectKey = (project: string): string => { if (typeof project !== "string" || !project.trim() || project.length > 400 || project.includes("\0")) throw Error("invalid memory use project"); return project; };
9
9
  function guard(context: MemoryUseContext): void { if (context.allowed?.() === false) throw Error("memory use unavailable"); context.assertCurrent?.(); }
10
10
  const count = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;
11
+ /** Sum a bounded delivery snapshot without treating a missing metric as an observed zero. */
12
+ export function summarizeMemoryUse(rows: readonly Counter[]): MemoryUseSummary {
13
+ if (!rows.length) return { state: "known", records: 0, rendered: null, delivered: null, cited: null };
14
+ const metric = (name: keyof CounterValues): number | null => {
15
+ let total = 0;
16
+ for (const row of rows) {
17
+ const value = row[name];
18
+ if (!count(value) || !Number.isSafeInteger(total + value)) return null;
19
+ total += value;
20
+ }
21
+ return total;
22
+ };
23
+ return { state: "known", records: rows.length, rendered: metric("rendered"), delivered: metric("delivered"), cited: metric("cited") };
24
+ }
11
25
  /** Counts are explicit per-delivery totals, never increments or inferred delivery/citation events. */
12
26
  export function recordMemoryUse(port: MemoryUsePort, key: CounterKey, values: CounterValues, context: MemoryUseContext = {}): boolean {
13
27
  try {
@@ -34,13 +48,7 @@ export function readMemoryUse(port: MemoryUsePort, project: string, id: string,
34
48
  rows.set(row.id, row);
35
49
  }
36
50
  }
37
- const metric = (name: keyof CounterValues): number | null => {
38
- if (!rows.size) return null;
39
- let total = 0;
40
- for (const row of rows.values()) { const value = row[name]; if (!count(value) || !Number.isSafeInteger(total + value)) return null; total += value; }
41
- return total;
42
- };
43
- const result: MemoryUseSummary = { state: "known", records: rows.size, rendered: metric("rendered"), delivered: metric("delivered"), cited: metric("cited") };
51
+ const result = summarizeMemoryUse([...rows.values()]);
44
52
  guard(context); return result;
45
53
  } catch { return unknown(); }
46
54
  }