@staix/agent-mem 0.37.0 → 0.39.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.
Files changed (49) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +1 -1
  3. package/package.json +1 -1
  4. package/src/brief-curated.ts +8 -4
  5. package/src/cli-agent-reads.ts +55 -4
  6. package/src/cli.ts +222 -93
  7. package/src/commands-table.ts +332 -171
  8. package/src/index.ts +5 -0
  9. package/src/memory/capacity-text.ts +100 -0
  10. package/src/memory/capacity.ts +1 -57
  11. package/src/memory/commands.ts +45 -9
  12. package/src/memory/curated-cache-state.ts +22 -3
  13. package/src/memory/doctor-text.ts +144 -0
  14. package/src/memory/doctor.ts +9 -86
  15. package/src/memory/eval-audit-text.ts +62 -0
  16. package/src/memory/eval-audit.ts +1 -34
  17. package/src/memory/eval-text.ts +32 -0
  18. package/src/memory/eval.ts +1 -14
  19. package/src/memory/formats.ts +2 -0
  20. package/src/memory/gc-text.ts +22 -0
  21. package/src/memory/gc.ts +0 -6
  22. package/src/memory/generation-index.ts +1 -1
  23. package/src/memory/index-file.ts +1 -1
  24. package/src/memory/metrics.ts +18 -10
  25. package/src/memory/migrate-text.ts +32 -0
  26. package/src/memory/migrate.ts +0 -29
  27. package/src/memory/prune-text.ts +29 -0
  28. package/src/memory/prune.ts +0 -26
  29. package/src/memory/report-text.ts +233 -0
  30. package/src/memory/shard-migration-text.ts +40 -0
  31. package/src/memory/shard-migration.ts +0 -37
  32. package/src/memory/status-text.ts +72 -29
  33. package/src/memory/store.ts +112 -17
  34. package/src/memory/style.ts +98 -1
  35. package/src/memory/sync-placement-bound.ts +2 -2
  36. package/src/memory/sync-placement-checkpoint-person.ts +1 -1
  37. package/src/memory/sync-placement-noop-cache.ts +93 -0
  38. package/src/memory/sync-placement-refusal-category.ts +18 -0
  39. package/src/memory/sync-placement-transport.ts +43 -7
  40. package/src/memory/sync-progress-text.ts +7 -0
  41. package/src/memory/sync-progress.ts +21 -7
  42. package/src/memory/sync-screen.ts +13 -0
  43. package/src/memory/work-lists.ts +6 -4
  44. package/src/setup-drift.ts +1 -1
  45. package/src/setup-writer-roots.ts +136 -0
  46. package/src/setup.ts +122 -159
  47. package/src/sync-placement-writer-context.ts +8 -3
  48. package/src/ui/plugin.ts +4 -2
  49. package/src/work-brief-preparation.ts +28 -0
@@ -1,7 +1,7 @@
1
1
  import { RECAP_SCRATCH } from "./recap-scratch.ts";
2
2
  import { buildCuratedBriefCache, buildPreferenceBriefCache } from "../brief-curated.ts";
3
3
  import { PREFERENCE_SLOT } from "./preference-brief.ts";
4
- import { curatedProfileBinding, invalidateCuratedCaches } from "./curated-cache-state.ts";
4
+ import { curatedProfileBinding, invalidateCuratedCaches, type CuratedCacheCandidate } from "./curated-cache-state.ts";
5
5
  import { assertPlacementRuntime, placementSelectorRefusal, SyncPlacementRuntimeError } from "./sync-placement-guard.ts";
6
6
  import { assertFormatFloor, floorRaiseHint, formatFloorAtLeast, PREFERENCE_MIN_READER } from "./formats.ts";
7
7
  import { readPublicPruneView } from "./public-prune-view.ts";
@@ -18,12 +18,12 @@ import { looksSecret } from "./screen.ts";
18
18
  import { mutationDatabase } from "./mutation.ts";
19
19
  import { memoryHome } from "./home.ts";
20
20
  import { machineId, type Machine } from "./machine.ts";
21
- import { assertProjectActive } from "./lifecycle.ts";
21
+ import { assertProjectActive, lifecycleResolver } from "./lifecycle.ts";
22
22
  export { machineId, type Machine } from "./machine.ts";
23
23
  import { rankedScore, rankedScoreDetails, unrankedScoreDetails, type SearchScoreDetails } from "./search-score.ts";
24
24
  export type { SearchScoreDetails } from "./search-score.ts";
25
25
  import { readWindowSql, readRef, type ReadWindow, type ReadRef, SearchIndex, captureSearch } from "./search-fts.ts";
26
- import { assertCuratedShardPaths, ensureShardDescriptor, readShardDescriptor, readShardedSelection, aliasedKeys, resolveAlias, resolveShardProfile, shardDir, shardKeyHash, shardMachineDir, userShardDir } from "./shard.ts";
26
+ import { assertCuratedShardPaths, ensureShardDescriptor, readShardDescriptor, readShardedSelection, aliasedKeys, effectiveAliases, resolveAlias, resolveShardProfile, shardDir, shardKeyHash, shardMachineDir, userShardDir } from "./shard.ts";
27
27
  import { readCaptureConfig, type CaptureRow } from "./capture.ts";
28
28
  import { assertSharedV1Op } from "./ops-contract.ts";
29
29
  import { generationDescriptor, generationDir, fsyncDirectory, canonicalJSON, hashJSON, readProfileJSON, resolveProfile, writeProfileJSON, readSelector, type BoundProfile, type ProfileInput, validateVaultLinkRow, vaultLinkId, type VaultLink, type VaultLinkRow, rebindPublicPruneProfile } from "./generation.ts";
@@ -33,6 +33,7 @@ import { readMigrationSources } from "./migrate.ts";
33
33
  import type { PruneSourceRow, PruneStorePort } from "./prune.ts";
34
34
  import { isDeepStrictEqual } from "node:util";
35
35
  import { registerReaderLease, type ReaderLease } from "./reader-lease.ts";
36
+ import { recordBriefPublicationFailure } from "./metrics.ts";
36
37
  import { groupByTask, taskGroupKey } from "./task-group.ts";
37
38
 
