bb-plugin-goal 0.0.0-stage → 0.1.3

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.
@@ -0,0 +1,892 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { Context, DateTime, Duration, Effect, Layer, Result } from "effect";
3
+ import {
4
+ GOAL_HISTORY_MAX_LIMIT,
5
+ GoalGatewayError,
6
+ GoalInvalidBlockage,
7
+ GoalInvalidCompletion,
8
+ GoalInvalidCursor,
9
+ GoalInvalidHistoryQuery,
10
+ GoalInvalidObjective,
11
+ GoalThreadArchived,
12
+ GoalThreadNotFound,
13
+ type GoalCommand,
14
+ type GoalDto,
15
+ type GoalFailure,
16
+ type GoalError,
17
+ type GoalHistoryPage,
18
+ } from "./domain";
19
+ import { decodeGoalHistoryCursor } from "./history-cursor";
20
+ import {
21
+ GoalRepository,
22
+ type GoalContinuationRecord,
23
+ type RecoverGoalUsageLimitRecord,
24
+ } from "./repository";
25
+ import type { GoalSettledContinuationObservation } from "./progress";
26
+
27
+ export type GoalThreadStatus =
28
+ | "active"
29
+ | "error"
30
+ | "idle"
31
+ | "pending"
32
+ | "starting"
33
+ | "stopping";
34
+
35
+ export type GoalThreadRuntimeStatus =
36
+ | "host-reconnecting"
37
+ | "waiting-for-host"
38
+ | "active"
39
+ | "error"
40
+ | "idle"
41
+ | "pending"
42
+ | "provisioning"
43
+ | "starting"
44
+ | "stopping";
45
+
46
+ export interface GoalThreadSnapshot {
47
+ readonly status: GoalThreadStatus;
48
+ readonly runtimeStatus: GoalThreadRuntimeStatus;
49
+ readonly queuedMessageCount: number;
50
+ readonly activePromptMode: "plan" | null;
51
+ readonly pendingInteractionCount: number;
52
+ readonly archived?: boolean;
53
+ readonly deleted?: boolean;
54
+ }
55
+
56
+ export type GoalContinuationEligibilityReasonCode =
57
+ | "queued-user-message"
58
+ | "thread-archived"
59
+ | "thread-deleted"
60
+ | "thread-status"
61
+ | "thread-runtime-status"
62
+ | "plan-mode"
63
+ | "pending-interaction";
64
+
65
+ export interface GoalContinuationEligibilityReason {
66
+ readonly code: GoalContinuationEligibilityReasonCode;
67
+ readonly message: string;
68
+ }
69
+
70
+ export interface GoalContinuationEligibility {
71
+ readonly eligible: boolean;
72
+ readonly reason: GoalContinuationEligibilityReason | null;
73
+ }
74
+
75
+ export function goalContinuationEligibility(
76
+ snapshot: GoalThreadSnapshot,
77
+ ): GoalContinuationEligibility {
78
+ if (snapshot.deleted === true) {
79
+ return {
80
+ eligible: false,
81
+ reason: { code: "thread-deleted", message: "thread is deleted" },
82
+ };
83
+ }
84
+ if (snapshot.archived === true) {
85
+ return {
86
+ eligible: false,
87
+ reason: { code: "thread-archived", message: "thread is archived" },
88
+ };
89
+ }
90
+ if (snapshot.queuedMessageCount > 0) {
91
+ return {
92
+ eligible: false,
93
+ reason: {
94
+ code: "queued-user-message",
95
+ message: `${snapshot.queuedMessageCount} queued user message(s)`,
96
+ },
97
+ };
98
+ }
99
+ if (snapshot.status !== "idle") {
100
+ return {
101
+ eligible: false,
102
+ reason: {
103
+ code: "thread-status",
104
+ message: `thread status is ${snapshot.status}`,
105
+ },
106
+ };
107
+ }
108
+ if (snapshot.runtimeStatus !== "idle") {
109
+ return {
110
+ eligible: false,
111
+ reason: {
112
+ code: "thread-runtime-status",
113
+ message: `thread runtime status is ${snapshot.runtimeStatus}`,
114
+ },
115
+ };
116
+ }
117
+ if (snapshot.activePromptMode === "plan") {
118
+ return {
119
+ eligible: false,
120
+ reason: {
121
+ code: "plan-mode",
122
+ message: "Plan mode is active",
123
+ },
124
+ };
125
+ }
126
+ if (snapshot.pendingInteractionCount > 0) {
127
+ return {
128
+ eligible: false,
129
+ reason: {
130
+ code: "pending-interaction",
131
+ message: `${snapshot.pendingInteractionCount} pending interaction(s)`,
132
+ },
133
+ };
134
+ }
135
+ return { eligible: true, reason: null };
136
+ }
137
+
138
+ export interface GoalThreadGatewayAdapter {
139
+ readonly threadExists: (threadId: string) => Promise<boolean>;
140
+ readonly readThreadOwnership?: (
141
+ threadId: string,
142
+ ) => Promise<{
143
+ readonly exists: boolean;
144
+ readonly archived: boolean;
145
+ readonly deleted: boolean;
146
+ }>;
147
+ readonly readThread?: (
148
+ threadId: string,
149
+ signal?: AbortSignal,
150
+ ) => Promise<GoalThreadSnapshot>;
151
+ readonly sendContinuation?: (
152
+ threadId: string,
153
+ deliveryMarker: string,
154
+ signal?: AbortSignal,
155
+ ) => Promise<void>;
156
+ readonly reconcileContinuation?: (
157
+ threadId: string,
158
+ deliveryMarker: string,
159
+ signal?: AbortSignal,
160
+ ) => Promise<boolean>;
161
+ readonly observeContinuation?: (
162
+ threadId: string,
163
+ deliveryMarker: string,
164
+ signal?: AbortSignal,
165
+ ) => Promise<GoalSettledContinuationObservation | null>;
166
+ }
167
+
168
+ export function goalContinuationMarker(continuationId: string): string {
169
+ return `bb-goal-continuation:${continuationId}`;
170
+ }
171
+
172
+ function isRecoverableBlocker(externalAction: string): boolean {
173
+ return /^(?:continue(?: working| debugging)?|debug|investigate|keep trying|try again|none|no blocker|unknown|uncertain)$/i.test(
174
+ externalAction,
175
+ );
176
+ }
177
+
178
+ interface GoalThreadGatewayService {
179
+ readonly requireThread: (
180
+ threadId: string,
181
+ ) => Effect.Effect<void, GoalThreadNotFound | GoalGatewayError>;
182
+ readonly readThread: (
183
+ threadId: string,
184
+ signal?: AbortSignal,
185
+ ) => Effect.Effect<GoalThreadSnapshot, GoalGatewayError>;
186
+ readonly requireUnarchivedThread: (
187
+ threadId: string,
188
+ ) => Effect.Effect<
189
+ void,
190
+ GoalThreadArchived | GoalThreadNotFound | GoalGatewayError
191
+ >;
192
+ readonly sendContinuation: (
193
+ threadId: string,
194
+ deliveryMarker: string,
195
+ signal?: AbortSignal,
196
+ ) => Effect.Effect<void, GoalGatewayError>;
197
+ readonly reconcileContinuation: (
198
+ threadId: string,
199
+ deliveryMarker: string,
200
+ signal?: AbortSignal,
201
+ ) => Effect.Effect<boolean, GoalGatewayError>;
202
+ readonly observeContinuation: (
203
+ threadId: string,
204
+ deliveryMarker: string,
205
+ signal?: AbortSignal,
206
+ ) => Effect.Effect<GoalSettledContinuationObservation | null, GoalGatewayError>;
207
+ }
208
+
209
+ export class GoalThreadGateway extends Context.Service<
210
+ GoalThreadGateway,
211
+ GoalThreadGatewayService
212
+ >()("bb-plugin-goal/GoalThreadGateway") {}
213
+
214
+ export function makeGoalThreadGatewayLayer(
215
+ adapter: GoalThreadGatewayAdapter,
216
+ ): Layer.Layer<GoalThreadGateway> {
217
+ return Layer.succeed(
218
+ GoalThreadGateway,
219
+ GoalThreadGateway.of({
220
+ requireThread: Effect.fn("GoalThreadGateway.requireThread")(
221
+ function* (threadId: string) {
222
+ const exists = yield* Effect.tryPromise({
223
+ try: () => adapter.threadExists(threadId),
224
+ catch: (cause) =>
225
+ new GoalGatewayError({
226
+ message: `Could not inspect thread ${threadId}: ${cause instanceof Error ? cause.message : String(cause)}`,
227
+ }),
228
+ });
229
+ if (!exists) return yield* new GoalThreadNotFound({ threadId });
230
+ },
231
+ ),
232
+ readThread: Effect.fn("GoalThreadGateway.readThread")(
233
+ function* (threadId: string, signal?: AbortSignal) {
234
+ if (adapter.readThread === undefined) {
235
+ return yield* new GoalGatewayError({
236
+ message: "The BB thread gateway cannot read thread state.",
237
+ });
238
+ }
239
+ return yield* Effect.tryPromise({
240
+ try: () => adapter.readThread!(threadId, signal),
241
+ catch: (cause) =>
242
+ new GoalGatewayError({
243
+ message: `Could not read thread ${threadId}: ${cause instanceof Error ? cause.message : String(cause)}`,
244
+ }),
245
+ });
246
+ },
247
+ ),
248
+ requireUnarchivedThread: Effect.fn(
249
+ "GoalThreadGateway.requireUnarchivedThread",
250
+ )(function* (threadId: string) {
251
+ if (adapter.readThreadOwnership === undefined) {
252
+ const exists = yield* Effect.tryPromise({
253
+ try: () => adapter.threadExists(threadId),
254
+ catch: (cause) =>
255
+ new GoalGatewayError({
256
+ message: `Could not inspect thread ${threadId}: ${cause instanceof Error ? cause.message : String(cause)}`,
257
+ }),
258
+ });
259
+ if (!exists) return yield* new GoalThreadNotFound({ threadId });
260
+ return;
261
+ }
262
+ const thread = yield* Effect.tryPromise({
263
+ try: () => adapter.readThreadOwnership!(threadId),
264
+ catch: (cause) =>
265
+ new GoalGatewayError({
266
+ message: `Could not read thread ${threadId}: ${cause instanceof Error ? cause.message : String(cause)}`,
267
+ }),
268
+ });
269
+ if (!thread.exists || thread.deleted === true) {
270
+ return yield* new GoalThreadNotFound({ threadId });
271
+ }
272
+ if (thread.archived === true) {
273
+ return yield* new GoalThreadArchived({ threadId });
274
+ }
275
+ }),
276
+ sendContinuation: Effect.fn("GoalThreadGateway.sendContinuation")(
277
+ function* (
278
+ threadId: string,
279
+ deliveryMarker: string,
280
+ signal?: AbortSignal,
281
+ ) {
282
+ if (adapter.sendContinuation === undefined) {
283
+ return yield* new GoalGatewayError({
284
+ message: "The BB thread gateway cannot send a Continuation.",
285
+ });
286
+ }
287
+ return yield* Effect.tryPromise({
288
+ try: () =>
289
+ adapter.sendContinuation!(threadId, deliveryMarker, signal),
290
+ catch: (cause) =>
291
+ new GoalGatewayError({
292
+ message: `Could not send a Continuation for thread ${threadId}: ${cause instanceof Error ? cause.message : String(cause)}`,
293
+ }),
294
+ });
295
+ },
296
+ ),
297
+ reconcileContinuation: Effect.fn(
298
+ "GoalThreadGateway.reconcileContinuation",
299
+ )(
300
+ function* (
301
+ threadId: string,
302
+ deliveryMarker: string,
303
+ signal?: AbortSignal,
304
+ ) {
305
+ if (adapter.reconcileContinuation === undefined) return false;
306
+ return yield* Effect.tryPromise({
307
+ try: () =>
308
+ adapter.reconcileContinuation!(threadId, deliveryMarker, signal),
309
+ catch: (cause) =>
310
+ new GoalGatewayError({
311
+ message: `Could not reconcile Continuation for thread ${threadId}: ${cause instanceof Error ? cause.message : String(cause)}`,
312
+ }),
313
+ });
314
+ },
315
+ ),
316
+ observeContinuation: Effect.fn("GoalThreadGateway.observeContinuation")(
317
+ function* (
318
+ threadId: string,
319
+ deliveryMarker: string,
320
+ signal?: AbortSignal,
321
+ ) {
322
+ if (adapter.observeContinuation === undefined) return null;
323
+ return yield* Effect.tryPromise({
324
+ try: () =>
325
+ adapter.observeContinuation!(threadId, deliveryMarker, signal),
326
+ catch: (cause) =>
327
+ new GoalGatewayError({
328
+ message: `Could not observe Continuation for thread ${threadId}: ${cause instanceof Error ? cause.message : String(cause)}`,
329
+ }),
330
+ });
331
+ },
332
+ ),
333
+ }),
334
+ );
335
+ }
336
+
337
+ interface GoalIdGeneratorService {
338
+ readonly next: Effect.Effect<string>;
339
+ }
340
+
341
+ export class GoalIdGenerator extends Context.Service<
342
+ GoalIdGenerator,
343
+ GoalIdGeneratorService
344
+ >()("bb-plugin-goal/GoalIdGenerator") {}
345
+
346
+ export const liveGoalIdGeneratorLayer = Layer.succeed(
347
+ GoalIdGenerator,
348
+ GoalIdGenerator.of({
349
+ next: Effect.sync(() => `goal_${randomUUID()}`),
350
+ }),
351
+ );
352
+
353
+ interface GoalClockService {
354
+ readonly nowIso: Effect.Effect<string>;
355
+ }
356
+
357
+ export class GoalClock extends Context.Service<GoalClock, GoalClockService>()(
358
+ "bb-plugin-goal/GoalClock",
359
+ ) {}
360
+
361
+ export const liveGoalClockLayer = Layer.succeed(
362
+ GoalClock,
363
+ GoalClock.of({ nowIso: DateTime.now.pipe(Effect.map(DateTime.formatIso)) }),
364
+ );
365
+
366
+ export type GoalCoordinatorResult =
367
+ | { readonly goal: GoalDto | null }
368
+ | { readonly page: GoalHistoryPage };
369
+
370
+ export const GOAL_CONTINUATION_LEASE_SECONDS = 30;
371
+
372
+ export interface GoalContinuationRequest {
373
+ readonly threadId: string;
374
+ readonly opportunityKey: string;
375
+ }
376
+
377
+ export type GoalContinuationProcessResult =
378
+ | { readonly kind: "idle" }
379
+ | { readonly kind: "sent"; readonly continuation: GoalContinuationRecord }
380
+ | {
381
+ readonly kind: "released";
382
+ readonly continuation: GoalContinuationRecord;
383
+ /** The Goal the release changed (a delivery failure pauses it). */
384
+ readonly changedGoal?: GoalDto;
385
+ };
386
+
387
+ interface GoalCoordinatorService {
388
+ readonly execute: (
389
+ command: GoalCommand,
390
+ ) => Effect.Effect<GoalCoordinatorResult, GoalError>;
391
+ readonly archiveThread: (
392
+ threadId: string,
393
+ ) => Effect.Effect<GoalDto | null, GoalError>;
394
+ readonly deleteThread: (threadId: string) => Effect.Effect<void, GoalError>;
395
+ readonly ownedThreadIds: () => Effect.Effect<readonly string[], GoalError>;
396
+ }
397
+
398
+ export class GoalCoordinator extends Context.Service<
399
+ GoalCoordinator,
400
+ GoalCoordinatorService
401
+ >()("bb-plugin-goal/GoalCoordinator") {
402
+ static readonly layer = Layer.effect(
403
+ GoalCoordinator,
404
+ Effect.gen(function* () {
405
+ const repository = yield* GoalRepository;
406
+ const gateway = yield* GoalThreadGateway;
407
+ const ids = yield* GoalIdGenerator;
408
+ const clock = yield* GoalClock;
409
+
410
+ const execute = Effect.fn("GoalCoordinator.execute")(
411
+ function* (command: GoalCommand) {
412
+ if (command.type === "show") {
413
+ return { goal: yield* repository.find(command.goalId) };
414
+ }
415
+
416
+ if (
417
+ command.type === "start" ||
418
+ command.type === "resume" ||
419
+ command.type === "complete" ||
420
+ command.type === "block" ||
421
+ command.type === "failure"
422
+ ) {
423
+ yield* gateway.requireUnarchivedThread(command.threadId);
424
+ } else {
425
+ yield* gateway.requireThread(command.threadId);
426
+ }
427
+
428
+ if (command.type === "status") {
429
+ return { goal: yield* repository.current(command.threadId) };
430
+ }
431
+
432
+ if (command.type === "failure") {
433
+ return {
434
+ goal: yield* repository.recordFailure({
435
+ threadId: command.threadId,
436
+ failure: command.failure,
437
+ now: yield* clock.nowIso,
438
+ event: command.event,
439
+ observedEvents: command.observedEvents,
440
+ }),
441
+ };
442
+ }
443
+
444
+ if (command.type === "history") {
445
+ if (
446
+ !Number.isInteger(command.limit) ||
447
+ command.limit < 1 ||
448
+ command.limit > GOAL_HISTORY_MAX_LIMIT
449
+ ) {
450
+ return yield* new GoalInvalidHistoryQuery({
451
+ message: `Goal history limit must be between 1 and ${GOAL_HISTORY_MAX_LIMIT}.`,
452
+ });
453
+ }
454
+ const boundary =
455
+ command.cursor === null
456
+ ? null
457
+ : yield* decodeGoalHistoryCursor(command.cursor);
458
+ if (boundary !== null && boundary.threadId !== command.threadId) {
459
+ return yield* new GoalInvalidCursor({
460
+ message: "The Goal history cursor is invalid or expired.",
461
+ });
462
+ }
463
+ return {
464
+ page: yield* repository.history({
465
+ threadId: command.threadId,
466
+ limit: command.limit,
467
+ boundary,
468
+ }),
469
+ };
470
+ }
471
+
472
+ if (command.type === "start") {
473
+ const objective = command.objective.trim();
474
+ if (objective.length === 0) {
475
+ return yield* new GoalInvalidObjective({
476
+ message: "A Goal objective cannot be empty.",
477
+ });
478
+ }
479
+
480
+ const id = yield* ids.next;
481
+ const now = yield* clock.nowIso;
482
+ return {
483
+ goal: yield* repository.start({
484
+ id,
485
+ threadId: command.threadId,
486
+ objective,
487
+ now,
488
+ }),
489
+ };
490
+ }
491
+
492
+ if (command.type === "delete") {
493
+ return {
494
+ goal: yield* repository.delete({
495
+ threadId: command.threadId,
496
+ goalId: command.goalId,
497
+ expectedRevision: command.expectedRevision,
498
+ }),
499
+ };
500
+ }
501
+
502
+ if (command.type === "complete") {
503
+ const summary = command.summary.trim();
504
+ const verificationEvidence = command.verificationEvidence.trim();
505
+ if (summary.length === 0 || verificationEvidence.length === 0) {
506
+ return yield* new GoalInvalidCompletion({
507
+ message:
508
+ "Goal Completion requires a summary and verification evidence.",
509
+ });
510
+ }
511
+ const now = yield* clock.nowIso;
512
+ return {
513
+ goal: yield* repository.mutate({
514
+ command: { ...command, summary, verificationEvidence },
515
+ now,
516
+ }),
517
+ };
518
+ }
519
+
520
+ if (command.type === "block") {
521
+ const externalAction = command.externalAction.trim();
522
+ const evidence = command.evidence.trim();
523
+ if (
524
+ externalAction.length === 0 ||
525
+ evidence.length === 0 ||
526
+ isRecoverableBlocker(externalAction) ||
527
+ !Number.isInteger(command.repeatedTurns) ||
528
+ command.repeatedTurns < 1
529
+ ) {
530
+ return yield* new GoalInvalidBlockage({
531
+ message:
532
+ "Goal Blockage requires an external action, concrete evidence, and a positive consecutive-turn count.",
533
+ });
534
+ }
535
+ const now = yield* clock.nowIso;
536
+ return {
537
+ goal: yield* repository.mutate({
538
+ command: { ...command, externalAction, evidence },
539
+ now,
540
+ }),
541
+ };
542
+ }
543
+
544
+ const guardedCommand =
545
+ command.type === "edit"
546
+ ? {
547
+ ...command,
548
+ objective: command.objective.trim(),
549
+ }
550
+ : command;
551
+ if (
552
+ guardedCommand.type === "edit" &&
553
+ guardedCommand.objective.length === 0
554
+ ) {
555
+ return yield* new GoalInvalidObjective({
556
+ message: "A Goal objective cannot be empty.",
557
+ });
558
+ }
559
+
560
+ const now = yield* clock.nowIso;
561
+ return {
562
+ goal: yield* repository.mutate({ command: guardedCommand, now }),
563
+ };
564
+ },
565
+ );
566
+
567
+ const archiveThread = Effect.fn("GoalCoordinator.archiveThread")(
568
+ function* (threadId: string) {
569
+ return yield* repository.archiveThread({
570
+ threadId,
571
+ now: yield* clock.nowIso,
572
+ });
573
+ },
574
+ );
575
+
576
+ const deleteThread = Effect.fn("GoalCoordinator.deleteThread")(
577
+ (threadId: string) => repository.deleteThread(threadId),
578
+ );
579
+
580
+ const ownedThreadIds = Effect.fn("GoalCoordinator.ownedThreadIds")(() =>
581
+ repository.ownedThreadIds(),
582
+ );
583
+
584
+ return GoalCoordinator.of({
585
+ execute,
586
+ archiveThread,
587
+ deleteThread,
588
+ ownedThreadIds,
589
+ });
590
+ }),
591
+ );
592
+ }
593
+
594
+ interface GoalContinuationCoordinatorService {
595
+ readonly enqueueIdle: (
596
+ request: GoalContinuationRequest,
597
+ ) => Effect.Effect<GoalContinuationRecord | null, GoalError>;
598
+ readonly recover: () => Effect.Effect<void, GoalError>;
599
+ readonly assessSettled: (
600
+ signal?: AbortSignal,
601
+ ) => Effect.Effect<readonly GoalDto[], GoalError>;
602
+ readonly recoverUsageLimits: () => Effect.Effect<readonly GoalDto[], GoalError>;
603
+ readonly nextUsageLimitReset: () => Effect.Effect<string | null, GoalError>;
604
+ readonly process: (
605
+ signal?: AbortSignal,
606
+ ) => Effect.Effect<GoalContinuationProcessResult, GoalError>;
607
+ }
608
+
609
+ export class GoalContinuationCoordinator extends Context.Service<
610
+ GoalContinuationCoordinator,
611
+ GoalContinuationCoordinatorService
612
+ >()("bb-plugin-goal/GoalContinuationCoordinator") {
613
+ static readonly layer = Layer.effect(
614
+ GoalContinuationCoordinator,
615
+ Effect.gen(function* () {
616
+ const repository = yield* GoalRepository;
617
+ const gateway = yield* GoalThreadGateway;
618
+ const ids = yield* GoalIdGenerator;
619
+ const clock = yield* GoalClock;
620
+
621
+ const nowAndLease = Effect.gen(function* () {
622
+ const now = yield* clock.nowIso;
623
+ const leaseExpiresAt = DateTime.formatIso(
624
+ DateTime.addDuration(
625
+ DateTime.makeUnsafe(now),
626
+ Duration.seconds(GOAL_CONTINUATION_LEASE_SECONDS),
627
+ ),
628
+ );
629
+ return { now, leaseExpiresAt };
630
+ });
631
+
632
+ const enqueueIdle = Effect.fn("GoalContinuationCoordinator.enqueueIdle")(
633
+ function* (request: GoalContinuationRequest) {
634
+ const current = yield* repository.current(request.threadId);
635
+ if (current === null || current.state !== "active") return null;
636
+ const now = yield* clock.nowIso;
637
+ const id = yield* ids.next;
638
+ return yield* repository.enqueueContinuation({
639
+ id,
640
+ threadId: request.threadId,
641
+ goalId: current.id,
642
+ goalRevision: current.revision,
643
+ opportunityKey: request.opportunityKey,
644
+ deliveryMarker: goalContinuationMarker(id),
645
+ now,
646
+ });
647
+ },
648
+ );
649
+
650
+ const recover = Effect.fn("GoalContinuationCoordinator.recover")(
651
+ function* () {
652
+ const now = yield* clock.nowIso;
653
+ yield* repository.recoverContinuations(now);
654
+ const sending = yield* repository.sendingContinuations();
655
+ for (const continuation of sending) {
656
+ const deliveryMarker =
657
+ continuation.deliveryMarker ??
658
+ goalContinuationMarker(continuation.id);
659
+ const delivered = yield* gateway.reconcileContinuation(
660
+ continuation.threadId,
661
+ deliveryMarker,
662
+ );
663
+ if (delivered) {
664
+ yield* repository.resolveContinuation({
665
+ id: continuation.id,
666
+ now,
667
+ outcome: "sent",
668
+ reason: "Delivery marker reconciled after restart",
669
+ });
670
+ } else {
671
+ yield* repository.requeueContinuation({
672
+ id: continuation.id,
673
+ deliveryMarker,
674
+ now,
675
+ reason: "Delivery marker absent after restart",
676
+ });
677
+ }
678
+ }
679
+ },
680
+ );
681
+
682
+ const recoverUsageLimits = Effect.fn(
683
+ "GoalContinuationCoordinator.recoverUsageLimits",
684
+ )(function* () {
685
+ const now = yield* clock.nowIso;
686
+ const due = yield* repository.dueUsageLimits(now);
687
+ const recovered: GoalDto[] = [];
688
+ for (const goal of due) {
689
+ const thread = yield* gateway.readThread(goal.threadId);
690
+ if (!goalContinuationEligibility(thread).eligible) continue;
691
+ const record: RecoverGoalUsageLimitRecord = {
692
+ goalId: goal.id,
693
+ threadId: goal.threadId,
694
+ expectedRevision: goal.revision,
695
+ now,
696
+ };
697
+ const updated = yield* repository.recoverUsageLimit(record);
698
+ if (updated !== null) recovered.push(updated);
699
+ }
700
+ return recovered;
701
+ });
702
+
703
+ const nextUsageLimitReset = Effect.fn(
704
+ "GoalContinuationCoordinator.nextUsageLimitReset",
705
+ )(() => repository.nextUsageLimitReset());
706
+
707
+ const assessSettled = Effect.fn(
708
+ "GoalContinuationCoordinator.assessSettled",
709
+ )(function* (signal?: AbortSignal) {
710
+ const continuations = yield* repository.unassessedSentContinuations();
711
+ const changed: GoalDto[] = [];
712
+ for (const continuation of continuations) {
713
+ if (signal?.aborted === true) break;
714
+ const thread = yield* gateway.readThread(
715
+ continuation.threadId,
716
+ signal,
717
+ );
718
+ if (thread.deleted === true) {
719
+ yield* repository.deleteThread(continuation.threadId);
720
+ continue;
721
+ }
722
+ if (thread.archived === true) {
723
+ const goal = yield* repository.archiveThread({
724
+ threadId: continuation.threadId,
725
+ now: yield* clock.nowIso,
726
+ });
727
+ if (goal !== null) changed.push(goal);
728
+ continue;
729
+ }
730
+ const deliveryMarker =
731
+ continuation.deliveryMarker ??
732
+ goalContinuationMarker(continuation.id);
733
+ const observation = yield* gateway.observeContinuation(
734
+ continuation.threadId,
735
+ deliveryMarker,
736
+ signal,
737
+ );
738
+ if (observation === null) continue;
739
+ const goal = yield* repository.assessContinuation({
740
+ continuationId: continuation.id,
741
+ goalId: continuation.goalId,
742
+ goalRevision: continuation.goalRevision,
743
+ threadId: continuation.threadId,
744
+ observation,
745
+ now: yield* clock.nowIso,
746
+ });
747
+ if (goal?.noProgressLastContinuationId === continuation.id) {
748
+ changed.push(goal);
749
+ }
750
+ }
751
+ return changed;
752
+ });
753
+
754
+ const process = Effect.fn("GoalContinuationCoordinator.process")(
755
+ function* (signal?: AbortSignal) {
756
+ const lease = yield* nowAndLease;
757
+ const continuation = yield* repository.claimContinuation(lease);
758
+ if (continuation === null) return { kind: "idle" as const };
759
+
760
+ const release = (reason: string) =>
761
+ repository.resolveContinuation({
762
+ id: continuation.id,
763
+ now: lease.now,
764
+ outcome: "released",
765
+ reason,
766
+ });
767
+ const current = yield* repository.current(continuation.threadId);
768
+ const thread = yield* gateway.readThread(
769
+ continuation.threadId,
770
+ signal,
771
+ );
772
+ const firstEligibility = goalContinuationEligibility(thread);
773
+ if (signal?.aborted === true) {
774
+ yield* release("plugin cancellation");
775
+ return { kind: "released" as const, continuation };
776
+ }
777
+ if (current === null) {
778
+ yield* release("Goal no longer exists");
779
+ return { kind: "released" as const, continuation };
780
+ }
781
+ if (current.id !== continuation.goalId) {
782
+ yield* release("A different Goal is active");
783
+ return { kind: "released" as const, continuation };
784
+ }
785
+ if (current.revision !== continuation.goalRevision) {
786
+ yield* release("Goal revision changed");
787
+ return { kind: "released" as const, continuation };
788
+ }
789
+ if (current.state !== "active") {
790
+ yield* release(`Goal state is ${current.state}`);
791
+ return { kind: "released" as const, continuation };
792
+ }
793
+ if (!firstEligibility.eligible) {
794
+ yield* release(
795
+ `Suspended before claim delivery: ${firstEligibility.reason!.message}`,
796
+ );
797
+ return { kind: "released" as const, continuation };
798
+ }
799
+
800
+ const deliveryMarker =
801
+ continuation.deliveryMarker ??
802
+ goalContinuationMarker(continuation.id);
803
+ const markedSending = yield* repository.markContinuationSending({
804
+ id: continuation.id,
805
+ deliveryMarker,
806
+ now: lease.now,
807
+ leaseExpiresAt: lease.leaseExpiresAt,
808
+ });
809
+ if (!markedSending) return { kind: "released" as const, continuation };
810
+
811
+ const threadBeforeSend = yield* gateway.readThread(
812
+ continuation.threadId,
813
+ signal,
814
+ );
815
+ const currentBeforeSend = yield* repository.current(
816
+ continuation.threadId,
817
+ );
818
+ const lateEligibility = goalContinuationEligibility(threadBeforeSend);
819
+ if (signal !== undefined && Boolean(signal.aborted)) {
820
+ yield* release("plugin cancellation");
821
+ return { kind: "released" as const, continuation };
822
+ }
823
+ if (currentBeforeSend === null) {
824
+ yield* release("Goal no longer exists before send");
825
+ return { kind: "released" as const, continuation };
826
+ }
827
+ if (currentBeforeSend.id !== continuation.goalId) {
828
+ yield* release("A different Goal is active before send");
829
+ return { kind: "released" as const, continuation };
830
+ }
831
+ if (currentBeforeSend.revision !== continuation.goalRevision) {
832
+ yield* release("Goal revision changed before send");
833
+ return { kind: "released" as const, continuation };
834
+ }
835
+ if (currentBeforeSend.state !== "active") {
836
+ yield* release(`Goal state is ${currentBeforeSend.state} before send`);
837
+ return { kind: "released" as const, continuation };
838
+ }
839
+ if (!lateEligibility.eligible) {
840
+ yield* release(
841
+ `Suspended immediately before send: ${lateEligibility.reason!.message}`,
842
+ );
843
+ return { kind: "released" as const, continuation };
844
+ }
845
+
846
+ // A failed send is an Effect failure, not a thrown exception, so it
847
+ // must be captured as a Result: a JS try/catch never sees it.
848
+ const sent = yield* Effect.result(
849
+ gateway.sendContinuation(
850
+ continuation.threadId,
851
+ deliveryMarker,
852
+ signal,
853
+ ),
854
+ );
855
+ if (Result.isFailure(sent)) {
856
+ const message = sent.failure.message;
857
+ const paused = yield* repository.recordFailure({
858
+ threadId: continuation.threadId,
859
+ failure: {
860
+ kind: "ordinary",
861
+ source: "plugin",
862
+ reason: `Continuation delivery failed: ${message}`,
863
+ },
864
+ now: lease.now,
865
+ });
866
+ yield* release(message);
867
+ return paused === null
868
+ ? { kind: "released" as const, continuation }
869
+ : { kind: "released" as const, continuation, changedGoal: paused };
870
+ }
871
+
872
+ yield* repository.resolveContinuation({
873
+ id: continuation.id,
874
+ now: lease.now,
875
+ outcome: "sent",
876
+ reason: "Continuation sent",
877
+ });
878
+ return { kind: "sent" as const, continuation };
879
+ },
880
+ );
881
+
882
+ return GoalContinuationCoordinator.of({
883
+ enqueueIdle,
884
+ recover,
885
+ assessSettled,
886
+ recoverUsageLimits,
887
+ nextUsageLimitReset,
888
+ process,
889
+ });
890
+ }),
891
+ );
892
+ }