@staix/agent-mem 0.23.1 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +14 -4
  3. package/package.json +1 -1
  4. package/src/brief-cache.ts +54 -0
  5. package/src/brief-capture.ts +82 -0
  6. package/src/brief-curated-native.ts +32 -0
  7. package/src/brief-curated.ts +65 -0
  8. package/src/cli.ts +1 -0
  9. package/src/curated-brief-cache.ts +29 -0
  10. package/src/hook-contract.ts +6 -2
  11. package/src/hook-record.ts +22 -2
  12. package/src/hook-spool-replay.ts +8 -1
  13. package/src/hook-spool.ts +2 -2
  14. package/src/hook-transcript.ts +10 -2
  15. package/src/hooks.ts +65 -14
  16. package/src/index.ts +5 -1
  17. package/src/memory/candidate-pending.ts +6 -2
  18. package/src/memory/candidates.ts +4 -2
  19. package/src/memory/capture-input.ts +7 -0
  20. package/src/memory/capture-plan.ts +10 -0
  21. package/src/memory/capture.ts +78 -8
  22. package/src/memory/curated-cache-state.ts +35 -0
  23. package/src/memory/formats.ts +6 -0
  24. package/src/memory/generation-index.ts +2 -0
  25. package/src/memory/generation-sync.ts +3 -0
  26. package/src/memory/metrics.ts +7 -1
  27. package/src/memory/migrate.ts +7 -1
  28. package/src/memory/public-prune-activation.ts +4 -1
  29. package/src/memory/public-prune-advance.ts +2 -0
  30. package/src/memory/reader-lease.ts +5 -3
  31. package/src/memory/record-instruction.ts +26 -0
  32. package/src/memory/record-variant-log.ts +90 -0
  33. package/src/memory/shard-migration.ts +4 -1
  34. package/src/memory/shard-sync.ts +3 -0
  35. package/src/memory/store.ts +131 -2
  36. package/src/memory/sync-placement-activation.ts +11 -3
  37. package/src/memory/sync-placement-transport.ts +3 -0
  38. package/src/memory/sync.ts +3 -2
  39. package/src/session-brief-worker.ts +13 -2
  40. package/src/session-brief.ts +130 -70
  41. package/src/ui/plugin.ts +104 -30
  42. package/src/ui/snapshot-cache.ts +141 -0
  43. package/src/ui/snapshot-revision.ts +87 -0
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-mem",
3
- "version": "0.23.1",
3
+ "version": "0.24.0",
4
4
  "description": "Bounded project memory tools and seven deterministic capture hooks, without a resident worker.",
