@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
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { readBriefCache } from "./brief-cache.ts";
|
|
4
|
+
import { curatedCacheFresh } from "./brief-curated.ts";
|
|
5
|
+
import { curatedProfileBinding } from "./memory/curated-cache-state.ts";
|
|
6
|
+
import { canonicalPath } from "./memory/platform.ts";
|
|
7
|
+
import { aliasedKeys, captureShardDir, resolveAlias } from "./memory/shard.ts";
|
|
8
|
+
import { machineId, MemoryStore, openShardStore } from "./memory/store.ts";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Explicit off-hook WRITE: opens the selected store with promotions deferred and atomically
|
|
12
|
+
* prepares one private curated cache (at most four 32-row pages and a 32 KiB file).
|
|
13
|
+
* Hosts must schedule this deliberately outside their hook latency budget. Never raises a floor.
|
|
14
|
+
*/
|
|
15
|
+
export function prepareCuratedBriefCache(base: string, project: string): void {
|
|
16
|
+
if (typeof base !== "string" || !base.trim() || typeof project !== "string" || !project.trim()) {
|
|
17
|
+
throw Error("curated cache preparation needs a memory directory and project; supply both before retrying off-hook");
|
|
18
|
+
}
|
|
19
|
+
const home = canonicalPath(base), key = resolveAlias(home, project), aliases = aliasedKeys(home, key);
|
|
20
|
+
const options = { memoryDir: home, deferPromotions: true, ...(aliases.length ? { reconcile: { canonical: key, aliases } } : {}) };
|
|
21
|
+
const store = existsSync(join(home, "shards.json")) ? openShardStore({ ...options, project: key }) : new MemoryStore(options);
|
|
22
|
+
try {
|
|
23
|
+
store.prepareCuratedBriefs([key]);
|
|
24
|
+
const cache = readBriefCache({ directory: captureShardDir(home, key, machineId(home).id), project: key, section: "curated" });
|
|
25
|
+
if (!cache || !curatedCacheFresh(cache, curatedProfileBinding(home, key), Date.now())) {
|
|
26
|
+
throw Error("curated cache preparation could not publish a current snapshot; run amem doctor, check source/file permissions, then retry off-hook");
|
|
27
|
+
}
|
|
28
|
+
} finally { store.close(); }
|
|
29
|
+
}
|
package/src/hook-contract.ts
CHANGED
|
@@ -1,15 +1,35 @@
|
|
|
1
|
+
import type { RecordIntakeCounts } from "./hook-record.ts";
|
|
1
2
|
export const HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "Stop", "SessionEnd"] as const;
|
|
2
3
|
export type HookEvent = typeof HOOK_EVENTS[number];
|
|
3
4
|
export const HOOK_INPUT_BYTES = 64 * 1024, HOOK_CONTEXT_BYTES = 1200, HOOK_OUTPUT_BYTES = 8192;
|
|
4
5
|
/** `unavailable` (#221): the scan threw, so no progress is known; unlike the others it is a fault, never accepted progress. */
|
|
5
6
|
export type HookTranscriptStopReason = "cap" | "deadline" | "spool_full" | "unavailable";
|
|
6
7
|
export const HOOK_TRANSCRIPT_STOP_REASONS: readonly HookTranscriptStopReason[] = ["cap", "deadline", "spool_full", "unavailable"];
|
|
7
|
-
export interface
|
|
8
|
+
export interface HookRecordCounts { recordValidRecords: number; recordBasisRecords: number; recordUnverifiedRecords: number }
|
|
9
|
+
export interface HookTranscriptProgress extends Partial<HookRecordCounts> { offset?: number; stopReason?: HookTranscriptStopReason; records?: RecordIntakeCounts }
|
|
8
10
|
export function isHookTranscriptProgress(value: unknown): value is HookTranscriptProgress {
|
|
9
11
|
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
10
12
|
const row = value as Record<string, unknown>;
|
|
11
|
-
return Object.keys(row).every(key =>
|
|
13
|
+
return Object.keys(row).every(key => ["offset", "stopReason", "recordValidRecords", "recordBasisRecords", "recordUnverifiedRecords", "records"].includes(key))
|
|
14
|
+
&& (row.records === undefined || isRecordIntakeCounts(row.records))
|
|
15
|
+
&& (["recordValidRecords", "recordBasisRecords", "recordUnverifiedRecords"].every(key => row[key] === undefined)
|
|
16
|
+
|| ["recordValidRecords", "recordBasisRecords", "recordUnverifiedRecords"].every(key => Number.isSafeInteger(row[key]) && (row[key] as number) >= 0)
|
|
17
|
+
&& (row.recordBasisRecords as number) <= (row.recordValidRecords as number) && (row.recordUnverifiedRecords as number) <= (row.recordValidRecords as number))
|
|
12
18
|
&& (row.offset !== undefined || row.stopReason !== undefined)
|
|
13
19
|
&& (row.offset === undefined || Number.isSafeInteger(row.offset) && (row.offset as number) >= 0)
|
|
14
20
|
&& (row.stopReason === undefined || (HOOK_TRANSCRIPT_STOP_REASONS as readonly string[]).includes(row.stopReason as string));
|
|
15
21
|
}
|
|
22
|
+
|
|
23
|
+
/** The worker protocol permits only bounded numeric receipts, never captured text. */
|
|
24
|
+
function isRecordIntakeCounts(value: unknown): value is RecordIntakeCounts {
|
|
25
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
26
|
+
const row = value as Record<string, unknown>;
|
|
27
|
+
const numeric = (n: unknown): n is number => Number.isSafeInteger(n) && (n as number) >= 0;
|
|
28
|
+
if (Object.keys(row).length !== 5 || !Object.keys(row).every(key => ["supported", "found", "staged", "duplicatesSkipped", "refused"].includes(key))
|
|
29
|
+
|| typeof row.supported !== "boolean" || !numeric(row.found) || !numeric(row.staged) || !numeric(row.duplicatesSkipped)
|
|
30
|
+
|| row.staged > row.found || row.duplicatesSkipped > row.found || (!row.supported && row.staged !== 0)
|
|
31
|
+
|| !row.refused || typeof row.refused !== "object" || Array.isArray(row.refused)) return false;
|
|
32
|
+
const reasons = ["record_invalid", "record_count", "record_length", "record_policy", "record_identity", "record_timestamp", "finality-unavailable"];
|
|
33
|
+
return Object.entries(row.refused).every(([reason, count]) => reasons.includes(reason) && numeric(count))
|
|
34
|
+
&& Object.values(row.refused).reduce<number>((sum, count) => sum + (count as number), 0) + row.staged + row.duplicatesSkipped <= row.found;
|
|
35
|
+
}
|
|
@@ -4,16 +4,17 @@ import { join } from "node:path";
|
|
|
4
4
|
import type { Database } from "bun:sqlite";
|
|
5
5
|
import { assertFormatFloor } from "./memory/formats.ts";
|
|
6
6
|
import { appendMetrics } from "./memory/metrics.ts";
|
|
7
|
-
import { configuredPolicyOptions } from "./memory/config.ts";
|
|
7
|
+
import { configuredPolicyOptions, recordsEnabled } from "./memory/config.ts";
|
|
8
8
|
import { canonicalPath, realPath } from "./memory/platform.ts";
|
|
9
9
|
import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
|
|
10
10
|
import { HookSpoolFull, stageTranscriptCapture } from "./hook-spool.ts";
|
|
11
11
|
import { cursorDatabase, HOOK_TRANSCRIPT_BYTES, privateDirectory } from "./hook-transcript.ts";
|
|
12
|
+
import { parseRecordLines, recordIntakeCounts, recordRefusal, type RecordIntakeCounts, type RecordDropReason } from "./hook-record.ts";
|
|
12
13
|
import type { HookTranscriptProgress } from "./hook-contract.ts";
|
|
13
14
|
|
|
14
15
|
// #216: jcode writes `<sessions>/<stem>.journal.jsonl`, one `{"meta":{...},"append_messages":[...]}` line per save. Only `meta.title` and
|
|
15
|
-
// `meta.compaction.summary_text` are read
|
|
16
|
-
// before `,"append_messages"` (an unescaped quote cannot occur inside a JSON string, so that marker cannot hide in text).
|
|
16
|
+
// `meta.compaction.summary_text` are read for capture. Enabled Record receipts inspect only main assistant text; finality is unavailable,
|
|
17
|
+
// so no Record is staged. Snapshots and reasoning are never read for Records. Metadata is sliced out before `,"append_messages"` (an unescaped quote cannot occur inside a JSON string, so that marker cannot hide in text).
|
|
17
18
|
const hash = (value: string) => createHash("sha256").update(value).digest("hex");
|
|
18
19
|
const META = '{"meta":', BODIES = ',"append_messages"', TITLE_BYTES = 512;
|
|
19
20
|
const object = (value: unknown): Record<string, unknown> | undefined => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
|
|
@@ -43,6 +44,7 @@ export async function scanJcodeJournal(target: { cwd: string; session: string; j
|
|
|
43
44
|
const cwd = realPath(target.cwd), base = canonicalPath(options.base);
|
|
44
45
|
assertFormatFloor(base, "hook-spool");
|
|
45
46
|
const policy = createStandalonePolicy(configuredPolicyOptions(base, cwd, options.policy));
|
|
47
|
+
const intake = recordsEnabled(base, cwd) ? recordIntakeCounts(false) : undefined;
|
|
46
48
|
const session = hash(`amem-session\0${target.session}`).slice(0, 16);
|
|
47
49
|
if (!lstatSync(target.journal, { throwIfNoEntry: false })) return;
|
|
48
50
|
if (lstatSync(target.journal).isSymbolicLink()) throw new Error("jcode journal unavailable");
|
|
@@ -71,6 +73,7 @@ export async function scanJcodeJournal(target: { cwd: string; session: string; j
|
|
|
71
73
|
const workStart = clock();
|
|
72
74
|
const due = () => clock() >= options.deadline || options.workBudgetMs !== undefined && clock() - workStart >= options.workBudgetMs;
|
|
73
75
|
let unpublished = false, start = 0, skipping = partial, stopReason: HookTranscriptProgress["stopReason"], newestLine: string | undefined;
|
|
76
|
+
const recordLines: { end: number; counts: RecordIntakeCounts }[] = [];
|
|
74
77
|
const compactions: { covers: unknown; text: string; at: string | undefined; subagent: boolean; dir: unknown }[] = [];
|
|
75
78
|
// #216 review (codex P2): a row belongs to the project of its own line. A journal of a session that moved between projects carries other
|
|
76
79
|
// `meta.working_dir` values; those rows are not staged under this hook's cwd. A missing working_dir keeps the hook's cwd (unchanged).
|
|
@@ -91,11 +94,41 @@ export async function scanJcodeJournal(target: { cwd: string; session: string; j
|
|
|
91
94
|
if (start === 0 && length >= HOOK_TRANSCRIPT_BYTES) { skipping = true; start = length; oversized++; }
|
|
92
95
|
break;
|
|
93
96
|
}
|
|
97
|
+
const lineStart = start;
|
|
94
98
|
let line: string;
|
|
95
99
|
try { line = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(start, newline)); } catch { start = newline + 1; continue; }
|
|
96
100
|
start = newline + 1;
|
|
97
101
|
if (!line.startsWith(META)) continue;
|
|
98
102
|
const metaEnd = line.indexOf(BODIES, META.length), head = metaEnd >= 0 ? line.slice(0, metaEnd) : line;
|
|
103
|
+
if (intake && line.includes("amem:")) {
|
|
104
|
+
const meta = journalMeta(line);
|
|
105
|
+
if (meta?.parent_id === null && ownsDir(meta.working_dir)) {
|
|
106
|
+
let entry: Record<string, unknown> | undefined;
|
|
107
|
+
try { entry = object(JSON.parse(line)); } catch { /* malformed body does not change metadata capture */ }
|
|
108
|
+
const counts = recordIntakeCounts(false);
|
|
109
|
+
let incomplete = false;
|
|
110
|
+
if (Array.isArray(entry?.append_messages)) for (const value of entry.append_messages) {
|
|
111
|
+
if (due()) { incomplete = true; break; }
|
|
112
|
+
const message = object(value);
|
|
113
|
+
if (message?.role !== "assistant" || typeof message.id !== "string" || !message.id
|
|
114
|
+
|| message.display_role != null || !Array.isArray(message.content)) continue;
|
|
115
|
+
// Native tool-call, background and reasoning messages are not final-answer evidence.
|
|
116
|
+
const blocks = message.content.map(object);
|
|
117
|
+
if (!blocks.length || blocks.some(block => block?.type !== "text" || typeof block.text !== "string")) continue;
|
|
118
|
+
const parsed = parseRecordLines(blocks.map(block => block!.text as string).join("\n"), due);
|
|
119
|
+
if (parsed.incomplete) { incomplete = true; break; }
|
|
120
|
+
counts.found += parsed.records.length;
|
|
121
|
+
if (parsed.records.length) recordRefusal(counts, "finality-unavailable", parsed.records.length);
|
|
122
|
+
for (const [reason, count] of Object.entries(parsed.drops)) {
|
|
123
|
+
counts.found += count;
|
|
124
|
+
recordRefusal(counts, reason as RecordDropReason, count);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (incomplete) { start = lineStart; stopReason = "deadline"; break; }
|
|
128
|
+
recordLines.push({ end: start, counts });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
99
132
|
if (head.includes('"compaction":{')) {
|
|
100
133
|
const meta = journalMeta(line), compaction = object(meta?.compaction);
|
|
101
134
|
if (meta && compaction && typeof compaction.summary_text === "string" && compaction.summary_text.trim()) {
|
|
@@ -144,7 +177,16 @@ export async function scanJcodeJournal(target: { cwd: string; session: string; j
|
|
|
144
177
|
db.query("UPDATE cursor SET offset=?,dev=?,ino=?,size=?,title=?,at=?,skipping=? WHERE id=1")
|
|
145
178
|
.run(offset, String(stat.dev), String(stat.ino), stat.size, cursor.title, cursor.at, skipping ? 1 : 0);
|
|
146
179
|
db.run("COMMIT");
|
|
147
|
-
|
|
180
|
+
if (intake) {
|
|
181
|
+
// Only acknowledged forward bytes produce receipts; a retry never recounts an unpublished prefix.
|
|
182
|
+
for (const line of recordLines) if (from + line.end <= offset) {
|
|
183
|
+
intake.found += line.counts.found;
|
|
184
|
+
for (const [reason, count] of Object.entries(line.counts.refused)) recordRefusal(intake, reason as RecordDropReason | "finality-unavailable", count);
|
|
185
|
+
}
|
|
186
|
+
if (Object.keys(intake.refused).length) appendMetrics(base, Object.entries(intake.refused).map(([reason, count]) => ({ at: new Date().toISOString(), kind: "hook" as const,
|
|
187
|
+
captureDrops: count, captureDropReason: reason as RecordDropReason | "finality-unavailable" })));
|
|
188
|
+
}
|
|
189
|
+
return { offset, ...(stopReason ? { stopReason } : {}), ...(intake ? { records: intake } : {}) };
|
|
148
190
|
} finally {
|
|
149
191
|
if (db) try { db.run("ROLLBACK"); } catch { /* committed */ }
|
|
150
192
|
db?.close();
|
package/src/hook-record.ts
CHANGED
|
@@ -7,10 +7,30 @@ export const RECORD_INSTRUCTION = [
|
|
|
7
7
|
"For fix/fail use symptom/cause -> fix/retry-when. No fences, quotes, secrets or PII.",
|
|
8
8
|
].join("\n");
|
|
9
9
|
|
|
10
|
+
/** Purpose-framed alternative; the canonical Record grammar is unchanged. */
|
|
11
|
+
export const RECORD_INSTRUCTION_B = [
|
|
12
|
+
"Future use: keep what code/git/instructions lack. Up to 2 final lines; else none:",
|
|
13
|
+
"amem: <decision|fix|fail|contract|finding> | <repo/path[#symbol],... or - for decision/contract> | <text, max 300 chars; basis:test|log|issue|run; prefix ? if unverified>",
|
|
14
|
+
"fix/fail: symptom/cause -> fix/retry-when. No fences, quotes, secrets or PII.",
|
|
15
|
+
].join("\n");
|
|
16
|
+
export type RecordInstructionVariant = "a" | "b";
|
|
17
|
+
export type RecordInstructionMode = RecordInstructionVariant | "alternate";
|
|
18
|
+
export const RECORD_INSTRUCTIONS = Object.freeze({ a: RECORD_INSTRUCTION, b: RECORD_INSTRUCTION_B });
|
|
19
|
+
export const RECORD_INSTRUCTION_BYTES = 332;
|
|
20
|
+
|
|
21
|
+
/** Parity of the persisted session hash is reproducible without the raw session id. */
|
|
22
|
+
export function recordInstructionVariant(mode: RecordInstructionMode, sessionKey?: string): RecordInstructionVariant {
|
|
23
|
+
if (mode !== "alternate") return mode;
|
|
24
|
+
return sessionKey && /^[a-f0-9]{16}$/.test(sessionKey) && Number.parseInt(sessionKey.slice(-1), 16) % 2 === 1 ? "b" : "a";
|
|
25
|
+
}
|
|
26
|
+
|
|
10
27
|
/** Data remains untrusted after the one exact package-owned instruction prefix. */
|
|
11
28
|
export function recordContextData(context: string): string {
|
|
12
|
-
const
|
|
13
|
-
|
|
29
|
+
for (const instruction of Object.values(RECORD_INSTRUCTIONS)) {
|
|
30
|
+
const prefix = `${instruction}\n`;
|
|
31
|
+
if (context.startsWith(prefix)) return context.slice(prefix.length);
|
|
32
|
+
}
|
|
33
|
+
return context;
|
|
14
34
|
}
|
|
15
35
|
|
|
16
36
|
export const RECORD_INPUT_BYTES = 256 * 1024;
|
|
@@ -89,3 +109,21 @@ export function parseRecordLines(text: string, shouldStop?: () => boolean): Pars
|
|
|
89
109
|
}
|
|
90
110
|
return result;
|
|
91
111
|
}
|
|
112
|
+
|
|
113
|
+
/** Additive numeric intake receipt; an unsupported reader never turns text into capture. */
|
|
114
|
+
export type RecordIntakeRefusal = RecordDropReason | "finality-unavailable";
|
|
115
|
+
/**
|
|
116
|
+
* Whether a drop reason records a Record parsing refusal rather than a lost capture. Those stay observable metrics but
|
|
117
|
+
* never reach the SessionStart loss notice: a deliberate `finality-unavailable` refusal is not capture that went missing.
|
|
118
|
+
*/
|
|
119
|
+
export const recordRefusalReason = (reason: string): reason is RecordIntakeRefusal => reason.startsWith("record_") || reason === "finality-unavailable";
|
|
120
|
+
export interface RecordIntakeCounts {
|
|
121
|
+
supported: boolean; found: number; staged: number; duplicatesSkipped: number;
|
|
122
|
+
refused: Partial<Record<RecordIntakeRefusal, number>>;
|
|
123
|
+
}
|
|
124
|
+
export function recordIntakeCounts(supported = true): RecordIntakeCounts {
|
|
125
|
+
return { supported, found: 0, staged: 0, refused: {}, duplicatesSkipped: 0 };
|
|
126
|
+
}
|
|
127
|
+
export function recordRefusal(counts: RecordIntakeCounts, reason: RecordIntakeRefusal, count = 1): void {
|
|
128
|
+
counts.refused[reason] = (counts.refused[reason] ?? 0) + count;
|
|
129
|
+
}
|
package/src/hook-spool-replay.ts
CHANGED
|
@@ -19,6 +19,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, opendirSync, read
|
|
|
19
19
|
import { isAbsolute, join } from "node:path";
|
|
20
20
|
import { hookCaptureScope, hookLegacyCaptureScope, hookSpoolReplayInternals as spool, type HookSpoolOwnedFile } from "./hook-spool.ts";
|
|
21
21
|
import { aliasedKeys, resolveAlias } from "./memory/aliases.ts";
|
|
22
|
+
import { buildCaptureBriefCache } from "./brief-capture.ts";
|
|
22
23
|
import { CaptureStore, type CaptureInput } from "./memory/capture.ts";
|
|
23
24
|
import { RecordNormalizationRefusal } from "./memory/capture-input.ts";
|
|
24
25
|
import { configuredPolicyOptions } from "./memory/config.ts";
|
|
@@ -296,6 +297,7 @@ export async function applyHookSpoolReplay(options: { base: string; plan: HookSp
|
|
|
296
297
|
|
|
297
298
|
const receipt: HookSpoolReplayReceipt = { plan: plan.digest, applied: 0, spooled: 0, retired: 0, retained: 0, absent: 0, outcomes: [] };
|
|
298
299
|
const planned = plan.records.filter(record => applicable(record, confirm)).sort((a, b) => a.mtimeMs - b.mtimeMs || a.name.localeCompare(b.name));
|
|
300
|
+
let preparedThrough = 0;
|
|
299
301
|
let store: CaptureStore | undefined, storeProject: string | undefined, held: HookSpoolOwnedFile | undefined;
|
|
300
302
|
try {
|
|
301
303
|
for (const record of planned) {
|
|
@@ -316,7 +318,7 @@ export async function applyHookSpoolReplay(options: { base: string; plan: HookSp
|
|
|
316
318
|
const decoded = spool.decoded(claim);
|
|
317
319
|
if (!decoded || decoded.unknown || hash(decoded.bytes) !== record.digest) { retain("decode_changed"); closeSync(claim.fd); held = undefined; continue; }
|
|
318
320
|
// One CaptureStore at a time: close the previous project's store before opening the next one.
|
|
319
|
-
if (storeProject !== record.project) { store?.close(); store = new CaptureStore({ memoryDir: home, project: record.project!, cwd: realPath(record.cwd) }); storeProject = record.project!; }
|
|
321
|
+
if (storeProject !== record.project) { store?.close(); store = new CaptureStore({ memoryDir: home, project: record.project!, cwd: realPath(record.cwd) }); storeProject = record.project!; preparedThrough = 0; }
|
|
320
322
|
let result: ReturnType<CaptureStore["append"]>;
|
|
321
323
|
try { result = store!.append(captureInput(decoded.value.capture as never, record.project!), { receipt: hash(decoded.bytes) }); }
|
|
322
324
|
catch (error) {
|
|
@@ -326,6 +328,11 @@ export async function applyHookSpoolReplay(options: { base: string; plan: HookSp
|
|
|
326
328
|
} else retain("claim changed before policy retirement; preview again before applying");
|
|
327
329
|
closeSync(claim.fd); held = undefined; continue;
|
|
328
330
|
}
|
|
331
|
+
if (store!.briefCommitId > preparedThrough) {
|
|
332
|
+
// Keep the claim on a cache failure: replay can retry its idempotent append and finish preparation.
|
|
333
|
+
await buildCaptureBriefCache(store!, { base: home, project: record.project!, cwd: realPath(record.cwd), builtThrough: store!.briefCommitId });
|
|
334
|
+
preparedThrough = store!.briefCommitId;
|
|
335
|
+
}
|
|
329
336
|
const spooled = "spooled" in result;
|
|
330
337
|
if (spooled) receipt.spooled++; else receipt.applied++;
|
|
331
338
|
const retired = spool.retireOwned(claim);
|
package/src/hook-spool.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { dirname, join, resolve } from "node:path";
|
|
|
5
5
|
import { homedir } from "node:os";
|
|
6
6
|
import type { CaptureAppend, CaptureInput } from "./memory/capture.ts";
|
|
7
7
|
import { parseRecordLines, type ParsedRecord, type RecordDropReason } from "./hook-record.ts";
|
|
8
|
-
import { CAPTURE_MAX_EXCERPT, TRANSCRIPT_CAPTURE_EVENTS, RecordNormalizationRefusal, clipCaptureUtf8, normalizeCaptureFields, toolCaptureExcerpt, toolInputLine, type CaptureFields, type NormalizedCaptureFields } from "./memory/capture-input.ts";
|
|
8
|
+
import { captureSessionKey, CAPTURE_MAX_EXCERPT, TRANSCRIPT_CAPTURE_EVENTS, RecordNormalizationRefusal, clipCaptureUtf8, normalizeCaptureFields, toolCaptureExcerpt, toolInputLine, type CaptureFields, type NormalizedCaptureFields } from "./memory/capture-input.ts";
|
|
9
9
|
import { canonicalPath, realPath } from "./memory/platform.ts";
|
|
10
10
|
import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
|
|
11
11
|
import { configuredPolicyOptions, loadAmemConfig, repoConfigRoot } from "./memory/config.ts";
|
|
@@ -21,7 +21,10 @@ import { HOOK_EVENTS, HOOK_INPUT_BYTES } from "./hook-contract.ts";
|
|
|
21
21
|
// (they still count it toward their file and byte caps). A later format that adds fields takes a new prefix again.
|
|
22
22
|
// #203: format 3 (`hook-v3-`) carries every record 0.18.0 cannot decode, today jcode-agent rows; 0.14-0.18 match neither
|
|
23
23
|
// `hook-` nor `hook-v2-` for it, so they leave it alone. Claude native rows stay format 2, byte for byte, so 0.18.0 keeps draining them.
|
|
24
|
-
const SCHEMA = "agent-mem.hook-capture/v1", FAMILY = "agent-mem.hook-capture", FORMAT = 2, PREFIX = "hook-v2-", FORMAT_V3 = 3, PREFIX_V3 = "hook-v3-";
|
|
24
|
+
const SCHEMA = "agent-mem.hook-capture/v1", FAMILY = "agent-mem.hook-capture", FORMAT = 2, PREFIX = "hook-v2-", FORMAT_V3 = 3, PREFIX_V3 = "hook-v3-", FORMAT_V4 = 4, PREFIX_V4 = "hook-v4-";
|
|
25
|
+
// #369: 0.24.0 retires non-Claude Records under v3; only these new Records use an unmatched prefix.
|
|
26
|
+
const RECORD_AGENTS = ["codex", "kimi", "pi", "qwen", "jcode"] as const;
|
|
27
|
+
const nonClaudeRecord = (agent: string, event: string) => event === "Record" && (RECORD_AGENTS as readonly string[]).includes(agent);
|
|
25
28
|
const RECORD_BYTES = HOOK_INPUT_BYTES + 8192, MAX_FILES = 256, MAX_BYTES = 2 * 1024 * 1024;
|
|
26
29
|
// One hook previously performed one replay of at most 32 files / 256 KiB.
|
|
27
30
|
// Interleaved subpasses share these same ceilings; they do not each get a fresh allowance.
|
|
@@ -32,7 +35,7 @@ export const hookReplayBudget = (): HookReplayBudget => ({ files: HOOK_REPLAY_MA
|
|
|
32
35
|
// ponytail: a finite native admission reserve covers deferred replay, not unlimited locked intake.
|
|
33
36
|
// Upgrade: coordinated append-only capacity accounting and observable backpressure at exhaustion.
|
|
34
37
|
const CAPACITY_FILES = 32, CAPACITY_BYTES = 256 * 1024;
|
|
35
|
-
const namePattern = /^(hook-(?:v[
|
|
38
|
+
const namePattern = /^(hook-(?:v[234]-)?([a-f0-9]{64})-([a-f0-9]{64})-([a-f0-9]{32})\.json)(?:\.draining-[a-f0-9]{24})?$/;
|
|
36
39
|
const hash = (value: string | Uint8Array) => createHash("sha256").update(value).digest("hex");
|
|
37
40
|
const summaryEvent = (event: string) => TRANSCRIPT_CAPTURE_EVENTS.includes(event);
|
|
38
41
|
function recordCapture(input: Pick<CaptureFields, "excerpt" | "paths">): ParsedRecord | undefined {
|
|
@@ -41,7 +44,9 @@ function recordCapture(input: Pick<CaptureFields, "excerpt" | "paths">): ParsedR
|
|
|
41
44
|
&& JSON.stringify(record.anchors) === JSON.stringify(input.paths ?? []) ? record : undefined;
|
|
42
45
|
}
|
|
43
46
|
interface Record { schema: string; format?: number; cwd: string; scope: string | null; root?: string; nonce: string; capture: NormalizedCaptureFields }
|
|
44
|
-
|
|
47
|
+
/** `backlog` reports older project work pending around a publication and says nothing about this call's record, which may
|
|
48
|
+
* be brand new; `duplicate` is the precise witness that an identical durable body already existed, so nothing was added. */
|
|
49
|
+
export interface PendingHookCapture { name: string; cwd: string; receipt: string; deferred?: true; backlog?: true; duplicate?: true }
|
|
45
50
|
export class HookSpoolFull extends Error { constructor() { super("hook storage full"); } }
|
|
46
51
|
/** #203: the agent a staged record belongs to. Claude hooks and jcode lifecycle observers share this spool, budget and replay. */
|
|
47
52
|
export const HOOK_AGENTS = ["claude", "jcode"] as const;
|
|
@@ -376,7 +381,8 @@ function decoded(file: OwnedFile): { value: Record; bytes: Buffer; unknown?: tru
|
|
|
376
381
|
if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.cwd !== "string" || typeof value.nonce !== "string" || !/^[a-f0-9]{32}$/.test(value.nonce)
|
|
377
382
|
|| value.scope !== null && (typeof value.scope !== "string" || !/^[a-f0-9]{64}$/.test(value.scope))) return undefined;
|
|
378
383
|
const v1 = value.schema === SCHEMA && !("format" in value), v3 = value.schema === FAMILY && value.format === FORMAT_V3;
|
|
379
|
-
const
|
|
384
|
+
const v4 = value.schema === FAMILY && value.format === FORMAT_V4;
|
|
385
|
+
const current = value.schema === FAMILY && value.format === FORMAT || v3 || v4;
|
|
380
386
|
if (!v1 && !current) return typeof value.schema === "string" ? { value, bytes, unknown: true } : undefined;
|
|
381
387
|
const keys = current ? 1 : 0;
|
|
382
388
|
if (![5 + keys, 6 + keys].includes(Object.keys(value).length)
|
|
@@ -385,10 +391,12 @@ function decoded(file: OwnedFile): { value: Record; bytes: Buffer; unknown?: tru
|
|
|
385
391
|
const c = value.capture;
|
|
386
392
|
if (!c || typeof c !== "object" || Array.isArray(c) || Object.keys(c).length < 8 || Object.keys(c).length > 10
|
|
387
393
|
|| Object.keys(c).some(key => !["at", "agent", "event", "tool", "paths", "status", "excerpt", "bytes", "session", "subagent"].includes(key))
|
|
388
|
-
||
|
|
394
|
+
|| (v4 ? !nonClaudeRecord(c.agent, c.event) : !(HOOK_AGENTS as readonly string[]).includes(c.agent)
|
|
395
|
+
|| (c.agent === "claude" && !TRANSCRIPT_CAPTURE_EVENTS.includes(c.event)) === v3)
|
|
396
|
+
|| ![...HOOK_EVENTS, ...TRANSCRIPT_CAPTURE_EVENTS].includes(c.event)
|
|
389
397
|
|| typeof c.at !== "string" || !Number.isFinite(Date.parse(c.at)) || typeof c.excerpt !== "string"
|
|
390
398
|
|| !Array.isArray(c.paths) || c.paths.some(path => typeof path !== "string")) return undefined;
|
|
391
|
-
if (c.event === "Record" && (c.agent !== "claude" || c.subagent === true || !recordCapture(c))) return undefined;
|
|
399
|
+
if (c.event === "Record" && ((!v4 && c.agent !== "claude") || c.subagent === true || !recordCapture(c))) return undefined;
|
|
392
400
|
const normalized = normalizeCaptureFields({ agent: c.agent, event: c.event, at: c.at, paths: c.paths, excerpt: c.excerpt,
|
|
393
401
|
...(c.tool === null ? {} : { tool: c.tool }), ...(c.status === null ? {} : { status: c.status }),
|
|
394
402
|
...(c.session === undefined ? {} : { session: c.session }), ...(c.subagent === undefined ? {} : { subagent: c.subagent }) });
|
|
@@ -687,7 +695,7 @@ export async function stageHookCapture(event: string, input: unknown, options: O
|
|
|
687
695
|
: contentText;
|
|
688
696
|
// #173: attribution. Only a fixed-width hash of the native session id is kept, never the id or transcript path;
|
|
689
697
|
// a non-empty agent_id marks a subagent (or in-process teammate) event. Both are read from the already-screened input.
|
|
690
|
-
const session =
|
|
698
|
+
const session = captureSessionKey(value.session_id);
|
|
691
699
|
const subagent = typeof value.agent_id === "string" && value.agent_id.length > 0;
|
|
692
700
|
const capture = normalizeCaptureFields({ agent: options.agent ?? "claude", event, paths, status: event === "PostToolUseFailure" ? "failed" : "ok",
|
|
693
701
|
...(session ? { session } : {}), ...(subagent ? { subagent: true } : {}),
|
|
@@ -703,8 +711,10 @@ export async function stageHookCapture(event: string, input: unknown, options: O
|
|
|
703
711
|
}
|
|
704
712
|
|
|
705
713
|
/** Transcript text is screened in full before caps, then shares the ordinary durable spool. */
|
|
706
|
-
export async function stageTranscriptCapture(input: CaptureFields, options: Options, receiptIdentity?: string, onRecordDrop?: (reason: RecordDropReason) => void): Promise<PendingHookCapture | undefined> {
|
|
707
|
-
|
|
714
|
+
export async function stageTranscriptCapture(input: CaptureFields, options: Options, receiptIdentity?: string, onRecordDrop?: (reason: RecordDropReason) => void, beforePublish?: () => void): Promise<PendingHookCapture | undefined> {
|
|
715
|
+
const nativeRecord = nonClaudeRecord(input.agent, input.event);
|
|
716
|
+
if (options.policy?.host && !nativeRecord || belowFloor(options.base) || !TRANSCRIPT_CAPTURE_EVENTS.includes(input.event)
|
|
717
|
+
|| !nativeRecord && input.agent !== "claude" && !(input.agent === "jcode" && (input.event === "Title" || input.event === "Compact"))) return;
|
|
708
718
|
const cwd = realPath(options.cwd), base = canonicalPath(options.base);
|
|
709
719
|
const policy = createStandalonePolicy(configuredPolicyOptions(base, cwd, options.policy));
|
|
710
720
|
const record = input.event === "Record";
|
|
@@ -725,21 +735,22 @@ export async function stageTranscriptCapture(input: CaptureFields, options: Opti
|
|
|
725
735
|
{ excerptBytes: configured.excerptBytes, paths: configured.capturePaths, denyPaths: configured.denyPaths });
|
|
726
736
|
if (record && (capture.excerpt !== input.excerpt || JSON.stringify(capture.paths) !== JSON.stringify(input.paths ?? []))) { onRecordDrop?.("record_policy"); return; }
|
|
727
737
|
if (capture.excerpt === "[secret-screened]" || !await policy.screen({ cwd, capture })) { if (record) onRecordDrop?.("record_policy"); return; }
|
|
738
|
+
beforePublish?.();
|
|
728
739
|
return publishCapture(input.event, capture, { ...options, cwd, base }, hash(receiptIdentity === undefined ? JSON.stringify(capture) : JSON.stringify([capture, receiptIdentity])).slice(0, 32));
|
|
729
740
|
}
|
|
730
741
|
|
|
731
742
|
function publishCapture(event: string, capture: NormalizedCaptureFields, options: Options, nonce = randomBytes(16).toString("hex")): PendingHookCapture {
|
|
732
743
|
const { cwd, base } = options;
|
|
733
744
|
const scope = hookCaptureScope(cwd, base) ?? null;
|
|
734
|
-
const v3 = capture.agent !== "claude" || TRANSCRIPT_CAPTURE_EVENTS.includes(event);
|
|
735
|
-
const record: Record = { schema: FAMILY, format: v3 ? FORMAT_V3 : FORMAT, cwd, scope, root: physicalRoot(cwd), nonce, capture }, bytes = JSON.stringify(record);
|
|
745
|
+
const v4 = nonClaudeRecord(capture.agent, event), v3 = capture.agent !== "claude" || TRANSCRIPT_CAPTURE_EVENTS.includes(event);
|
|
746
|
+
const record: Record = { schema: FAMILY, format: v4 ? FORMAT_V4 : v3 ? FORMAT_V3 : FORMAT, cwd, scope, root: physicalRoot(cwd), nonce, capture }, bytes = JSON.stringify(record);
|
|
736
747
|
if (Buffer.byteLength(bytes) > RECORD_BYTES) throw new Error("hook record bound");
|
|
737
748
|
const dir = directory(base), writing = join(dir, ".writing"); privateDirectory(dir); privateDirectory(writing);
|
|
738
749
|
let destination = dir, deferred = false, backlog = false;
|
|
739
750
|
const budget = maintenanceBudget(), incomingBytes = Buffer.byteLength(bytes), cwdHash = hash(cwd);
|
|
740
751
|
if (event !== "SessionStart") cleanStaleWriting(writing, budget);
|
|
741
752
|
const withinShare = (rows: ReturnType<typeof entries>, maximum: number) => rows.filter(row => namePattern.exec(row.name)?.[2] === cwdHash).length < maximum / 4;
|
|
742
|
-
const name = `${v3 ? PREFIX_V3 : PREFIX}${cwdHash}-${scope ?? "0".repeat(64)}-${nonce}.json`;
|
|
753
|
+
const name = `${v4 ? PREFIX_V4 : v3 ? PREFIX_V3 : PREFIX}${cwdHash}-${scope ?? "0".repeat(64)}-${nonce}.json`;
|
|
743
754
|
let activeInventory: ReturnType<typeof entries> | undefined, reserveInventory: ReturnType<typeof entries> | undefined;
|
|
744
755
|
if (TRANSCRIPT_CAPTURE_EVENTS.includes(event)) {
|
|
745
756
|
// Transcript cursor recovery can repeat a deterministic publication. An already
|
|
@@ -757,7 +768,7 @@ function publishCapture(event: string, capture: NormalizedCaptureFields, options
|
|
|
757
768
|
if (existing.initial.size !== incomingBytes) continue;
|
|
758
769
|
const held = Buffer.alloc(incomingBytes);
|
|
759
770
|
if (readSync(existing.fd, held, 0, held.length, 0) === held.length && owns(existing) && held.equals(Buffer.from(bytes))) {
|
|
760
|
-
return { name, cwd, receipt: hash(bytes), backlog: true, ...(capacity ? { deferred: true as const } : {}) };
|
|
771
|
+
return { name, cwd, receipt: hash(bytes), backlog: true, duplicate: true, ...(capacity ? { deferred: true as const } : {}) };
|
|
761
772
|
}
|
|
762
773
|
} catch { /* Changed or unavailable evidence is not acknowledgement. */ }
|
|
763
774
|
finally { if (existing) closeSync(existing.fd); }
|
package/src/hook-transcript.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { captureSessionKey } from "./memory/capture-input.ts";
|
|
1
2
|
import { parseRecordLines, RECORD_INPUT_BYTES, type ParsedRecordTurn, type RecordDropReason } from "./hook-record.ts";
|
|
2
3
|
import { stripPrivateSpans } from "./memory/private-spans.ts";
|
|
3
4
|
import { assertFormatFloor } from "./memory/formats.ts";
|
|
@@ -126,7 +127,7 @@ export async function scanHookTranscriptTail(input: unknown, options: Options):
|
|
|
126
127
|
if (!await policy.screen(value)) return;
|
|
127
128
|
const captureRecords = recordsEnabled(base, cwd)
|
|
128
129
|
&& !(typeof value.agent_id === "string" && value.agent_id.length > 0);
|
|
129
|
-
const session =
|
|
130
|
+
const session = captureSessionKey(value.session_id)!;
|
|
130
131
|
if (lstatSync(value.transcript_path).isSymbolicLink()) throw new Error("transcript unavailable");
|
|
131
132
|
const transcript = realPath(value.transcript_path);
|
|
132
133
|
// Parent aliases must not hide a configured deny path behind an allowed spelling.
|
|
@@ -156,6 +157,7 @@ export async function scanHookTranscriptTail(input: unknown, options: Options):
|
|
|
156
157
|
const after = fstatSync(fd), live = lstatSync(value.transcript_path);
|
|
157
158
|
if (length !== bytes.length || after.size < stat.size || live.dev !== stat.dev || live.ino !== stat.ino || realPath(value.transcript_path) !== transcript) return;
|
|
158
159
|
let start = 0, stopReason: HookTranscriptProgress["stopReason"];
|
|
160
|
+
const recordMetrics = { recordValidRecords: 0, recordBasisRecords: 0, recordUnverifiedRecords: 0 };
|
|
159
161
|
// ponytail: the two-record cap is per native message.id within this scan only; no durable count.
|
|
160
162
|
// A crash after staging but before cursor save has the summaries' duplicate window.
|
|
161
163
|
// Upgrade to a msgid+ordinal receipt if the AC6 live week demonstrates duplicates.
|
|
@@ -191,6 +193,12 @@ export async function scanHookTranscriptTail(input: unknown, options: Options):
|
|
|
191
193
|
if (records) {
|
|
192
194
|
for (const [reason, count] of Object.entries(records.parsed.drops)) dropRecord(reason as RecordDropReason, count!);
|
|
193
195
|
if (records.parsed.incomplete) { stopReason = "deadline"; break; }
|
|
196
|
+
if (records.messageId && records.at) {
|
|
197
|
+
const admitted = records.parsed.records.slice(0, Math.max(0, 2 - (recordCounts.get(records.messageId) ?? 0)));
|
|
198
|
+
recordMetrics.recordValidRecords += admitted.length;
|
|
199
|
+
recordMetrics.recordBasisRecords += admitted.filter(record => record.text.includes("basis:")).length;
|
|
200
|
+
recordMetrics.recordUnverifiedRecords += admitted.filter(record => record.text.startsWith("?")).length;
|
|
201
|
+
}
|
|
194
202
|
if (records.messageId && records.at) for (const record of records.parsed.records) {
|
|
195
203
|
const count = recordCounts.get(records.messageId) ?? 0;
|
|
196
204
|
if (count >= 2) { dropRecord("record_count"); continue; }
|
|
@@ -262,7 +270,7 @@ export async function scanHookTranscriptTail(input: unknown, options: Options):
|
|
|
262
270
|
assertFormatFloor(base, "hook-spool");
|
|
263
271
|
db.query("UPDATE cursor SET offset=?,dev=?,ino=?,size=?,title=?,at=?,skipping=? WHERE id=1").run(cursor.offset + start, String(stat.dev), String(stat.ino), stat.size, cursor.title, cursor.at, cursor.skipping);
|
|
264
272
|
db.run("COMMIT");
|
|
265
|
-
return { offset: cursor.offset + start, ...(stopReason ? { stopReason } : {}) };
|
|
273
|
+
return { offset: cursor.offset + start, ...recordMetrics, ...(stopReason ? { stopReason } : {}) };
|
|
266
274
|
} finally {
|
|
267
275
|
try { if (db) { try { db.run("ROLLBACK"); } catch { /* Already committed. */ } db.close(); } } finally { closeSync(fd); }
|
|
268
276
|
}
|