@staix/agent-mem 0.23.1 → 0.25.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 +28 -12
- package/package.json +1 -1
- package/src/brief-cache.ts +60 -0
- package/src/brief-capture.ts +82 -0
- package/src/brief-curated-native.ts +52 -0
- package/src/brief-curated.ts +118 -0
- package/src/cli.ts +8 -2
- package/src/curated-brief-cache.ts +29 -0
- package/src/hook-contract.ts +22 -2
- package/src/hook-jcode-journal.ts +46 -4
- package/src/hook-record.ts +40 -2
- package/src/hook-spool-replay.ts +8 -1
- package/src/hook-spool.ts +25 -14
- package/src/hook-transcript.ts +10 -2
- package/src/hooks.ts +68 -17
- package/src/index.ts +6 -1
- package/src/ingest-records.ts +113 -0
- package/src/ingest.ts +106 -9
- package/src/mcp-memory.ts +2 -2
- package/src/mcp.ts +1 -1
- package/src/memory/candidate-pending.ts +6 -2
- package/src/memory/candidates.ts +60 -7
- package/src/memory/capture-input.ts +7 -0
- package/src/memory/capture-plan.ts +10 -0
- package/src/memory/capture.ts +98 -8
- package/src/memory/consolidate.ts +35 -1
- package/src/memory/curated-cache-state.ts +36 -0
- package/src/memory/decay-review.ts +3 -1
- package/src/memory/formats.ts +20 -0
- package/src/memory/generation-index.ts +2 -0
- package/src/memory/generation-sync.ts +3 -0
- package/src/memory/index-file.ts +1 -1
- package/src/memory/intent-brief.ts +42 -4
- package/src/memory/metrics.ts +10 -4
- package/src/memory/migrate.ts +7 -1
- package/src/memory/note-add.ts +2 -0
- package/src/memory/ops-contract.ts +1 -1
- package/src/memory/preference-brief.ts +22 -0
- package/src/memory/public-prune-activation.ts +4 -1
- package/src/memory/public-prune-advance.ts +2 -0
- package/src/memory/reader-lease.ts +5 -3
- package/src/memory/recall.ts +4 -1
- package/src/memory/record-candidates.ts +179 -0
- package/src/memory/record-instruction.ts +26 -0
- package/src/memory/record-variant-log.ts +90 -0
- package/src/memory/search-fts.ts +3 -0
- package/src/memory/shard-migration.ts +4 -1
- package/src/memory/shard-sync.ts +3 -0
- package/src/memory/store.ts +184 -4
- package/src/memory/sync-placement-activation.ts +11 -3
- package/src/memory/sync-placement-transport.ts +3 -0
- package/src/memory/sync.ts +3 -2
- package/src/session-brief-worker.ts +13 -2
- package/src/session-brief.ts +150 -70
- package/src/ui/plugin.ts +104 -30
- package/src/ui/snapshot-cache.ts +141 -0
- package/src/ui/snapshot-revision.ts +87 -0
package/src/memory/candidates.ts
CHANGED
|
@@ -27,10 +27,19 @@ export class ConsolidationReviewLimit extends Error {
|
|
|
27
27
|
export const COUNTER_RETENTION = { count: 10_000, ageMs: 90 * 86400_000 } as const;
|
|
28
28
|
export type CandidateVerdict = "public" | "private" | "pii" | "unknown";
|
|
29
29
|
export interface CandidateTarget { id: string; revision: string }
|
|
30
|
+
/** One capture `Record` row a candidate was derived from: the session hash, its row time and the hash of the stored line. */
|
|
31
|
+
export interface RecordSource { session: string; at: string; textHash: string }
|
|
32
|
+
/**
|
|
33
|
+
* #368 binds a Record-derived candidate to the capture rows it quotes, so acceptance can prove they are still present and
|
|
34
|
+
* unchanged. `key` is the grouping identity (kind plus anchors, or kind plus text when the Record carries no anchor), so a
|
|
35
|
+
* later `amem consolidate` over the same sources does not queue the same lesson twice.
|
|
36
|
+
*/
|
|
37
|
+
export interface RecordSourceBinding { key: string; anchors: string[]; sources: RecordSource[] }
|
|
30
38
|
export type CandidateInput = { project: string } & (
|
|
31
39
|
| { kind: "correction"; target: CandidateTarget; proposedText: string; reason: string; noteKind?: "decision" | "contract" | "fail" }
|
|
32
|
-
|
|
33
|
-
| { kind: "
|
|
40
|
+
/** `about` is the deterministic edge set a proposer already knows (the anchors a Record names), so acceptance needs no re-extraction. */
|
|
41
|
+
| { kind: "fail"; target?: CandidateTarget; approach: string; symptom: string; cause: string; evidenceRefs: string[]; retryWhen: string; about?: string[]; record?: RecordSourceBinding }
|
|
42
|
+
| { kind: "memory"; text: string; title?: string; noteKind?: "decision" | "finding" | "contract" | "fail" | "preference"; about?: string[]; record?: RecordSourceBinding }
|
|
34
43
|
| { kind: "decay"; target: CandidateTarget; reason: string }
|
|
35
44
|
| { kind: "promotion"; target: CandidateTarget; goalId: string }
|
|
36
45
|
| { kind: "consolidation"; action: "merge" | "supersession" | "recurring-fix"; targets: CandidateTarget[]; text: string; about: string[]; noteKind: "decision" | "finding" | "contract" | "fail" }
|
|
@@ -53,6 +62,11 @@ export interface CandidateAcceptance {
|
|
|
53
62
|
policy: (candidate: Candidate, target: View | undefined, note: NoteInput, goal?: GoalView) => boolean;
|
|
54
63
|
/** Required for multi-source consolidation; must change with the effective host policy. */
|
|
55
64
|
policyVersion?: () => string;
|
|
65
|
+
/**
|
|
66
|
+
* #368: rechecks the capture rows a Record-derived candidate quotes, at acceptance time. Absent means the host cannot
|
|
67
|
+
* prove the source, and accepting such a candidate refuses instead of writing memory from a row nobody verified.
|
|
68
|
+
*/
|
|
69
|
+
recordSource?: (project: string, binding: RecordSourceBinding) => "present" | "changed" | "missing";
|
|
56
70
|
}
|
|
57
71
|
export interface CandidateAcceptanceResult { candidateId: string; noteId: string; alreadyAccepted: boolean }
|
|
58
72
|
|
|
@@ -69,14 +83,37 @@ const publicOnly = (verdict: CandidateVerdict) => { if (verdict !== "public") th
|
|
|
69
83
|
const validActor = (actor: string) => { if (actor !== "person" && actor !== "agent") throw new Error("candidate actor must be person or agent"); };
|
|
70
84
|
const attributionPeer = (actor: "person" | "agent") => cliAttribution()?.peer ?? actor;
|
|
71
85
|
const validTarget = (value: CandidateTarget | undefined) => value !== undefined && entryId(value.id) && candidateId(value.revision);
|
|
86
|
+
const SOURCE_HASH = /^[a-f0-9]{64}$/, SESSION_HASH = /^[a-f0-9]{16}$/;
|
|
87
|
+
/** A Record binding names its own rows: session hash, exact row time and stored-line hash, keyed by the grouping identity. */
|
|
88
|
+
function validRecord(value: RecordSourceBinding | undefined): value is RecordSourceBinding {
|
|
89
|
+
return value !== undefined && SOURCE_HASH.test(value.key) && Array.isArray(value.sources) && value.sources.length >= 1 && value.sources.length <= 8
|
|
90
|
+
&& value.sources.every(source => SESSION_HASH.test(source.session) && typeof source.at === "string" && !Number.isNaN(Date.parse(source.at)) && SOURCE_HASH.test(source.textHash))
|
|
91
|
+
// One turn may emit two Records, so a source is identified by its text as well as its session and time.
|
|
92
|
+
&& new Set(value.sources.map(source => `${source.session}\n${source.at}\n${source.textHash}`)).size === value.sources.length
|
|
93
|
+
&& Array.isArray(value.anchors) && value.anchors.length <= 32 && value.anchors.every(anchor => text(anchor, 400));
|
|
94
|
+
}
|
|
95
|
+
/** Path and symbol edges of a Record candidate, kept to the same node bound as a consolidation proposal. */
|
|
96
|
+
const validAbout = (value: unknown) => value === undefined
|
|
97
|
+
|| Array.isArray(value) && value.length <= 32 && value.every(node => text(node, 400));
|
|
98
|
+
/**
|
|
99
|
+
* A Record-derived fail candidate leaves approach and cause for the reviewer: the grammar records one `<symptom/cause>`
|
|
100
|
+
* group and one `<fix/retry-when>` group, so the row fills the symptom and the retry condition, while the approach and a
|
|
101
|
+
* cause stated separately have no source. Only a candidate carrying the binding may leave those two empty.
|
|
102
|
+
*/
|
|
103
|
+
const recordFailField = (key: "approach" | "symptom" | "cause" | "retryWhen", value: unknown, record: RecordSourceBinding | undefined) =>
|
|
104
|
+
(key === "approach" || key === "cause") && record !== undefined ? (value === "" || text(value)) : text(value);
|
|
72
105
|
function validate(input: CandidateInput): void {
|
|
73
106
|
if (!input || !text(input.project, 400)) throw new Error("invalid candidate project");
|
|
74
107
|
if (input.kind === "correction") {
|
|
75
108
|
if (!validTarget(input.target) || !text(input.proposedText) || !text(input.reason) || input.noteKind !== undefined && !["decision", "contract", "fail"].includes(input.noteKind)) throw new Error("invalid correction candidate");
|
|
76
109
|
} else if (input.kind === "fail") {
|
|
77
|
-
if (input.target !== undefined && !validTarget(input.target) ||
|
|
110
|
+
if (input.target !== undefined && !validTarget(input.target) || input.record !== undefined && !validRecord(input.record) || !validAbout(input.about)
|
|
111
|
+
|| !recordFailField("approach", input.approach, input.record) || !recordFailField("symptom", input.symptom, input.record)
|
|
112
|
+
|| !recordFailField("cause", input.cause, input.record) || !recordFailField("retryWhen", input.retryWhen, input.record)
|
|
113
|
+
|| !Array.isArray(input.evidenceRefs) || input.evidenceRefs.length < 1 || input.evidenceRefs.length > 16 || !input.evidenceRefs.every(x => text(x, 400))) throw new Error("invalid fail candidate");
|
|
78
114
|
} else if (input.kind === "memory") {
|
|
79
|
-
if (!text(input.text, 3000) || input.title !== undefined && !text(input.title, 200) || input.noteKind !== undefined && !["decision", "finding", "contract", "fail"].includes(input.noteKind)
|
|
115
|
+
if (!text(input.text, 3000) || input.title !== undefined && !text(input.title, 200) || input.noteKind !== undefined && !["decision", "finding", "contract", "fail", "preference"].includes(input.noteKind)
|
|
116
|
+
|| input.record !== undefined && !validRecord(input.record) || !validAbout(input.about)) throw new Error("invalid memory candidate");
|
|
80
117
|
} else if (input.kind === "promotion") {
|
|
81
118
|
if (!validTarget(input.target) || !entryId(input.goalId)) throw new Error("invalid promotion candidate");
|
|
82
119
|
} else if (input.kind === "consolidation") {
|
|
@@ -219,7 +256,8 @@ export class CandidateStore {
|
|
|
219
256
|
this.path = join(this.dir, "candidates.db");
|
|
220
257
|
this.db = new Database(this.path, { create: true });
|
|
221
258
|
this.db.run(`PRAGMA busy_timeout = ${CANDIDATE_DB_BUSY_TIMEOUT_MS}`);
|
|
222
|
-
|
|
259
|
+
// A warm read must not manufacture a revision; every extra permission bit still gets stripped.
|
|
260
|
+
if ((lstatSync(this.path).mode & 0o7777) !== 0o600) chmodSync(this.path, 0o600);
|
|
223
261
|
// `journal_mode = WAL` takes a lock that busy_timeout does not always wait for, so several processes opening a brand-new home at once (every `amem mcp` builds this store at
|
|
224
262
|
// startup) can see "database is locked". It is retried for a bounded time: the first caller switches the mode, the others then find it already WAL.
|
|
225
263
|
retryLocked(() => this.db.run("PRAGMA journal_mode = WAL"));
|
|
@@ -242,7 +280,8 @@ export class CandidateStore {
|
|
|
242
280
|
if (overflow) throw new ConsolidationReviewLimit(overflow.project, overflow.n);
|
|
243
281
|
this.db.run(`INSERT INTO consolidation_reviews (id, project, status, note_id)
|
|
244
282
|
SELECT id, project, status, note_id FROM candidates WHERE kind = 'consolidation' AND status IN ('accepting', 'accepted', 'rejected')
|
|
245
|
-
ON CONFLICT(id) DO UPDATE SET status = excluded.status, note_id = excluded.note_id
|
|
283
|
+
ON CONFLICT(id) DO UPDATE SET status = excluded.status, note_id = excluded.note_id
|
|
284
|
+
WHERE consolidation_reviews.status IS NOT excluded.status OR consolidation_reviews.note_id IS NOT excluded.note_id`);
|
|
246
285
|
}
|
|
247
286
|
private prune(): void {
|
|
248
287
|
this.db.transaction(() => {
|
|
@@ -382,6 +421,16 @@ export class CandidateStore {
|
|
|
382
421
|
if (data.kind === "decay") throw new Error("decay candidates are listing-only; no automatic mutation is available");
|
|
383
422
|
if (data.kind === "promotion") return this.acceptPromotion(candidate, data, context);
|
|
384
423
|
if (data.kind === "consolidation") return this.acceptConsolidation(candidate, data, context);
|
|
424
|
+
// #368: a Record-derived candidate quotes capture rows. Absent proof, or a row that moved since the queue, refuses
|
|
425
|
+
// before anything is written, and the message names the one command that queues a candidate over the current rows.
|
|
426
|
+
const sources = (data.kind === "memory" || data.kind === "fail") ? data.record : undefined;
|
|
427
|
+
const recheckSources = () => {
|
|
428
|
+
if (sources === undefined) return;
|
|
429
|
+
if (typeof context.recordSource !== "function") throw new Error("record source check unavailable; this host cannot verify the capture row this candidate quotes");
|
|
430
|
+
const verdict = context.recordSource(context.project, sources);
|
|
431
|
+
if (verdict === "missing") throw new Error(`record source row is missing (${sources.sources.length} cited, pruned or forgotten from capture); reject this candidate, or rerun \`amem consolidate\` once the transcript has been ingested again`);
|
|
432
|
+
if (verdict === "changed") throw new Error("record source row changed since this candidate was queued; rerun `amem consolidate` to queue a candidate over the current rows");
|
|
433
|
+
};
|
|
385
434
|
const execute = () => {
|
|
386
435
|
const resolve = () => {
|
|
387
436
|
const target = data.kind === "memory" ? undefined : data.target;
|
|
@@ -391,18 +440,22 @@ export class CandidateStore {
|
|
|
391
440
|
return current;
|
|
392
441
|
};
|
|
393
442
|
const target = resolve();
|
|
443
|
+
recheckSources();
|
|
394
444
|
const body = data.kind === "memory" ? data.text : data.kind === "correction" ? `${data.proposedText}\n\nReason: ${data.reason}`
|
|
395
445
|
: `Approach: ${oneLine(data.approach)}\nSymptom: ${oneLine(data.symptom)}\nCause: ${oneLine(data.cause)}\nEvidence: ${data.evidenceRefs.map(oneLine).join(", ")}\nRetry when: ${oneLine(data.retryWhen)}`;
|
|
396
446
|
const note: NoteInput = { op: "note", ...(data.kind === "memory" && data.title ? { title: data.title } : {}), project: data.kind === "correction" ? target!.project : context.project,
|
|
397
447
|
scope: data.kind === "correction" ? target!.scope : "project",
|
|
398
448
|
// A demoted synced target is logically short, but replacing it locally would narrow its reach (X04).
|
|
399
449
|
tier: data.kind === "correction" && target!.local ? "short" : "long",
|
|
400
|
-
kind: data.kind === "fail" ? "fail" : data.noteKind ?? (target?.kind === "contract" || target?.kind === "fail" ? target.kind : "decision"), peer: attributionPeer(context.actor), source: "person",
|
|
450
|
+
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
|
+
// 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 ?? [] : [])])],
|
|
401
453
|
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}` };
|
|
402
454
|
if (note.text.length > 4000) throw new Error("accepted candidate text exceeds the v1 note limit");
|
|
403
455
|
if (context.policy(structuredClone(candidate), target && structuredClone(target), structuredClone(note)) !== true) throw new Error("candidate refused by current host policy");
|
|
404
456
|
return context.store.withAcceptedNote(note, append => {
|
|
405
457
|
resolve(); // Recheck under the same mutation lock as the note and supersede appends.
|
|
458
|
+
recheckSources();
|
|
406
459
|
const started = this.beginAcceptance(id, context.project);
|
|
407
460
|
if (started) return { candidateId: id, noteId: started, alreadyAccepted: true };
|
|
408
461
|
// ponytail: the sidecar receipt and v1 append are not one transaction. An interrupted 'accepting' row refuses
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
1
2
|
import { looksSecret } from "./screen.ts";
|
|
2
3
|
import { isDenied } from "./platform.ts";
|
|
3
4
|
import { stripPrivateSpans } from "./private-spans.ts";
|
|
@@ -20,6 +21,12 @@ const ROW_OVERHEAD_BYTES = 96;
|
|
|
20
21
|
/** The session key is a fixed-width hash prefix, so it adds a bounded amount covered by the row overhead. */
|
|
21
22
|
export const SESSION_KEY = /^[a-f0-9]{16}$/;
|
|
22
23
|
|
|
24
|
+
/** Existing capture attribution hash; never persist the raw native session id. */
|
|
25
|
+
export function captureSessionKey(raw: unknown): string | undefined {
|
|
26
|
+
return typeof raw === "string" && raw.length > 0 && raw.length <= 256
|
|
27
|
+
? createHash("sha256").update(`amem-session\0${raw}`).digest("hex").slice(0, 16) : undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
23
30
|
export interface CaptureFields {
|
|
24
31
|
agent: string; event: string;
|
|
25
32
|
tool?: string; paths?: string[]; status?: string; excerpt?: string;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #331: true when an `EXPLAIN QUERY PLAN` result is the bounded `Record` seek `countOutsideRecent` requires, meaning the
|
|
3
|
+
* derived index is searched with the project and an upper `at` bound, with no table scan and no temporary sort.
|
|
4
|
+
* It lives outside `capture.ts` only so `src/index.ts`'s capture re-export does not carry it; the store method and its
|
|
5
|
+
* result type stay the root surface. Its own test covers a bundled SQLite that renders the seek differently.
|
|
6
|
+
*/
|
|
7
|
+
export function outsideCountPlanIsBounded(plan: readonly { detail: string }[]): boolean {
|
|
8
|
+
return plan.some(row => /^SEARCH rows USING INDEX rows_brief_records_v1 \(project=\?[^)]*at<\?/.test(row.detail))
|
|
9
|
+
&& !plan.some(row => /^SCAN rows\b/.test(row.detail) || row.detail.includes("TEMP B-TREE"));
|
|
10
|
+
}
|
package/src/memory/capture.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
+
import { invalidateBriefCache } from "../brief-cache.ts";
|
|
1
2
|
import { assertFormatFloor } from "./formats.ts";
|
|
2
3
|
import { Database } from "bun:sqlite";
|
|
3
4
|
import { createHash, randomBytes } from "node:crypto";
|
|
4
5
|
import { chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, opendirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
6
|
import { join } from "node:path";
|
|
6
7
|
import { looksSecret } from "./screen.ts";
|
|
8
|
+
import { outsideCountPlanIsBounded } from "./capture-plan.ts";
|
|
7
9
|
import { captureAttribution, normalizeCaptureFields, RecordNormalizationRefusal, SESSION_KEY, type CaptureFields } from "./capture-input.ts";
|
|
8
10
|
export { CAPTURE_MAX_EXCERPT, CAPTURE_MAX_PATHS } from "./capture-input.ts";
|
|
9
11
|
import { memoryBase } from "./home.ts";
|
|
@@ -98,6 +100,15 @@ export interface CaptureOptions {
|
|
|
98
100
|
*/
|
|
99
101
|
lifecycle?: "enforce" | "ignore";
|
|
100
102
|
}
|
|
103
|
+
/** A bounded, index-only answer to an event count outside the retained recent window (#331). */
|
|
104
|
+
export interface CaptureOutsideCount {
|
|
105
|
+
/** Matching rows outside the window, at most the store's window bound. */
|
|
106
|
+
rows: number;
|
|
107
|
+
/** True when the true count is at least one more than `rows` reports. */
|
|
108
|
+
capped: boolean;
|
|
109
|
+
/** False when nothing could answer this event safely: no derived index, or a plan that is not the bounded seek. */
|
|
110
|
+
available: boolean;
|
|
111
|
+
}
|
|
101
112
|
export interface CaptureAppendOptions {
|
|
102
113
|
/** Opaque stable source receipt for deterministic transcript replay. Requires an explicit source timestamp. */
|
|
103
114
|
receipt?: string;
|
|
@@ -184,6 +195,8 @@ const toRow = (r: RawRow): CaptureRow => ({ id: r.id, at: r.at, project: r.proje
|
|
|
184
195
|
|
|
185
196
|
export class CaptureStore {
|
|
186
197
|
readonly dir: string;
|
|
198
|
+
/** Highest Record or summary row committed by this instance, including capture-spool replay; no cache I/O in the store. */
|
|
199
|
+
briefCommitId = 0;
|
|
187
200
|
/** The canonical project key of this shard (aliases resolved). */
|
|
188
201
|
readonly key: string;
|
|
189
202
|
/** Rows the pre-T1 machine-wide capture store handed this shard on open. */
|
|
@@ -200,6 +213,10 @@ export class CaptureStore {
|
|
|
200
213
|
private contended = false;
|
|
201
214
|
private readonly readOnly: boolean;
|
|
202
215
|
private recentReadIds?: number[];
|
|
216
|
+
/** The oldest retained (at,id) pair: every row below it is outside the recent window. */
|
|
217
|
+
private recentBoundary?: { at: string; id: number };
|
|
218
|
+
/** The host's own window bound, reused as the outside count's cost bound. */
|
|
219
|
+
private maxRecentReadRows = 0;
|
|
203
220
|
/** True when the optional recent snapshot excludes older capture rows. */
|
|
204
221
|
readonly recentReadTruncated: boolean = false;
|
|
205
222
|
|
|
@@ -261,13 +278,17 @@ export class CaptureStore {
|
|
|
261
278
|
db.run(`PRAGMA busy_timeout = ${timeout}`); db.run("PRAGMA cache_size = -2048"); db.run("PRAGMA mmap_size = 0");
|
|
262
279
|
db.run("BEGIN");
|
|
263
280
|
if (opts.recentReadRows) {
|
|
264
|
-
// The existing rows_at index supplies the reverse time/id walk; retain ids only.
|
|
281
|
+
// The existing rows_at index supplies the reverse time/id walk; retain ids and the oldest retained pair only.
|
|
265
282
|
// One sentinel records excluded history without counting or loading its bodies.
|
|
266
|
-
const sql = "SELECT id FROM rows INDEXED BY rows_at ORDER BY at DESC, id DESC LIMIT ?";
|
|
283
|
+
const sql = "SELECT id, at FROM rows INDEXED BY rows_at ORDER BY at DESC, id DESC LIMIT ?";
|
|
267
284
|
const plan = db.query(`EXPLAIN QUERY PLAN ${sql}`).all(maxReadRows + 1) as { detail: string }[];
|
|
268
285
|
if (plan.some(row => row.detail.includes("TEMP B-TREE"))) throw new Error("capture recent index unavailable");
|
|
269
|
-
const recent = db.query(sql).all(maxReadRows + 1) as { id: number }[];
|
|
270
|
-
|
|
286
|
+
const recent = db.query(sql).all(maxReadRows + 1) as { id: number; at: string }[];
|
|
287
|
+
const retained = recent.slice(0, maxReadRows);
|
|
288
|
+
this.recentReadIds = retained.map(row => row.id);
|
|
289
|
+
const boundary = retained.at(-1);
|
|
290
|
+
if (boundary) this.recentBoundary = { at: boundary.at, id: boundary.id };
|
|
291
|
+
this.maxRecentReadRows = maxReadRows;
|
|
271
292
|
this.recentReadTruncated = recent.length > maxReadRows;
|
|
272
293
|
} else {
|
|
273
294
|
const count = (db.query("SELECT COUNT(*) AS n FROM (SELECT 1 FROM rows LIMIT ?)").get(maxReadRows + 1) as { n: number }).n;
|
|
@@ -280,7 +301,7 @@ export class CaptureStore {
|
|
|
280
301
|
}
|
|
281
302
|
const db = new Database(file, { create: true });
|
|
282
303
|
this.db = db;
|
|
283
|
-
try { chmodSync(file, 0o600); } catch { /* best effort */ }
|
|
304
|
+
try { if ((lstatSync(file).mode & 0o7777) !== 0o600) chmodSync(file, 0o600); } catch { /* best effort */ }
|
|
284
305
|
try {
|
|
285
306
|
db.run(`PRAGMA busy_timeout = ${opts.busyTimeoutMs ?? CAPTURE_BUSY_TIMEOUT_MS}`);
|
|
286
307
|
db.run("PRAGMA journal_mode = WAL");
|
|
@@ -460,6 +481,7 @@ export class CaptureStore {
|
|
|
460
481
|
if (!prior) throw new Error("capture receipt lookup failed");
|
|
461
482
|
return { id: prior.id, already: true };
|
|
462
483
|
}).immediate();
|
|
484
|
+
if ("id" in result && (row.event === "Record" || row.event === "Recap" || row.event === "Compact")) this.briefCommitId = Math.max(this.briefCommitId, result.id);
|
|
463
485
|
try { this.evict(); } catch (error) {
|
|
464
486
|
if (!lockError(error)) throw error; // the row is already committed; a locked eviction simply resumes on a later append
|
|
465
487
|
}
|
|
@@ -558,6 +580,7 @@ export class CaptureStore {
|
|
|
558
580
|
else if (line) batch.push(line);
|
|
559
581
|
}
|
|
560
582
|
try {
|
|
583
|
+
let summaryThrough = 0;
|
|
561
584
|
this.db.transaction(() => {
|
|
562
585
|
for (const line of batch) {
|
|
563
586
|
let raw: Partial<NormalizedCapture> & { bytes?: number };
|
|
@@ -569,10 +592,14 @@ export class CaptureStore {
|
|
|
569
592
|
candidate = typeof raw.bytes === "number" && typeof raw.excerpt === "string" ? raw as NormalizedCapture : this.normalize(raw as CaptureInput);
|
|
570
593
|
} catch { skipped++; continue; }
|
|
571
594
|
if (!validRow(candidate)) { skipped++; continue; }
|
|
572
|
-
const
|
|
573
|
-
if (
|
|
595
|
+
const id = this.insertRow(candidate, createHash("sha256").update(line).digest("hex"));
|
|
596
|
+
if (id !== undefined) {
|
|
597
|
+
drained++;
|
|
598
|
+
if (candidate.event === "Record" || candidate.event === "Recap" || candidate.event === "Compact") summaryThrough = Math.max(summaryThrough, id);
|
|
599
|
+
}
|
|
574
600
|
}
|
|
575
601
|
}).immediate();
|
|
602
|
+
this.briefCommitId = Math.max(this.briefCommitId, summaryThrough);
|
|
576
603
|
} catch (error) {
|
|
577
604
|
if (!lockError(error)) throw error;
|
|
578
605
|
break; // still contended: the spool stays for the next invocation
|
|
@@ -597,6 +624,7 @@ export class CaptureStore {
|
|
|
597
624
|
const id = Number(this.db.query("INSERT INTO rows (at, project, agent, event, tool, paths, status, excerpt, bytes, spool_id, session, subagent) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
|
|
598
625
|
.run(row.at, row.project, row.agent, row.event, row.tool, JSON.stringify(row.paths), row.status, row.excerpt, row.bytes, spoolId, row.session ?? null, row.subagent ? 1 : null).lastInsertRowid);
|
|
599
626
|
this.addBytes(row.bytes);
|
|
627
|
+
if (row.event === "Record" || row.event === "Recap" || row.event === "Compact") invalidateBriefCache({ directory: this.dir, project: this.key, section: "capture" });
|
|
600
628
|
return id;
|
|
601
629
|
} catch (error) {
|
|
602
630
|
if (String((error as Error)?.message ?? "").includes("UNIQUE")) return undefined; // a racing drain won this line
|
|
@@ -628,12 +656,15 @@ export class CaptureStore {
|
|
|
628
656
|
private evictWhere(where: string, bind: string[], start: number): { rows: number; bytes: number } {
|
|
629
657
|
let rows = 0, bytes = 0;
|
|
630
658
|
for (let batch = 0; batch < CAPTURE_EVICT_MAX_BATCHES && performance.now() - start < CAPTURE_EVICT_MAX_MS; batch++) {
|
|
631
|
-
const old = this.db.query(`SELECT id, bytes FROM rows WHERE ${where} ORDER BY at, id LIMIT ?`).all(...bind, CAPTURE_EVICT_BATCH_ROWS) as { id: number; bytes: number }[];
|
|
659
|
+
const old = this.db.query(`SELECT id, bytes, event FROM rows WHERE ${where} ORDER BY at, id LIMIT ?`).all(...bind, CAPTURE_EVICT_BATCH_ROWS) as { id: number; bytes: number; event: string }[];
|
|
632
660
|
if (!old.length) break;
|
|
633
661
|
const removedBytes = old.reduce((sum, r) => sum + r.bytes, 0);
|
|
634
662
|
// Deleting rows and adjusting the running size is atomic too; a lock cannot leave a permanently stale counter.
|
|
635
663
|
this.db.transaction(() => {
|
|
636
664
|
for (const { id } of old) this.db.query("DELETE FROM rows WHERE id = ?").run(id);
|
|
665
|
+
if (old.some(row => row.event === "Record" || row.event === "Recap" || row.event === "Compact")) {
|
|
666
|
+
invalidateBriefCache({ directory: this.dir, project: this.key, section: "capture" });
|
|
667
|
+
}
|
|
637
668
|
if (removedBytes) this.addBytes(-removedBytes);
|
|
638
669
|
}).immediate();
|
|
639
670
|
rows += old.length;
|
|
@@ -701,6 +732,65 @@ export class CaptureStore {
|
|
|
701
732
|
return { rows: rows.slice(0, limit).map(toRow), partial: partial || rows.length > limit };
|
|
702
733
|
}
|
|
703
734
|
|
|
735
|
+
/**
|
|
736
|
+
* #368: the stored Record rows of exactly these turns. A candidate cites its rows by session hash and time, and the brief
|
|
737
|
+
* window holds only the newest 32, so proving a candidate with that window would read every older row as pruned. These are
|
|
738
|
+
* point lookups on the `at` index with an explicit per-turn cap: no scan, no window, and no index or spool work.
|
|
739
|
+
*/
|
|
740
|
+
readRecordTurns(turns: readonly { session: string; at: string }[]): CaptureRow[] {
|
|
741
|
+
this.checkReadBinding();
|
|
742
|
+
if (!Array.isArray(turns) || turns.length < 1 || turns.length > 8 || turns.some(turn => !turn
|
|
743
|
+
|| typeof turn.session !== "string" || !SESSION_KEY.test(turn.session) || typeof turn.at !== "string" || !Number.isFinite(Date.parse(turn.at)))) {
|
|
744
|
+
throw new Error("invalid record turn lookup; use 1 to 8 session hashes with a parseable time");
|
|
745
|
+
}
|
|
746
|
+
const columns = new Set((this.db.query("PRAGMA table_info(rows)").all() as { name: string }[]).map(column => column.name));
|
|
747
|
+
if (!columns.has("session")) return []; // a shard older than attribution cannot hold a row any candidate cites
|
|
748
|
+
const subagent = columns.has("subagent") ? " AND (subagent IS NULL OR subagent != 1)" : "";
|
|
749
|
+
const sql = `SELECT * FROM rows WHERE at = ? AND project = ? AND event = 'Record' AND session = ?${subagent} ORDER BY id LIMIT ?`;
|
|
750
|
+
const rows: RawRow[] = [];
|
|
751
|
+
for (const turn of turns) rows.push(...this.db.query(sql).all(new Date(Date.parse(turn.at)).toISOString(), this.key, turn.session, 9) as RawRow[]);
|
|
752
|
+
return rows.map(toRow);
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/** Serialize a derived cache snapshot/publication with summary invalidation and commits in every writer. */
|
|
756
|
+
withBriefCaptureSnapshot<T>(write: (summaries: { rows: CaptureRow[]; partial: boolean }, builtThrough: number) => T): T {
|
|
757
|
+
this.writable();
|
|
758
|
+
return this.db.transaction(() => {
|
|
759
|
+
const latest = this.db.query("SELECT id FROM rows ORDER BY id DESC LIMIT 1").get() as { id: number } | null;
|
|
760
|
+
return write(this.readBriefSummaries(), latest?.id ?? 0);
|
|
761
|
+
}).immediate();
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* #331: how many `Record` rows sit outside the retained recent window, within the same `since` lower bound a host applies.
|
|
766
|
+
* Index-only and bounded by the window: it reads no row content, returns no ids and never scans `rows`.
|
|
767
|
+
* The cohort is the one `rows_brief_records_v1` covers, main-session Records; `available: false` means no derived index
|
|
768
|
+
* answers this event yet (a large legacy store) or the plan is not the bounded seek, never a quiet fallback to a scan
|
|
769
|
+
* and never a throw, so a host upgrade that changes planner rendering degrades the answer instead of the caller.
|
|
770
|
+
*/
|
|
771
|
+
countOutsideRecent(f: { event: string; since?: string }): CaptureOutsideCount {
|
|
772
|
+
this.checkReadBinding();
|
|
773
|
+
if (!this.readOnly || this.recentReadIds === undefined) throw new Error("outside-window counts require a read-only recent window; open CaptureStore with readOnly and recentReadRows");
|
|
774
|
+
if (typeof f?.event !== "string" || !f.event.trim() || f.event.length > 64) throw new Error("invalid capture event filter");
|
|
775
|
+
if (f.since !== undefined && (typeof f.since !== "string" || !f.since || f.since.length > 64)) throw new Error("invalid capture since bound");
|
|
776
|
+
// ponytail: Record is the only event with a derived index; counting another event needs its own partial index first.
|
|
777
|
+
if (f.event !== "Record" || !this.db.query("SELECT 1 FROM sqlite_master WHERE name='rows_brief_records_v1' AND type='index'").get()) {
|
|
778
|
+
return { rows: 0, capped: false, available: false };
|
|
779
|
+
}
|
|
780
|
+
const cap = this.maxRecentReadRows, boundary = this.recentBoundary;
|
|
781
|
+
if (!boundary) return { rows: 0, capped: false, available: true }; // an empty shard holds nothing outside the window
|
|
782
|
+
const sinceSql = f.since === undefined ? "" : " AND at >= ?";
|
|
783
|
+
const sql = `SELECT COUNT(*) AS n FROM (SELECT 1 FROM rows INDEXED BY rows_brief_records_v1
|
|
784
|
+
WHERE project=? AND event='Record' AND (subagent IS NULL OR subagent != 1) AND (at,id) < (?,?)${sinceSql} LIMIT ?)`;
|
|
785
|
+
const bind = [this.key, boundary.at, boundary.id, ...(f.since === undefined ? [] : [f.since]), cap + 1];
|
|
786
|
+
const plan = this.db.query(`EXPLAIN QUERY PLAN ${sql}`).all(...bind) as { detail: string }[];
|
|
787
|
+
// The guarantee is a seek bounded by the window boundary, not merely an index: an unbounded walk of the project's
|
|
788
|
+
// Record history would report the same numbers at a cost that grows with history, so the count is not answered.
|
|
789
|
+
if (!outsideCountPlanIsBounded(plan)) return { rows: 0, capped: false, available: false };
|
|
790
|
+
const n = (this.db.query(sql).get(...bind) as { n: number }).n;
|
|
791
|
+
return { rows: Math.min(n, cap), capped: n > cap, available: true };
|
|
792
|
+
}
|
|
793
|
+
|
|
704
794
|
/** Index reads return at most33 bodies. Legacy fallback reads at most128 recent rows. */
|
|
705
795
|
readBriefSummaries(limit = BRIEF_SUMMARY_CANDIDATES): { rows: CaptureRow[]; partial: boolean } {
|
|
706
796
|
this.checkReadBinding();
|
|
@@ -1,23 +1,32 @@
|
|
|
1
|
-
import { CandidateStore, ConsolidationReviewLimit, candidateInputId, candidateTargetRevision, type CandidateInput } from "./candidates.ts";
|
|
1
|
+
import { CANDIDATE_RETENTION, CandidateStore, ConsolidationReviewLimit, candidateInputId, candidateTargetRevision, type CandidateInput } from "./candidates.ts";
|
|
2
2
|
import { consolidationClusters } from "./consolidation-clusters.ts";
|
|
3
3
|
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
7
|
import { proposeModelConsolidations, type ModelConsolidationOptions, type ModelConsolidationReport } from "./consolidation-model.ts";
|
|
8
|
+
import { recordCandidates, type RecordCandidateCounts, type RecordCandidateWindow } from "./record-candidates.ts";
|
|
8
9
|
|
|
9
10
|
export interface ConsolidationOptions {
|
|
10
11
|
project: string; actor: "person" | "agent"; policy: () => StandalonePolicy; policyVersion: () => string;
|
|
11
12
|
allowed?: () => boolean; assertCurrent?: () => void;
|
|
12
13
|
/** Person-enabled host callback only. Absent means no model work or budget reservation. */
|
|
13
14
|
model?: ModelConsolidationOptions;
|
|
15
|
+
/**
|
|
16
|
+
* #368: the newest capture Record window, read again on every call. Absent means this host has no capture to read, so no
|
|
17
|
+
* Record candidate is proposed and nothing else changes.
|
|
18
|
+
*/
|
|
19
|
+
records?: () => RecordCandidateWindow;
|
|
14
20
|
}
|
|
21
|
+
/** Record proposals are counted apart from consolidation ones, so a person can see which pass queued what. */
|
|
22
|
+
export interface RecordConsolidationReport extends RecordCandidateCounts { queued: number; refused: number }
|
|
15
23
|
export interface ConsolidationReport {
|
|
16
24
|
schema: "amem.consolidation/v1"; project: string; candidates: { id: string; action: string; sources: string[] }[];
|
|
17
25
|
engine: "fts5" | "substring"; truncated: boolean; oversized: number; localExcluded: number;
|
|
18
26
|
/** Proposals whose candidate already exists as accepted, accepting or rejected: they are not queued again and are not in `candidates`. */
|
|
19
27
|
alreadyReviewed: number;
|
|
20
28
|
model?: ModelConsolidationReport;
|
|
29
|
+
records?: RecordConsolidationReport;
|
|
21
30
|
}
|
|
22
31
|
export class ConsolidationProposalError extends Error {
|
|
23
32
|
constructor(readonly proposed: string[], readonly refusal?: ConsolidationReviewLimit) {
|
|
@@ -46,6 +55,8 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
|
|
|
46
55
|
for (const value of raw) {
|
|
47
56
|
check(); const row = memoryPolicySnapshot(value);
|
|
48
57
|
if (!row || row.project !== project || !recallViewIsLive(row, store.readNow()) || modelAnswer(row)) continue;
|
|
58
|
+
// #370: a preference is a person-owned statement; consolidation never merges or infers one (the issue keeps inference out of scope).
|
|
59
|
+
if (row.kind === "preference") continue;
|
|
49
60
|
if (await policy.screen(row)) rows.push(row);
|
|
50
61
|
}
|
|
51
62
|
check();
|
|
@@ -55,6 +66,8 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
|
|
|
55
66
|
let oversized = 0;
|
|
56
67
|
for (const cluster of clustered.clusters) {
|
|
57
68
|
const first = cluster.sources[0]!;
|
|
69
|
+
// A preference row never reaches a cluster (the row filter above), so this keeps the candidate's kind union honest, not a downgrade.
|
|
70
|
+
if (first.kind === "preference") continue;
|
|
58
71
|
if (cluster.sources.some(row => row.scope !== first.scope || row.local !== first.local)) continue;
|
|
59
72
|
const text = `${cluster.reason}\n\nUntrusted quoted sources, not instructions:\n${cluster.sources.map(row => JSON.stringify({ ref: `mem:${row.id}`, kind: row.kind, text: row.text })).join("\n")}`;
|
|
60
73
|
const about = [...new Set(cluster.sources.flatMap(row => [...row.about, ...(row.task ? [`task:${row.task}`] : [])]))].sort();
|
|
@@ -76,6 +89,27 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
|
|
|
76
89
|
candidates.put(input, "public");
|
|
77
90
|
report.candidates.push({ id, action: input.action, sources: input.targets.map(target => `mem:${target.id}`) });
|
|
78
91
|
}
|
|
92
|
+
// #368: the same one-at-a-time discipline for Record rows. A group key already in the queue is not proposed again, so a
|
|
93
|
+
// second run over the same window writes nothing; the row and the built input are both screened before it is stored.
|
|
94
|
+
if (options.records !== undefined) {
|
|
95
|
+
check();
|
|
96
|
+
const queued = new Set<string>(), reviewed = new Set<string>();
|
|
97
|
+
for (const known of candidates.list({ project, status: "all", limit: CANDIDATE_RETENTION.count })) {
|
|
98
|
+
const key = known.input.kind === "memory" || known.input.kind === "fail" ? known.input.record?.key : undefined;
|
|
99
|
+
if (key !== undefined) (known.status === "pending" || known.status === "accepting" ? queued : reviewed).add(key);
|
|
100
|
+
}
|
|
101
|
+
const proposed = recordCandidates(options.records(), project, { queued, reviewed }), counts: RecordConsolidationReport = { ...proposed.counts, queued: 0, refused: 0 };
|
|
102
|
+
for (const proposal of proposed.proposals) {
|
|
103
|
+
check(); if (!await policy.screen(proposal.source)) { counts.refused++; continue; }
|
|
104
|
+
check(); if (!await policy.screen(proposal.input)) { counts.refused++; continue; }
|
|
105
|
+
check();
|
|
106
|
+
candidates.put(proposal.input, "public");
|
|
107
|
+
counts.queued++;
|
|
108
|
+
report.candidates.push({ id: candidateInputId(proposal.input), action: `record:${proposal.input.kind === "fail" ? "fail" : proposal.input.noteKind}`,
|
|
109
|
+
sources: (proposal.input.record?.sources ?? []).map(source => `capture:${source.session}@${source.at}`) });
|
|
110
|
+
}
|
|
111
|
+
report.records = counts;
|
|
112
|
+
}
|
|
79
113
|
if (options.model !== undefined) report.model = await proposeModelConsolidations(store, candidates, synced, options.model, { project, actor: options.actor, check, policy });
|
|
80
114
|
} catch (error) { throw new ConsolidationProposalError(report.candidates.map(row => row.id), error instanceof ConsolidationReviewLimit ? error : undefined); }
|
|
81
115
|
return report;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { existsSync, lstatSync, readdirSync, rmSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { readSelector } from "./generation.ts";
|
|
4
|
+
import { aliasedKeys, readShardDescriptor, readShardedSelection } from "./shard.ts";
|
|
5
|
+
|
|
6
|
+
/** Small selected-profile binding only; never a generation/source refresh. */
|
|
7
|
+
export function curatedProfileBinding(base: string, project: string): string {
|
|
8
|
+
return JSON.stringify({ selector: readSelector(base).revision,
|
|
9
|
+
shards: existsSync(join(base, "shards.json")) ? readShardedSelection(base) : null,
|
|
10
|
+
aliases: aliasedKeys(base, project) });
|
|
11
|
+
}
|
|
12
|
+
/** Off-hook conservative invalidation: derived directories only, never enumerate authoritative logs. */
|
|
13
|
+
export function invalidateCuratedCaches(base: string): string[] {
|
|
14
|
+
const projects = new Set<string>(), root = join(base, "projects");
|
|
15
|
+
if (!existsSync(root)) return [];
|
|
16
|
+
for (const hash of readdirSync(root)) {
|
|
17
|
+
if (!/^[a-f0-9]{16}$/.test(hash)) continue;
|
|
18
|
+
const directory = join(root, hash), stat = lstatSync(directory);
|
|
19
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) continue;
|
|
20
|
+
const descriptor = readShardDescriptor(base, hash);
|
|
21
|
+
const machines = join(directory, "machine");
|
|
22
|
+
if (!existsSync(machines)) continue;
|
|
23
|
+
const parent = lstatSync(machines); if (!parent.isDirectory() || parent.isSymbolicLink()) continue;
|
|
24
|
+
for (const machine of readdirSync(machines)) {
|
|
25
|
+
if (!/^[a-f0-9]{16}$/.test(machine)) continue;
|
|
26
|
+
const scope = join(machines, machine), info = lstatSync(scope);
|
|
27
|
+
if (!info.isDirectory() || info.isSymbolicLink()) continue;
|
|
28
|
+
// The preference slot (#370) is its own file here; a reader that only knows the curated one leaves it to age out.
|
|
29
|
+
const files = ["brief-curated.json", "brief-preferences.json"].map(name => join(scope, name));
|
|
30
|
+
if (!files.some(file => lstatSync(file, { throwIfNoEntry: false }))) continue;
|
|
31
|
+
for (const file of files) rmSync(file, { force: true });
|
|
32
|
+
if (descriptor) projects.add(descriptor.key);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return [...projects];
|
|
36
|
+
}
|
|
@@ -63,7 +63,9 @@ export function decayPreview(store: MemoryStore, project: string, options: Decay
|
|
|
63
63
|
const entries: DecayEntry[] = []; let withheld = 0, citedExemptions = 0;
|
|
64
64
|
for (let index = 0; index < rows.length; index++) {
|
|
65
65
|
const view = rows[index];
|
|
66
|
-
|
|
66
|
+
// #370: a preference never expires automatically, so decay never demotes one; naming one as an id is refused below like any other
|
|
67
|
+
// ineligible target rather than silently skipping it.
|
|
68
|
+
const eligible = view && (!requested || view.id === requested[index]) && view.project === project && view.tier === "long" && view.kind !== "preference" && !view.supersededBy && Number.isFinite(Date.parse(view.at)) && Date.parse(view.at) < cutoff
|
|
67
69
|
&& !(view.task && tasks.has(view.task)) && !view.about.some(node => goalNodes.has(node) || node.startsWith("task:") && tasks.has(node.slice(5)));
|
|
68
70
|
if (!eligible) { if (requested) throw Error("requested entry is not eligible for decay"); continue; }
|
|
69
71
|
if (cited.has(view.id)) { citedExemptions++; if (requested) throw Error("requested entry has a retained recorded citation"); continue; }
|
package/src/memory/formats.ts
CHANGED
|
@@ -12,6 +12,12 @@ export const FORMATS_FILE = "formats.json";
|
|
|
12
12
|
export const FORMAT_SURFACES = ["curated", "capture", "hook-spool", "candidates", "work-lists", "sync"] as const;
|
|
13
13
|
export type FormatSurface = typeof FORMAT_SURFACES[number];
|
|
14
14
|
export interface FormatFloor { surface: string; minReader: string; since: string }
|
|
15
|
+
/**
|
|
16
|
+
* The first release whose readers understand the `preference` note kind (#370). An older reader drops such a row and refuses its own
|
|
17
|
+
* machine's sync publish over it, so a preference write is refused until a person records a floor at or above this one.
|
|
18
|
+
*/
|
|
19
|
+
// The writer refuses until the person records the floor, so no host writes a row its peers cannot sync past.
|
|
20
|
+
export const PREFERENCE_MIN_READER = "0.25.0";
|
|
15
21
|
const MAX_BYTES = 64 * 1024, SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/;
|
|
16
22
|
|
|
17
23
|
export class FormatFloorError extends Error {
|
|
@@ -63,3 +69,17 @@ export function assertFormatFloor(home: string, surface: FormatSurface): void {
|
|
|
63
69
|
throw new FormatFloorError("format_floor", `amem ${reader} is below the ${surface} format floor ${floor.minReader} (since ${floor.since}) recorded in ${join(home, FORMATS_FILE)}; nothing was read or written. Upgrade amem to ${floor.minReader} or later.`, { ...floor, reader });
|
|
64
70
|
}
|
|
65
71
|
}
|
|
72
|
+
|
|
73
|
+
/** A person opts into a capability only by an applicable floor, never by this code writing one. */
|
|
74
|
+
export function formatFloorAtLeast(home: string, surface: FormatSurface, minimum: string): boolean {
|
|
75
|
+
if (!SEMVER.test(minimum)) return false;
|
|
76
|
+
return (readFormatFloors(home) ?? []).some(floor => (floor.surface === surface || floor.surface === "home") && !below(floor.minReader, minimum));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The step a person takes to raise a floor: the exact record, the file it goes in, and that this package never writes that file. It is the
|
|
81
|
+
* next step a refusal names, so the writer that refuses keeps the path and the record from one place.
|
|
82
|
+
*/
|
|
83
|
+
export function floorRaiseHint(home: string, surface: FormatSurface, minReader: string): string {
|
|
84
|
+
return `append {"surface":"${surface}","minReader":"${minReader}","since":"YYYY-MM-DD"} to ${join(home, FORMATS_FILE)} by hand (amem never writes that file)`;
|
|
85
|
+
}
|
|
@@ -20,6 +20,7 @@ export interface GenerationIndexOptions {
|
|
|
20
20
|
profile: BoundProfile; db: Database; now: () => number;
|
|
21
21
|
apply: (line: string, source: string) => void;
|
|
22
22
|
withMutation: <T>(work: () => T) => T;
|
|
23
|
+
beforeCuratedWrite?: (targets: readonly string[]) => void;
|
|
23
24
|
limits?: readonly LegacyCheckpoint[]; commit?: string;
|
|
24
25
|
}
|
|
25
26
|
/** Pure deadline summary shared by migration and prune: no live index or host TTL is a proof. */
|
|
@@ -401,6 +402,7 @@ export class GenerationIndex {
|
|
|
401
402
|
if (!complete.some(value => canonicalJSON(JSON.parse(value)) === canonicalJSON(row))) return fail();
|
|
402
403
|
} else {
|
|
403
404
|
if (!bytes.subarray(0, tail.length).equals(tail)) return fail();
|
|
405
|
+
this.options.beforeCuratedWrite?.(row.targets.map(target => target.id));
|
|
404
406
|
let offset = tail.length;
|
|
405
407
|
while (offset < bytes.length) { const wrote = writeSync(fd, bytes, offset, bytes.length - offset); if (wrote <= 0) fail(); offset += wrote; }
|
|
406
408
|
}
|
|
@@ -77,6 +77,7 @@ function validatePublic(bytes: string, generation: string, path: string, checkPr
|
|
|
77
77
|
export async function syncGenerationMemory(store: MemoryStore, opts: SyncOptions = {}): Promise<SyncResult> {
|
|
78
78
|
const placementRefusal = placementRuntimeRefusal(store.profile.home, store.profile);
|
|
79
79
|
if (placementRefusal) return { ok: false, pushed: false, entries: 0, error: placementRefusal };
|
|
80
|
+
let releaseCurated: (() => void) | undefined;
|
|
80
81
|
let pushed = false, releaseMutation: (() => void) | undefined, releaseSync: (() => void) | undefined;
|
|
81
82
|
const result = (error: string): SyncResult => ({ ok: false, pushed, entries: 0, error });
|
|
82
83
|
const profile = store.profile, generation = profile.generation, dir = store.dir;
|
|
@@ -98,6 +99,7 @@ export async function syncGenerationMemory(store: MemoryStore, opts: SyncOptions
|
|
|
98
99
|
if (opts.signal?.aborted) return result("stopped");
|
|
99
100
|
releaseMutation = acquireMutation(dir);
|
|
100
101
|
if (!releaseMutation) return result("another generation mutation is running");
|
|
102
|
+
releaseCurated = store.beginCuratedCacheUpdate();
|
|
101
103
|
releaseSync = lockSync(dir);
|
|
102
104
|
if (!releaseSync) return result("another generation sync is running or its owner is unknown");
|
|
103
105
|
validateGeneration(profile.home, generation);
|
|
@@ -250,5 +252,6 @@ export async function syncGenerationMemory(store: MemoryStore, opts: SyncOptions
|
|
|
250
252
|
for (const transient of transientRefs) { try { await syncGit(dir, [...(transient.cache ? ["--git-dir", transient.cache] : []), "update-ref", "-d", transient.ref]); } catch { /* local refs remain non-public if cleanup itself fails */ } }
|
|
251
253
|
try { releaseSync?.(); } catch { /* cleanup cannot turn an observed sync result into an uncaught error */ }
|
|
252
254
|
try { releaseMutation?.(); } catch { /* closed/broken derived lock is a local recovery concern */ }
|
|
255
|
+
releaseCurated?.();
|
|
253
256
|
}
|
|
254
257
|
}
|
package/src/memory/index-file.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Bumped when the index's tables change: an index with another version is dropped and rebuilt from the logs. */
|
|
2
|
-
export const INDEX_VERSION =
|
|
2
|
+
export const INDEX_VERSION = 4; // 4: the preference kind (an older index skipped such notes)
|
|
3
3
|
/** The version that released 0.14.0 through 0.18.0 build into the unversioned names below; it keeps them so this release shares their warm index. */
|
|
4
4
|
const SHARED_INDEX_VERSION = 3;
|
|
5
5
|
|