5
5
  "mcpServers": {
6
6
  "agent-mem": {
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Curated memory with append-only JSONL logs, a derived SQLite index, short- and long-term tiers, a typed graph, goals with leases, and git sync between machines. Extracted from [agent-hub](https://github.com/STAIxBWLB/agent-hub), with compatible storage and entry IDs.
4
4
 
5
5
  <!-- facts:version -->
6
- Version: 0.23.1. Requires Bun 1.4.2 or later; no runtime dependencies.
6
+ Version: 0.24.0. Requires Bun 1.4.2 or later; no runtime dependencies.
7
7
  <!-- /facts:version -->
8
8
 
9
9
  ## Quick start
@@ -322,7 +322,7 @@ Known-format pending records whose cwd is positively absent can retire after one
322
322
 
323
323
  If both replayable tiers fill, or SessionStart's reserve alone fills, the current event can be dropped. The library receipt reports `dropped: true`, `dropReason: "spool_full"`, `dropCount: 1`, and the metric reports `captureDrops: 1` with `captureDropReason: "spool_full"`. Non-SessionStart native stdout remains empty. Native SessionStart emits only `hookSpecificOutput`, placing a bounded notice with reason counts from the last 200 metric samples after its untrusted-data header inside `additionalContext`, not in new top-level fields. These are rolling-window counts, not all-time totals. The header stays before all memory data even when the brief is otherwise unavailable; the optional trusted Record instruction precedes it. The combined instruction and context stay within the same byte bound. Finite-capacity and retirement losses are observable rather than reported as captured. Exact-once replay applies to positively bound retained records that can progress; unlimited lossless intake is not promised. Soft-cap overshoot, unpublished `.writing/` leftovers and power-loss durability retain the [contracts ceiling](docs/contracts.md#p3-hook-and-native-intake-boundaries-13).
324
324
 
325
- SessionStart prioritizes known open work and defers unsafe curated refresh with a fixed coverage reason. Native capture reads the newest 128 rows through an existing read-only time index and marks excluded older history partial, instead of rejecting a larger store. It never creates schema/FTS or repairs indexes. Missing/locked/incompatible sources are explicitly unavailable. The standalone `sessionStartBrief()` retains all its original sources. Recovery failure cannot discard a computed brief. Work, reader-lease and capture host ports use zero busy-wait and cooperative deadline checks; ordinary library callers retain their original defaults, including 3,000 ms waits. No watcher, resident worker, model/network call, embedding job or vault access is added. Host policy callbacks remain unsupported by `runHook`, while the standalone brief composes them normally.
325
+ SessionStart prioritizes known open work. Native curated notes use a private prebuilt section prepared after curated writes and sync, with current policy screening before work and whole-line output after work. Admission requires all writers to be upgraded and a person-raised `home` or `curated` floor of 0.24.0 or later; code never changes that floor. Below it, native curated stays deferred. Migration and profile/selector changes invalidate caches without rebuilding; a later curated write or explicit trigger prepares them. Only an unmarked person `amem brief` or an explicit off-hook host call to the root export `prepareCuratedBriefCache(base, project)` prepares a quiet project cache. The export is a write: it opens one selected store, reads at most four 32-row pages and writes one file up to 32 KiB. MCP, agent-marked CLI reads and library `sessionStartBrief()` never prepare it. A project with no curated writes and neither explicit trigger keeps native curated unavailable; mutations rebuild only their touched projects after invalidating old derived files. Missing and stale files report `curated cache missing` or `curated cache stale` without rebuilding. Profile/generation binding, selected-note expiry and a 24-hour age cap bound freshness; see [the curated cache contract](docs/contracts.md#r2-hook-budget-150-mb-ceiling-per-runner-baseline-regression-300-ms-maximum-228). Native capture uses the prebuilt Record/Recap/Compact section; raw chronological history remains a library source. Neither native cache path creates schema/FTS or repairs indexes. Missing/locked/incompatible sources are explicitly unavailable. The standalone `sessionStartBrief()` retains all its original sources. Recovery failure cannot discard a computed brief. Work and reader-lease host ports use zero busy-wait and cooperative deadline checks; ordinary library callers retain their original defaults, including 3,000 ms waits. No watcher, resident worker, model/network call, embedding job or vault access is added. Host policy callbacks remain unsupported by `runHook`, while the standalone brief composes them normally.
326
326
 
327
327
  SessionStart admits directly to the reserve with at most 32 metadata entries and performs no active-tier scan or replay. Both tiers use per-cwd fair shares (64 active records, 8 reserve records), grouping together all HOME/scope variants of a cwd. Admission can retire native records from an overrepresented cwd, counting each loss as `scope_capacity` before removal. Accepted summaries survive same-cwd pressure; new summaries backpressure without advancing their transcript cursor. A fully verified foreign all-summary inventory can use counted `summary_capacity` eviction; otherwise it stays pending for replay. All admission maintenance shares a 32-file/256 KiB body-read bound; unknown/newer schemas retain their seven-day protection. Non-SessionStart hooks maintain and drain both tiers. This is bounded reserve admission, not O(1) accounting; an atomic slot-reservation protocol is the upgrade. Parent brief storage still contains synchronous filesystem/SQLite work between cooperative deadline checks; asynchronous/deadline-aware storage remains the upgrade, not a larger handler limit. The R2 limits remain 150 ms p95, with a 140 ms handler budget; the absolute 100 MB peak RSS was retired by #228 for a 150 MB per-invocation ceiling plus a per-runner baseline regression gate. Functional tests construct a programmatic host-only deadline; the actual executable exposes no environment or CLI deadline extension. Its exec-only boot-clock handoff can only shorten the deadline and is cleared before hook import. Dedicated budget scripts retain the actual CLI, original sample counts, cold attempt 0 and timeout/reaper assertions. The [P3 receipt](docs/p3-hook-budget-2026-10-23.md) identifies prior-head evidence separately from current acceptance; the current rework has no newly claimed both-OS green CI result.
328
328
 
@@ -432,7 +432,7 @@ Only explicit serialized expiry is eligible: a note's `expires`, or an exact dem
432
432
 
433
433
  Standalone CLI prune is local-only, even over a synced target. No `--policy-free` escape enables public prune. A later policy-aware host integration must authenticate intent and attest the exact public payload and current policy revision; only verified public target/basis provenance may sync. Local masks, plans, journals, caches and sidecars never sync. Generation sync refuses public or unknown remote visibility. An interrupted apply resumes the same durable row IDs and exact partial tail; it never rewrites complete lines.
434
434
 
435
- Candidate/counter sidecars are not migrated. `amem review list --kind memory` lists the new machine-local memory candidates under a selected generation; the default legacy review list retains its generation refusal. General memory candidates can be accepted with `review accept --kind memory` into the current project store after current standalone screening; older correction/fail candidates still require profile-aware host integration for generation acceptance.
435
+ Candidate/counter sidecars are not migrated. `amem review list` lists machine-local candidates under the selected generation. General memory, correction and fail candidates can be accepted into the selected project store after current standalone screening and applicable target checks.
436
436
 
437
437
  Real migration remains blocked until the separately reviewed generation-capable amem release and exact-pinned agent-hub integration are installed and their running stores prove the same home/G/selector revision. Synthetic cross-writes and exact prune readbacks precede separately confirmed real migration; known local handles must be quiesced/closed and reopened through the supported session-preserving lifecycle. Release, deployment, real migration, host evidence/capture receipts and real multi-machine sync are not established by these source changes. Deactivation omits generation-only notes/prunes from the v1 view and is not a lossless rollback.
438
438
 
@@ -458,7 +458,7 @@ Library callers open an already sealed shard directly with `openShardStore({ hom
458
458
 
459
459
  Dry run reports v1, generation-owned/local, prune and translated-prune counts, plus refused relations. A private-to-private replacement across projects refuses before effects. A shared entry superseded by a private entry also refuses: the dry run reports `shared superseded by private: N` and entry IDs only. Un-supersede it, or promote the replacement to shared, then rerun. `ponytail:` supporting that direction requires a body-free lifecycle witness; revisit when a read-only dry run on a copy of the person's home reports a nonzero count, never by probing or migrating the live home here. Private-to-shared replacements remain supported. See [the T2 contract](docs/curated-shard-migration.md).
460
460
 
461
- After a split, ordinary generation `amem migrate` modes (including `--deactivate`) refuse without changing the selector. Use `amem migrate --shards --resume` to finish the split. General memory candidates can be accepted with `review accept --kind memory` into the selected project shard after standalone screening; correction/fail candidates still refuse pending shard-aware host integration. Default `prune` selects the current project's shard; use `amem prune --user --cutoff <UTC> --dry-run` and `amem prune --user --apply --plan <file>` for shared/user entries. The current project, reader-admission and split-marker checks remain in force.
461
+ After a split, ordinary generation `amem migrate` modes (including `--deactivate`) refuse without changing the selector. Use `amem migrate --shards --resume` to finish the split. General memory, correction and fail candidates can be accepted into the selected project shard after standalone screening and applicable target checks. Default `prune` selects the current project's shard; use `amem prune --user --cutoff <UTC> --dry-run` and `amem prune --user --apply --plan <file>` for shared/user entries. The current project, reader-admission and split-marker checks remain in force.
462
462
 
463
463
  A native shard crash tail is left to its original writer's recovery. Migration checks planned copy tails and translation-receipt tails before changing activation; matching copies finish append-only and mismatches give an inspection hint. Dangling lifecycle/suggestion metadata is carried as ids-only user data and counted, so a target arriving later retains its intent. Cross-private replacements have their own ids-only count and the un-supersede/promote-to-shared remedy. During interruption the catalog keeps capture information available while `curatedEntries` is `null` and `curatedAvailable` is `false`; its cached capture counts may still lag.
464
464
 
@@ -571,8 +571,18 @@ Search gives these events the existing 1.25 conversation weight and session grou
571
571
 
572
572
  ## Assistant records (#313)
573
573
 
574
+ Native SessionStart (`startup` and `compact`) preloads and screens the capture cache before work can spend the deadline, reserving only the newest permitted main-session Recap/Compact line. Work consumes the remaining pool. At the existing capture output position, up to five whole canonical Records use the then-remaining bytes; the reserved newest summary follows Records, and a second summary may use only bytes left after Records. The library brief follows the same reservation and output order. A line that cannot fit whole after the header and Record instruction is skipped and marks capture partial; budget allocation never truncates a display line or Record. The library and CLI still query capture directly and retain chronological raw-row fill after the preferred rows.
575
+
576
+ Stop/SessionEnd Record/summary commits and hook-spool replay prepare `brief-capture.json` (0600) in the project's machine directory. It preserves up to five canonical Records before up to two screened main-session summaries, including the current session, with their display values and the committed capture row watermark. Ordinary raw recent captures are excluded. Record commits refresh the cache too. The native read is one byte-capped file read, re-screens full source values under current policy, and never opens a capture database or rebuilds the cache. Missing or unreadable caches report `capture: capture cache missing`; total context bytes and native deadlines are unchanged. A busy snapshot can leave the cache missing until a later Record or summary commit. Refs #337.
577
+
574
578
  Since 0.23.0, native Claude SessionStart can prepend the package-owned `RECORD_INSTRUCTION` before the untrusted memory header, including on resume. Its three lines occupy 331 UTF-8 bytes, or 332 with the separator, reserved from the existing 1,200-byte context budget. The metric reports the actual emitted `recordInstructionBytes` and `recordInstructionEstimatedTokens` (83 when emitted, an approximation). The full block is omitted when it cannot fit; it never turns a failed or timed-out hook into valid context. Set `records: false` in the home's `amem.config.json` or the repository's `.amem/config` to disable the instruction and new extraction; false wins across both files.
575
579
 
580
+ For the #313 AC6 comparison week (#325), the person can create a private `record-instruction.json` in the memory home containing `{"instruction":"alternate"}` (`a`, `b` and `alternate` are the only values). This is separate from `amem.config.json`, whose `records` key remains boolean-only. The file must be regular, single-link, owned by the current uid and not group- or other-writable (`mode & 022 == 0`): normal 0644 is accepted; 0664 and 0666 are rejected. Core never writes the selection file. Missing means A; an invalid, unreadable, group/other-writable, oversized, foreign-owned or linked file also means A, with numeric `recordInstructionInvalid: 1` in the hook metric, without refusing the hook. Existing 0.23.x readers ignore this file and retain A. B uses purpose framing with a `basis:` hint and `?` for unverified text. Both reserve 332 bytes before the untrusted header; A emits 332 bytes including the separator, B emits 331 (about 83 estimated tokens each). Alternate uses even/odd parity of the last hex digit of the existing 16-character capture session hash for A/B, so resume keeps the same variant without exposing a raw session id. A missing or invalid session id falls back to A rather than guessing parity; metrics record that resolved A choice. `records: false` in either configuration file still wins. `RECORD_INSTRUCTION` remains the exact A text; `RECORD_INSTRUCTION_B`, `RECORD_INSTRUCTIONS`, `readRecordInstruction`, `captureSessionKey`, `recordInstructionVariant` and their mode/variant types let hosts reuse the package-owned text and selection rule. `basis:` and `?` remain ordinary Record text, with no grammar or capture-field change. The person compares the variants during the live week before deciding the default. [Record variant measurements](docs/bench/record-instruction-variants.md) records the public fixture protocol and its evidence status.
581
+
582
+ The live-week counters use a separate `record-variants.jsonl` beside the existing resource metrics. Each row contains `at`, the hook `event`, resolved `variant` (`a` or `b`) and allowlisted numeric Record fields; no Record text is written. Observations use single short `O_APPEND` writes and 0600 creation, retaining eight days within a 4 MiB hard cap. Capture rows, spool events/status values and the general resource metrics retention are unchanged. One session is one SessionStart with source `startup` or `resume`, including an omitted instruction; `recordInstructionEmitted` and `recordEnabled` distinguish exposure and opt-out. One turn is one Stop invocation. Stop/SessionEnd report eligible parsed Record counts, the number containing `basis:` and the number starting with `?`; these are parsing observations, not durable-publication counts. SessionEnd contributes Records but no Stop-turn denominator. An unavailable scan leaves counts unknown, and the report never converts missing counters into zero. SessionStart reports actual emitted brief bytes including the instruction. Capacity trims leave 1 MiB of headroom (4 MiB trigger, 3 MiB retained). Incomplete or unknown transcript scans are excluded from exact Stop-turn observations; the full-window exact share stays null until coverage is complete.
583
+
584
+ Run `bun scripts/report-record-variants.ts --input /path/to/memory/record-variants.jsonl` read-only to report sessions, Records/session, the share of Stop turns with a Record, basis and uncertainty shares, and mean brief bytes with explicit denominators. Missing Stop scan counters produce an incomplete/null exact turn share and a separate observed share. The bounded first-line probe triggers an age rewrite only past nine days, keeping eight days (daily hysteresis). Ordinary appends never read the tail or rewrite it. When the 4 MiB cap forces older observations out, numeric `capTrimmed` markers make `window.capForcedTrim` true and coverage incomplete; do not treat a capped window as a complete AC6 week. The general metrics file retains its existing 64 KiB trigger and newest-200 discipline.
585
+
576
586
  At Stop/SessionEnd, complete native assistant text can yield `Record` capture events through the existing transcript scan. `parseRecordLines`, `RECORD_INSTRUCTION` and `recordsEnabled(base, cwd?)` are public root exports; hosts check `recordsEnabled` before emitting the instruction or capturing parsed Records. The canonical grammar is maintained in `src/hook-record.ts`. The parser checks format and explicit text exclusions; hosts still apply their capture privacy policy before storage. It accepts the five kinds decision/fix/fail/contract/finding, repository-relative anchors and at most 300 text characters, excludes fenced/quoted examples, and requires the fix/fail relation. Missing native row time or stable `message.id` refuses extraction. At most two syntactically valid record lines are considered per stable message per scan call, with no persisted count. Whole records are declined on a denied anchor, policy refusal, truncation or redaction; no partial record is saved.
577
587
 
578
588
  Records stay machine-local capture, not curated evidence or review candidates. They reuse Title/Recap/Compact staging, deterministic receipts and replay, with canonical line content and the native row timestamp; no Record-only receipt or capture-row schema is added. Source-row privacy flags are screened before capture, and replay refuses to clip or remove anchors from a pending Record when caps change. A slow replay opportunity cannot strand the second Record in the same transcript row. A crash after staging but before cursor save retains the existing duplicate window. A message-ID/ordinal receipt is a future upgrade if the AC6 duplicate experiment requires it. Record-to-candidate conversion and other ingest/Jcode paths remain outside this change; AC6 and real-home rollout are person-run checks.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.23.1",
3
+ "version": "0.24.0",
4
4
  "description": "Curated, shared memory for coding agents: append-only logs, a derived index, tiers and a typed graph.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,54 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, openSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ /** Shared bounded transport for prebuilt brief sections; never a database or a refresh on read. */
6
+ export const BRIEF_CACHE_BYTES = 32 * 1024;
7
+ export interface BriefCacheBinding { directory: string; project: string; section: "capture" | "curated" }
8
+ export interface BriefCacheRow { source: unknown; data: unknown; partial: boolean }
9
+ export interface CuratedBriefMetadata { builtAt: number; binding: string; expiresAt: number | null }
10
+ export interface BriefCache {
11
+ schema: "agent-mem.brief-cache/v1"; project: string; section: BriefCacheBinding["section"];
12
+ builtThrough: number; partial: boolean; rows: BriefCacheRow[];
13
+ curated?: CuratedBriefMetadata;
14
+ }
15
+ export function briefCacheFile(binding: BriefCacheBinding): string { return join(binding.directory, `brief-${binding.section}.json`); }
16
+
17
+ export function readBriefCache(binding: BriefCacheBinding): BriefCache | undefined {
18
+ let fd: number | undefined;
19
+ try {
20
+ fd = openSync(briefCacheFile(binding), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
21
+ const stat = fstatSync(fd);
22
+ if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid?.() || stat.size < 1 || stat.size > BRIEF_CACHE_BYTES || (stat.mode & 0o077) !== 0) return;
23
+ const bytes = Buffer.alloc(BRIEF_CACHE_BYTES + 1);
24
+ const size = readSync(fd, bytes, 0, bytes.length, 0); // one bounded read, including an oversize sentinel
25
+ const after = fstatSync(fd);
26
+ if (size !== stat.size || size > BRIEF_CACHE_BYTES || stat.size !== after.size || stat.mtimeMs !== after.mtimeMs || stat.ctimeMs !== after.ctimeMs) return;
27
+ const cache = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, size))) as BriefCache;
28
+ if (cache.schema !== "agent-mem.brief-cache/v1" || cache.project !== binding.project || cache.section !== binding.section
29
+ || !Number.isSafeInteger(cache.builtThrough) || cache.builtThrough < 1 || typeof cache.partial !== "boolean"
30
+ || (cache.curated !== undefined && (cache.section !== "curated" || !cache.curated || !Number.isFinite(cache.curated.builtAt)
31
+ || typeof cache.curated.binding !== "string" || !cache.curated.binding
32
+ || !(cache.curated.expiresAt === null || Number.isFinite(cache.curated.expiresAt))))
33
+ || !Array.isArray(cache.rows) || cache.rows.length > 8
34
+ || cache.rows.some(row => !row || typeof row.partial !== "boolean" || row.source === undefined || row.data === undefined)) return;
35
+ return cache;
36
+ } catch { return undefined; }
37
+ finally { if (fd !== undefined) closeSync(fd); }
38
+ }
39
+
40
+ /** Invalidate under the source store's write transaction, before a summary can commit. */
41
+ export function invalidateBriefCache(binding: BriefCacheBinding): void { rmSync(briefCacheFile(binding), { force: true }); }
42
+
43
+ /** Atomic private replacement; callers serialize publication with their source-store writers. Refuse a replacement when a newer committed-row watermark is already visible. */
44
+ export function writeBriefCache(binding: BriefCacheBinding, cache: BriefCache): void {
45
+ const text = JSON.stringify(cache) + "\n";
46
+ if (Buffer.byteLength(text) > BRIEF_CACHE_BYTES) throw new Error("brief cache byte bound");
47
+ const file = briefCacheFile(binding), temporary = `${file}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
48
+ try {
49
+ writeFileSync(temporary, text, { mode: 0o600, flag: "wx" });
50
+ const prior = readBriefCache(binding);
51
+ if (prior && prior.builtThrough > cache.builtThrough) return;
52
+ renameSync(temporary, file);
53
+ } finally { rmSync(temporary, { force: true }); }
54
+ }
@@ -0,0 +1,82 @@
1
+ import { parseRecordLines } from "./hook-record.ts";
2
+ import type { CaptureRow, CaptureStore } from "./memory/capture.ts";
3
+ import { configuredPolicyOptions } from "./memory/config.ts";
4
+ import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
5
+ import { BRIEF_CACHE_BYTES, writeBriefCache, type BriefCacheRow } from "./brief-cache.ts";
6
+
7
+ /** Bound display values only after complete-row policy; flatten controls before serialization. */
8
+ export function displayText(text: string, maximum: number): { text: string; partial: boolean } {
9
+ const flattened = text.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, " ");
10
+ let out = "", bytes = 0;
11
+ for (const character of flattened) {
12
+ const size = Buffer.byteLength(character);
13
+ if (bytes + size > maximum) return { text: out, partial: true };
14
+ out += character; bytes += size;
15
+ }
16
+ return { text: out, partial: flattened !== text };
17
+ }
18
+ export function captureDisplay(row: CaptureRow): { data: unknown; partial: boolean } {
19
+ const excerpt = displayText(row.excerpt, 240), event = displayText(row.event, 64);
20
+ const paths = row.paths.slice(0, 2).map(path => displayText(path, 80));
21
+ return { data: { id: row.id, at: row.at, event: event.text, paths: paths.map(path => path.text), excerpt: excerpt.text },
22
+ partial: excerpt.partial || event.partial || row.paths.length > paths.length || paths.some(path => path.partial) };
23
+ }
24
+ /** Preserve #313 whole canonical Records before summaries. */
25
+ export function recordDisplay(row: CaptureRow): { data: unknown; partial: boolean } | undefined {
26
+ const parsed = parseRecordLines(row.excerpt), record = parsed.records[0];
27
+ if (!record || parsed.records.length !== 1 || Object.keys(parsed.drops).length || record.line !== row.excerpt
28
+ || JSON.stringify(record.anchors) !== JSON.stringify(row.paths)) return;
29
+ return { data: { event: "Record", paths: record.anchors, excerpt: record.line }, partial: false };
30
+ }
31
+
32
+ export interface CaptureBriefOptions { base: string; project: string; cwd: string; builtThrough: number; policy?: StandalonePolicyOptions }
33
+ /** Reuse the library's #201 summary query, full-row screen, two-summary selection and display, with existing Record priority. */
34
+ export function buildCaptureBriefCache(store: CaptureStore, options: CaptureBriefOptions): void {
35
+ if (options.policy?.host) throw new Error("prebuilt capture requires synchronous standalone screening");
36
+ const policy = createStandalonePolicy(configuredPolicyOptions(options.base, options.cwd, options.policy));
37
+ store.withBriefCaptureSnapshot((summaries, builtThrough) => {
38
+ const records = store.readBriefRecords(), recordRows: BriefCacheRow[] = [], summaryRows: BriefCacheRow[] = [];
39
+ const watermark = Math.max(options.builtThrough, builtThrough);
40
+ let partial = summaries.partial || records.partial, count = 0;
41
+ let storedBytes = Buffer.byteLength(JSON.stringify({ schema: "agent-mem.brief-cache/v1", project: options.project,
42
+ section: "capture", builtThrough: watermark, partial: false, rows: [] })) + 1;
43
+ const keep = (target: BriefCacheRow[], source: CaptureRow, shown: { data: unknown; partial: boolean }) => {
44
+ const row = { source, ...shown }, bytes = Buffer.byteLength(JSON.stringify(row)) + (count ? 1 : 0);
45
+ const displayBytes = Buffer.byteLength(JSON.stringify({ section: "capture", evidence: false, data: shown.data }));
46
+ if (displayBytes > 768 || storedBytes + bytes > BRIEF_CACHE_BYTES) { partial = true; return false; }
47
+ target.push(row); count++; storedBytes += bytes; partial ||= shown.partial; return true;
48
+ };
49
+ // Keep the two summary candidates independently of Record/context allocation. The reader alone owns the brief pool.
50
+ let selectedSummaries = 0;
51
+ for (const source of summaries.rows) {
52
+ if (source.project !== options.project || source.subagent === true || !policy.screenStandalone(source)) continue;
53
+ if (selectedSummaries >= 2) break;
54
+ const shown = captureDisplay(source);
55
+ if (!policy.screenStandalone(shown.data)) continue;
56
+ selectedSummaries++; keep(summaryRows, source, shown);
57
+ }
58
+ let selectedRecords = 0;
59
+ for (const source of records.rows) {
60
+ if (source.project !== options.project || source.subagent === true) continue;
61
+ if (selectedRecords >= 5) { partial = true; break; }
62
+ if (!policy.screenStandalone(source)) continue;
63
+ const shown = recordDisplay(source);
64
+ if (!shown || !policy.screenStandalone(shown.data)) continue;
65
+ if (keep(recordRows, source, shown)) selectedRecords++;
66
+ }
67
+ writeBriefCache({ directory: store.dir, project: options.project, section: "capture" }, {
68
+ schema: "agent-mem.brief-cache/v1", project: options.project, section: "capture", builtThrough: watermark, partial,
69
+ rows: [...recordRows, ...summaryRows],
70
+ });
71
+ });
72
+ }
73
+
74
+ /** Cache files are untrusted derived data: require the same project and canonical summary display. */
75
+ export function validCachedCapture(row: BriefCacheRow, project: string): boolean {
76
+ const source = row.source as CaptureRow | null;
77
+ if (!source || source.project !== project || source.subagent === true || !["Record", "Recap", "Compact"].includes(source.event)
78
+ || !Number.isSafeInteger(source.id) || source.id < 1 || typeof source.at !== "string" || !Number.isFinite(Date.parse(source.at))
79
+ || typeof source.excerpt !== "string" || !Array.isArray(source.paths) || source.paths.some(value => typeof value !== "string")) return false;
80
+ const shown = source.event === "Record" ? recordDisplay(source) : captureDisplay(source);
81
+ return !!shown && JSON.stringify(shown.data) === JSON.stringify(row.data) && shown.partial === row.partial;
82
+ }
@@ -0,0 +1,32 @@
1
+ import { lstatSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { briefCacheFile, readBriefCache, type BriefCache } from "./brief-cache.ts";
4
+ import { curatedCacheFresh } from "./brief-curated.ts";
5
+ import { assertFormatFloor, formatFloorAtLeast, FormatFloorError } from "./memory/formats.ts";
6
+ import { captureShardDir } from "./memory/shard.ts";
7
+
8
+ // ponytail: #322 is planned for 0.24.0. If that release ships before this change,
9
+ // the release PR must move this constant to the first release containing invalidation.
10
+ export const CURATED_CACHE_MIN_READER = "0.24.0";
11
+
12
+ /**
13
+ * ponytail: a missed invalidation path can serve at most 24 hours of stale curated data.
14
+ * Upgrade to the bounded authoritative manifest frontier if real missed paths justify it.
15
+ * No writer or reader raises the person-owned floor.
16
+ */
17
+ export function readCuratedBriefCache(options: { base: string; project: string; profile: string; supportingRelease: string; deferredReason: string; now: number }): { cache?: BriefCache; reason?: string } {
18
+ try {
19
+ assertFormatFloor(options.base, "curated");
20
+ if (!formatFloorAtLeast(options.base, "curated", options.supportingRelease)) return { reason: options.deferredReason };
21
+ let machine: unknown;
22
+ try { machine = JSON.parse(readFileSync(join(options.base, "machine.json"), "utf8")).id; } catch { /* No machine means no prebuilt section. */ }
23
+ if (typeof machine !== "string" || !/^[a-f0-9]{16}$/.test(machine)) return { reason: "curated cache missing" };
24
+ const binding = { directory: captureShardDir(options.base, options.project, machine), project: options.project, section: "curated" as const };
25
+ if (!lstatSync(briefCacheFile(binding), { throwIfNoEntry: false })) return { reason: "curated cache missing" };
26
+ const cache = readBriefCache(binding);
27
+ return cache && curatedCacheFresh(cache, options.profile, options.now) ? { cache } : { reason: "curated cache stale" };
28
+ } catch (error) {
29
+ if (error instanceof FormatFloorError) return { reason: error.code === "format_floor" ? "floor: upgrade amem" : "floor: amem doctor" };
30
+ return { reason: "curated cache stale" };
31
+ }
32
+ }
@@ -0,0 +1,65 @@
1
+ import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
2
+ import { configuredPolicyOptions } from "./memory/config.ts";
3
+ import type { MemoryStore, View } from "./memory/store.ts";
4
+ import { displayText } from "./brief-capture.ts";
5
+ import { BRIEF_CACHE_BYTES, writeBriefCache, type BriefCacheRow } from "./brief-cache.ts";
6
+
7
+ const PAGE_ROWS = 32, MAX_PAGES = 4, SECTION_RECORDS = 4, RECORD_BYTES = 768, MAX_AGE = 24 * 60 * 60 * 1000;
8
+
9
+ /** Canonical curated display shared by the library brief and snapshot writer. */
10
+ export function noteDisplay(view: View): { data: unknown; partial: boolean } {
11
+ const body = displayText(view.text, 240), title = view.title === null ? undefined : displayText(view.title, 96);
12
+ return { data: { id: view.id, at: view.at, kind: view.kind, ...(title ? { title: title.text } : {}), text: body.text },
13
+ partial: body.partial || title?.partial === true };
14
+ }
15
+
16
+ export function validCachedCurated(row: BriefCacheRow, project: string, now = Date.now()): boolean {
17
+ const source = row.source as View | null;
18
+ if (!source || source.project !== project || typeof source.id !== "string" || !/^[a-f0-9]{32}$/.test(source.id)
19
+ || typeof source.at !== "string" || !Number.isFinite(Date.parse(source.at)) || typeof source.text !== "string"
20
+ || !(source.title === null || typeof source.title === "string") || typeof source.kind !== "string"
21
+ || source.supersededBy !== null || (source.expiresAt !== null && (!Number.isFinite(Date.parse(source.expiresAt)) || Date.parse(source.expiresAt) <= now))) return false;
22
+ const shown = noteDisplay(source);
23
+ return JSON.stringify(shown.data) === JSON.stringify(row.data) && shown.partial === row.partial;
24
+ }
25
+
26
+ export function curatedCacheFresh(cache: { curated?: { builtAt: number; binding: string; expiresAt: number | null } }, binding: string, now: number): boolean {
27
+ const metadata = cache.curated;
28
+ return !!metadata && metadata.binding === binding && Number.isFinite(metadata.builtAt) && metadata.builtAt <= now
29
+ && now - metadata.builtAt < MAX_AGE && (metadata.expiresAt === null || Number.isFinite(metadata.expiresAt) && metadata.expiresAt > now);
30
+ }
31
+
32
+ export function buildCuratedBriefCache(store: Pick<MemoryStore, "readPage" | "withDeferredPromotions">,
33
+ options: { base: string; project: string; directory: string; binding: string; cwd?: string; now?: () => number; policy?: StandalonePolicyOptions }): void {
34
+ if (options.policy?.host) throw new Error("prebuilt curated brief requires synchronous standalone policy; remove host policy or use the async session brief");
35
+ const now = (options.now ?? Date.now)(), policy = createStandalonePolicy(configuredPolicyOptions(options.base, options.cwd, options.policy));
36
+ const rows: BriefCacheRow[] = [], expires: number[] = [];
37
+ let partial = false, after: { position: number; id: string } | undefined, complete = false;
38
+ let bytes = Buffer.byteLength(JSON.stringify({ schema: "agent-mem.brief-cache/v1", project: options.project, section: "curated", builtThrough: 1, partial: false, rows: [], curated: { builtAt: now, binding: options.binding, expiresAt: null } })) + 1;
39
+ store.withDeferredPromotions(() => {
40
+ for (let pageNo = 0; pageNo < MAX_PAGES; pageNo++) {
41
+ const page = store.readPage({ project: options.project, limit: PAGE_ROWS, after });
42
+ for (const source of page.rows) {
43
+ if (source.project !== options.project) { partial = true; continue; }
44
+ if (source.supersededBy || source.expiresAt !== null && Date.parse(source.expiresAt) <= now) continue;
45
+ if (!policy.screenStandalone(source)) continue;
46
+ if (rows.length >= SECTION_RECORDS) { partial = true; complete = true; break; }
47
+ const shown = noteDisplay(source);
48
+ if (!policy.screenStandalone(shown.data)) continue;
49
+ const row = { source, data: shown.data, partial: shown.partial }, rowBytes = Buffer.byteLength(JSON.stringify(row)) + (rows.length ? 1 : 0);
50
+ const displayBytes = Buffer.byteLength(JSON.stringify({ section: "curated", evidence: true, data: shown.data }));
51
+ if (displayBytes > RECORD_BYTES || bytes + rowBytes > BRIEF_CACHE_BYTES) { partial = true; continue; }
52
+ rows.push(row); bytes += rowBytes; partial ||= shown.partial;
53
+ if (source.expiresAt !== null) expires.push(Date.parse(source.expiresAt));
54
+ }
55
+ if (complete || !page.next) { complete = true; break; }
56
+ after = { position: page.next.position, id: page.next.id };
57
+ }
58
+ if (!complete) partial = true;
59
+ });
60
+ const expiresAt = expires.length ? Math.min(...expires) : null;
61
+ writeBriefCache({ directory: options.directory, project: options.project, section: "curated" }, {
62
+ schema: "agent-mem.brief-cache/v1", project: options.project, section: "curated", builtThrough: Math.max(1, now), partial, rows,
63
+ curated: { builtAt: now, binding: options.binding, expiresAt },
64
+ });
65
+ }
package/src/cli.ts CHANGED
@@ -479,6 +479,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
479
479
  const result = await buildIntentBrief(createIntentBriefSource(store, project),
480
480
  { project, cwd: root, repo: project, intent, paths, symbols, maxBytes, policy, policyVersion, assertCurrent, now: () => store.readNow(), stale: createRecallStalenessProbe({ cwd: root, rootConfirmed, policy }) });
481
481
  assertCurrent(); outputReady(result.items.map(view => view.id), project);
482
+ if (actor === "person") store.prepareCuratedBriefs([project]);
482
483
  return options["--json"] ? JSON.stringify({ brief: result.text, bytes: result.bytes, truncated: result.truncated, state: result.state }, null, 2) : result.text;
483
484
  } finally { store.close(); }
484
485
  }
@@ -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
+ }
@@ -4,11 +4,15 @@ export const HOOK_INPUT_BYTES = 64 * 1024, HOOK_CONTEXT_BYTES = 1200, HOOK_OUTPU
4
4
  /** `unavailable` (#221): the scan threw, so no progress is known; unlike the others it is a fault, never accepted progress. */
