@ftrdotdev/pi-delegates 0.1.0 → 0.2.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 (94) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/OPERATIONS.md +79 -6
  3. package/README.md +25 -17
  4. package/ROADMAP.md +21 -0
  5. package/TESTING.md +153 -318
  6. package/package.json +4 -3
  7. package/skills/pi-delegates/SKILL.md +29 -0
  8. package/skills/pi-delegates/references/launch.md +28 -0
  9. package/src/docs-contract.test.ts +106 -0
  10. package/src/domain/definitions.ts +3 -1
  11. package/src/domain/failure.ts +33 -0
  12. package/src/domain/model-source.ts +30 -0
  13. package/src/domain/orchestration/control.test.ts +69 -35
  14. package/src/domain/orchestration/control.ts +110 -89
  15. package/src/domain/orchestration/fanout.test.ts +125 -20
  16. package/src/domain/orchestration/fanout.ts +60 -22
  17. package/src/domain/orchestration/gates.test.ts +14 -15
  18. package/src/domain/orchestration/launch.test.ts +210 -11
  19. package/src/domain/orchestration/launch.ts +142 -32
  20. package/src/domain/orchestration/requests.test.ts +11 -16
  21. package/src/domain/orchestration/requests.ts +14 -1
  22. package/src/domain/orchestration/review.test.ts +89 -11
  23. package/src/domain/orchestration/run-wait.test.ts +4 -1
  24. package/src/domain/orchestration/run-wait.ts +1 -1
  25. package/src/domain/orchestration/workflow.test.ts +157 -16
  26. package/src/domain/orchestration/workflow.ts +269 -196
  27. package/src/domain/run-records.ts +214 -52
  28. package/src/domain/settlement.test.ts +186 -0
  29. package/src/domain/settlement.ts +137 -0
  30. package/src/domain/shapes.test.ts +20 -0
  31. package/src/domain/skills.test.ts +31 -20
  32. package/src/domain/skills.ts +36 -19
  33. package/src/domain/toolkit.test.ts +15 -1
  34. package/src/domain/toolkit.ts +8 -13
  35. package/src/domain/turn-budget.test.ts +37 -0
  36. package/src/domain/turn-budget.ts +23 -0
  37. package/src/domain/view.test.ts +78 -14
  38. package/src/domain/view.ts +67 -35
  39. package/src/extension/commands.test.ts +27 -23
  40. package/src/extension/commands.ts +10 -7
  41. package/src/extension/entry.test.ts +214 -56
  42. package/src/extension/entry.ts +78 -40
  43. package/src/extension/gate-alerts.test.ts +10 -8
  44. package/src/extension/inspector-command.test.ts +173 -21
  45. package/src/extension/inspector-command.ts +100 -53
  46. package/src/extension/prompt.test.ts +2 -4
  47. package/src/extension/retry-observer.test.ts +292 -0
  48. package/src/extension/retry-observer.ts +150 -0
  49. package/src/extension/settle-alerts.test.ts +579 -0
  50. package/src/extension/settle-alerts.ts +175 -0
  51. package/src/extension/shortcut.test.ts +6 -8
  52. package/src/extension/tools.test.ts +325 -24
  53. package/src/extension/tools.ts +61 -13
  54. package/src/extension/version.test.ts +21 -29
  55. package/src/goldens.test.ts +294 -0
  56. package/src/harness-policy.test.ts +13 -11
  57. package/src/layers.test.ts +309 -0
  58. package/src/layers.ts +405 -0
  59. package/src/package-manifest.test.ts +32 -19
  60. package/src/presentation/actions.test.ts +8 -8
  61. package/src/presentation/activity.test.ts +7 -8
  62. package/src/presentation/close.test.ts +14 -16
  63. package/src/presentation/inspector.test.ts +14 -11
  64. package/src/presentation/inspector.ts +27 -25
  65. package/src/presentation/overlay.test.ts +1 -3
  66. package/src/presentation/repaint.test.ts +226 -190
  67. package/src/presentation/snapshot.test.ts +5 -0
  68. package/src/presentation/status.test.ts +43 -0
  69. package/src/presentation/status.ts +30 -0
  70. package/src/presentation/strip.test.ts +13 -6
  71. package/src/presentation/strip.ts +7 -14
  72. package/src/presentation/wording.test.ts +153 -3
  73. package/src/presentation/wording.ts +78 -6
  74. package/src/runtime/bridge.ts +38 -44
  75. package/src/runtime/{timers.test.ts → clock.test.ts} +1 -1
  76. package/src/runtime/clock.ts +31 -0
  77. package/src/runtime/config.test.ts +26 -7
  78. package/src/runtime/config.ts +6 -1
  79. package/src/runtime/execution-env.test.ts +6 -8
  80. package/src/runtime/extensions.test.ts +4 -4
  81. package/src/runtime/extensions.ts +23 -11
  82. package/src/runtime/handle.ts +54 -0
  83. package/src/runtime/log.test.ts +19 -7
  84. package/src/runtime/log.ts +23 -0
  85. package/src/runtime/mcp.test.ts +29 -32
  86. package/src/runtime/mcp.ts +70 -3
  87. package/src/runtime/runtime-state.test.ts +25 -0
  88. package/src/runtime/runtime-state.ts +36 -0
  89. package/src/runtime/session-tag.ts +11 -0
  90. package/src/runtime/session.test.ts +24 -31
  91. package/src/runtime/session.ts +99 -261
  92. package/src/runtime/storage.ts +29 -0
  93. package/src/test-hygiene.test.ts +97 -0
  94. package/src/runtime/timers.ts +0 -10
