@staix/agent-mem 0.33.0 → 0.35.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 (50) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +4 -2
  3. package/package.json +2 -1
  4. package/skills/_shared/amem-adapter.md +10 -0
  5. package/skills/amem-ops/SKILL.md +15 -0
  6. package/skills/amem-recall/SKILL.md +13 -0
  7. package/skills/amem-remember/SKILL.md +13 -0
  8. package/skills/amem-review/SKILL.md +14 -0
  9. package/skills/amem-status/SKILL.md +12 -0
  10. package/src/amem-read-tools.ts +20 -0
  11. package/src/cli.ts +50 -12
  12. package/src/commands-table.ts +3 -2
  13. package/src/hook-jcode-journal.ts +8 -2
  14. package/src/hook-spool.ts +5 -0
  15. package/src/hooks.ts +16 -3
  16. package/src/index.ts +2 -0
  17. package/src/mcp-memory.ts +73 -15
  18. package/src/mcp.ts +2 -2
  19. package/src/memory/binding-read-set.ts +18 -0
  20. package/src/memory/capacity.ts +7 -3
  21. package/src/memory/commands.ts +19 -7
  22. package/src/memory/doctor.ts +26 -2
  23. package/src/memory/home-binding-fence.ts +97 -0
  24. package/src/memory/intent-brief.ts +26 -11
  25. package/src/memory/intent-node-matcher.ts +62 -0
  26. package/src/memory/metrics.ts +75 -28
  27. package/src/memory/profile-lock-diagnostic.ts +5 -5
  28. package/src/memory/public-prune-input-chain.ts +4 -1
  29. package/src/memory/public-prune-view.ts +6 -1
  30. package/src/memory/recall-staleness.ts +18 -7
  31. package/src/memory/shard-sync-history.ts +27 -6
  32. package/src/memory/shard.ts +1 -1
  33. package/src/memory/sync-placement-activation.ts +2 -2
  34. package/src/memory/sync-placement-active.ts +4 -1
  35. package/src/memory/sync-placement-bound.ts +1 -1
  36. package/src/memory/sync-placement-capture.ts +17 -6
  37. package/src/memory/sync-placement-checkpoint-person.ts +26 -4
  38. package/src/memory/sync-placement-checkpoint-prospective.ts +5 -1
  39. package/src/memory/sync-placement-guard.ts +17 -2
  40. package/src/memory/sync-placement-inspection-evidence.ts +17 -6
  41. package/src/memory/sync-placement-inspection.ts +2 -2
  42. package/src/memory/sync-placement-prerequisites.ts +1 -1
  43. package/src/memory/sync-placement-refusal.ts +1 -1
  44. package/src/memory/sync-placement-writer-renewal.ts +1 -1
  45. package/src/memory/sync-placement-writer-revision-format.ts +3 -3
  46. package/src/session-brief.ts +47 -7
  47. package/src/setup.ts +62 -11
  48. package/src/skills-install.ts +241 -0
  49. package/src/sync-placement-writer-context.ts +94 -19
  50. package/src/ui/plugin.ts +1 -1
@@ -8,7 +8,8 @@ import { readActivePlacementBinding } from "./sync-placement-active.ts";
8
8
  import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
9
9
  import { previewSelectedSyncPlacementSources } from "./sync-placement-capture.ts";
10
10
  import { placementInventory, placementInventoryBatches, type InventoryRealm } from "./sync-placement-inventory.ts";
11
- import { captureInspectionJournal, inspectRetainedPublicationHistories, PlacementInspectionObjects } from "./sync-placement-inspection-evidence.ts";
11
+ import { captureInspectionJournal, inspectRetainedPublicationHistories, PlacementHistoryBoundError, PlacementInspectionObjects } from "./sync-placement-inspection-evidence.ts";
12
+ import { ShardHistoryError } from "./shard-sync-history.ts";
12
13
  import { createPlacementRecord, SyncPlacementJournalError, PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, type PlacementRealm } from "./sync-placement-journal-format.ts";
13
14
  import { materializePlacementRows, verifiedPlacementPrunes } from "./sync-placement-materialize.ts";
14
15
  import { planPlacementPublicationAsync, publicationBytes, publicationFileNames } from "./sync-placement-publication-plan.ts";
