@staix/agent-mem 0.38.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.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/brief-curated.ts +8 -4
- package/src/cli-agent-reads.ts +2 -1
- package/src/cli.ts +58 -26
- package/src/index.ts +5 -0
- package/src/memory/capacity-text.ts +100 -0
- package/src/memory/capacity.ts +0 -92
- package/src/memory/commands.ts +6 -1
- package/src/memory/curated-cache-state.ts +22 -3
- package/src/memory/doctor-text.ts +144 -0
- package/src/memory/doctor.ts +8 -140
- package/src/memory/eval-audit-text.ts +62 -0
- package/src/memory/eval-audit.ts +0 -57
- package/src/memory/eval-text.ts +32 -0
- package/src/memory/eval.ts +0 -28
- package/src/memory/formats.ts +2 -0
- package/src/memory/gc-text.ts +22 -0
- package/src/memory/gc.ts +0 -19
- package/src/memory/generation-index.ts +1 -1
- package/src/memory/index-file.ts +1 -1
- package/src/memory/metrics.ts +18 -10
- package/src/memory/migrate-text.ts +32 -0
- package/src/memory/migrate.ts +0 -29
- package/src/memory/prune-text.ts +29 -0
- package/src/memory/prune.ts +0 -26
- package/src/memory/report-text.ts +2 -0
- package/src/memory/shard-migration-text.ts +40 -0
- package/src/memory/shard-migration.ts +0 -37
- package/src/memory/store.ts +112 -17
- package/src/memory/sync-placement-bound.ts +2 -2
- package/src/memory/sync-placement-checkpoint-person.ts +1 -1
- package/src/memory/sync-placement-noop-cache.ts +93 -0
- package/src/memory/sync-placement-refusal-category.ts +18 -0
- package/src/memory/sync-placement-transport.ts +43 -7
- package/src/memory/sync-progress-text.ts +7 -0
- package/src/memory/sync-progress.ts +21 -7
- package/src/memory/sync-screen.ts +13 -0
- package/src/memory/work-lists.ts +6 -4
- package/src/setup-drift.ts +1 -1
- package/src/setup-writer-roots.ts +136 -0
- package/src/setup.ts +3 -116
- package/src/sync-placement-writer-context.ts +8 -3
- package/src/ui/plugin.ts +4 -2
- package/src/work-brief-preparation.ts +28 -0
|
@@ -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:
|
|
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:
|
|
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:
|
|
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,
|
|
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
|
|
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. */
|
package/src/memory/work-lists.ts
CHANGED
|
@@ -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 {
|
|
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
|
}
|
package/src/setup-drift.ts
CHANGED
|
@@ -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
|
+
}
|
package/src/setup.ts
CHANGED
|
@@ -18,16 +18,16 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
|
18
18
|
import { fileURLToPath } from "node:url";
|
|
19
19
|
import { isDeepStrictEqual, types } from "node:util";
|
|
20
20
|
import { HOOK_EVENTS } from "./hook-contract.ts";
|
|
21
|
+
import { decodeReceipt, JOURNAL_MAX, readSetupWriterRoots, setupReceiptRemedy, SetupWriterRootsError, SETUP_TARGETS, type Receipt, type SetupTarget } from "./setup-writer-roots.ts";
|
|
22
|
+
export { readSetupWriterRoots, setupReceiptRemedy, SetupWriterRootsError, SETUP_TARGETS, type SetupTarget };
|
|
21
23
|
import { readEffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
|
|
22
24
|
import { placementMarkerState } from "./memory/sync-placement-guard.ts";
|
|
23
25
|
import { memoryHome } from "./memory/home.ts";
|
|
24
26
|
import { PLAIN, singleLine, type Style } from "./memory/style.ts";
|
|
25
27
|
import { canonicalPath, memoryGitEnv, memoryGitSync, processLiveness, processSignature, realPath } from "./memory/platform.ts";
|
|
26
28
|
|
|
27
|
-
export const SETUP_TARGETS = ["claude", "codex", "kimi", "pi", "qwen", "jcode", "opencode", "gemini", "agy"] as const;
|
|
28
29
|
/** Workspace-scoped Antigravity setup is always selected explicitly. */
|
|
29
30
|
export const SETUP_ALL_TARGETS = SETUP_TARGETS.filter(target => target !== "agy");
|
|
30
|
-
export type SetupTarget = typeof SETUP_TARGETS[number];
|
|
31
31
|
// Only recorded layout verification versions belong here; null means no version was recorded.
|
|
32
32
|
const SETUP_VERIFIED_VERSIONS: Readonly<Record<SetupTarget, string | null>> = {
|
|
33
33
|
claude: null, codex: "0.165.0", kimi: null, pi: null, qwen: "0.26.1", jcode: "0.99.1", opencode: "1.18.35", gemini: "0.61.0", agy: null,
|
|
@@ -38,7 +38,6 @@ type Image = ConfigImage;
|
|
|
38
38
|
interface PlannedHook { event: string; command: string; timeout: number }
|
|
39
39
|
interface Change { key: string; path: string; before: Image; after: Image; start?: Image }
|
|
40
40
|
interface DirectoryIdentity { dev: number; ino: number }
|
|
41
|
-
interface Receipt { createdDirectory?: DirectoryIdentity; version: 1 | 2; target: SetupTarget; intent: string; phase: "prepared" | "applied"; changes: Change[] }
|
|
42
41
|
export interface SetupContext {
|
|
43
42
|
env?: Env; bun?: string; entry?: string; stdinTTY?: boolean; cwd?: string;
|
|
44
43
|
/** `--root`: an absolute amem install root to register instead of the running one (#199). Ignored when `entry` is given. */
|
|
@@ -61,7 +60,7 @@ export interface SetupPlan {
|
|
|
61
60
|
/** #551, additive: the placement-inventory warning, repeated on the apply receipt so `--apply` shows it too. */
|
|
62
61
|
placementWriter?: string;
|
|
63
62
|
}
|
|
64
|
-
const MAX = SETUP_CONFIG_BYTES
|
|
63
|
+
const MAX = SETUP_CONFIG_BYTES;
|
|
65
64
|
const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
66
65
|
const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'";
|
|
67
66
|
function record(value: unknown): Record<string, unknown> {
|
|
@@ -217,24 +216,6 @@ function assertOpencodeLayout(c: ReturnType<typeof context>, mode: SetupPlan["mo
|
|
|
217
216
|
}
|
|
218
217
|
function intent(c: ReturnType<typeof context>, target: SetupTarget): string { return digest([1, target, c.paths[target], c.bun, c.entry, ...(["codex", "kimi", "qwen"].includes(target) ? ["capture-json-v1"] : []), ...(target === "jcode" ? ["jcode-hooks-v1"] : []), ...(["claude", "codex", "kimi", "pi", "qwen", "jcode"].includes(target) ? ["root-hooks-v2"] : []), ...(target === "agy" ? [c.workspace!.root] : [])]); }
|
|
219
218
|
function journal(c: ReturnType<typeof context>, target: SetupTarget): string { return join(c.state, target === "agy" ? `agy-${digest(c.workspace!.root)}.json` : `${target}.json`); }
|
|
220
|
-
function decodeReceipt(value: Record<string, unknown>, target: SetupTarget, count: number, strict = false): Receipt {
|
|
221
|
-
if (strict && Object.keys(value).some(key => !["version", "target", "intent", "phase", "changes", "createdDirectory"].includes(key))) throw Error("setup receipt invalid");
|
|
222
|
-
if (value.version !== 1 && value.version !== 2) throw Error("setup receipt version is unsupported; run setup or undo with the release that wrote it");
|
|
223
|
-
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");
|
|
224
|
-
for (let i = 0; i < value.changes.length; i++) {
|
|
225
|
-
const change = record(value.changes[i]);
|
|
226
|
-
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");
|
|
227
|
-
for (const key of ["before", "after", ...(change.start !== undefined ? ["start"] : [])]) {
|
|
228
|
-
const v = record(change[key]);
|
|
229
|
-
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");
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
if (value.createdDirectory !== undefined) {
|
|
233
|
-
const created = record(value.createdDirectory);
|
|
234
|
-
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");
|
|
235
|
-
}
|
|
236
|
-
return value as unknown as Receipt;
|
|
237
|
-
}
|
|
238
219
|
function receipt(c: ReturnType<typeof context>, target: SetupTarget, requireRuntime = false): Receipt | undefined {
|
|
239
220
|
const raw = read(journal(c, target), JOURNAL_MAX); if (raw.bytes === null) return;
|
|
240
221
|
const value = decodeReceipt(record(JSON.parse(Buffer.from(raw.bytes, "base64").toString("utf8"))), target, c.paths[target].length);
|
|
@@ -872,97 +853,3 @@ export async function runSetup(target: string, mode: SetupPlan["mode"], options:
|
|
|
872
853
|
}
|
|
873
854
|
|
|
874
855
|
|
|
875
|
-
/**
|
|
876
|
-
* #520: the fixed remedy for a receipt whose recorded amem install no longer exists, shared by setup, the placement
|
|
877
|
-
* sync refusal, doctor and the marked diagnostic. It names the target and both commands, never the recorded path.
|
|
878
|
-
*/
|
|
879
|
-
export function setupReceiptRemedy(target: SetupTarget, applied = false): string {
|
|
880
|
-
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`;
|
|
881
|
-
}
|
|
882
|
-
/**
|
|
883
|
-
* Fixed safe category only; receipt text, native paths and external error messages are never diagnostics.
|
|
884
|
-
* `target` is set only when an applied receipt names a runtime root whose absence was positively identified, so the
|
|
885
|
-
* refusal can name the setup target and its remedy without exposing the recorded path (#520).
|
|
886
|
-
*/
|
|
887
|
-
export class SetupWriterRootsError extends Error {
|
|
888
|
-
readonly code = "setup_writer_roots_unavailable";
|
|
889
|
-
constructor(readonly category: "unsafe" | "changed" | "bound" | "unsupported" | "pending" | "unavailable", readonly target?: SetupTarget) {
|
|
890
|
-
super(target
|
|
891
|
-
? `Setup writer inventory: ${setupReceiptRemedy(target, true)}.`
|
|
892
|
-
: `Setup writer inventory ${category}; inspect setup receipts and rerun setup before activation.`);
|
|
893
|
-
this.name = "SetupWriterRootsError";
|
|
894
|
-
}
|
|
895
|
-
}
|
|
896
|
-
/** Current managed MCP AFTER images only. Native configuration paths and historical BEFORE/START images are never opened. */
|
|
897
|
-
export function readSetupWriterRoots(home: string): string[] {
|
|
898
|
-
function fail(category: SetupWriterRootsError["category"], target?: SetupTarget): never { throw new SetupWriterRootsError(category, target); }
|
|
899
|
-
try {
|
|
900
|
-
const owned = (stat: BigIntStats) => { if (stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o077n) !== 0n) fail("unsafe"); };
|
|
901
|
-
const stamp = (stat: BigIntStats) => JSON.stringify([stat.dev, stat.ino, stat.uid, stat.mode, stat.nlink, stat.size, stat.mtimeNs, stat.ctimeNs].map(String));
|
|
902
|
-
const base = lstatSync(home, { bigint: true, throwIfNoEntry: false }); if (!base) return []; owned(base); if (!base.isDirectory()) fail("unsafe");
|
|
903
|
-
const directory = join(home, "setup"), initial = lstatSync(directory, { bigint: true, throwIfNoEntry: false });
|
|
904
|
-
if (!initial) return [];
|
|
905
|
-
owned(initial); if (!initial.isDirectory()) fail("unsafe");
|
|
906
|
-
// ponytail:256 setup namespace entries and doctor's existing32MiB aggregate receipt-byte ceiling.
|
|
907
|
-
// A reviewed metadata-only setup inventory is required before increasing either ceiling.
|
|
908
|
-
const files: { name: string; stat: BigIntStats }[] = [], namespace: string[] = [], iterator = opendirSync(directory);
|
|
909
|
-
let entries = 0, totalBytes = 0;
|
|
910
|
-
try { for (;;) {
|
|
911
|
-
const entry = iterator.readSync(); if (!entry) break;
|
|
912
|
-
namespace.push(entry.name);
|
|
913
|
-
if (++entries > 256) fail("bound"); if (entry.name === "setup.lock") fail("pending");
|
|
914
|
-
if (!entry.name.endsWith(".json")) continue; // Retained .json.stale-* and unregistered temps are historical, never current authority.
|
|
915
|
-
const stat = lstatSync(join(directory, entry.name), { bigint: true }); owned(stat); if (!stat.isFile() || stat.nlink !== 1n) fail("unsafe");
|
|
916
|
-
if (stat.size > BigInt(JOURNAL_MAX) || totalBytes + Number(stat.size) > 32 * 1024 * 1024) fail("bound");
|
|
917
|
-
totalBytes += Number(stat.size); files.push({ name: entry.name, stat });
|
|
918
|
-
} } finally { iterator.closeSync(); }
|
|
919
|
-
const roots = new Set<string>(), launchers: { entry: string; root: string }[] = [];
|
|
920
|
-
for (const file of files.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
921
|
-
const target = (file.name.startsWith("agy-") && /^agy-[a-f0-9]{64}\.json$/.test(file.name) ? "agy" : file.name.slice(0, -5)) as SetupTarget;
|
|
922
|
-
if (!SETUP_TARGETS.includes(target) || target === "agy" && !/^agy-[a-f0-9]{64}\.json$/.test(file.name)) fail("unsupported");
|
|
923
|
-
const path = join(directory, file.name), fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
924
|
-
let text: string;
|
|
925
|
-
try {
|
|
926
|
-
const opened = fstatSync(fd, { bigint: true }); owned(opened); if (!opened.isFile() || opened.nlink !== 1n || stamp(opened) !== stamp(file.stat)) fail("changed");
|
|
927
|
-
const data = Buffer.alloc(Number(opened.size) + 1); let count = 0;
|
|
928
|
-
while (count < data.length) { const n = readSync(fd, data, count, data.length - count, count); if (!n) break; count += n; }
|
|
929
|
-
if (count !== Number(opened.size) || stamp(fstatSync(fd, { bigint: true })) !== stamp(opened) || stamp(lstatSync(path, { bigint: true })) !== stamp(opened)) fail("changed");
|
|
930
|
-
text = new TextDecoder("utf-8", { fatal: true }).decode(data.subarray(0, count));
|
|
931
|
-
} finally { closeSync(fd); }
|
|
932
|
-
const counts: Record<SetupTarget, number> = { claude: 2, codex: 2, kimi: 2, pi: 2, qwen: 1, jcode: 2, opencode: 1, gemini: 1, agy: 1 };
|
|
933
|
-
let value: Receipt;
|
|
934
|
-
try { value = decodeReceipt(record(JSON.parse(text)), target, counts[target], true); } catch { return fail("unsupported"); }
|
|
935
|
-
if (value.phase !== "applied") fail("pending");
|
|
936
|
-
const runtime = mcpLauncher(mcpRecord(target, value.changes[0]!.after), target);
|
|
937
|
-
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))
|
|
938
|
-
|| target === "opencode" && [runtime.bun, runtime.entry].some(value => /\{(?:env|file):/.test(value))) fail("unsupported");
|
|
939
|
-
// #520: only a positively identified ENOENT/ENOTDIR for the recorded root names its setup target; a non-directory,
|
|
940
|
-
// a permission error and every other unreadable state stay anonymous.
|
|
941
|
-
let root: string;
|
|
942
|
-
try { root = realPath(dirname(dirname(runtime.entry))); }
|
|
943
|
-
catch (error) {
|
|
944
|
-
const code = (error as NodeJS.ErrnoException).code;
|
|
945
|
-
if (code === "ENOENT" || code === "ENOTDIR") fail("unavailable", target);
|
|
946
|
-
fail("unavailable");
|
|
947
|
-
}
|
|
948
|
-
if (!lstatSync(root, { throwIfNoEntry: false })?.isDirectory()) fail("unavailable");
|
|
949
|
-
roots.add(root); launchers.push({ entry: runtime.entry, root });
|
|
950
|
-
}
|
|
951
|
-
const finalHome = lstatSync(home, { bigint: true }); owned(finalHome);
|
|
952
|
-
if (!finalHome.isDirectory() || stamp(lstatSync(directory, { bigint: true })) !== stamp(initial) || finalHome.dev !== base.dev || finalHome.ino !== base.ino) fail("changed");
|
|
953
|
-
const finalNames: string[] = [], finalDirectory = opendirSync(directory);
|
|
954
|
-
try { for (;;) { const entry = finalDirectory.readSync(); if (!entry) break; if (finalNames.length >= namespace.length) fail("changed"); finalNames.push(entry.name); } }
|
|
955
|
-
finally { finalDirectory.closeSync(); }
|
|
956
|
-
if (JSON.stringify(finalNames.sort()) !== JSON.stringify(namespace.sort())) fail("changed");
|
|
957
|
-
for (const file of files) if (stamp(lstatSync(join(directory, file.name), { bigint: true })) !== stamp(file.stat)) fail("changed");
|
|
958
|
-
for (const runtime of launchers) if (realPath(dirname(dirname(runtime.entry))) !== runtime.root) fail("changed");
|
|
959
|
-
return [...roots].sort();
|
|
960
|
-
} catch (error) {
|
|
961
|
-
if (error && typeof error === "object" && !types.isProxy(error) && error instanceof SetupWriterRootsError) {
|
|
962
|
-
const category = Object.getOwnPropertyDescriptor(error, "category"), target = Object.getOwnPropertyDescriptor(error, "target")?.value;
|
|
963
|
-
if (category && "value" in category && ["unsafe", "changed", "bound", "unsupported", "pending", "unavailable"].includes(category.value))
|
|
964
|
-
throw new SetupWriterRootsError(category.value, typeof target === "string" && (SETUP_TARGETS as readonly string[]).includes(target) ? target as SetupTarget : undefined);
|
|
965
|
-
}
|
|
966
|
-
throw new SetupWriterRootsError("unavailable");
|
|
967
|
-
}
|
|
968
|
-
}
|
|
@@ -3,7 +3,7 @@ import { types } from "node:util";
|
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
4
|
import { canonicalPath, realPath } from "./memory/platform.ts";
|
|
5
5
|
import { canonicalJSON } from "./memory/generation.ts";
|
|
6
|
-
import { readSetupWriterRoots, SETUP_TARGETS, setupReceiptRemedy, SetupWriterRootsError, type SetupTarget } from "./setup.ts";
|
|
6
|
+
import { readSetupWriterRoots, SETUP_TARGETS, setupReceiptRemedy, SetupWriterRootsError, type SetupTarget } from "./setup-writer-roots.ts";
|
|
7
7
|
import { placementMarkerState } from "./memory/sync-placement-guard.ts";
|
|
8
8
|
import { measureSyncPlacementWriters, extractSyncPlacementWriterFailure, type SyncPlacementWriterFailureDetail, type SyncPlacementWriterMeasurement } from "./memory/sync-placement-writers.ts";
|
|
9
9
|
import { readEffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
|
|
@@ -12,6 +12,7 @@ import { FormatFloorError } from "./memory/formats.ts";
|
|
|
12
12
|
import type { PlacementCapturePort } from "./memory/sync-placement-capture.ts";
|
|
13
13
|
import { SharedWriterRevisionError } from "./memory/sync-placement-writer-revision-format.ts";
|
|
14
14
|
|
|
15
|
+
import { WRITER_CAUSE_CLASSES, WRITER_ROOT_CATEGORIES, type PlacementWriterRefusal } from "./memory/sync-placement-refusal-category.ts";
|
|
15
16
|
export type PlacementWriterRootCategory = "running CLI" | "host package" | "setup receipt" | "declared writer" | "active locator" | "home floor" | "writer renewal";
|
|
16
17
|
export type PlacementWriterContextPhase = "initial" | "active";
|
|
17
18
|
const failureDetails:Record<SyncPlacementWriterFailureDetail,string>={
|
|
@@ -69,8 +70,6 @@ function setupReceiptRefusal(error: unknown): { target: SetupTarget; phase: Plac
|
|
|
69
70
|
return { target: target as SetupTarget, phase: fields.phase?.value === "initial" ? "initial" : "active",
|
|
70
71
|
...(typeof detail === "string" && Object.hasOwn(failureDetails, detail) ? { detail: detail as SyncPlacementWriterFailureDetail } : {}) };
|
|
71
72
|
}
|
|
72
|
-
const WRITER_ROOT_CATEGORIES=["running CLI","host package","setup receipt","declared writer","active locator","home floor","writer renewal"] as const satisfies readonly PlacementWriterRootCategory[];
|
|
73
|
-
const WRITER_CAUSE_CLASSES=["missing","changed","unavailable"] as const;
|
|
74
73
|
/**
|
|
75
74
|
* #551 AC1: the refusal as fixed own data for a person-facing surface. A real PlacementWriterContextError - or the one a
|
|
76
75
|
* later sync failure carries as `placementRefusal` - is rebuilt from its own validated fields, so a tampered message, a
|
|
@@ -94,6 +93,12 @@ function placementWriterRefusal(error: unknown): PlacementWriterContextError | u
|
|
|
94
93
|
state === "staging" || state === "pending" || state === "checkpoint-pending" ? state : undefined,
|
|
95
94
|
typeof target === "string" && (SETUP_TARGETS as readonly string[]).includes(target) ? target as SetupTarget : undefined);
|
|
96
95
|
}
|
|
96
|
+
/** Closed data projection for progress telemetry. Shaped errors from other module copies do not qualify. */
|
|
97
|
+
export function placementWriterRefusalDetail(error: unknown): PlacementWriterRefusal | undefined {
|
|
98
|
+
const refusal = placementWriterRefusal(error);
|
|
99
|
+
return refusal && { causeClass: refusal.causeClass, rootCategory: refusal.category };
|
|
100
|
+
}
|
|
101
|
+
|
|
97
102
|
/** #551: no category is claimed here, because the state could not be read far enough to name one. */
|
|
98
103
|
const PLACEMENT_WRITER_UNVERIFIED_TEXT = "Placement writer verification could not establish a category: the retained writer inventory or its history could not be read far enough to name one; inspect the home with a compatible release, then run amem migrate --sync-placement --dry-run.";
|
|
99
104
|
/** An inventory state that could not be proven: never reported as a missing root, and never given an invented category. */
|
package/src/ui/plugin.ts
CHANGED
|
@@ -25,12 +25,14 @@ import { catalogKeys, readCatalogFresh } from "../memory/catalog.ts";
|
|
|
25
25
|
import { configuredPolicy, configuredPolicyOptions } from "../memory/config.ts";
|
|
26
26
|
import { openCuratedForRead, requireShard } from "../memory/curated-read.ts";
|
|
27
27
|
import { applyDecay, assertExactDecayForget, decayPreview, DECAY_DEFAULT_DAYS, readDecayCounters } from "../memory/decay-review.ts";
|
|
28
|
-
import {
|
|
28
|
+
import { planGc, runGc } from "../memory/gc.ts";
|
|
29
|
+
import { gcText } from "../memory/gc-text.ts";
|
|
29
30
|
import { memoryHome } from "../memory/home.ts";
|
|
30
31
|
import { appendLifecycle, assertProjectActive, projectState } from "../memory/lifecycle.ts";
|
|
31
32
|
import { hasFailLabel, noteAdd, parseFailTemplate } from "../memory/note-add.ts";
|
|
32
33
|
import type { StandalonePolicy } from "../memory/policy.ts";
|
|
33
|
-
import { applyPrune, planPrune
|
|
34
|
+
import { applyPrune, planPrune } from "../memory/prune.ts";
|
|
35
|
+
import { pruneText } from "../memory/prune-text.ts";
|
|
34
36
|
import { aliasedKeys, PlacementRealmRefusal, placementRealmGap, placementRealmView, readShardedSelection, resolveAlias, type PlacementRealmGap, type PlacementRealmView } from "../memory/shard.ts";
|
|
35
37
|
import { machineId, MemoryStore, openShardStore, type StoreOptions, type View } from "../memory/store.ts";
|
|
36
38
|
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { readWorkBrief, workLogSegments, workPolicyRevision } from "./brief-work.ts";
|
|
4
|
+
import { configuredPolicyOptions } from "./memory/config.ts";
|
|
5
|
+
import { machineId } from "./memory/machine.ts";
|
|
6
|
+
import { recordBriefPublicationFailure } from "./memory/metrics.ts";
|
|
7
|
+
import { aliasedKeys, resolveAlias, shardDir } from "./memory/shard.ts";
|
|
8
|
+
import { WorkListStore } from "./memory/work-lists.ts";
|
|
9
|
+
|
|
10
|
+
/** Explicit off-hook preparation for existing work logs, including logs written before snapshots existed. */
|
|
11
|
+
export async function prepareWorkBriefCache(base: string, project: string, cwd: string): Promise<void> {
|
|
12
|
+
try {
|
|
13
|
+
const canonical = resolveAlias(base, project), aliases = aliasedKeys(base, canonical);
|
|
14
|
+
if (![canonical, ...aliases].some(key => existsSync(join(shardDir(base, key), "work", "log")))) return;
|
|
15
|
+
const segments = workLogSegments(base, canonical, aliases);
|
|
16
|
+
if (!segments) return recordBriefPublicationFailure(base, "work", "source_unavailable");
|
|
17
|
+
const machine = machineId(base).id, policyOptions = () => configuredPolicyOptions(base, cwd);
|
|
18
|
+
const homeRevision = workPolicyRevision(configuredPolicyOptions(base)), effectiveRevision = workPolicyRevision(policyOptions());
|
|
19
|
+
const current = (policy: string, revision?: string) => {
|
|
20
|
+
const brief = readWorkBrief({ base, project: canonical, machine, revision });
|
|
21
|
+
return brief?.policy === policy && JSON.stringify(brief.segments) === JSON.stringify(segments);
|
|
22
|
+
};
|
|
23
|
+
if (current(homeRevision) && (homeRevision === effectiveRevision || current(effectiveRevision, effectiveRevision))) return;
|
|
24
|
+
const store = new WorkListStore({ base, project: canonical, aliases, policy: () => false, briefPolicyOptions: policyOptions });
|
|
25
|
+
try { await store.publishBrief(); }
|
|
26
|
+
finally { store.close(); }
|
|
27
|
+
} catch { recordBriefPublicationFailure(base, "work", "source_unavailable"); }
|
|
28
|
+
}
|