@evomap/evolver-core 2.0.0-beta.9 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/dist/algo/candidateAssembly.d.ts +7 -2
  2. package/dist/algo/candidateAssembly.js +81 -13
  3. package/dist/algo/capabilityCandidates.js +10 -0
  4. package/dist/algo/cycleEngine.d.ts +23 -2
  5. package/dist/algo/cycleEngine.js +236 -36
  6. package/dist/algo/exploration.d.ts +7 -0
  7. package/dist/algo/exploration.js +16 -3
  8. package/dist/algo/geneHealth.d.ts +2 -2
  9. package/dist/algo/geneHealth.js +5 -4
  10. package/dist/algo/geneSelection.d.ts +63 -5
  11. package/dist/algo/geneSelection.js +330 -30
  12. package/dist/algo/index.d.ts +2 -0
  13. package/dist/algo/index.js +2 -0
  14. package/dist/algo/orchestrator.d.ts +8 -1
  15. package/dist/algo/orchestrator.js +15 -3
  16. package/dist/algo/publishEligibility.d.ts +34 -0
  17. package/dist/algo/publishEligibility.js +52 -0
  18. package/dist/algo/ucb1.d.ts +53 -0
  19. package/dist/algo/ucb1.js +156 -0
  20. package/dist/assetstore/assetSidecarRecords.d.ts +7 -2
  21. package/dist/assetstore/assetSidecarRecords.js +238 -0
  22. package/dist/assetstore/assetSidecarRecovery.js +2 -2
  23. package/dist/assetstore/assetStoreHealth.d.ts +6 -0
  24. package/dist/assetstore/assetStoreHealth.js +56 -14
  25. package/dist/assetstore/assetStoreStorage.d.ts +1 -1
  26. package/dist/assetstore/assetStoreStorage.js +27 -9
  27. package/dist/assetstore/assetSyncLedger.d.ts +86 -0
  28. package/dist/assetstore/assetSyncLedger.js +683 -4
  29. package/dist/assetstore/index.d.ts +1 -0
  30. package/dist/assetstore/index.js +1 -0
  31. package/dist/assetstore/localAssetStoreSnapshot.d.ts +51 -0
  32. package/dist/assetstore/localAssetStoreSnapshot.js +329 -0
  33. package/dist/assetstore/localJsonl.d.ts +4 -2
  34. package/dist/assetstore/localJsonl.js +89 -9
  35. package/dist/assetstore/provenance.d.ts +80 -4
  36. package/dist/assetstore/provenance.js +313 -5
  37. package/dist/assetstore/provider.d.ts +58 -1
  38. package/dist/assetstore/provider.js +97 -6
  39. package/dist/benchmark/antiGeneBenchmark.d.ts +2 -0
  40. package/dist/benchmark/antiGeneBenchmark.js +4 -3
  41. package/dist/benchmark/antiGeneRollout.d.ts +2 -0
  42. package/dist/benchmark/antiGeneRollout.js +4 -3
  43. package/dist/benchmark/index.d.ts +2 -1
  44. package/dist/benchmark/index.js +2 -1
  45. package/dist/benchmark/selectionFlatAbstention.d.ts +152 -0
  46. package/dist/benchmark/selectionFlatAbstention.js +481 -0
  47. package/dist/bootstrap/envFingerprint.d.ts +9 -0
  48. package/dist/bootstrap/envFingerprint.js +5 -0
  49. package/dist/bootstrap/index.d.ts +2 -1
  50. package/dist/bootstrap/index.js +2 -1
  51. package/dist/bootstrap/v1EnvCompat.d.ts +111 -0
  52. package/dist/bootstrap/v1EnvCompat.js +280 -0
  53. package/dist/events/eventArchive.d.ts +2 -0
  54. package/dist/events/eventArchive.js +13 -3
  55. package/dist/events/eventSchema.d.ts +7 -7
  56. package/dist/events/eventStore.d.ts +2 -0
  57. package/dist/events/eventStore.js +5 -1
  58. package/dist/events/ingest.d.ts +1 -0
  59. package/dist/events/ingest.js +1 -0
  60. package/dist/events/paths.d.ts +3 -1
  61. package/dist/events/paths.js +4 -0
  62. package/dist/events/public.d.ts +2 -2
  63. package/dist/events/public.js +2 -2
  64. package/dist/events/reports.d.ts +2 -0
  65. package/dist/events/reports.js +4 -0
  66. package/dist/exec/autoExec.d.ts +43 -2
  67. package/dist/exec/autoExec.js +76 -9
  68. package/dist/exec/autonomousCycle.d.ts +22 -4
  69. package/dist/exec/autonomousCycle.js +64 -13
  70. package/dist/exec/claudeBridge.d.ts +32 -7
  71. package/dist/exec/claudeBridge.js +281 -29
  72. package/dist/exec/prompt.js +5 -1
  73. package/dist/exec/runnerRegistry.d.ts +68 -26
  74. package/dist/exec/runnerRegistry.js +307 -72
  75. package/dist/exec/selfPr.js +1 -7
  76. package/dist/feedback/envelope.d.ts +61 -0
  77. package/dist/feedback/envelope.js +168 -0
  78. package/dist/feedback/index.d.ts +1 -0
  79. package/dist/feedback/index.js +1 -0
  80. package/dist/hooks/hooks.js +1 -0
  81. package/dist/hub/assetCallLog.d.ts +35 -1
  82. package/dist/hub/assetCallLog.js +124 -1
  83. package/dist/hub/bindings.d.ts +8 -1
  84. package/dist/hub/bindings.js +17 -6
  85. package/dist/hub/capability.d.ts +90 -3
  86. package/dist/hub/fake.d.ts +2 -2
  87. package/dist/hub/fake.js +1 -1
  88. package/dist/hub/questionGenerator.d.ts +5 -1
  89. package/dist/hub/questionGenerator.js +8 -6
  90. package/dist/index.d.ts +3 -1
  91. package/dist/index.js +4 -1
  92. package/dist/mailbox/dispatch.d.ts +1 -1
  93. package/dist/mailbox/dispatch.js +22 -6
  94. package/dist/mailbox/envelope.d.ts +7 -1
  95. package/dist/mailbox/envelope.js +9 -2
  96. package/dist/mailbox/ipcServer.d.ts +10 -2
  97. package/dist/mailbox/ipcServer.js +163 -13
  98. package/dist/mailbox/store.d.ts +89 -3
  99. package/dist/mailbox/store.js +895 -41
  100. package/dist/ops/evolutionGraphProjection.d.ts +20 -0
  101. package/dist/ops/evolutionGraphProjection.js +315 -0
  102. package/dist/ops/index.d.ts +2 -1
  103. package/dist/ops/index.js +2 -1
  104. package/dist/ops/selfUpdate.d.ts +8 -0
  105. package/dist/ops/selfUpdate.js +24 -8
  106. package/dist/personality/schema.d.ts +16 -16
  107. package/dist/schema/evolutionGraph.d.ts +784 -0
  108. package/dist/schema/evolutionGraph.js +187 -0
  109. package/dist/schema/index.d.ts +1 -0
  110. package/dist/schema/index.js +1 -0
  111. package/dist/schema/signal.d.ts +3 -3
  112. package/dist/schema/signal.js +1 -1
  113. package/dist/signals/curriculum.d.ts +55 -0
  114. package/dist/signals/curriculum.js +202 -0
  115. package/dist/signals/cycleHistoryFromEvents.js +17 -8
  116. package/dist/signals/expand.d.ts +15 -1
  117. package/dist/signals/expand.js +169 -1
  118. package/dist/signals/extractor.d.ts +2 -2
  119. package/dist/signals/extractor.js +31 -6
  120. package/dist/signals/index.d.ts +3 -1
  121. package/dist/signals/index.js +3 -1
  122. package/dist/signals/metaSignals.d.ts +4 -0
  123. package/dist/signals/metaSignals.js +42 -0
  124. package/dist/signals/signalGate.js +1 -1
  125. package/dist/signals/taskDomain.d.ts +22 -0
  126. package/dist/signals/taskDomain.js +43 -0
  127. package/dist/strategy/constraintAblation.js +115 -369
  128. package/dist/strategy/constraintAblationPredicates.d.ts +31 -0
  129. package/dist/strategy/constraintAblationPredicates.js +339 -0
  130. package/dist/trace/index.d.ts +3 -1
  131. package/dist/trace/index.js +3 -1
  132. package/dist/trace/learningTrace.d.ts +209 -0
  133. package/dist/trace/learningTrace.js +276 -0
  134. package/dist/trace/proxyTurns.d.ts +31 -0
  135. package/dist/trace/proxyTurns.js +137 -0
  136. package/dist/verify/sandboxRunner.d.ts +28 -0
  137. package/dist/verify/sandboxRunner.js +218 -19
  138. package/dist/verify/sandboxedValidation.d.ts +9 -0
  139. package/dist/verify/sandboxedValidation.js +113 -13
  140. package/dist/verify/validation.d.ts +11 -1
  141. package/dist/verify/validation.js +31 -0
  142. package/package.json +5 -2