@@ -1,7 +1,7 @@
1
1
  import type { Context } from "@earendil-works/chord/context";
2
2
  import type { ModelThinkingLevel } from "@earendil-works/pi-ai";
3
3
  import type { ConversationId, Task, TaskOptions, Tx } from "@earendil-works/pi-durable";
4
- import { Effect, Schema } from "effect";
4
+ import { Effect, Match, Schema } from "effect";
5
5
  import type { SessionRuntime } from "../../runtime/session.ts";
6
6
  import { requestId } from "../../runtime/bridge.ts";
7
7
  import {
@@ -24,6 +24,8 @@ import {
24
24
  type RunState,
25
25
  } from "../run-records.ts";
26
26
  import { bindToolkit } from "../toolkit.ts";
27
+ import { resolveMaxTurns } from "../turn-budget.ts";
28
+ import { Execution } from "../failure.ts";
27
29
  import { FanoutRequest, type FanoutChild, type FanoutInput, type FanoutPolicy } from "./fanout.ts";
28
30
  import { REVIEW_INSTRUCTION } from "./review.ts";
29
31
  import { CODING_EXTENSION } from "../names.ts";
@@ -36,14 +38,33 @@ export const SingleRequest = Schema.Struct({
36
38
  agent: Schema.String,
37
39
  task: Schema.String,
38
40
  definition: Schema.optional(InlineDefinition),
41
+ /** The turn budget for this call; a child's own value wins over it. */
42
+ maxTurns: Schema.optional(Schema.Finite),
43
+ /** Absent: `wait`. Part of the request, so part of the run's identity. */
44
+ execution: Schema.optional(Execution),
39
45
  });
40
46
  export type SingleRequest = typeof SingleRequest.Type;
41
47
 
48
+ /** The one normalization: `wait` and absent hash identically, so they are one run. */
49
+ export const requestForIdentity = <T extends { readonly execution?: Execution | undefined }>(
50
+ request: T,
51
+ ): T => (request.execution !== "wait" ? request : { ...request, execution: undefined });
52
+
42
53
  export const ReviewRequest = Schema.Struct({
43
54
  kind: Schema.Literal("review"),
44
55
  task: Schema.String,
45
- reviewers: Schema.Array(Schema.Struct({ agent: Schema.String })),
56
+ reviewers: Schema.Array(
57
+ Schema.Struct({
58
+ agent: Schema.String,
59
+ /** This reviewer's own budget. */
60
+ maxTurns: Schema.optional(Schema.Finite),
61
+ }),
62
+ ),
63
+ /** The budget for every reviewer this request does not name one for. */
64
+ maxTurns: Schema.optional(Schema.Finite),
46
65
  lane: Schema.optional(Schema.String),
66
+ /** Absent: `wait`. */
67
+ execution: Schema.optional(Execution),
47
68
  });
48
69
  export type ReviewRequest = typeof ReviewRequest.Type;
49
70
 
@@ -249,9 +270,10 @@ export const textFor = (view: RunView): string => {
249
270
  ...(view.gates.length > 0 ? [`gate ${view.gates.join(", ")}`] : []),
250
271
  ...(view.requests.length > 0 ? [`request ${view.requests.join(", ")}`] : []),
251
272
  ];
273
+ // Waiting with nothing named is a group whose children run, not a decision.
252
274
  return parts.length > 0
253
275
  ? `Run ${view.runId} waits for ${parts.join(" and ")}.`
254
- : `Run ${view.runId} waits.`;
276
+ : `Run ${view.runId} is running.`;
255
277
  }
