@tangle-network/harness-sessions 1.0.16 → 1.0.18

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
@@ -25,6 +25,7 @@ npm install @tangle-network/harness-sessions
25
25
  | `codex` | `codex.rollout-jsonl` | `rollout-*-{id}.jsonl` under `sessions/` and `archived_sessions/` of every Codex home (below) | turn context (the configured model) | per response (`last_token_usage`); session total from `total_token_usage` |
26
26
  | `opencode` | `opencode.sqlite` | `.local/share/opencode/opencode.db` (shared by every session) | session record (`providerID/modelID`) | per step (`step-finish`) |
27
27
  | `pi` | `pi.session-jsonl` | `.pi/agent/sessions/**/*_{id}.jsonl` | session record (`provider/model`) | per assistant message |
28
+ | `prime` | `prime.session-jsonl` | `.prime-provider/prime-agent-dirs/**/sessions/*.jsonl` | session record (`provider/model`) | per assistant message |
28
29
  | `kimi-code` | `kimi.session-dir` | `.kimi-code/sessions/wd_<hash>/{id}/agents/main/wire.jsonl`; retained `.kimi/sessions/*/{id}/wire.jsonl` and child wires | requested model recorded separately; served identity unknown | per step, excluding mirrored and wrapped child events |
29
30
  | `factory-droids` | `factory.session-jsonl` | `.factory/sessions/*/{id}.jsonl` plus settings | configured model in settings (`turn-context`) | session total in settings |
30
31
 
@@ -39,6 +40,8 @@ Homes that resolve to one directory count once. A session copied into several ho
39
40
 
40
41
  `listReaders()` and the exported catalog own the complete installed format inventory.
41
42
 
43
+ Prime marks its session headers with `rlmDepth` (`isPrimeSessionHeader`); a marked session keeps its recorded ID, cwd and `parentSession`-proven parent wherever its file is copied or renamed, while an unmarked recording keeps its store-filename identity. A header that records a `parentSession` fork also surfaces `fork` provenance on the session and summary, and marks the prehistory it replayed from its parent per message (`inherited`); the reference itself is never dereferenced.
44
+
42
45
  Kimi uses the full `session_<uuid>` directory as its native ID, not the agent directory `main`. `kimiReader.stores` (also `KIMI_STORES` from the catalog entry) declares both layouts; the existing `STORES['kimi.session-dir']` remains the legacy declaration for consumers that still run that producer. A store's optional `globs` overrides the reader's default file globs, including when reading a v2 capture whose payload names are flat. No state or configuration sidecar is needed to read the current wire.
43
46
 
44
47
  The current flat wire records prompts and loop steps alongside appended message snapshots, usage mirrors and a token-counting context summary. The fold takes prompt input and loop content/tools/step usage once; it preserves separately recorded injected user context. `llm.request` supplies `requestedModel`, without promoting configured or usage labels into served identity. Explicit native endings map completed to completed, cancelled/prompt-aborted to aborted, and failed/blocked to error; an assistant-looking prefix stays open. A later matching prompt ending preserves the turn's structured error. Unknown ending reasons stay open with an integrity gap. Recorded step counters of zero remain zero, while absent usage remains unknown. The retained fixture proves the completed and prefix cases; failure/abort mappings follow the official producer schema and await real failure captures. Nonzero accounting and new-format child-agent discovery remain unproved.
package/dist/builder.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { HarnessSession, ModelCall, Part, SessionEnding, SessionError, SessionFormatId, SessionMessage, SessionSummary, SessionToolDefinitionSnapshot, TokenUsage } from './schema.js';
1
+ import type { HarnessSession, ModelCall, Part, SessionEnding, SessionError, SessionForkProvenance, SessionFormatId, SessionMessage, SessionSummary, SessionToolDefinitionSnapshot, TokenUsage } from './schema.js';
2
2
  import type { SourceStats } from './source.js';
3
3
  export type BuildMode = 'full' | 'summary';
4
4
  export declare function isoTime(value: unknown): string | null;
@@ -42,6 +42,7 @@ export declare class SessionBuilder {
42
42
  private truncated;
43
43
  private sessionUsage;
44
44
  private ending;
45
+ private forkProvenance;
45
46
  constructor(harness: string, format: SessionFormatId, modelSource: HarnessSession['modelSource'], mode: BuildMode, nativeSessionId: string, parentNativeSessionId?: string | null);
46
47
  seen(value: unknown): string | null;
47
48
  message(message: SessionMessage): SessionMessage;
@@ -55,6 +56,7 @@ export declare class SessionBuilder {
55
56
  inputText: string | null;
56
57
  at: string | null;
57
58
  messageId: string;
59
+ inherited?: boolean;
58
60
  }): void;
