@staix/agent-mem 0.42.0 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/package.json +2 -2
- package/src/cli.ts +32 -3
- package/src/commands-table.ts +6 -2
- package/src/index.ts +2 -0
- package/src/ingest-hosts.ts +440 -0
- package/src/memory/candidates.ts +12 -0
- package/src/memory/capture.ts +23 -0
- package/src/memory/doctor.ts +8 -5
- package/src/memory/formats-raise.ts +1 -1
- package/src/memory/formats.ts +11 -0
- package/src/memory/generation-sync.ts +1 -1
- package/src/memory/home-binding-fence.ts +2 -1
- package/src/memory/live-state.ts +85 -0
- package/src/memory/migrate.ts +3 -3
- package/src/memory/mutation.ts +6 -3
- package/src/memory/public-prune-activation.ts +1 -1
- package/src/memory/public-prune-advance.ts +1 -1
- package/src/memory/public-prune-inputs.ts +1 -1
- package/src/memory/purge-intent.ts +27 -0
- package/src/memory/purge-matcher.ts +101 -0
- package/src/memory/purge-plan.ts +90 -0
- package/src/memory/read-curated-entries.ts +244 -0
- package/src/memory/reader-lease.ts +3 -0
- package/src/memory/shard-migration.ts +3 -3
- package/src/memory/shard-sync.ts +3 -3
- package/src/memory/store.ts +4 -69
- package/src/memory/sync-placement-activation-locks.ts +12 -3
- package/src/memory/sync-placement-active.ts +2 -0
- package/src/memory/sync-placement-guard.ts +2 -0
- package/src/memory/sync-placement-journal.ts +1 -1
- package/src/memory/sync-placement-transport.ts +8 -3
- package/src/memory/sync.ts +3 -2
- package/src/setup-console.ts +1 -1
- package/src/setup-drift.ts +4 -3
- package/src/setup-owned.ts +9 -1
- package/src/setup.ts +36 -6
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.
|
|
6
|
+
Version: 0.43.0. Requires Bun 1.4.2 or later; runtime dependencies: @staix/cli-output, @staix/mcp-stdio.
|
|
7
7
|
<!-- /facts:version -->
|
|
8
8
|
|
|
9
9
|
## Quick start
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@staix/agent-mem",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.43.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",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {
|
|
15
15
|
"@staix/cli-output": "0.1.4",
|
|
16
|
-
"@staix/mcp-stdio": "0.
|
|
16
|
+
"@staix/mcp-stdio": "0.5.0"
|
|
17
17
|
},
|
|
18
18
|
"devDependencies": {
|
|
19
19
|
"@staix/agent-console": "0.1.3",
|
package/src/cli.ts
CHANGED
|
@@ -81,6 +81,7 @@ import { markShown, pendingSummary } from "./memory/candidate-pending.ts";
|
|
|
81
81
|
import { buildNote, FAIL_TEMPLATE, hasFailLabel, noteAdd, parseFailTemplate, type FailFields } from "./memory/note-add.ts";
|
|
82
82
|
import { runEditor } from "./memory/editor.ts";
|
|
83
83
|
import { listAgyReceiptLocations } from "./setup-drift.ts";
|
|
84
|
+
import { PURGE_INTENT_FILE, purgePending } from "./memory/purge-intent.ts";
|
|
84
85
|
import { doctorReport } from "./memory/doctor.ts";
|
|
85
86
|
import { doctorText } from "./memory/doctor-text.ts";
|
|
86
87
|
import { statusText, type StatusView } from "./memory/status-text.ts";
|
|
@@ -514,7 +515,23 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
514
515
|
const parsed = parseCommand(argv);
|
|
515
516
|
if (parsed.options["--help"] === true) return commandHelp(argv);
|
|
516
517
|
const kind = parsed.positionals[0];
|
|
517
|
-
if (parsed.positionals.length !== 1 || !["codex", "kimi", "pi", "qwen"].includes(kind ?? "")) throw new Error("usage: amem ingest codex|kimi|pi|qwen [--since ISO] [--json]");
|
|
518
|
+
if (parsed.positionals.length !== 1 || !["codex", "kimi", "pi", "qwen", "opencode", "gemini", "agy"].includes(kind ?? "")) throw new Error("usage: amem ingest codex|kimi|pi|qwen|opencode|gemini|agy [--since ISO] [--json]");
|
|
519
|
+
if (kind === "opencode" || kind === "gemini" || kind === "agy") {
|
|
520
|
+
const { ingestHost } = await import("./ingest-hosts.ts");
|
|
521
|
+
// #647: the Gemini SessionEnd hook passes its JSON on stdin; only transcript_path is read from it, and a bad input ingests nothing.
|
|
522
|
+
let transcript: string | undefined;
|
|
523
|
+
if (parsed.options["--hook-input"] === true) {
|
|
524
|
+
if (kind !== "gemini") throw new Error("--hook-input applies only to amem ingest gemini");
|
|
525
|
+
try {
|
|
526
|
+
const input = JSON.parse((context.stdin ?? (() => readFileSync(0, "utf8")))().slice(0, 64 * 1024)) as { transcript_path?: unknown };
|
|
527
|
+
if (typeof input.transcript_path === "string" && input.transcript_path.startsWith("/")) transcript = input.transcript_path;
|
|
528
|
+
} catch { /* fail open: no transcript, nothing ingested */ }
|
|
529
|
+
if (transcript === undefined) return parsed.options["--json"] === true ? JSON.stringify({ files: 0, read: 0, imported: 0, skipped: 0, spooled: 0, remaining: false, errors: 0 }, null, 2) : "";
|
|
530
|
+
}
|
|
531
|
+
const result = await ingestHost(kind, { cwd: context.cwd ?? process.cwd(), base: memoryHome(context.env ?? process.env), env: context.env ?? process.env,
|
|
532
|
+
...(transcript ? { transcript } : {}), ...(typeof parsed.options["--since"] === "string" ? { since: parsed.options["--since"] as string } : {}) });
|
|
533
|
+
return parsed.options["--json"] === true ? JSON.stringify(result, null, 2) : ingestText(kind, result as IngestReceipt, outputStyle(context, parsed.options), reportWidth(context));
|
|
534
|
+
}
|
|
518
535
|
const { ingestTranscript } = await import("./ingest.ts");
|
|
519
536
|
const result = await ingestTranscript(kind as IngestKind, {
|
|
520
537
|
cwd: context.cwd ?? process.cwd(), base: memoryHome(context.env ?? process.env),
|
|
@@ -927,11 +944,23 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
|
|
|
927
944
|
}
|
|
928
945
|
if (sub === "doctor") {
|
|
929
946
|
// F15: one read-only report; see src/memory/doctor.ts for exactly what "read-only" covers.
|
|
930
|
-
const where = resolveMemoryHome()
|
|
947
|
+
const where = resolveMemoryHome();
|
|
948
|
+
if (purgePending(where.home)) {
|
|
949
|
+
const purge = { status: "pending", file: PURGE_INTENT_FILE,
|
|
950
|
+
next: "Keep this home closed and retain the barrier for recovery. See docs/purge-design.md, Placement cut and recovery." };
|
|
951
|
+
return options["--json"] ? JSON.stringify({ purge }, null, 2) : `Local purge pending (${purge.file}). ${purge.next}`;
|
|
952
|
+
}
|
|
953
|
+
const project = boundProject();
|
|
931
954
|
const report = await doctorReport({ home: where.home, homeSource: where.source, cwd: policyCwd, project, aliases: aliasedKeys(where.home, project), now: Date.now(),
|
|
932
955
|
openCurated: base => curatedStoreAt(base, project, { deferPromotions: true }) });
|
|
933
956
|
return options["--json"] ? JSON.stringify(report, null, 2) : doctorText(report, outputStyle(context, options), reportOptions(context, options));
|
|
934
957
|
}
|
|
958
|
+
if (sub === "purge") {
|
|
959
|
+
const { planPurge } = await import("./memory/purge-plan.ts");
|
|
960
|
+
const matchFile = options["--match-file"];
|
|
961
|
+
const plan = administrative(planPurge(memoryHome(), { entryId: parsed.positionals[0] ?? "", ...(typeof matchFile === "string" ? { matchFile: resolve(context.cwd ?? process.cwd(), matchFile) } : {}) }));
|
|
962
|
+
return JSON.stringify(plan, null, 2);
|
|
963
|
+
}
|
|
935
964
|
if (sub === "prune") {
|
|
936
965
|
const applying = options["--apply"] === true;
|
|
937
966
|
if (applying ? options["--dry-run"] || options["--cutoff"] || !options["--plan"] : !options["--dry-run"] || !options["--cutoff"] || options["--plan"]) throw new Error("usage: amem prune [--user] --cutoff <UTC> --dry-run | [--user] --apply --plan <file>");
|
|
@@ -1827,7 +1856,7 @@ function reportWidth(context: CliContext): number | undefined {
|
|
|
1827
1856
|
}
|
|
1828
1857
|
|
|
1829
1858
|
/** Native ingest remains capture-only and agent-reachable; this formats only its returned receipt. */
|
|
1830
|
-
export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = PLAIN, columns?: number): string {
|
|
1859
|
+
export function ingestText(kind: IngestKind | "opencode" | "gemini" | "agy", result: IngestReceipt, s: Style = PLAIN, columns?: number): string {
|
|
1831
1860
|
const state = result.errors || result.remaining || result.spooled ? "attention" : result.files || result.read ? "complete" : "skipped";
|
|
1832
1861
|
const reason: string | undefined = result.reason;
|
|
1833
1862
|
const actions: Record<string, string> = {
|
package/src/commands-table.ts
CHANGED
|
@@ -62,8 +62,9 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
62
62
|
examples: ["amem manifest --json"], options: json("the manifest") },
|
|
63
63
|
hook: { group: "setup", description: "Run a fail-open, context-only capture hook", examples: ["amem hook SessionStart"], args: [{ name: "event", values: [...HOOK_EVENTS, "jcode"] }] },
|
|
64
64
|
ingest: { group: "setup", description: "Capture native session transcripts incrementally", details: "Runs once per call; no watcher.",
|
|
65
|
-
examples: ["amem ingest codex", "amem ingest pi --since 2026-11-01"], options: { ...json("the ingest receipt"), "--since": date("Only transcripts since this ISO date or time")
|
|
66
|
-
|
|
65
|
+
examples: ["amem ingest codex", "amem ingest pi --since 2026-11-01", "amem ingest opencode"], options: { ...json("the ingest receipt"), "--since": date("Only transcripts since this ISO date or time"),
|
|
66
|
+
"--hook-input": flag("Read a Gemini SessionEnd hook's transcript_path from stdin", "Setup writes this flag into the Gemini hook; it never blocks or denies.") },
|
|
67
|
+
args: [{ name: "kind", values: ["codex", "kimi", "pi", "qwen", "opencode", "gemini", "agy"] }] },
|
|
67
68
|
"vault-candidates": { group: "read", description: "List screened durable vault candidates", details: "Per project, or across projects with --all-projects.",
|
|
68
69
|
examples: ["amem vault-candidates", "amem vault-candidates --all-projects --limit 20"],
|
|
69
70
|
options: { ...json("the candidates"), "--limit": number("Maximum candidates per project (1..100)"),
|
|
@@ -262,6 +263,9 @@ export const COMMANDS: Record<string, CommandDefinition> = {
|
|
|
262
263
|
doctor: { group: "read", description: "Check this project's memory health, read-only",
|
|
263
264
|
details: "Duplicates and stale notes, pending candidates, capture freshness per CLI, the brief's token cost, index equals rebuild, reader leases, the policy in effect, and ingest and sync cadence.",
|
|
264
265
|
examples: ["amem doctor", "amem doctor --json"], options: { ...json("the doctor report"), "--verbose": flag("Show static notes and history lines (human output only)") } },
|
|
266
|
+
purge: { group: "maintenance", description: "Preview a local purge of an exact curated entry", args: [{ name: "id" }],
|
|
267
|
+
examples: ["amem purge <id>", "amem purge <id> --match-file matcher.txt"],
|
|
268
|
+
options: { ...json("the sealed purge preview"), "--match-file": path("Private file with literal capture and candidate text") } },
|
|
265
269
|
prune: { group: "maintenance", description: "Plan or apply exact-entry expiry in a generation", examples: ["amem prune --dry-run --cutoff 2026-01-01", "amem prune --apply --plan plan.json"], mutates: true,
|
|
266
270
|
options: { ...json("the prune plan or receipt"), "--cutoff": date("Canonical UTC expiry cutoff"), "--dry-run": flag("Print a local sealed plan without writes"),
|
|
267
271
|
"--user": flag("Select the user shard after a curated split", "Default: the current project."),
|
package/src/index.ts
CHANGED
|
@@ -100,3 +100,5 @@ export { readRecordInstruction, RECORD_INSTRUCTION_FILE } from "./memory/record-
|
|
|
100
100
|
export { groupByTask, taskGroupKey } from "./memory/task-group.ts";
|
|
101
101
|
|
|
102
102
|
export { SKILL_NAMES, installSkills, exportSkills, skillRoot, type SkillAction, type SkillInstallReport } from "./skills-install.ts";
|
|
103
|
+
// #680: read-only curated lookup by id for read-only hosts; its presence is the capability signal.
|
|
104
|
+
export { readCuratedEntries, READ_CURATED_MAX_IDS, type ReadCuratedEntriesOptions, type ReadCuratedEntriesResult } from "./memory/read-curated-entries.ts";
|
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { closeSync, fstatSync, lstatSync, openSync, opendirSync, readSync, constants, chmodSync, mkdirSync, readFileSync, writeFileSync, renameSync, type Stats } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { CaptureStore, type CaptureInput } from "./memory/capture.ts";
|
|
8
|
+
import { memoryHome } from "./memory/home.ts";
|
|
9
|
+
import { canonicalPath, realPath } from "./memory/platform.ts";
|
|
10
|
+
import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
|
|
11
|
+
import { configuredPolicyOptions, recordsEnabled } from "./memory/config.ts";
|
|
12
|
+
import { captureSessionKey, RecordNormalizationRefusal, withholdToolArguments } from "./memory/capture-input.ts";
|
|
13
|
+
import { stripPrivateSpans } from "./memory/private-spans.ts";
|
|
14
|
+
import { parseRecordLines, recordIntakeCounts, recordRefusal, type RecordIntakeCounts } from "./hook-record.ts";
|
|
15
|
+
import { memoryProjectKey } from "./memory/project.ts";
|
|
16
|
+
import { effectiveAliases } from "./memory/shard.ts";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* #647: session transcript capture for OpenCode, Gemini CLI and Antigravity (agy). Owner decisions 2026-11-28 (#647 D3, D4):
|
|
20
|
+
* a session is attributed as a whole to the one project directory it is bound to (any other session is skipped), and only
|
|
21
|
+
* messages final at read time are captured, keyed by session and message id, never retracted. Native stores are read only:
|
|
22
|
+
* a JSONL file through one non-following descriptor, a SQLite store from an in-memory copy of its main file, so no -wal,
|
|
23
|
+
* -shm or journal file is ever created in the host's data directory. No watcher, daemon, model or network call.
|
|
24
|
+
* Sources (verified 2026-11-28 against the installed CLIs, structure only):
|
|
25
|
+
* - Gemini CLI 0.67.0 packages/core/src/services/chatRecordingService.ts: `<home>/.gemini/tmp/<slug>/chats/session-*.jsonl`,
|
|
26
|
+
* a header {sessionId, projectHash, startTime, kind, directories?}, message records {id, timestamp, type, content}, and
|
|
27
|
+
* `$set.messages`, `$patch` and `$rewindTo` records replayed here like the native loader; `<slug>/.project_root` holds the cwd.
|
|
28
|
+
* - OpenCode 1.19.5 `<xdgData>/opencode/opencode.db`: session(directory, time_updated), message(data.role, data.finish, data.time),
|
|
29
|
+
* part(data.type text|tool).
|
|
30
|
+
* - Antigravity CLI 1.5.18 `~/.gemini/antigravity-cli/brain/<id>/.system_generated/logs/transcript.jsonl` steps {step_index,
|
|
31
|
+
* source, type, status, created_at, content, tool_calls}, and conversation_summaries.db(conversation_id, workspace_uris, status).
|
|
32
|
+
*/
|
|
33
|
+
export type HostIngestKind = "opencode" | "gemini" | "agy";
|
|
34
|
+
export const HOST_INGEST_KINDS: readonly HostIngestKind[] = ["opencode", "gemini", "agy"];
|
|
35
|
+
export interface HostIngestOptions {
|
|
36
|
+
cwd: string; base?: string; env?: NodeJS.ProcessEnv;
|
|
37
|
+
/** Gemini SessionEnd hook: exactly this transcript, as the host passes it on stdin. */
|
|
38
|
+
transcript?: string;
|
|
39
|
+
since?: string; policy?: StandalonePolicyOptions;
|
|
40
|
+
/** Tests pin the clock for the OpenCode quiet delay. */
|
|
41
|
+
now?: () => number;
|
|
42
|
+
}
|
|
43
|
+
export interface HostIngestReceipt {
|
|
44
|
+
files: number; read: number; imported: number; skipped: number; spooled: number; remaining: boolean; errors: number;
|
|
45
|
+
reason?: "source_bound" | "source_unavailable" | "schema_or_time" | "cursor_busy" | "scope_changed" | "unsupported_version";
|
|
46
|
+
/** Sessions not bound to exactly one project directory (#647 D3), and sessions bound to another project. */
|
|
47
|
+
unattributed?: number;
|
|
48
|
+
records?: RecordIntakeCounts;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const MAX_SOURCE_BYTES = 16 * 1024 * 1024, MAX_DB_BYTES = 64 * 1024 * 1024, MAX_SESSIONS = 256, MAX_MESSAGES = 4096, MAX_DISCOVERY = 4096;
|
|
52
|
+
/** OpenCode rows are rewritten while a reply streams; a finished assistant message is taken only once its session has been quiet this long. */
|
|
53
|
+
export const OPENCODE_QUIET_MS = 30_000;
|
|
54
|
+
const hash = (value: string | Uint8Array) => createHash("sha256").update(value).digest("hex");
|
|
55
|
+
const object = (value: unknown): value is Record<string, any> => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
56
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
57
|
+
const same = (a: Stats, b: Stats) => a.dev === b.dev && a.ino === b.ino;
|
|
58
|
+
const iso = (value: unknown): string | undefined => {
|
|
59
|
+
const millis = typeof value === "number" && Number.isFinite(value) ? value : typeof value === "string" && /^\d{4}-\d\d-\d\dT/.test(value) ? Date.parse(value) : NaN;
|
|
60
|
+
if (!Number.isFinite(millis)) return undefined;
|
|
61
|
+
try { return new Date(millis).toISOString(); } catch { return undefined; }
|
|
62
|
+
};
|
|
63
|
+
function expandHome(value: string): string {
|
|
64
|
+
return value === "~" ? homedir() : value.startsWith("~/") ? join(homedir(), value.slice(2)) : value;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** One regular, singly linked, non-symlink file read whole through one descriptor, within a byte bound; any other file reads as unavailable. */
|
|
68
|
+
const UNAVAILABLE = new Error("");
|
|
69
|
+
function readPublic(file: string, max: number): { bytes: Buffer; stat: Stats } {
|
|
70
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
71
|
+
try {
|
|
72
|
+
const stat = fstatSync(fd), named = lstatSync(file);
|
|
73
|
+
// Callers catch this and report the `source_unavailable` reason; it never reaches a person.
|
|
74
|
+
if (!stat.isFile() || stat.nlink !== 1 || !same(stat, named) || named.isSymbolicLink() || stat.size > max) throw UNAVAILABLE;
|
|
75
|
+
const bytes = Buffer.alloc(stat.size); let read = 0;
|
|
76
|
+
while (read < stat.size) { const n = readSync(fd, bytes, read, stat.size - read, read); if (n <= 0) break; read += n; }
|
|
77
|
+
return { bytes: bytes.subarray(0, read), stat };
|
|
78
|
+
} finally { closeSync(fd); }
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* A SQLite store opened from an in-memory copy of its main file (condition 2 of the plan review): nothing is created or written in the
|
|
82
|
+
* host's directory. A store whose WAL holds frames not yet checkpointed cannot be read this way; it reports `walPending` instead of
|
|
83
|
+
* falling back to stale data, and doctor names it.
|
|
84
|
+
*/
|
|
85
|
+
function snapshotDatabase(file: string): { db: Database; stat: Stats } | { walPending: true } {
|
|
86
|
+
const wal = lstatSync(`${file}-wal`, { throwIfNoEntry: false });
|
|
87
|
+
if (wal && (!wal.isFile() || wal.isSymbolicLink() || wal.size > 0)) return { walPending: true };
|
|
88
|
+
const { bytes, stat } = readPublic(file, MAX_DB_BYTES);
|
|
89
|
+
const image = new Uint8Array(bytes);
|
|
90
|
+
if (image.length < 100 || Buffer.from(image.subarray(0, 16)).toString("latin1") !== "SQLite format 3\0") throw UNAVAILABLE;
|
|
91
|
+
// WAL mode is a header flag; an in-memory image must use rollback mode or SQLite reaches for the sidecar files.
|
|
92
|
+
if (image[18] === 2) image[18] = 1;
|
|
93
|
+
if (image[19] === 2) image[19] = 1;
|
|
94
|
+
const db = Database.deserialize(image, { readonly: true });
|
|
95
|
+
db.run("PRAGMA busy_timeout = 0");
|
|
96
|
+
return { db, stat };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A per-source cursor of message ids already taken. Private, bounded, replaced atomically; it only saves work, receipts dedupe. */
|
|
100
|
+
interface Seen { stamp: string; ids: string[] }
|
|
101
|
+
const MAX_SEEN = 8192;
|
|
102
|
+
function seenFile(dir: string, kind: HostIngestKind, source: string) { return join(dir, `${kind}-${hash(source).slice(0, 32)}.json`); }
|
|
103
|
+
function loadSeen(file: string): Seen {
|
|
104
|
+
try {
|
|
105
|
+
const stat = lstatSync(file);
|
|
106
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) return { stamp: "", ids: [] };
|
|
107
|
+
const value = JSON.parse(readFileSync(file, "utf8")) as Seen;
|
|
108
|
+
return typeof value.stamp === "string" && Array.isArray(value.ids) && value.ids.every(id => typeof id === "string" && /^[a-f0-9]{64}$/.test(id)) ? value : { stamp: "", ids: [] };
|
|
109
|
+
} catch { return { stamp: "", ids: [] }; }
|
|
110
|
+
}
|
|
111
|
+
function saveSeen(file: string, value: Seen): void {
|
|
112
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
113
|
+
writeFileSync(temp, JSON.stringify({ stamp: value.stamp, ids: value.ids.slice(-MAX_SEEN) }), { mode: 0o600, flag: "w" });
|
|
114
|
+
renameSync(temp, file);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** A final message ready to capture: its stable key, time, the capture row, and an assistant text a Record may come from. */
|
|
118
|
+
interface FinalMessage { key: string; at: string; input: Omit<CaptureInput, "project">; recordText?: string; recordFinal?: boolean; sources: unknown[] }
|
|
119
|
+
interface Session { source: string; stamp: string; id: string; origin: string | undefined; ambiguous: boolean; messages: FinalMessage[] }
|
|
120
|
+
|
|
121
|
+
// --- Gemini ---------------------------------------------------------------------------------------------------------
|
|
122
|
+
function geminiRoot(env: NodeJS.ProcessEnv): string {
|
|
123
|
+
const configured = env.GEMINI_CLI_HOME?.trim();
|
|
124
|
+
return join(configured && isAbsolute(configured) ? resolve(configured) : env.HOME?.trim() || homedir(), ".gemini");
|
|
125
|
+
}
|
|
126
|
+
function geminiFiles(env: NodeJS.ProcessEnv): { files: string[]; bounded: boolean; unavailable: boolean } {
|
|
127
|
+
const root = join(geminiRoot(env), "tmp"), files: string[] = []; let visited = 0, bounded = false;
|
|
128
|
+
let projects: ReturnType<typeof opendirSync>;
|
|
129
|
+
const unavailable = { files, bounded, unavailable: true };
|
|
130
|
+
try { if (lstatSync(root).isSymbolicLink()) return unavailable; projects = opendirSync(root); } catch { return unavailable; }
|
|
131
|
+
try {
|
|
132
|
+
for (let slug = projects.readSync(); slug; slug = projects.readSync()) {
|
|
133
|
+
if (++visited > MAX_DISCOVERY) { bounded = true; break; }
|
|
134
|
+
if (!slug.isDirectory() || slug.isSymbolicLink()) continue;
|
|
135
|
+
const chats = join(root, slug.name, "chats");
|
|
136
|
+
let dir: ReturnType<typeof opendirSync>;
|
|
137
|
+
try { if (lstatSync(chats).isSymbolicLink()) continue; dir = opendirSync(chats); } catch { continue; }
|
|
138
|
+
try {
|
|
139
|
+
for (let item = dir.readSync(); item; item = dir.readSync()) {
|
|
140
|
+
if (++visited > MAX_DISCOVERY) { bounded = true; break; }
|
|
141
|
+
if (item.isFile() && !item.isSymbolicLink() && /^session-.*\.jsonl$/.test(item.name)) files.push(join(chats, item.name));
|
|
142
|
+
}
|
|
143
|
+
} finally { dir.closeSync(); }
|
|
144
|
+
if (bounded) break;
|
|
145
|
+
}
|
|
146
|
+
} finally { projects.closeSync(); }
|
|
147
|
+
return { files: files.sort(), bounded, unavailable: false };
|
|
148
|
+
}
|
|
149
|
+
const geminiText = (content: unknown): string => typeof content === "string" ? content
|
|
150
|
+
: Array.isArray(content) ? content.filter(part => object(part) && typeof part.text === "string" && part.thought !== true).map(part => part.text).join("\n") : "";
|
|
151
|
+
/** Replays a session file the way the native loader does: $set.messages replaces, $patch edits or removes, $rewindTo truncates. */
|
|
152
|
+
export function replayGemini(text: string): { header?: Record<string, any>; messages: Map<string, Record<string, any>>; invalid: number } {
|
|
153
|
+
const messages = new Map<string, Record<string, any>>(); let header: Record<string, any> | undefined, invalid = 0;
|
|
154
|
+
for (const line of text.split("\n")) {
|
|
155
|
+
if (!line.trim()) continue;
|
|
156
|
+
let record: unknown;
|
|
157
|
+
try { record = JSON.parse(line); } catch { invalid++; continue; }
|
|
158
|
+
if (!object(record)) { invalid++; continue; }
|
|
159
|
+
if (typeof record.$rewindTo === "string") {
|
|
160
|
+
let found = false;
|
|
161
|
+
for (const id of [...messages.keys()]) { if (id === record.$rewindTo) found = true; if (found) messages.delete(id); }
|
|
162
|
+
if (!found) messages.clear();
|
|
163
|
+
} else if (object(record.$patch)) {
|
|
164
|
+
const patches = [record.$patch, ...(Array.isArray(record.$patch.updates) ? record.$patch.updates : [])];
|
|
165
|
+
for (const patch of patches) if (object(patch) && typeof patch.id === "string" && messages.has(patch.id) && patch.content !== undefined) messages.get(patch.id)!.content = patch.content;
|
|
166
|
+
if (Array.isArray(record.$patch.removeIds)) for (const id of record.$patch.removeIds) if (typeof id === "string") messages.delete(id);
|
|
167
|
+
} else if (object(record.$set)) {
|
|
168
|
+
if (Array.isArray(record.$set.messages)) { messages.clear(); for (const message of record.$set.messages) if (object(message) && typeof message.id === "string") messages.set(message.id, message); }
|
|
169
|
+
} else if (typeof record.sessionId === "string" && typeof record.projectHash === "string") header = { ...header, ...record };
|
|
170
|
+
else if (typeof record.id === "string") messages.set(record.id, record);
|
|
171
|
+
else invalid++;
|
|
172
|
+
}
|
|
173
|
+
return { header, messages, invalid };
|
|
174
|
+
}
|
|
175
|
+
function geminiOrigin(file: string): string | undefined {
|
|
176
|
+
try {
|
|
177
|
+
const rootFile = join(file, "..", "..", ".project_root"), stat = lstatSync(rootFile);
|
|
178
|
+
if (stat.isFile() && !stat.isSymbolicLink() && stat.size <= 4096) return readFileSync(rootFile, "utf8").trim();
|
|
179
|
+
} catch { /* no origin */ }
|
|
180
|
+
return undefined;
|
|
181
|
+
}
|
|
182
|
+
function geminiSession(file: string, bytes: Buffer, stamp: string): Session | undefined {
|
|
183
|
+
let text: string;
|
|
184
|
+
try { text = utf8.decode(bytes); } catch { return undefined; }
|
|
185
|
+
const { header, messages } = replayGemini(text);
|
|
186
|
+
if (!header || typeof header.sessionId !== "string") return undefined;
|
|
187
|
+
// D3: the session's origin is its project's .project_root; any extra directory makes it ambiguous.
|
|
188
|
+
let origin = geminiOrigin(file), ambiguous = Array.isArray(header.directories) && header.directories.length > 1;
|
|
189
|
+
if (Array.isArray(header.directories) && header.directories.length === 1 && typeof header.directories[0] === "string" && origin && resolve(header.directories[0]) !== resolve(origin)) ambiguous = true;
|
|
190
|
+
const out: FinalMessage[] = [];
|
|
191
|
+
for (const message of messages.values()) {
|
|
192
|
+
const at = iso(message.timestamp); if (!at) continue;
|
|
193
|
+
if (message.type !== "user" && message.type !== "gemini") continue;
|
|
194
|
+
const excerpt = geminiText(message.content);
|
|
195
|
+
const tools = Array.isArray(message.toolCalls) ? message.toolCalls.filter(object) : [];
|
|
196
|
+
if (excerpt) out.push({ key: `${message.id}`, at, input: { agent: "gemini", event: "message", excerpt: excerpt.slice(0, 2000), status: message.type === "user" ? "user" : "assistant" },
|
|
197
|
+
// Gemini records carry no completion marker, so a Record from it is finality-unavailable (#395).
|
|
198
|
+
...(message.type === "gemini" ? { recordText: excerpt, recordFinal: false } : {}), sources: [message] });
|
|
199
|
+
for (const call of tools) {
|
|
200
|
+
if (typeof call.name !== "string" || typeof call.id !== "string") continue;
|
|
201
|
+
out.push({ key: `${message.id}/${call.id}`, at, input: { agent: "gemini", event: "function_call", tool: call.name.slice(0, 64),
|
|
202
|
+
excerpt: withholdToolArguments(JSON.stringify(call.args ?? {})).slice(0, 2000), ...(typeof call.status === "string" ? { status: call.status.slice(0, 64) } : {}) }, sources: [call] });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return { source: file, stamp, id: header.sessionId, origin, ambiguous, messages: out };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// --- OpenCode -------------------------------------------------------------------------------------------------------
|
|
209
|
+
function opencodeDatabase(env: NodeJS.ProcessEnv): string {
|
|
210
|
+
const data = env.XDG_DATA_HOME?.trim();
|
|
211
|
+
return join(data && isAbsolute(data) ? data : join(env.HOME?.trim() || homedir(), ".local", "share"), "opencode", "opencode.db");
|
|
212
|
+
}
|
|
213
|
+
function opencodeSessions(db: Database, now: number): Session[] {
|
|
214
|
+
const sessions = db.query("SELECT id, directory, time_updated FROM session WHERE parent_id IS NULL ORDER BY time_updated DESC LIMIT ?").all(MAX_SESSIONS) as { id: string; directory: string; time_updated: number }[];
|
|
215
|
+
const out: Session[] = [];
|
|
216
|
+
const messages = db.query("SELECT id, time_created, data FROM message WHERE session_id = ? ORDER BY time_created, id LIMIT ?");
|
|
217
|
+
const parts = db.query("SELECT id, data FROM part WHERE message_id = ? ORDER BY id LIMIT 256");
|
|
218
|
+
for (const session of sessions) {
|
|
219
|
+
// D4: rows are rewritten while a reply streams; a session that changed within the quiet delay is left for a later pass.
|
|
220
|
+
if (now - session.time_updated < OPENCODE_QUIET_MS) continue;
|
|
221
|
+
const list: FinalMessage[] = [];
|
|
222
|
+
// A user message is final only once a later assistant message of the session has finished.
|
|
223
|
+
const pending: FinalMessage[] = [];
|
|
224
|
+
for (const row of messages.all(session.id, MAX_MESSAGES) as { id: string; time_created: number; data: string }[]) {
|
|
225
|
+
let data: unknown; try { data = JSON.parse(row.data); } catch { continue; }
|
|
226
|
+
if (!object(data) || !["user", "assistant"].includes(data.role)) continue;
|
|
227
|
+
const at = iso(object(data.time) ? data.time.created : row.time_created); if (!at) continue;
|
|
228
|
+
// Only a finished assistant message is final; it also releases the user messages before it.
|
|
229
|
+
if (data.role === "assistant" && (typeof data.finish !== "string" || data.finish === "")) continue;
|
|
230
|
+
if (data.role === "assistant") list.push(...pending.splice(0));
|
|
231
|
+
const target = data.role === "user" ? pending : list;
|
|
232
|
+
const texts: string[] = [];
|
|
233
|
+
for (const part of parts.all(row.id) as { id: string; data: string }[]) {
|
|
234
|
+
let value: unknown; try { value = JSON.parse(part.data); } catch { continue; }
|
|
235
|
+
if (!object(value)) continue;
|
|
236
|
+
if (value.type === "text" && typeof value.text === "string" && value.synthetic !== true) texts.push(value.text);
|
|
237
|
+
if (value.type === "tool" && typeof value.tool === "string" && object(value.state) && ["completed", "error"].includes(value.state.status)) {
|
|
238
|
+
list.push({ key: `${row.id}/${part.id}`, at, input: { agent: "opencode", event: "function_call", tool: value.tool.slice(0, 64),
|
|
239
|
+
excerpt: withholdToolArguments(JSON.stringify(value.state.input ?? {})).slice(0, 2000), status: value.state.status === "error" ? "error" : "success" }, sources: [value] });
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const excerpt = texts.join("\n");
|
|
243
|
+
if (excerpt) target.push({ key: row.id, at, input: { agent: "opencode", event: "message", excerpt: excerpt.slice(0, 2000), status: data.role },
|
|
244
|
+
...(data.role === "assistant" ? { recordText: excerpt, recordFinal: data.finish === "stop" } : {}), sources: [data] });
|
|
245
|
+
}
|
|
246
|
+
out.push({ source: `opencode:${session.id}`, stamp: String(session.time_updated), id: session.id, origin: typeof session.directory === "string" ? session.directory : undefined, ambiguous: false, messages: list });
|
|
247
|
+
}
|
|
248
|
+
return out;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// --- Antigravity ----------------------------------------------------------------------------------------------------
|
|
252
|
+
function agyRoot(env: NodeJS.ProcessEnv): string { return join(env.HOME?.trim() || homedir(), ".gemini", "antigravity-cli"); }
|
|
253
|
+
function agyWorkspaces(root: string): Map<string, { uris: string[]; idle: boolean }> | { walPending: true } | undefined {
|
|
254
|
+
let opened: ReturnType<typeof snapshotDatabase>;
|
|
255
|
+
try { opened = snapshotDatabase(join(root, "conversation_summaries.db")); } catch { return undefined; }
|
|
256
|
+
if ("walPending" in opened) return opened;
|
|
257
|
+
try {
|
|
258
|
+
const rows = opened.db.query("SELECT conversation_id, workspace_uris, status FROM conversation_summaries LIMIT ?").all(MAX_DISCOVERY) as { conversation_id: string; workspace_uris: string; status: string }[];
|
|
259
|
+
const out = new Map<string, { uris: string[]; idle: boolean }>();
|
|
260
|
+
for (const row of rows) {
|
|
261
|
+
let uris: unknown; try { uris = JSON.parse(row.workspace_uris); } catch { uris = undefined; }
|
|
262
|
+
out.set(row.conversation_id, { uris: Array.isArray(uris) ? uris.filter(uri => typeof uri === "string") : [], idle: row.status === "CASCADE_RUN_STATUS_IDLE" });
|
|
263
|
+
}
|
|
264
|
+
return out;
|
|
265
|
+
} catch { return undefined; } finally { opened.db.close(); }
|
|
266
|
+
}
|
|
267
|
+
function agySession(id: string, file: string, bytes: Buffer, stamp: string, workspace: { uris: string[]; idle: boolean } | undefined): Session | undefined {
|
|
268
|
+
let text: string;
|
|
269
|
+
try { text = utf8.decode(bytes); } catch { return undefined; }
|
|
270
|
+
const uris = workspace?.uris ?? [];
|
|
271
|
+
let origin: string | undefined;
|
|
272
|
+
if (uris.length === 1) { try { origin = fileURLToPath(uris[0]!); } catch { origin = undefined; } }
|
|
273
|
+
const out: FinalMessage[] = [];
|
|
274
|
+
for (const line of text.split("\n")) {
|
|
275
|
+
if (!line.trim()) continue;
|
|
276
|
+
let step: unknown; try { step = JSON.parse(line); } catch { continue; }
|
|
277
|
+
// D4: only a step the native writer marked DONE is final.
|
|
278
|
+
if (!object(step) || step.status !== "DONE" || !Number.isSafeInteger(step.step_index)) continue;
|
|
279
|
+
const at = iso(step.created_at); if (!at) continue;
|
|
280
|
+
if ((step.type === "USER_INPUT" || step.type === "PLANNER_RESPONSE") && typeof step.content === "string" && step.content) {
|
|
281
|
+
out.push({ key: String(step.step_index), at, input: { agent: "agy", event: "message", excerpt: step.content.slice(0, 2000), status: step.type === "USER_INPUT" ? "user" : "assistant" },
|
|
282
|
+
// A planner response is a completed turn only when the conversation is idle and it called no tool.
|
|
283
|
+
...(step.type === "PLANNER_RESPONSE" ? { recordText: step.content, recordFinal: workspace?.idle === true && !(Array.isArray(step.tool_calls) && step.tool_calls.length) } : {}), sources: [step] });
|
|
284
|
+
}
|
|
285
|
+
if (Array.isArray(step.tool_calls)) step.tool_calls.forEach((call: unknown, index: number) => {
|
|
286
|
+
if (!object(call) || typeof call.name !== "string") return;
|
|
287
|
+
out.push({ key: `${step.step_index}/${index}`, at, input: { agent: "agy", event: "function_call", tool: call.name.slice(0, 64), excerpt: withholdToolArguments(JSON.stringify(call.args ?? {})).slice(0, 2000) }, sources: [call] });
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
return { source: file, stamp, id, origin, ambiguous: uris.length !== 1, messages: out };
|
|
291
|
+
}
|
|
292
|
+
function agyFiles(root: string): { files: { id: string; file: string }[]; bounded: boolean; unavailable: boolean } {
|
|
293
|
+
const brain = join(root, "brain"), files: { id: string; file: string }[] = []; let visited = 0, bounded = false;
|
|
294
|
+
let dir: ReturnType<typeof opendirSync>;
|
|
295
|
+
const unavailable = { files, bounded, unavailable: true };
|
|
296
|
+
try { if (lstatSync(brain).isSymbolicLink()) return unavailable; dir = opendirSync(brain); } catch { return unavailable; }
|
|
297
|
+
try {
|
|
298
|
+
for (let item = dir.readSync(); item; item = dir.readSync()) {
|
|
299
|
+
if (++visited > MAX_DISCOVERY) { bounded = true; break; }
|
|
300
|
+
if (!item.isDirectory() || item.isSymbolicLink() || !/^[0-9a-f-]{8,64}$/.test(item.name)) continue;
|
|
301
|
+
files.push({ id: item.name, file: join(brain, item.name, ".system_generated", "logs", "transcript.jsonl") });
|
|
302
|
+
}
|
|
303
|
+
} finally { dir.closeSync(); }
|
|
304
|
+
return { files: files.sort((a, b) => a.id.localeCompare(b.id)), bounded, unavailable: false };
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Where a host's capture is read from; doctor reports this, never content. */
|
|
308
|
+
export function hostIngestSource(kind: HostIngestKind, env: NodeJS.ProcessEnv = process.env): { path: string; state: "ready" | "absent" | "wal_pending" } {
|
|
309
|
+
const path = kind === "gemini" ? join(geminiRoot(env), "tmp") : kind === "opencode" ? opencodeDatabase(env) : join(agyRoot(env), "brain");
|
|
310
|
+
const present = lstatSync(path, { throwIfNoEntry: false });
|
|
311
|
+
if (!present) return { path, state: "absent" };
|
|
312
|
+
if (kind === "opencode") { const wal = lstatSync(`${path}-wal`, { throwIfNoEntry: false }); if (wal && wal.size > 0) return { path, state: "wal_pending" }; }
|
|
313
|
+
return { path, state: "ready" };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** `amem ingest opencode|gemini|agy`: capture-only, one bounded pass, no resident process. */
|
|
317
|
+
export async function ingestHost(kind: HostIngestKind, options: HostIngestOptions): Promise<HostIngestReceipt> {
|
|
318
|
+
const records = recordIntakeCounts(kind !== "gemini");
|
|
319
|
+
const result: HostIngestReceipt = { records, files: 0, read: 0, imported: 0, skipped: 0, spooled: 0, remaining: false, errors: 0, unattributed: 0 };
|
|
320
|
+
const fail = (reason: NonNullable<HostIngestReceipt["reason"]>, remaining = false) => { result.errors++; result.reason ??= reason; result.remaining ||= remaining; };
|
|
321
|
+
if (!HOST_INGEST_KINDS.includes(kind) || options.since !== undefined && !Number.isFinite(Date.parse(options.since))
|
|
322
|
+
|| options.transcript !== undefined && (kind !== "gemini" || typeof options.transcript !== "string" || !isAbsolute(options.transcript) || options.transcript.includes("\0"))) { fail("source_bound"); return result; }
|
|
323
|
+
const env = options.env ?? process.env, since = options.since === undefined ? undefined : new Date(options.since).toISOString(), now = options.now ?? Date.now;
|
|
324
|
+
let capture: CaptureStore | undefined;
|
|
325
|
+
try {
|
|
326
|
+
const cwd = realPath(options.cwd), base = canonicalPath(options.base ?? memoryHome()), aliases = effectiveAliases(base);
|
|
327
|
+
const requested = memoryProjectKey(cwd, { repositoryIsolation: true }), project = aliases.get(requested) ?? requested;
|
|
328
|
+
const policyOptions = configuredPolicyOptions(base, cwd, options.policy), policy = createStandalonePolicy(policyOptions);
|
|
329
|
+
const owned = new Map<string, boolean>();
|
|
330
|
+
const ownProject = (origin: string | undefined) => {
|
|
331
|
+
if (!origin || !isAbsolute(expandHome(origin))) return false;
|
|
332
|
+
// Memoized: a project key resolves the repository root, and many sessions share one origin.
|
|
333
|
+
const known = owned.get(origin); if (known !== undefined) return known;
|
|
334
|
+
let mine = false;
|
|
335
|
+
try { const key = memoryProjectKey(realPath(expandHome(origin)), { repositoryIsolation: true }); mine = (aliases.get(key) ?? key) === project; } catch { mine = false; }
|
|
336
|
+
owned.set(origin, mine); return mine;
|
|
337
|
+
};
|
|
338
|
+
// Discovery first, so a host with no store opens no capture shard.
|
|
339
|
+
const sessions: Session[] = [];
|
|
340
|
+
// The cursor directory is found through a read-only capture view, which creates nothing; when the shard does not exist yet nothing is warm.
|
|
341
|
+
let cursorRoot: string | null | undefined;
|
|
342
|
+
const unchanged = (stamp: string, source: string) => {
|
|
343
|
+
if (cursorRoot === undefined) { try { const view = new CaptureStore({ memoryDir: base, project, readOnly: true }); cursorRoot = join(view.dir, "ingest"); view.close(); } catch { cursorRoot = null; } }
|
|
344
|
+
return cursorRoot !== null && loadSeen(seenFile(cursorRoot, kind, source)).stamp === stamp;
|
|
345
|
+
};
|
|
346
|
+
if (kind === "gemini") {
|
|
347
|
+
const found = options.transcript !== undefined ? { files: [options.transcript], bounded: false, unavailable: false } : geminiFiles(env);
|
|
348
|
+
if (found.unavailable) { fail("source_unavailable"); return result; }
|
|
349
|
+
if (found.bounded) { result.remaining = true; result.reason = "source_bound"; }
|
|
350
|
+
for (const file of found.files.slice(0, MAX_SESSIONS)) {
|
|
351
|
+
const stat = lstatSync(file, { throwIfNoEntry: false });
|
|
352
|
+
// D3 before any read: a session whose project root is another project's (or missing) is never parsed.
|
|
353
|
+
if (!ownProject(geminiOrigin(file))) { result.files++; result.unattributed!++; continue; }
|
|
354
|
+
if (stat && unchanged(`${stat.ino}:${stat.size}:${stat.mtimeMs}`, file)) { result.files++; continue; }
|
|
355
|
+
try {
|
|
356
|
+
const { bytes, stat } = readPublic(file, MAX_SOURCE_BYTES);
|
|
357
|
+
const session = geminiSession(file, bytes, `${stat.ino}:${stat.size}:${stat.mtimeMs}`);
|
|
358
|
+
if (session) sessions.push(session); else fail("schema_or_time");
|
|
359
|
+
} catch { fail("source_unavailable"); }
|
|
360
|
+
}
|
|
361
|
+
} else if (kind === "opencode") {
|
|
362
|
+
const file = opencodeDatabase(env);
|
|
363
|
+
if (!lstatSync(file, { throwIfNoEntry: false })) { fail("source_unavailable"); return result; }
|
|
364
|
+
let opened: ReturnType<typeof snapshotDatabase>;
|
|
365
|
+
try { opened = snapshotDatabase(file); } catch { fail("source_unavailable"); return result; }
|
|
366
|
+
// Condition 2: a store with uncheckpointed WAL frames is skipped and reported, never read stale.
|
|
367
|
+
if ("walPending" in opened) { fail("source_unavailable", true); return result; }
|
|
368
|
+
try { sessions.push(...opencodeSessions(opened.db, now())); } catch { fail("schema_or_time"); } finally { opened.db.close(); }
|
|
369
|
+
} else {
|
|
370
|
+
const root = agyRoot(env), found = agyFiles(root);
|
|
371
|
+
if (found.unavailable) { fail("source_unavailable"); return result; }
|
|
372
|
+
if (found.bounded) { result.remaining = true; result.reason = "source_bound"; }
|
|
373
|
+
const workspaces = agyWorkspaces(root);
|
|
374
|
+
if (workspaces && "walPending" in workspaces) { fail("source_unavailable", true); return result; }
|
|
375
|
+
for (const { id, file } of found.files.slice(0, MAX_SESSIONS)) {
|
|
376
|
+
const stat = lstatSync(file, { throwIfNoEntry: false });
|
|
377
|
+
if (!stat) continue;
|
|
378
|
+
const workspace = workspaces?.get(id), stamp = `${stat.ino}:${stat.size}:${stat.mtimeMs}:${JSON.stringify(workspace ?? null)}`;
|
|
379
|
+
// D3 before any read: the conversation's workspace list is in the summaries, so a foreign or multi-root one is never parsed.
|
|
380
|
+
const uris = workspace?.uris ?? [];
|
|
381
|
+
let origin: string | undefined; if (uris.length === 1) { try { origin = fileURLToPath(uris[0]!); } catch { origin = undefined; } }
|
|
382
|
+
if (uris.length !== 1 || !ownProject(origin)) { result.files++; result.unattributed!++; continue; }
|
|
383
|
+
// Warm pass: an unchanged file whose cursor matches is not read again.
|
|
384
|
+
if (unchanged(stamp, file)) { result.files++; continue; }
|
|
385
|
+
try {
|
|
386
|
+
const { bytes, stat: read } = readPublic(file, MAX_SOURCE_BYTES);
|
|
387
|
+
const session = agySession(id, file, bytes, `${read.ino}:${read.size}:${read.mtimeMs}:${JSON.stringify(workspace ?? null)}`, workspace);
|
|
388
|
+
if (session) sessions.push(session); else fail("schema_or_time");
|
|
389
|
+
} catch { fail("source_unavailable"); }
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
if (!sessions.length) return result;
|
|
393
|
+
capture = new CaptureStore({ memoryDir: base, project, cwd });
|
|
394
|
+
const cursorDir = join(capture.dir, "ingest"); mkdirSync(cursorDir, { recursive: true, mode: 0o700 }); chmodSync(cursorDir, 0o700);
|
|
395
|
+
const enabled = recordsEnabled(base, cwd);
|
|
396
|
+
for (const session of sessions) {
|
|
397
|
+
result.files++;
|
|
398
|
+
// D3: a whole session belongs to the one project directory it is bound to; anything else is skipped.
|
|
399
|
+
if (session.ambiguous || !ownProject(session.origin)) { result.unattributed!++; result.skipped += session.messages.length; continue; }
|
|
400
|
+
const file = seenFile(cursorDir, kind, session.source), seen = loadSeen(file);
|
|
401
|
+
const fresh = session.messages.filter(message => !seen.ids.includes(hash(`${kind}\n${session.id}\n${message.key}`)));
|
|
402
|
+
if (seen.stamp === session.stamp && !fresh.length) continue;
|
|
403
|
+
const sessionKey = captureSessionKey(`${kind}:${session.id}`);
|
|
404
|
+
for (const message of fresh) {
|
|
405
|
+
result.read++;
|
|
406
|
+
const receipt = hash(`${kind}\n${session.id}\n${message.key}`);
|
|
407
|
+
if (since !== undefined && message.at < since) { result.skipped++; seen.ids.push(receipt); continue; }
|
|
408
|
+
const input: CaptureInput = { ...message.input, project, at: message.at, ...(sessionKey ? { session: sessionKey } : {}) } as CaptureInput;
|
|
409
|
+
if (!await policy.screen(message.sources) || !await policy.screen(input)) { result.skipped++; seen.ids.push(receipt); continue; }
|
|
410
|
+
// D4: keyed by session and message id, so a rewritten message never adds a second row.
|
|
411
|
+
const appended = capture.append(input, { receipt });
|
|
412
|
+
if ("spooled" in appended) result.spooled++; else if (appended.already) result.skipped++; else result.imported++;
|
|
413
|
+
if (message.recordText?.includes("amem:")) {
|
|
414
|
+
const parsed = parseRecordLines(message.recordText);
|
|
415
|
+
const found = parsed.records.length + Object.values(parsed.drops).reduce<number>((total, count) => total + (count ?? 0), 0);
|
|
416
|
+
records.found += found;
|
|
417
|
+
for (const [reason, count] of Object.entries(parsed.drops)) recordRefusal(records, reason as never, count!);
|
|
418
|
+
if (!message.recordFinal) { if (parsed.records.length) recordRefusal(records, "finality-unavailable", parsed.records.length); }
|
|
419
|
+
else if (!enabled) { if (parsed.records.length) recordRefusal(records, "record_policy", parsed.records.length); }
|
|
420
|
+
else {
|
|
421
|
+
// Appended directly with its own receipt instead of through the hook spool, so the spool format and its older readers are unchanged.
|
|
422
|
+
for (const record of parsed.records) {
|
|
423
|
+
const row: CaptureInput = { project, agent: kind, event: "Record", excerpt: record.line, paths: record.anchors, at: message.at, ...(sessionKey ? { session: sessionKey } : {}) };
|
|
424
|
+
if (stripPrivateSpans(record.line) !== record.line || !await policy.screen({ cwd, input: row, paths: record.anchors.map(anchor => anchor.split("#")[0]!) })) { recordRefusal(records, "record_policy"); continue; }
|
|
425
|
+
try {
|
|
426
|
+
const stored = capture.append(row, { receipt: hash(`${kind}\n${session.id}\n${message.key}\nrecord\n${record.line}`) });
|
|
427
|
+
if ("already" in stored && stored.already) records.duplicatesSkipped++; else records.staged++;
|
|
428
|
+
} catch (error) { if (error instanceof RecordNormalizationRefusal) recordRefusal(records, "record_length"); else throw error; }
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
seen.ids.push(receipt);
|
|
433
|
+
}
|
|
434
|
+
seen.stamp = session.stamp;
|
|
435
|
+
try { saveSeen(file, seen); } catch { fail("cursor_busy"); }
|
|
436
|
+
}
|
|
437
|
+
} catch { fail("scope_changed"); }
|
|
438
|
+
finally { capture?.close(); }
|
|
439
|
+
return result;
|
|
440
|
+
}
|