@tangle-network/harness-sessions 0.4.0 → 1.0.1

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
@@ -86,6 +86,7 @@ harness-sessions read <file|home|capture> [--harness h] [--session id] [--summar
86
86
  - A session with zero model calls is not the trace of a turn.
87
87
  - `locate(home, { cwd })` keeps a session whose recorded cwd is `cwd` or lies under it on a path boundary (`withinPath`): `/w/agent` matches `/w/agent/sub`, never `/w/agent-dev-container`. Every store is resolved against the `home` given; only the Codex environment overrides above depend on the process.
88
88
  - An unparsable record is counted in `integrity.unparsedRecords` and never stops a read (`corruption: 'strict'` throws instead). A record cut off at the end of a live copy is reported as a torn tail, not as corruption.
89
+ - Kimi discovery refuses a selected wire path that is a symlink, directory or special file; an unrelated native ID remains absent. JSONL reads recheck the opened descriptor as a regular file with `O_NOFOLLOW` and `O_NONBLOCK`, including after a located path is replaced. Platforms without these flags refuse the read. This protects the final file component, not ancestor-directory confinement; existing Codex home-directory aliases and SQLite's separate symlink policy remain unchanged. Kimi refs retain recorded context companion inventory.
89
90
  - `ending.status` is `completed`, `error`, `aborted` or `open`. `open` means the records stop mid-turn: the turn was still running or the process died.
90
91
  - An OpenCode store is opened read-only where it lies, with no copy: SQLite never writes the store or its write-ahead log. With a log present it reads the log's committed rows and keeps only its own shared-memory index (`-shm`) current; without one the store is opened immutable and nothing is created beside it. A store SQLite cannot open in place (a log with no `-shm` in a directory it cannot write, such as a capture on read-only storage, or any store under Node before 22.15, whose `node:sqlite` takes no URI file names) is read from a private copy. `integrity.sourceFiles` names the session as `<store>#session=<id>` with a digest of the rows read for it.
91
92
 
@@ -48,7 +48,6 @@ function usageOf(value) {
48
48
  export function createFold(ref, mode, stats) {
49
49
  const builder = new SessionBuilder(HARNESS, FORMAT, EVIDENCE[FORMAT].servedModel, mode, ref.nativeSessionId, ref.parentNativeSessionId);
50
50
  let turn = 0;
51
- let calls = 0;
52
51
  let step = null;
53
52
  let lastToolCall = null;
54
53
  let aborted = null;
@@ -61,8 +60,7 @@ export function createFold(ref, mode, stats) {
61
60
  const openStep = (at) => {
62
61
  if (step)
63
62
  return step;
64
- calls += 1;
65
- const id = `${builder.nativeSessionId}:turn:${turn}:step:${calls}`;
63
+ const id = `${builder.nativeSessionId}:turn:${turn}:step:${builder.modelCalls.length + 1}`;
66
64
  const call = builder.modelCall({ id, at, provider: null, servedModel: null, requestedModel: null, usage: null, costUsd: null, stopReason: null, error: null });
67
65
  builder.message({ id: `${id}:message`, role: 'assistant', actor: 'agent', at, modelCallId: id, parts: [] });
68
66
  step = { call, messageId: `${id}:message` };
@@ -168,9 +166,8 @@ export function createFold(ref, mode, stats) {
168
166
  }
169
167
  case 'StepRetry': {
170
168
  // A failed attempt Kimi retried: a model call that returned no answer.
171
- calls += 1;
172
169
  builder.modelCall({
173
- id: `${builder.nativeSessionId}:turn:${turn}:retry:${calls}`, at, provider: null, servedModel: null, requestedModel: null, usage: null, costUsd: null, stopReason: null,
170
+ id: `${builder.nativeSessionId}:turn:${turn}:retry:${builder.modelCalls.length + 1}`, at, provider: null, servedModel: null, requestedModel: null, usage: null, costUsd: null, stopReason: null,
174
171
  error: sessionError(str(payload.error_type) ?? 'retry', `${str(payload.error_type) ?? 'error'}${payload.status_code ? ` (status ${String(payload.status_code)})` : ''}`, at, count(payload.status_code)),
175
172
  });
176
173
  break;
@@ -235,20 +232,18 @@ async function locate(home, opts) {
235
232
  const root = join(home, store.root);
236
233
  const pattern = storeGlob('globs' in store ? store.globs.session : WIRE);
237
234
  const children = storeGlob(CHILD_WIRE);
238
- for (const rel of await walkFiles(root)) {
239
- if (!pattern.test(rel) && !children.test(rel))
240
- continue;
235
+ const matches = (rel) => {
241
236
  const { id, parent } = sessionIdentity(rel);
242
- // A parent lookup includes its recorded child wires; a child lookup selects that agent.
243
- if (opts.nativeSessionId && id !== opts.nativeSessionId && parent !== opts.nativeSessionId)
244
- continue;
237
+ return (pattern.test(rel) || children.test(rel)) && (!opts.nativeSessionId || id === opts.nativeSessionId || parent === opts.nativeSessionId);
238
+ };
239
+ for (const rel of await walkFiles(root, undefined, matches)) {
245
240
  const path = join(root, rel);
246
241
  const mtime = await mtimeMs(path);
247
242
  if (opts.sinceMs && mtime < opts.sinceMs)
248
243
  continue;
249
244
  const context = join(dirname(path), 'context.jsonl');
250
245
  const files = (await mtimeMs(context)) > 0 ? [path, context] : [path];
251
- const ref = { harness: HARNESS, format: FORMAT, nativeSessionId: id, path, files, home, cwd: null, mtimeMs: mtime, parentNativeSessionId: parent };
246
+ const ref = { ...kimiRefForFile(path), files, home, mtimeMs: mtime };
252
247
  if (opts.cwd) {
253
248
  ref.cwd = (await fold(ref, 'summary', {})).cwd;
254
249
  if (ref.cwd === null || !withinPath(ref.cwd, opts.cwd))
package/dist/source.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { createReadStream, rmSync } from 'node:fs';
3
- import { copyFile, mkdtemp, realpath, stat } from 'node:fs/promises';
2
+ import { constants, rmSync } from 'node:fs';
3
+ import { copyFile, mkdtemp, open, realpath, stat } from 'node:fs/promises';
4
4
  import { createRequire } from 'node:module';
5
5
  import { tmpdir } from 'node:os';
6
6
  import { join } from 'node:path';
@@ -61,45 +61,55 @@ export async function* readJsonlRecords(path, stats, options = {}) {
61
61
  }
62
62
  return value;
63
63
  };
64
- const stream = createReadStream(path, { highWaterMark: 1 << 20, signal: options.signal });
65
- for await (const chunk of stream) {
66
- hash.update(chunk);
67
- stats.bytes += chunk.length;
68
- let start = 0;
69
- for (;;) {
70
- const index = chunk.indexOf(NEWLINE, start);
71
- if (index === -1)
72
- break;
73
- let line;
74
- if (pendingBytes > 0) {
75
- pending.push(chunk.subarray(start, index));
76
- line = Buffer.concat(pending);
77
- pending = [];
78
- pendingBytes = 0;
64
+ if (typeof constants.O_NOFOLLOW !== 'number' || typeof constants.O_NONBLOCK !== 'number')
65
+ throw new Error('Safe native JSONL reads require O_NOFOLLOW and O_NONBLOCK');
66
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
67
+ try {
68
+ if (!(await file.stat()).isFile())
69
+ throw new Error(`${path}: native session must be a regular file`);
70
+ const stream = file.createReadStream({ highWaterMark: 1 << 20, signal: options.signal, autoClose: false });
71
+ for await (const chunk of stream) {
72
+ hash.update(chunk);
73
+ stats.bytes += chunk.length;
74
+ let start = 0;
75
+ for (;;) {
76
+ const index = chunk.indexOf(NEWLINE, start);
77
+ if (index === -1)
78
+ break;
79
+ let line;
80
+ if (pendingBytes > 0) {
81
+ pending.push(chunk.subarray(start, index));
82
+ line = Buffer.concat(pending);
83
+ pending = [];
84
+ pendingBytes = 0;
85
+ }
86
+ else {
87
+ line = chunk.subarray(start, index);
88
+ }
89
+ const record = parse(line, true);
90
+ if (record !== undefined) {
91
+ stats.line = lineNumber;
92
+ yield record;
93
+ }
94
+ start = index + 1;
79
95
  }
80
- else {
81
- line = chunk.subarray(start, index);
96
+ if (start < chunk.length) {
97
+ pending.push(chunk.subarray(start));
98
+ pendingBytes += chunk.length - start;
82
99
  }
83
- const record = parse(line, true);
100
+ }
101
+ if (pendingBytes > 0) {
102
+ const record = parse(Buffer.concat(pending), false);
84
103
  if (record !== undefined) {
85
104
  stats.line = lineNumber;
86
105
  yield record;
87
106
  }
88
- start = index + 1;
89
- }
90
- if (start < chunk.length) {
91
- pending.push(chunk.subarray(start));
92
- pendingBytes += chunk.length - start;
93
107
  }
108
+ stats.sha256 = `sha256:${hash.digest('hex')}`;
94
109
  }
95
- if (pendingBytes > 0) {
96
- const record = parse(Buffer.concat(pending), false);
97
- if (record !== undefined) {
98
- stats.line = lineNumber;
99
- yield record;
100
- }
110
+ finally {
111
+ await file.close();
101
112
  }
102
- stats.sha256 = `sha256:${hash.digest('hex')}`;
103
113
  }
104
114
  export function newSourceStats(path) {
105
115
  return { path, sha256: '', bytes: 0, unparsed: 0, tornTail: false, line: 0 };
package/dist/stores.d.ts CHANGED
@@ -1,13 +1,10 @@
1
- import type { NativeSessionStore } from './schema.js';
2
1
  export { assertStoreRoot, CODEX_HOME_RULE, EVIDENCE, isCodexHome, SESSION_FORMAT_IDS, STORES, storeGlob, withinPath } from './catalog.js';
3
- /** Every file under `dir`, as paths relative to it with `/` separators. Missing dirs yield none. */
4
- export declare function walkFiles(dir: string, signal?: AbortSignal): Promise<string[]>;
2
+ /** Regular files under `dir`; an optional matcher refuses selected unsafe entries before descent. */
3
+ export declare function walkFiles(dir: string, signal?: AbortSignal, matches?: (path: string) => boolean): Promise<string[]>;
5
4
  /** Session files a locate reads at once: a store holds thousands, and each read waits on the disk. */
6
5
  export declare const LOCATE_READS = 32;
7
6
  /** `fn` over `items`, at most `limit` at a time, with the results in the order of `items`. */
8
7
  export declare function mapLimit<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]>;
9
- /** Files under `home` that one store glob matches, as absolute paths. */
10
- export declare function storeFiles(home: string, store: NativeSessionStore, glob: string, nativeSessionId?: string): Promise<string[]>;
11
8
  export declare function mtimeMs(path: string): Promise<number>;
12
9
  /**
13
10
  * Every Codex home under `home`, by `CODEX_HOME_RULE`: `home` itself when it is one (a fleet seat's
package/dist/stores.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { readdir, realpath, stat } from 'node:fs/promises';
2
2
  import { homedir } from 'node:os';
3
3
  import { join, relative, resolve, sep } from 'node:path';
4
- import { CODEX_HOME_RULE, isCodexHome, storeGlob } from './catalog.js';
4
+ import { CODEX_HOME_RULE, isCodexHome } from './catalog.js';
5
5
  import { isMissing } from './source.js';
6
6
  export { assertStoreRoot, CODEX_HOME_RULE, EVIDENCE, isCodexHome, SESSION_FORMAT_IDS, STORES, storeGlob, withinPath } from './catalog.js';
7
- /** Every file under `dir`, as paths relative to it with `/` separators. Missing dirs yield none. */
8
- export async function walkFiles(dir, signal) {
7
+ /** Regular files under `dir`; an optional matcher refuses selected unsafe entries before descent. */
8
+ export async function walkFiles(dir, signal, matches) {
9
9
  const out = [];
10
10
  const visit = async (current) => {
11
11
  signal?.throwIfAborted();
@@ -20,10 +20,14 @@ export async function walkFiles(dir, signal) {
20
20
  }
21
21
  for (const entry of entries) {
22
22
  const path = join(current, entry.name);
23
+ const rel = relative(dir, path).split(sep).join('/');
24
+ const matched = matches?.(rel);
25
+ if (matched && !entry.isFile())
26
+ throw new Error(`${path}: native session must be a regular file, not a directory, link or special file`);
23
27
  if (entry.isDirectory())
24
28
  await visit(path);
25
- else if (entry.isFile())
26
- out.push(relative(dir, path).split(sep).join('/'));
29
+ else if (entry.isFile() && matched !== false)
30
+ out.push(rel);
27
31
  }
28
32
  };
29
33
  await visit(dir);
@@ -45,12 +49,6 @@ export async function mapLimit(items, limit, fn) {
45
49
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
46
50
  return results;
47
51
  }
48
- /** Files under `home` that one store glob matches, as absolute paths. */
49
- export async function storeFiles(home, store, glob, nativeSessionId) {
50
- const root = join(home, store.root);
51
- const pattern = storeGlob(glob, nativeSessionId);
52
- return (await walkFiles(root)).filter((path) => pattern.test(path)).map((path) => join(root, path));
53
- }
54
52
  export async function mtimeMs(path) {
55
53
  try {
56
54
  return (await stat(path)).mtimeMs;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/harness-sessions",
3
- "version": "0.4.0",
3
+ "version": "1.0.1",
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,
@@ -40,8 +40,8 @@
40
40
  "LICENSE"
41
41
  ],
42
42
  "dependencies": {
43
- "@tangle-network/agent-core": "^0.15.0",
44
- "@tangle-network/agent-trace-contract": "^2.1.0"
43
+ "@tangle-network/agent-core": "^1.0.0",
44
+ "@tangle-network/agent-trace-contract": "^2.2.0"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/node": "26.6.5",