59
61
  toolResult(id: string, result: {
60
62
  output: unknown;
@@ -64,6 +66,7 @@ export declare class SessionBuilder {
64
66
  name?: string;
65
67
  messageId: string;
66
68
  details?: unknown;
69
+ inherited?: boolean;
67
70
  }): void;
68
71
  modelCall(call: ModelCall): ModelCall;
69
72
  getModelCall(id: string): ModelCall | undefined;
@@ -81,12 +84,16 @@ export declare class SessionBuilder {
81
84
  markTruncated(reason: string): void;
82
85
  closeNativeTurn(id: string, firstModelCall: number, ending: SessionEnding): void;
83
86
  setSessionUsage(usage: TokenUsage | null): void;
87
+ /** Recorded by the fold when the session header proves a parent session; mutations before finish() are kept. */
88
+ fork(fork: SessionForkProvenance): void;
84
89
  end(ending: SessionEnding): void;
85
90
  inferEnding(aborted?: {
86
91
  at: string | null;
87
92
  error: SessionError | null;
88
93
  }): void;
89
94
  get endingStatus(): SessionEnding['status'];
95
+ /** Keep replay visible in full conversations and out of the fork's execution totals. */
96
+ private ownedModelCalls;
90
97
  private usage;
91
98
  private servedModels;
92
99
  build(): HarnessSession;
package/dist/builder.js CHANGED
@@ -91,6 +91,7 @@ export class SessionBuilder {
91
91
  truncated = false;
92
92
  sessionUsage;
93
93
  ending = { status: 'open', error: null, at: null };
94
+ forkProvenance = null;
94
95
  constructor(harness, format, modelSource, mode, nativeSessionId, parentNativeSessionId = null) {
95
96
  this.harness = harness;
96
97
  this.format = format;
@@ -103,18 +104,20 @@ export class SessionBuilder {
103
104
  const at = isoTime(value);
104
105
  if (at === null)
105
106
  return null;
106
- if (this.startedAt === null || at < this.startedAt)
107
+ if (!this.forkProvenance?.createdAt && (this.startedAt === null || at < this.startedAt))
107
108
  this.startedAt = at;
108
109
  if (this.endedAt === null || at > this.endedAt)
109
110
  this.endedAt = at;
110
111
  return at;
111
112
  }
112
113
  message(message) {
113
- if (message.role === 'assistant' && message.actor === 'agent')
114
- this.replies += 1;
115
- if (message.role === 'user' && (message.actor === 'human' || message.actor === 'subagent-spawn'))
116
- this.inputsSinceLastCall += 1;
117
- this.lastRole = message.role;
114
+ if (!message.inherited) {
115
+ if (message.role === 'assistant' && message.actor === 'agent')
116
+ this.replies += 1;
117
+ if (message.role === 'user' && (message.actor === 'human' || message.actor === 'subagent-spawn'))
118
+ this.inputsSinceLastCall += 1;
119
+ this.lastRole = message.role;
120
+ }
118
121
  if (this.full) {
119
122
  this.messages.push(message);
120
123
  this.messageById.set(message.id, message);
@@ -142,12 +145,15 @@ export class SessionBuilder {
142
145
  if (this.toolCallIds.has(call.id))
143
146
  return;
144
147
  this.toolCallIds.add(call.id);
145
- this.openToolCalls.add(call.id);
146
- this.toolCallCount += 1;
148
+ if (!call.inherited) {
149
+ this.openToolCalls.add(call.id);
150
+ this.toolCallCount += 1;
151
+ }
147
152
  if (!this.full)
148
153
  return;
149
154
  this.toolCalls.set(call.id, {
150
155
  id: call.id,
156
+ ...(call.inherited ? { inherited: true } : {}),
151
157
  name: call.name,
152
158
  input: call.input,
153
159
  inputText: call.inputText,
@@ -160,7 +166,7 @@ export class SessionBuilder {
160
166
  }
161
167
  toolResult(id, result) {
162
168
  if (!this.toolCallIds.has(id)) {
163
- this.toolCall({ id, name: result.name ?? 'unknown', input: null, inputText: null, at: result.at, messageId: result.messageId });
169
+ this.toolCall({ id, name: result.name ?? 'unknown', input: null, inputText: null, at: result.at, messageId: result.messageId, inherited: result.inherited });
164
170
  this.gap(`tool result ${id} has no recorded call`);
165
171
  }
166
172
  this.openToolCalls.delete(id);
@@ -174,7 +180,8 @@ export class SessionBuilder {
174
180
  call.endedAt = result.at;
175
181
  }
176
182
  modelCall(call) {
177
- this.inputsSinceLastCall = 0;
183
+ if (!call.inherited)
184
+ this.inputsSinceLastCall = 0;
178
185
  this.modelCalls.push(call);
179
186
  this.modelCallById.set(call.id, call);
180
187
  return call;
@@ -232,6 +239,12 @@ export class SessionBuilder {
232
239
  setSessionUsage(usage) {
233
240
  this.sessionUsage = usage;
234
241
  }
242
+ /** Recorded by the fold when the session header proves a parent session; mutations before finish() are kept. */
243
+ fork(fork) {
244
+ this.forkProvenance = fork;
245
+ if (fork.createdAt)
246
+ this.startedAt = fork.createdAt;
247
+ }
235
248
  end(ending) {
236
249
  this.ending = ending;
237
250
  }
@@ -241,7 +254,7 @@ export class SessionBuilder {
241
254
  this.ending = { status: error ? 'error' : 'aborted', error, at: aborted.at ?? error?.at ?? null };
242
255
  return;
243
256
  }
244
- const last = this.modelCalls[this.modelCalls.length - 1];
257
+ const last = this.ownedModelCalls().at(-1);
245
258
  if (last?.error && this.inputsSinceLastCall === 0) {
246
259
  this.ending = { status: 'error', error: last.error, at: last.error.at ?? last.at };
247
260
  return;
@@ -255,18 +268,24 @@ export class SessionBuilder {
255
268
  get endingStatus() {
256
269
  return this.ending.status;
257
270
  }
271
+ /** Keep replay visible in full conversations and out of the fork's execution totals. */
272
+ ownedModelCalls() {
273
+ return this.forkProvenance ? this.modelCalls.filter((call) => !call.inherited) : this.modelCalls;
274
+ }
258
275
  usage() {
259
276
  if (this.sessionUsage !== undefined)
260
277
  return this.sessionUsage;
261
278
  const total = { input: null, output: null, reasoning: null, cacheRead: null, cacheWrite: null };
262
279
  for (const call of this.modelCalls)
263
- if (call.usage)
280
+ if (!call.inherited && call.usage)
264
281
  addUsage(total, call.usage);
265
282
  return usageOrNull(total);
266
283
  }
267
284
  servedModels() {
268
285
  const models = {};
269
286
  for (const call of this.modelCalls) {
287
+ if (call.inherited)
288
+ continue;
270
289
  const key = servedModelKey(call);
271
290
  if (key !== null)
272
291
  models[key] = (models[key] ?? 0) + 1;
@@ -297,6 +316,7 @@ export class SessionBuilder {
297
316
  usage: this.usage(),
298
317
  ending: this.ending,
299
318
  ...(this.turnReceipts.length ? { turnReceipts: this.turnReceipts } : {}),
319
+ ...(this.forkProvenance ? { fork: this.forkProvenance } : {}),
300
320
  children: this.children,
301
321
  integrity: {
302
322
  sourceFiles: this.sources,
@@ -307,20 +327,22 @@ export class SessionBuilder {
307
327
  };
308
328
  }
309
329
  summary() {
330
+ const owned = this.ownedModelCalls();
310
331
  return {
311
332
  harness: this.harness,
312
333
  format: this.format,
313
334
  nativeSessionId: this.nativeSessionId,
314
335
  parentNativeSessionId: this.parentNativeSessionId,
315
- modelCalls: this.modelCalls.length,
336
+ modelCalls: owned.length,
316
337
  replies: this.replies,
317
338
  toolCalls: this.toolCallCount,
318
339
  servedModels: this.servedModels(),
319
- lastServedModel: [...this.modelCalls].reverse().map(servedModelKey).find((key) => key !== null) ?? null,
340
+ lastServedModel: [...owned].reverse().map(servedModelKey).find((key) => key !== null) ?? null,
320
341
  modelSource: this.modelSource,
321
342
  usage: this.usage(),
322
343
  ending: this.ending,
323
344
  ...(this.turnReceipts.length ? { turnReceipts: this.turnReceipts } : {}),
345
+ ...(this.forkProvenance ? { fork: this.forkProvenance } : {}),
324
346
  unparsedRecords: this.unparsed,
325
347
  bytes: this.sources.reduce((sum, s) => sum + s.bytes, 0),
326
348
  truncated: this.truncated,
@@ -8,14 +8,17 @@ import { EVIDENCE, STORES, mtimeMs, withinPath } from '../stores.js';
8
8
  const FORMAT = 'opencode.sqlite';
9
9
  const STORE = STORES[FORMAT];
10
10
  const HARNESS = 'opencode';
11
+ // OpenCode records reasoning beside its output (its own `total` adds the two), so `output` here is their sum:
12
+ // every completion token, as TokenUsage counts it.
11
13
  function usageOf(tokens) {
12
14
  if (!isRecord(tokens))
13
15
  return null;
14
16
  const cache = isRecord(tokens.cache) ? tokens.cache : {};
17
+ const output = count(tokens.output), reasoning = count(tokens.reasoning);
15
18
  return usageOrNull({
16
19
  input: count(tokens.input),
17
- output: count(tokens.output),
18
- reasoning: count(tokens.reasoning),
20
+ output: output === null && reasoning === null ? null : (output ?? 0) + (reasoning ?? 0),
21
+ reasoning,
19
22
  cacheRead: count(cache.read),
20
23
  cacheWrite: count(cache.write),
21
24
  });
@@ -1,10 +1,11 @@
1
1
  import { isRecord } from '@tangle-network/agent-core';
2
2
  import { basename, join } from 'node:path';
3
- import { SessionBuilder, count, sessionError, str, textOf, usageOrNull } from '../builder.js';
3
+ import { SessionBuilder, count, isoTime, sessionError, str, textOf, usageOrNull } from '../builder.js';
4
4
  import { fileRecords } from '../source.js';
5
5
  import { foldedReader, runFold } from './fold.js';
6
6
  import { EVIDENCE, STORES, mtimeMs, storeGlob, walkFiles, withinPath } from '../stores.js';
7
7
  import { headRecord } from './head.js';
8
+ import { isPrimeSessionHeader, primeParentNativeSessionId } from './prime-header.js';
8
9
  const FORMAT = 'pi.session-jsonl';
9
10
  const STORE = STORES[FORMAT];
10
11
  const HARNESS = 'pi';
@@ -50,24 +51,56 @@ export function createFold(ref, mode, stats, harness = HARNESS, format = FORMAT)
50
51
  let branches = 0;
51
52
  let compactions = 0;
52
53
  let aborted = null;
54
+ let fork = null;
55
+ let readingForkPrefix = false;
53
56
  const observe = (entry) => {
54
57
  const entryAt = builder.seen(entry.timestamp);
55
58
  const id = str(entry.id) ?? `${builder.nativeSessionId}:${stats.line}`;
56
59
  const parentId = str(entry.parentId);
57
60
  if (entry.type === 'session') {
58
- if (typeof entry.id === 'string' && harness !== 'prime')
61
+ if (isPrimeSessionHeader(entry)) {
62
+ if (harness !== 'prime')
63
+ throw new Error('expected pi, found prime session header');
59
64
  builder.nativeSessionId = entry.id;
65
+ if (typeof entry.parentSession === 'string' && entry.parentSession.trim()) {
66
+ fork = {
67
+ parentNativeSessionId: primeParentNativeSessionId(entry.parentSession),
68
+ parentSession: entry.parentSession,
69
+ rlmDepth: entry.rlmDepth,
70
+ userFork: entry.rlmDepth === 0,
71
+ createdAt: isoTime(entry.timestamp),
72
+ inheritedEntries: 0,
73
+ };
74
+ builder.parentNativeSessionId = fork.parentNativeSessionId;
75
+ builder.fork(fork);
76
+ readingForkPrefix = true;
77
+ }
78
+ }
79
+ else if (typeof entry.id === 'string' && harness !== 'prime') {
80
+ builder.nativeSessionId = entry.id;
81
+ }
60
82
  builder.cwd = str(entry.cwd);
61
83
  previousId = null;
62
84
  return;
63
85
  }
86
+ // Prime copies its parent's linked path, in order, before appending new work. A later
87
+ // event with an old clock cannot reopen that path. Equal timestamps establish no ordering.
88
+ const inherited = readingForkPrefix && fork?.createdAt != null && entryAt !== null
89
+ && entryAt < fork.createdAt && typeof entry.id === 'string' && entry.id.length > 0
90
+ && entry.parentId === previousId;
91
+ if (inherited && fork)
92
+ fork.inheritedEntries += 1;
93
+ else
94
+ readingForkPrefix = false;
95
+ const provenance = inherited ? { inherited: true } : {};
96
+ const emit = (value) => { builder.message(inherited ? { ...value, inherited: true } : value); };
64
97
  if (parentId !== null && previousId !== null && parentId !== previousId)
65
98
  branches += 1;
66
99
  previousId = id;
67
100
  if (entry.type === 'compaction') {
68
101
  compactions += 1;
69
102
  if (typeof entry.summary === 'string') {
70
- builder.message({ id, role: 'user', actor: 'injected', at: entryAt, modelCallId: null, parts: [{ type: 'text', text: entry.summary }] });
103
+ emit({ id, role: 'user', actor: 'injected', at: entryAt, modelCallId: null, parts: [{ type: 'text', text: entry.summary }] });
71
104
  }
72
105
  return;
73
106
  }
@@ -78,15 +111,17 @@ export function createFold(ref, mode, stats, harness = HARNESS, format = FORMAT)
78
111
  const role = str(message.role);
79
112
  if (role === 'user') {
80
113
  aborted = null;
81
- builder.message({ id, role: 'user', actor: ref.parentNativeSessionId ? 'subagent-spawn' : 'human', at, modelCallId: null, parts: contentParts(message.content, id) });
114
+ // A Prime session that kept the conversation level (userFork) is a user fork, not a delegated child.
115
+ emit({ id, role: 'user', actor: builder.parentNativeSessionId && fork?.userFork !== true ? 'subagent-spawn' : 'human', at, modelCallId: null, parts: contentParts(message.content, id) });
82
116
  return;
83
117
  }
84
118
  if (role === 'toolResult') {
85
119
  const callId = str(message.toolCallId) ?? `${id}:result`;
86
- builder.message({ id, role: 'tool', actor: 'tool-result', at, modelCallId: null, parts: [{ type: 'tool-result', toolCallId: callId }] });
120
+ emit({ id, role: 'tool', actor: 'tool-result', at, modelCallId: null, parts: [{ type: 'tool-result', toolCallId: callId }] });
87
121
  const content = message.content;
88
122
  const single = Array.isArray(content) && content.length === 1 && isRecord(content[0]) && content[0].type === 'text';
89
123
  builder.toolResult(callId, {
124
+ ...provenance,
90
125
  output: single ? content[0].text : (content ?? null),
91
126
  text: textOf(content),
92
127
  isError: message.isError === true,
@@ -103,6 +138,7 @@ export function createFold(ref, mode, stats, harness = HARNESS, format = FORMAT)
103
138
  const failed = stopReason === 'error';
104
139
  const { usage, cost } = usageOf(message.usage);
105
140
  builder.modelCall({
141
+ ...provenance,
106
142
  id,
107
143
  at,
108
144
  provider: failed ? null : str(message.provider),
@@ -121,14 +157,15 @@ export function createFold(ref, mode, stats, harness = HARNESS, format = FORMAT)
121
157
  const callId = str(block.id) ?? `${id}:call:${parts.length}`;
122
158
  parts.push({ type: 'tool-call', toolCallId: callId });
123
159
  const input = block.arguments ?? block.input ?? null;
124
- builder.toolCall({ id: callId, name: str(block.name) ?? 'tool', input, inputText: typeof input === 'string' ? input : null, at, messageId: id });
160
+ builder.toolCall({ ...provenance, id: callId, name: str(block.name) ?? 'tool', input, inputText: typeof input === 'string' ? input : null, at, messageId: id });
125
161
  }
126
- builder.message({ id, role: 'assistant', actor: failed ? 'injected' : 'agent', at, modelCallId: id, parts: failed && parts.length === 0 && errorText ? [{ type: 'text', text: errorText }] : parts });
127
- aborted = stopReason === 'aborted' ? { at, message: errorText } : null;
162
+ emit({ id, role: 'assistant', actor: failed ? 'injected' : 'agent', at, modelCallId: id, parts: failed && parts.length === 0 && errorText ? [{ type: 'text', text: errorText }] : parts });
163
+ if (!inherited)
164
+ aborted = stopReason === 'aborted' ? { at, message: errorText } : null;
128
165
  return;
129
166
  }
130
167
  if (role === 'system' || role === 'custom' || role === 'bashExecution') {
131
- builder.message({ id, role: role === 'system' ? 'system' : 'user', actor: 'injected', at, modelCallId: null, parts: contentParts(message.content ?? message.output, id) });
168
+ emit({ id, role: role === 'system' ? 'system' : 'user', actor: 'injected', at, modelCallId: null, parts: contentParts(message.content ?? message.output, id) });
132
169
  }
133
170
  };
134
171
  const finish = () => {
@@ -157,6 +194,8 @@ async function locate(home, opts) {
157
194
  if (opts.sinceMs && mtime < opts.sinceMs)
158
195
  continue;
159
196
  const header = await headRecord(path, (r) => r.type === 'session', 1);
197
+ if (isPrimeSessionHeader(header))
198
+ continue;
160
199
  const cwd = header ? str(header.cwd) : null;
161
200
  if (opts.cwd && (cwd === null || !withinPath(cwd, opts.cwd)))
162
201
  continue;
@@ -0,0 +1,18 @@
1
+ interface PrimeSessionHeader {
2
+ type: 'session';
3
+ id: string;
4
+ rlmDepth: number;
5
+ cwd?: unknown;
6
+ timestamp?: unknown;
7
+ parentSession?: unknown;
8
+ }
9
+ /**
10
+ * Whether a session record is a Prime session header. Prime marks its headers with a recursion
11
+ * `rlmDepth` (0 on a root session and on a user fork); the Pi family shares the rest of the header
12
+ * shape, including `version`, without ever writing that field. An unmarked header is therefore
13
+ * ambiguous and stays with its historical filename identity.
14
+ */
15
+ export declare function isPrimeSessionHeader(record: unknown): record is PrimeSessionHeader;
16
+ /** The parent's native session ID from a recorded `parentSession` reference (a session file path or a plain ID). The reference is never dereferenced. */
17
+ export declare function primeParentNativeSessionId(parentSession: string): string;
18
+ export {};
@@ -0,0 +1,22 @@
1
+ import { isRecord } from '@tangle-network/agent-core';
2
+ /**
3
+ * Whether a session record is a Prime session header. Prime marks its headers with a recursion
4
+ * `rlmDepth` (0 on a root session and on a user fork); the Pi family shares the rest of the header
5
+ * shape, including `version`, without ever writing that field. An unmarked header is therefore
6
+ * ambiguous and stays with its historical filename identity.
7
+ */
8
+ export function isPrimeSessionHeader(record) {
9
+ if (!isRecord(record))
10
+ return false;
11
+ if (record.type !== 'session')
12
+ return false;
13
+ if (typeof record.id !== 'string' || record.id.length === 0)
14
+ return false;
15
+ const depth = record.rlmDepth;
16
+ return typeof depth === 'number' && Number.isInteger(depth) && depth >= 0;
17
+ }
18
+ /** The parent's native session ID from a recorded `parentSession` reference (a session file path or a plain ID). The reference is never dereferenced. */
19
+ export function primeParentNativeSessionId(parentSession) {
20
+ const name = parentSession.replace(/\\/gu, '/').split('/').pop() ?? parentSession;
21
+ return name.replace(/\.jsonl$/u, '') || parentSession;
22
+ }
@@ -1,3 +1,4 @@
1
1
  import type { HarnessSessionReader, SessionRef } from '../schema.js';
2
+ export { isPrimeSessionHeader, primeParentNativeSessionId } from './prime-header.js';
2
3
  export declare function primeRefForFile(path: string): SessionRef;
3
4
  export declare const primeReader: HarnessSessionReader;
@@ -1,8 +1,11 @@
1
1
  import { basename, join } from 'node:path';
2
2
  import { fileRecords } from '../source.js';
3
- import { STORES, mtimeMs, storeGlob, walkFiles } from '../stores.js';
3
+ import { STORES, mtimeMs, storeGlob, walkFiles, withinPath } from '../stores.js';
4
4
  import { foldedReader, runFold } from './fold.js';
5
+ import { headRecord } from './head.js';
5
6
  import { createFold } from './pi.js';
7
+ import { isPrimeSessionHeader, primeParentNativeSessionId } from './prime-header.js';
8
+ export { isPrimeSessionHeader, primeParentNativeSessionId } from './prime-header.js';
6
9
  const FORMAT = 'prime.session-jsonl';
7
10
  const STORE = STORES[FORMAT];
8
11
  const HARNESS = 'prime';
@@ -24,10 +27,23 @@ export const primeReader = foldedReader({ harness: HARNESS, refForFile: primeRef
24
27
  if (!pattern.test(rel))
25
28
  continue;
26
29
  const path = join(root, rel);
27
- const ref = primeRefForFile(path);
28
- if (opts.nativeSessionId && ref.nativeSessionId !== opts.nativeSessionId)
30
+ const mtime = await mtimeMs(path);
31
+ if (opts.sinceMs && mtime < opts.sinceMs)
29
32
  continue;
30
- refs.push({ ...ref, home, mtimeMs: await mtimeMs(path) });
33
+ const first = await headRecord(path, (r) => r.type === 'session', 1);
34
+ const header = isPrimeSessionHeader(first) ? first : null;
35
+ // An unmarked header is Pi-family ambiguous: keep the store filename identity it always had.
36
+ const id = header ? header.id : idFromName(rel);
37
+ const cwd = header && typeof header.cwd === 'string' ? header.cwd : null;
38
+ const parentSession = header && typeof header.parentSession === 'string' ? header.parentSession : null;
39
+ if (opts.nativeSessionId && id !== opts.nativeSessionId && idFromName(rel) !== opts.nativeSessionId)
40
+ continue;
41
+ if (opts.cwd && (cwd === null || !withinPath(cwd, opts.cwd)))
42
+ continue;
43
+ refs.push({
44
+ harness: HARNESS, format: FORMAT, nativeSessionId: id, path, files: [path], home, cwd, mtimeMs: mtime,
45
+ parentNativeSessionId: parentSession === null ? null : primeParentNativeSessionId(parentSession),
46
+ });
31
47
  }
32
48
  return refs.sort((a, b) => b.mtimeMs - a.mtimeMs);
33
49
  }, fold);
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { HarnessSession, HarnessSessionReader, LocateOptions, ModelCall, NativeSessionCopy, NativeSessionStore, NativeTurnReceipt, Part, RawEvidenceArchiveManifestV2, ReadOptions, SessionEnding, SessionError, SessionEvidenceSources, SessionFormatId, SessionIntegrity, SessionMessage, SessionRef, SessionSummary, SessionToolCall, SessionToolDefinition, SessionToolDefinitionSnapshot, TokenUsage, } from './schema.js';
1
+ export type { HarnessSession, HarnessSessionReader, LocateOptions, ModelCall, NativeSessionCopy, NativeSessionStore, NativeTurnReceipt, Part, RawEvidenceArchiveManifestV2, ReadOptions, SessionEnding, SessionError, SessionEvidenceSources, SessionFormatId, SessionForkProvenance, SessionIntegrity, SessionMessage, SessionRef, SessionSummary, SessionToolCall, SessionToolDefinition, SessionToolDefinitionSnapshot, TokenUsage, } from './schema.js';
2
2
  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';
@@ -14,7 +14,7 @@ export { factoryReader, factoryRefForFile } from './formats/factory.js';
14
14
  export { grokReader, grokRefForFile } from './formats/grok.js';
15
15
  export { nanoclawReader, nanoclawRefForFile } from './formats/nanoclaw.js';
16
16
  export { hermesReader, hermesSessionsInStore } from './formats/hermes.js';
17
- export { primeReader, primeRefForFile } from './formats/prime.js';
17
+ export { primeReader, primeRefForFile, isPrimeSessionHeader, primeParentNativeSessionId } from './formats/prime.js';
18
18
  export { sandboxEventsSession, type SandboxEventsRun } from './formats/sandbox-events.js';
19
19
  export { openclawReader } from './formats/openclaw.js';
20
20
  export { listCapture, readCapture, RETENTION_MANIFEST_KIND, RETENTION_SESSIONS, type CaptureListing, type CapturedSessionRef, } from './capture.js';
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ export { factoryReader, factoryRefForFile } from './formats/factory.js';
13
13
  export { grokReader, grokRefForFile } from './formats/grok.js';
14
14
  export { nanoclawReader, nanoclawRefForFile } from './formats/nanoclaw.js';
15
15
  export { hermesReader, hermesSessionsInStore } from './formats/hermes.js';
16
- export { primeReader, primeRefForFile } from './formats/prime.js';
16
+ export { primeReader, primeRefForFile, isPrimeSessionHeader, primeParentNativeSessionId } from './formats/prime.js';
17
17
  export { sandboxEventsSession } from './formats/sandbox-events.js';
18
18
  export { openclawReader } from './formats/openclaw.js';
19
19
  export { listCapture, readCapture, RETENTION_MANIFEST_KIND, RETENTION_SESSIONS, } from './capture.js';
package/dist/input.js CHANGED
@@ -11,6 +11,7 @@ const FOLDS = {
11
11
  pi: piFold,
12
12
  'kimi-code': kimiFold,
13
13
  'factory-droids': (ref, mode, stats) => factoryFold(ref, mode, stats),
14
+ prime: (ref, mode, stats) => piFold(ref, mode, stats, 'prime', 'prime.session-jsonl'),
14
15
  };
15
16
  function foldInput(harness, input, init, mode, options) {
16
17
  const reader = readerFor(harness);
@@ -22,16 +22,17 @@ export function toChatMessages(session, options = {}) {
22
22
  for (const message of session.messages) {
23
23
  if (message.actor === 'injected' && !keepInjected)
24
24
  continue;
25
+ const provenance = message.inherited ? { is_copied_context: true } : {};
25
26
  if (message.role === 'system') {
26
27
  if (keepSystem)
27
- out.push({ role: 'system', content: texts(message, 'text') });
28
+ out.push({ ...provenance, role: 'system', content: texts(message, 'text') });
28
29
  continue;
29
30
  }
30
31
  if (message.role === 'user') {
31
32
  const content = texts(message, 'text');
32
33
  if (content.length === 0 && !message.parts.some((p) => p.type === 'attachment'))
33
34
  continue;
34
- out.push({ role: 'user', content });
35
+ out.push({ ...provenance, role: 'user', content });
35
36
  continue;
36
37
  }
37
38
  if (message.role === 'tool') {
@@ -40,6 +41,7 @@ export function toChatMessages(session, options = {}) {
40
41
  continue;
41
42
  const call = calls.get(part.toolCallId);
42
43
  out.push({
44
+ ...provenance,
43
45
  role: 'tool',
44
46
  tool_call_id: part.toolCallId,
45
47
  ...(call ? { name: call.name } : {}),
@@ -64,6 +66,7 @@ export function toChatMessages(session, options = {}) {
64
66
  if (text.length === 0 && reasoning.length === 0 && toolCalls.length === 0)
65
67
  continue;
66
68
  out.push({
69
+ ...provenance,
67
70
  role: 'assistant',
68
71
  content: text.length > 0 ? text : null,
69
72
  ...(reasoning.length > 0 ? { reasoning_content: reasoning } : {}),
@@ -25,6 +25,7 @@ export function toOtlpSpans(session, options = {}) {
25
25
  'tangle.harness_session.format': session.format,
26
26
  'tangle.harness_session.ending': session.ending.status,
27
27
  ...(session.parentNativeSessionId ? { 'tangle.harness_session.parent': session.parentNativeSessionId } : {}),
28
+ ...(session.fork ? { 'tangle.harness_session.role': session.fork.userFork ? 'operator' : 'child' } : {}),
28
29
  },
29
30
  }),
30
31
  ];
@@ -52,6 +53,7 @@ export function toOtlpSpans(session, options = {}) {
52
53
  ...(call.usage?.output != null ? { outputTokens: call.usage.output } : {}),
53
54
  ...(call.costUsd != null ? { costUsd: call.costUsd } : {}),
54
55
  attributes: {
56
+ ...(call.inherited ? { 'tangle.harness_session.inherited': true } : {}),
55
57
  ...(call.usage?.cacheRead != null ? { 'gen_ai.usage.cache_read.input_tokens': call.usage.cacheRead } : {}),
56
58
  ...(call.usage?.cacheWrite != null ? { 'gen_ai.usage.cache_creation.input_tokens': call.usage.cacheWrite } : {}),
57
59
  ...(call.usage?.reasoning != null ? { 'gen_ai.usage.reasoning_tokens': call.usage.reasoning } : {}),
@@ -76,6 +78,7 @@ export function toOtlpSpans(session, options = {}) {
76
78
  : call.status === 'completed' ? { code: 'STATUS_CODE_OK' } : { code: 'STATUS_CODE_UNSET' },
77
79
  attributes: {
78
80
  'gen_ai.tool.call.id': call.id,
81
+ ...(call.inherited ? { 'tangle.harness_session.inherited': true } : {}),
79
82
  'tangle.tool.status': call.status,
80
83
  ...(chars > 0 ? { 'input.value': cap(call.inputText ?? JSON.stringify(call.input ?? null), chars) } : {}),
81
84
  ...(chars > 0 && call.result?.text ? { 'output.value': cap(call.result.text, chars) } : {}),
@@ -8,6 +8,7 @@ export interface TurnToolCall {
8
8
  }
9
9
  export interface Turn {
10
10
  role: 'user' | 'assistant' | 'system' | 'tool';
11
+ is_copied_context?: boolean;
11
12
  seq?: number;
12
13
  text?: string;
13
14
  text_summary?: string;
@@ -71,11 +71,12 @@ export function toTurns(session, options = {}) {
71
71
  let seq = 0;
72
72
  for (const message of session.messages) {
73
73
  const ts = message.at ?? '';
74
+ const provenance = message.inherited ? { is_copied_context: true } : {};
74
75
  if (message.role === 'user') {
75
76
  const body = text(message, 'text');
76
77
  if (!body)
77
78
  continue;
78
- turns.push({ role: 'user', seq: seq++, text: body.length > textChars ? summarizeText(body, textChars) : body, ts });
79
+ turns.push({ ...provenance, role: 'user', seq: seq++, text: body.length > textChars ? summarizeText(body, textChars) : body, ts });
79
80
  continue;
80
81
  }
81
82
  if (message.role !== 'assistant')
@@ -101,6 +102,7 @@ export function toTurns(session, options = {}) {
101
102
  });
102
103
  const model = call?.servedModel ?? undefined;
103
104
  turns.push({
105
+ ...provenance,
104
106
  seq: seq++,
105
107
  role: 'assistant',
106
108
  ...(body ? { text: body.length > textChars ? summarizeText(body, textChars) : body, text_summary: summarizeText(body, summaryChars) } : {}),
@@ -117,9 +119,10 @@ export function toTurns(session, options = {}) {
117
119
  }
118
120
  export function primaryModel(session) {
119
121
  const counts = new Map();
120
- for (const call of session.modelCalls)
121
- if (call.servedModel)
122
+ for (const call of session.modelCalls) {
123
+ if (!call.inherited && call.servedModel)
122
124
  counts.set(call.servedModel, (counts.get(call.servedModel) ?? 0) + 1);
125
+ }
123
126
  let best = null;
124
127
  let bestCount = 0;
125
128
  for (const [model, n] of counts)
package/dist/schema.d.ts CHANGED
@@ -15,6 +15,10 @@ export interface SessionEvidenceSources {
15
15
  usage: 'per-response' | 'cumulative' | 'session-total';
16
16
  endingError: 'session-record' | 'none';
17
17
  }
18
+ /**
19
+ * One response's tokens, or a sum of them. `output` is every completion token, reasoning included; `reasoning` is the
20
+ * part of `output` spent reasoning and is never added to it. A reader whose harness records the two apart adds them.
21
+ */
18
22
  export interface TokenUsage {
19
23
  input: number | null;
20
24
  output: number | null;
@@ -55,9 +59,13 @@ export interface SessionMessage {
55
59
  parts: Part[];
56
60
  /** What a harness-injected system message is, in the harness's words: Claude Code's attachment type, such as `instructions`. */
57
61
  source?: string;
62
+ /** True when the session header proves this message replays parent prehistory, not this session's own work. */
63
+ inherited?: boolean;
58
64
  }
59
65
  export interface SessionToolCall {
60
66
  id: string;
67
+ /** The native fork copied this call from its parent. */
68
+ inherited?: boolean;
61
69
  name: string;
62
70
  input: unknown;
63
71
  inputText: string | null;
@@ -75,6 +83,8 @@ export interface SessionToolCall {
75
83
  }
76
84
  export interface ModelCall {
77
85
  id: string;
86
+ /** The native fork copied this completion from its parent. */
87
+ inherited?: boolean;
78
88
  at: string | null;
79
89
  provider: string | null;
80
90
  servedModel: string | null;
@@ -124,6 +134,25 @@ export interface NativeTurnReceipt {
124
134
  /** Totals over this closed turn. Each incomplete token class stays null. */
125
135
  usage: TokenUsage | null;
126
136
  }
137
+ /**
138
+ * Fork provenance a session's own header records (Prime `parentSession`): the session continues
139
+ * another recorded session file. The reference is read as identity evidence only; this reader
140
+ * never dereferences the path.
141
+ */
142
+ export interface SessionForkProvenance {
143
+ /** The parent's native session ID, derived from the recorded `parentSession` reference (its file stem or plain ID). */
144
+ parentNativeSessionId: string;
145
+ /** The verbatim `parentSession` value from the header. */
146
+ parentSession: string;
147
+ /** The recursion depth recorded on this session's header; 0 is the top conversation level. */
148
+ rlmDepth: number;
149
+ /** True when the fork stayed at the conversation level (`rlmDepth` 0): a user fork, not a delegated child. */
150
+ userFork: boolean;
151
+ /** The forked session header's own creation timestamp; inherited prehistory carries earlier timestamps. */
152
+ createdAt: string | null;
153
+ /** Length of the linked native prefix recorded strictly before the fork's creation. */
154
+ inheritedEntries: number;
155
+ }
127
156
  export interface HarnessSession {
128
157
  schema: 'tangle.harness-session.v1';
129
158
  harness: string;
@@ -143,6 +172,8 @@ export interface HarnessSession {
143
172
  usage: TokenUsage | null;
144
173
  ending: SessionEnding;
145
174
  turnReceipts?: NativeTurnReceipt[];
175
+ /** Present when the session header itself proves this session continues another recorded session. */
176
+ fork?: SessionForkProvenance;
146
177
  children: Array<{
147
178
  nativeSessionId: string;
148
179
  toolCallId: string | null;
@@ -163,6 +194,7 @@ export interface SessionSummary {
163
194
  usage: TokenUsage | null;
164
195
  ending: SessionEnding;
165
196
  turnReceipts?: NativeTurnReceipt[];
197
+ fork?: SessionForkProvenance;
166
198
  unparsedRecords: number;
167
199
  bytes: number;
168
200
  truncated: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/harness-sessions",
3
- "version": "1.0.16",
3
+ "version": "1.0.18",
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,