@principles/core 1.83.0 → 1.84.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 (25) hide show
  1. package/dist/runtime-v2/index.d.ts +2 -0
  2. package/dist/runtime-v2/index.d.ts.map +1 -1
  3. package/dist/runtime-v2/index.js +2 -0
  4. package/dist/runtime-v2/index.js.map +1 -1
  5. package/dist/runtime-v2/internalization/dreamer-output.d.ts +4 -3
  6. package/dist/runtime-v2/internalization/dreamer-output.d.ts.map +1 -1
  7. package/dist/runtime-v2/internalization/dreamer-output.js +11 -9
  8. package/dist/runtime-v2/internalization/dreamer-output.js.map +1 -1
  9. package/dist/runtime-v2/internalization/dreamer-runner.d.ts +31 -92
  10. package/dist/runtime-v2/internalization/dreamer-runner.d.ts.map +1 -1
  11. package/dist/runtime-v2/internalization/dreamer-runner.js +79 -495
  12. package/dist/runtime-v2/internalization/dreamer-runner.js.map +1 -1
  13. package/dist/runtime-v2/runner/__tests__/base-peer-runner-trust-boundary.test.d.ts +2 -0
  14. package/dist/runtime-v2/runner/__tests__/base-peer-runner-trust-boundary.test.d.ts.map +1 -0
  15. package/dist/runtime-v2/runner/__tests__/base-peer-runner-trust-boundary.test.js +238 -0
  16. package/dist/runtime-v2/runner/__tests__/base-peer-runner-trust-boundary.test.js.map +1 -0
  17. package/dist/runtime-v2/runner/base-peer-runner.d.ts +122 -0
  18. package/dist/runtime-v2/runner/base-peer-runner.d.ts.map +1 -0
  19. package/dist/runtime-v2/runner/base-peer-runner.js +516 -0
  20. package/dist/runtime-v2/runner/base-peer-runner.js.map +1 -0
  21. package/dist/runtime-v2/runner/peer-runner-types.d.ts +107 -0
  22. package/dist/runtime-v2/runner/peer-runner-types.d.ts.map +1 -0
  23. package/dist/runtime-v2/runner/peer-runner-types.js +13 -0
  24. package/dist/runtime-v2/runner/peer-runner-types.js.map +1 -0
  25. package/package.json +1 -1