256
278
  case "running":
257
279
  return `Run ${view.runId} is running.`;
@@ -292,6 +314,64 @@ const finish = async (
292
314
  return { view, text: textFor(view) };
293
315
  };
294
316
 
317
+ /** One child's budget: child level, request level, definition, then the config default. */
318
+ const budgetOf = (input: {
319
+ readonly child?: number | undefined;
320
+ readonly request?: number | undefined;
321
+ readonly definition: AgentDefinition;
322
+ readonly deps: LaunchDeps;
323
+ }): number =>
324
+ resolveMaxTurns({
325
+ ...(input.child === undefined ? {} : { child: input.child }),
326
+ ...(input.request === undefined ? {} : { request: input.request }),
327
+ ...(input.definition.maxTurns === undefined ? {} : { definition: input.definition.maxTurns }),
328
+ configDefault: input.deps.runtime.config.maxTurns,
329
+ ceiling: input.deps.runtime.config.maxTurnsCeiling,
330
+ });
331
+
332
+ /** A detached group returns once its children exist; admission is short, never the run. */
333
+ export const DETACHED_ADMIT_MS = 5_000;
334
+
335
+ /** Waits, bounded, until the run's children are claimed: a detached group's whole wait. */
336
+ export const awaitChildren = async (
337
+ runtime: SessionRuntime,
338
+ runId: string,
339
+ count: number,
340
+ boundMs: number = DETACHED_ADMIT_MS,
341
+ ): Promise<void> => {
342
+ const deadline = runtime.now() + boundMs;
343
+ while (runtime.now() < deadline) {
344
+ const doc = await runtime.snapshot(RunDoc, runId);
345
+ if ((doc?.childRunIds.length ?? 0) >= count) return;
346
+ await new Promise<void>((resolve) => {
347
+ runtime.timers.setTimeout(resolve, 10);
348
+ });
349
+ }
350
+ };
351
+
352
+ /**
353
+ * Wait enters the frozen wait unchanged; detached returns the opening view at
354
+ * claim, or once a group's children exist so the view names one row per child.
355
+ */
356
+ const afterClaim = async (
357
+ execution: Execution | undefined,
358
+ runId: string,
359
+ deps: LaunchDeps,
360
+ children: number = 0,
361
+ ): Promise<LaunchResult> => {
362
+ if (execution !== "detached") return finish(runId, deps.runtime, deps.waitMs, deps.signal);
363
+ if (children > 0) {
364
+ await awaitChildren(
365
+ deps.runtime,
366
+ runId,
367
+ children,
368
+ Math.min(deps.waitMs > 0 ? deps.waitMs : DETACHED_ADMIT_MS, DETACHED_ADMIT_MS),
369
+ );
370
+ }
371
+ const view = await viewRun(runId, deps.runtime);
372
+ return { view, text: textFor(view) };
373
+ };
374
+
295
375
  /** A codemode definition accepts workflow launches only. */