38
39
  /**
@@ -143,6 +144,11 @@ const oneLine = (text: string): string => text.replace(/\s+/g, " ").trim().slice
143
144
 
144
145
  /** A board task's key in hub memory: unique across `ahub reset --all`, which restarts the ids. */
145
146
  export const taskKey = (project: string, task: { id: number; created: number }): string => `${project}#${task.id}@${task.created}`;
147
+ /** The board namespace in a task key can itself contain '#'. */
148
+ function taskProject(task: string): string | null {
149
+ const separator = task.lastIndexOf("#");
150
+ return separator > 0 ? task.slice(0, separator) : null;
151
+ }
146
152
 
147
153
  /** A person's name for this machine, shown beside its id. */
148
154
  export function setMachineLabel(dir: string, label: string): Machine {
@@ -222,6 +228,9 @@ interface BootstrapBinding { token: typeof MIGRATION_BOOTSTRAP; profile: BoundPr
222
228
  // Defer publication until the outermost source fence in this process has released.
223
229
  const curatedDepth = new Map<string, number>();
224
230
  const curatedPending = new Map<string, Map<MemoryStore, Set<string>>>();
231
+ const curatedRecovery = new Map<string, CuratedCacheCandidate[]>();
232
+ // ponytail: two extra project preparations per fence release. An explicit bulk maintenance command is the upgrade for a large cold home.
233
+ const CURATED_RECOVERY_LIMIT = 2;
225
234
  /** #424: a project-scope, non-preference row appears only in its own project's prebuilt curated brief (the preference slot also reads shared rows). */
226
235
  const curatedLocal = (row: { scope?: string; kind?: string }): boolean => row.scope === "project" && row.kind !== "preference";
227
236
  let publishingCurated = false;
@@ -297,7 +306,7 @@ export class MemoryStore {
297
306
  db.run(`PRAGMA busy_timeout = ${MEMORY_DB_BUSY_TIMEOUT_MS}`);
298
307
  db.run("PRAGMA journal_mode = WAL");
299
308
  if ((db.query("PRAGMA user_version").get() as { user_version: number }).user_version !== INDEX_VERSION) {
300
- for (const t of ["segments", "heads", "entries", "ops", "edges", "goals"]) db.run(`DROP TABLE IF EXISTS ${t}`);
309
+ for (const t of ["segments", "heads", "entries", "ops", "edges", "goals", "unsettled_tasks"]) db.run(`DROP TABLE IF EXISTS ${t}`);
301
310
  db.run(`PRAGMA user_version = ${INDEX_VERSION}`);
302
311
  }
303
312
  db.run("CREATE TABLE IF NOT EXISTS segments (file TEXT PRIMARY KEY, offset INTEGER NOT NULL)");
@@ -309,6 +318,9 @@ export class MemoryStore {
309
318
  db.run("CREATE TABLE IF NOT EXISTS ops (id TEXT PRIMARY KEY, op TEXT NOT NULL, at TEXT NOT NULL, machine TEXT NOT NULL, target TEXT NOT NULL, by TEXT, actor TEXT NOT NULL)");
310
319
  db.run("CREATE TABLE IF NOT EXISTS edges (src TEXT NOT NULL, dst TEXT NOT NULL, PRIMARY KEY (src, dst))");
311
320
  db.run("CREATE INDEX IF NOT EXISTS edges_dst ON edges (dst)");
321
+ db.run("CREATE TABLE IF NOT EXISTS unsettled_tasks (project TEXT NOT NULL, task TEXT NOT NULL, PRIMARY KEY(project, task)) WITHOUT ROWID");
322
+ db.run("CREATE INDEX IF NOT EXISTS entries_task ON entries(task) WHERE task IS NOT NULL");
323
+ db.run("CREATE INDEX IF NOT EXISTS ops_settlement ON ops(target) WHERE op = 'settle'");
312
324
  this.db = db;
313
325
  this.mutationDb = openedMutation = mutationDatabase(this.dir);
314
326
  // One derived FTS copy per profile: a generation handle and a shared-v1 handle on one home never resync-fight.
@@ -319,7 +331,7 @@ export class MemoryStore {
319
331
  apply: (line, source) => this.apply(line, source), withMutation: work => this.withMutation(work), beforeCuratedWrite: targets => {
320
332
  const rows = this.db.query("SELECT project, scope, kind FROM entries WHERE id IN (SELECT value FROM json_each(?))").all(JSON.stringify(targets)) as { project: string; scope: string; kind: string }[];
321
333
  // #424: only the touched projects' prebuilt briefs; a shared or preference row (or an unknown target) can reach every project's slot.
322
- invalidateCuratedCaches(this.profile.home, rows.length === targets.length && rows.every(row => curatedLocal(row)) && rows.every(row => this.curatedChangeLocal(row.project, targets)) ? rows.map(row => row.project) : undefined);
334
+ this.invalidateCuratedForPublication(rows.length === targets.length && rows.every(row => curatedLocal(row)) && rows.every(row => this.curatedChangeLocal(row.project, targets)) ? rows.map(row => row.project) : undefined);
323
335
  this.queueCuratedProjects(rows.map(row => row.project));
324
336
  },
325
337
  ...(bootstrap ? { limits: bootstrap.limits } : {}), ...(bootstrap?.commit ? { commit: bootstrap.commit } : {}) });
@@ -424,7 +436,7 @@ export class MemoryStore {
424
436
  finally { release(); }
425
437
  }
426
438
 
427
- private deferCuratedPublication(): () => void {
439
+ private deferCuratedPublication(recover = true): () => void {
428
440
  const home = this.profile.home;
429
441
  curatedDepth.set(home, (curatedDepth.get(home) ?? 0) + 1);
430
442
  return () => {
@@ -433,11 +445,26 @@ export class MemoryStore {
433
445
  curatedDepth.delete(home);
434
446
  if (publishingCurated) return;
435
447
  const pending = curatedPending.get(home); curatedPending.delete(home);
436
- if (!pending) return;
448
+ const recovery = curatedRecovery.get(home); curatedRecovery.delete(home);
449
+ if (!pending && !recovery) return;
437
450
  publishingCurated = true;
438
451
  // #466: a project's own handle publishes its brief instead of a second handle indexing the same shard.
439
- try { for (const [store, projects] of pending) store.publishCurated(projects, store, true); }
440
- finally { publishingCurated = false; }
452
+ try {
453
+ for (const [store, projects] of pending ?? []) store.publishCurated(projects, store, true);
454
+ if (recover && recovery?.length) {
455
+ try {
456
+ const aliases = effectiveAliases(home);
457
+ const touched = new Set(Array.from(pending?.values() ?? []).flatMap(projects => [...projects].map(project => aliases.get(project) ?? project)));
458
+ const state = lifecycleResolver(home);
459
+ const candidates = recovery.filter(({ project }) => !touched.has(project) && !aliases.has(project) && state(project) === "active")
460
+ .sort((a, b) => b.activity - a.activity || a.project.localeCompare(b.project));
461
+ // Resume after the previous warm cohort. Reusing the removed set would always pick the same projects.
462
+ const start = candidates.findLastIndex(candidate => candidate.warm) + 1;
463
+ const additional = [...candidates.slice(start), ...candidates.slice(0, start)].slice(0, CURATED_RECOVERY_LIMIT);
464
+ if (additional.length) this.publishCurated(new Set(additional.map(candidate => candidate.project)));
465
+ } catch { recordBriefPublicationFailure(home, "curated", "source_unavailable"); }
466
+ }
467
+ } finally { publishingCurated = false; }
441
468
  };
442
469
  }
443
470
 
@@ -490,10 +517,23 @@ export class MemoryStore {
490
517
  if (this.curatedRelations.size > 8192) this.curatedRelations = null;
491
518
  }
492
519
 
520
+ private invalidateCuratedForPublication(projects?: readonly string[]): void {
521
+ const home = this.profile.home;
522
+ if (projects || !this.profile.sharded || publishingCurated || curatedRecovery.has(home)) {
523
+ invalidateCuratedCaches(home, projects);
524
+ return;
525
+ }
526
+ const candidates: CuratedCacheCandidate[] = [];
527
+ invalidateCuratedCaches(home, undefined, {
528
+ machine: this.machine.id, now: Date.now(), candidate: candidate => candidates.push(candidate),
529
+ });
530
+ curatedRecovery.set(home, candidates);
531
+ }
532
+
493
533
  /** #424: `local` means the change is visible only in `project`'s prebuilt brief; otherwise every project's cache is invalidated. */
494
534
  private markCuratedChange(project?: string, local = false): void {
495
535
  if (this.bootstrapOnly) return;
496
- invalidateCuratedCaches(this.profile.home, project && local ? [project] : undefined);
536
+ this.invalidateCuratedForPublication(project && local ? [project] : undefined);
497
537
  this.queueCuratedProjects(project ? [project] : []);
498
538
  }
499
539
 
@@ -522,7 +562,7 @@ export class MemoryStore {
522
562
  beginCuratedCacheUpdate(): () => void {
523
563
  const release = this.deferCuratedPublication();
524
564
  let before: Map<string, string>;
525
- try { before = this.curatedProjectRevisions(); invalidateCuratedCaches(this.profile.home); }
565
+ try { before = this.curatedProjectRevisions(); this.invalidateCuratedForPublication(); }
526
566
  catch (error) { release(); throw error; }
527
567
  return () => {
528
568
  try {
@@ -537,7 +577,7 @@ export class MemoryStore {
537
577
  /** Off-hook preparation; callers never invoke this from native SessionStart. */
538
578
  prepareCuratedBriefs(projects?: readonly string[]): void {
539
579
  try { this.curatedRebuildAll = projects === undefined; this.publishCurated(new Set(projects ?? []), projects?.length === 1 ? this : undefined); }
540
- catch { /* An off-hook read still succeeds when its optional derived cache cannot be prepared. */ }
580
+ catch { recordBriefPublicationFailure(this.profile.home, "curated", "source_unavailable"); }
541
581
  }
542
582
 
543
583
  private publishCurated(input: ReadonlySet<string>, opened?: MemoryStore, openOnMiss = false): void {
@@ -550,6 +590,7 @@ export class MemoryStore {
550
590
  }
551
591
  for (const raw of projects) {
552
592
  let view: MemoryStore | undefined;
593
+ let failure: "source_unavailable" | "binding_changed" | "write_failed" = "source_unavailable";
553
594
  try {
554
595
  const project = resolveAlias(this.profile.home, raw), aliases = aliasedKeys(this.profile.home, project);
555
596
  const common = { memoryDir: this.profile.home, deferPromotions: true, now: this.now, ...(aliases.length ? { reconcile: { canonical: project, aliases } } : {}) };
@@ -570,6 +611,7 @@ export class MemoryStore {
570
611
  view.curatedPublication = true;
571
612
  try {
572
613
  view.withStoreFences(() => {
614
+ failure = "binding_changed";
573
615
  const selected = readSelector(this.profile.home);
574
616
  const shards = sharded ? readShardedSelection(this.profile.home) : null;
575
617
  if (view!.profile.selectorRevision !== selected.revision || view!.profile.kind !== (shards ? "generation" : selected.selector?.kind ?? "shared-v1")
@@ -581,15 +623,20 @@ export class MemoryStore {
581
623
  }
582
624
  // Stamp the source handle's inputs, never a newer metadata read that it did not open.
583
625
  const binding = JSON.stringify({ selector: selected.revision, shards, aliases });
626
+ failure = "write_failed";
584
627
  ensureShardDescriptor(this.profile.home, project);
585
628
  const directory = shardMachineDir(this.profile.home, project, machineId(this.profile.home).id);
586
629
  mkdirSync(directory, { recursive: true, mode: 0o700 });
587
630
  buildCuratedBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
588
631
  buildPreferenceBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
589
- if (curatedProfileBinding(this.profile.home, project) !== binding) for (const name of ["brief-curated.json", "brief-preferences.json"]) rmSync(join(directory, name), { force: true });
632
+ failure = "binding_changed";
633
+ if (curatedProfileBinding(this.profile.home, project) !== binding) {
634
+ for (const name of ["brief-curated.json", "brief-preferences.json"]) rmSync(join(directory, name), { force: true });
635
+ recordBriefPublicationFailure(this.profile.home, "curated", failure);
636
+ }
590
637
  });
591
638
  } finally { view.curatedPublication = false; }
592
- } catch { /* Failed derived publication leaves the invalidated cache unavailable; a later mutation retries. */ }
639
+ } catch { recordBriefPublicationFailure(this.profile.home, "curated", failure); }
593
640
  finally { try { if (view !== opened) view?.close(); } catch { /* Preserve the authoritative mutation result. */ } }
594
641
  }
595
642
  }
@@ -906,7 +953,7 @@ export class MemoryStore {
906
953
  // #466: the settle rows and every promotion they release land before one publication runs, and `promoting` covers
907
954
  // this handle, its user overlay and its alias shards for the whole call.
908
955
  return this.withDeferredPromotions(() => {
909
- const release = this.deferCuratedPublication();
956
+ const release = this.deferCuratedPublication(false);
910
957
  try {
911
958
  const entry = { op: "settle", target: task, actor, by: this.until() } as const;
912
959
  const at = new Date(this.now()).toISOString();
@@ -931,6 +978,37 @@ export class MemoryStore {
931
978
  }
932
979
  /** Whether any entry was saved against the task. */
933
980
  hasTask(task: string): boolean { this.ensureFresh(); return this.readRows("SELECT 1 FROM entries WHERE task = ?", task).length > 0; }
981
+ /** A live page of task keys in this exact namespace without any visible settlement, including legacy. */
982
+ unsettledTaskKeys(project: string, options: { after?: string; limit?: number } = {}): { keys: string[]; next?: string } {
983
+ const { after, limit = 64 } = options;
984
+ if (typeof project !== "string" || !project.trim()) throw Error("Task discovery requires a non-empty project. Pass the board's project key.");
985
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 256) throw Error("Task discovery limit must be an integer from 1 to 256. Omit limit to use 64.");
986
+ if (after !== undefined && (typeof after !== "string" || taskProject(after) !== project))
987
+ throw Error("Invalid task discovery cursor. Use the next cursor returned for the same project, or omit after to start a new sweep.");
988
+ this.withDeferredPromotions(() => this.ensureFresh());
989
+ const stores = this.readStores(), candidates = new Set<string>();
990
+ for (const store of stores) {
991
+ if (store.stale) throw Error("Task discovery could not refresh a readable store. Another process may hold its index lock, or a segment may be unreadable. Retry the sweep later. If this persists, run amem doctor.");
992
+ const rows = store.db.query("SELECT task FROM unsettled_tasks WHERE project = ? AND task > ? ORDER BY task LIMIT ?")
993
+ .all(project, after ?? "", limit + 1) as { task: string }[];
994
+ for (const row of rows) candidates.add(row.task);
995
+ }
996
+ // SQLite BINARY orders UTF-8 bytes. Keep exactly that order when merging store frontiers.
997
+ const ordered = [...candidates].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)));
998
+ const examined = ordered.slice(0, limit);
999
+ const next = ordered.length > limit ? examined[limit - 1] : undefined;
1000
+ if (stores.length === 1 || !examined.length) return { keys: examined, ...(next ? { next } : {}) };
1001
+
1002
+ // A settlement may live only in another readable store. One indexed existence probe per key
1003
+ // and store suffices, even if many settle rows name the same key. Advance past keys settled in other stores too.
1004
+ const visibleSettlements = new Set<string>(), batch = JSON.stringify(examined);
1005
+ for (const store of stores) {
1006
+ const rows = store.db.query(`SELECT value AS task FROM json_each(?) AS candidate
1007
+ WHERE EXISTS (SELECT 1 FROM ops WHERE op = 'settle' AND target = candidate.value)`).all(batch) as { task: string }[];
1008
+ for (const row of rows) visibleSettlements.add(row.task);
1009
+ }
1010
+ return { keys: examined.filter(key => !visibleSettlements.has(key)), ...(next ? { next } : {}) };
1011
+ }
934
1012
  private promoting = false;
935
1013
  private readonly screen?: PromotionScreen;
936
1014
  /**
@@ -1024,7 +1102,7 @@ export class MemoryStore {
1024
1102
  // One transaction: no reader sees the index empty, and no other process commits an offset in between.
1025
1103
  this.rebuildingSearch = true;
1026
1104
  try {
1027
- this.db.transaction(() => { for (const t of ["segments", "heads", "entries", "ops", "edges", "goals"]) this.db.run(`DELETE FROM ${t}`); this.refresh(); }).immediate();
1105
+ this.db.transaction(() => { for (const t of ["segments", "heads", "entries", "ops", "edges", "goals", "unsettled_tasks"]) this.db.run(`DELETE FROM ${t}`); this.refresh(); }).immediate();
1028
1106
  } finally { this.rebuildingSearch = false; }
1029
1107
  this.syncSearchIndex(); // one batched derived write, not one search.db transaction per rebuilt entry
1030
1108
  }
@@ -1053,6 +1131,14 @@ export class MemoryStore {
1053
1131
  const inserted = this.db.query(`INSERT OR IGNORE INTO entries (id, at, machine, project, scope, tier, kind, peer, title, text, task, about, supersedes, promoted_from, source, expires)
1054
1132
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, e.at, e.machine, e.project, e.scope === "shared" ? "shared" : "project", e.tier === "long" ? "long" : "short",
1055
1133
  e.kind, e.peer, e.title ?? null, e.text, e.task ?? null, JSON.stringify(e.about.map(String)), e.supersedes ?? null, e.promotedFrom ?? null, e.source ?? "hub", typeof e.expires === "string" ? e.expires : null).changes;
1134
+ // The board namespace belongs to the task key, independently of the note's owning project.
1135
+ // INSERT OR IGNORE makes duplicate replay idempotent, and the indexed probe handles settle-before-note.
1136
+ if (e.task) {
1137
+ const project = taskProject(e.task);
1138
+ if (project !== null) this.db.query(`INSERT OR IGNORE INTO unsettled_tasks(project, task)
1139
+ SELECT ?, ? WHERE NOT EXISTS (SELECT 1 FROM ops WHERE op = 'settle' AND target = ?)`)
1140
+ .run(project, e.task, e.task);
1141
+ }
1056
1142
  this.rememberCuratedRelation(id, [e.supersedes, e.promotedFrom].filter((value): value is string => !!value));
1057
1143
  // The FTS copy follows the committed row. `changes` is only a hint here (bun:sqlite misreports it for ignored
1058
1144
  // inserts inside a transaction): addCurated is idempotent by entry id, and a missed hint becomes a count drift
@@ -1068,6 +1154,8 @@ export class MemoryStore {
1068
1154
  const dated = !["demote", "settle", "lease", "lease_force"].includes(e.op) || (typeof e.by === "string" && !Number.isNaN(Date.parse(e.by)));
1069
1155
  if (!str(e.target, 400) || !opt(e.by) || !opt(e.actor) || !dated) { this.log(`memory segment ${segment}: a malformed entry was skipped`); return; }
1070
1156
  this.db.query("INSERT OR IGNORE INTO ops (id, op, at, machine, target, by, actor) VALUES (?, ?, ?, ?, ?, ?, ?)").run(id, e.op, e.at, e.machine, e.target, e.by ?? null, e.actor ?? "");
1157
+ if (e.op === "settle") this.db.query("DELETE FROM unsettled_tasks WHERE project = ? AND task = ?")
1158
+ .run(taskProject(e.target), e.target);
1071
1159
  if (e.op === "supersede" && e.by) this.rememberCuratedRelation(e.target, [e.by]);
1072
1160
  }
1073
1161
  }
@@ -1256,7 +1344,14 @@ export class MemoryStore {
1256
1344
  const gone = new Set<string>();
1257
1345
  for (const v of expired) for (let id: string | undefined = v.id; id && !gone.has(id); id = parent.get(id)) gone.add(id);
1258
1346
  if (!gone.size) return 0;
1259
- this.db.transaction(() => { for (const id of gone) { this.db.query("DELETE FROM entries WHERE id = ?").run(id); this.db.query("DELETE FROM edges WHERE src = ?").run(id); } }).immediate();
1347
+ this.db.transaction(() => {
1348
+ for (const id of gone) {
1349
+ const row = this.db.query("DELETE FROM entries WHERE id = ? RETURNING task").get(id) as { task: string | null } | null;
1350
+ if (row?.task) this.db.query(`DELETE FROM unsettled_tasks WHERE project = ? AND task = ?
1351
+ AND NOT EXISTS (SELECT 1 FROM entries WHERE task = ?)`).run(taskProject(row.task), row.task, row.task);
1352
+ this.db.query("DELETE FROM edges WHERE src = ?").run(id);
1353
+ }
1354
+ }).immediate();
1260
1355
  this.searchIndex.markDirty(); // FTS cannot subtract rows incrementally: the next search resyncs it
1261
1356
  return gone.size;
1262
1357
  }
@@ -3,7 +3,9 @@
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";
6
+ import { MARKERS, SECTION_MARKER, SGR_RESET, cellWidth, markerCell, paint, Report, type MarkerName } from "@staix/cli-output";
7
+
8
+ import type { View } from "./store.ts";
7
9
 
8
10
  export interface Style {
9
11
  readonly color: boolean;
@@ -65,9 +67,104 @@ export function label(s: Style, state: "ok" | "attention" | "skipped" | "unavail
65
67
  return ` ${paint([{ role: MARKERS[marker].role, text }], s.color)}`;
66
68
  }
67
69
 
70
+ /** #590 C2: a past or future ISO time relative to `now` ("just now", "5 min ago", "3 h ago", "2 d ago", "in 4 d"); `--json` keeps the exact value. */
71
+ export function relativeTime(iso: string | null | undefined, now: number): string {
72
+ if (!iso) return "never";
73
+ const at = Date.parse(iso);
74
+ if (!Number.isFinite(at)) return "unknown time";
75
+ const delta = now - at, abs = Math.abs(delta), minute = 60_000, hour = 60 * minute, day = 24 * hour;
76
+ if (abs < minute) return "just now";
77
+ const amount = abs < hour ? `${Math.floor(abs / minute)} min` : abs < day ? `${Math.floor(abs / hour)} h` : `${Math.floor(abs / day)} d`;
78
+ return delta >= 0 ? `${amount} ago` : `in ${amount}`;
79
+ }
80
+
81
+ /** #590 C3: a byte count in binary units ("812 B", "5.7 KiB", "2.0 MiB"). */
82
+ export function humanBytes(bytes: number): string {
83
+ if (!Number.isFinite(bytes) || bytes < 1024) return `${Math.max(0, Math.round(bytes))} B`;
84
+ const units = ["KiB", "MiB", "GiB", "TiB"];
85
+ let value = bytes / 1024, unit = 0;
86
+ while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; }
87
+ return `${value.toFixed(1)} ${units[unit]}`;
88
+ }
89
+
90
+ /** #590 C1: `identicalGroups` -> `identical groups`, `cap_mb` -> `cap mb`; human rows never print a raw key. */
91
+ export const wordedKey = (key: string): string => key.replace(/_/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase();
92
+
93
+ /** #590 C1: worded "label value" pairs without JSON; zero, empty and null values are left out, as in `facts`. */
94
+ export function wordedFacts(values: Record<string, unknown>): string {
95
+ return Object.entries(values).filter(([, value]) => value !== 0 && value !== null && value !== undefined && value !== false && value !== ""
96
+ && !(Array.isArray(value) && value.length === 0) && !(typeof value === "object" && !Array.isArray(value) && Object.keys(value as object).length === 0))
97
+ .map(([key, value]) => `${wordedKey(key)} ${typeof value === "object" && !Array.isArray(value) ? wordedFacts(value as Record<string, unknown>) : Array.isArray(value) ? value.join(", ") : value === true ? "yes" : String(value)}`).join(", ");
98
+ }
99
+
68
100
  /** "key value" pairs, leaving out zero, empty and null values; returns "" when nothing material is left. */
69
101
  export function facts(values: Record<string, unknown>): string {
70
102
  return Object.entries(values).filter(([, value]) => value !== 0 && value !== null && value !== undefined && value !== false && value !== ""
71
103
  && !(Array.isArray(value) && value.length === 0) && !(typeof value === "object" && !Array.isArray(value) && Object.keys(value as object).length === 0))
72
104
  .map(([key, value]) => `${key} ${typeof value === "object" ? Array.isArray(value) ? value.join(", ") : JSON.stringify(value) : String(value)}`).join(", ");
73
105
  }
106
+
107
+ export const CLI_MEMORY_RENDER = Symbol("cli-memory-render");
108
+ export interface HumanMemoryRow { id: string; kind: string; at: string; text: string; project?: string; tier?: string; peer?: string; scope?: string; flags?: readonly string[] }
109
+ export interface HumanMemoryRender { columns?: number; style?: Style; now?: number; actor?: "person" | "agent" }
110
+ type HumanRender = HumanMemoryRender;
111
+ function clipCells(value: string, limit: number): string {
112
+ const text = singleLine(value).replace(/\s+/g, " ").trim();
113
+ if (cellWidth(text) <= limit) return text;
114
+ let out = "";
115
+ for (const { segment } of new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(text)) {
116
+ if (cellWidth(out + segment + "...") > limit) break;
117
+ out += segment;
118
+ }
119
+ return out.trimEnd() + "...";
120
+ }
121
+
122
+ /** Render only rows already selected and screened by the caller. */
123
+ export function memoryTableText(rows: readonly HumanMemoryRow[], title: string, render: HumanRender = {}, context?: string): string {
124
+ const width = Math.max(20, render.columns ?? 80), s = render.style ?? PLAIN, report = new Report(width, s.ascii, { sanitize: singleLine });
125
+ const tier = (row: HumanMemoryRow) => row.tier ? `${row.tier}${row.scope === "shared" ? "*" : ""}` : undefined;
126
+ const details = (row: HumanMemoryRow): string[] => [tier(row), row.peer, ...(row.flags ?? [])].filter((value): value is string => !!value);
127
+ report.header("amem", title); if (context) report.line(context); report.section("Entries", String(rows.length));
128
+ if (!rows.length) report.line(" No entries.");
129
+ else if (width < 65) report.table(["ID", "TEXT"], rows.flatMap(row => [[displayMemoryId(row.id, 12), clipCells(`${row.project ? `${row.project}: ` : ""}${row.text}`, Math.max(3, width - 18))], ...details(row).map(detail => ["", detail])]), 1, { widths: [12, Math.max(3, width - 18)], emptyCell: "blank" });
130
+ else if (rows.some(row => row.project)) {
131
+ const textWidth = Math.max(3, width - 54);
132
+ report.table(["PROJECT", "ID", "KIND", "WHEN", "TEXT"], rows.flatMap(row => [[clipCells(row.project ?? "", 16), displayMemoryId(row.id, 12), clipCells(row.kind, 8), clipCells(relativeTime(row.at, render.now ?? Date.now()), 8), clipCells(row.text, textWidth)], ...details(row).map(detail => ["", "", "", "", detail])]), 4, { widths: [16, 12, 8, 8, textWidth], emptyCell: "blank" });
133
+ }
134
+ else {
135
+ const textWidth = Math.max(3, width - 59);
136
+ report.table(["ID", "KIND", "TIER", "PEER", "WHEN", "TEXT"], rows.flatMap(row => [[displayMemoryId(row.id, 13), clipCells(row.kind, 10), clipCells(tier(row) ?? "-", 6), clipCells(row.peer ?? "-", 8), clipCells(relativeTime(row.at, render.now ?? Date.now()), 10), clipCells(row.text, textWidth)], ...(row.flags ?? []).map(flag => ["", "", "", "", "", flag])]), 5, { widths: [13, 10, 6, 8, 10, textWidth], emptyCell: "blank" });
137
+ }
138
+ if (rows.some(row => row.tier && row.scope === "shared")) report.note("* marks shared scope.");
139
+ if (rows.length) report.note("Full text: amem show <id> or --json.");
140
+ return report.render(s.color).join("\n");
141
+ }
142
+
143
+ function displayMemoryId(id: string, limit: number): string {
144
+ return /^(?:repo:)?[a-f0-9]{16,}$/.test(id) ? id.slice(0, limit) : clipCells(id, limit);
145
+ }
146
+
147
+ export function memoryRecordText(row: HumanMemoryRow, render: HumanRender = {}, fields: readonly (readonly [string, string])[] = []): string {
148
+ const s = render.style ?? PLAIN, report = new Report(render.columns ?? 80, s.ascii, { sanitize: text => text.replace(/[\p{Cf}\p{Zl}\p{Zp}]/gu, " ") });
149
+ report.header("amem", "Memory"); report.section("Entry");
150
+ report.kv([["ID", row.id], ["Kind", row.kind], ["When", relativeTime(row.at, render.now ?? Date.now())], ...fields]);
151
+ report.section("Text"); report.line(row.text);
152
+ return report.render(s.color).join("\n");
153
+ }
154
+
155
+ export function memoryScoresText(rows: readonly { id: string; details: Record<string, unknown> }[], render: HumanRender = {}): string {
156
+ if (!rows.length) return "";
157
+ const s = render.style ?? PLAIN, report = new Report(render.columns ?? 80, s.ascii, { sanitize: singleLine });
158
+ report.section("Scores");
159
+ report.kv(rows.map(row => [displayMemoryId(row.id, 16), Object.entries(row.details).map(([key, value]) => `${wordedKey(key)} ${value === null || value === undefined ? "-" : String(value)}`).join(", ")]));
160
+ return report.render(s.color).join("\n");
161
+ }
162
+
163
+ export function memoryDetailText(view: View, render: HumanRender = {}): string {
164
+ const s = render.style ?? PLAIN, report = new Report(render.columns ?? 80, s.ascii, { sanitize: text => text.replace(/[\p{Cf}\p{Zl}\p{Zp}]/gu, " ") });
165
+ const stale = view as View & { stale?: boolean; staleReason?: string };
166
+ report.header("amem", "Memory"); report.section("Entry");
167
+ report.kv([["ID", view.id], ["Kind", view.kind], ["Tier", view.tier], ["When", relativeTime(view.at, render.now ?? Date.now())], ["Peer", view.peer], ["Scope", view.scope], ["Project", view.project], ["Machine", view.machine], ...(render.actor ? [["Actor", render.actor] as [string, string]] : []), ...(stale.stale ? [["Stale", stale.staleReason?.replace(/_/g, " ") ?? "yes"] as [string, string]] : []), ...(view.task ? [["Task", view.task] as [string, string]] : []), ...(view.expiresAt ? [["Expires", relativeTime(view.expiresAt, render.now ?? Date.now())] as [string, string]] : []), ...(view.promotedFrom ? [["Promoted from", view.promotedFrom] as [string, string]] : []), ...(view.supersededBy ? [["Superseded by", view.supersededBy] as [string, string]] : []), ...(view.about.length ? [["About", view.about.join(", ")] as [string, string]] : [])]);
168
+ report.section("Text"); if (view.title) report.line(view.title); report.line(view.text);
169
+ return report.render(s.color).join("\n");
170
+ }
@@ -18,11 +18,11 @@ const phases: Record<PlacementSyncBoundPhase, string> = { "source-capture": "sou
18
18
  export function placementSyncBoundMessage(bound: PlacementSyncBound): string {
19
19
  // #288 step 3: a full live window is relieved by a person-reviewed checkpoint; records stay a reported bound.
20
20
  const remedy = bound.kind === "journal-objects"
21
- ? "The active epoch journal cannot hold this publication; preview a checkpoint with amem migrate --sync-placement --checkpoint --writer-root <install root> (repeat for every install), then confirm it after the exact command is approved and rerun amem sync."
21
+ ? "The active epoch journal cannot hold this publication. Save a new private preview with (umask 077; set -C; amem migrate --sync-placement --checkpoint --writer-root <install root> --json > checkpoint-plan.json). Repeat --writer-root for every install. After reviewing and approving the saved plan, run amem migrate --sync-placement --checkpoint --writer-root <install root> --confirm --plan checkpoint-plan.json with the same roots, then rerun amem sync."
22
22
  : bound.kind === "journal-records"
23
23
  ? "The active epoch journal cannot hold this publication; retain the inputs and report this bound."
24
24
  : "Retain the inputs and report this bound; no row was omitted to fit.";
25
- return `Placement sync refused before any publication attempt: ${phases[bound.phase]} exceeds its supported ${bound.kind} bound (observed ${bound.observed}, limit ${bound.limit}). No source, selector, epoch, journal or remote ref was changed. ${remedy}`;
25
+ return `Placement sync refused before any publication attempt: ${phases[bound.phase]} exceeds its supported ${bound.kind} bound (observed ${bound.observed}, limit ${bound.limit}). No source, selector, epoch, journal or remote ref was changed by this publication. ${remedy}`;
26
26
  }
27
27
  /** Expected input refusal before a publication attempt exists. Code stays "bound" for existing callers. */
28
28
  export class PlacementSyncBoundError extends SyncPlacementJournalError {
@@ -26,7 +26,7 @@ import { withPlacementCheckpointFences } from "./sync-placement-activation-locks
26
26
  import { assertPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
27
27
  import { placementFenceDirectories } from "./sync-placement-writer-renewal.ts";
28
28
  import { initialPlacementWriterContext } from "../sync-placement-writer-context.ts";
29
- import { readSetupWriterRoots, SetupWriterRootsError } from "../setup.ts";
29
+ import { readSetupWriterRoots, SetupWriterRootsError } from "../setup-writer-roots.ts";
30
30
  import { checkpointProspective, type CheckpointProspective } from "./sync-placement-checkpoint-prospective.ts";
31
31
  import { ShardHistoryError, type ShardHistoryCause } from "./shard-sync-history.ts";
32
32
 
@@ -0,0 +1,93 @@
1
+ /**
2
+ * #612: a derived, machine-local cache that lets a placement publication with nothing to do skip policy evaluation.
3
+ * It holds one key digest and the four not-needed decision counts, never a path, row id or text. It is never read
4
+ * for publication, capture or import: a hit only returns `not-needed` with the stored counts, and any read failure,
5
+ * unknown schema, size overrun, bad count, foreign owner, loose mode, link or key mismatch takes the full path.
6
+ * Deleting it is always safe. Every operation stays inside `<home>/sync-noop-cache/` and touches nothing else.
7
+ * ponytail: one file per publication slot (sha256 of the epoch and its selected realms); the upgrade path is pruning
8
+ * slots not seen in the last inventory run if stale slots ever accumulate past a handful per home.
9
+ */
10
+ import { createHash, randomBytes } from "node:crypto";
11
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeSync, type Stats } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { canonicalJSON } from "./generation.ts";
14
+
15
+ export const PLACEMENT_NOOP_CACHE_SCHEMA = "agent-mem.placement-noop-cache/v1";
16
+ export const PLACEMENT_NOOP_CACHE_MAX_BYTES = 512;
17
+ export const PLACEMENT_NOOP_CACHE_DIR = "sync-noop-cache";
18
+
19
+ export interface PlacementNoopCounts { permitted: number; local: number; declined: number; held: number }
20
+ export interface PlacementNoopKeyInput {
21
+ version: string; writersHash: string; screenIdentity: string | null; policyHash: string; sourceHash: string; aliasesHash: string; contextHash: string; markerHash: string;
22
+ remoteHash: string; journal: { sequence: number; headHash: string };
23
+ targets: readonly { remote: string | null; local: string | null; pruned: readonly string[]; fetched: readonly string[] }[];
24
+ }
25
+
26
+ const sha = (value: string) => createHash("sha256").update(value).digest("hex");
27
+ const HEX64 = /^[a-f0-9]{64}$/;
28
+
29
+ /** The reuse key: every input a no-op decision depends on. Any change produces a different digest. */
30
+ export function placementNoopKey(input: PlacementNoopKeyInput): string {
31
+ return sha(canonicalJSON({ ...input, targets: input.targets.map(t => ({ ...t, pruned: [...t.pruned].sort(), fetched: [...t.fetched].sort() })) }));
32
+ }
33
+
34
+ const uid = () => process.getuid?.();
35
+ /** Owned by this user, no group/other bits, and the expected type. Symbolic links never qualify. */
36
+ function privateNode(stat: Stats | undefined, kind: "dir" | "file"): boolean {
37
+ if (!stat || stat.isSymbolicLink() || (kind === "dir" ? !stat.isDirectory() : !stat.isFile())) return false;
38
+ const owner = uid(); return (owner === undefined || stat.uid === owner) && (stat.mode & 0o077) === 0;
39
+ }
40
+ function cacheDir(home: string): string | undefined {
41
+ const dir = join(home, PLACEMENT_NOOP_CACHE_DIR);
42
+ try { return privateNode(lstatSync(dir, { throwIfNoEntry: false }), "dir") ? dir : undefined; } catch { return undefined; }
43
+ }
44
+ const count = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
45
+ const NOFOLLOW = constants.O_NOFOLLOW ?? 0, NONBLOCK = constants.O_NONBLOCK ?? 0;
46
+
47
+ /** Stored counts when the file holds exactly `key`; undefined on any other state. Never throws, never writes. */
48
+ export function readPlacementNoopCache(home: string, slot: string, key: string): PlacementNoopCounts | undefined {
49
+ if (!HEX64.test(slot)) return undefined;
50
+ const dir = cacheDir(home); if (!dir) return undefined;
51
+ let fd: number | undefined;
52
+ try {
53
+ fd = openSync(join(dir, `${slot}.json`), constants.O_RDONLY | NOFOLLOW | NONBLOCK);
54
+ const stat = fstatSync(fd); if (!privateNode(stat, "file") || stat.size > PLACEMENT_NOOP_CACHE_MAX_BYTES) return undefined;
55
+ const buffer = Buffer.alloc(PLACEMENT_NOOP_CACHE_MAX_BYTES + 1); let length = 0, read = 0;
56
+ while ((read = readSync(fd, buffer, length, buffer.length - length, null)) > 0) { length += read; if (length > PLACEMENT_NOOP_CACHE_MAX_BYTES) return undefined; }
57
+ if (!cacheDir(home)) return undefined; // the directory must still be the private one after the read
58
+ const value = JSON.parse(buffer.subarray(0, length).toString("utf8")) as Record<string, unknown>;
59
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 3) return undefined;
60
+ if (value.schema !== PLACEMENT_NOOP_CACHE_SCHEMA || typeof value.key !== "string" || !HEX64.test(value.key) || value.key !== key) return undefined;
61
+ const c = value.counts as Record<string, unknown> | null;
62
+ if (!c || typeof c !== "object" || Array.isArray(c) || Object.keys(c).length !== 4) return undefined;
63
+ if (!count(c.permitted) || !count(c.local) || !count(c.declined) || !count(c.held)) return undefined;
64
+ return { permitted: c.permitted, local: c.local, declined: c.declined, held: c.held };
65
+ } catch { return undefined; }
66
+ finally { if (fd !== undefined) try { closeSync(fd); } catch { /* cache only */ } }
67
+ }
68
+
69
+ /** Atomic private write (0700 directory, 0600 file, exclusive temporary then rename). Best effort: a failure only loses the cache. */
70
+ export function writePlacementNoopCache(home: string, slot: string, key: string, counts: PlacementNoopCounts): void {
71
+ if (!HEX64.test(slot) || !HEX64.test(key) || ![counts.permitted, counts.local, counts.declined, counts.held].every(count)) return;
72
+ const bytes = Buffer.from(canonicalJSON({ schema: PLACEMENT_NOOP_CACHE_SCHEMA, key, counts: { permitted: counts.permitted, local: counts.local, declined: counts.declined, held: counts.held } }) + "\n");
73
+ if (bytes.length > PLACEMENT_NOOP_CACHE_MAX_BYTES) return;
74
+ try { mkdirSync(join(home, PLACEMENT_NOOP_CACHE_DIR), { mode: 0o700 }); } catch { /* exists or unavailable: checked next */ }
75
+ const dir = cacheDir(home); if (!dir) return;
76
+ const temp = join(dir, `.${randomBytes(8).toString("hex")}.tmp`); let created = false;
77
+ try {
78
+ const fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | NOFOLLOW, 0o600); created = true;
79
+ try { writeSync(fd, bytes); fsyncSync(fd); } finally { closeSync(fd); }
80
+ if (!cacheDir(home)) return;
81
+ const target = join(dir, `${slot}.json`), prior = lstatSync(target, { throwIfNoEntry: false });
82
+ if (prior && !prior.isFile()) return; // never replace a link or directory someone else put there
83
+ renameSync(temp, target); created = false;
84
+ } catch { /* cache only */ }
85
+ finally { if (created) try { unlinkSync(temp); } catch { /* cache only */ } }
86
+ }
87
+
88
+ /** Invalidate one slot: any outcome other than not-needed. Removes only a regular file inside the private directory. Never throws. */
89
+ export function clearPlacementNoopCache(home: string, slot: string): void {
90
+ if (!HEX64.test(slot)) return;
91
+ const dir = cacheDir(home); if (!dir) return;
92
+ try { const path = join(dir, `${slot}.json`), stat = lstatSync(path, { throwIfNoEntry: false }); if (stat?.isFile()) unlinkSync(path); } catch { /* cache only */ }
93
+ }
@@ -1,3 +1,21 @@
1
+ import type { PlacementWriterRootCategory } from "../sync-placement-writer-context.ts";
2
+
1
3
  /** #426: the fixed refusal categories of a placement sync; shared by the transport and the progress sidecar. */
2
4
  export const PLACEMENT_REFUSAL_CATEGORIES = ["epoch", "source-selection", "policy", "remote", "writer-pin", "size-bound", "lock", "other"] as const;
3
5
  export type PlacementRefusalCategory = typeof PLACEMENT_REFUSAL_CATEGORIES[number];
6
+
7
+ /** #613: only these two fixed writer-proof facts may be retained. */
8
+ export const WRITER_ROOT_CATEGORIES = ["running CLI", "host package", "setup receipt", "declared writer", "active locator", "home floor", "writer renewal"] as const satisfies readonly PlacementWriterRootCategory[];
9
+ export const WRITER_CAUSE_CLASSES = ["missing", "changed", "unavailable"] as const;
10
+ export interface PlacementWriterRefusal {
11
+ causeClass: typeof WRITER_CAUSE_CLASSES[number];
12
+ rootCategory: PlacementWriterRootCategory;
13
+ }
14
+
15
+ export function validPlacementWriterRefusal(value: unknown): value is PlacementWriterRefusal {
16
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 2) return false;
17
+ const { causeClass, rootCategory } = value as Record<string, unknown>;
18
+ return Object.hasOwn(value, "causeClass") && Object.hasOwn(value, "rootCategory")
19
+ && (WRITER_CAUSE_CLASSES as readonly unknown[]).includes(causeClass)
20
+ && (WRITER_ROOT_CATEGORIES as readonly unknown[]).includes(rootCategory);
21
+ }