@staix/agent-mem 0.27.0 → 0.28.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 +9 -9
- package/package.json +1 -1
- package/src/cli-agent-reads.ts +11 -19
- package/src/cli.ts +121 -26
- package/src/commands-table.ts +6 -0
- package/src/index.ts +2 -0
- package/src/mcp-memory.ts +19 -6
- package/src/memory/candidate-origin.ts +63 -0
- package/src/memory/candidates.ts +30 -10
- package/src/memory/capture.ts +25 -0
- package/src/memory/cli-attribution.ts +17 -1
- package/src/memory/commands.ts +3 -1
- package/src/memory/consolidate.ts +15 -3
- package/src/memory/consolidation-model.ts +10 -4
- package/src/memory/formats-raise.ts +114 -0
- package/src/memory/sync-placement-batch-intent.ts +100 -0
- package/src/memory/sync-placement-journal-storage.ts +83 -12
- package/src/memory/sync-placement-transport.ts +17 -3
- package/src/ui/panel.js +7 -2
- package/src/ui/plugin.ts +2 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #323: where a candidate came from, as ids only. The proposing host supplies them; nothing is inferred from capture.
|
|
3
|
+
* Stored in its own nullable `candidates.origin` column, outside the hashed payload, so a candidate id and every older reader
|
|
4
|
+
* (which selects named columns or ignores unknown ones) are unchanged. A row written before 0.28 has no origin: `unknown`.
|
|
5
|
+
*/
|
|
6
|
+
export interface CandidateOrigin {
|
|
7
|
+
/** The capture session key: 16 lowercase hex, the same `session` a capture row carries. */
|
|
8
|
+
session?: string;
|
|
9
|
+
/** The proposing agent's peer id. */
|
|
10
|
+
peer?: string;
|
|
11
|
+
/** When the proposal was made, canonical UTC. */
|
|
12
|
+
at?: string;
|
|
13
|
+
/** An opaque host turn id. */
|
|
14
|
+
turn?: string;
|
|
15
|
+
}
|
|
16
|
+
import { looksSecret } from "./screen.ts";
|
|
17
|
+
const SESSION = /^[a-f0-9]{16}$/, ID = /^[A-Za-z0-9._:@-]{1,120}$/;
|
|
18
|
+
|
|
19
|
+
/** Ids only: a field that is not a bounded id is refused, so no text, path or secret can enter `origin`. */
|
|
20
|
+
export function validOrigin(value: unknown): CandidateOrigin | undefined {
|
|
21
|
+
if (value === undefined || value === null) return undefined;
|
|
22
|
+
if (typeof value !== "object" || Array.isArray(value)) throw new Error("candidate origin must be an object; supply session, peer, at or turn ids");
|
|
23
|
+
const keys = Object.keys(value), raw = value as Record<string, unknown>;
|
|
24
|
+
if (keys.some(key => !["session", "peer", "at", "turn"].includes(key))) throw new Error("candidate origin has an unknown field; use only session, peer, at and turn");
|
|
25
|
+
const out: CandidateOrigin = {};
|
|
26
|
+
if (raw.session !== undefined) { if (typeof raw.session !== "string" || !SESSION.test(raw.session)) throw new Error("candidate origin session must be a 16-character lowercase hex capture session key; pass the capture session key"); out.session = raw.session; }
|
|
27
|
+
if (raw.peer !== undefined) { if (typeof raw.peer !== "string" || !ID.test(raw.peer)) throw new Error("candidate origin peer must be 1 to 120 characters from A-Z, a-z, 0-9, dot, underscore, colon, at sign or hyphen; pass a peer id"); out.peer = raw.peer; }
|
|
28
|
+
if (raw.turn !== undefined) { if (typeof raw.turn !== "string" || !ID.test(raw.turn)) throw new Error("candidate origin turn must be 1 to 120 characters from A-Z, a-z, 0-9, dot, underscore, colon, at sign or hyphen; pass a turn id"); out.turn = raw.turn; }
|
|
29
|
+
if (raw.at !== undefined) {
|
|
30
|
+
if (typeof raw.at !== "string" || !Number.isFinite(Date.parse(raw.at)) || new Date(raw.at).toISOString() !== raw.at) throw new Error("candidate origin time must be canonical UTC; pass an ISO timestamp with milliseconds and Z");
|
|
31
|
+
out.at = raw.at;
|
|
32
|
+
}
|
|
33
|
+
// AC3: the unchanged secret screen applies to the ids too; an id shaped like a token is refused, never stored.
|
|
34
|
+
if (Object.values(out).some(value => looksSecret(value))) throw new Error("candidate origin refused by the secret screen; remove the secret-like id and pass a safe session or peer id");
|
|
35
|
+
return Object.keys(out).length ? out : undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** #323 AC1: every supplied origin field as an ids-only graph node, so an accepted note keeps the whole origin. */
|
|
39
|
+
export function originNodes(origin: CandidateOrigin | undefined): string[] {
|
|
40
|
+
if (!origin) return [];
|
|
41
|
+
return [...(origin.session ? [`session:${origin.session}`] : []), ...(origin.peer ? [`peer:${origin.peer}`] : []),
|
|
42
|
+
...(origin.at ? [`origin-at:${origin.at}`] : []), ...(origin.turn ? [`turn:${origin.turn}`] : [])];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type OriginRecheck = "available" | "origin expired" | "unavailable" | "unknown";
|
|
46
|
+
/**
|
|
47
|
+
* #323 item 4: whether a note's origin session can still be re-checked against capture. Only a confirmed absence from a readable,
|
|
48
|
+
* session-capable store is `origin expired` (never a failed check). An unreadable, missing, unsupported or policy-withheld capture is
|
|
49
|
+
* `unavailable`, so expiry is never claimed and withheld rows are never disclosed; no recorded session is `unavailable` too.
|
|
50
|
+
*/
|
|
51
|
+
export function originRecheck(origin: CandidateOrigin | undefined, known: boolean, lookup: (session: string) => "present" | "absent" | "unavailable" | "unsupported"): OriginRecheck {
|
|
52
|
+
if (!known) return "unknown";
|
|
53
|
+
if (!origin?.session) return "unavailable";
|
|
54
|
+
let state: ReturnType<typeof lookup>; try { state = lookup(origin.session); } catch { return "unavailable"; }
|
|
55
|
+
return state === "present" ? "available" : state === "absent" ? "origin expired" : "unavailable";
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** One line for previews and the note provenance; absent fields read `unavailable`, never a guess. */
|
|
59
|
+
export function originLine(origin: CandidateOrigin | undefined, known = true): string {
|
|
60
|
+
if (!known) return "origin: unknown (proposed before origin was recorded)";
|
|
61
|
+
if (!origin) return "origin: unavailable";
|
|
62
|
+
return `origin: session ${origin.session ?? "unavailable"}, peer ${origin.peer ?? "unavailable"}, at ${origin.at ?? "unavailable"}${origin.turn ? `, turn ${origin.turn}` : ""}`;
|
|
63
|
+
}
|
package/src/memory/candidates.ts
CHANGED
|
@@ -9,6 +9,8 @@ import { cliAttribution } from "./cli-attribution.ts";
|
|
|
9
9
|
import { memoryHome } from "./home.ts";
|
|
10
10
|
import { realPath } from "./platform.ts";
|
|
11
11
|
import { stripPrivateDeep } from "./private-spans.ts";
|
|
12
|
+
import { originNodes, validOrigin, type CandidateOrigin } from "./candidate-origin.ts";
|
|
13
|
+
const hasColumn = (db: Database, name: string): boolean => (db.query("PRAGMA table_info(candidates)").all() as { name: string }[]).some(column => column.name === name);
|
|
12
14
|
import { MemoryStore, type GoalView, type NoteInput, type View } from "./store.ts";
|
|
13
15
|
|
|
14
16
|
export const CANDIDATE_DB_BUSY_TIMEOUT_MS = 3000;
|
|
@@ -46,7 +48,11 @@ export type CandidateInput = { project: string } & (
|
|
|
46
48
|
| { kind: "model-answer"; marker: "model-answer"; targets: CandidateTarget[]; text: string }
|
|
47
49
|
);
|
|
48
50
|
export type CandidateStatus = "pending" | "accepting" | "accepted" | "rejected";
|
|
49
|
-
export interface Candidate { id: string; createdAt: string; status: CandidateStatus; input: CandidateInput; acceptedNoteId: string | null
|
|
51
|
+
export interface Candidate { id: string; createdAt: string; status: CandidateStatus; input: CandidateInput; acceptedNoteId: string | null;
|
|
52
|
+
/** #323: ids the proposing host supplied; absent when it supplied none. */
|
|
53
|
+
origin?: CandidateOrigin;
|
|
54
|
+
/** #323: false for a row written before origin was recorded (pre-0.28 writer): its origin is unknown, not absent. */
|
|
55
|
+
originKnown: boolean }
|
|
50
56
|
export interface ConsolidationReview { status: Exclude<CandidateStatus, "pending">; acceptedNoteId: string | null }
|
|
51
57
|
const KINDS: readonly string[] = ["correction", "fail", "decay", "memory", "promotion", "consolidation", "model-answer"] satisfies CandidateInput["kind"][];
|
|
52
58
|
export interface CandidateFilter { project: string; status?: CandidateStatus | "all"; kind?: CandidateInput["kind"]; limit?: number }
|
|
@@ -167,14 +173,21 @@ function retryLocked(work: () => void): void {
|
|
|
167
173
|
}
|
|
168
174
|
}
|
|
169
175
|
|
|
170
|
-
type CandidateRow = { id: string; payload: string; at: number; status: CandidateStatus; note_id: string | null };
|
|
176
|
+
type CandidateRow = { id: string; payload: string; at: number; status: CandidateStatus; note_id: string | null; origin?: string | null };
|
|
177
|
+
/** #323: NULL (a pre-0.28 row, or a column an older writer never filled) is unknown; `{}` is a recorded empty origin. */
|
|
178
|
+
function decodeOrigin(raw: string | null | undefined): { origin?: CandidateOrigin; originKnown: boolean } {
|
|
179
|
+
if (raw === null || raw === undefined) return { originKnown: false };
|
|
180
|
+
let parsed: unknown; try { parsed = JSON.parse(raw); } catch { throw new Error("candidate origin unreadable; inspect or restore the candidate database before retrying"); }
|
|
181
|
+
const origin = validOrigin(parsed);
|
|
182
|
+
return origin ? { origin, originKnown: true } : { originKnown: true };
|
|
183
|
+
}
|
|
171
184
|
/** Canonical persisted decoding shared by the writer and its read-only inbox port. */
|
|
172
185
|
function decodeCandidate(row: CandidateRow, unknownKind: () => void): Candidate | undefined {
|
|
173
186
|
const input = JSON.parse(row.payload) as CandidateInput;
|
|
174
187
|
if (input && typeof input === "object" && !KINDS.includes(input.kind)) { unknownKind(); return undefined; }
|
|
175
188
|
validate(input);
|
|
176
189
|
if (hash({ schema: "agent-mem.candidate/v1", input }) !== row.id) throw new Error("candidate content hash mismatch");
|
|
177
|
-
return { id: row.id, createdAt: new Date(row.at).toISOString(), status: row.status, input, acceptedNoteId: row.note_id };
|
|
190
|
+
return { id: row.id, createdAt: new Date(row.at).toISOString(), status: row.status, input, acceptedNoteId: row.note_id, ...decodeOrigin(row.origin) };
|
|
178
191
|
}
|
|
179
192
|
const CANDIDATE_EXPIRED_SQL = "at <= ? AND (status IN ('accepted', 'rejected') OR (shown_at IS NOT NULL AND shown_at <= ?))";
|
|
180
193
|
const CANDIDATE_PRIORITY_SQL = "CASE WHEN status IN ('pending', 'accepting') AND shown_at IS NULL THEN 2 WHEN status IN ('pending', 'accepting') THEN 1 ELSE 0 END DESC, at DESC";
|
|
@@ -194,8 +207,8 @@ export function withPendingCandidates<T>(memoryDir: string, run: (reader: Pendin
|
|
|
194
207
|
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("pending candidates unavailable");
|
|
195
208
|
const db = new Database(file, { readonly: true }); let closed = false;
|
|
196
209
|
try {
|
|
197
|
-
const shown = hasShownColumn(db), now = Date.now();
|
|
198
|
-
const live = (scope: boolean) => `WITH raw AS (SELECT rowid AS candidate_rowid, id, project, kind, payload, at, status, note_id, ${shown ? "shown_at" : "NULL AS shown_at"} FROM candidates${scope ? " WHERE project IN (SELECT value FROM json_each(?))" : ""}),
|
|
210
|
+
const shown = hasShownColumn(db), origins = hasColumn(db, "origin"), now = Date.now();
|
|
211
|
+
const live = (scope: boolean) => `WITH raw AS (SELECT rowid AS candidate_rowid, id, project, kind, payload, at, status, note_id, ${shown ? "shown_at" : "NULL AS shown_at"}, ${origins ? "origin" : "NULL AS origin"} FROM candidates${scope ? " WHERE project IN (SELECT value FROM json_each(?))" : ""}),
|
|
199
212
|
live AS (SELECT * FROM raw WHERE NOT (${CANDIDATE_EXPIRED_SQL})),
|
|
200
213
|
retained AS (SELECT *, row_number() OVER (PARTITION BY project ORDER BY ${CANDIDATE_PRIORITY_SQL}, candidate_rowid DESC) AS retention_rank FROM live)`;
|
|
201
214
|
const assertOpen = () => { if (closed) throw new Error("pending candidate reader is closed"); };
|
|
@@ -265,6 +278,8 @@ export class CandidateStore {
|
|
|
265
278
|
// F7 / AC4: when a candidate was first shown to the person. In place and nullable: an older database gains it here, and a reader without it treats every row as unshown.
|
|
266
279
|
// Several processes open this store at once (every `amem mcp` builds it at startup), so the check and the ALTER are one immediate transaction: the loser waits, then sees the column.
|
|
267
280
|
if (!hasShownColumn(this.db)) this.db.transaction(() => { if (!hasShownColumn(this.db)) this.db.run("ALTER TABLE candidates ADD COLUMN shown_at INTEGER"); }).immediate();
|
|
281
|
+
// #323: the origin ids, in place and nullable like shown_at. Outside the hashed payload, so ids are unchanged and an older reader never sees it.
|
|
282
|
+
if (!hasColumn(this.db, "origin")) this.db.transaction(() => { if (!hasColumn(this.db, "origin")) this.db.run("ALTER TABLE candidates ADD COLUMN origin TEXT"); }).immediate();
|
|
268
283
|
this.db.run("CREATE TABLE IF NOT EXISTS consolidation_reviews (id TEXT PRIMARY KEY, project TEXT NOT NULL, status TEXT NOT NULL, note_id TEXT)");
|
|
269
284
|
this.db.run("CREATE TABLE IF NOT EXISTS counters (id TEXT PRIMARY KEY, project TEXT NOT NULL, payload TEXT NOT NULL, at INTEGER NOT NULL, rendered INTEGER, delivered INTEGER, cited INTEGER)");
|
|
270
285
|
this.prune();
|
|
@@ -300,11 +315,13 @@ export class CandidateStore {
|
|
|
300
315
|
private decode(row: CandidateRow): Candidate | undefined {
|
|
301
316
|
return decodeCandidate(row, () => { this.skippedUnknownKinds++; });
|
|
302
317
|
}
|
|
303
|
-
put(rawInput: CandidateInput, verdict: CandidateVerdict): string {
|
|
318
|
+
put(rawInput: CandidateInput, verdict: CandidateVerdict, rawOrigin?: CandidateOrigin, screen?: (origin: CandidateOrigin) => boolean): string {
|
|
304
319
|
// `<private>` spans are never stored: dropped before the input is validated, hashed (so the id) or written.
|
|
305
320
|
const input = stripPrivateDeep(rawInput);
|
|
306
321
|
publicOnly(verdict); validate(input);
|
|
307
|
-
const payload = canonical(input), id = candidateInputId(input);
|
|
322
|
+
const origin = validOrigin(rawOrigin), payload = canonical(input), id = candidateInputId(input);
|
|
323
|
+
// AC3: the caller's configured privacy screen sees the origin ids before they are stored; a refused origin refuses the proposal.
|
|
324
|
+
if (origin && screen && screen(origin) !== true) throw new Error("candidate origin refused by the configured privacy policy; remove the declined id or review the current policy");
|
|
308
325
|
// Prune, count, insert and prune again are ONE immediate transaction: concurrent proposers (several agents) cannot all pass the count and then let the cap evict an unseen candidate.
|
|
309
326
|
return this.db.transaction((): string => {
|
|
310
327
|
this.prune();
|
|
@@ -321,7 +338,8 @@ export class CandidateStore {
|
|
|
321
338
|
// Upgrade with an explicit person-audited receipt archive before increasing this bounded sidecar capacity.
|
|
322
339
|
if (allocated.n >= CONSOLIDATION_REVIEW_LIMIT) throw new ConsolidationReviewLimit(input.project, allocated.n);
|
|
323
340
|
}
|
|
324
|
-
|
|
341
|
+
// A re-proposal of the same content keeps its first origin: the id is content-addressed, and the first proposer is the one to re-check.
|
|
342
|
+
this.db.query("INSERT OR IGNORE INTO candidates (id, project, kind, payload, at, status, origin) VALUES (?, ?, ?, ?, ?, 'pending', ?)").run(id, input.project, input.kind, payload, this.now(), JSON.stringify(origin ?? {}));
|
|
325
343
|
this.prune();
|
|
326
344
|
return id;
|
|
327
345
|
}).immediate();
|
|
@@ -449,7 +467,7 @@ export class CandidateStore {
|
|
|
449
467
|
tier: data.kind === "correction" && target!.local ? "short" : "long",
|
|
450
468
|
kind: data.kind === "fail" ? "fail" : data.noteKind ?? (target?.kind === "contract" || target?.kind === "fail" || target?.kind === "preference" ? target.kind : "decision"), peer: attributionPeer(context.actor), source: "person",
|
|
451
469
|
// A Record candidate carries the edges its anchors name, so the accepted note stays findable by path and symbol.
|
|
452
|
-
about: [...new Set([...(target?.about ?? []), ...(data.kind === "memory" || data.kind === "fail" ? data.about ?? [] : [])])],
|
|
470
|
+
about: [...new Set([...(target?.about ?? []), ...(data.kind === "memory" || data.kind === "fail" ? data.about ?? [] : []), ...originNodes(candidate.origin)])],
|
|
453
471
|
text: data.kind === "correction" ? acceptedCorrectionText(data, id) : `Accepted candidate: ${id}\nTarget revision: ${(data.kind === "memory" ? undefined : data.target)?.revision ?? "none"}\nTarget entry: ${(data.kind === "memory" ? undefined : data.target)?.id ?? "none"}\n\n${body}` };
|
|
454
472
|
if (note.text.length > 4000) throw new Error("accepted candidate text exceeds the v1 note limit");
|
|
455
473
|
if (context.policy(structuredClone(candidate), target && structuredClone(target), structuredClone(note)) !== true) throw new Error("candidate refused by current host policy");
|
|
@@ -499,7 +517,7 @@ export class CandidateStore {
|
|
|
499
517
|
return current;
|
|
500
518
|
};
|
|
501
519
|
const sources = check(), first = sources[0]!;
|
|
502
|
-
const note: NoteInput = { op: "note", project: context.project, scope: first.scope, tier: "long", kind: data.noteKind, peer: attributionPeer(context.actor), source: "person", about: [...data.about],
|
|
520
|
+
const note: NoteInput = { op: "note", project: context.project, scope: first.scope, tier: "long", kind: data.noteKind, peer: attributionPeer(context.actor), source: "person", about: [...new Set([...data.about, ...originNodes(candidate.origin)])],
|
|
503
521
|
text: `${ACCEPTED_CONSOLIDATION_PREFIX}${candidate.id}\nAction: ${data.action}\nSources: ${data.targets.map(target => `mem:${target.id}`).join(", ")}\n\n${data.text}` };
|
|
504
522
|
if (note.text.length > 4000) throw Error("accepted consolidation exceeds the v1 note limit");
|
|
505
523
|
for (const source of sources) if (context.policy(structuredClone(candidate), structuredClone(source), structuredClone(note)) !== true) throw Error("consolidation refused by current host policy");
|
|
@@ -543,6 +561,8 @@ export class CandidateStore {
|
|
|
543
561
|
resolve();
|
|
544
562
|
const replay = this.beginAcceptance(candidate.id, context.project); if (replay) return { candidateId: candidate.id, noteId: replay, alreadyAccepted: true };
|
|
545
563
|
// A thrown append remains accepting: its authored-row outcome needs person-audited recovery.
|
|
564
|
+
// #323: a promotion keeps its canonical identity (the id is the source note's own fields), so its origin stays on the candidate row
|
|
565
|
+
// (`amem review list --status all`), not on the promoted note: an extra edge would fork that id across machines.
|
|
546
566
|
const noteId = context.store.promote(target.id, context.actor, context.project);
|
|
547
567
|
if (noteId === undefined) {
|
|
548
568
|
this.db.query("UPDATE candidates SET status = 'pending' WHERE id = ? AND project IN (SELECT value FROM json_each(?)) AND status = 'accepting'").run(candidate.id, this.scope(context.project));
|
package/src/memory/capture.ts
CHANGED
|
@@ -737,6 +737,31 @@ export class CaptureStore {
|
|
|
737
737
|
* window holds only the newest 32, so proving a candidate with that window would read every older row as pruned. These are
|
|
738
738
|
* point lookups on the `at` index with an explicit per-turn cap: no scan, no window, and no index or spool work.
|
|
739
739
|
*/
|
|
740
|
+
/**
|
|
741
|
+
* #323 item 4: check at most 128 newest rows plus a sentinel, with no unbounded session scan. Any withheld row makes an absent
|
|
742
|
+
* session inconclusive, so the result cannot distinguish a hidden session from an absent one. Only a complete screened window
|
|
743
|
+
* can establish absence. This port requires a read-only store and never creates or migrates capture storage.
|
|
744
|
+
*/
|
|
745
|
+
sessionState(session: string, visible: (row: CaptureRow) => boolean): "present" | "absent" | "unavailable" | "unsupported" {
|
|
746
|
+
this.checkReadBinding();
|
|
747
|
+
if (!this.readOnly) throw new Error("session recheck requires a read-only capture store; open CaptureStore with readOnly: true");
|
|
748
|
+
if (typeof session !== "string" || !SESSION_KEY.test(session)) throw new Error("invalid session key; use a 16-character lowercase hex capture session key");
|
|
749
|
+
const columns = new Set((this.db.query("PRAGMA table_info(rows)").all() as { name: string }[]).map(column => column.name));
|
|
750
|
+
if (!columns.has("session")) return "unsupported";
|
|
751
|
+
// INTEGER PRIMARY KEY order stops after the fixed sentinel; never filter by session before the bound.
|
|
752
|
+
const rows = this.db.query("SELECT * FROM rows ORDER BY id DESC LIMIT 129").all() as RawRow[];
|
|
753
|
+
let withheld = false, present = false;
|
|
754
|
+
try {
|
|
755
|
+
for (const raw of rows.slice(0, 128)) {
|
|
756
|
+
const row = toRow(raw), permitted = visible(row) === true;
|
|
757
|
+
if (!permitted) withheld = true;
|
|
758
|
+
else if (row.project === this.key && row.session === session) present = true;
|
|
759
|
+
}
|
|
760
|
+
} catch { return "unavailable"; }
|
|
761
|
+
if (present) return "present";
|
|
762
|
+
return withheld || rows.length > 128 || this.recentReadTruncated ? "unavailable" : "absent";
|
|
763
|
+
}
|
|
764
|
+
|
|
740
765
|
readRecordTurns(turns: readonly { session: string; at: string }[]): CaptureRow[] {
|
|
741
766
|
this.checkReadBinding();
|
|
742
767
|
if (!Array.isArray(turns) || turns.length < 1 || turns.length > 8 || turns.some(turn => !turn
|
|
@@ -6,7 +6,23 @@ const scope = new AsyncLocalStorage<Readonly<CliAttribution>>();
|
|
|
6
6
|
|
|
7
7
|
/** Preserve library defaults outside an ordinary CLI invocation, including concurrent calls. */
|
|
8
8
|
export function cliAttribution(): Readonly<CliAttribution> | undefined { return scope.getStore(); }
|
|
9
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Run `work` with `identity` in the attribution scope (root API, #431 / agent-hub#1522). Only library code that reads the scope is
|
|
11
|
+
* attributed: `rawMemoryCommand` promote, demote, forget, supersede, confirm and reject, every `rawGoalCommand` write and the
|
|
12
|
+
* `MemoryStore.dedupe` replacement record `identity.actor` as the operation actor (default `user`); notes written by `CandidateStore.accept`
|
|
13
|
+
* record `identity.peer` as their peer (default: the accept call's actor). Other writes, including a direct `MemoryStore.note`, are not
|
|
14
|
+
* attributed and keep what their caller passes. An agent scope also refuses withheld targets in those commands and screens
|
|
15
|
+
* `assertCliPolicy` values with `identity.policy`. Attribution only: it never authenticates, grants access or bypasses a screen.
|
|
16
|
+
* docs/contracts.md (Attribution scope) is the full list. It refuses before running `work` when it has no agent identity (no usable peer).
|
|
17
|
+
*/
|
|
18
|
+
export function withCliAttribution<T>(identity: CliAttribution, work: () => T): T {
|
|
19
|
+
if (!identity || (identity.actor !== "person" && identity.actor !== "agent")) throw new Error("memory attribution needs actor person or agent");
|
|
20
|
+
const remedy = "Fix or unset AGENTHUB_PEER_ID, or pass a nonblank session peer id of at most 120 characters without control characters";
|
|
21
|
+
if (typeof identity.peer !== "string" || !identity.peer.trim()) throw new Error(`memory attribution peer is missing or blank; nothing was run. ${remedy}`);
|
|
22
|
+
if (identity.peer.length > 120) throw new Error(`memory attribution peer exceeds 120 characters; nothing was run. ${remedy}`);
|
|
23
|
+
if (/[\p{Cc}]/u.test(identity.peer)) throw new Error(`memory attribution peer contains a control character; nothing was run. ${remedy}`);
|
|
24
|
+
return scope.run(Object.freeze({ ...identity, peer: identity.actor === "agent" && identity.peer === "person" ? "agent" : identity.peer }), work);
|
|
25
|
+
}
|
|
10
26
|
|
|
11
27
|
/** Display metadata derived from the existing peer field; never a claim of authentication. */
|
|
12
28
|
export const noteDisplayActor = (peer: string): "person" | "agent" => peer === "person" ? "person" : "agent";
|
package/src/memory/commands.ts
CHANGED
|
@@ -32,6 +32,8 @@ export interface MemoryCommandOptions {
|
|
|
32
32
|
sync?: Omit<SyncOptions, "remote">;
|
|
33
33
|
open: () => MemoryStore;
|
|
34
34
|
readable: (notes: View[]) => View[];
|
|
35
|
+
/** #431: an agent-marked CLI graph is screened by `readable`; a host's raw graph stays an explicit person-only ceiling. */
|
|
36
|
+
screenGraph?: boolean;
|
|
35
37
|
stale?: (view: View) => boolean | undefined;
|
|
36
38
|
/** Prepared row ids only: the host must wait for successful output before recording rendered. */
|
|
37
39
|
outputReady?: (notes: readonly View[]) => void;
|
|
@@ -188,7 +190,7 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
|
|
|
188
190
|
if (hops !== 1 && hops !== 2) fail("--hops takes 1 or 2");
|
|
189
191
|
const asOf = flag("--as-of"), history = rest.includes("--history"); if (history) rest.splice(rest.indexOf("--history"), 1);
|
|
190
192
|
const start = rest[0] ?? fail(`usage: ${names.memory} graph <id|node>`);
|
|
191
|
-
const g = recallGraph(store, project, start, hops, { person: opts.person, history, asOf });
|
|
193
|
+
const g = recallGraph(store, project, start, hops, { person: opts.person, history, asOf }, opts.screenGraph ? rows => opts.readable(rows) : undefined);
|
|
192
194
|
if ((!start.includes(":") || start.startsWith("mem:")) && !g.nodes.length) fail(`no memory entry ${start} (${names.memory} list shows the ids)`);
|
|
193
195
|
const node = !start.includes(":") || start.startsWith("mem:") ? g.nodes[0]!.id : start;
|
|
194
196
|
return json ? JSON.stringify(g, null, 2) : [`${g.nodes.length} nodes, ${g.edges.length} edges around ${node}`, ...g.edges.map((e) => `${e.from} -${e.rel}-> ${e.to}`)].join("\n");
|
|
@@ -4,11 +4,14 @@ import { memoryPolicySnapshot, type StandalonePolicy } from "./policy.ts";
|
|
|
4
4
|
import { recallViewIsLive } from "./recall.ts";
|
|
5
5
|
import type { MemoryStore, View } from "./store.ts";
|
|
6
6
|
import { realPath } from "./platform.ts";
|
|
7
|
+
import { validOrigin, type CandidateOrigin } from "./candidate-origin.ts";
|
|
7
8
|
import { proposeModelConsolidations, type ModelConsolidationOptions, type ModelConsolidationReport } from "./consolidation-model.ts";
|
|
8
9
|
import { recordCandidates, type RecordCandidateCounts, type RecordCandidateWindow } from "./record-candidates.ts";
|
|
9
10
|
|
|
10
11
|
export interface ConsolidationOptions {
|
|
11
12
|
project: string; actor: "person" | "agent"; policy: () => StandalonePolicy; policyVersion: () => string;
|
|
13
|
+
/** #323: ids of the run that proposes (its peer, its session if the host knows one); recorded on each candidate, never inferred. */
|
|
14
|
+
origin?: CandidateOrigin;
|
|
12
15
|
allowed?: () => boolean; assertCurrent?: () => void;
|
|
13
16
|
/** Person-enabled host callback only. Absent means no model work or budget reservation. */
|
|
14
17
|
model?: ModelConsolidationOptions;
|
|
@@ -51,6 +54,14 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
|
|
|
51
54
|
check();
|
|
52
55
|
if (!await policy.screen({ project })) throw Error("consolidation refused by current policy");
|
|
53
56
|
check();
|
|
57
|
+
// #323 AC3: the full host policy screens the run origin, then the synchronous snapshot again after the check fence; a declined
|
|
58
|
+
// origin is recorded as none and the run goes on. The policy version is fenced by check() before every put below.
|
|
59
|
+
let originSnapshot: CandidateOrigin | undefined;
|
|
60
|
+
try { originSnapshot = validOrigin(memoryPolicySnapshot(options.origin)); } catch { originSnapshot = undefined; }
|
|
61
|
+
if (originSnapshot) Object.freeze(originSnapshot);
|
|
62
|
+
let runOrigin = originSnapshot && await policy.screen({ project, origin: originSnapshot }) ? originSnapshot : undefined;
|
|
63
|
+
check();
|
|
64
|
+
if (runOrigin && !policy.screenStandalone({ project, origin: runOrigin })) runOrigin = undefined;
|
|
54
65
|
const raw = store.withDeferredPromotions(() => store.list({ project, limit: 257 })), rows: View[] = [];
|
|
55
66
|
for (const value of raw) {
|
|
56
67
|
check(); const row = memoryPolicySnapshot(value);
|
|
@@ -86,7 +97,7 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
|
|
|
86
97
|
check();
|
|
87
98
|
const id = candidateInputId(input), known = candidates.get(id, project);
|
|
88
99
|
if (known && known.status !== "pending" || candidates.reviewedConsolidation(id, project)) { report.alreadyReviewed++; continue; }
|
|
89
|
-
candidates.put(input, "public");
|
|
100
|
+
candidates.put(input, "public", runOrigin && policy.screenStandalone({ project, origin: runOrigin }) ? runOrigin : undefined);
|
|
90
101
|
report.candidates.push({ id, action: input.action, sources: input.targets.map(target => `mem:${target.id}`) });
|
|
91
102
|
}
|
|
92
103
|
// #368: the same one-at-a-time discipline for Record rows. A group key already in the queue is not proposed again, so a
|
|
@@ -103,14 +114,15 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
|
|
|
103
114
|
check(); if (!await policy.screen(proposal.source)) { counts.refused++; continue; }
|
|
104
115
|
check(); if (!await policy.screen(proposal.input)) { counts.refused++; continue; }
|
|
105
116
|
check();
|
|
106
|
-
|
|
117
|
+
// #323: the proposer's origin only. The Record's own capture sessions stay in its bound sources; none is promoted to origin.
|
|
118
|
+
candidates.put(proposal.input, "public", runOrigin && policy.screenStandalone({ project, origin: runOrigin }) ? runOrigin : undefined);
|
|
107
119
|
counts.queued++;
|
|
108
120
|
report.candidates.push({ id: candidateInputId(proposal.input), action: `record:${proposal.input.kind === "fail" ? "fail" : proposal.input.noteKind}`,
|
|
109
121
|
sources: (proposal.input.record?.sources ?? []).map(source => `capture:${source.session}@${source.at}`) });
|
|
110
122
|
}
|
|
111
123
|
report.records = counts;
|
|
112
124
|
}
|
|
113
|
-
if (options.model !== undefined) report.model = await proposeModelConsolidations(store, candidates, synced, options.model, { project, actor: options.actor, check, policy });
|
|
125
|
+
if (options.model !== undefined) report.model = await proposeModelConsolidations(store, candidates, synced, options.model, { project, actor: options.actor, check, policy, ...(runOrigin ? { origin: runOrigin } : {}) });
|
|
114
126
|
} catch (error) { throw new ConsolidationProposalError(report.candidates.map(row => row.id), error instanceof ConsolidationReviewLimit ? error : undefined); }
|
|
115
127
|
return report;
|
|
116
128
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { types } from "node:util";
|
|
2
2
|
import { candidateTargetRevision, type CandidateInput, type CandidateStore } from "./candidates.ts";
|
|
3
3
|
import { memoryPolicySnapshot, type StandalonePolicy } from "./policy.ts";
|
|
4
|
+
import { validOrigin, type CandidateOrigin } from "./candidate-origin.ts";
|
|
4
5
|
import { realPath } from "./platform.ts";
|
|
5
6
|
import { recallViewIsLive } from "./recall.ts";
|
|
6
7
|
import type { MemoryStore, View } from "./store.ts";
|
|
@@ -11,7 +12,7 @@ export interface ModelConsolidationOptions {
|
|
|
11
12
|
enabled: true;
|
|
12
13
|
run: (input: ModelConsolidationInput, signal: AbortSignal) => Promise<{ text: string } | null>;
|
|
13
14
|
}
|
|
14
|
-
export interface ModelConsolidationGuard { project: string; actor: "person" | "agent"; check(): void; policy: StandalonePolicy }
|
|
15
|
+
export interface ModelConsolidationGuard { project: string; actor: "person" | "agent"; check(): void; policy: StandalonePolicy; /** #323: the run origin, kept on each model candidate. */ origin?: import("./candidate-origin.ts").CandidateOrigin }
|
|
15
16
|
export interface ModelConsolidationReport {
|
|
16
17
|
state: "disabled" | "known" | "unknown"; ids: string[]; calls: number; nonAnswers: number; rejected: number; oversized: number;
|
|
17
18
|
limited: boolean; timedOut: boolean; truncated: boolean;
|
|
@@ -33,8 +34,11 @@ async function invoke(model: ModelConsolidationOptions, input: ModelConsolidatio
|
|
|
33
34
|
export async function proposeModelConsolidations(store: MemoryStore, candidates: CandidateStore, rows: readonly View[], model: ModelConsolidationOptions | undefined, guard: ModelConsolidationGuard): Promise<ModelConsolidationReport> {
|
|
34
35
|
const report: ModelConsolidationReport = { state: model === undefined ? "disabled" : "known", ids: [], calls: 0, nonAnswers: 0, rejected: 0, oversized: 0, limited: false, timedOut: false, truncated: false };
|
|
35
36
|
if (model === undefined) return report;
|
|
36
|
-
if (guard.actor !== "person") throw Error("model consolidation requires person
|
|
37
|
+
if (guard.actor !== "person" && guard.actor !== "agent") throw Error("model consolidation requires a person or an agent-marked session");
|
|
37
38
|
try {
|
|
39
|
+
let originSnapshot: CandidateOrigin | undefined;
|
|
40
|
+
try { originSnapshot = validOrigin(memoryPolicySnapshot(guard.origin)); } catch { originSnapshot = undefined; }
|
|
41
|
+
if (originSnapshot) Object.freeze(originSnapshot);
|
|
38
42
|
if (!model || model.enabled !== true || typeof model.run !== "function" || !guard.project.trim() || guard.project.length > 400) throw Error("model consolidation unavailable");
|
|
39
43
|
guard.check();
|
|
40
44
|
if (realPath(candidates.dir) !== realPath(store.profile.home)) throw Error("model consolidation home mismatch");
|
|
@@ -42,7 +46,7 @@ export async function proposeModelConsolidations(store: MemoryStore, candidates:
|
|
|
42
46
|
const project = guard.project, sourceCurrent = store.beginRecallRead(), sources: ModelConsolidationNote[] = [], seen = new Set<string>();
|
|
43
47
|
const check = (batch: readonly ModelConsolidationNote[]) => {
|
|
44
48
|
guard.check(); sourceCurrent();
|
|
45
|
-
if (guard.
|
|
49
|
+
if (guard.project !== project) throw Error("model consolidation context changed");
|
|
46
50
|
const placements = batch.length ? store.entryPlacements(batch.map(row => row.id), project) : new Map<string, "local" | "synced">();
|
|
47
51
|
store.withDeferredPromotions(() => {
|
|
48
52
|
for (const row of batch) {
|
|
@@ -88,9 +92,11 @@ export async function proposeModelConsolidations(store: MemoryStore, candidates:
|
|
|
88
92
|
if (text.length > 3000) { report.oversized++; continue; }
|
|
89
93
|
const candidate: Extract<CandidateInput, { kind: "model-answer" }> = { project, kind: "model-answer", marker: "model-answer", targets: batch.map(row => ({ id: row.id, revision: row.revision })), text };
|
|
90
94
|
guard.check();
|
|
95
|
+
// #323 AC3: the run origin goes through the same full host screen as the candidate, with it; a declined origin is dropped.
|
|
96
|
+
const origin = originSnapshot && await guard.policy.screen({ project, candidate, origin: originSnapshot }) && guard.policy.screenStandalone({ project, candidate, origin: originSnapshot }) ? originSnapshot : undefined;
|
|
91
97
|
const permitted = await guard.policy.screen({ project, output: value, candidate }); check(batch);
|
|
92
98
|
if (!permitted) { report.rejected++; continue; }
|
|
93
|
-
report.ids.push(candidates.put(candidate, "public"));
|
|
99
|
+
report.ids.push(candidates.put(candidate, "public", origin && guard.policy.screenStandalone({ project, candidate, origin }) ? origin : undefined));
|
|
94
100
|
}
|
|
95
101
|
return report;
|
|
96
102
|
} catch { report.state = "unknown"; report.rejected++; return report; }
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readSync, renameSync, rmSync, writeFileSync, fsyncSync } from "node:fs";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { FORMAT_SURFACES, FORMATS_FILE, readFormatFloors, type FormatFloor } from "./formats.ts";
|
|
5
|
+
import { acquireMutation } from "./mutation.ts";
|
|
6
|
+
import { realPath } from "./platform.ts";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* #431 AC6: `amem formats raise <surface> <minReader> [--confirm]`. The preview names the exact record and every writer this home
|
|
10
|
+
* knows about; the raise appends that one record and refuses while any known writer is below `minReader`. A writer whose version
|
|
11
|
+
* cannot be read refuses too: an unproven writer is treated as below. Records are never rewritten or removed.
|
|
12
|
+
*/
|
|
13
|
+
const PLAIN = /^(\d+)\.(\d+)\.(\d+)$/;
|
|
14
|
+
const MAX_WRITERS = 256, PACKAGE_BYTES = 64 * 1024, MAX_ANCESTORS = 12;
|
|
15
|
+
export type FormatRaiseSurface = typeof FORMAT_SURFACES[number] | "home";
|
|
16
|
+
export interface FormatWriter { source: "setup" | "sync-placement" | "running" | "library-host" | "self"; root: string; version: string | null; pid?: number; host?: string }
|
|
17
|
+
export interface FormatWriterInventory { writers: FormatWriter[]; incomplete: string[] }
|
|
18
|
+
export interface FormatRaisePlan {
|
|
19
|
+
home: string; file: string; record: FormatFloor; writers: FormatWriter[]; below: FormatWriter[]; incomplete: string[];
|
|
20
|
+
existing: FormatFloor[]; alreadyAtLeast: boolean; ready: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const parts = (version: string) => PLAIN.exec(version)!.slice(1, 4).map(Number);
|
|
24
|
+
export function versionBelow(version: string, floor: string): boolean {
|
|
25
|
+
const a = parts(version), b = parts(floor);
|
|
26
|
+
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i]! < b[i]!;
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The version of an amem install root, or null when it is not a readable `@staix/agent-mem` package with a plain release version. */
|
|
31
|
+
export function installVersion(root: string): string | null {
|
|
32
|
+
let fd: number | undefined;
|
|
33
|
+
try {
|
|
34
|
+
fd = openSync(join(root, "package.json"), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
35
|
+
const stat = fstatSync(fd); if (!stat.isFile() || stat.size > PACKAGE_BYTES) return null;
|
|
36
|
+
const data = Buffer.alloc(stat.size); let at = 0;
|
|
37
|
+
while (at < data.length) { const n = readSync(fd, data, at, data.length - at, at); if (n <= 0) return null; at += n; }
|
|
38
|
+
const value = JSON.parse(data.toString("utf8")) as { name?: unknown; version?: unknown };
|
|
39
|
+
return value.name === "@staix/agent-mem" && typeof value.version === "string" && PLAIN.test(value.version) ? value.version : null;
|
|
40
|
+
} catch { return null; } finally { if (fd !== undefined) closeSync(fd); }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Install roots of running processes that load agent-mem: an amem CLI (`<root>/bin/amem.js` or `<root>/src/cli.ts`), or a host that embeds
|
|
45
|
+
* it as a library (ahub, vmem), found as `node_modules/@staix/agent-mem` in an ancestor of a script path on its command line. Bounded.
|
|
46
|
+
* `embedded(dir)` answers whether `dir/node_modules/@staix/agent-mem` exists; it defaults to the filesystem.
|
|
47
|
+
*/
|
|
48
|
+
export function runningAmemRoots(table: () => string, embedded: (dir: string) => boolean = dir => existsSync(join(dir, "node_modules", "@staix", "agent-mem", "package.json"))): { pid: number; root: string; host?: string }[] {
|
|
49
|
+
const out: { pid: number; root: string; host?: string }[] = [], memo = new Map<string, string | null>();
|
|
50
|
+
const library = (script: string): string | null => {
|
|
51
|
+
let dir = dirname(script);
|
|
52
|
+
for (let depth = 0; depth < MAX_ANCESTORS && dir !== dirname(dir); depth++, dir = dirname(dir)) {
|
|
53
|
+
if (memo.has(dir)) return memo.get(dir)!;
|
|
54
|
+
let found: string | null = null;
|
|
55
|
+
try { if (embedded(dir)) found = join(dir, "node_modules", "@staix", "agent-mem"); } catch { /* unreadable: look further up */ }
|
|
56
|
+
if (found) { memo.set(dir, found); return found; }
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
};
|
|
60
|
+
for (const line of table().split("\n")) {
|
|
61
|
+
const match = /^\s*(\d+)\s+(.*)$/.exec(line); if (!match) continue;
|
|
62
|
+
const pid = Number(match[1]); if (pid === process.pid) continue;
|
|
63
|
+
const tokens = match[2]!.split(/\s+/);
|
|
64
|
+
const cli = tokens.map(token => /^(\/.+)\/(?:bin\/amem\.js|src\/cli\.ts)$/.exec(token)).find(Boolean);
|
|
65
|
+
if (cli) out.push({ pid, root: cli[1]! });
|
|
66
|
+
else for (const token of tokens) {
|
|
67
|
+
if (!token.startsWith("/") || !/\.(?:[cm]?[jt]s)$/.test(token)) continue;
|
|
68
|
+
const root = library(token); if (!root) continue;
|
|
69
|
+
out.push({ pid, root, host: token }); break;
|
|
70
|
+
}
|
|
71
|
+
if (out.length >= MAX_WRITERS) break;
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function planFormatRaise(home: string, surface: string, minReader: string, inventory: FormatWriterInventory, now: () => Date = () => new Date()): FormatRaisePlan {
|
|
77
|
+
if (surface !== "home" && !(FORMAT_SURFACES as readonly string[]).includes(surface)) throw new Error(`unknown format surface ${surface}; use one of home, ${FORMAT_SURFACES.join(", ")}`);
|
|
78
|
+
if (!PLAIN.test(minReader)) throw new Error("minReader must be a plain release version such as 0.27.0");
|
|
79
|
+
const base = realPath(home), existing = readFormatFloors(base) ?? [];
|
|
80
|
+
const record: FormatFloor = { surface, minReader, since: now().toISOString().slice(0, 10) };
|
|
81
|
+
const below = inventory.writers.filter(writer => writer.version === null || versionBelow(writer.version, minReader));
|
|
82
|
+
const alreadyAtLeast = existing.some(floor => floor.surface === surface && PLAIN.test(floor.minReader) && !versionBelow(floor.minReader, minReader));
|
|
83
|
+
return { home: base, file: join(base, FORMATS_FILE), record, writers: inventory.writers, below, incomplete: inventory.incomplete, existing, alreadyAtLeast,
|
|
84
|
+
ready: !below.length && !inventory.incomplete.length && !alreadyAtLeast };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function formatRaiseRefusal(plan: FormatRaisePlan): string | undefined {
|
|
88
|
+
if (plan.alreadyAtLeast) return `formats.json already records a ${plan.record.surface} floor at or above ${plan.record.minReader}; nothing to raise`;
|
|
89
|
+
if (plan.incomplete.length) return `the writer inventory is incomplete (${plan.incomplete.join("; ")}); fix it before raising a floor`;
|
|
90
|
+
if (plan.below.length) return `writers below ${plan.record.minReader}: ${plan.below.map(writer => `${writer.source} ${writer.root}${writer.pid ? ` (pid ${writer.pid}${writer.host ? `, ${writer.host}` : ""})` : ""} at ${writer.version ?? "unknown version"}`).join("; ")}. Upgrade or stop them, then rerun`;
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Appends the planned record under the home's mutation fence after rechecking the floors and the inventory are unchanged. */
|
|
95
|
+
export function applyFormatRaise(plan: FormatRaisePlan, recheck: () => FormatRaisePlan): FormatFloor {
|
|
96
|
+
const refusal = formatRaiseRefusal(plan); if (refusal) throw new Error(refusal);
|
|
97
|
+
const release = acquireMutation(plan.home); if (!release) throw new Error("another memory writer holds this home; rerun when it finishes");
|
|
98
|
+
try {
|
|
99
|
+
const fresh = recheck();
|
|
100
|
+
if (JSON.stringify(fresh.existing) !== JSON.stringify(plan.existing) || JSON.stringify(fresh.writers) !== JSON.stringify(plan.writers)) throw new Error("formats.json or the writer inventory changed since the preview; rerun the preview");
|
|
101
|
+
const again = formatRaiseRefusal(fresh); if (again) throw new Error(again);
|
|
102
|
+
const stat = lstatSync(plan.file, { throwIfNoEntry: false });
|
|
103
|
+
if (stat && (stat.isSymbolicLink() || !stat.isFile())) throw new Error(`${plan.file} is not a regular file`);
|
|
104
|
+
const text = JSON.stringify([...plan.existing, plan.record], null, 2) + "\n", temporary = join(dirname(plan.file), `.${FORMATS_FILE}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
|
|
105
|
+
try {
|
|
106
|
+
writeFileSync(temporary, text, { mode: 0o600, flag: "wx" });
|
|
107
|
+
const fd = openSync(temporary, constants.O_RDONLY); try { fsyncSync(fd); } finally { closeSync(fd); }
|
|
108
|
+
renameSync(temporary, plan.file);
|
|
109
|
+
} catch (error) { rmSync(temporary, { force: true }); throw error; }
|
|
110
|
+
const read = readFormatFloors(plan.home) ?? [];
|
|
111
|
+
if (JSON.stringify(read.at(-1)) !== JSON.stringify(plan.record)) throw new Error("formats.json did not read back the appended record");
|
|
112
|
+
return plan.record;
|
|
113
|
+
} finally { release(); }
|
|
114
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/** Closed v2 publication append intent. The I/O layer owns fencing and durable prefix completion. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { types } from "node:util";
|
|
4
|
+
import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
5
|
+
import { PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, PLACEMENT_JOURNAL_MAX_OBJECTS, PLACEMENT_JOURNAL_MAX_RECORDS,
|
|
6
|
+
SyncPlacementJournalError, validatePlacementRecord, type PlacementRecord } from "./sync-placement-journal-format.ts";
|
|
7
|
+
|
|
8
|
+
// ponytail: 20 MiB holds the records under the existing 256-object/64 KiB journal ceiling plus metadata;
|
|
9
|
+
// replace this in-memory envelope with a bounded streaming manifest before increasing the journal ceiling.
|
|
10
|
+
export const PLACEMENT_BATCH_INTENT_MAX_BYTES = 20 * 1024 * 1024;
|
|
11
|
+
export interface PlacementBatchChunk { name: string; prefixBytes: number; prefixHash: string; first: number; count: number; suffixHash: string }
|
|
12
|
+
export interface PlacementBatchIntent {
|
|
13
|
+
schema: "agent-mem.sync-placement-append-intent/v2"; epochHash: string; attemptHash: string;
|
|
14
|
+
previousHash: string; records: PlacementRecord[]; chunks: PlacementBatchChunk[]; seal: string;
|
|
15
|
+
}
|
|
16
|
+
const digest = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
|
|
17
|
+
const bytesOf = (record: PlacementRecord) => Buffer.from(canonicalJSON(record) + "\n");
|
|
18
|
+
const hex = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
|
|
19
|
+
const object = (value: unknown, keys: string[]): Record<string, unknown> => {
|
|
20
|
+
if (!value || typeof value !== "object" || types.isProxy(value) || Array.isArray(value)) throw new SyncPlacementJournalError("corrupt");
|
|
21
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
22
|
+
if (Object.keys(descriptors).sort().join(",") !== [...keys].sort().join(",") || Object.values(descriptors).some(descriptor => !("value" in descriptor))) throw new SyncPlacementJournalError("corrupt");
|
|
23
|
+
return Object.fromEntries(Object.entries(descriptors).map(([key, descriptor]) => [key, descriptor.value]));
|
|
24
|
+
};
|
|
25
|
+
const fail = (): never => { throw new SyncPlacementJournalError("corrupt"); };
|
|
26
|
+
const array = (value: unknown, limit: number): unknown[] => {
|
|
27
|
+
if (!Array.isArray(value) || types.isProxy(value) || value.length < 1 || value.length > limit) return fail();
|
|
28
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
29
|
+
if (Object.keys(descriptors).length !== value.length + 1) return fail();
|
|
30
|
+
return Array.from({ length: value.length }, (_, index) => {
|
|
31
|
+
const descriptor = descriptors[String(index)];
|
|
32
|
+
if (!descriptor || !("value" in descriptor)) return fail();
|
|
33
|
+
return descriptor.value;
|
|
34
|
+
});
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** Validate an entire batch and its canonical record chain before any storage effect. */
|
|
38
|
+
export function validatePlacementBatchIntent(value: unknown, epochHash: string): PlacementBatchIntent {
|
|
39
|
+
const row = object(value, ["schema", "epochHash", "attemptHash", "previousHash", "records", "chunks", "seal"]);
|
|
40
|
+
if (row.schema !== "agent-mem.sync-placement-append-intent/v2" || row.epochHash !== epochHash || !hex(epochHash)
|
|
41
|
+
|| !hex(row.attemptHash) || !hex(row.previousHash) || !hex(row.seal)) return fail();
|
|
42
|
+
let recordBytes = 0;
|
|
43
|
+
const records = array(row.records, PLACEMENT_JOURNAL_MAX_RECORDS).map(value => {
|
|
44
|
+
const record = validatePlacementRecord(value);
|
|
45
|
+
recordBytes += bytesOf(record).length;
|
|
46
|
+
if (recordBytes > PLACEMENT_BATCH_INTENT_MAX_BYTES) return fail();
|
|
47
|
+
return record;
|
|
48
|
+
});
|
|
49
|
+
let head = row.previousHash, sequence = records[0]!.sequence - 1;
|
|
50
|
+
for (const record of records) {
|
|
51
|
+
if (record.epochHash !== epochHash || record.previousHash !== head || record.sequence !== ++sequence) return fail();
|
|
52
|
+
head = record.seal;
|
|
53
|
+
}
|
|
54
|
+
let first = 0, previousIndex = -1;
|
|
55
|
+
const chunks = array(row.chunks, PLACEMENT_JOURNAL_MAX_OBJECTS).map(value => {
|
|
56
|
+
const chunk = object(value, ["name", "prefixBytes", "prefixHash", "first", "count", "suffixHash"]);
|
|
57
|
+
if (typeof chunk.name !== "string" || !/^records-\d{5}\.jsonl$/.test(chunk.name)
|
|
58
|
+
|| !Number.isSafeInteger(chunk.prefixBytes) || (chunk.prefixBytes as number) < 0 || !hex(chunk.prefixHash)
|
|
59
|
+
|| !Number.isSafeInteger(chunk.first) || chunk.first !== first || !Number.isSafeInteger(chunk.count)
|
|
60
|
+
|| (chunk.count as number) < 1 || !hex(chunk.suffixHash)) return fail();
|
|
61
|
+
const index = Number(chunk.name.slice(8, 13)), count = chunk.count as number;
|
|
62
|
+
if ((previousIndex >= 0 && index !== previousIndex + 1) || first + count > records.length
|
|
63
|
+
|| (first > 0 && (chunk.prefixBytes !== 0 || chunk.prefixHash !== digest(Buffer.alloc(0))))) return fail();
|
|
64
|
+
const suffix = Buffer.concat(records.slice(first, first + count).map(bytesOf));
|
|
65
|
+
if ((chunk.prefixBytes as number) + suffix.length > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES || digest(suffix) !== chunk.suffixHash) return fail();
|
|
66
|
+
const result: PlacementBatchChunk = { name: chunk.name, prefixBytes: chunk.prefixBytes as number, prefixHash: chunk.prefixHash, first, count, suffixHash: chunk.suffixHash };
|
|
67
|
+
first += count; previousIndex = index; return result;
|
|
68
|
+
});
|
|
69
|
+
if (first !== records.length) return fail();
|
|
70
|
+
const body = { schema: "agent-mem.sync-placement-append-intent/v2" as const, epochHash, attemptHash: row.attemptHash, previousHash: row.previousHash, records, chunks };
|
|
71
|
+
if (hashJSON(body) !== row.seal || Buffer.byteLength(canonicalJSON({ ...body, seal: row.seal }) + "\n") > PLACEMENT_BATCH_INTENT_MAX_BYTES) return fail();
|
|
72
|
+
return { ...body, seal: row.seal };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Lay out the frozen record sequence across existing or new journal chunks without reading or writing files. */
|
|
76
|
+
export function planPlacementBatchIntent(epochHash: string, attemptHash: string, records: readonly PlacementRecord[],
|
|
77
|
+
existing: readonly { name: string; size: number; hash: string }[]): PlacementBatchIntent {
|
|
78
|
+
if (!records.length || !hex(epochHash) || !hex(attemptHash)) return fail();
|
|
79
|
+
const chunks: PlacementBatchChunk[] = [], empty = digest(Buffer.alloc(0));
|
|
80
|
+
let used = existing.at(-1)?.size ?? 0, index = existing.length ? existing.length - 1 : 0;
|
|
81
|
+
let prefixBytes = existing.at(-1)?.size ?? 0, prefixHash = existing.at(-1)?.hash ?? empty;
|
|
82
|
+
let first = 0, count = 0, suffix: Buffer[] = [];
|
|
83
|
+
const flush = () => {
|
|
84
|
+
if (!count) return;
|
|
85
|
+
chunks.push({ name: `records-${String(index).padStart(5, "0")}.jsonl`, prefixBytes, prefixHash, first, count, suffixHash: digest(Buffer.concat(suffix)) });
|
|
86
|
+
first += count; count = 0; suffix = []; index++; used = 0; prefixBytes = 0; prefixHash = empty;
|
|
87
|
+
};
|
|
88
|
+
for (const record of records) {
|
|
89
|
+
const data = bytesOf(validatePlacementRecord(record));
|
|
90
|
+
if (data.length > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) return fail();
|
|
91
|
+
if (used + data.length > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) {
|
|
92
|
+
if (count) flush(); else { index++; used = 0; prefixBytes = 0; prefixHash = empty; }
|
|
93
|
+
}
|
|
94
|
+
used += data.length; count++; suffix.push(data);
|
|
95
|
+
}
|
|
96
|
+
flush();
|
|
97
|
+
const body = { schema: "agent-mem.sync-placement-append-intent/v2" as const, epochHash, attemptHash,
|
|
98
|
+
previousHash: records[0]!.previousHash, records: [...records], chunks };
|
|
99
|
+
return validatePlacementBatchIntent({ ...body, seal: hashJSON(body) }, epochHash);
|
|
100
|
+
}
|