296
376
  const assertWorkflowOnly = (agent: string, definition: AgentDefinition): void => {
297
377
  if (definition.codemode === "runs") {
@@ -321,29 +401,21 @@ const assertScriptSize = (script: string): void => {
321
401
  }
322
402
  };
323
403
 
324
- /** A new request kind must be handled here, or this call fails to compile. */
325
- const assertNever = (value: never): never => {
326
- throw new Error(`Unhandled launch kind: ${String(value)}`);
327
- };
328
-
329
404
  /** Launches one agent, waits under the soft deadline and returns its view. */
330
- export const launch = async (request: LaunchRequest, deps: LaunchDeps): Promise<LaunchResult> => {
331
- switch (request.kind) {
332
- case "fanout":
333
- return launchFanout(request, deps);
334
- case "review":
335
- return launchReview(request, deps);
336
- case "workflow":
337
- return launchSingle({ kind: "single", agent: request.agent, task: request.script }, deps, {
338
- lane: request.lane ?? "workflow",
339
- mode: "workflow",
340
- });
341
- case "single":
342
- return launchSingle(request, deps, { lane: "default", mode: "single" });
343
- default:
344
- return assertNever(request);
345
- }
346
- };
405
+ export const launch = async (request: LaunchRequest, deps: LaunchDeps): Promise<LaunchResult> =>
406
+ Match.value(request).pipe(
407
+ Match.discriminators("kind")({
408
+ single: (r) => launchSingle(r, deps, { lane: "default", mode: "single" }),
409
+ fanout: (r) => launchFanout(r, deps),
410
+ review: (r) => launchReview(r, deps),
411
+ workflow: (r) =>
412
+ launchSingle({ kind: "single", agent: r.agent, task: r.script }, deps, {
413
+ lane: r.lane ?? "workflow",
414
+ mode: "workflow",
415
+ }),
416
+ }),
417
+ Match.exhaustive,
418
+ );
347
419
 
348
420
  export interface SingleClaimRequest {
349
421
  readonly runTask: Task<RunInput, RunState, RunResult, Record<never, never>>;
@@ -354,6 +426,8 @@ export interface SingleClaimRequest {
354
426
  readonly conversationId: ConversationId;
355
427
  readonly ownership: TaskOptions["ownership"];
356
428
  readonly mode: RunMode;
429
+ /** The launch kind the run document records; absent: `wait`. */
430
+ readonly execution?: Execution;
357
431
  /** The workflow run whose child this is: recorded as `parentRunId` and appended to its list. */
358
432
  readonly parent?: {
359
433
  readonly runId: string;
@@ -387,6 +461,7 @@ export const claimSingle = async (
387
461
  definition: request.input.definition.name,
388
462
  lane: request.input.lane,
389
463
  mode: request.mode,
464
+ ...(request.execution === undefined ? {} : { execution: request.execution }),
390
465
  ...(request.parent === undefined ? {} : { parentRunId: request.parent.runId }),
391
466
  };
392
467
  const claimed = await claimLaunch(tx, {
@@ -418,6 +493,7 @@ export const claimSingle = async (
418
493
  doc.attempt = claimed.attempt;
419
494
  doc.taskId = taskId;
420
495
  doc.gateRunId = gateRunId;
496
+ doc.maxTurns = input.maxTurns;
421
497
  if (request.parent !== undefined) {
422
498
  doc.parentRunId = request.parent.runId;
423
499
  const parentDoc = await tx.doc(RunDoc, request.parent.runId, {
@@ -452,8 +528,14 @@ const launchSingle = async (
452
528
  assertWorkflowOnly(request.agent, plan.definition);
453
529
  }
454
530
  await validateToolkit(plan.definition, deps);
455
- const identity = requestId(deps.runtime.sessionId, resolved);
531
+ const identity = requestId(deps.runtime.sessionId, requestForIdentity(resolved));
456
532
  const lane = options.lane;
533
+ const maxTurns = resolveMaxTurns({
534
+ ...(resolved.maxTurns === undefined ? {} : { request: resolved.maxTurns }),
535
+ ...(plan.definition.maxTurns === undefined ? {} : { definition: plan.definition.maxTurns }),
536
+ configDefault: deps.runtime.config.maxTurns,
537
+ ceiling: deps.runtime.config.maxTurnsCeiling,
538
+ });
457
539
 
458
540
  const claim = await deps.runtime.run((context) =>
459
541
  claimSingle((change) => deps.runtime.harness.commit(change, deps.context ?? context), {
@@ -464,17 +546,18 @@ const launchSingle = async (
464
546
  task: request.task,
465
547
  host: deps.host,
466
548
  lane,
467
- maxTurns: deps.runtime.config.maxTurns,
549
+ maxTurns,
468
550
  },
469
551
  requestedAgent: request.agent,
470
552
  conversationId: deps.runtime.root.id,
471
553
  ownership: { kind: "conversation" },
472
554
  mode: options.mode,
555
+ ...(request.execution === undefined ? {} : { execution: request.execution }),
473
556
  index: true,
474
557
  }),
475
558
  );
476
559
 
477
- return finish(claim.runId, deps.runtime, deps.waitMs, deps.signal);
560
+ return afterClaim(request.execution, claim.runId, deps);
478
561
  };
479
562
 
480
563
  const startGroup = async (
@@ -490,8 +573,17 @@ const startGroup = async (
490
573
  readonly label: string;
491
574
  },
492
575
  ): Promise<LaunchResult> => {
493
- const identity = requestId(deps.runtime.sessionId, request);
494
- const seed = { definition: group.definition, lane: group.lane, mode: group.mode };
576
+ const identity = requestId(
577
+ deps.runtime.sessionId,
578
+ requestForIdentity(request as LaunchRequest & { readonly execution?: Execution }),
579
+ );
580
+ const execution = "execution" in request ? request.execution : undefined;
581
+ const seed = {
582
+ definition: group.definition,
583
+ lane: group.lane,
584
+ mode: group.mode,
585
+ ...(execution === undefined ? {} : { execution }),
586
+ };
495
587
 
496
588
  const claim = await deps.runtime.run((context) =>
497
589
  deps.runtime.harness.commit(async (tx) => {
@@ -509,6 +601,7 @@ const startGroup = async (
509
601
  children: group.children,
510
602
  host: deps.host,
511
603
  maxTurns: deps.runtime.config.maxTurns,
604
+ ...(execution === undefined ? {} : { execution }),
512
605
  policy: group.policy,
513
606
  review: group.review,
514
607
  };
@@ -517,6 +610,7 @@ const startGroup = async (
517
610
  conversationId: deps.runtime.root.id,
518
611
  });
519
612
  const doc = await tx.doc(RunDoc, claimed.runId, seed);
613
+ doc.execution = execution ?? "wait";
520
614
  doc.requestedAgent = group.lane;
521
615
  doc.task = `${group.label}: ${group.children.length} children`;
522
616
  doc.requestId = identity;
@@ -529,7 +623,7 @@ const startGroup = async (
529
623
  }, deps.context ?? context),
530
624
  );
531
625
 
532
- return finish(claim.runId, deps.runtime, deps.waitMs, deps.signal);
626
+ return afterClaim(execution, claim.runId, deps, group.children.length);
533
627
  };
534
628
 
535
629
  const launchFanout = async (request: FanoutRequest, deps: LaunchDeps): Promise<LaunchResult> => {
@@ -538,7 +632,17 @@ const launchFanout = async (request: FanoutRequest, deps: LaunchDeps): Promise<L
538
632
  const plan = await planFor({ kind: "single", agent: entry.agent, task: entry.task }, deps);
539
633
  assertWorkflowOnly(entry.agent, plan.definition);
540
634
  await validateToolkit(plan.definition, deps);
541
- children.push({ agent: entry.agent, task: entry.task, definition: plan.definition });
635
+ children.push({
636
+ agent: entry.agent,
637
+ task: entry.task,
638
+ definition: plan.definition,
639
+ maxTurns: budgetOf({
640
+ child: entry.maxTurns,
641
+ request: request.maxTurns,
642
+ definition: plan.definition,
643
+ deps,
644
+ }),
645
+ });
542
646
  }
543
647
  return startGroup(request, deps, {
544
648
  lane: request.lane,
@@ -567,6 +671,12 @@ const launchReview = async (request: ReviewRequest, deps: LaunchDeps): Promise<L
567
671
  role: `${plan.definition.prompt.role}\n\n${REVIEW_INSTRUCTION}`,
568
672
  },
569
673
  },
674
+ maxTurns: budgetOf({
675
+ child: reviewer.maxTurns,
676
+ request: request.maxTurns,
677
+ definition: plan.definition,
678
+ deps,
679
+ }),
570
680
  });
571
681
  }
572
682
  return startGroup(request, deps, {
@@ -1,26 +1,20 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
2
  import { assert, it } from "@effect/vitest";
3
+ import { makeTempDir } from "../../../test-support/platform.ts";
3
4
  import { Effect } from "effect";
4
- import { mkdtemp } from "node:fs/promises";
5
- import { tmpdir } from "node:os";
6
- import { join } from "node:path";
7
5
  import { stubHostSource } from "../../../test-support/stub-model-source.ts";
8
6
  import { HostModelAdapter } from "../../runtime/models.ts";
9
- import {
10
- openReadOnlyRuntime,
11
- openSessionRuntime,
12
- storePathFor,
13
- type SessionIdentity,
14
- } from "../../runtime/session.ts";
7
+ import { openReadOnlyRuntime, storePathFor, type SessionIdentity } from "../../runtime/session.ts";
8
+
15
9
  import { CODING_EXTENSION, QUESTIONS_EXTENSION } from "../names.ts";
16
10
  import type { SessionRuntime } from "../../runtime/session.ts";
17
11
  import { nullLogSink, type LogFields, type LogLevel, type LogSink } from "../../runtime/log.ts";
12
+ import type { SkillsCatalogue } from "../skills.ts";
18
13
  import { bindToolkit } from "../toolkit.ts";
19
14
  import { defineAgent } from "../definitions.ts";
20
15
  import { refusingSandbox } from "./workflow-section.ts";
21
16
  import { createDelegatesRegistry } from "../../runtime/extensions.ts";
22
17
  import type { AdmissionHost } from "./admission.ts";
23
- import type { SkillsService } from "../skills.ts";
24
18
  import { DAY_MS } from "./gates.ts";
25
19
  import {
26
20
  askTool,
@@ -36,6 +30,7 @@ import {
36
30
  type RequestIndexRow,
37
31
  type RequestRecord,
38
32
  } from "./requests.ts";
33
+ import { openTestSession, type TestSession } from "../../../test-support/seams.ts";
39
34
 
40
35
  interface DocToken {
41
36
  readonly definition: {
@@ -353,13 +348,13 @@ it("an answer that lands before the commit makes the tool return instead of park
353
348
  });
354
349
 
355
350
  it("the registry installs ask under the questions extension", async () => {
356
- const skills: SkillsService = {
351
+ const skills: SkillsCatalogue["Service"] = {
357
352
  all: () => [],
358
353
  find: () => undefined,
359
354
  resolve: () => [],
360
355
  render: () => "",
361
- diagnostics: () => [],
362
- reload: Effect.void,
356
+ diagnostics: Effect.succeed([]),
357
+ reload: Effect.succeed([]),
363
358
  };
364
359
  const admission: AdmissionHost = {
365
360
  inspect: () => Promise.reject(new Error("the install must not inspect the harness")),
@@ -518,12 +513,12 @@ it("the tool's cancel hook commits the cancellation once", async () => {
518
513
  });
519
514
 
520
515
  const identityFor = async (sessionId: string): Promise<SessionIdentity> => {
521
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-requests-"));
516
+ const sessionDir = await makeTempDir("delegates-requests-");
522
517
  return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
523
518
  };
524
519
 
525
- const openAt = (identity: SessionIdentity, now: () => number): Promise<SessionRuntime> =>
526
- openSessionRuntime({
520
+ const openAt = (identity: SessionIdentity, now: () => number): Promise<TestSession> =>
521
+ openTestSession({
527
522
  identity,
528
523
  models: new HostModelAdapter(stubHostSource()),
529
524
  now,
@@ -13,7 +13,7 @@ import {
13
13
  import { obj, str } from "@earendil-works/pi-schema";
14
14
  import { Schema } from "effect";
15
15
  import type { SessionRuntime } from "../../runtime/session.ts";
16
- import type { LogSink } from "../../runtime/log.ts";
16
+ import { errorFields, type LogSink } from "../../runtime/log.ts";
17
17
  import type { ViewPort } from "../view.ts";
18
18
  import { taskId as toTaskId } from "../ids.ts";
19
19
  import { ToolkitDoc } from "../toolkit.ts";
@@ -767,3 +767,16 @@ export const pruneRequests = async (runtime: SessionRuntime): Promise<number> =>
767
767
  }, context),
768
768
  );
769
769
  };
770
+
771
+ /**
772
+ * The start-up sweep: prune, report the count, and never fail the session. A
773
+ * failed sweep is one warning; the next start retries it.
774
+ */
775
+ export const sweepRequests = async (runtime: SessionRuntime): Promise<void> => {
776
+ try {
777
+ const pruned = await pruneRequests(runtime);
778
+ if (pruned > 0) runtime.log.write("info", "requests.pruned", { retired: pruned });
779
+ } catch (error) {
780
+ runtime.log.write("warn", "requests.prune_failed", errorFields(error));
781
+ }
782
+ };
@@ -1,5 +1,6 @@
1
1
  import { MemoryStorage } from "@earendil-works/pi-durable";
2
2
  import { assert, it } from "@effect/vitest";
3
+ import { makeTempDir } from "../../../test-support/platform.ts";
3
4
  import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
4
5
  import {
5
6
  dispositionArbitrary,
@@ -7,9 +8,6 @@ import {
7
8
  freeTextArbitrary,
8
9
  noteArbitrary,
9
10
  } from "../../../test-support/arbitraries.ts";
10
- import { mkdtemp } from "node:fs/promises";
11
- import { tmpdir } from "node:os";
12
- import { join } from "node:path";
13
11
  import { stubHostSource } from "../../../test-support/stub-model-source.ts";
14
12
  import { createCatalogue } from "../definitions.ts";
15
13
  import { launch, type HostDefaults } from "./launch.ts";
@@ -19,10 +17,13 @@ import {
19
17
  ReviewDoc,
20
18
  type Disposition as DispositionType,
21
19
  } from "./review.ts";
22
- import { viewSession } from "../view.ts";
20
+ import { viewRun, viewSession } from "../view.ts";
21
+ import { RunDoc } from "../run-records.ts";
22
+ import { waitFor } from "../../../test-support/wait.ts";
23
23
  import { DEFAULTS } from "../../runtime/config.ts";
24
24
  import { HostModelAdapter } from "../../runtime/models.ts";
25
- import { openSessionRuntime, type SessionIdentity } from "../../runtime/session.ts";
25
+ import { type SessionIdentity } from "../../runtime/session.ts";
26
+ import { openTestSession } from "../../../test-support/seams.ts";
26
27
 
27
28
  const host: HostDefaults = {
28
29
  model: { provider: "stub", modelId: "stub-1" },
@@ -30,7 +31,7 @@ const host: HostDefaults = {
30
31
  };
31
32
 
32
33
  const identityFor = async (sessionId: string): Promise<SessionIdentity> => {
33
- const sessionDir = await mkdtemp(join(tmpdir(), "delegates-review-"));
34
+ const sessionDir = await makeTempDir("delegates-review-");
34
35
  return { sessionId, sessionDir, cwd: sessionDir, agentDir: sessionDir };
35
36
  };
36
37
 
@@ -39,7 +40,7 @@ const corpus = (texts: readonly string[]) => stubHostSource({ texts });
39
40
  const reviewers = [{ agent: "reviewer" }, { agent: "reviewer" }, { agent: "reviewer" }];
40
41
 
41
42
  it("each reviewer gets a disposition row", async () => {
42
- const runtime = await openSessionRuntime({
43
+ const runtime = await openTestSession({
43
44
  identity: await identityFor("s-1"),
44
45
  models: new HostModelAdapter(
45
46
  corpus([
@@ -82,7 +83,7 @@ it.each(cases)("aggregation follows the policy order: %j", (dispositions, expect
82
83
  });
83
84
 
84
85
  it("a reviewer that fails yields inconclusive", async () => {
85
- const runtime = await openSessionRuntime({
86
+ const runtime = await openTestSession({
86
87
  identity: await identityFor("s-1"),
87
88
  models: new HostModelAdapter(
88
89
  stubHostSource({
@@ -108,7 +109,7 @@ it("a reviewer that fails yields inconclusive", async () => {
108
109
  });
109
110
 
110
111
  it("a malformed answer is inconclusive and keeps the raw text", async () => {
111
- const runtime = await openSessionRuntime({
112
+ const runtime = await openTestSession({
112
113
  identity: await identityFor("s-1"),
113
114
  models: new HostModelAdapter(corpus(["looks good to me", '{"disposition":"maybe"}'])),
114
115
  storage: new MemoryStorage(),
@@ -175,7 +176,7 @@ it.prop(
175
176
 
176
177
  it("dispositions survive a reopen", async () => {
177
178
  const identity = await identityFor("s-1");
178
- const first = await openSessionRuntime({
179
+ const first = await openTestSession({
179
180
  identity,
180
181
  models: new HostModelAdapter(
181
182
  corpus(['{"disposition":"accepted"}', '{"disposition":"rejected"}']),
@@ -187,7 +188,7 @@ it("dispositions survive a reopen", async () => {
187
188
  );
188
189
  await first.close();
189
190
 
190
- const second = await openSessionRuntime({ identity, models: new HostModelAdapter(corpus([])) });
191
+ const second = await openTestSession({ identity, models: new HostModelAdapter(corpus([])) });
191
192
  try {
192
193
  const session = await viewSession(second);
193
194
  const review = session.reviews[0];
@@ -212,3 +213,80 @@ it("chooses the last valid object after prose with two objects", () => {
212
213
  note: "fix it",
213
214
  });
214
215
  });
216
+
217
+ const deferred = (): { readonly promise: Promise<void>; readonly release: () => void } => {
218
+ let release: () => void = () => {};
219
+ const promise = new Promise<void>((resolve) => {
220
+ release = resolve;
221
+ });
222
+ return { promise, release };
223
+ };
224
+
225
+ it("a detached review returns the group status without waiting", async () => {
226
+ const held = deferred();
227
+ const runtime = await openTestSession({
228
+ identity: await identityFor("s-detached"),
229
+ models: new HostModelAdapter(
230
+ stubHostSource({
231
+ text: '{"disposition":"accepted"}',
232
+ hold: () => held.promise,
233
+ holdAt: [1, 2],
234
+ }),
235
+ ),
236
+ storage: new MemoryStorage(),
237
+ });
238
+ try {
239
+ const result = await launch(
240
+ {
241
+ kind: "review",
242
+ task: "review the diff",
243
+ reviewers: [{ agent: "reviewer" }, { agent: "reviewer" }],
244
+ execution: "detached",
245
+ },
246
+ { runtime, catalogue: createCatalogue(), host, waitMs: 5_000 },
247
+ );
248
+ assert.notStrictEqual(result.view.status, "answered");
249
+ assert.strictEqual(await runtime.snapshot(ReviewDoc, result.view.runId), undefined);
250
+ assert.strictEqual((await runtime.snapshot(RunDoc, result.view.runId))?.execution, "detached");
251
+ held.release();
252
+ await waitFor(
253
+ async () => (await viewRun(result.view.runId, runtime)).status === "answered",
254
+ "the detached review settles",
255
+ 10_000,
256
+ );
257
+ } finally {
258
+ await runtime.close();
259
+ }
260
+ }, 20_000);
261
+
262
+ it("a review honours a reviewer's own budget", async () => {
263
+ const runtime = await openTestSession({
264
+ identity: await identityFor("s-budget"),
265
+ models: new HostModelAdapter(
266
+ corpus(['{"disposition":"accepted"}', '{"disposition":"accepted"}']),
267
+ ),
268
+ storage: new MemoryStorage(),
269
+ });
270
+ try {
271
+ const result = await launch(
272
+ {
273
+ kind: "review",
274
+ task: "review the diff",
275
+ maxTurns: 120,
276
+ reviewers: [{ agent: "reviewer", maxTurns: 40 }, { agent: "reviewer" }],
277
+ },
278
+ { runtime, catalogue: createCatalogue(), host, waitMs: 20_000 },
279
+ );
280
+ const parent = await runtime.snapshot(RunDoc, result.view.runId);
281
+ const docs = [];
282
+ for (const runId of parent?.childRunIds ?? []) {
283
+ docs.push(await runtime.snapshot(RunDoc, runId));
284
+ }
285
+ assert.deepStrictEqual(
286
+ docs.map((doc) => doc?.maxTurns),
287
+ [40, 120],
288
+ );
289
+ } finally {
290
+ await runtime.close();
291
+ }
292
+ }, 20_000);
@@ -1,6 +1,6 @@
1
1
  import { assert, it } from "@effect/vitest";
2
2
  import type { SessionRuntime } from "../../runtime/session.ts";
3
- import type { Timers } from "../../runtime/timers.ts";
3
+ import type { Timers } from "../../runtime/clock.ts";
4
4
  import { fakeDocRuntime } from "../../../test-support/fake-doc-runtime.ts";
5
5
  import { textFor } from "./launch.ts";
6
6
  import { ATTENTION_BACKSTOP_MS, ATTENTION_RETRY_MS, waitForRun, waitForTask } from "./run-wait.ts";
@@ -76,6 +76,9 @@ const waitingView = (input: Partial<RunView> = {}): RunView => ({
76
76
  gates: [],
77
77
  requests: [],
78
78
  diagnostic: null,
79
+ execution: "wait",
80
+ maxTurns: null,
81
+ failure: null,
79
82
  ...input,
80
83
  });
81
84
 
@@ -1,6 +1,6 @@
1
1
  import type { Context } from "@earendil-works/chord/context";
2
2
  import type { SessionRuntime } from "../../runtime/session.ts";
3
- import type { Timers } from "../../runtime/timers.ts";
3
+ import type { Timers } from "../../runtime/clock.ts";
4
4
  import { observeSessionDoc, type Detach } from "../../runtime/observe.ts";
5
5
  import { errorFields } from "../../runtime/log.ts";
6
6
  import { GateIndexDoc, pendingGates } from "./gates.ts";