@@ -0,0 +1,276 @@
1
+ // Agent runtime trace instrumentation (Learning Ops slice 1).
2
+ // Aligns with evomap-hub Learning Ops data plane contract (schemaVersion `trace_event.v0` /
3
+ // `learning_packet.v0`): the runtime emits ordered TraceEvents over the agent-run lifecycle and
4
+ // assembles a LearningPacket DRAFT locally. Hub delivery goes through the LearningPacketSink port —
5
+ // core never hardcodes a hub endpoint (file/console/memory sinks let a run trace without hub access).
6
+ import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';
7
+ import { dirname } from 'node:path';
8
+ export const TRACE_EVENT_SCHEMA = 'trace_event.v0';
9
+ export const LEARNING_PACKET_SCHEMA = 'learning_packet.v0';
10
+ /** Lifecycle vocabulary for slice 1. Kept flat + closed so hub-side eventType stays queryable. */
11
+ export const TRACE_EVENT_TYPES = [
12
+ 'run.started',
13
+ 'run.completed',
14
+ 'model.called',
15
+ 'tool.called',
16
+ 'tool.failed',
17
+ 'retry.attempted',
18
+ 'reflection.recorded',
19
+ 'intervention.received',
20
+ ];
21
+ export class InMemoryTraceSink {
22
+ events = [];
23
+ emit(event) { this.events.push(event); }
24
+ }
25
+ /** JSONL append sink for local inspection / offline replay. */
26
+ export class FileTraceSink {
27
+ path;
28
+ constructor(path) {
29
+ this.path = path;
30
+ }
31
+ emit(event) {
32
+ mkdirSync(dirname(this.path), { recursive: true });
33
+ appendFileSync(this.path, `${JSON.stringify(event)}\n`, 'utf8');
34
+ }
35
+ }
36
+ export class ConsoleTraceSink {
37
+ log;
38
+ constructor(log = (line) => console.error(line)) {
39
+ this.log = log;
40
+ }
41
+ emit(event) { this.log(`[trace] ${event.sequence} ${event.eventType} ${JSON.stringify(event.payload)}`); }
42
+ }
43
+ /**
44
+ * Per-run trace recorder: the single hook surface the runtime calls at lifecycle points.
45
+ * Sequence numbers are assigned here (monotonic per run), so downstream ordering never depends on
46
+ * sink latency or clock resolution.
47
+ */
48
+ export class AgentRunTraceRecorder {
49
+ opts;
50
+ sequence = 0;
51
+ recorded = [];
52
+ constructor(opts) {
53
+ this.opts = opts;
54
+ }
55
+ get events() { return this.recorded; }
56
+ runStarted(input = {}) {
57
+ return this.record('run.started', {
58
+ ...(input.taskSummary !== undefined ? { taskSummary: input.taskSummary } : {}),
59
+ ...(input.signals !== undefined ? { signals: [...input.signals] } : {}),
60
+ ...(input.geneId !== undefined ? { geneId: input.geneId } : {}),
61
+ }, input.metadata);
62
+ }
63
+ modelCalled(input = {}) {
64
+ return this.record('model.called', {
65
+ ...(input.provider !== undefined ? { provider: input.provider } : {}),
66
+ ...(input.model !== undefined ? { model: input.model } : {}),
67
+ ...(input.requestId !== undefined ? { requestId: input.requestId } : {}),
68
+ ...(input.latencyMs !== undefined ? { latencyMs: input.latencyMs } : {}),
69
+ ...(input.usage !== undefined ? { usage: input.usage } : {}),
70
+ ...(input.stopReason !== undefined ? { stopReason: input.stopReason } : {}),
71
+ });
72
+ }
73
+ toolCalled(input) {
74
+ return this.record('tool.called', {
75
+ toolName: input.toolName,
76
+ ...(input.callId !== undefined ? { callId: input.callId } : {}),
77
+ ...(input.durationMs !== undefined ? { durationMs: input.durationMs } : {}),
78
+ }, input.metadata);
79
+ }
80
+ toolFailed(input) {
81
+ return this.record('tool.failed', {
82
+ toolName: input.toolName,
83
+ ...(input.callId !== undefined ? { callId: input.callId } : {}),
84
+ error: input.error,
85
+ });
86
+ }
87
+ retryAttempted(input) {
88
+ return this.record('retry.attempted', {
89
+ attempt: input.attempt,
90
+ ...(input.reason !== undefined ? { reason: input.reason } : {}),
91
+ ...(input.target !== undefined ? { target: input.target } : {}),
92
+ });
93
+ }
94
+ reflectionRecorded(input) {
95
+ return this.record('reflection.recorded', {
96
+ outcome: input.outcome,
97
+ ...(input.action !== undefined ? { action: input.action } : {}),
98
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
99
+ });
100
+ }
101
+ interventionReceived(input) {
102
+ return this.record('intervention.received', {
103
+ kind: input.kind,
104
+ ...(input.actorId !== undefined ? { actorId: input.actorId } : {}),
105
+ ...(input.detail !== undefined ? { detail: input.detail } : {}),
106
+ });
107
+ }
108
+ runCompleted(input) {
109
+ return this.record('run.completed', {
110
+ status: input.status,
111
+ ...(input.score !== undefined ? { score: input.score } : {}),
112
+ ...(input.reason !== undefined ? { reason: input.reason } : {}),
113
+ ...(input.producedValue !== undefined ? { producedValue: input.producedValue } : {}),
114
+ ...(input.failureKind !== undefined ? { failureKind: input.failureKind } : {}),
115
+ });
116
+ }
117
+ /** Fold one normalized llm_turn (trace/trajectory.ts) into model.called + tool.called/tool.failed events. */
118
+ recordLlmTurn(turn) {
119
+ const out = [this.modelCalled({
120
+ ...(turn.provider !== null ? { provider: turn.provider } : {}),
121
+ ...(turn.chosen_model !== null ? { model: turn.chosen_model } : {}),
122
+ ...(turn.request_id !== null ? { requestId: turn.request_id } : {}),
123
+ ...(turn.latency_ms !== null ? { latencyMs: turn.latency_ms } : {}),
124
+ ...(turn.usage !== undefined ? { usage: { ...turn.usage } } : {}),
125
+ ...(typeof turn.stop_reason === 'string' ? { stopReason: turn.stop_reason } : {}),
126
+ })];
127
+ if (Array.isArray(turn.tool_calls)) {
128
+ for (const call of turn.tool_calls) {
129
+ const rec = call;
130
+ const toolName = typeof rec.name === 'string' && rec.name.length > 0 ? rec.name : 'unknown_tool';
131
+ const callId = typeof rec.id === 'string' ? rec.id : undefined;
132
+ out.push(typeof rec.error === 'string' && rec.error.length > 0
133
+ ? this.toolFailed({ toolName, ...(callId !== undefined ? { callId } : {}), error: rec.error })
134
+ : this.toolCalled({ toolName, ...(callId !== undefined ? { callId } : {}) }));
135
+ }
136
+ }
137
+ return out;
138
+ }
139
+ record(eventType, payload, metadata) {
140
+ this.sequence += 1;
141
+ const at = (this.opts.now ?? Date.now)();
142
+ const event = {
143
+ schemaVersion: TRACE_EVENT_SCHEMA,
144
+ eventId: (this.opts.eventIdFactory ?? ((seq) => `${this.opts.runId}-${String(seq).padStart(4, '0')}`))(this.sequence),
145
+ eventType,
146
+ traceId: this.opts.runId,
147
+ ...(this.opts.sessionId !== undefined ? { sessionId: this.opts.sessionId } : {}),
148
+ ...(this.opts.taskId !== undefined ? { taskId: this.opts.taskId } : {}),
149
+ sequence: this.sequence,
150
+ occurredAt: new Date(at).toISOString(),
151
+ payload,
152
+ metadata: metadata ?? {},
153
+ };
154
+ this.recorded.push(event);
155
+ this.opts.sink?.emit(event);
156
+ return event;
157
+ }
158
+ }
159
+ /* ── Root-event bridge: existing cycle lifecycle → trace events, via the sanctioned ObserverBus ── */
160
+ const BRIDGED_EVENT_TYPES = [
161
+ 'cycle.started', 'cycle.solidified', 'cycle.failed',
162
+ 'reflection.recorded',
163
+ 'actor.human.nudge', 'actor.human.intervene', 'actor.human.teach',
164
+ 'actor.human.review.approve', 'actor.human.review.reject',
165
+ ];
166
+ function asRecord(value) {
167
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
168
+ }
169
+ /**
170
+ * Bypass-side bridge (never blocks the write path): maps the engine's existing root events onto the
171
+ * run's TraceEvent stream, so CycleEngine needs no code change for run start/completion, reflection,
172
+ * or human intervention coverage.
173
+ */
174
+ export function learningTraceObserver(deps) {
175
+ const meta = {
176
+ name: 'learning_trace',
177
+ eventTypes: BRIDGED_EVENT_TYPES,
178
+ idempotent: true,
179
+ timeoutMs: deps.timeoutMs ?? 2_000,
180
+ };
181
+ return {
182
+ meta,
183
+ handle(event) {
184
+ const payload = asRecord(event.payload) ?? {};
185
+ if (event.type === 'cycle.started') {
186
+ deps.recorder.runStarted({ metadata: { cycleId: payload['cycleId'] ?? null } });
187
+ return;
188
+ }
189
+ if (event.type === 'cycle.solidified' || event.type === 'cycle.failed') {
190
+ const outcome = asRecord(payload['outcome']);
191
+ const status = event.type === 'cycle.solidified' ? 'success' : 'failed';
192
+ const score = typeof outcome?.['score'] === 'number' ? outcome['score'] : undefined;
193
+ const reason = typeof payload['error'] === 'string'
194
+ ? payload['error']
195
+ : typeof payload['reason'] === 'string' ? payload['reason'] : undefined;
196
+ deps.recorder.runCompleted({
197
+ status,
198
+ ...(score !== undefined ? { score } : {}),
199
+ ...(reason !== undefined ? { reason } : {}),
200
+ ...(typeof payload['producedValue'] === 'boolean' ? { producedValue: payload['producedValue'] } : {}),
201
+ ...(typeof payload['failureKind'] === 'string' ? { failureKind: payload['failureKind'] } : {}),
202
+ });
203
+ return;
204
+ }
205
+ if (event.type === 'reflection.recorded') {
206
+ deps.recorder.reflectionRecorded({
207
+ outcome: typeof payload['outcome'] === 'string' ? payload['outcome'] : 'unknown',
208
+ ...(typeof payload['action'] === 'string' ? { action: payload['action'] } : {}),
209
+ ...(typeof payload['summary'] === 'string' ? { summary: payload['summary'] } : {}),
210
+ });
211
+ return;
212
+ }
213
+ // actor.human.*: host/human intervention audit trail.
214
+ deps.recorder.interventionReceived({
215
+ kind: event.type.replace(/^actor\.human\./, ''),
216
+ ...(event.actor.id !== undefined ? { actorId: event.actor.id } : {}),
217
+ ...(typeof payload['detail'] === 'string' ? { detail: payload['detail'] } : {}),
218
+ });
219
+ },
220
+ };
221
+ }
222
+ export function buildLearningPacketDraft(recorder, input) {
223
+ const events = [...recorder.events].sort((a, b) => a.sequence - b.sequence);
224
+ const first = events[0];
225
+ const completed = [...events].reverse().find((e) => e.eventType === 'run.completed');
226
+ const completedStatus = completed?.payload['status'];
227
+ const failureKind = completed?.payload['failureKind'];
228
+ const started = events.find((e) => e.eventType === 'run.started');
229
+ const startedSummary = started?.payload['taskSummary'];
230
+ return {
231
+ schemaVersion: LEARNING_PACKET_SCHEMA,
232
+ status: 'draft',
233
+ source: { repo: input.sourceRepo, run: first?.traceId ?? 'unknown-run', type: 'agent_run', id: first?.traceId ?? 'unknown-run' },
234
+ task: {
235
+ taskId: first?.taskId ?? null,
236
+ summary: input.taskSummary ?? (typeof startedSummary === 'string' ? startedSummary : null),
237
+ signals: [...(input.signals ?? [])],
238
+ },
239
+ context: {
240
+ sessionId: first?.sessionId ?? null,
241
+ traceId: first?.traceId ?? 'unknown-run',
242
+ environment: input.environment ?? {},
243
+ },
244
+ trajectory: events,
245
+ artifacts: { placeholder: true, items: [] },
246
+ evaluation: {
247
+ placeholder: input.verification === undefined,
248
+ outcomeStatus: completedStatus === 'success' ? 'success' : completedStatus === 'failed' ? 'failed' : 'unknown',
249
+ verifier: input.verification?.verifier ?? null,
250
+ ...(input.verification !== undefined ? { verifierPassed: input.verification.passed } : {}),
251
+ ...(input.verification?.score !== undefined ? { verifierScore: input.verification.score } : {}),
252
+ failureCategory: typeof failureKind === 'string' ? failureKind : null,
253
+ },
254
+ governance: { placeholder: true, redactionStatus: 'metadata_only', consentStatus: 'unknown', trainingEligible: false, retentionPolicy: 'standard' },
255
+ };
256
+ }
257
+ export class InMemoryLearningPacketSink {
258
+ drafts = [];
259
+ async submit(draft) {
260
+ this.drafts.push(draft);
261
+ return { accepted: true };
262
+ }
263
+ }
264
+ /** Writes one JSON file per run — the offline/no-hub path (and a manual-inspection artifact). */
265
+ export class FileLearningPacketSink {
266
+ dir;
267
+ constructor(dir) {
268
+ this.dir = dir;
269
+ }
270
+ async submit(draft) {
271
+ mkdirSync(this.dir, { recursive: true });
272
+ const path = `${this.dir}/${draft.source.run}.learning-packet.json`;
273
+ writeFileSync(path, `${JSON.stringify(draft, null, 2)}\n`, 'utf8');
274
+ return { accepted: true, reason: path };
275
+ }
276
+ }
@@ -0,0 +1,31 @@
1
+ import { type TraceReadOptions } from './trajectoryExport.js';
2
+ import { type TraceTurnDraft } from './trajectory.js';
3
+ /** One agent run's wall-clock window (epoch ms, same host clock as the proxy's ts). */
4
+ export interface RunTurnWindow {
5
+ startMs: number;
6
+ endMs: number;
7
+ }
8
+ export interface SelectRunLlmTurnsOptions {
9
+ /**
10
+ * Exact-match correlation key: when the caller knows the spawned agent's session id, only that session's
11
+ * turns are returned (the window heuristic is skipped — the id is authoritative).
12
+ */
13
+ sessionId?: string;
14
+ }
15
+ export interface CollectRunLlmTurnsOptions extends SelectRunLlmTurnsOptions {
16
+ /** Decryption material forwarded to readTraceRowsFromJsonl. allowPartial is always forced on. */
17
+ readOptions?: TraceReadOptions;
18
+ }
19
+ /**
20
+ * Pure selector (unit-testable without fs): pick the turns that belong to the run per the correlation
21
+ * contract above, sorted by ts ascending (stable — equal timestamps keep day-file append order, and the
22
+ * recorder's fold order becomes the sequence order).
23
+ */
24
+ export declare function selectRunLlmTurns(turns: readonly TraceTurnDraft[], window: RunTurnWindow, opts?: SelectRunLlmTurnsOptions): TraceTurnDraft[];
25
+ /**
26
+ * Read the proxy trace day-files in `dir` and return this run's llm_turns (see the correlation contract
27
+ * above), ready to fold via recordLlmTurn. Reuses readTraceRowsFromJsonl (decryption + row parsing) and
28
+ * traceRecordToTurnDraft (normalization). Never throws: any failure — no proxy, missing dir, unreadable
29
+ * file, undecryptable rows — degrades to [].
30
+ */
31
+ export declare function collectRunLlmTurns(dir: string, window: RunTurnWindow, opts?: CollectRunLlmTurnsOptions): TraceTurnDraft[];
@@ -0,0 +1,137 @@
1
+ // Proxy llm_turn → run fold (Learning Ops slice 5): collect the per-request llm_turn records the LLM proxy
2
+ // captured DURING one agent run's wall-clock window, normalized as TraceTurnDrafts ready for
3
+ // AgentRunTraceRecorder.recordLlmTurn. This is what upgrades a run's trajectory from the bridge's single
4
+ // coarse model.called (the headless runner is a black box) to real per-request fidelity
5
+ // (provider/model/usage/latency/stop_reason + tool-call detail).
6
+ //
7
+ // Correlation contract (why time window + session-first-turn, not session_id alone): the headless runner does
8
+ // not report its session id back to the bridge (`claude -p --output-format text` is opaque), and llm_turn rows
9
+ // carry no cwd — so the run has no exact key to look up. What the run DOES own is its wall-clock window on the
10
+ // same host the proxy writes from (one shared clock, no skew). A turn belongs to the run iff:
11
+ // 1. its ts falls inside [startMs, endMs], AND
12
+ // 2. its session's FIRST observed turn also falls inside the window — a session spawned by this run cannot
13
+ // have traffic predating the run, while a concurrent interactive session (started earlier) is excluded by
14
+ // its pre-window history. Sessionless turns (session_id null) fall back to the window test alone.
15
+ // Callers that DO know the spawned agent's session id (e.g. a future runner passing --session-id) can pass
16
+ // `sessionId` for exact-match correlation instead of the heuristic.
17
+ //
18
+ // Residual risk, accepted + documented: an interactive session whose very first request starts inside the run
19
+ // window is indistinguishable from the run's own agent. On an unattended daemon host this is rare, and the
20
+ // fold is observability-only — it can bias a trace, never a verdict.
21
+ //
22
+ // Everything degrades silently to [] (missing dir, unreadable file, undecryptable envelope, bad ts): the
23
+ // learning trace must never fail or slow a task.
24
+ import { readdirSync, readFileSync } from 'node:fs';
25
+ import { join } from 'node:path';
26
+ import { readTraceRowsFromJsonl } from './trajectoryExport.js';
27
+ import { traceRecordToTurnDraft } from './trajectory.js';
28
+ /** Any proxy day-file (`llm-trace-*.jsonl`). */
29
+ const TRACE_FILE_RE = /^llm-trace-.*\.jsonl$/i;
30
+ /** The canonical day-stamped name the proxy's JsonlTraceSink writes (`llm-trace-YYYYMMDD.jsonl`, UTC). */
31
+ const DAY_STAMPED_FILE_RE = /^llm-trace-(\d{8})\.jsonl$/i;
32
+ function utcDayStamp(ms) {
33
+ const d = new Date(ms);
34
+ const p = (n) => String(n).padStart(2, '0');
35
+ return `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}`;
36
+ }
37
+ /**
38
+ * Keep day-stamped files that could contain the window's turns. Heuristic correlation must inspect all earlier
39
+ * day files to prove that an in-window session did not start before the run; exact session-id correlation only
40
+ * needs files that overlap the run window.
41
+ * Non-day-stamped `llm-trace-*.jsonl` names (custom sinks/tests) are kept conservatively — the ts window
42
+ * filter below is the authority; the filename filter only trims read volume.
43
+ */
44
+ function fileCoversWindow(name, window, includeSessionHistory) {
45
+ const match = DAY_STAMPED_FILE_RE.exec(name);
46
+ if (!match)
47
+ return true;
48
+ const stamp = match[1];
49
+ return (includeSessionHistory || stamp >= utcDayStamp(window.startMs)) && stamp <= utcDayStamp(window.endMs);
50
+ }
51
+ function turnTsMs(turn) {
52
+ if (turn.ts === null)
53
+ return null;
54
+ const ms = Date.parse(turn.ts);
55
+ return Number.isFinite(ms) ? ms : null;
56
+ }
57
+ /**
58
+ * Pure selector (unit-testable without fs): pick the turns that belong to the run per the correlation
59
+ * contract above, sorted by ts ascending (stable — equal timestamps keep day-file append order, and the
60
+ * recorder's fold order becomes the sequence order).
61
+ */
62
+ export function selectRunLlmTurns(turns, window, opts = {}) {
63
+ const stamped = turns
64
+ .map((turn) => ({ turn, tsMs: turnTsMs(turn) }))
65
+ .filter((entry) => entry.tsMs !== null);
66
+ let selected;
67
+ if (opts.sessionId !== undefined) {
68
+ selected = stamped.filter(({ turn }) => turn.session_id === opts.sessionId);
69
+ }
70
+ else {
71
+ // First observed turn per session across ALL provided turns (including pre-window rows from the same
72
+ // day files) — this is what tells an in-run spawned session apart from an older concurrent one.
73
+ const firstTsBySession = new Map();
74
+ for (const { turn, tsMs } of stamped) {
75
+ if (turn.session_id === null)
76
+ continue;
77
+ const prev = firstTsBySession.get(turn.session_id);
78
+ if (prev === undefined || tsMs < prev)
79
+ firstTsBySession.set(turn.session_id, tsMs);
80
+ }
81
+ selected = stamped.filter(({ turn, tsMs }) => {
82
+ if (tsMs < window.startMs || tsMs > window.endMs)
83
+ return false;
84
+ if (turn.session_id === null)
85
+ return true;
86
+ const firstTs = firstTsBySession.get(turn.session_id);
87
+ return firstTs !== undefined && firstTs >= window.startMs;
88
+ });
89
+ }
90
+ return selected
91
+ .map((entry, index) => ({ ...entry, index }))
92
+ .sort((a, b) => a.tsMs - b.tsMs || a.index - b.index)
93
+ .map(({ turn }) => turn);
94
+ }
95
+ /**
96
+ * Read the proxy trace day-files in `dir` and return this run's llm_turns (see the correlation contract
97
+ * above), ready to fold via recordLlmTurn. Reuses readTraceRowsFromJsonl (decryption + row parsing) and
98
+ * traceRecordToTurnDraft (normalization). Never throws: any failure — no proxy, missing dir, unreadable
99
+ * file, undecryptable rows — degrades to [].
100
+ */
101
+ export function collectRunLlmTurns(dir, window, opts = {}) {
102
+ try {
103
+ if (!(window.endMs >= window.startMs))
104
+ return [];
105
+ const names = readdirSync(dir)
106
+ .filter((name) => TRACE_FILE_RE.test(name) && fileCoversWindow(name, window, opts.sessionId === undefined))
107
+ .sort();
108
+ const turns = [];
109
+ for (const name of names) {
110
+ const dayMatch = DAY_STAMPED_FILE_RE.exec(name);
111
+ const isHistoricalDay = opts.sessionId === undefined
112
+ && dayMatch !== null
113
+ && dayMatch[1] < utcDayStamp(window.startMs);
114
+ let text;
115
+ try {
116
+ text = readFileSync(join(dir, name), 'utf8');
117
+ }
118
+ catch {
119
+ continue;
120
+ }
121
+ // allowPartial forced on: an undecryptable envelope is a coverage gap, never a fold failure.
122
+ const { rows } = readTraceRowsFromJsonl(text, { ...(opts.readOptions ?? {}), allowPartial: true });
123
+ for (const row of rows) {
124
+ const turn = traceRecordToTurnDraft(row);
125
+ if (turn !== null) {
126
+ // Older day files establish that a session predates this run; they can never contribute candidate
127
+ // turns even if a malformed row carries an in-window timestamp.
128
+ turns.push(isHistoricalDay ? { ...turn, ts: new Date(window.startMs - 1).toISOString() } : turn);
129
+ }
130
+ }
131
+ }
132
+ return selectRunLlmTurns(turns, window, opts.sessionId !== undefined ? { sessionId: opts.sessionId } : {});
133
+ }
134
+ catch {
135
+ return [];
136
+ }
137
+ }
@@ -19,13 +19,41 @@ export interface SandboxOptions {
19
19
  * unprivileged mount namespaces are unavailable. Binaries live outside these dirs, so the command still runs.
20
20
  */
21
21
  hideHomeSecrets?: boolean;
22
+ /** Remount the inherited filesystem read-only inside the mount namespace, leaving only an isolated /tmp writable. */
23
+ readOnlyFilesystem?: boolean;
24
+ /** Host scratch directory exposed as the sandbox's only writable filesystem. */
25
+ writableTmpDir?: string;
26
+ /** Read-only checkout root remounted at its original absolute path after HOME and /tmp are hidden. */
27
+ readOnlyRoot?: string;
28
+ /** Put the full command tree in a bounded cgroup v2. Required by verified Skill execution. */
29
+ resourceLimits?: boolean;
22
30
  /** Injected unshare-availability probe (test seam). Default: a real `unshare -r -m -n true` check (cached). */
23
31
  unshareCheck?: () => boolean;
32
+ /** Injected cgroup allocator (test seam). */
33
+ resourceGroupFactory?: () => SandboxResourceGroup | null;
24
34
  }
