@tangle-network/harness-sessions 1.0.15 → 1.0.16

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/README.md CHANGED
@@ -58,7 +58,7 @@ For a producer or retained reader with an already attested file inventory, `read
58
58
  ## Use
59
59
 
60
60
  ```ts
61
- import { readerFor, listCapture, toChatMessages, toOtlpSpans, toTurns } from '@tangle-network/harness-sessions'
61
+ import { readerFor, listCapture, nativeStoreSessions, toChatMessages, toOtlpSpans, toTurns } from '@tangle-network/harness-sessions'
62
62
 
63
63
  // Sessions in a HOME, through the harness's declared store
64
64
  const reader = readerFor('pi')
@@ -67,10 +67,16 @@ for (const ref of await reader.locate('/home/agent')) {
67
67
  const session = await reader.read(ref) // full fidelity: nothing is truncated
68
68
  }
69
69
 
70
+ // A copied or live SQLite store, optionally restricted to a recorded session
71
+ const refs = await nativeStoreSessions(storePath, { nativeSessionId })
72
+ for (const ref of refs) await readerFor(ref.harness).read(ref)
73
+
70
74
  // Sessions in a capture (provider retention layout today, raw-evidence archive v2 when given)
71
75
  const { sessions, missing } = await listCapture(captureDir)
