@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
@@ -8,7 +8,7 @@ import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncF
8
8
  import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
9
9
  import { isLocalKey, localKeyOptInMessage, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
10
10
  import { memoryPolicySnapshot } from "./policy.ts";
11
- import { outboundPolicyEvaluator } from "./sync-screen.ts";
11
+ import { outboundPolicyEvaluator, rowScreenIdentity } from "./sync-screen.ts";
12
12
  import { readActivePlacementBinding } from "./sync-placement-active.ts";
13
13
  import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
14
14
  import { captureSyncPlacementContextAsync, placementCaptureContextHash, previewSyncPlacementSources, type PlacementCapture, type PlacementPendingSource } from "./sync-placement-capture.ts";
@@ -21,7 +21,8 @@ import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, SyncPlacementFormatError }
21
21
  import { PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS, createPlacementRecord, placementKeyId, type PlacementEvent, type PlacementRealm, type PlacementRecord } from "./sync-placement-journal-format.ts";
22
22
  import { rebuildPlacementProjection, type PlacementProjection } from "./sync-placement-projection.ts";
23
23
  import { readPlacementJournal, readPlacementWriterJournalAnchors, placementWriterJournalToken, appendPlacementEvent, appendPlacementEvents, releasePlacementStorageCaches, ensurePlacementPublicationDurability, readPlacementPublicationMetadata, placementDecisionOwners, placementJournalObjectComposition, placementJournalObjectCompositionText, type PlacementJournalObjectComposition, type PlacementJournalRead, type PlacementStorageOptions } from "./sync-placement-journal-storage.ts";
24
- import { formatFloorAtLeast } from "./formats.ts";
24
+ import { amemReaderVersion, formatFloorAtLeast } from "./formats.ts";
25
+ import { clearPlacementNoopCache, placementNoopKey, readPlacementNoopCache, writePlacementNoopCache, type PlacementNoopCounts } from "./sync-placement-noop-cache.ts";
25
26
  import { preparePlacementPublication, readPlacementPublication, recordPlacementPublicationPhase, type PlacementPublicationRead } from "./sync-placement-publication-storage.ts";
26
27
  import { planPlacementPublication, planPlacementPublicationAsync, planPlacementPublicationV2Async, placementDecisionReuseEnabled, PLACEMENT_PUBLICATION_PLAN_V2_SCHEMA, publicationBytes, publicationFileNames, type PlacementPublicationBundle, type PlacementPublicationDecision, type PlacementPublicationSource, type PlacementPublicationObject } from "./sync-placement-publication-plan.ts";
27
28
  import { placementPublicationEventSteps } from "./sync-placement-publication-events.ts";