35
+ export interface SandboxResourceGroup {
36
+ procsFile: string;
37
+ cleanup: () => void;
38
+ }
39
+ /** Configure an already-created cgroup. Kept separate so limit values are testable without resource exhaustion. */
40
+ export declare function configureSandboxResourceGroup(path: string): boolean;
41
+ /** Allocate a delegated cgroup v2 for one validation command. Returns null unless every limit is enforceable. */
42
+ export declare function createSandboxResourceGroup(): SandboxResourceGroup | null;
43
+ /** Join the cgroup before exec, so attacker-controlled code never runs outside the aggregate resource budget. */
44
+ export declare function resourceLimitedCommand(cmd: string, args: readonly string[], procsFile: string): {
45
+ cmd: string;
46
+ args: string[];
47
+ };
48
+ export declare function sandboxResourceLimitsAvailable(): boolean;
25
49
  /** Wrap an (executable,args) in unprivileged namespaces per the requested isolation (pure — testable). */
26
50
  export declare function isolationCommand(bin: string, args: readonly string[], opts: {
27
51
  noNetwork?: boolean;
28
52
  hideHomeSecrets?: boolean;
53
+ readOnlyFilesystem?: boolean;
54
+ writableTmpDir?: string;
55
+ readOnlyRoot?: string;
56
+ cwd?: string;
29
57
  }): {
30
58
  cmd: string;
31
59
  args: string[];