72
76
  ```
73
77
 
78
+ The SDK and `harness-sessions read <file>` select OpenCode, Hermes and OpenClaw by database schema. NanoClaw uses the inbound and outbound databases in its session directory. A session reference lists its database files and any existing SQLite sidecars. A foreign schema or an absent session ID returns an empty list. Pass `harness` to resolve a database with more than one native schema.
79
+
74
80
  Projections trim; the reader never does:
75
81
 
76
82
  - `toChatMessages(session)`: agent-eval's chat-with-tools messages.
package/dist/capture.js CHANGED
@@ -3,9 +3,7 @@ import { readJsonValues } from './manifest-scan.js';
3
3
  import { readdir, readFile } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { str } from './builder.js';
6
- import { opencodeSessionsInStore } from './formats/opencode.js';
7
- import { hermesSessionsInStore } from './formats/hermes.js';
8
- import { openclawSessionsInStore } from './formats/openclaw.js';
6
+ import { nativeStoreSessions } from './native-store.js';
9
7
  import { kimiRefForFile, linkKimiFamily } from './formats/kimi.js';
10
8
  import { maybeReaderFor, readerFor, readerForFormat } from './registry.js';
11
9
  import { isMissing } from './source.js';
@@ -78,6 +76,10 @@ async function fromV2(archiveDir, manifest, listing) {
78
76
  listing.missing.push({ sandboxSessionId: null, harness: copy.harness, reason: 'no_reader_for_harness', nativeSessionId: copy.nativeSessionId });
79
77
  continue;
80
78
  }
79
+ if (!reader.formats.includes(copy.format)) {
80
+ listing.missing.push({ sandboxSessionId: null, harness: copy.harness, reason: 'harness_format_mismatch', nativeSessionId: copy.nativeSessionId });
81
+ continue;
82
+ }
81
83
  const stores = reader.stores.filter((s) => s.format === copy.format);
82
84
  const store = stores.find((s) => copy.files.some((f) => storePathOf(f).includes(`${s.root}/`))) ?? stores[0] ?? reader.stores[0];
83
85
  const inStore = (path) => {
@@ -93,7 +95,18 @@ async function fromV2(archiveDir, manifest, listing) {
93
95
  continue;
94
96
  }
95
97
  const path = join(archiveDir, db.path);
96
- const refs = store.format === 'hermes.state-sqlite' ? await hermesSessionsInStore(path) : store.format === 'openclaw.session-jsonl' ? await openclawSessionsInStore(path) : await opencodeSessionsInStore(path, null, {});
98
+ let refs;
99
+ try {
100
+ refs = await nativeStoreSessions(path, { harness: reader.harness });
101
+ }
102
+ catch (error) {
103
+ listing.missing.push({
104
+ sandboxSessionId: null, harness: copy.harness, nativeSessionId: copy.nativeSessionId, path: db.path,
105
+ reason: isMissing(error) ? 'store_file_missing' : 'store_unreadable',
106
+ detail: error instanceof Error ? error.message : String(error),
107
+ });
108
+ continue;
109
+ }
97
110
  const children = new Map();
98
111
  for (const ref of refs)
99
112
  if (ref.parentNativeSessionId) {
package/dist/cli.js CHANGED
@@ -1,13 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { stat } from 'node:fs/promises';
3
- import { join } from 'node:path';
3
+ import { join, resolve, sep } from 'node:path';
4
4
  import { listCapture, RETENTION_SESSIONS } from './capture.js';
5
- import { claudeCodeRefForFile } from './formats/claude-code.js';
6
- import { codexRefForFile } from './formats/codex.js';
7
- import { opencodeSessionsInStore } from './formats/opencode.js';
8
- import { piRefForFile } from './formats/pi.js';
9
- import { kimiRefForFile } from './formats/kimi.js';
10
- import { factoryRefForFile } from './formats/factory.js';
5
+ import { isNativeStoreDatabase, nativeStoreSessions } from './native-store.js';
11
6
  import { listReaders, readerFor } from './registry.js';
12
7
  function usage() {
13
8
  process.stderr.write('usage: harness-sessions read <file|home|capture> [--harness h] [--session id] [--cwd dir] [--summary] [--json]\n');
@@ -22,31 +17,21 @@ async function isDir(path) {
22
17
  }
23
18
  }
24
19
  function harnessOfFile(path) {
25
- if (/\.db$/u.test(path))
26
- return 'opencode';
27
- if (/(^|\/)\.claude\/projects\//u.test(path))
28
- return 'claude-code';
29
- if (/(^|\/)\.codex\/sessions\//u.test(path) || /rollout-[^/]*\.jsonl$/u.test(path))
30
- return 'codex';
31
- if (/(^|\/)\.pi\/agent\/sessions\//u.test(path))
32
- return 'pi';
33
- if (/(^|\/)\.kimi(?:-code)?\/sessions\/.+\/wire\.jsonl$/u.test(path))
34
- return 'kimi-code';
35
- if (/(^|\/)\.factory\/sessions\//u.test(path))
36
- return 'factory-droids';
37
- return null;
20
+ const absolute = resolve(path).split(sep).join('/');
21
+ const known = listReaders().find(reader => reader.stores.some(store => absolute.includes('/' + store.root + '/')));
22
+ return known?.harness ?? (/rollout-[^/]*\.jsonl$/u.test(path) ? 'codex' : null);
38
23
  }
39
24
  async function refsForFile(path, harness, session) {
25
+ if (await isNativeStoreDatabase(path)) {
26
+ return nativeStoreSessions(path, { ...(harness && { harness }), ...(session && { nativeSessionId: session }) });
27
+ }
40
28
  const h = harness ?? harnessOfFile(path);
41
29
  if (h === null)
42
30
  throw new Error(`cannot tell which harness wrote ${path}; pass --harness`);
43
31
  const reader = readerFor(h);
44
- if (reader.harness === 'opencode')
45
- return opencodeSessionsInStore(path, null, session ? { nativeSessionId: session } : {});
46
- const ref = reader.harness === 'claude-code'
47
- ? claudeCodeRefForFile(path, /\/subagents\//u.test(path) ? 'parent' : null)
48
- : reader.harness === 'codex' ? codexRefForFile(path) : reader.harness === 'kimi-code' ? kimiRefForFile(path) : reader.harness === 'factory-droids' ? factoryRefForFile(path) : piRefForFile(path);
49
- return [ref];
32
+ if (!reader.refForFile)
33
+ throw new Error(`The ${reader.harness} reader requires its native store`);
34
+ return [reader.refForFile(path)];
50
35
  }
51
36
  async function main(argv) {
52
37
  const [command, target, ...rest] = argv;
@@ -263,8 +263,13 @@ async function locate(home, opts) {
263
263
  }
264
264
  return refs.sort((a, b) => b.mtimeMs - a.mtimeMs);
265
265
  }
266
- export const claudeCodeReader = foldedReader({ harness: HARNESS, aliases: ['claude', 'claude-code-acp', 'claudish'], format: FORMAT, globs: { session: STORE.files[0], children: STORE.files[1] }, stores: CLAUDE_CODE_STORES }, locate, fold);
267
- export function claudeCodeRefForFile(path, parentNativeSessionId = null) {
266
+ export const claudeCodeReader = foldedReader({ harness: HARNESS, refForFile: claudeCodeRefForFile, aliases: ['claude', 'claude-code-acp', 'claudish'], format: FORMAT, globs: { session: STORE.files[0], children: STORE.files[1] }, stores: CLAUDE_CODE_STORES }, locate, fold);
267
+ function parentForFile(path) {
268
+ const parts = path.split(/[/\\]/u);
269
+ const index = parts.lastIndexOf('subagents');
270
+ return index > 0 && /^agent-.*\.jsonl$/u.test(parts.at(-1) ?? '') ? parts[index - 1] : null;
271
+ }
272
+ export function claudeCodeRefForFile(path, parentNativeSessionId = parentForFile(path)) {
268
273
  const name = basename(path, '.jsonl');
269
274
  return {
270
275
  harness: HARNESS,
@@ -407,7 +407,7 @@ async function locate(home, opts) {
407
407
  }
408
408
  return [...largest.values()].map((c) => c.ref).sort((a, b) => b.mtimeMs - a.mtimeMs);
409
409
  }
410
- export const codexReader = foldedReader({ harness: HARNESS, aliases: ['codex-acp', 'codex-cli'], format: FORMAT, stores: CODEX_STORES }, locate, fold);
410
+ export const codexReader = foldedReader({ harness: HARNESS, refForFile: codexRefForFile, aliases: ['codex-acp', 'codex-cli'], format: FORMAT, stores: CODEX_STORES }, locate, fold);
411
411
  export function codexRefForFile(path) {
412
412
  return {
413
413
  harness: HARNESS,
@@ -133,7 +133,7 @@ async function locate(home, opts) {
133
133
  }
134
134
  return filtered.sort((a, b) => b.mtimeMs - a.mtimeMs);
135
135
  }
136
- export const factoryReader = foldedReader({ harness: HARNESS, aliases: ['factory', 'droid'], format: FORMAT }, locate, fold);
136
+ export const factoryReader = foldedReader({ harness: HARNESS, refForFile: factoryRefForFile, aliases: ['factory', 'droid'], format: FORMAT }, locate, fold);
137
137
  export function factoryRefForFile(path) {
138
138
  return { harness: HARNESS, format: FORMAT, nativeSessionId: basename(path, '.jsonl'), path, files: [path], home: null, cwd: null, mtimeMs: 0, parentNativeSessionId: null };
139
139
  }
@@ -8,6 +8,6 @@ export interface SessionFold {
8
8
  }
9
9
  export declare function runFold(fold: SessionFold, source: RecordSource): Promise<SessionBuilder>;
10
10
  /** A reader: what differs between harnesses is how a session is found and folded. */
11
- export declare function foldedReader(reader: Pick<HarnessSessionReader, 'harness' | 'aliases'> & Partial<Pick<HarnessSessionReader, 'stores' | 'globs'>> & {
11
+ export declare function foldedReader(reader: Pick<HarnessSessionReader, 'harness' | 'aliases'> & Partial<Pick<HarnessSessionReader, 'stores' | 'globs' | 'refForFile' | 'sqlite'>> & {
12
12
  format: SessionFormatId;
13
13
  }, locate: (home: string, opts: LocateOptions) => Promise<SessionRef[]>, fold: (ref: SessionRef, mode: BuildMode, opts: ReadOptions) => Promise<SessionBuilder>): HarnessSessionReader;
@@ -14,6 +14,8 @@ export function foldedReader(reader, locate, fold) {
14
14
  stores: reader.stores ?? [store],
15
15
  globs: reader.globs ?? { session: store.files[0] },
16
16
  evidence: EVIDENCE[reader.format],
17
+ ...(reader.refForFile && { refForFile: reader.refForFile }),
18
+ ...(reader.sqlite && { sqlite: reader.sqlite }),
17
19
  locate: (home, opts = {}) => locate(home, opts),
18
20
  read: async (ref, opts = {}) => (await fold(ref, 'full', opts)).build(),
19
21
  summarize: async (ref, opts = {}) => (await fold(ref, 'summary', opts)).summary(),
@@ -109,7 +109,7 @@ async function fold(ref, mode, options) {
109
109
  const model = isRecord(summary) ? str(summary.current_model_id) : null;
110
110
  return runFold(createFold(ref, mode, records.stats, model, usageOf(await markedJson(ref, 'signals.json', 'primaryModelId'))), records);
111
111
  }
112
- export const grokReader = foldedReader({ harness: HARNESS, aliases: ['grok-build'], format: FORMAT }, async (home, opts) => {
112
+ export const grokReader = foldedReader({ harness: HARNESS, refForFile: grokRefForFile, aliases: ['grok-build'], format: FORMAT }, async (home, opts) => {
113
113
  const root = join(home, STORE.root);
114
114
  const pattern = storeGlob(STORE.files[0], opts.nativeSessionId);
115
115
  const refs = [];
@@ -1,3 +1,3 @@
1
1
  import type { HarnessSessionReader, SessionRef } from '../schema.js';
2
- export declare function hermesSessionsInStore(path: string): Promise<SessionRef[]>;
2
+ export declare function hermesSessionsInStore(path: string, nativeSessionId?: string): Promise<SessionRef[]>;
3
3
  export declare const hermesReader: HarnessSessionReader;
@@ -1,7 +1,7 @@
1
1
  import { foldedReader } from './fold.js';
2
2
  import { basename, join } from 'node:path';
3
3
  import { SessionBuilder, count, str, usageOrNull } from '../builder.js';
4
- import { withSqlite } from '../source.js';
4
+ import { sqliteStoreFiles, withSqlite } from '../source.js';
5
5
  import { EVIDENCE, STORES, mtimeMs, walkFiles } from '../stores.js';
6
6
  const FORMAT = 'hermes.state-sqlite';
7
7
  const STORE = STORES[FORMAT];
@@ -62,28 +62,30 @@ async function fold(ref, mode) {
62
62
  builder.inferEnding();
63
63
  return builder;
64
64
  }
65
- export async function hermesSessionsInStore(path) {
66
- const refs = [];
67
- await withSqlite(path, (db) => {
68
- for (const row of db.prepare('SELECT id FROM sessions').all()) {
69
- refs.push({ harness: HARNESS, format: FORMAT, nativeSessionId: row.id, path, files: [path], home: null, cwd: null, mtimeMs: 0, parentNativeSessionId: null });
70
- }
71
- }).catch(() => undefined);
72
- return refs;
65
+ async function sessionRefs(path, nativeSessionId) {
66
+ const [mtime, files] = await Promise.all([mtimeMs(path), sqliteStoreFiles(path)]);
67
+ return withSqlite(path, db => {
68
+ const rows = nativeSessionId === undefined ? db.prepare('SELECT id FROM sessions').all() : db.prepare('SELECT id FROM sessions WHERE id = ?').all(nativeSessionId);
69
+ return rows.map(row => ({ harness: HARNESS, format: FORMAT, nativeSessionId: String(row.id), path, files, home: null, cwd: null, mtimeMs: mtime, parentNativeSessionId: null }));
70
+ });
71
+ }
72
+ export function hermesSessionsInStore(path, nativeSessionId) {
73
+ return sessionRefs(path, nativeSessionId).catch(() => []);
73
74
  }
74
- export const hermesReader = foldedReader({ harness: HARNESS, aliases: [], format: FORMAT }, async (home, opts) => {
75
+ export const hermesReader = foldedReader({ harness: HARNESS, aliases: [], format: FORMAT,
76
+ sqlite: {
77
+ matches: has => has('sessions', 'input_tokens') && has('sessions', 'started_at') && has('messages', 'tool_calls') && has('messages', 'session_id'),
78
+ sessions: (path, opts) => sessionRefs(path, opts.nativeSessionId),
79
+ },
80
+ }, async (home, opts) => {
75
81
  const root = join(home, STORE.root);
76
82
  const refs = [];
77
83
  for (const rel of await walkFiles(root)) {
78
84
  if (basename(rel) !== 'state.db')
79
85
  continue;
80
86
  const path = join(root, rel);
81
- const mtime = await mtimeMs(path);
82
- for (const ref of await hermesSessionsInStore(path)) {
83
- if (opts.nativeSessionId && ref.nativeSessionId !== opts.nativeSessionId)
84
- continue;
85
- refs.push({ ...ref, home, mtimeMs: mtime });
86
- }
87
+ for (const ref of await hermesSessionsInStore(path, opts.nativeSessionId))
88
+ refs.push({ ...ref, home });
87
89
  }
88
90
  return refs;
89
91
  }, fold);
@@ -353,7 +353,7 @@ async function locate(home, opts) {
353
353
  }
354
354
  return selectedRefs.sort((a, b) => b.mtimeMs - a.mtimeMs);
355
355
  }
356
- export const kimiReader = foldedReader({ harness: HARNESS, aliases: ['kimi', 'kimi-cli'], format: FORMAT, globs: { session: WIRE, children: CHILD_WIRE }, stores: KIMI_STORES }, locate, fold);
356
+ export const kimiReader = foldedReader({ harness: HARNESS, refForFile: kimiRefForFile, aliases: ['kimi', 'kimi-cli'], format: FORMAT, globs: { session: WIRE, children: CHILD_WIRE }, stores: KIMI_STORES }, locate, fold);
357
357
  function refForWire(path, storePath, indices) {
358
358
  const { id, parent, root } = sessionIdentity(storePath);
359
359
  let owner = parent;
@@ -1,7 +1,8 @@
1
1
  import { foldedReader } from './fold.js';
2
2
  import { basename, dirname, join } from 'node:path';
3
+ import { stat } from 'node:fs/promises';
3
4
  import { SessionBuilder } from '../builder.js';
4
- import { withSqlite } from '../source.js';
5
+ import { isMissing, sqliteStoreFiles, withSqlite } from '../source.js';
5
6
  import { EVIDENCE, STORES, mtimeMs, storeGlob, walkFiles } from '../stores.js';
6
7
  const FORMAT = 'nanoclaw.session-sqlite';
7
8
  const STORE = STORES[FORMAT];
@@ -30,12 +31,47 @@ function readTable(db, table, role, builder) {
30
31
  async function fold(ref, mode) {
31
32
  const builder = new SessionBuilder(HARNESS, FORMAT, EVIDENCE[FORMAT].servedModel, mode, ref.nativeSessionId, ref.parentNativeSessionId);
32
33
  const dir = dirname(ref.path);
33
- await withSqlite(join(dir, 'inbound.db'), (db) => readTable(db, 'messages_in', 'user', builder)).catch(() => undefined);
34
+ try {
35
+ await withSqlite(join(dir, 'inbound.db'), db => readTable(db, 'messages_in', 'user', builder));
36
+ }
37
+ catch (error) {
38
+ if (!isMissing(error))
39
+ throw error;
40
+ }
34
41
  await withSqlite(join(dir, 'outbound.db'), (db) => readTable(db, 'messages_out', 'assistant', builder));
35
42
  builder.inferEnding();
36
43
  return builder;
37
44
  }
38
- export const nanoclawReader = foldedReader({ harness: HARNESS, aliases: [], format: FORMAT }, async (home, opts) => {
45
+ async function sessionRefs(path, nativeSessionId) {
46
+ const dir = dirname(path);
47
+ const outbound = join(dir, 'outbound.db');
48
+ const inbound = join(dir, 'inbound.db');
49
+ const ref = nanoclawRefForFile(outbound);
50
+ if (nativeSessionId !== undefined && nativeSessionId !== ref.nativeSessionId)
51
+ return [];
52
+ if (path === inbound)
53
+ await withSqlite(outbound, db => db.prepare('SELECT seq, kind, content FROM messages_out LIMIT 0').all());
54
+ const files = await sqliteStoreFiles(outbound);
55
+ try {
56
+ if ((await stat(inbound)).isFile()) {
57
+ if (path !== inbound)
58
+ await withSqlite(inbound, db => db.prepare('SELECT seq, kind, content FROM messages_in LIMIT 0').all());
59
+ files.push(...await sqliteStoreFiles(inbound));
60
+ }
61
+ }
62
+ catch (error) {
63
+ if (!isMissing(error))
64
+ throw error;
65
+ }
66
+ return [{ ...ref, files, mtimeMs: await mtimeMs(outbound) }];
67
+ }
68
+ export const nanoclawReader = foldedReader({ harness: HARNESS, aliases: [], format: FORMAT,
69
+ sqlite: {
70
+ matches: (has, path) => (basename(path) === 'outbound.db' && has('messages_out', 'seq') && has('messages_out', 'content'))
71
+ || (basename(path) === 'inbound.db' && has('messages_in', 'seq') && has('messages_in', 'content')),
72
+ sessions: (path, opts) => sessionRefs(path, opts.nativeSessionId),
73
+ },
74
+ }, async (home, opts) => {
39
75
  const root = join(home, STORE.root);
40
76
  const pattern = storeGlob(STORE.files[0], opts.nativeSessionId);
41
77
  const refs = [];
@@ -43,11 +79,10 @@ export const nanoclawReader = foldedReader({ harness: HARNESS, aliases: [], form
43
79
  if (!pattern.test(rel))
44
80
  continue;
45
81
  const path = join(root, rel);
46
- const id = basename(dirname(rel));
47
- const mtime = await mtimeMs(path);
48
- if ((opts.sinceMs && mtime < opts.sinceMs) || (opts.nativeSessionId && id !== opts.nativeSessionId))
49
- continue;
50
- refs.push({ harness: HARNESS, format: FORMAT, nativeSessionId: id, path, files: [path, join(dirname(path), 'inbound.db')], home, cwd: null, mtimeMs: mtime, parentNativeSessionId: null });
82
+ for (const ref of await sessionRefs(path, opts.nativeSessionId)) {
83
+ if (!opts.sinceMs || ref.mtimeMs >= opts.sinceMs)
84
+ refs.push({ ...ref, home });
85
+ }
51
86
  }
52
87
  return refs.sort((a, b) => b.mtimeMs - a.mtimeMs);
53
88
  }, fold);
@@ -1,3 +1,3 @@
1
1
  import type { HarnessSessionReader, SessionRef } from '../schema.js';
2
- export declare function openclawSessionsInStore(path: string): Promise<SessionRef[]>;
2
+ export declare function openclawSessionsInStore(path: string, nativeSessionId?: string): Promise<SessionRef[]>;
3
3
  export declare const openclawReader: HarnessSessionReader;
@@ -3,7 +3,7 @@ import { zstdDecompressSync } from 'node:zlib';
3
3
  import { join } from 'node:path';
4
4
  import { isRecord } from '@tangle-network/agent-core';
5
5
  import { SessionBuilder, count, str, textOf, usageOrNull } from '../builder.js';
6
- import { withSqlite } from '../source.js';
6
+ import { sqliteStoreFiles, withSqlite } from '../source.js';
7
7
  import { EVIDENCE, STORES, mtimeMs, walkFiles } from '../stores.js';
8
8
  const FORMAT = 'openclaw.session-jsonl';
9
9
  const STORE = STORES[FORMAT];
@@ -67,13 +67,15 @@ function readDb(db, sessionId, builder) {
67
67
  builder.message({ id, role: 'assistant', actor: 'agent', at, modelCallId, parts });
68
68
  }
69
69
  }
70
- export async function openclawSessionsInStore(path) {
71
- const refs = [];
72
- await withSqlite(path, (db) => {
73
- for (const row of db.prepare('SELECT session_id FROM session_windows').all())
74
- refs.push({ harness: HARNESS, format: FORMAT, nativeSessionId: row.session_id, path, files: [path], home: null, cwd: null, mtimeMs: 0, parentNativeSessionId: null });
75
- }).catch(() => undefined);
76
- return refs;
70
+ async function sessionRefs(path, nativeSessionId) {
71
+ const [mtime, files] = await Promise.all([mtimeMs(path), sqliteStoreFiles(path)]);
72
+ return withSqlite(path, db => {
73
+ const rows = nativeSessionId === undefined ? db.prepare('SELECT session_id FROM session_windows').all() : db.prepare('SELECT session_id FROM session_windows WHERE session_id = ?').all(nativeSessionId);
74
+ return rows.map(row => ({ harness: HARNESS, format: FORMAT, nativeSessionId: String(row.session_id), path, files, home: null, cwd: null, mtimeMs: mtime, parentNativeSessionId: null }));
75
+ });
76
+ }
77
+ export function openclawSessionsInStore(path, nativeSessionId) {
78
+ return sessionRefs(path, nativeSessionId).catch(() => []);
77
79
  }
78
80
  async function fold(ref, mode) {
79
81
  const builder = new SessionBuilder(HARNESS, FORMAT, EVIDENCE[FORMAT].servedModel, mode, ref.nativeSessionId, ref.parentNativeSessionId);
@@ -81,18 +83,19 @@ async function fold(ref, mode) {
81
83
  builder.inferEnding();
82
84
  return builder;
83
85
  }
84
- export const openclawReader = foldedReader({ harness: HARNESS, aliases: [], format: FORMAT }, async (home, opts) => {
86
+ export const openclawReader = foldedReader({ harness: HARNESS, aliases: [], format: FORMAT,
87
+ sqlite: {
88
+ matches: has => has('session_windows', 'session_id') && has('transcript_events', 'event_zstd') && has('transcript_events', 'seq'),
89
+ sessions: (path, opts) => sessionRefs(path, opts.nativeSessionId),
90
+ },
91
+ }, async (home, opts) => {
85
92
  const refs = [];
86
93
  for (const rel of await walkFiles(join(home, STORE.root))) {
87
94
  if (!rel.endsWith('openclaw-agent.sqlite'))
88
95
  continue;
89
96
  const path = join(home, STORE.root, rel);
90
- const mtime = await mtimeMs(path);
91
- for (const ref of await openclawSessionsInStore(path)) {
92
- if (opts.nativeSessionId && ref.nativeSessionId !== opts.nativeSessionId)
93
- continue;
94
- refs.push({ ...ref, home, mtimeMs: mtime });
95
- }
97
+ for (const ref of await openclawSessionsInStore(path, opts.nativeSessionId))
98
+ refs.push({ ...ref, home });
96
99
  }
97
100
  return refs.sort((a, b) => b.mtimeMs - a.mtimeMs);
98
101
  }, fold);
@@ -3,7 +3,7 @@ import { isRecord } from '@tangle-network/agent-core';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { join } from 'node:path';
5
5
  import { SessionBuilder, count, isoTime, sessionError, str, usageOrNull } from '../builder.js';
6
- import { isMissing, withSqlite } from '../source.js';
6
+ import { isMissing, sqliteStoreFiles, withSqlite } from '../source.js';
7
7
  import { EVIDENCE, STORES, mtimeMs, withinPath } from '../stores.js';
8
8
  const FORMAT = 'opencode.sqlite';
9
9
  const STORE = STORES[FORMAT];
@@ -197,21 +197,24 @@ async function fold(ref, mode, options) {
197
197
  return builder;
198
198
  }
199
199
  export async function opencodeSessionsInStore(path, home, opts = {}) {
200
- const mtime = await mtimeMs(path);
201
- const files = [path];
202
- for (const suffix of ['-wal', '-shm'])
203
- if ((await mtimeMs(`${path}${suffix}`)) > 0)
204
- files.push(`${path}${suffix}`);
200
+ const [mtime, files] = await Promise.all([mtimeMs(path), sqliteStoreFiles(path)]);
205
201
  return withSqlite(path, (db) => {
206
- const rows = db.prepare('SELECT id, parent_id, directory, time_updated FROM session ORDER BY time_updated DESC').all();
202
+ const query = 'SELECT id, parent_id, directory, time_updated FROM session';
203
+ const rows = (opts.nativeSessionId === undefined
204
+ ? db.prepare(query + ' ORDER BY time_updated DESC').all()
205
+ : db.prepare(query + ' WHERE id = ?').all(opts.nativeSessionId));
207
206
  return rows
208
- .filter((row) => (!opts.nativeSessionId || row.id === opts.nativeSessionId)
209
- && (!opts.cwd || withinPath(row.directory, opts.cwd))
207
+ .filter((row) => (!opts.cwd || withinPath(row.directory, opts.cwd))
210
208
  && (!opts.sinceMs || row.time_updated >= opts.sinceMs))
211
209
  .map((row) => ({ harness: HARNESS, format: FORMAT, nativeSessionId: row.id, path, files, home, cwd: row.directory, mtimeMs: row.time_updated || mtime, parentNativeSessionId: row.parent_id }));
212
210
  });
213
211
  }
214
- export const opencodeReader = foldedReader({ harness: HARNESS, aliases: ['opencode-acp', 'opencode-cli'], format: FORMAT }, async (home, opts) => {
212
+ export const opencodeReader = foldedReader({ harness: HARNESS, aliases: ['opencode-acp', 'opencode-cli'], format: FORMAT,
213
+ sqlite: {
214
+ matches: has => has('session', 'parent_id') && has('message', 'session_id') && has('part', 'message_id'),
215
+ sessions: (path, opts) => opencodeSessionsInStore(path, null, opts),
216
+ },
217
+ }, async (home, opts) => {
215
218
  const path = join(home, STORE.root, STORE.files[0]);
216
219
  try {
217
220
  return await opencodeSessionsInStore(path, home, opts);
@@ -167,7 +167,7 @@ async function locate(home, opts) {
167
167
  }
168
168
  return refs.sort((a, b) => b.mtimeMs - a.mtimeMs);
169
169
  }
170
- export const piReader = foldedReader({ harness: HARNESS, aliases: ['pi-coding-agent', 'pi-agent'], format: FORMAT }, locate, fold);
170
+ export const piReader = foldedReader({ harness: HARNESS, refForFile: piRefForFile, aliases: ['pi-coding-agent', 'pi-agent'], format: FORMAT }, locate, fold);
171
171
  export function piRefForFile(path) {
172
172
  return { harness: HARNESS, format: FORMAT, nativeSessionId: idFromName(path), path, files: [path], home: null, cwd: null, mtimeMs: 0, parentNativeSessionId: null };
173
173
  }
@@ -1,2 +1,3 @@
1
- import type { HarnessSessionReader } from '../schema.js';
1
+ import type { HarnessSessionReader, SessionRef } from '../schema.js';
2
+ export declare function primeRefForFile(path: string): SessionRef;
2
3
  export declare const primeReader: HarnessSessionReader;
@@ -9,11 +9,14 @@ const HARNESS = 'prime';
9
9
  function idFromName(path) {
10
10
  return basename(path, '.jsonl').replace(/^[\dTZ.:-]+_/u, '');
11
11
  }
12
+ export function primeRefForFile(path) {
13
+ return { harness: HARNESS, format: FORMAT, nativeSessionId: idFromName(path), path, files: [path], home: null, cwd: null, mtimeMs: 0, parentNativeSessionId: null };
14
+ }
12
15
  async function fold(ref, mode, opts) {
13
16
  const records = fileRecords(ref.path, { strict: opts.corruption === 'strict', signal: opts.signal });
14
17
  return runFold(createFold(ref, mode, records.stats, HARNESS, FORMAT), records);
15
18
  }
16
- export const primeReader = foldedReader({ harness: HARNESS, aliases: [], format: FORMAT }, async (home, opts) => {
19
+ export const primeReader = foldedReader({ harness: HARNESS, refForFile: primeRefForFile, aliases: [], format: FORMAT }, async (home, opts) => {
17
20
  const root = join(home, STORE.root);
18
21
  const pattern = storeGlob(STORE.files[0], opts.nativeSessionId);
19
22
  const refs = [];
@@ -21,10 +24,10 @@ export const primeReader = foldedReader({ harness: HARNESS, aliases: [], format:
21
24
  if (!pattern.test(rel))
22
25
  continue;
23
26
  const path = join(root, rel);
24
- const id = idFromName(rel);
25
- if (opts.nativeSessionId && id !== opts.nativeSessionId)
27
+ const ref = primeRefForFile(path);
28
+ if (opts.nativeSessionId && ref.nativeSessionId !== opts.nativeSessionId)
26
29
  continue;
27
- refs.push({ harness: HARNESS, format: FORMAT, nativeSessionId: id, path, files: [path], home, cwd: null, mtimeMs: await mtimeMs(path), parentNativeSessionId: null });
30
+ refs.push({ ...ref, home, mtimeMs: await mtimeMs(path) });
28
31
  }
29
32
  return refs.sort((a, b) => b.mtimeMs - a.mtimeMs);
30
33
  }, fold);
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export { HARNESS_SESSION_SCHEMA } from './schema.js';
3
3
  export { CLAUDE_CODE_STORES, CODEX_HOME_RULE, CODEX_STORES, EVIDENCE, KIMI_STORES, SESSION_FORMAT_IDS, STORES, assertStoreRoot, isCodexHome, storeGlob, withinPath } from './catalog.js';
4
4
  export { codexHomes } from './stores.js';
5
5
  export { knownHarnesses, listReaders, maybeReaderFor, readerFor, readerForFormat } from './registry.js';
6
+ export { isNativeStoreDatabase, nativeStoreSessions } from './native-store.js';
6
7
  export { claudeCodeReader, claudeCodeRefForFile } from './formats/claude-code.js';
7
8
  export { claudeRecordIsMachine, claudeTypedPromptText, type ClaudeRecordFacts } from './formats/claude-records.js';
8
9
  export { codexReader, codexRefForFile } from './formats/codex.js';
@@ -13,7 +14,7 @@ export { factoryReader, factoryRefForFile } from './formats/factory.js';
13
14
  export { grokReader, grokRefForFile } from './formats/grok.js';
14
15
  export { nanoclawReader, nanoclawRefForFile } from './formats/nanoclaw.js';
15
16
  export { hermesReader, hermesSessionsInStore } from './formats/hermes.js';
16
- export { primeReader } from './formats/prime.js';
17
+ export { primeReader, primeRefForFile } from './formats/prime.js';
17
18
  export { sandboxEventsSession, type SandboxEventsRun } from './formats/sandbox-events.js';
18
19
  export { openclawReader } from './formats/openclaw.js';
19
20
  export { listCapture, readCapture, RETENTION_MANIFEST_KIND, RETENTION_SESSIONS, type CaptureListing, type CapturedSessionRef, } from './capture.js';
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@ export { HARNESS_SESSION_SCHEMA } from './schema.js';
2
2
  export { CLAUDE_CODE_STORES, CODEX_HOME_RULE, CODEX_STORES, EVIDENCE, KIMI_STORES, SESSION_FORMAT_IDS, STORES, assertStoreRoot, isCodexHome, storeGlob, withinPath } from './catalog.js';
3
3
  export { codexHomes } from './stores.js';
4
4
  export { knownHarnesses, listReaders, maybeReaderFor, readerFor, readerForFormat } from './registry.js';
5
+ export { isNativeStoreDatabase, nativeStoreSessions } from './native-store.js';
5
6
  export { claudeCodeReader, claudeCodeRefForFile } from './formats/claude-code.js';
6
7
  export { claudeRecordIsMachine, claudeTypedPromptText } from './formats/claude-records.js';
7
8
  export { codexReader, codexRefForFile } from './formats/codex.js';
@@ -12,7 +13,7 @@ export { factoryReader, factoryRefForFile } from './formats/factory.js';
12
13
  export { grokReader, grokRefForFile } from './formats/grok.js';
13
14
  export { nanoclawReader, nanoclawRefForFile } from './formats/nanoclaw.js';
14
15
  export { hermesReader, hermesSessionsInStore } from './formats/hermes.js';
15
- export { primeReader } from './formats/prime.js';
16
+ export { primeReader, primeRefForFile } from './formats/prime.js';
16
17
  export { sandboxEventsSession } from './formats/sandbox-events.js';
17
18
  export { openclawReader } from './formats/openclaw.js';
18
19
  export { listCapture, readCapture, RETENTION_MANIFEST_KIND, RETENTION_SESSIONS, } from './capture.js';
@@ -0,0 +1,8 @@
1
+ import type { SessionRef } from './schema.js';
2
+ /** The file content identifies SQLite even when its name or enclosing store changed. */
3
+ export declare function isNativeStoreDatabase(path: string): Promise<boolean>;
4
+ /** Enumerate the owning reader's sessions. A foreign schema or absent ID has no matches. */
5
+ export declare function nativeStoreSessions(path: string, options?: {
6
+ harness?: string;
7
+ nativeSessionId?: string;
8
+ }): Promise<SessionRef[]>;
@@ -0,0 +1,39 @@
1
+ import { open } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { listReaders, readerFor } from './registry.js';
4
+ import { withSqlite } from './source.js';
5
+ const signature = Buffer.from('SQLite format 3\0');
6
+ /** The file content identifies SQLite even when its name or enclosing store changed. */
7
+ export async function isNativeStoreDatabase(path) {
8
+ const file = await open(path, 'r');
9
+ try {
10
+ const data = Buffer.alloc(signature.length);
11
+ const { bytesRead } = await file.read(data, 0, data.length, 0);
12
+ return bytesRead === data.length && data.equals(signature);
13
+ }
14
+ finally {
15
+ await file.close();
16
+ }
17
+ }
18
+ /** Enumerate the owning reader's sessions. A foreign schema or absent ID has no matches. */
19
+ export async function nativeStoreSessions(path, options = {}) {
20
+ const target = resolve(path);
21
+ const candidates = options.harness === undefined ? listReaders() : [readerFor(options.harness)];
22
+ const matches = await withSqlite(target, (db) => {
23
+ const columns = new Map();
24
+ const query = db.prepare('SELECT name FROM pragma_table_info(?)');
25
+ function hasColumn(table, column) {
26
+ let names = columns.get(table);
27
+ if (!names) {
28
+ names = new Set(query.all(table).map(row => String(row.name)));
29
+ columns.set(table, names);
30
+ }
31
+ return names.has(column);
32
+ }
33
+ return candidates.filter(reader => reader.sqlite?.matches(hasColumn, target));
34
+ });
35
+ if (matches.length > 1)
36
+ throw new Error(`Multiple harness schemas in ${target}: ${matches.map(r => r.harness).join(', ')}. Select a harness.`);
37
+ const store = matches[0]?.sqlite;
38
+ return store ? store.sessions(target, options) : [];
39
+ }
package/dist/schema.d.ts CHANGED
@@ -200,6 +200,13 @@ export interface HarnessSessionReader {
200
200
  children?: string;
201
201
  };
202
202
  evidence: SessionEvidenceSources;
203
+ /** Resolve a single native transcript file without enumerating a home directory. */
204
+ refForFile?(path: string): SessionRef;
205
+ /** Recognize and enumerate this harness's native SQLite store. */
206
+ sqlite?: {
207
+ matches(hasColumn: (table: string, column: string) => boolean, path: string): boolean;
208
+ sessions(path: string, options: LocateOptions): Promise<SessionRef[]>;
209
+ };
203
210
  locate(home: string, opts?: LocateOptions): Promise<SessionRef[]>;
204
211
  read(ref: SessionRef, opts?: ReadOptions): Promise<HarnessSession>;
205
212
  summarize(ref: SessionRef, opts?: Pick<ReadOptions, 'signal'>): Promise<SessionSummary>;
package/dist/source.d.ts CHANGED
@@ -32,5 +32,7 @@ export declare function textRecordsSync(text: string, stats: SourceStats, option
32
32
  firstLine?: number;
33
33
  }): Generator<Record<string, unknown>>;
34
34
  export declare function arrayRecordsSync(values: readonly unknown[], stats: SourceStats, firstLine?: number): Generator<Record<string, unknown>>;
35
+ /** Files needed to move a live SQLite store, including the write-ahead log when present. */
36
+ export declare function sqliteStoreFiles(path: string): Promise<string[]>;
35
37
  export declare function withSqlite<T>(path: string, use: (db: DatabaseSync) => T): Promise<T>;
36
38
  export declare function isMissing(error: unknown): boolean;
package/dist/source.js CHANGED
@@ -171,6 +171,15 @@ async function exists(path) {
171
171
  throw error;
172
172
  }
173
173
  }
174
+ /** Files needed to move a live SQLite store, including the write-ahead log when present. */
175
+ export async function sqliteStoreFiles(path) {
176
+ const files = [path];
177
+ for (const suffix of ['-wal', '-shm']) {
178
+ if (await exists(path + suffix))
179
+ files.push(path + suffix);
180
+ }
181
+ return files;
182
+ }
174
183
  async function openSqlite(path) {
175
184
  const mode = (await exists(`${path}-wal`)) ? 'mode=ro' : 'immutable=1';
176
185
  const { DatabaseSync } = loadSqlite();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/harness-sessions",
3
- "version": "1.0.15",
3
+ "version": "1.0.16",
4
4
  "description": "One reader for every coding-agent harness's native session (Claude Code, Codex, OpenCode, Pi): store layouts, a normalized session with messages, tool calls, served models, usage and ending errors, and projections to chat messages, OTLP spans and turns",
5
5
  "type": "module",
6
6
  "sideEffects": false,