@@ -293,6 +294,24 @@ class PlacementTransport {
293
294
  phaseNow: SyncProgressPhase = "writer-verification";
294
295
  enter(...args: Parameters<SyncProgress["phase"]>): void { this.phaseNow = args[0]; this.progress?.phase(...args); }
295
296
  refusal?: PlacementRefusalCategory;
297
+ /** #612: the last materialization's decision counts, and the counts a no-op cache hit returned. */
298
+ decisionCounts?: PlacementNoopCounts; noopHit?: PlacementNoopCounts; noopKept=false; syncLockHeld=false;
299
+ /** #612: optional slot deletion runs only with the sync lock and every mutation fence positively held and still current. */
300
+ holdsNoopFences(): boolean {
301
+ if(!this.syncLockHeld||!this.rootMutation||!this.homeMutation||!this.targets.length||this.targets.some(target=>!target.mutation))return false;
302
+ try{this.metadata();return true;}catch{return false;}
303
+ }
304
+ /** #612: the no-op reuse key over this run's captured and freshly read inputs; undefined when any input is missing. */
305
+ noopSlot(): string { return digest(canonicalJSON({epochHash:this.epochHash,realms:this.targets.map(physical)})); }
306
+ noopKey(): string|undefined {
307
+ const capture=this.capture,version=amemReaderVersion();if(!capture||!version||!this.writerInventory||!this.epochHash)return undefined;
308
+ // An arbitrary host screen has no cross-run identity, so it always takes the full path; only the package's deterministic screen binds.
309
+ const screenIdentity=this.opts.screen===undefined?null:rowScreenIdentity(this.opts.screen);if(screenIdentity===undefined)return undefined;
310
+ return placementNoopKey({version,screenIdentity,writersHash:hashJSON({writers:this.writerInventory.writers,revision:this.writerInventory.revisionHash??null}),
311
+ policyHash:capture.context.policyHash,sourceHash:capture.context.sourceHash,aliasesHash:capture.context.aliasesHash,contextHash:placementCaptureContextHash(capture),
312
+ markerHash:capture.markerHash,remoteHash:digest(this.url),journal:{sequence:this.journal.sequence,headHash:this.journal.headHash},
313
+ targets:this.targets.map(target=>({remote:target.remote??null,local:target.local??null,pruned:[...(target.store.prunePort().snapshot().pruned??[])],fetched:[...target.fetched]}))});
314
+ }
296
315
  async observe(phase: PlacementSyncPhase): Promise<void> { await this.phase?.(phase); }
297
316
  storage(factual = false): PlacementStorageOptions { if (!this.homeMutation) refuse(); return { mutation: this.homeMutation, assertCurrent: factual ? () => this.metadata() : this.check, ...(this.attemptHash ? { publicationAttemptHash: this.attemptHash } : {}) }; }
298
317
  configStamp():string {
@@ -342,7 +361,7 @@ class PlacementTransport {
342
361
  await yieldTurn(); this.prove(); // a host callout ends any reusable proof
343
362
  if (!existsSync(this.root)) mkdirSync(this.root, { mode: 0o700 });
344
363
  const transport = acquireMutation(this.root); if (!transport) refuse("lock"); this.rootMutation=transport; this.releases.push(transport);
345
- const sync = generationSyncLock(this.root); if (!sync) refuse("lock"); this.releases.push(sync);
364
+ const sync = generationSyncLock(this.root); if (!sync) refuse("lock"); this.releases.push(sync); this.syncLockHeld=true;
346
365
  for (const dir of [...new Set([this.home, ...this.targets.map(target => target.store.dir)])].sort()) {
347
366
  const handle = acquireMutation(dir); if (!handle) refuse("lock"); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
348
367
  for (const target of this.targets) if (target.store.dir === dir) target.mutation = handle;
@@ -459,11 +478,11 @@ class PlacementTransport {
459
478
  this.prove();
460
479
  for(const [index,target]of this.targets.entries())Object.assign(target,materialized.targets[index]!);
461
480
  const {decisions,plannedTargets:targets,objects}=materialized;
462
- if(this.progress){
481
+ {
463
482
  // Each decision lands in one bucket: policy-declined, source-local, or held for a journal/dependency reason.
464
483
  const counts={permitted:0,local:0,declined:0,held:0},other=new Set(["journal-hold","related-local","unsupported-reference","unverified-prune"]);
465
484
  for(const d of decisions)counts[d.eligible?"permitted":d.reason==="source-local"?"local":d.reason&&!other.has(d.reason)?"declined":"held"]++;
466
- this.progress.counts(counts);
485
+ this.decisionCounts=counts;this.progress?.counts(counts);
467
486
  }
468
487
  this.enter("publication-plan");
469
488
  const body={epochHash:this.epochHash,generation:this.journal.epoch.generation,homeHash:capture.context.homeHash,contextHash:placementCaptureContextHash(capture),markerHash:capture.markerHash,
@@ -680,7 +699,7 @@ class PlacementTransport {
680
699
  const cause:SyncFailureCause|undefined=ok?undefined:this.opts.signal?.aborted?"stopped":this.bound?"bound":outcome==="unknown"?"unknown-outcome":this.failureCause??(this.refusal?"refusal":"unavailable");
681
700
  return{ok,pushed:this.accepted&&(this.attempted||this.recovered&&!!this.current?.bundle.root.targets.some(target=>target.publish)),entries:this.current?.exported??0,...(error?{error}:{}),
682
701
  ...(cause?{failure:{cause,...(cause==="refusal"&&this.refusal?{category:this.refusal}:{})}}:{}),...(this.applications?{pruneApplication:{...this.applications.application}}:{}),
683
- placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),...(this.journalObjects?{journalObjects:this.journalObjects}:{}),...(this.refusal?{refusal:{category:this.refusal,phase:this.phaseNow}}:{}),withheld:this.current?.withheld??0,exported:this.current?.exported??0,
702
+ placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),...(this.journalObjects?{journalObjects:this.journalObjects}:{}),...(this.refusal?{refusal:{category:this.refusal,phase:this.phaseNow}}:{}),withheld:this.current?.withheld??(this.noopHit?this.noopHit.local+this.noopHit.declined+this.noopHit.held:0),exported:this.current?.exported??0,
684
703
  ...(this.lastPolicyHash?{lastPolicyHash:this.lastPolicyHash}:{}),...(this.lastPolicyCheckUnixMs!==undefined?{lastPolicyCheckUnixMs:this.lastPolicyCheckUnixMs,policyCheckSource:this.policyCheckSource??(this.recovered?"durable-intent" as const:"live" as const)}:{}),
685
704
  policyCeiling:"last-positive-check-before-in-flight-push",...(this.recovered?{recovered:true}:{})}};
686
705
  }
@@ -732,6 +751,16 @@ class PlacementTransport {
732
751
  &&root.policyHash===this.capture!.context.policyHash&&root.targets.every((target,index)=>target.expectedRemoteHead===(this.targets[index]?.remote??null));
733
752
  if(!stable)return await this.terminalUnknown(retained);
734
753
  }
754
+ // #612: a fresh attempt whose every no-op input equals the last not-needed run skips policy evaluation; any mismatch takes the full path.
755
+ const noopKey=retained?undefined:this.noopKey();
756
+ if(noopKey){
757
+ const hit=readPlacementNoopCache(this.home,this.noopSlot(),noopKey);
758
+ if(hit){
759
+ await yieldTurn();const applications=await this.applicationCoordinator();await applications.prepare();
760
+ if(!this.importsNeeded()){this.prove();this.noopHit=hit;this.noopKept=true;this.progress?.counts(hit);this.attemptHash=undefined;return this.result(true,"not-needed");}
761
+ }
762
+ }
763
+ clearPlacementNoopCache(this.home,this.noopSlot());
735
764
  const frontier=retained?{...this.journal,sequence:retained.bundle.root.journal.sequence,headHash:retained.bundle.root.journal.headHash}:this.journal;
736
765
  const material=await this.materialize(retained?.bundle.root.createdUnixSeconds??Math.floor(Date.now()/1000),frontier,retained?.bundle);
737
766
  const changed=material.bundle.root.targets.some((target,index)=>target.publish&&target.commit!==(this.targets[index]!.remote??null));
@@ -749,7 +778,11 @@ class PlacementTransport {
749
778
  }
750
779
  this.current=material;this.attemptHash=material.bundle.root.seal;
751
780
  await yieldTurn();const applications=await this.applicationCoordinator();await applications.prepare();
752
- if(!retained&&!material.events.length&&!changed&&!this.importsNeeded()){this.attemptHash=undefined;return this.result(true,"not-needed");}
781
+ if(!retained&&!material.events.length&&!changed&&!this.importsNeeded()){
782
+ this.attemptHash=undefined;
783
+ if(noopKey&&this.decisionCounts&&noopKey===this.noopKey()){writePlacementNoopCache(this.home,this.noopSlot(),noopKey,this.decisionCounts);this.noopKept=true;}
784
+ return this.result(true,"not-needed");
785
+ }
753
786
  if(!retained){await this.observe("before-plan-fsync");await yieldTurn();this.prove();preparePlacementPublication(this.home,material.bundle,this.storage());await this.observe("plan-fsynced");await yieldTurn();this.prove();}
754
787
  // One mutation batch: a complete proof on each side, fence checks (and at most 1 s of proof reuse) per record.
755
788
  this.prove();await this.appendThrough(material.bundle,material.events,material.preCount);this.prove();
@@ -791,6 +824,9 @@ class PlacementTransport {
791
824
  return this.result(false,"not-needed",placementRefusalMessage(this.refusal,this.phaseNow));
792
825
  }finally{
793
826
  let ownedCache=true;try{this.metadata();}catch{ownedCache=false;}
827
+ // #612: every terminal path other than a full-path not-needed or a cache hit invalidates its slot, but only once admission
828
+ // completed: the sync lock and every mutation fence are held and current. A run refused before that leaves the slot alone.
829
+ if(!this.noopKept&&this.epochHash&&this.holdsNoopFences())try{clearPlacementNoopCache(this.home,this.noopSlot());}catch{}
794
830
  if(ownedCache){
795
831
  for(const ref of this.refs)try{this.metadata();await generationSyncGit(this.root,this.args(["update-ref","--no-deref","-d",ref]),undefined);}catch{}
796
832
  for(const file of this.temporary)try{this.metadata();rmSync(file,{force:true});}catch{}
@@ -0,0 +1,7 @@
1
+ import type { PlacementWriterRefusal } from "./sync-placement-refusal-category.ts";
2
+
3
+ export function writerRefusalText({ causeClass, rootCategory }: PlacementWriterRefusal): string {
4
+ const writerRoot = rootCategory !== "active locator" && rootCategory !== "home floor";
5
+ const renewal = rootCategory === "writer renewal" || (writerRoot && causeClass !== "unavailable");
6
+ return `${renewal ? "writer renewal needed" : "writer proof refused"} (${rootCategory}, ${causeClass})`;
7
+ }
@@ -9,7 +9,7 @@
9
9
  import { randomBytes } from "node:crypto";
10
10
  import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, opendirSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";
11
11
  import { join } from "node:path";
12
- import { PLACEMENT_REFUSAL_CATEGORIES, type PlacementRefusalCategory } from "./sync-placement-refusal-category.ts";
12
+ import { PLACEMENT_REFUSAL_CATEGORIES, validPlacementWriterRefusal, type PlacementRefusalCategory, type PlacementWriterRefusal } from "./sync-placement-refusal-category.ts";
13
13
  import { processLiveness, processSignature, type Liveness } from "./platform.ts";
14
14
 
15
15
  export const SYNC_PROGRESS_SCHEMA = "agent-mem.sync-progress/v1", SYNC_PROGRESS_INTERVAL_MS = 1000, SYNC_PROGRESS_DIR = "sync-status";
@@ -48,6 +48,16 @@ export interface SyncProgressSnapshot {
48
48
  /** #426: for a failed placement sync, the fixed category of the check that refused (allowlisted, no text). */
49
49
  category?: PlacementRefusalCategory;
50
50
  }
51
+ interface SyncStatusSnapshot extends SyncProgressSnapshot {
52
+ writerRefusal?: PlacementWriterRefusal;
53
+ }
54
+
55
+ /** The CLI attaches its typed writer evidence only at a failed terminal checkpoint. */
56
+ export function syncStatusSnapshot(snapshot: SyncProgressSnapshot, writerRefusal?: PlacementWriterRefusal): SyncStatusSnapshot {
57
+ if (snapshot.state !== "failed" || !validPlacementWriterRefusal(writerRefusal)) return snapshot;
58
+ return { ...snapshot, writerRefusal: { causeClass: writerRefusal.causeClass, rootCategory: writerRefusal.rootCategory } };
59
+ }
60
+
51
61
  export type SyncProgressSink = (snapshot: SyncProgressSnapshot) => void;
52
62
  export interface SyncProgressOptions { sink: SyncProgressSink; intervalMs?: number; now?: () => number; mono?: () => number; operationId?: string }
53
63
 
@@ -157,7 +167,7 @@ function readBounded(file: string): Buffer | undefined {
157
167
  }
158
168
  const count = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
159
169
  /** Allowlisted enumerations and non-negative integers only: a tampered sidecar cannot inject text into a terminal. */
160
- function validate(value: unknown, operationId: string): { snapshot: SyncProgressSnapshot; owner: Owner } | undefined {
170
+ function validate(value: unknown, operationId: string): { snapshot: SyncStatusSnapshot; owner: Owner } | undefined {
161
171
  if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
162
172
  const v = value as Record<string, unknown>, owner = v.owner as Record<string, unknown> | undefined, proofs = v.proofs as Record<string, unknown> | undefined, counts = v.counts as Record<string, unknown> | undefined, inventory = v.inventory as Record<string, unknown> | undefined;
163
173
  if (v.schema !== SYNC_PROGRESS_SCHEMA || v.operationId !== operationId || !(STATES as readonly unknown[]).includes(v.state) || !(PHASES as readonly unknown[]).includes(v.phase)
@@ -166,12 +176,13 @@ function validate(value: unknown, operationId: string): { snapshot: SyncProgress
166
176
  || v.unit !== undefined && (!(UNITS as readonly unknown[]).includes(v.unit) || !count(v.completed)) || v.total !== undefined && !count(v.total)
167
177
  || v.cause !== undefined && !(CAUSES as readonly unknown[]).includes(v.cause)
168
178
  || v.category !== undefined && !(PLACEMENT_REFUSAL_CATEGORIES as readonly unknown[]).includes(v.category)
179
+ || v.writerRefusal !== undefined && (v.state !== "failed" || !validPlacementWriterRefusal(v.writerRefusal))
169
180
  || counts !== undefined && ![counts.permitted, counts.local, counts.declined, counts.held].every(count)
170
181
  || inventory !== undefined && (!inventory || typeof inventory !== "object" || ![inventory.publications, inventory.completed, inventory.realms].every(count) || (inventory.completed as number) > (inventory.publications as number)
171
182
  || inventory.truncated !== undefined && inventory.truncated !== true
172
183
  || inventory.outcomes !== undefined && (!Array.isArray(inventory.outcomes) || inventory.outcomes.length > MAX_REALM_OUTCOMES
173
184
  || inventory.outcomes.some((item: unknown) => !item || typeof item !== "object" || !realmLabel((item as { realm?: unknown }).realm) || !(SYNC_REALM_OUTCOMES as readonly unknown[]).includes((item as { outcome?: unknown }).outcome))))) return undefined;
174
- const snapshot: SyncProgressSnapshot = { schema: SYNC_PROGRESS_SCHEMA, operationId, state: v.state as SyncProgressState, phase: v.phase as SyncProgressPhase, attempt: v.attempt as number,
185
+ const snapshot: SyncStatusSnapshot = { schema: SYNC_PROGRESS_SCHEMA, operationId, state: v.state as SyncProgressState, phase: v.phase as SyncProgressPhase, attempt: v.attempt as number,
175
186
  startedUnixMs: v.startedUnixMs as number, elapsedMs: v.elapsedMs as number, phaseElapsedMs: v.phaseElapsedMs as number,
176
187
  ...(v.unit !== undefined ? { unit: v.unit as SyncProgressUnit, completed: v.completed as number, ...(v.total !== undefined ? { total: v.total as number } : {}) } : {}),
177
188
  ...(counts ? { counts: { permitted: counts.permitted as number, local: counts.local as number, declined: counts.declined as number, held: counts.held as number } } : {}),
@@ -179,10 +190,11 @@ function validate(value: unknown, operationId: string): { snapshot: SyncProgress
179
190
  ...(inventory ? { inventory: { publications: inventory.publications as number, completed: inventory.completed as number, realms: inventory.realms as number,
180
191
  ...(Array.isArray(inventory.outcomes) ? { outcomes: (inventory.outcomes as { realm: string; outcome: SyncRealmOutcome }[]).map(item => ({ realm: item.realm, outcome: item.outcome })) } : {}),
181
192
  ...(inventory.truncated === true ? { truncated: true } : {}) } } : {}),
182
- ...(v.cause !== undefined ? { cause: v.cause as SyncProgressCause } : {}), ...(v.category !== undefined ? { category: v.category as PlacementRefusalCategory } : {}) };
193
+ ...(v.cause !== undefined ? { cause: v.cause as SyncProgressCause } : {}), ...(v.category !== undefined ? { category: v.category as PlacementRefusalCategory } : {}),
194
+ ...(v.writerRefusal !== undefined ? { writerRefusal: v.writerRefusal as PlacementWriterRefusal } : {}) };
183
195
  return { snapshot, owner: { pid: owner.pid as number, ...(typeof owner.signature === "string" ? { signature: owner.signature } : {}) } };
184
196
  }
185
- function load(dir: string, name: string): { snapshot: SyncProgressSnapshot; owner: Owner } | undefined {
197
+ function load(dir: string, name: string): { snapshot: SyncStatusSnapshot; owner: Owner } | undefined {
186
198
  try { const bytes = readBounded(join(dir, name)); return bytes ? validate(JSON.parse(bytes.toString("utf8")), name.slice(0, 16)) : undefined; } catch { return undefined; }
187
199
  }
188
200
 
@@ -194,6 +206,8 @@ function load(dir: string, name: string): { snapshot: SyncProgressSnapshot; owne
194
206
  export function syncProgressSidecar(home: string, owner: Owner = { pid: process.pid, ...(processSignature(process.pid) ? { signature: processSignature(process.pid)! } : {}) }): SyncProgressSink {
195
207
  const dir = join(home, SYNC_PROGRESS_DIR); let ready = false;
196
208
  return snapshot => {
209
+ const body = JSON.stringify({ ...snapshot, owner }) + "\n";
210
+ if (Buffer.byteLength(body) > MAX_BYTES) throw new Error("sync status exceeds its byte bound");
197
211
  if (!ready) {
198
212
  mkdirSync(dir, { mode: 0o700, recursive: true }); if (!privateDirectory(dir)) throw new Error("sync status directory unavailable");
199
213
  const kept = names(dir).filter(name => name !== `${snapshot.operationId}.json`).map(name => ({ name, mtimeMs: lstatSync(join(dir, name), { throwIfNoEntry: false })?.mtimeMs ?? 0 })).sort((a, b) => b.mtimeMs - a.mtimeMs);
@@ -204,11 +218,11 @@ export function syncProgressSidecar(home: string, owner: Owner = { pid: process.
204
218
  ready = true;
205
219
  }
206
220
  const file = join(dir, `${snapshot.operationId}.json`), temporary = join(dir, `.${snapshot.operationId}.tmp`);
207
- rmSync(temporary, { force: true }); writeFileSync(temporary, JSON.stringify({ ...snapshot, owner }) + "\n", { mode: 0o600, flag: "wx" }); renameSync(temporary, file);
221
+ rmSync(temporary, { force: true }); writeFileSync(temporary, body, { mode: 0o600, flag: "wx" }); renameSync(temporary, file);
208
222
  };
209
223
  }
210
224
 
211
- export interface SyncOperationStatus extends SyncProgressSnapshot { ownerLiveness: Liveness; lastAliveAgoMs: number; lastWorkProgressAgoMs: number }
225
+ export interface SyncOperationStatus extends SyncStatusSnapshot { ownerLiveness: Liveness; lastAliveAgoMs: number; lastWorkProgressAgoMs: number }
212
226
  export interface SyncStatusReport { operations: SyncOperationStatus[]; malformed: number }
213
227
  /**
214
228
  * Read-only status for another terminal: opens no realm, takes no lock, renews no proof and writes nothing. A running
@@ -65,6 +65,19 @@ export function syncOutboundContent(row: unknown): Record<string, unknown> {
65
65
 
66
66
  /** A row passes when the machine's configured policy and the caller's extra screen (if any) both accept its text. */
67
67
  export type RowScreen = (row: Record<string, unknown>) => boolean;
68
+ /**
69
+ * #612: screens whose verdict is a pure function of standalone policy options, recorded with the canonical digest of those
70
+ * options. Package-internal: only these may share a cross-run no-op cache identity; any other host callback has none and
71
+ * always takes the full path.
72
+ */
73
+ const deterministicScreens = new WeakMap<RowScreen, string>();
74
+ export function deterministicRowScreen(options: { denyPaths?: readonly string[]; piiPatterns?: readonly string[] }): RowScreen {
75
+ const frozen = { denyPaths: [...(options.denyPaths ?? [])], piiPatterns: [...(options.piiPatterns ?? [])] }, policy = createStandalonePolicy(frozen);
76
+ const screen: RowScreen = row => policy.screenStandalone(row);
77
+ deterministicScreens.set(screen, createHash("sha256").update(JSON.stringify(frozen)).digest("hex")); return screen;
78
+ }
79
+ /** The cross-run identity of a screen, or undefined for an arbitrary callback (which has none). */
80
+ export function rowScreenIdentity(screen: RowScreen): string | undefined { return deterministicScreens.get(screen); }
68
81
  export type SyncPolicyCategory = StandalonePolicyDecline | "host";
69
82
  export type OutboundVerdict = { ok: true } | { ok: false; category: SyncPolicyCategory };
70
83
  /** One evaluator for actual sync and public inspection, with the same projection and AND composition. */
@@ -10,6 +10,7 @@ import { canonicalPath } from "./platform.ts";
10
10
  import { looksSecret } from "./screen.ts";
11
11
  import { stripPrivateDeep, stripPrivateSpans } from "./private-spans.ts";
12
12
  import { ensureShardDescriptor, resolveAlias, shardDir } from "./shard.ts";
13
+ import { recordBriefPublicationFailure } from "./metrics.ts";
13
14
  import { machineId } from "./machine.ts";
14
15
  import type { WorkBrief, WorkBriefBinding, WorkSegment } from "../brief-work.ts";
15
16
  import { WORK_BRIEF_BYTES, WORK_BRIEF_VIEWS, pruneWorkBriefs, readWorkBrief, reserveWorkBriefSlot, workLogSegments, workPolicyRevision, writeWorkBrief } from "../brief-work.ts";
@@ -437,7 +438,7 @@ export class WorkListStore {
437
438
  const revision = workPolicyRevision(effective);
438
439
  if (revision !== workPolicyRevision(home)) await this.publishPolicyBrief(effective, revision, row, frame);
439
440
  }
440
- } catch { /* A later write retries. */ }
441
+ } catch { recordBriefPublicationFailure(this.base, "work", "write_failed"); }
441
442
  }
442
443
 
443
444
  private async publishPolicyBrief(options: StandalonePolicyOptions, revision: string | undefined, row?: WorkRow, frame?: WriteFrame): Promise<void> {
@@ -451,7 +452,7 @@ export class WorkListStore {
451
452
  this.briefRetryWrites.delete(key);
452
453
  const standalone = createStandalonePolicy({ denyPaths: options.denyPaths, piiPatterns: options.piiPatterns });
453
454
  const segments = workLogSegments(this.base, this.project, this.aliased.map(store => store.project));
454
- if (!segments) return;
455
+ if (!segments) return recordBriefPublicationFailure(this.base, "work", "source_unavailable");
455
456
  const binding = { base: this.base, project: this.project, machine: this.machine, ...(revision ? { revision } : {}) };
456
457
  const policy = workPolicyRevision(options);
457
458
  if (row && frame?.prior && frame.ordered) {
@@ -466,8 +467,8 @@ export class WorkListStore {
466
467
  }
467
468
  const views = await this.read(undefined, true, input => standalone.screenStandalone(input));
468
469
  const rest = workLogSegments(this.base, this.project, this.aliased.map(store => store.project));
469
- if (!rest || JSON.stringify(segments) !== JSON.stringify(rest)) return;
470
- if (revision && (!this.briefPolicyOptions || workPolicyRevision(this.briefPolicyOptions()) !== revision)) return;
470
+ if (!rest || JSON.stringify(segments) !== JSON.stringify(rest)) return recordBriefPublicationFailure(this.base, "work", "frontier_changed");
471
+ if (revision && (!this.briefPolicyOptions || workPolicyRevision(this.briefPolicyOptions()) !== revision)) return recordBriefPublicationFailure(this.base, "work", "binding_changed");
471
472
  this.publish(binding, { schema: "agent-mem.brief-work/v1", project: this.project, segments, policy,
472
473
  rows: views.slice(0, WORK_BRIEF_VIEWS).map(source => ({ source })), truncated: views.length > WORK_BRIEF_VIEWS }, key, shrinkRetry);
473
474
  }
@@ -481,6 +482,7 @@ export class WorkListStore {
481
482
  return ok;
482
483
  });
483
484
  if (!written) {
485
+ recordBriefPublicationFailure(this.base, "work", "byte_bound");
484
486
  this.briefRetryWrites.set(key, { remaining: 1024, shrinkCooldown: shrinkRetry ? 128 : 0 });
485
487
  if (this.briefRetryWrites.size > 5) this.briefRetryWrites.delete(this.briefRetryWrites.keys().next().value!);
486
488
  }
@@ -2,7 +2,7 @@ import { closeSync, constants, type Dir, existsSync, fstatSync, lstatSync, opend
2
2
  import { dirname, isAbsolute, join, resolve } from "node:path";
3
3
  import { createHash } from "node:crypto";
4
4
  import { isDeepStrictEqual } from "node:util";
5
- import { setupReceiptRemedy, type SetupTarget } from "./setup.ts";
5
+ import { setupReceiptRemedy, type SetupTarget } from "./setup-writer-roots.ts";
6
6
  import { SETUP_CONFIG_BYTES } from "./setup-toml.ts";
7
7
  import { amemCaptureCommand, amemCaptureHooks, managedAfter, managedHookEntries, mcpLauncher, mcpRecord, type ConfigImage } from "./setup-owned.ts";
8
8
  import { resolveSetupPaths, type SetupEnvironment } from "./setup-paths.ts";
@@ -0,0 +1,136 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, opendirSync, openSync, readSync, type BigIntStats } from "node:fs";
2
+ import { dirname, isAbsolute, join } from "node:path";
3
+ import { types } from "node:util";
4
+ import { realPath } from "./memory/platform.ts";
5
+ import { mcpLauncher, mcpRecord, type ConfigImage } from "./setup-owned.ts";
6
+ import { SETUP_CONFIG_BYTES } from "./setup-toml.ts";
7
+
8
+ /**
9
+ * #592: the setup-receipt reader the placement writer inventory needs, split out of setup.ts so that sync and
10
+ * placement modules never import setup's human report (and with it a runtime dependency). setup.ts re-exports all of it.
11
+ */
12
+ export const SETUP_TARGETS = ["claude", "codex", "kimi", "pi", "qwen", "jcode", "opencode", "gemini", "agy"] as const;
13
+ export type SetupTarget = typeof SETUP_TARGETS[number];
14
+ const MAX = SETUP_CONFIG_BYTES;
15
+ export const JOURNAL_MAX = 12 * MAX;
16
+ type Image = ConfigImage;
17
+ interface Change { key: string; path: string; before: Image; after: Image; start?: Image }
18
+ interface DirectoryIdentity { dev: number; ino: number }
19
+ export interface Receipt { createdDirectory?: DirectoryIdentity; version: 1 | 2; target: SetupTarget; intent: string; phase: "prepared" | "applied"; changes: Change[] }
20
+ function record(value: unknown): Record<string, unknown> {
21
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("setup configuration must be an object");
22
+ return value as Record<string, unknown>;
23
+ }
24
+ export function decodeReceipt(value: Record<string, unknown>, target: SetupTarget, count: number, strict = false): Receipt {
25
+ if (strict && Object.keys(value).some(key => !["version", "target", "intent", "phase", "changes", "createdDirectory"].includes(key))) throw Error("setup receipt invalid");
26
+ if (value.version !== 1 && value.version !== 2) throw Error("setup receipt version is unsupported; run setup or undo with the release that wrote it");
27
+ if (value.target !== target || typeof value.intent !== "string" || !/^[a-f0-9]{64}$/.test(value.intent) || strict && value.intent.length !== 64 || !["prepared", "applied"].includes(String(value.phase)) || !Array.isArray(value.changes) || value.changes.length !== count && !(target === "jcode" && value.changes.length === 1)) throw Error("setup receipt does not match this installation");
28
+ for (let i = 0; i < value.changes.length; i++) {
29
+ const change = record(value.changes[i]);
30
+ if (change.key !== `${target}:${i}` || strict && (Object.keys(change).some(key => !["key", "path", "before", "after", "start"].includes(key)) || typeof change.path !== "string" || !isAbsolute(change.path) || change.path.length > 4096 || change.path.includes("\0"))) throw Error("setup receipt target mismatch");
31
+ for (const key of ["before", "after", ...(change.start !== undefined ? ["start"] : [])]) {
32
+ const v = record(change[key]);
33
+ if (strict && Object.keys(v).sort().join() !== "bytes,mode" || !Number.isInteger(v.mode) || Number(v.mode) < 0 || Number(v.mode) > 0o777 || v.bytes !== null && (typeof v.bytes !== "string" || v.bytes.length > 2 * MAX || strict && (v.bytes.length > Math.ceil(MAX / 3) * 4 || v.bytes.length / 4 * 3 - (v.bytes.endsWith("==") ? 2 : v.bytes.endsWith("=") ? 1 : 0) > MAX) || Buffer.from(v.bytes, "base64").toString("base64") !== v.bytes)) throw Error("setup receipt invalid");
34
+ }
35
+ }
36
+ if (value.createdDirectory !== undefined) {
37
+ const created = record(value.createdDirectory);
38
+ if (target !== "agy" || Object.keys(created).sort().join() !== "dev,ino" || !Number.isSafeInteger(created.dev) || Number(created.dev) < 0 || !Number.isSafeInteger(created.ino) || Number(created.ino) <= 0) throw Error("setup receipt directory ownership invalid");
39
+ }
40
+ return value as unknown as Receipt;
41
+ }
42
+
43
+ /**
44
+ * #520: the fixed remedy for a receipt whose recorded amem install no longer exists, shared by setup, the placement
45
+ * sync refusal, doctor and the marked diagnostic. It names the target and both commands, never the recorded path.
46
+ */
47
+ export function setupReceiptRemedy(target: SetupTarget, applied = false): string {
48
+ return `the ${applied ? "applied " : ""}${target} setup receipt names an amem install that no longer exists; run amem setup ${target} --apply to refresh the receipt or amem setup ${target} --undo to remove it`;
49
+ }
50
+ /**
51
+ * Fixed safe category only; receipt text, native paths and external error messages are never diagnostics.
52
+ * `target` is set only when an applied receipt names a runtime root whose absence was positively identified, so the
53
+ * refusal can name the setup target and its remedy without exposing the recorded path (#520).
54
+ */
55
+ export class SetupWriterRootsError extends Error {
56
+ readonly code = "setup_writer_roots_unavailable";
57
+ constructor(readonly category: "unsafe" | "changed" | "bound" | "unsupported" | "pending" | "unavailable", readonly target?: SetupTarget) {
58
+ super(target
59
+ ? `Setup writer inventory: ${setupReceiptRemedy(target, true)}.`
60
+ : `Setup writer inventory ${category}; inspect setup receipts and rerun setup before activation.`);
61
+ this.name = "SetupWriterRootsError";
62
+ }
63
+ }
64
+ /** Current managed MCP AFTER images only. Native configuration paths and historical BEFORE/START images are never opened. */
65
+ export function readSetupWriterRoots(home: string): string[] {
66
+ function fail(category: SetupWriterRootsError["category"], target?: SetupTarget): never { throw new SetupWriterRootsError(category, target); }
67
+ try {
68
+ const owned = (stat: BigIntStats) => { if (stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o077n) !== 0n) fail("unsafe"); };
69
+ const stamp = (stat: BigIntStats) => JSON.stringify([stat.dev, stat.ino, stat.uid, stat.mode, stat.nlink, stat.size, stat.mtimeNs, stat.ctimeNs].map(String));
70
+ const base = lstatSync(home, { bigint: true, throwIfNoEntry: false }); if (!base) return []; owned(base); if (!base.isDirectory()) fail("unsafe");
71
+ const directory = join(home, "setup"), initial = lstatSync(directory, { bigint: true, throwIfNoEntry: false });
72
+ if (!initial) return [];
73
+ owned(initial); if (!initial.isDirectory()) fail("unsafe");
74
+ // ponytail:256 setup namespace entries and doctor's existing32MiB aggregate receipt-byte ceiling.
75
+ // A reviewed metadata-only setup inventory is required before increasing either ceiling.
76
+ const files: { name: string; stat: BigIntStats }[] = [], namespace: string[] = [], iterator = opendirSync(directory);
77
+ let entries = 0, totalBytes = 0;
78
+ try { for (;;) {
79
+ const entry = iterator.readSync(); if (!entry) break;
80
+ namespace.push(entry.name);
81
+ if (++entries > 256) fail("bound"); if (entry.name === "setup.lock") fail("pending");
82
+ if (!entry.name.endsWith(".json")) continue; // Retained .json.stale-* and unregistered temps are historical, never current authority.
83
+ const stat = lstatSync(join(directory, entry.name), { bigint: true }); owned(stat); if (!stat.isFile() || stat.nlink !== 1n) fail("unsafe");
84
+ if (stat.size > BigInt(JOURNAL_MAX) || totalBytes + Number(stat.size) > 32 * 1024 * 1024) fail("bound");
85
+ totalBytes += Number(stat.size); files.push({ name: entry.name, stat });
86
+ } } finally { iterator.closeSync(); }
87
+ const roots = new Set<string>(), launchers: { entry: string; root: string }[] = [];
88
+ for (const file of files.sort((a, b) => a.name.localeCompare(b.name))) {
89
+ const target = (file.name.startsWith("agy-") && /^agy-[a-f0-9]{64}\.json$/.test(file.name) ? "agy" : file.name.slice(0, -5)) as SetupTarget;
90
+ if (!SETUP_TARGETS.includes(target) || target === "agy" && !/^agy-[a-f0-9]{64}\.json$/.test(file.name)) fail("unsupported");
91
+ const path = join(directory, file.name), fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
92
+ let text: string;
93
+ try {
94
+ const opened = fstatSync(fd, { bigint: true }); owned(opened); if (!opened.isFile() || opened.nlink !== 1n || stamp(opened) !== stamp(file.stat)) fail("changed");
95
+ const data = Buffer.alloc(Number(opened.size) + 1); let count = 0;
96
+ while (count < data.length) { const n = readSync(fd, data, count, data.length - count, count); if (!n) break; count += n; }
97
+ if (count !== Number(opened.size) || stamp(fstatSync(fd, { bigint: true })) !== stamp(opened) || stamp(lstatSync(path, { bigint: true })) !== stamp(opened)) fail("changed");
98
+ text = new TextDecoder("utf-8", { fatal: true }).decode(data.subarray(0, count));
99
+ } finally { closeSync(fd); }
100
+ const counts: Record<SetupTarget, number> = { claude: 2, codex: 2, kimi: 2, pi: 2, qwen: 1, jcode: 2, opencode: 1, gemini: 1, agy: 1 };
101
+ let value: Receipt;
102
+ try { value = decodeReceipt(record(JSON.parse(text)), target, counts[target], true); } catch { return fail("unsupported"); }
103
+ if (value.phase !== "applied") fail("pending");
104
+ const runtime = mcpLauncher(mcpRecord(target, value.changes[0]!.after), target);
105
+ if (!runtime || runtime.bun.includes("\0") || runtime.entry.length > 4096 || runtime.entry.includes("\0") || !["/bin/amem.js", "/src/cli.ts"].some(suffix => runtime.entry.endsWith(suffix))
106
+ || target === "opencode" && [runtime.bun, runtime.entry].some(value => /\{(?:env|file):/.test(value))) fail("unsupported");
107
+ // #520: only a positively identified ENOENT/ENOTDIR for the recorded root names its setup target; a non-directory,
108
+ // a permission error and every other unreadable state stay anonymous.
109
+ let root: string;
110
+ try { root = realPath(dirname(dirname(runtime.entry))); }
111
+ catch (error) {
112
+ const code = (error as NodeJS.ErrnoException).code;
113
+ if (code === "ENOENT" || code === "ENOTDIR") fail("unavailable", target);
114
+ fail("unavailable");
115
+ }
116
+ if (!lstatSync(root, { throwIfNoEntry: false })?.isDirectory()) fail("unavailable");
117
+ roots.add(root); launchers.push({ entry: runtime.entry, root });
118
+ }
119
+ const finalHome = lstatSync(home, { bigint: true }); owned(finalHome);
120
+ if (!finalHome.isDirectory() || stamp(lstatSync(directory, { bigint: true })) !== stamp(initial) || finalHome.dev !== base.dev || finalHome.ino !== base.ino) fail("changed");
121
+ const finalNames: string[] = [], finalDirectory = opendirSync(directory);
122
+ try { for (;;) { const entry = finalDirectory.readSync(); if (!entry) break; if (finalNames.length >= namespace.length) fail("changed"); finalNames.push(entry.name); } }
123
+ finally { finalDirectory.closeSync(); }
124
+ if (JSON.stringify(finalNames.sort()) !== JSON.stringify(namespace.sort())) fail("changed");
125
+ for (const file of files) if (stamp(lstatSync(join(directory, file.name), { bigint: true })) !== stamp(file.stat)) fail("changed");
126
+ for (const runtime of launchers) if (realPath(dirname(dirname(runtime.entry))) !== runtime.root) fail("changed");
127
+ return [...roots].sort();
128
+ } catch (error) {
129
+ if (error && typeof error === "object" && !types.isProxy(error) && error instanceof SetupWriterRootsError) {
130
+ const category = Object.getOwnPropertyDescriptor(error, "category"), target = Object.getOwnPropertyDescriptor(error, "target")?.value;
131
+ if (category && "value" in category && ["unsafe", "changed", "bound", "unsupported", "pending", "unavailable"].includes(category.value))
132
+ throw new SetupWriterRootsError(category.value, typeof target === "string" && (SETUP_TARGETS as readonly string[]).includes(target) ? target as SetupTarget : undefined);
133
+ }
134
+ throw new SetupWriterRootsError("unavailable");
135
+ }
136
+ }