5
5
  export type HookTranscriptStopReason = "cap" | "deadline" | "spool_full" | "unavailable";
6
6
  export const HOOK_TRANSCRIPT_STOP_REASONS: readonly HookTranscriptStopReason[] = ["cap", "deadline", "spool_full", "unavailable"];
7
- export interface HookTranscriptProgress { offset?: number; stopReason?: HookTranscriptStopReason }
7
+ export interface HookRecordCounts { recordValidRecords: number; recordBasisRecords: number; recordUnverifiedRecords: number }
8
+ export interface HookTranscriptProgress extends Partial<HookRecordCounts> { offset?: number; stopReason?: HookTranscriptStopReason }
8
9
  export function isHookTranscriptProgress(value: unknown): value is HookTranscriptProgress {
9
10
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
10
11
  const row = value as Record<string, unknown>;
11
- return Object.keys(row).every(key => key === "offset" || key === "stopReason")
12
+ return Object.keys(row).every(key => ["offset", "stopReason", "recordValidRecords", "recordBasisRecords", "recordUnverifiedRecords"].includes(key))
13
+ && (["recordValidRecords", "recordBasisRecords", "recordUnverifiedRecords"].every(key => row[key] === undefined)
14
+ || ["recordValidRecords", "recordBasisRecords", "recordUnverifiedRecords"].every(key => Number.isSafeInteger(row[key]) && (row[key] as number) >= 0)
15
+ && (row.recordBasisRecords as number) <= (row.recordValidRecords as number) && (row.recordUnverifiedRecords as number) <= (row.recordValidRecords as number))
12
16
  && (row.offset !== undefined || row.stopReason !== undefined)
13
17
  && (row.offset === undefined || Number.isSafeInteger(row.offset) && (row.offset as number) >= 0)
14
18
  && (row.stopReason === undefined || (HOOK_TRANSCRIPT_STOP_REASONS as readonly string[]).includes(row.stopReason as string));
@@ -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 prefix = `${RECORD_INSTRUCTION}\n`;
13
- return context.startsWith(prefix) ? context.slice(prefix.length) : context;
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;
@@ -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";
@@ -687,7 +687,7 @@ export async function stageHookCapture(event: string, input: unknown, options: O
687
687
  : contentText;
688
688
  // #173: attribution. Only a fixed-width hash of the native session id is kept, never the id or transcript path;
689
689
  // a non-empty agent_id marks a subagent (or in-process teammate) event. Both are read from the already-screened input.
690
- const session = typeof value.session_id === "string" && value.session_id.length > 0 && value.session_id.length <= 256 ? hash(`amem-session\0${value.session_id}`).slice(0, 16) : undefined;
690
+ const session = captureSessionKey(value.session_id);
691
691
  const subagent = typeof value.agent_id === "string" && value.agent_id.length > 0;
692
692
  const capture = normalizeCaptureFields({ agent: options.agent ?? "claude", event, paths, status: event === "PostToolUseFailure" ? "failed" : "ok",
693
693
  ...(session ? { session } : {}), ...(subagent ? { subagent: true } : {}),
@@ -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 = hash(`amem-session\0${value.session_id}`).slice(0, 16);
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
  }