@@ -0,0 +1,516 @@
1
+ /**
2
+ * BasePeerRunner — Abstract base class for all peer runners (PRI-302).
3
+ *
4
+ * Extracts the shared lease → buildContext → invoke → poll → fetch →
5
+ * validate → succeed/fail pipeline from 8 duplicated runner implementations.
6
+ *
7
+ * Subclasses implement:
8
+ * - permanentErrorCategories (abstract getter)
9
+ * - buildContext() — runner-specific context assembly
10
+ * - invokeRuntime() — runner-specific LLM invocation
11
+ * - validateOutput() — runner-specific output validation
12
+ * - succeedTask() — runner-specific artifact commit + task success
13
+ *
14
+ * Optional hooks:
15
+ * - emitSuccessTelemetry() — runner-specific success telemetry (default: no-op)
16
+ * - checkLineageIntegrity() — lineage strip contract check (default: no-op)
17
+ *
18
+ * @see docs/adr/0003-peer-agent-state-machine-orchestration.md
19
+ * @see Linear PRI-302
20
+ */
21
+ import { PDRuntimeError } from '../error-categories.js';
22
+ import { RunnerPhase } from './runner-phase.js';
23
+ // ── Defaults ─────────────────────────────────────────────────────────────────
24
+ const DEFAULT_PEER_RUNNER_OPTIONS = {
25
+ pollIntervalMs: 5_000,
26
+ timeoutMs: 300_000,
27
+ defaultMaxAttempts: 3,
28
+ agentId: 'peer-runner',
29
+ };
30
+ function resolvePeerRunnerOptions(options, defaultAgentId) {
31
+ return {
32
+ pollIntervalMs: options.pollIntervalMs ?? DEFAULT_PEER_RUNNER_OPTIONS.pollIntervalMs,
33
+ timeoutMs: options.timeoutMs ?? DEFAULT_PEER_RUNNER_OPTIONS.timeoutMs,
34
+ defaultMaxAttempts: options.defaultMaxAttempts ?? DEFAULT_PEER_RUNNER_OPTIONS.defaultMaxAttempts,
35
+ owner: options.owner,
36
+ runtimeKind: options.runtimeKind,
37
+ agentId: options.agentId ?? defaultAgentId,
38
+ };
39
+ }
40
+ // ── BasePeerRunner ───────────────────────────────────────────────────────────
41
+ /**
42
+ * Abstract base class for peer runners.
43
+ *
44
+ * TContext — the type returned by buildContext(). Must include contextHash.
45
+ * TOutput — the type of the validated LLM output.
46
+ */
47
+ export class BasePeerRunner {
48
+ // ── Shared dependencies (protected for subclass access) ──
49
+ stateManager;
50
+ runtimeAdapter;
51
+ eventEmitter;
52
+ artifactStore;
53
+ resolvedOptions;
54
+ config;
55
+ phase = RunnerPhase.Idle;
56
+ constructor(deps, options, config) {
57
+ this.stateManager = deps.stateManager;
58
+ this.runtimeAdapter = deps.runtimeAdapter;
59
+ this.eventEmitter = deps.eventEmitter;
60
+ this.artifactStore = deps.artifactStore;
61
+ this.config = config;
62
+ this.resolvedOptions = resolvePeerRunnerOptions(options, config.defaultAgentId);
63
+ }
64
+ // ── Observability ──────────────────────────────────────────────────────────
65
+ /** Current internal phase. For testing/observability only. */
66
+ get currentPhase() {
67
+ return this.phase;
68
+ }
69
+ // ── Optional hooks (default no-op) ─────────────────────────────────────────
70
+ /** Emit runner-specific success telemetry. Called after validation passes. */
71
+ // eslint-disable-next-line @typescript-eslint/class-methods-use-this
72
+ emitSuccessTelemetry(_taskId, _output, _context) {
73
+ // default no-op
74
+ }
75
+ /**
76
+ * Check lineage strip contract. Called AFTER validation passes.
77
+ * Receives validated output — safe to treat as TOutput.
78
+ */
79
+ // eslint-disable-next-line @typescript-eslint/class-methods-use-this
80
+ checkLineageIntegrity(_taskId, _output) {
81
+ // default no-op
82
+ }
83
+ /**
84
+ * Transform output after fetch, before validation.
85
+ * Used by runners that need to re-inject lineage fields stripped by the adapter.
86
+ * Receives untrusted data — must NOT assume TOutput shape.
87
+ */
88
+ // eslint-disable-next-line @typescript-eslint/class-methods-use-this
89
+ postFetchTransform(_taskId, _untrustedOutput) {
90
+ // default no-op
91
+ }
92
+ // ── Template method: full pipeline ─────────────────────────────────────────
93
+ /**
94
+ * Execute the full peer runner lifecycle for a task.
95
+ *
96
+ * Pipeline: lease → resolveRunId → buildContext → invoke → poll →
97
+ * fetch → validate → succeedTask (abstract)
98
+ *
99
+ * Each invocation is independent — no mutable state between run() calls.
100
+ */
101
+ async run(taskId) {
102
+ this.phase = RunnerPhase.Idle;
103
+ // 1. Acquire lease — isolated try/catch so lease_conflict never uses synthetic TaskRecord
104
+ let leasedTask;
105
+ try {
106
+ leasedTask = await this.stateManager.acquireLease({
107
+ taskId,
108
+ owner: this.resolvedOptions.owner,
109
+ runtimeKind: this.resolvedOptions.runtimeKind,
110
+ });
111
+ }
112
+ catch (error) {
113
+ return await this.handleLeaseOrPhaseError(taskId, error);
114
+ }
115
+ // 1b. Validate task kind
116
+ if (leasedTask.taskKind !== this.config.expectedTaskKind) {
117
+ this.emitEvent('wrong_task_kind', taskId, {
118
+ expectedKind: this.config.expectedTaskKind,
119
+ actualKind: leasedTask.taskKind,
120
+ });
121
+ await this.stateManager.markTaskFailed(taskId, 'input_invalid');
122
+ return {
123
+ status: 'failed',
124
+ taskId,
125
+ errorCategory: 'input_invalid',
126
+ failureReason: `Task kind must be '${this.config.expectedTaskKind}', got '${leasedTask.taskKind}'`,
127
+ attemptCount: leasedTask.attemptCount,
128
+ };
129
+ }
130
+ this.emitEvent('task_leased', taskId, {
131
+ taskKind: this.config.expectedTaskKind,
132
+ attemptCount: leasedTask.attemptCount,
133
+ });
134
+ // All subsequent errors use the real leasedTask — no synthetic TaskRecord allowed
135
+ try {
136
+ // 2. Resolve store runId
137
+ const storeRunId = await this.resolveStoreRunId(taskId);
138
+ // 3. Build context
139
+ this.phase = RunnerPhase.BuildingContext;
140
+ const context = await this.buildContext(taskId);
141
+ this.emitEvent('context_built', taskId, { contextHash: context.contextHash });
142
+ // 4. Invoke runtime
143
+ this.phase = RunnerPhase.Invoking;
144
+ const runHandle = await this.invokeRuntime(taskId, context);
145
+ this.emitEvent('run_started', taskId, {
146
+ runtimeKind: this.resolvedOptions.runtimeKind,
147
+ });
148
+ // 5. Poll until terminal
149
+ this.phase = RunnerPhase.Polling;
150
+ const finalStatus = await this.pollUntilTerminal(runHandle);
151
+ // 6. Handle non-success terminal states
152
+ if (finalStatus.status !== 'succeeded') {
153
+ return await this.handleRuntimeFailure(taskId, leasedTask, finalStatus);
154
+ }
155
+ // 7. Fetch output (returns unknown — untrusted LLM/runtime payload)
156
+ this.phase = RunnerPhase.FetchingOutput;
157
+ const untrustedOutput = await this.fetchAndParseOutput(runHandle.runId, taskId);
158
+ // 7b. Post-fetch transform on untrusted data (e.g., re-inject lineage fields).
159
+ // Operates on `unknown` — must NOT assume TOutput shape (ERR-001).
160
+ this.postFetchTransform(taskId, untrustedOutput);
161
+ // 8. Validate — the trust boundary. Only validated output becomes TOutput.
162
+ this.phase = RunnerPhase.Validating;
163
+ const validationResult = await this.validateOutput(untrustedOutput, taskId, context);
164
+ if (!validationResult.valid) {
165
+ return await this.handleValidationError({
166
+ taskId,
167
+ task: leasedTask,
168
+ errors: validationResult.errors,
169
+ errorCategory: validationResult.errorCategory,
170
+ });
171
+ }
172
+ // Validation passed — safe to treat as TOutput.
173
+ const output = untrustedOutput;
174
+ this.emitEvent('output_validated', taskId, {});
175
+ // 8b. Check lineage integrity (receives validated output)
176
+ this.checkLineageIntegrity(taskId, output);
177
+ // 8c. Emit success telemetry (receives validated output)
178
+ this.emitSuccessTelemetry(taskId, output, context);
179
+ // 9. Succeed task (abstract — subclass implements commit strategy)
180
+ return await this.succeedTask(taskId, storeRunId, output, leasedTask, context.contextHash, context);
181
+ }
182
+ catch (error) {
183
+ // Post-lease errors use retryOrFail with the real leasedTask
184
+ return await this.handlePostLeaseError(taskId, leasedTask, error);
185
+ }
186
+ }
187
+ // ── Telemetry ──────────────────────────────────────────────────────────────
188
+ /**
189
+ * Emit a telemetry event with the runner's name prefix.
190
+ * Event type: `{runnerName}_{eventType}`
191
+ */
192
+ emitEvent(eventType, taskId, payload) {
193
+ this.eventEmitter.emitTelemetry({
194
+ eventType: `${this.config.runnerName}_${eventType}`,
195
+ traceId: taskId,
196
+ timestamp: new Date().toISOString(),
197
+ sessionId: this.resolvedOptions.owner,
198
+ agentId: this.resolvedOptions.agentId,
199
+ payload,
200
+ });
201
+ }
202
+ // ── Polling ────────────────────────────────────────────────────────────────
203
+ async pollUntilTerminal(runHandle) {
204
+ const deadline = Date.now() + this.resolvedOptions.timeoutMs;
205
+ const terminalStatuses = ['succeeded', 'failed', 'timed_out', 'cancelled'];
206
+ while (Date.now() < deadline) {
207
+ const status = await this.runtimeAdapter.pollRun(runHandle.runId);
208
+ if (terminalStatuses.includes(status.status)) {
209
+ return status;
210
+ }
211
+ await this.sleep(this.resolvedOptions.pollIntervalMs);
212
+ }
213
+ // Timeout — cancel gracefully
214
+ let cancelFailed = false;
215
+ try {
216
+ await this.runtimeAdapter.cancelRun(runHandle.runId);
217
+ }
218
+ catch (cancelErr) {
219
+ cancelFailed = true;
220
+ this.emitEvent('cancel_run_failed', runHandle.runId, {
221
+ runId: runHandle.runId,
222
+ errorMessage: cancelErr instanceof Error ? cancelErr.message : String(cancelErr),
223
+ });
224
+ }
225
+ const cancelNote = cancelFailed ? ' (cancelRun also failed)' : '';
226
+ throw new PDRuntimeError('timeout', `Run ${runHandle.runId} timed out after ${this.resolvedOptions.timeoutMs}ms${cancelNote}`);
227
+ }
228
+ // ── Output fetching ────────────────────────────────────────────────────────
229
+ /**
230
+ * Fetch raw output from the runtime adapter.
231
+ *
232
+ * Returns `unknown` — the payload is untrusted LLM/runtime output.
233
+ * Callers MUST validate before treating as TOutput (ERR-001, ERR-005).
234
+ */
235
+ async fetchAndParseOutput(runId, taskId) {
236
+ let result;
237
+ try {
238
+ result = await this.runtimeAdapter.fetchOutput(runId);
239
+ }
240
+ catch (fetchErr) {
241
+ this.emitEvent('output_extraction_failed', taskId, {
242
+ runId,
243
+ stage: 'fetchOutput',
244
+ errorMessage: fetchErr instanceof Error ? fetchErr.message : String(fetchErr),
245
+ });
246
+ throw fetchErr;
247
+ }
248
+ if (!result || !result.payload) {
249
+ this.emitEvent('output_extraction_failed', taskId, {
250
+ runId,
251
+ stage: 'payload_missing',
252
+ errorMessage: `No output available for run ${runId}`,
253
+ });
254
+ throw new PDRuntimeError('output_invalid', `No output available for run ${runId}`);
255
+ }
256
+ // Structural check: payload must be a non-null object.
257
+ // This is NOT a type assertion — we still return `unknown`.
258
+ const { payload } = result;
259
+ if (typeof payload !== 'object' || payload === null) {
260
+ this.emitEvent('output_extraction_failed', taskId, {
261
+ runId,
262
+ stage: 'payload_not_object',
263
+ errorMessage: `Output payload is not an object for run ${runId}`,
264
+ });
265
+ throw new PDRuntimeError('output_invalid', `Output payload is not an object for run ${runId}`);
266
+ }
267
+ return payload;
268
+ }
269
+ // ── Lineage resolution ─────────────────────────────────────────────────────
270
+ /** Resolve artifact IDs from predecessor tasks for lineage tracking. */
271
+ async resolveLineageArtifactIds(taskId) {
272
+ const { hydratePITaskRecord } = await import('../internalization/pitask-metadata.js');
273
+ const task = await this.stateManager.getTask(taskId);
274
+ if (!task)
275
+ return { ids: [], hasRejected: false };
276
+ const piTask = hydratePITaskRecord(task);
277
+ const deps = piTask?.dependencyTaskIds ?? [];
278
+ if (deps.length === 0)
279
+ return { ids: [], hasRejected: false };
280
+ const lineageIds = [];
281
+ let hasRejected = false;
282
+ const results = await Promise.allSettled(deps.map((depId) => this.artifactStore.listBySourceTaskId(depId)));
283
+ for (const result of results) {
284
+ if (result.status === 'fulfilled') {
285
+ for (const artifact of result.value) {
286
+ lineageIds.push(artifact.artifactId);
287
+ }
288
+ }
289
+ else {
290
+ hasRejected = true;
291
+ }
292
+ }
293
+ return { ids: lineageIds, hasRejected };
294
+ }
295
+ // ── Store helpers ──────────────────────────────────────────────────────────
296
+ async resolveStoreRunId(taskId) {
297
+ const runs = await this.stateManager.getRunsByTask(taskId);
298
+ const latestRun = runs[runs.length - 1];
299
+ if (!latestRun) {
300
+ throw new PDRuntimeError('execution_failed', `No run records found for task ${taskId} after lease acquisition`);
301
+ }
302
+ return latestRun.runId;
303
+ }
304
+ /** Compute a deterministic hash from context references (observability only). */
305
+ static hashContextRefs(refs) {
306
+ if (refs.length === 0)
307
+ return 'empty';
308
+ const str = refs.join('|');
309
+ let hash = 0;
310
+ for (let i = 0; i < str.length; i++) {
311
+ hash = (Math.imul(31, hash) + str.charCodeAt(i)) | 0;
312
+ }
313
+ return `ctx-${Math.abs(hash).toString(16)}`;
314
+ }
315
+ // ── Error handling ─────────────────────────────────────────────────────────
316
+ async handleLeaseOrPhaseError(taskId, error) {
317
+ const classified = this.classifyError(error);
318
+ // lease_conflict is concurrent-access conflict, not a state change.
319
+ // No mutation methods (markTaskFailed/markTaskRetryWait) are called.
320
+ if (classified.category === 'lease_conflict') {
321
+ this.emitEvent('run_failed', taskId, {
322
+ errorCategory: 'lease_conflict',
323
+ errorMessage: classified.message,
324
+ });
325
+ return {
326
+ status: 'failed',
327
+ taskId,
328
+ errorCategory: 'lease_conflict',
329
+ failureReason: classified.message,
330
+ attemptCount: 1,
331
+ };
332
+ }
333
+ // Non-lease errors (e.g., storage_unavailable before lease) must not
334
+ // use synthetic TaskRecord. Build one with real defaults from options.
335
+ this.emitEvent('run_failed', taskId, {
336
+ errorCategory: classified.category,
337
+ errorMessage: classified.message,
338
+ });
339
+ const task = {
340
+ taskId,
341
+ taskKind: this.config.expectedTaskKind,
342
+ status: 'leased',
343
+ createdAt: new Date().toISOString(),
344
+ updatedAt: new Date().toISOString(),
345
+ attemptCount: 1,
346
+ maxAttempts: this.resolvedOptions.defaultMaxAttempts,
347
+ };
348
+ return this.retryOrFail({ taskId, task, errorCategory: classified.category, failureReason: classified.message });
349
+ }
350
+ async handlePostLeaseError(taskId, task, error) {
351
+ const classified = this.classifyError(error);
352
+ this.emitEvent('run_failed', taskId, {
353
+ errorCategory: classified.category,
354
+ errorMessage: classified.message,
355
+ });
356
+ return this.retryOrFail({ taskId, task, errorCategory: classified.category, failureReason: classified.message });
357
+ }
358
+ async handleRuntimeFailure(taskId, task, runStatus) {
359
+ const errorCategory = this.mapRunStatusToErrorCategory(runStatus.status, runStatus.reason);
360
+ this.emitEvent('run_failed', taskId, {
361
+ runStatus: runStatus.status,
362
+ errorCategory,
363
+ });
364
+ return this.retryOrFail({
365
+ taskId,
366
+ task,
367
+ errorCategory,
368
+ failureReason: `Runtime execution ended with status: ${runStatus.status}`,
369
+ });
370
+ }
371
+ async handleValidationError(ctx) {
372
+ const category = ctx.errorCategory ?? 'output_invalid';
373
+ this.emitEvent('output_invalid', ctx.taskId, {
374
+ errorCount: ctx.errors.length,
375
+ errorCategory: category,
376
+ });
377
+ return this.retryOrFail({
378
+ taskId: ctx.taskId,
379
+ task: ctx.task,
380
+ errorCategory: category,
381
+ failureReason: `Validation failed: ${ctx.errors.join('; ')}`,
382
+ });
383
+ }
384
+ // ── Retry/fail state machine ───────────────────────────────────────────────
385
+ /**
386
+ * Core retry-or-fail decision.
387
+ *
388
+ * Uses try/catch around markTaskFailed/markTaskRetryWait for robustness.
389
+ * If state manager operations fail, returns storage_unavailable instead of
390
+ * propagating the exception (ERR-002: graceful degradation with reason).
391
+ */
392
+ async retryOrFail(ctx) {
393
+ // Permanent errors — never retry
394
+ if (this.permanentErrorCategories.has(ctx.errorCategory)) {
395
+ try {
396
+ await this.stateManager.markTaskFailed(ctx.taskId, ctx.errorCategory);
397
+ }
398
+ catch (stateErr) {
399
+ this.emitEvent('mark_failed_error', ctx.taskId, {
400
+ errorCategory: 'storage_unavailable',
401
+ attemptCount: ctx.task.attemptCount,
402
+ errorMessage: stateErr instanceof Error ? stateErr.message : String(stateErr),
403
+ });
404
+ return {
405
+ status: 'failed',
406
+ taskId: ctx.taskId,
407
+ errorCategory: 'storage_unavailable',
408
+ failureReason: `State manager error: ${ctx.failureReason}`,
409
+ attemptCount: ctx.task.attemptCount,
410
+ };
411
+ }
412
+ this.emitEvent('task_failed', ctx.taskId, {
413
+ errorCategory: ctx.errorCategory,
414
+ attemptCount: ctx.task.attemptCount,
415
+ failureReason: ctx.failureReason,
416
+ });
417
+ this.phase = RunnerPhase.Failed;
418
+ return {
419
+ status: 'failed',
420
+ taskId: ctx.taskId,
421
+ errorCategory: ctx.errorCategory,
422
+ failureReason: ctx.failureReason,
423
+ attemptCount: ctx.task.attemptCount,
424
+ };
425
+ }
426
+ // Retry policy check
427
+ const shouldRetry = this.stateManager.getRetryPolicy().shouldRetry(ctx.task);
428
+ if (shouldRetry) {
429
+ try {
430
+ await this.stateManager.markTaskRetryWait(ctx.taskId, ctx.errorCategory);
431
+ }
432
+ catch (stateErr) {
433
+ this.emitEvent('mark_retry_error', ctx.taskId, {
434
+ errorCategory: 'storage_unavailable',
435
+ attemptCount: ctx.task.attemptCount,
436
+ errorMessage: stateErr instanceof Error ? stateErr.message : String(stateErr),
437
+ });
438
+ return {
439
+ status: 'failed',
440
+ taskId: ctx.taskId,
441
+ errorCategory: 'storage_unavailable',
442
+ failureReason: `State manager error: ${ctx.failureReason}`,
443
+ attemptCount: ctx.task.attemptCount,
444
+ };
445
+ }
446
+ this.emitEvent('task_retried', ctx.taskId, {
447
+ errorCategory: ctx.errorCategory,
448
+ attemptCount: ctx.task.attemptCount,
449
+ });
450
+ this.phase = RunnerPhase.RetryWaiting;
451
+ return {
452
+ status: 'retried',
453
+ taskId: ctx.taskId,
454
+ errorCategory: ctx.errorCategory,
455
+ failureReason: ctx.failureReason,
456
+ attemptCount: ctx.task.attemptCount,
457
+ };
458
+ }
459
+ // Max attempts exceeded
460
+ try {
461
+ await this.stateManager.markTaskFailed(ctx.taskId, 'max_attempts_exceeded');
462
+ }
463
+ catch (stateErr) {
464
+ this.emitEvent('mark_failed_error', ctx.taskId, {
465
+ errorCategory: 'storage_unavailable',
466
+ attemptCount: ctx.task.attemptCount,
467
+ errorMessage: stateErr instanceof Error ? stateErr.message : String(stateErr),
468
+ });
469
+ return {
470
+ status: 'failed',
471
+ taskId: ctx.taskId,
472
+ errorCategory: 'storage_unavailable',
473
+ failureReason: `State manager error: ${ctx.failureReason}`,
474
+ attemptCount: ctx.task.attemptCount,
475
+ };
476
+ }
477
+ this.emitEvent('task_failed', ctx.taskId, {
478
+ errorCategory: 'max_attempts_exceeded',
479
+ attemptCount: ctx.task.attemptCount,
480
+ failureReason: `Max attempts exceeded: ${ctx.failureReason}`,
481
+ });
482
+ this.phase = RunnerPhase.Failed;
483
+ return {
484
+ status: 'failed',
485
+ taskId: ctx.taskId,
486
+ errorCategory: 'max_attempts_exceeded',
487
+ failureReason: `Max attempts exceeded: ${ctx.failureReason}`,
488
+ attemptCount: ctx.task.attemptCount,
489
+ };
490
+ }
491
+ // ── Error classification ──────────────────────────────────────────────────
492
+ // eslint-disable-next-line @typescript-eslint/class-methods-use-this
493
+ classifyError(error) {
494
+ if (error instanceof PDRuntimeError) {
495
+ return { category: error.category, message: error.message };
496
+ }
497
+ if (error instanceof Error) {
498
+ return { category: 'execution_failed', message: error.message };
499
+ }
500
+ return { category: 'execution_failed', message: String(error) };
501
+ }
502
+ // eslint-disable-next-line @typescript-eslint/class-methods-use-this
503
+ mapRunStatusToErrorCategory(status, _reason) {
504
+ switch (status) {
505
+ case 'failed': return 'execution_failed';
506
+ case 'timed_out': return 'timeout';
507
+ case 'cancelled': return 'cancelled';
508
+ default: return 'execution_failed';
509
+ }
510
+ }
511
+ // eslint-disable-next-line @typescript-eslint/class-methods-use-this
512
+ sleep(ms) {
513
+ return new Promise((resolve) => setTimeout(resolve, ms));
514
+ }
515
+ }
516
+ //# sourceMappingURL=base-peer-runner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base-peer-runner.js","sourceRoot":"","sources":["../../../src/runtime-v2/runner/base-peer-runner.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAWH,OAAO,EAAE,cAAc,EAAwB,MAAM,wBAAwB,CAAC;AAE9E,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAWhD,gFAAgF;AAEhF,MAAM,2BAA2B,GAAuE;IACtG,cAAc,EAAE,KAAK;IACrB,SAAS,EAAE,OAAO;IAClB,kBAAkB,EAAE,CAAC;IACrB,OAAO,EAAE,aAAa;CACd,CAAC;AAEX,SAAS,wBAAwB,CAC/B,OAA0B,EAC1B,cAAsB;IAEtB,OAAO;QACL,cAAc,EAAE,OAAO,CAAC,cAAc,IAAI,2BAA2B,CAAC,cAAc;QACpF,SAAS,EAAE,OAA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the per-runner duplicated interfaces:
5
+ * - DreamerRunnerOptions / ScribeRunnerOptions / ...
6
+ * - DreamerRunnerDeps / ScribeRunnerDeps / ...
7
+ * - DreamerRunnerResult / ScribeRunnerResult / ...
8
+ * - FailureContext / SucceedContext / ValidationErrorContext
9
+ *
10
+ * @see docs/adr/0003-peer-agent-state-machine-orchestration.md
11
+ */
12
+ import type { PDErrorCategory } from '../error-categories.js';
13
+ import type { RuntimeStateManager } from '../store/runtime-state-manager.js';
14
+ import type { PDRuntimeAdapter } from '../runtime-protocol.js';
15
+ import type { StoreEventEmitter } from '../store/event-emitter.js';
16
+ import type { PIArtifactStore } from '../internalization/pi-artifact.js';
17
+ import type { PeerRunnerKind } from '../internalization/peer-runner-contracts.js';
18
+ import type { TaskRecord } from '../task-status.js';
19
+ /** Shared runner options. All peer runners accept this shape. */
20
+ export interface PeerRunnerOptions {
21
+ readonly pollIntervalMs?: number;
22
+ readonly timeoutMs?: number;
23
+ readonly defaultMaxAttempts?: number;
24
+ readonly owner: string;
25
+ readonly runtimeKind: string;
26
+ readonly agentId?: string;
27
+ }
28
+ /** Resolved options with defaults applied. */
29
+ export interface ResolvedPeerRunnerOptions {
30
+ readonly pollIntervalMs: number;
31
+ readonly timeoutMs: number;
32
+ readonly defaultMaxAttempts: number;
33
+ readonly owner: string;
34
+ readonly runtimeKind: string;
35
+ readonly agentId: string;
36
+ }
37
+ /**
38
+ * Shared dependencies injected into all peer runners.
39
+ *
40
+ * Runners with additional dependencies (e.g. DiagnosticianRunner needs
41
+ * ContextAssembler + DiagnosticianCommitter) should extend this interface.
42
+ */
43
+ export interface PeerRunnerDeps {
44
+ readonly stateManager: RuntimeStateManager;
45
+ readonly runtimeAdapter: PDRuntimeAdapter;
46
+ readonly eventEmitter: StoreEventEmitter;
47
+ readonly artifactStore: PIArtifactStore;
48
+ }
49
+ /**
50
+ * Runner-specific configuration passed to the BasePeerRunner constructor.
51
+ * Each subclass provides its own config instance.
52
+ */
53
+ export interface PeerRunnerConfig {
54
+ /** Runner name for telemetry event prefix (e.g. 'dreamer', 'scribe'). */
55
+ readonly runnerName: string;
56
+ /** Expected taskKind for lease validation (e.g. 'dreamer'). */
57
+ readonly expectedTaskKind: PeerRunnerKind;
58
+ /** Default agentId if not provided in options. */
59
+ readonly defaultAgentId: string;
60
+ /** ResultRef prefix (e.g. 'dreamer' → 'dreamer://runId'). */
61
+ readonly resultRefPrefix: string;
62
+ }
63
+ /** Status values shared by all peer runner results. */
64
+ export type PeerRunnerResultStatus = 'succeeded' | 'failed' | 'retried';
65
+ /**
66
+ * Generic result type for all peer runners.
67
+ * Replaces the per-runner result interfaces (DreamerRunnerResult, etc.).
68
+ */
69
+ export interface PeerRunnerResult<TOutput> {
70
+ readonly status: PeerRunnerResultStatus;
71
+ readonly taskId: string;
72
+ readonly runId?: string;
73
+ readonly artifactId?: string;
74
+ readonly resultRef?: string;
75
+ readonly contextHash?: string;
76
+ readonly output?: TOutput;
77
+ readonly errorCategory?: PDErrorCategory;
78
+ readonly failureReason?: string;
79
+ readonly attemptCount: number;
80
+ }
81
+ /**
82
+ * Validation result returned by the abstract validateOutput() method.
83
+ * Replaces the per-runner validation result interfaces.
84
+ *
85
+ * Note: named PeerRunnerValidationResult to avoid collision with
86
+ * ValidationResult from rule-code-validator.ts.
87
+ */
88
+ export interface PeerRunnerValidationResult {
89
+ readonly valid: boolean;
90
+ readonly errors: readonly string[];
91
+ readonly errorCategory?: PDErrorCategory;
92
+ }
93
+ /** Context for the retryOrFail decision. */
94
+ export interface FailureContext {
95
+ readonly taskId: string;
96
+ readonly task: TaskRecord;
97
+ readonly errorCategory: PDErrorCategory;
98
+ readonly failureReason: string;
99
+ }
100
+ /** Context for validation error handling. */
101
+ export interface ValidationErrorContext {
102
+ readonly taskId: string;
103
+ readonly task: TaskRecord;
104
+ readonly errors: readonly string[];
105
+ readonly errorCategory?: PDErrorCategory;
106
+ }
107
+ //# sourceMappingURL=peer-runner-types.d.ts.map
@@ -0,0 +1 @@
1
+ {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