@@ -83,6 +84,9 @@ export async function checkpointProspective(home: string): Promise<{ value: Chec
83
84
  let histories: Awaited<ReturnType<typeof inspectRetainedPublicationHistories>>;
84
85
  try { histories = await inspectRetainedPublicationHistories(journal, targets.map(target => ({ realm: target.realm, generation: active.profile.generation })), objects); }
85
86
  catch (error) {
87
+ // #567: a retained-history bound reached directly (tree, retained object, row count) is a named refusal with its
88
+ // counts, never the cache-unavailable fallback that would hide it behind a smaller-looking plan.
89
+ if (error instanceof PlacementHistoryBoundError) throw new ShardHistoryError("bound", { kind: error.kind, limit: error.limit, observed: error.observed });
86
90
  if (error instanceof SyncPlacementJournalError && (error.code === "corrupt" || error.code === "bound"))
87
91
  return { value: { state: "unavailable", reason: "cache-or-remote-evidence-unavailable" },
88
92
  assertCurrent: () => { checkInventory(); source.assertSourcesUnchanged(); journal.assertCurrent(); } };
@@ -11,7 +11,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type Bi
11
11
  import { join } from "node:path";
12
12
  import { LOCAL_METADATA_MAX_BYTES, legacyProfileMarkerShape, type BoundProfile } from "./generation.ts";
13
13
  import { legacyShardMarkerShape } from "./shard.ts";
14
- import { PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA, validatePlacementProfile, validatePlacementShards } from "./sync-placement-format.ts";
14
+ import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA, validatePlacementProfile, validatePlacementShards } from "./sync-placement-format.ts";
15
15
  import { PLACEMENT_ACTIVATION_INTENT } from "./sync-placement-activation-path.ts";
16
16
  import { profileLockRefusal, rememberProfileLockError } from "./profile-lock-diagnostic.ts";
17
17
 
@@ -60,7 +60,7 @@ export function doctorScratchInventory(home: string): EffectiveRealmInventory |
60
60
 
61
61
  export const PLACEMENT_STAGE1_REFUSAL = "sync placement v3 requires matching durable activation metadata; keep the current compatible profile active until person-authorized activation is complete";
62
62
  export const PLACEMENT_MARKER_REFUSAL = "sync placement metadata is invalid or unsupported; person inspection and a compatible reader are required before continuing";
63
- export const PLACEMENT_ACTIVATION_PENDING = "sync placement activation is pending or incomplete; have the person inspect retained evidence and run amem migrate --sync-placement --resume, or --abandon only while both markers retain their original v2 bytes";
63
+ export const PLACEMENT_ACTIVATION_PENDING = "sync placement activation is pending or incomplete; inspect retained evidence and run amem migrate --sync-placement --resume, or --abandon only while both markers retain their original v2 bytes";
64
64
  export class SyncPlacementRuntimeError extends Error {
65
65
  readonly code: "sync_placement_not_enabled" | "sync_placement_unavailable";
66
66
  constructor(reason: string) { super(reason); this.name = "SyncPlacementRuntimeError"; this.code = reason === PLACEMENT_STAGE1_REFUSAL ? "sync_placement_not_enabled" : "sync_placement_unavailable";rememberProfileLockError(this,reason); }
@@ -90,6 +90,21 @@ function readMarker(file: string): unknown | undefined {
90
90
  export function readPlacementRuntimeMarkers(home: string): { profile: unknown | undefined; shards: unknown | undefined } {
91
91
  return { profile: readMarker(join(home, "profile.json")), shards: readMarker(join(home, "shards.json")) };
92
92
  }
93
+ /** #551 AC2: whether a home is provably a placement home, provably not one, or unprovable from its own markers. */
94
+ export type PlacementMarkerState = "placement" | "unverified" | "not placement";
95
+ /**
96
+ * #551 AC2: a caller that decides whether placement writer verification applies reads this instead of parsing the markers
97
+ * itself. A marker that cannot be read, is unsafe or does not parse proves neither state, so it is `unverified` - never a
98
+ * home reported as one that never activated placement sync, and never a root reported as missing.
99
+ */
100
+ export function placementMarkerState(home: string): PlacementMarkerState {
101
+ let markers: { profile: unknown | undefined; shards: unknown | undefined };
102
+ try { markers = readPlacementRuntimeMarkers(home); } catch { return "unverified"; }
103
+ if (schema(markers.profile) === PLACEMENT_PROFILE_SCHEMA || schema(markers.shards) === PLACEMENT_SHARDS_SCHEMA)
104
+ return (markers.profile as { publicationFormat?: unknown } | undefined)?.publicationFormat === PLACEMENT_FORMAT ? "placement" : "unverified";
105
+ // A missing marker or a recognizable legacy one is a home that never activated placement sync; any other shape is malformed.
106
+ return legacyProfileMarkerShape(markers.profile) && legacyShardMarkerShape(markers.shards) ? "not placement" : "unverified";
107
+ }
93
108
  function schema(value: unknown): unknown {
94
109
  if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
95
110
  return Object.getOwnPropertyDescriptor(value, "schema")?.value;
@@ -79,7 +79,7 @@ export async function inspectRetainedPublicationHistories(snapshot: InspectionJo
79
79
  if (!tip) continue;
80
80
  if (planned.refHash !== hash(shardSyncRef(target.realm))) unavailable();
81
81
  const auditor = objects.auditor(target.realm, target.generation), history = await auditor.history(tip);
82
- if (history.rows.size > SYNC_SCREEN_MAX_ROWS) bound();
82
+ if (history.rows.size > SYNC_SCREEN_MAX_ROWS) historyBound("history-rows", SYNC_SCREEN_MAX_ROWS, history.rows.size);
83
83
  const membership = [...history.rows.values()].map(row => ({ id: row.id, rowHash: hashJSON(row) })).sort((a, b) => a.id.localeCompare(b.id));
84
84
  if (hashJSON(membership) !== planned.exportSetHash || hash(history.files.get("shard.json") ?? Buffer.alloc(0)) !== planned.descriptorHash
85
85
  || planned.tree !== objects.tree(tip)) unavailable();
@@ -123,6 +123,12 @@ export async function inspectRetainedPublicationHistories(snapshot: InspectionJo
123
123
 
124
124
  function unavailable(): never { throw new SyncPlacementJournalError("corrupt"); }
125
125
  function bound(): never { throw new SyncPlacementJournalError("bound"); }
126
+ export type PlacementHistoryBoundKind = "graph-bytes" | "graph-objects" | "object-bytes" | "history-rows";
127
+ /** #567: still code `bound` for every existing catch; adds which retained-history bound was exceeded, as counts only. */
128
+ export class PlacementHistoryBoundError extends SyncPlacementJournalError {
129
+ constructor(readonly kind: PlacementHistoryBoundKind, readonly limit: number, readonly observed: number) { super("bound"); }
130
+ }
131
+ function historyBound(kind: PlacementHistoryBoundKind, limit: number, observed: number): never { throw new PlacementHistoryBoundError(kind, limit, observed); }
126
132
  const hash = (bytes: string | Uint8Array) => createHash("sha256").update(bytes).digest("hex");
127
133
  const oid = (value: string) => /^[a-f0-9]{40}$/.test(value);
128
134
  const forbidden = ["commondir", "shallow", "info/grafts", "objects/info/alternates", "objects/info/http-alternates", "config.worktree"];
@@ -171,7 +177,6 @@ export class PlacementInspectionObjects {
171
177
  private readonly check: () => void;
172
178
  private bytes = 0;
173
179
  private sourceRows = 0;
174
- private sourceBytes = 0;
175
180
  private readonly sourcePacks = new Set<string>();
176
181
  private readonly objects = new Map<string, { type: string; bytes: Buffer }>();
177
182
  constructor(home: string, check: () => void) {
@@ -220,16 +225,22 @@ export class PlacementInspectionObjects {
220
225
  // Larger retained histories need a reviewed immutable digest inventory; physical row-pack limits stay separate.
221
226
  if (!oid(object)) unavailable();
222
227
  const prior = this.objects.get(object); if (prior) { if (prior.type !== type || prior.bytes.length > maximum) unavailable(); return Buffer.from(prior.bytes); }
223
- if (this.objects.size >= SYNC_SCREEN_MAX_ROWS) bound();
228
+ if (this.objects.size >= SYNC_SCREEN_MAX_ROWS) historyBound("graph-objects", SYNC_SCREEN_MAX_ROWS, this.objects.size + 1);
224
229
  if (this.text(["cat-file", "-t", object]) !== type) unavailable();
225
230
  const size = Number(this.text(["cat-file", "-s", object]));
226
- if (!Number.isSafeInteger(size) || size < 0 || size > maximum || this.bytes + size > PUBLIC_PRUNE_GRAPH_MAX_BYTES) bound();
231
+ if (!Number.isSafeInteger(size) || size < 0) bound();
232
+ if (size > maximum) historyBound("object-bytes", maximum, size);
233
+ if (this.bytes + size > PUBLIC_PRUNE_GRAPH_MAX_BYTES) historyBound("graph-bytes", PUBLIC_PRUNE_GRAPH_MAX_BYTES, this.bytes + size);
227
234
  const result = this.run(["cat-file", type, object], Math.max(1, maximum));
228
235
  if (result.code !== 0 || result.bytes.length !== size || createHash("sha1").update(`${type} ${size}\0`).update(result.bytes).digest("hex") !== object) unavailable();
229
236
  this.bytes += size; this.objects.set(object, { type, bytes: result.bytes }); return Buffer.from(result.bytes);
230
237
  }
231
238
  auditor(realm: ShardSyncRealm, generation: string): ShardHistoryAuditor {
232
239
  // The byte cache is shared and bounded. Do not retain a full decoded body map for every historical receipt.
240
+ // #567: retained-history inspection is bounded by object() (80 MiB graph bytes, 20000 objects) plus the cumulative
241
+ // row count below, never by the 8 MiB sync-screen byte envelope: that envelope bounds what sync publishes, and a
242
+ // full window's already-published packs routinely exceed it, which deadlocked the checkpoint meant to relieve it.
243
+ // ponytail: the 80 MiB graph bound is the ceiling; past it, a reviewed immutable digest inventory replaces the cache.
233
244
  return new ShardHistoryAuditor({ realm, generation, placement: true, publicPrune: true, git: async args => this.text(args),
234
245
  object: async (id, type) => this.object(id, type, type === "commit" ? 65536 : SHARD_PACK_MAX_BYTES),
235
246
  blob: async (id, path) => {
@@ -237,8 +248,8 @@ export class PlacementInspectionObjects {
237
248
  const physical = canonicalJSON([realm, id]);
238
249
  if (path.startsWith("rows/") && !this.sourcePacks.has(physical)) {
239
250
  let lines = 0; for (const byte of bytes) if (byte === 10) lines++;
240
- if (this.sourceRows + lines > SYNC_SCREEN_MAX_ROWS || this.sourceBytes + bytes.length > SYNC_SCREEN_MAX_BYTES) bound();
241
- this.sourceRows += lines; this.sourceBytes += bytes.length; this.sourcePacks.add(physical);
251
+ if (this.sourceRows + lines > SYNC_SCREEN_MAX_ROWS) historyBound("history-rows", SYNC_SCREEN_MAX_ROWS, this.sourceRows + lines);
252
+ this.sourceRows += lines; this.sourcePacks.add(physical);
242
253
  }
243
254
  return bytes;
244
255
  } });
@@ -92,8 +92,8 @@ function callbacks(input: SyncPlacementInspectionOptions): SyncPlacementInspecti
92
92
  }
93
93
  function inactive(store: MemoryStore): Extract<SyncPlacementInspection, { complete: false }> {
94
94
  const steps: string[] = [];
95
- if (!store.profile.sharded) steps.push("Have the person run amem migrate --shards --dry-run, review the plan, then amem migrate --shards --apply.");
96
- if (!store.profile.foreignPruneFormat) steps.push("Have the person run amem migrate --public-prune-view --dry-run, review the plan, then amem migrate --public-prune-view --apply.");
95
+ if (!store.profile.sharded) steps.push("Run amem migrate --shards --dry-run, review the plan, then run amem migrate --shards --apply after the exact command is approved.");
96
+ if (!store.profile.foreignPruneFormat) steps.push("Run amem migrate --public-prune-view --dry-run, review the plan, then run amem migrate --public-prune-view --apply after the exact command is approved.");
97
97
  steps.push("Complete separately person-authorized placement activation with compatible exact writer pins; this stage provides no placement activation command or marker writer.");
98
98
  return { complete: false, reason: "placement-not-active", nextStep: "Placement is not active. " + steps.join(" ") };
99
99
  }
@@ -12,7 +12,7 @@ const preview = "amem migrate --sync-placement --dry-run";
12
12
  /** Typed only for safe adapter diagnostics; the floor predicate and remedy stay shared. */
13
13
  export class PlacementHomeFloorError extends Error {
14
14
  constructor(minReader: string) {
15
- super(`Sync placement requires a person-authored home floor of ${minReader} or later in formats.json; have the person append that record, then rerun ${preview}.`);
15
+ super(`Sync placement requires a home floor of ${minReader} or later in formats.json; preview amem formats raise home ${minReader}, add --confirm after the exact command is approved, then rerun ${preview}.`);
16
16
  this.name = "PlacementHomeFloorError";
17
17
  }
18
18
  }
@@ -14,7 +14,7 @@ const NEXT: Record<PlacementRefusalCategory, string> = {
14
14
  "source-selection": "Another writer changed the selected sources during the run; close other memory writers, then rerun amem sync.",
15
15
  policy: "The memory policy changed or is not attested; reload the host so it passes the current policy, then rerun amem sync.",
16
16
  remote: "Check the private sync remote (amem sync --remote <url> once, and that the repository is private and reachable), then rerun amem sync.",
17
- "writer-pin": "A writer sharing this home no longer matches its recorded install; upgrade it to the pinned version, or have the person review amem migrate --sync-placement --dry-run --writer-root <install root> to re-pin it, then rerun amem sync.",
17
+ "writer-pin": "A writer sharing this home no longer matches its recorded install; upgrade it to the pinned version, or review amem migrate --sync-placement --dry-run --writer-root <install root>, then apply the re-pin after the exact command is approved and rerun amem sync.",
18
18
  "size-bound": "Retain the inputs and report this bound; no row was omitted to fit.",
19
19
  lock: "Another sync or memory writer holds this home; wait for it to finish (amem sync --status), then rerun amem sync.",
20
20
  other: "Rerun amem sync; if it refuses again, report the category and phase shown here.",
@@ -32,7 +32,7 @@ export class WriterRenewalError extends Error{
32
32
  :causeClass==="capacity"
33
33
  ? `Writer renewal metadata capacity is exhausted ${details}; retain this epoch and request a separately reviewed archival/checkpoint protocol before another renewal.`
34
34
  :causeClass==="authorization"
35
- ? "Writer renewal requires explicit person authorization of this exact inventory; have the person preview it with amem migrate --sync-placement --dry-run and then apply."
35
+ ? "Writer renewal requires approval of this exact inventory; preview it with amem migrate --sync-placement --dry-run, then apply after the exact command is approved."
36
36
  : "Writer renewal frozen inventory or binding changed; restore it and run amem migrate --sync-placement --resume, or use --abandon before commit append starts and review a new dry-run.");
37
37
  this.name="WriterRenewalError";
38
38
  }
@@ -20,12 +20,12 @@ export const WRITER_RENEWAL_INTENT_SCHEMA="agent-mem.sync-placement-writer-renew
20
20
 
21
21
  export type SharedWriterRevisionErrorCode="invalid"|"bound"|"changed"|"pending"|"checkpoint-pending"|"staging"|"cap";
22
22
  const messages:Record<SharedWriterRevisionErrorCode,string>={
23
- invalid:"Writer renewal metadata is invalid or unsupported; have the person inspect the retained same-epoch inventory and rerun amem migrate --sync-placement --dry-run.",
23
+ invalid:"Writer renewal metadata is invalid or unsupported; inspect the retained same-epoch inventory and rerun amem migrate --sync-placement --dry-run.",
24
24
  bound:"Writer renewal metadata exceeds its supported bound; retain the existing inventory and request a separately reviewed archival/checkpoint before retrying.",
25
25
  changed:"Writer renewal bindings changed; retain the existing inventory, inspect the same-epoch evidence and review a fresh dry-run before applying.",
26
- pending:"Writer renewal is pending; preserve its exact intent and have the person run amem migrate --sync-placement --resume.",
26
+ pending:"Writer renewal is pending; preserve its exact intent and run amem migrate --sync-placement --resume.",
27
27
  "checkpoint-pending":PLACEMENT_CHECKPOINT_PENDING_MESSAGE,
28
- staging:"Writer renewal has orphan staging without a registered final intent; have the person inspect it and run amem migrate --sync-placement --abandon, then amem migrate --sync-placement --dry-run before another apply.",
28
+ staging:"Writer renewal has orphan staging without a registered final intent; inspect it and run amem migrate --sync-placement --abandon, then amem migrate --sync-placement --dry-run before another apply.",
29
29
  cap:"Writer revision capacity is exhausted (remaining 0); retain this epoch and request a separately reviewed archival/checkpoint before another renewal.",
30
30
  };
31
31
  // ponytail: at most64 immutable writer revisions; only a separately reviewed archival/checkpoint can extend this history.
@@ -9,6 +9,8 @@ import { curatedProfileBinding } from "./memory/curated-cache-state.ts";
9
9
  import { captureDisplay, displayText, recordDisplay, validCachedCapture } from "./brief-capture.ts";
10
10
  import { readWorkBrief, workLogSegments, workPolicyRevision } from "./brief-work.ts";
11
11
  import { assertFormatFloor, FormatFloorError } from "./memory/formats.ts";
12
+ import { collectBindingReads } from "./memory/binding-read-set.ts";
13
+ import { FENCE_MAX_PATHS, fenceIsComplete, homeBindingPaths, sameHomeBinding, snapshotHomeBinding, type HomeBindingSnapshot } from "./memory/home-binding-fence.ts";
12
14
  import { readSelector } from "./memory/generation.ts";
13
15
  import { memoryHome } from "./memory/home.ts";
14
16
  import { canonicalPath, realPath } from "./memory/platform.ts";
@@ -105,19 +107,57 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
105
107
  const effectivePolicy = configuredPolicyOptions(base, options.repository === false ? undefined : cwd, options.policy);
106
108
  const policy = createStandalonePolicy(effectivePolicy), release = options.measureOnly ? Object.assign(() => {}, { verify: () => {} }) : registerReaderLease(base, options.nativeSession ? { signature: options.nativeSession.signature, busyTimeoutMs: 0 } : undefined);
107
109
  closers.push(release);
108
- const selection = readSelector(base).revision;
110
+ const initial = readSelector(base), selection = initial.revision;
109
111
  const sharded = !!lstatSync(join(base, "shards.json"), { throwIfNoEntry: false });
110
112
  const shardSelection = sharded ? JSON.stringify(readShardedSelection(base)) : undefined;
111
113
  const aliases = aliasedKeys(base, project), reconcile = aliases.length ? { canonical: project, aliases } : undefined;
114
+ // #396: every value the guard compares is derived from the binding's own bytes, so the per-value fence pays for a
115
+ // full read of those bytes twice per screened row. This fence answers the same question by hashing them instead,
116
+ // and hands the call back to the full comparison whenever an input moved, could not be read safely, or the reader
117
+ // reported more paths than the caller bounds. `fenceSupported` latches off, so a home this fence cannot describe
118
+ // keeps exactly today's cost.
119
+ const fenceHome = (() => { try { return realPath(base); } catch { return undefined; } })();
120
+ const fenceSelector = initial.selector as { pruneInputSetHash?: string; placementHead?: string } | undefined;
121
+ let fenceSupported = fenceHome !== undefined, fence: HomeBindingSnapshot | undefined;
122
+ let fencePaths = homeBindingPaths(fenceHome ?? base, fenceSelector);
112
123
  let drifted = false;
113
- const guard = () => {
124
+ const compareBinding = () => {
125
+ if (resolveAlias(base, requested) !== project || aliasedKeys(base, project).join("\n") !== aliases.join("\n")
126
+ || readSelector(base).revision !== selection || projectState(base, project) !== "active") throw new BindingChanged();
127
+ const split = !!lstatSync(join(base, "shards.json"), { throwIfNoEntry: false });
128
+ if (split !== sharded || split && JSON.stringify(readShardedSelection(base)) !== shardSelection) throw new BindingChanged();
129
+ };
130
+ const guard = (full = false) => {
114
131
  try {
115
132
  if (drifted) throw new BindingChanged();
116
133
  release.verify();
117
- if (resolveAlias(base, requested) !== project || aliasedKeys(base, project).join("\n") !== aliases.join("\n")
118
- || readSelector(base).revision !== selection || projectState(base, project) !== "active") throw new BindingChanged();
119
- const split = !!lstatSync(join(base, "shards.json"), { throwIfNoEntry: false });
120
- if (split !== sharded || split && JSON.stringify(readShardedSelection(base)) !== shardSelection) throw new BindingChanged();
134
+ if (!fenceSupported) { compareBinding(); return; }
135
+ const known = fence?.paths ?? fencePaths;
136
+ if (!full && fence !== undefined && sameHomeBinding(snapshotHomeBinding(known), fence)) return;
137
+ // Adopt only over a set that did not move while it was compared, and never leave this guard on an unproven
138
+ // state: a moved or newly reported set is re-read here, and two rounds that still disagree refuse. The caller's
139
+ // bound is read on the reported list before the expanded set is ever hashed.
140
+ let paths = known, adopted: HomeBindingSnapshot | undefined;
141
+ for (let attempt = 0; attempt < 2 && adopted === undefined; attempt++) {
142
+ const before = snapshotHomeBinding(paths);
143
+ const { paths: reported } = collectBindingReads(compareBinding);
144
+ const after = snapshotHomeBinding(paths);
145
+ const next = homeBindingPaths(fenceHome!, fenceSelector, reported);
146
+ // A set this fence cannot describe keeps today's cost: the comparison inside this bracket is the proof today's
147
+ // guard offers too, and every later guard reads the binding itself.
148
+ // The comparison above ran before the unsafe or over-limit observation, so it does not cover this instant: latch
149
+ // off, then compare once more before this caller proceeds. A throw lands in the catch below and refuses.
150
+ if (next.length > FENCE_MAX_PATHS || !fenceIsComplete(before) || !fenceIsComplete(after)) {
151
+ fence = undefined; fencePaths = next; fenceSupported = false; compareBinding(); return;
152
+ }
153
+ const sameSet = next.length === paths.length && next.every((path, index) => path === paths[index]);
154
+ // Only a set that did not move while it was compared, and whose two hashes agree, is stamped. Anything else is
155
+ // re-read here, and a second round that still disagrees throws instead of handing this caller's screen a state
156
+ // no comparison covered.
157
+ if (sameSet && sameHomeBinding(before, after)) adopted = after; else paths = next;
158
+ }
159
+ if (adopted === undefined) throw new BindingChanged();
160
+ fence = adopted; fencePaths = [...adopted.paths];
121
161
  } catch { drifted = true; throw new BindingChanged(); }
122
162
  };
123
163
  // Fixed native screening has no host callback to observe intermediate rows. Buffer
@@ -412,7 +452,7 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
412
452
  emitReserved(); coverage.capture = "partial";
413
453
  }
414
454
  }
415
- guard();
455
+ guard(true);
416
456
  let context = [header(coverage, reasons), ...(candidateLine ? [candidateLine] : []), ...lines].join("\n");
417
457
  while (Buffer.byteLength(context) > maximum && lines.length) {
418
458
  const repoIndex = lines.findLastIndex(line => line.startsWith('{"section":"repo",'));
package/src/setup.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { installSkills, skillRoot, type SkillInstallReport } from "./skills-install.ts";
1
2
  import { cliAttribution } from "./memory/cli-attribution.ts";
2
3
  import { configuredPolicy } from "./memory/config.ts";
3
4
  import { SETUP_CONFIG_BYTES, updateTomlArray } from "./setup-toml.ts";
@@ -16,6 +17,8 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
16
17
  import { fileURLToPath } from "node:url";
17
18
  import { isDeepStrictEqual, types } from "node:util";
18
19
  import { HOOK_EVENTS } from "./hook-contract.ts";
20
+ import { readEffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
21
+ import { placementMarkerState } from "./memory/sync-placement-guard.ts";
19
22
  import { memoryHome } from "./memory/home.ts";
20
23
  import { label, PLAIN, singleLine, type Style } from "./memory/style.ts";
21
24
  import { canonicalPath, memoryGitEnv, memoryGitSync, processLiveness, processSignature, realPath } from "./memory/platform.ts";
@@ -48,10 +51,14 @@ export interface SetupContext {
48
51
  /** Trusted test seam; production always runs the named native CLI in a private staging HOME. */
49
52
  native?: (argv: readonly string[], env: Env, cwd: string) => void;
50
53
  }
54
+ export type SetupSkillResult = { target: SetupTarget; report?: SkillInstallReport; reason?: string; refused?: boolean };
51
55
  export interface SetupPlan {
56
+ skills?: SetupSkillResult[];
52
57
  targets: SetupTarget[]; mode: "preview" | "apply" | "undo"; root?: InstallRoot;
53
58
  actions: { target: SetupTarget; version?: ClientVersion; files: string[]; receipt: string; cwd?: string; registration: string[] | null; lifecycle: string; available: boolean; hooks: PlannedHook[]; removes?: { file: string; event: string; command: string }[]; mcpChange: "add" | "replace" | "restore" | "unchanged"; commands: string[][]; state: string }[];
54
59
  notes: string[];
60
+ /** #551, additive: the placement-inventory warning, repeated on the apply receipt so `--apply` shows it too. */
61
+ placementWriter?: string;
55
62
  }
56
63
  const MAX = SETUP_CONFIG_BYTES, JOURNAL_MAX = 12 * MAX;
57
64
  const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
@@ -261,6 +268,24 @@ function strayCaptures(target: SetupTarget, image: Image, current: string): { ev
261
268
  } catch { return []; }
262
269
  }
263
270
  const lifecycle = (target: SetupTarget) => target === "opencode" || target === "gemini" || target === "agy" ? "MCP only; native capture unavailable" : target === "jcode" ? "post_tool and turn_end capture hooks" : target === "claude" ? "seven bounded native hooks" : target === "pi" ? "session_shutdown incremental ingest" : "SessionEnd incremental ingest";
271
+ /**
272
+ * #551 AC2: the placement writer inventory this home's sync will verify. A root the inventory provably does not hold is named
273
+ * as such with the renewal step to take first; an inventory that cannot be read is reported as unverified, never as a missing
274
+ * entry. It writes nothing, refuses nothing and returns undefined on a home that is not activated for placement sync.
275
+ */
276
+ function placementWriterInventoryNote(root: string, home: string): string | undefined {
277
+ // #551 AC2: only a proven non-placement home stays silent. Markers that cannot be read or parsed prove nothing either way,
278
+ // so they fall through to the inventory read below, which reports the state as unverified instead of as a missing root.
279
+ if (placementMarkerState(home) === "not placement") return undefined;
280
+ let roots: readonly string[] | undefined;
281
+ try { roots = readEffectiveSyncPlacementWriters(home).roots; } catch { roots = undefined; }
282
+ if (roots === undefined) return "WARNING: the active placement writer inventory could not be verified here, so this root is neither confirmed nor refused. Setup registers it exactly as previewed and changes no inventory entry; check the inventory with the person before relying on placement sync.";
283
+ let canonical: string;
284
+ try { canonical = realPath(root); } catch { return undefined; }
285
+ if (roots.includes(canonical)) return undefined;
286
+ // #551 AC2: the suggested argument is shell-quoted, so a root with a space, a quote or a shell metacharacter stays one argument.
287
+ return `WARNING: this install root is outside the active placement writer inventory, so placement sync stops in writer verification once setup registers it. Renew the inventory first with the person - amem migrate --sync-placement --dry-run --writer-root ${quote(canonical)}, then --apply - and rerun setup after that. Setup writes no inventory entry and never refuses on this alone.`;
288
+ }
264
289
  export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", options: SetupContext = {}): SetupPlan {
265
290
  if (target !== "all" && !SETUP_TARGETS.includes(target as SetupTarget)) throw Error("usage: amem setup claude|codex|kimi|pi|qwen|jcode|opencode|gemini|agy|all [--apply|--undo]");
266
291
  const targets: SetupTarget[] = target === "all" ? [...SETUP_ALL_TARGETS] : [target as SetupTarget];
@@ -292,9 +317,13 @@ export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", o
292
317
  if (!c.workspace.ignored) pluginNotes.push("WARNING: .agents/mcp_config.json is not Git-ignored; it contains absolute local paths. Setup will refuse it if it becomes tracked.");
293
318
  }
294
319
  if (c.root) pluginNotes.push(`Registers the install root ${c.root.path} (amem ${c.root.version}) for hooks and MCP; current registrations change only on --apply.`);
320
+ // #551: the root this plan registers may not be in the home's active placement inventory, which stops sync in writer verification.
321
+ const placementWriter = placementWriterInventoryNote(c.root?.path ?? fileURLToPath(new URL("..", import.meta.url)), dirname(c.state));
322
+ if (placementWriter) pluginNotes.push(placementWriter);
295
323
  if (target === "all") pluginNotes.push("Antigravity is repository-scoped and excluded from all; run amem setup agy explicitly inside its repository.");
296
324
  if (targets.includes("jcode")) pluginNotes.push("Launch Jcode with JCODE_DISABLE_CLAUDE_MCP=1 and without a same-name project override: imported Claude stdio entries can replace this private amem binding with a shared daemon-cwd server. Use a new workspace-bound session when changing projects.");
297
- return { targets, mode, ...(c.root ? { root: c.root } : {}), actions: targets.map(target => {
325
+ const skills = mode === "undo" ? [] : skillResults(c, targets.filter(target => available(c, target, options)), "preview", mode);
326
+ return { targets, mode, ...(skills.length ? { skills } : {}), ...(c.root ? { root: c.root } : {}), ...(placementWriter ? { placementWriter } : {}), actions: targets.map(target => {
298
327
  const receipted = receipt(c, target, false), files = mode === "undo" && receipted ? receipted.changes.map(change => change.path) : c.paths[target];
299
328
  for (const file of files) read(file);
300
329
  const stale = mode !== "undo" && !!receipted && staleReceipt(target, receipted);
@@ -603,7 +632,21 @@ function prepare(c: ReturnType<typeof context>, target: SetupTarget, options: Se
603
632
  }
604
633
  function save(c: ReturnType<typeof context>, value: Receipt): void { write(journal(c, value.target), image(JSON.stringify(value) + "\n")); }
605
634
  function available(c: ReturnType<typeof context>, target: SetupTarget, options: SetupContext): boolean { return target === "agy" || !!options.native || Bun.which(target, { PATH: c.env.PATH ?? process.env.PATH }) !== null; }
606
- export interface SetupApplyResult { applied: SetupTarget[]; unchanged: SetupTarget[]; skipped?: { target: SetupTarget; reason: string }[] }
635
+ export interface SetupApplyResult { skills?: SetupSkillResult[]; applied: SetupTarget[]; unchanged: SetupTarget[]; skipped?: { target: SetupTarget; reason: string }[]; warnings?: string[] }
636
+ function skillResults(c: ReturnType<typeof context>, targets: SetupTarget[], mode: "preview" | "apply" | "undo", requested: SetupPlan["mode"] = mode, prior?: SetupSkillResult[]): SetupSkillResult[] {
637
+ return targets.flatMap((target): SetupSkillResult[] => {
638
+ const retry = `amem setup ${target} ${requested === "undo" ? "--undo" : "--apply"}${requested !== "undo" && c.root ? ` --root ${quote(c.root.path)}` : ""}`;
639
+ try {
640
+ const root = skillRoot(target, c.env, c.home);
641
+ if (!root) return [];
642
+ const planned = prior?.find(row => row.target === target)?.report;
643
+ if (mode === "apply" && planned?.actions.every(action => action.change === "refused")) return [{ target, report: planned }];
644
+ const expected = mode === "apply" && planned ? { root: planned.root, ...(planned.linkedFrom ? { linkedFrom: planned.linkedFrom } : {}) } : undefined;
645
+ return [{ target, report: installSkills(root, mode, c.root?.path, c.root?.version, retry, c.env, expected) }];
646
+ }
647
+ catch (error) { return [{ target, refused: true, reason: `${error instanceof Error ? error.message : String(error)}; inspect and retry ${retry}` }]; }
648
+ });
649
+ }
607
650
  /** Claim only a directory this invocation actually created, never one merely absent at preview. */
608
651
  function prepareCreatedDirectory(c: ReturnType<typeof context>, value: Receipt): void {
609
652
  if (value.target !== "agy") return;
@@ -652,15 +695,17 @@ function applyUnlocked(plan: SetupPlan, options: SetupContext = {}): SetupApplyR
652
695
  for (let i = 0; i < value.changes.length; i++) { const change = value.changes[i]!; if (!sameImage(item.expected[i]!, change.after)) write(change.path, change.after, item.expected[i]!, publishGuard(c, value.target, options)); }
653
696
  value.phase = "applied"; save(c, value); applied.push(value.target);
654
697
  }
655
- return { applied, unchanged, ...(skipped.length ? { skipped } : {}) };
698
+ const skills = skillResults(c, targets, "apply", "apply", plan.skills);
699
+ return { applied, unchanged, ...(skills.length ? { skills } : {}), ...(skipped.length ? { skipped } : {}) };
656
700
  }
657
701
  /** Byte-exact for untouched files, otherwise remove/restore only this installer's owned entries. */
658
- function undoUnlocked(plan: SetupPlan, options: SetupContext = {}): { restored: SetupTarget[] } {
702
+ function undoUnlocked(plan: SetupPlan, options: SetupContext = {}): { restored: SetupTarget[]; skills?: SetupSkillResult[] } {
659
703
  const c = contextForPlan(plan, options), receipts = plan.targets.map(target => receipt(c, target, false)).filter((value): value is Receipt => !!value);
660
704
  const pending = receipts.map(value => ({ value, files: value.changes.map((change, index) => { const expected = read(change.path); return { change, expected, restored: restoreChange(value, change, index, expected) }; }) }));
661
705
  for (const item of pending) for (const file of item.files) if (!sameImage(read(file.change.path), file.expected)) throw Error("setup configuration changed during undo preparation");
662
706
  for (const item of pending) { if (item.value.target === "agy") c.workspace!.assertCurrent(); for (const file of item.files) if (!sameImage(file.expected, file.restored)) write(file.change.path, file.restored, file.expected, publishGuard(c, item.value.target, options)); removeCreatedDirectory(c, item.value); rmSync(journal(c, item.value.target)); }
663
- return { restored: receipts.map(value => value.target) };
707
+ const skills = skillResults(c, plan.targets, "undo");
708
+ return { restored: receipts.map(value => value.target), ...(skills.length ? { skills } : {}) };
664
709
  }
665
710
 
666
711
  function withSetupLock<T>(options: SetupContext, run: () => T): T {
@@ -686,9 +731,11 @@ function withSetupLock<T>(options: SetupContext, run: () => T): T {
686
731
  export function applySetup(plan: SetupPlan, options: SetupContext = {}): SetupApplyResult {
687
732
  if (plan.targets.includes("jcode")) assertJcodeHome(options.env ?? process.env);
688
733
  if (plan.targets.includes("agy")) contextForPlan(plan, options);
689
- return withSetupLock(options, () => applyUnlocked(plan, options));
734
+ const result = withSetupLock(options, () => applyUnlocked(plan, options));
735
+ // #551 AC2: `--apply` prints only this result, so the plan's placement warning is repeated on the receipt.
736
+ return plan.placementWriter ? { ...result, warnings: [plan.placementWriter] } : result;
690
737
  }
691
- export function undoSetup(plan: SetupPlan, options: SetupContext = {}): { restored: SetupTarget[] } {
738
+ export function undoSetup(plan: SetupPlan, options: SetupContext = {}): { restored: SetupTarget[]; skills?: SetupSkillResult[] } {
692
739
  if (plan.targets.includes("jcode")) assertJcodeHome(options.env ?? process.env);
693
740
  if (plan.targets.includes("agy")) contextForPlan(plan, options);
694
741
  return withSetupLock(options, () => undoUnlocked(plan, options));
@@ -719,6 +766,8 @@ export function setupPlanText(plan: SetupPlan, s: Style = PLAIN): string {
719
766
  if (action.available && !action.hooks.length && plan.mode !== "undo") lines.push(` hook ${s.dim("none")}`);
720
767
  lines.push(` ${s.dim(action.lifecycle)}`);
721
768
  }
769
+ for (const row of plan.skills ?? []) for (const action of row.report?.actions ?? []) lines.push(` skill ${row.target}: ${action.name} ${action.change} ${action.path}${row.report?.linkedFrom ? ` (linked from ${row.report.linkedFrom})` : ""}${action.reason ? `: ${action.reason}` : ""}`);
770
+ for (const row of plan.skills ?? []) if (row.reason) lines.push(` skill ${row.target}: ${row.reason}`);
722
771
  const warnings = plan.notes.filter(note => /^WARNING|detected|version-specific/.test(note)), notes = plan.notes.filter(note => !warnings.includes(note));
723
772
  if (skipped.length) lines.push("", `Skipped clients: ${skipped.map(action => action.target).join(", ")} (not installed)`);
724
773
  if (warnings.length) lines.push("", "Warnings:", ...warnings.map(note => ` - ${s.attention(note)}`));
@@ -727,10 +776,12 @@ export function setupPlanText(plan: SetupPlan, s: Style = PLAIN): string {
727
776
  return lines.join("\n");
728
777
  }
729
778
 
730
- function setupResultText(result: SetupApplyResult | { restored: SetupTarget[] }, s: Style): string {
731
- if ("restored" in result) return `${label(s, "ok")} restored: ${result.restored.join(", ") || "none"}`;
779
+ function setupResultText(result: SetupApplyResult | { restored: SetupTarget[]; skills?: SetupSkillResult[] }, s: Style): string {
780
+ const skills = (result.skills ?? []).flatMap(row => [...(row.reason ? [`skill ${row.target}: ${row.reason}`] : []), ...(row.report?.actions ?? []).map(a => `skill ${row.target}: ${a.name} ${a.change} ${a.path}${row.report?.linkedFrom ? ` (linked from ${row.report.linkedFrom})` : ""}${a.reason ? `: ${a.reason}` : ""}`)]);
781
+ if ("restored" in result) return [`${label(s, "ok")} restored: ${result.restored.join(", ") || "none"}`, ...skills].join("\n");
732
782
  return [`${label(s, "ok")} applied: ${result.applied.join(", ") || "none"}`, `${label(s, "ok")} unchanged: ${result.unchanged.join(", ") || "none"}`,
733
- ...(result.skipped ?? []).map(item => `${label(s, "skipped")} ${item.target}: ${item.reason}`)].join("\n");
783
+ ...(result.skipped ?? []).map(item => `${label(s, "skipped")} ${item.target}: ${item.reason}`),
784
+ ...(result.warnings ?? []).map(warning => `${label(s, "attention")} ${warning}`), ...skills].join("\n");
734
785
  }
735
786
 
736
787
  /** Compatibility formatter for confirmation-style callers: the raw plan under `--json`, the readable plan otherwise. */
@@ -762,7 +813,7 @@ export class SetupWriterRootsError extends Error {
762
813
  constructor(readonly category: "unsafe" | "changed" | "bound" | "unsupported" | "pending" | "unavailable", readonly target?: SetupTarget) {
763
814
  super(target
764
815
  ? `Setup writer inventory: ${setupReceiptRemedy(target, true)}.`
765
- : `Setup writer inventory ${category}; have the person inspect setup receipts and rerun setup before activation.`);
816
+ : `Setup writer inventory ${category}; inspect setup receipts and rerun setup before activation.`);
766
817
  this.name = "SetupWriterRootsError";
767
818
  }
768
819
  }