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,1735 @@
1
+ import type BetterSqlite3 from "better-sqlite3";
2
+ import { Context, Effect, Layer, Schema } from "effect";
3
+ import {
4
+ GoalAlreadyExists,
5
+ GoalDtoSchema,
6
+ GoalInvalidBlockage,
7
+ GoalInvalidTransition,
8
+ GoalNotFound,
9
+ GoalPersistenceError,
10
+ GoalRecordNotFound,
11
+ GoalStaleGuard,
12
+ type GoalBlockedCommand,
13
+ type GoalCompletionCommand,
14
+ type GoalDto,
15
+ type GoalFailure,
16
+ type GoalFailureEventIdentity,
17
+ type GoalGuardedAction,
18
+ type GoalHistoryPage,
19
+ type GoalMutationCommand,
20
+ type GoalNoProgressEvidence,
21
+ type GoalProgressSignalKind,
22
+ } from "./domain";
23
+ import {
24
+ encodeGoalHistoryCursor,
25
+ type GoalHistoryBoundary,
26
+ } from "./history-cursor";
27
+
28
+ export const GOAL_MIGRATIONS = [
29
+ `CREATE TABLE IF NOT EXISTS goals (
30
+ id TEXT PRIMARY KEY,
31
+ thread_id TEXT NOT NULL,
32
+ objective TEXT NOT NULL CHECK (length(objective) > 0),
33
+ state TEXT NOT NULL CHECK (state IN ('active', 'paused', 'waiting', 'completed', 'blocked', 'canceled')),
34
+ revision INTEGER NOT NULL CHECK (revision >= 1),
35
+ created_at TEXT NOT NULL,
36
+ updated_at TEXT NOT NULL,
37
+ finished_at TEXT
38
+ )`,
39
+ `CREATE UNIQUE INDEX IF NOT EXISTS goals_one_unfinished_per_thread
40
+ ON goals(thread_id)
41
+ WHERE finished_at IS NULL`,
42
+ `CREATE TABLE IF NOT EXISTS goal_history_order (
43
+ goal_id TEXT PRIMARY KEY,
44
+ thread_id TEXT NOT NULL,
45
+ sequence INTEGER NOT NULL CHECK (sequence >= 1),
46
+ UNIQUE(thread_id, sequence)
47
+ );
48
+ INSERT OR IGNORE INTO goal_history_order (goal_id, thread_id, sequence)
49
+ SELECT id, thread_id,
50
+ ROW_NUMBER() OVER (PARTITION BY thread_id ORDER BY created_at, rowid)
51
+ FROM goals;
52
+ CREATE TABLE IF NOT EXISTS goal_history_counters (
53
+ thread_id TEXT PRIMARY KEY,
54
+ last_sequence INTEGER NOT NULL CHECK (last_sequence >= 1)
55
+ );
56
+ INSERT INTO goal_history_counters (thread_id, last_sequence)
57
+ SELECT thread_id, MAX(sequence)
58
+ FROM goal_history_order
59
+ GROUP BY thread_id
60
+ ON CONFLICT(thread_id) DO UPDATE SET
61
+ last_sequence = MAX(last_sequence, excluded.last_sequence);
62
+ CREATE INDEX IF NOT EXISTS goals_history_by_thread
63
+ ON goal_history_order(thread_id, sequence DESC)`,
64
+ `ALTER TABLE goals ADD COLUMN completion_summary TEXT;
65
+ ALTER TABLE goals ADD COLUMN verification_evidence TEXT`,
66
+ `ALTER TABLE goals ADD COLUMN blockage_external_action TEXT;
67
+ ALTER TABLE goals ADD COLUMN blockage_evidence TEXT;
68
+ ALTER TABLE goals ADD COLUMN blockage_repeated_turns INTEGER`,
69
+ `CREATE TABLE IF NOT EXISTS goal_blockage_qualifications (
70
+ goal_id TEXT PRIMARY KEY,
71
+ thread_id TEXT NOT NULL,
72
+ goal_revision INTEGER NOT NULL CHECK (goal_revision >= 1),
73
+ blocker_key TEXT NOT NULL,
74
+ external_action TEXT NOT NULL,
75
+ evidence TEXT NOT NULL,
76
+ repeated_turns INTEGER NOT NULL CHECK (repeated_turns >= 1),
77
+ updated_at TEXT NOT NULL
78
+ )`,
79
+ `CREATE TABLE IF NOT EXISTS goal_continuations (
80
+ id TEXT PRIMARY KEY,
81
+ thread_id TEXT NOT NULL,
82
+ goal_id TEXT NOT NULL,
83
+ goal_revision INTEGER NOT NULL CHECK (goal_revision >= 1),
84
+ opportunity_key TEXT NOT NULL,
85
+ attempt INTEGER NOT NULL CHECK (attempt >= 0),
86
+ state TEXT NOT NULL CHECK (state IN ('pending', 'claimed', 'sending', 'resolved')),
87
+ outcome TEXT CHECK (outcome IS NULL OR outcome IN ('sent', 'released', 'expired')),
88
+ lease_expires_at TEXT,
89
+ outcome_reason TEXT,
90
+ created_at TEXT NOT NULL,
91
+ updated_at TEXT NOT NULL,
92
+ UNIQUE(thread_id, opportunity_key)
93
+ );
94
+ CREATE INDEX IF NOT EXISTS goal_continuations_pending
95
+ ON goal_continuations(state, lease_expires_at, created_at)`,
96
+ `ALTER TABLE goal_continuations ADD COLUMN delivery_marker TEXT`,
97
+ `ALTER TABLE goals ADD COLUMN pause_reason_code TEXT;
98
+ ALTER TABLE goals ADD COLUMN pause_reason TEXT;
99
+ ALTER TABLE goals ADD COLUMN usage_limit_kind TEXT;
100
+ ALTER TABLE goals ADD COLUMN usage_reset_at TEXT`,
101
+ `CREATE TABLE IF NOT EXISTS goal_failure_events (
102
+ thread_id TEXT NOT NULL,
103
+ event_id TEXT NOT NULL,
104
+ event_seq INTEGER CHECK (event_seq IS NULL OR event_seq >= 0),
105
+ event_created_at INTEGER NOT NULL,
106
+ observed_at TEXT NOT NULL,
107
+ PRIMARY KEY (thread_id, event_id)
108
+ );
109
+ CREATE INDEX IF NOT EXISTS goal_failure_events_by_sequence
110
+ ON goal_failure_events(thread_id, event_seq DESC)`,
111
+ `ALTER TABLE goal_failure_events ADD COLUMN turn_id TEXT`,
112
+ `ALTER TABLE goals ADD COLUMN no_progress_consecutive_count INTEGER NOT NULL DEFAULT 0;
113
+ ALTER TABLE goals ADD COLUMN no_progress_last_continuation_id TEXT;
114
+ ALTER TABLE goals ADD COLUMN no_progress_assistant_result_fingerprint TEXT;
115
+ ALTER TABLE goals ADD COLUMN no_progress_evidence_json TEXT;
116
+ ALTER TABLE goal_continuations ADD COLUMN progress_assessed_at TEXT;
117
+ ALTER TABLE goal_continuations ADD COLUMN progress_evidence_json TEXT;
118
+ CREATE INDEX IF NOT EXISTS goal_continuations_unassessed_sent
119
+ ON goal_continuations(outcome, progress_assessed_at, created_at)`,
120
+ ] as const;
121
+
122
+ export function migrateGoalDatabase(database: BetterSqlite3.Database): void {
123
+ const migrate = database.transaction(() => {
124
+ for (const statement of GOAL_MIGRATIONS) {
125
+ database.exec(statement);
126
+ }
127
+ });
128
+ migrate();
129
+ }
130
+
131
+ interface StartGoalRecord {
132
+ readonly id: string;
133
+ readonly threadId: string;
134
+ readonly objective: string;
135
+ readonly now: string;
136
+ }
137
+
138
+ export interface MutateGoalRecord {
139
+ readonly command:
140
+ | GoalMutationCommand
141
+ | GoalCompletionCommand
142
+ | GoalBlockedCommand;
143
+ readonly now: string;
144
+ }
145
+
146
+ export interface RecordGoalFailure {
147
+ readonly threadId: string;
148
+ readonly failure: GoalFailure;
149
+ readonly now: string;
150
+ readonly event?: GoalFailureEventIdentity;
151
+ readonly observedEvents?: readonly GoalFailureEventIdentity[];
152
+ }
153
+
154
+ export interface RecoverGoalUsageLimitRecord {
155
+ readonly goalId: string;
156
+ readonly threadId: string;
157
+ readonly expectedRevision: number;
158
+ readonly now: string;
159
+ }
160
+
161
+ export interface HistoryGoalRecords {
162
+ readonly threadId: string;
163
+ readonly limit: number;
164
+ readonly boundary: GoalHistoryBoundary | null;
165
+ }
166
+
167
+ export interface DeleteGoalRecord {
168
+ readonly threadId: string;
169
+ readonly goalId: string;
170
+ readonly expectedRevision: number;
171
+ }
172
+
173
+ export interface ArchiveGoalThreadRecord {
174
+ readonly threadId: string;
175
+ readonly now: string;
176
+ }
177
+
178
+ type GoalMutationError =
179
+ | GoalNotFound
180
+ | GoalStaleGuard
181
+ | GoalInvalidTransition
182
+ | GoalInvalidBlockage
183
+ | GoalPersistenceError;
184
+
185
+ type GoalDeleteError = GoalNotFound | GoalStaleGuard | GoalPersistenceError;
186
+
187
+ export type GoalContinuationState =
188
+ | "pending"
189
+ | "claimed"
190
+ | "sending"
191
+ | "resolved";
192
+ export type GoalContinuationOutcome = "sent" | "released" | "expired";
193
+
194
+ export interface GoalContinuationRecord {
195
+ readonly id: string;
196
+ readonly threadId: string;
197
+ readonly goalId: string;
198
+ readonly goalRevision: number;
199
+ readonly opportunityKey: string;
200
+ readonly deliveryMarker: string | null;
201
+ readonly attempt: number;
202
+ readonly state: GoalContinuationState;
203
+ readonly outcome: GoalContinuationOutcome | null;
204
+ readonly leaseExpiresAt: string | null;
205
+ readonly outcomeReason: string | null;
206
+ readonly createdAt: string;
207
+ readonly updatedAt: string;
208
+ readonly progressAssessedAt: string | null;
209
+ }
210
+
211
+ export interface EnqueueGoalContinuationRecord {
212
+ readonly id: string;
213
+ readonly threadId: string;
214
+ readonly goalId: string;
215
+ readonly goalRevision: number;
216
+ readonly opportunityKey: string;
217
+ readonly deliveryMarker: string;
218
+ readonly now: string;
219
+ }
220
+
221
+ export interface ClaimGoalContinuationRecord {
222
+ readonly now: string;
223
+ readonly leaseExpiresAt: string;
224
+ }
225
+
226
+ export interface MarkGoalContinuationSendingRecord {
227
+ readonly id: string;
228
+ readonly deliveryMarker: string;
229
+ readonly now: string;
230
+ readonly leaseExpiresAt: string;
231
+ }
232
+
233
+ export interface RequeueGoalContinuationRecord {
234
+ readonly id: string;
235
+ readonly deliveryMarker: string;
236
+ readonly now: string;
237
+ readonly reason: string;
238
+ }
239
+
240
+ export interface ResolveGoalContinuationRecord {
241
+ readonly id: string;
242
+ readonly now: string;
243
+ readonly outcome: GoalContinuationOutcome;
244
+ readonly reason: string;
245
+ }
246
+
247
+ export interface AssessGoalContinuationRecord {
248
+ readonly continuationId: string;
249
+ readonly goalId: string;
250
+ readonly goalRevision: number;
251
+ readonly threadId: string;
252
+ readonly observation: Omit<
253
+ GoalNoProgressEvidence,
254
+ | "continuationId"
255
+ | "signals"
256
+ | "previousAssistantResultFingerprint"
257
+ | "assessment"
258
+ | "observedAt"
259
+ > & {
260
+ readonly signals: readonly Exclude<
261
+ GoalProgressSignalKind,
262
+ "changed-assistant-result"
263
+ >[];
264
+ };
265
+ readonly now: string;
266
+ }
267
+
268
+ interface GoalRepositoryService {
269
+ readonly start: (
270
+ record: StartGoalRecord,
271
+ ) => Effect.Effect<GoalDto, GoalAlreadyExists | GoalPersistenceError>;
272
+ readonly current: (
273
+ threadId: string,
274
+ ) => Effect.Effect<GoalDto | null, GoalPersistenceError>;
275
+ readonly history: (
276
+ record: HistoryGoalRecords,
277
+ ) => Effect.Effect<GoalHistoryPage, GoalPersistenceError>;
278
+ readonly find: (
279
+ goalId: string,
280
+ ) => Effect.Effect<GoalDto, GoalRecordNotFound | GoalPersistenceError>;
281
+ readonly mutate: (
282
+ record: MutateGoalRecord,
283
+ ) => Effect.Effect<GoalDto, GoalMutationError>;
284
+ readonly recordFailure: (
285
+ record: RecordGoalFailure,
286
+ ) => Effect.Effect<GoalDto | null, GoalPersistenceError>;
287
+ readonly dueUsageLimits: (
288
+ now: string,
289
+ ) => Effect.Effect<readonly GoalDto[], GoalPersistenceError>;
290
+ readonly recoverUsageLimit: (
291
+ record: RecoverGoalUsageLimitRecord,
292
+ ) => Effect.Effect<GoalDto | null, GoalPersistenceError>;
293
+ readonly nextUsageLimitReset: () => Effect.Effect<string | null, GoalPersistenceError>;
294
+ readonly delete: (
295
+ record: DeleteGoalRecord,
296
+ ) => Effect.Effect<GoalDto, GoalDeleteError>;
297
+ readonly archiveThread: (
298
+ record: ArchiveGoalThreadRecord,
299
+ ) => Effect.Effect<GoalDto | null, GoalPersistenceError>;
300
+ readonly deleteThread: (
301
+ threadId: string,
302
+ ) => Effect.Effect<void, GoalPersistenceError>;
303
+ readonly ownedThreadIds: () => Effect.Effect<
304
+ readonly string[],
305
+ GoalPersistenceError
306
+ >;
307
+ readonly enqueueContinuation: (
308
+ record: EnqueueGoalContinuationRecord,
309
+ ) => Effect.Effect<GoalContinuationRecord | null, GoalPersistenceError>;
310
+ readonly recoverContinuations: (
311
+ now: string,
312
+ ) => Effect.Effect<void, GoalPersistenceError>;
313
+ readonly sendingContinuations: () => Effect.Effect<
314
+ readonly GoalContinuationRecord[],
315
+ GoalPersistenceError
316
+ >;
317
+ readonly requeueContinuation: (
318
+ record: RequeueGoalContinuationRecord,
319
+ ) => Effect.Effect<boolean, GoalPersistenceError>;
320
+ readonly claimContinuation: (
321
+ record: ClaimGoalContinuationRecord,
322
+ ) => Effect.Effect<GoalContinuationRecord | null, GoalPersistenceError>;
323
+ readonly markContinuationSending: (
324
+ record: MarkGoalContinuationSendingRecord,
325
+ ) => Effect.Effect<boolean, GoalPersistenceError>;
326
+ readonly resolveContinuation: (
327
+ record: ResolveGoalContinuationRecord,
328
+ ) => Effect.Effect<boolean, GoalPersistenceError>;
329
+ readonly unassessedSentContinuations: () => Effect.Effect<
330
+ readonly GoalContinuationRecord[],
331
+ GoalPersistenceError
332
+ >;
333
+ readonly assessContinuation: (
334
+ record: AssessGoalContinuationRecord,
335
+ ) => Effect.Effect<GoalDto | null, GoalPersistenceError>;
336
+ }
337
+
338
+ export class GoalRepository extends Context.Service<
339
+ GoalRepository,
340
+ GoalRepositoryService
341
+ >()("bb-plugin-goal/GoalRepository") {}
342
+
343
+ const decodeGoal = Schema.decodeUnknownSync(GoalDtoSchema);
344
+
345
+ type GoalRow = {
346
+ readonly id: string;
347
+ readonly threadId: string;
348
+ readonly objective: string;
349
+ readonly state: string;
350
+ readonly revision: number;
351
+ readonly createdAt: string;
352
+ readonly updatedAt: string;
353
+ readonly finishedAt: string | null;
354
+ readonly completionSummary: string | null;
355
+ readonly verificationEvidence: string | null;
356
+ readonly blockageExternalAction: string | null;
357
+ readonly blockageEvidence: string | null;
358
+ readonly blockageRepeatedTurns: number | null;
359
+ readonly pauseReasonCode: string | null;
360
+ readonly pauseReason: string | null;
361
+ readonly usageLimitKind: string | null;
362
+ readonly usageResetAt: string | null;
363
+ readonly noProgressConsecutiveCount: number;
364
+ readonly noProgressLastContinuationId: string | null;
365
+ readonly noProgressAssistantResultFingerprint: string | null;
366
+ readonly noProgressEvidence: string | null;
367
+ };
368
+
369
+ type GoalHistoryRow = GoalRow & { readonly historySequence: number };
370
+
371
+ type GoalBlockageQualificationRow = {
372
+ readonly goalRevision: number;
373
+ readonly blockerKey: string;
374
+ readonly repeatedTurns: number;
375
+ };
376
+
377
+ type GoalContinuationRow = {
378
+ readonly id: string;
379
+ readonly threadId: string;
380
+ readonly goalId: string;
381
+ readonly goalRevision: number;
382
+ readonly opportunityKey: string;
383
+ readonly deliveryMarker: string | null;
384
+ readonly attempt: number;
385
+ readonly state: GoalContinuationState;
386
+ readonly outcome: GoalContinuationOutcome | null;
387
+ readonly leaseExpiresAt: string | null;
388
+ readonly outcomeReason: string | null;
389
+ readonly createdAt: string;
390
+ readonly updatedAt: string;
391
+ readonly progressAssessedAt: string | null;
392
+ };
393
+
394
+ function decodeContinuation(row: GoalContinuationRow): GoalContinuationRecord {
395
+ return row;
396
+ }
397
+
398
+ function decodeGoalRow(row: GoalRow): GoalDto {
399
+ return decodeGoal({
400
+ ...row,
401
+ noProgressEvidence:
402
+ row.noProgressEvidence === null
403
+ ? null
404
+ : JSON.parse(row.noProgressEvidence),
405
+ }) as GoalDto;
406
+ }
407
+
408
+ function messageFromCause(cause: unknown): string {
409
+ return cause instanceof Error ? cause.message : String(cause);
410
+ }
411
+
412
+ function normalizeBlocker(externalAction: string): string {
413
+ return externalAction.trim().replace(/\s+/g, " ").toLocaleLowerCase();
414
+ }
415
+
416
+ function permitsMutation(goal: GoalDto, action: GoalGuardedAction): boolean {
417
+ switch (action) {
418
+ case "edit":
419
+ case "cancel":
420
+ return goal.finishedAt === null;
421
+ case "complete":
422
+ case "block":
423
+ return goal.state === "active";
424
+ case "pause":
425
+ return goal.state === "active" || goal.state === "waiting";
426
+ case "resume":
427
+ return goal.state === "paused" || goal.state === "waiting";
428
+ }
429
+ }
430
+
431
+ function mutationErrorFromCause(cause: unknown): GoalMutationError {
432
+ if (
433
+ cause instanceof GoalNotFound ||
434
+ cause instanceof GoalStaleGuard ||
435
+ cause instanceof GoalInvalidTransition ||
436
+ cause instanceof GoalInvalidBlockage
437
+ ) {
438
+ return cause;
439
+ }
440
+ return new GoalPersistenceError({
441
+ message: `Could not mutate Goal state: ${messageFromCause(cause)}`,
442
+ });
443
+ }
444
+
445
+ function deleteErrorFromCause(cause: unknown): GoalDeleteError {
446
+ if (cause instanceof GoalNotFound || cause instanceof GoalStaleGuard) {
447
+ return cause;
448
+ }
449
+ return new GoalPersistenceError({
450
+ message: `Could not delete Goal: ${messageFromCause(cause)}`,
451
+ });
452
+ }
453
+
454
+ const goalColumns = `SELECT
455
+ id,
456
+ thread_id AS threadId,
457
+ objective,
458
+ state,
459
+ revision,
460
+ created_at AS createdAt,
461
+ updated_at AS updatedAt,
462
+ finished_at AS finishedAt,
463
+ completion_summary AS completionSummary,
464
+ verification_evidence AS verificationEvidence,
465
+ blockage_external_action AS blockageExternalAction,
466
+ blockage_evidence AS blockageEvidence,
467
+ blockage_repeated_turns AS blockageRepeatedTurns,
468
+ pause_reason_code AS pauseReasonCode,
469
+ pause_reason AS pauseReason,
470
+ usage_limit_kind AS usageLimitKind,
471
+ usage_reset_at AS usageResetAt,
472
+ no_progress_consecutive_count AS noProgressConsecutiveCount,
473
+ no_progress_last_continuation_id AS noProgressLastContinuationId,
474
+ no_progress_assistant_result_fingerprint AS noProgressAssistantResultFingerprint,
475
+ no_progress_evidence_json AS noProgressEvidence
476
+ FROM goals`;
477
+
478
+ export interface CurrentGoalSnapshotReader {
479
+ readonly current: (threadId: string) => GoalDto | null;
480
+ }
481
+
482
+ export function makeCurrentGoalSnapshotReader(
483
+ database: BetterSqlite3.Database,
484
+ ): CurrentGoalSnapshotReader {
485
+ const selectCurrent = database.prepare<[string], GoalRow>(`${goalColumns}
486
+ WHERE thread_id = ? AND finished_at IS NULL
487
+ ORDER BY created_at DESC
488
+ LIMIT 1`);
489
+ return {
490
+ current(threadId) {
491
+ const row = selectCurrent.get(threadId);
492
+ return row === undefined ? null : decodeGoalRow(row);
493
+ },
494
+ };
495
+ }
496
+
497
+ export function makeGoalRepositoryLayer(
498
+ database: BetterSqlite3.Database,
499
+ ): Layer.Layer<GoalRepository> {
500
+ return Layer.effect(
501
+ GoalRepository,
502
+ Effect.sync(() => {
503
+ const selectCurrent = database.prepare<[string], GoalRow>(`${goalColumns}
504
+ WHERE thread_id = ? AND finished_at IS NULL
505
+ ORDER BY created_at DESC
506
+ LIMIT 1`);
507
+ const historyColumns = `SELECT
508
+ goals.id,
509
+ goals.thread_id AS threadId,
510
+ goals.objective,
511
+ goals.state,
512
+ goals.revision,
513
+ goals.created_at AS createdAt,
514
+ goals.updated_at AS updatedAt,
515
+ goals.finished_at AS finishedAt,
516
+ goals.completion_summary AS completionSummary,
517
+ goals.verification_evidence AS verificationEvidence,
518
+ goals.blockage_external_action AS blockageExternalAction,
519
+ goals.blockage_evidence AS blockageEvidence,
520
+ goals.blockage_repeated_turns AS blockageRepeatedTurns,
521
+ goals.pause_reason_code AS pauseReasonCode,
522
+ goals.pause_reason AS pauseReason,
523
+ goals.usage_limit_kind AS usageLimitKind,
524
+ goals.usage_reset_at AS usageResetAt,
525
+ goals.no_progress_consecutive_count AS noProgressConsecutiveCount,
526
+ goals.no_progress_last_continuation_id AS noProgressLastContinuationId,
527
+ goals.no_progress_assistant_result_fingerprint AS noProgressAssistantResultFingerprint,
528
+ goals.no_progress_evidence_json AS noProgressEvidence,
529
+ goal_history_order.sequence AS historySequence
530
+ FROM goals
531
+ INNER JOIN goal_history_order
532
+ ON goal_history_order.goal_id = goals.id`;
533
+ const selectByThreadAndId = database.prepare<[string, string], GoalRow>(
534
+ `${goalColumns} WHERE id = ? AND thread_id = ? LIMIT 1`,
535
+ );
536
+ const selectById = database.prepare<[string], GoalRow>(
537
+ `${goalColumns} WHERE id = ? LIMIT 1`,
538
+ );
539
+ const selectHistoryFirst = database.prepare<
540
+ [string, number],
541
+ GoalHistoryRow
542
+ >(`${historyColumns}
543
+ WHERE goal_history_order.thread_id = ?
544
+ ORDER BY goal_history_order.sequence DESC
545
+ LIMIT ?`);
546
+ const selectHistoryAfter = database.prepare<
547
+ [string, number, number],
548
+ GoalHistoryRow
549
+ >(`${historyColumns}
550
+ WHERE goal_history_order.thread_id = ?
551
+ AND goal_history_order.sequence < ?
552
+ ORDER BY goal_history_order.sequence DESC
553
+ LIMIT ?`);
554
+
555
+ const nextHistorySequence = database.prepare<
556
+ [string],
557
+ { readonly sequence: number }
558
+ >(`INSERT INTO goal_history_counters (thread_id, last_sequence)
559
+ VALUES (?, 1)
560
+ ON CONFLICT(thread_id) DO UPDATE SET
561
+ last_sequence = last_sequence + 1
562
+ RETURNING last_sequence AS sequence`);
563
+ const insertHistoryOrder = database.prepare(
564
+ `INSERT INTO goal_history_order (goal_id, thread_id, sequence)
565
+ VALUES (?, ?, ?)`,
566
+ );
567
+ const insert = database.prepare(
568
+ `INSERT INTO goals (
569
+ id, thread_id, objective, state, revision,
570
+ created_at, updated_at, finished_at
571
+ ) VALUES (?, ?, ?, 'active', 1, ?, ?, NULL)`,
572
+ );
573
+ const edit = database.prepare(
574
+ `UPDATE goals
575
+ SET objective = ?, revision = revision + 1, updated_at = ?,
576
+ no_progress_consecutive_count = 0,
577
+ no_progress_last_continuation_id = NULL,
578
+ no_progress_assistant_result_fingerprint = NULL,
579
+ no_progress_evidence_json = NULL
580
+ WHERE id = ? AND thread_id = ? AND revision = ? AND finished_at IS NULL`,
581
+ );
582
+ const pause = database.prepare(
583
+ `UPDATE goals
584
+ SET state = 'paused', revision = revision + 1, updated_at = ?,
585
+ pause_reason_code = 'manual', pause_reason = 'Paused by user',
586
+ usage_limit_kind = NULL, usage_reset_at = NULL
587
+ WHERE id = ? AND thread_id = ? AND revision = ?
588
+ AND state IN ('active', 'waiting') AND finished_at IS NULL`,
589
+ );
590
+ const resume = database.prepare(
591
+ `UPDATE goals
592
+ SET state = 'active', revision = revision + 1, updated_at = ?,
593
+ pause_reason_code = NULL, pause_reason = NULL,
594
+ usage_limit_kind = NULL, usage_reset_at = NULL,
595
+ no_progress_consecutive_count = 0,
596
+ no_progress_last_continuation_id = NULL,
597
+ no_progress_assistant_result_fingerprint = NULL,
598
+ no_progress_evidence_json = NULL
599
+ WHERE id = ? AND thread_id = ? AND revision = ? AND state IN ('paused', 'waiting') AND finished_at IS NULL`,
600
+ );
601
+ const recordFailure = database.prepare(
602
+ `UPDATE goals
603
+ SET state = ?, revision = revision + 1, updated_at = ?,
604
+ pause_reason_code = ?, pause_reason = ?, usage_limit_kind = ?,
605
+ usage_reset_at = ?
606
+ WHERE id = ? AND thread_id = ?
607
+ AND (
608
+ state = 'active' OR
609
+ (state IN ('paused', 'waiting')
610
+ AND pause_reason_code IN ('failure', 'usage-limit'))
611
+ )
612
+ AND finished_at IS NULL`,
613
+ );
614
+ const insertFailureEvent = database.prepare(
615
+ `INSERT OR IGNORE INTO goal_failure_events (
616
+ thread_id, event_id, event_seq, event_created_at, turn_id, observed_at
617
+ ) VALUES (?, ?, ?, ?, ?, ?)`,
618
+ );
619
+ const selectMaxFailureEventSeq = database.prepare<
620
+ [string],
621
+ { readonly eventSeq: number | null }
622
+ >(
623
+ `SELECT MAX(event_seq) AS eventSeq FROM goal_failure_events
624
+ WHERE thread_id = ?`,
625
+ );
626
+ const selectFailureEventForTurn = database.prepare<
627
+ [string, string],
628
+ { readonly eventId: string }
629
+ >(
630
+ `SELECT event_id AS eventId FROM goal_failure_events
631
+ WHERE thread_id = ? AND turn_id = ?
632
+ LIMIT 1`,
633
+ );
634
+ const recoverUsageLimit = database.prepare(
635
+ `UPDATE goals
636
+ SET state = 'active', revision = revision + 1, updated_at = ?,
637
+ pause_reason_code = NULL, pause_reason = NULL,
638
+ usage_limit_kind = NULL, usage_reset_at = NULL
639
+ WHERE id = ? AND thread_id = ? AND revision = ? AND state = 'waiting'
640
+ AND pause_reason_code = 'usage-limit'
641
+ AND usage_reset_at IS NOT NULL AND usage_reset_at <= ?
642
+ AND finished_at IS NULL`,
643
+ );
644
+ const selectDueUsageLimits = database.prepare<[string], GoalRow>(
645
+ `${goalColumns} WHERE state = 'waiting'
646
+ AND pause_reason_code = 'usage-limit'
647
+ AND usage_reset_at IS NOT NULL AND usage_reset_at <= ?
648
+ AND finished_at IS NULL
649
+ ORDER BY usage_reset_at, id`,
650
+ );
651
+ const selectNextUsageLimitReset = database.prepare<[], { readonly usageResetAt: string }>(
652
+ `SELECT MIN(usage_reset_at) AS usageResetAt FROM goals
653
+ WHERE state = 'waiting' AND pause_reason_code = 'usage-limit'
654
+ AND usage_reset_at IS NOT NULL AND finished_at IS NULL`,
655
+ );
656
+ const cancel = database.prepare(
657
+ `UPDATE goals
658
+ SET state = 'canceled', revision = revision + 1, updated_at = ?, finished_at = ?
659
+ WHERE id = ? AND thread_id = ? AND revision = ? AND finished_at IS NULL`,
660
+ );
661
+ const complete = database.prepare(
662
+ `UPDATE goals
663
+ SET state = 'completed', revision = revision + 1,
664
+ updated_at = ?, finished_at = ?, completion_summary = ?,
665
+ verification_evidence = ?
666
+ WHERE id = ? AND thread_id = ? AND revision = ?
667
+ AND state = 'active' AND finished_at IS NULL`,
668
+ );
669
+ const block = database.prepare(
670
+ `UPDATE goals
671
+ SET state = 'blocked', revision = revision + 1,
672
+ updated_at = ?, finished_at = ?, blockage_external_action = ?,
673
+ blockage_evidence = ?, blockage_repeated_turns = ?
674
+ WHERE id = ? AND thread_id = ? AND revision = ?
675
+ AND state = 'active' AND finished_at IS NULL`,
676
+ );
677
+ const selectBlockageQualification = database.prepare<
678
+ [string, string],
679
+ GoalBlockageQualificationRow
680
+ >(`SELECT goal_revision AS goalRevision,
681
+ blocker_key AS blockerKey, repeated_turns AS repeatedTurns
682
+ FROM goal_blockage_qualifications
683
+ WHERE goal_id = ? AND thread_id = ?`);
684
+ const saveBlockageQualification = database.prepare(
685
+ `INSERT INTO goal_blockage_qualifications (
686
+ goal_id, thread_id, goal_revision, blocker_key, external_action,
687
+ evidence, repeated_turns, updated_at
688
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
689
+ ON CONFLICT(goal_id) DO UPDATE SET
690
+ goal_revision = excluded.goal_revision,
691
+ blocker_key = excluded.blocker_key,
692
+ external_action = excluded.external_action,
693
+ evidence = excluded.evidence,
694
+ repeated_turns = excluded.repeated_turns,
695
+ updated_at = excluded.updated_at`,
696
+ );
697
+ const deleteBlockageQualification = database.prepare(
698
+ `DELETE FROM goal_blockage_qualifications WHERE goal_id = ?`,
699
+ );
700
+ const deleteByGuard = database.prepare(
701
+ `DELETE FROM goals
702
+ WHERE id = ? AND thread_id = ? AND revision = ?`,
703
+ );
704
+ const deleteHistoryOrder = database.prepare(
705
+ `DELETE FROM goal_history_order WHERE goal_id = ?`,
706
+ );
707
+ const archiveUnfinishedGoal = database.prepare(
708
+ `UPDATE goals
709
+ SET state = 'paused', revision = revision + 1, updated_at = ?,
710
+ pause_reason_code = 'archived',
711
+ pause_reason = 'Paused because the owning thread was archived',
712
+ usage_limit_kind = NULL, usage_reset_at = NULL
713
+ WHERE thread_id = ? AND state IN ('active', 'waiting')
714
+ AND finished_at IS NULL`,
715
+ );
716
+ const releaseThreadContinuations = database.prepare(
717
+ `UPDATE goal_continuations
718
+ SET state = 'resolved', outcome = 'released', lease_expires_at = NULL,
719
+ outcome_reason = 'Owning thread archived', updated_at = ?
720
+ WHERE thread_id = ? AND state IN ('pending', 'claimed', 'sending')`,
721
+ );
722
+ const neutralizeThreadAssessments = database.prepare(
723
+ `UPDATE goal_continuations
724
+ SET progress_assessed_at = ?,
725
+ progress_evidence_json = '{"assessment":"ignored","reason":"Owning thread archived"}',
726
+ updated_at = ?
727
+ WHERE thread_id = ? AND state = 'resolved' AND outcome = 'sent'
728
+ AND progress_assessed_at IS NULL`,
729
+ );
730
+ const deleteThreadGoals = database.prepare(
731
+ `DELETE FROM goals WHERE thread_id = ?`,
732
+ );
733
+ const deleteThreadHistoryOrder = database.prepare(
734
+ `DELETE FROM goal_history_order WHERE thread_id = ?`,
735
+ );
736
+ const deleteThreadHistoryCounter = database.prepare(
737
+ `DELETE FROM goal_history_counters WHERE thread_id = ?`,
738
+ );
739
+ const deleteThreadBlockageQualifications = database.prepare(
740
+ `DELETE FROM goal_blockage_qualifications WHERE thread_id = ?`,
741
+ );
742
+ const deleteThreadContinuations = database.prepare(
743
+ `DELETE FROM goal_continuations WHERE thread_id = ?`,
744
+ );
745
+ const deleteThreadFailureEvents = database.prepare(
746
+ `DELETE FROM goal_failure_events WHERE thread_id = ?`,
747
+ );
748
+ const selectOwnedThreadIds = database.prepare<
749
+ [],
750
+ { readonly threadId: string }
751
+ >(`SELECT thread_id AS threadId FROM goals
752
+ UNION SELECT thread_id FROM goal_history_order
753
+ UNION SELECT thread_id FROM goal_history_counters
754
+ UNION SELECT thread_id FROM goal_blockage_qualifications
755
+ UNION SELECT thread_id FROM goal_continuations
756
+ UNION SELECT thread_id FROM goal_failure_events
757
+ ORDER BY threadId`);
758
+ const continuationColumns = `SELECT
759
+ id,
760
+ thread_id AS threadId,
761
+ goal_id AS goalId,
762
+ goal_revision AS goalRevision,
763
+ opportunity_key AS opportunityKey,
764
+ delivery_marker AS deliveryMarker,
765
+ attempt,
766
+ state,
767
+ outcome,
768
+ lease_expires_at AS leaseExpiresAt,
769
+ outcome_reason AS outcomeReason,
770
+ created_at AS createdAt,
771
+ updated_at AS updatedAt,
772
+ progress_assessed_at AS progressAssessedAt
773
+ FROM goal_continuations`;
774
+ const insertContinuation = database.prepare(`
775
+ INSERT INTO goal_continuations (
776
+ id, thread_id, goal_id, goal_revision, opportunity_key,
777
+ delivery_marker, attempt, state, outcome, lease_expires_at,
778
+ outcome_reason, created_at, updated_at
779
+ ) VALUES (?, ?, ?, ?, ?, ?, 0, 'pending', NULL, NULL, NULL, ?, ?)
780
+ ON CONFLICT DO NOTHING
781
+ `);
782
+ const selectContinuationById = database.prepare<[string], GoalContinuationRow>(
783
+ `${continuationColumns} WHERE id = ?`,
784
+ );
785
+ const selectPendingContinuation = database.prepare<[], GoalContinuationRow>(
786
+ `${continuationColumns}
787
+ WHERE state = 'pending'
788
+ ORDER BY created_at, id
789
+ LIMIT 1`,
790
+ );
791
+ const expireClaimedContinuations = database.prepare<[string, string]>(`
792
+ UPDATE goal_continuations
793
+ SET state = 'pending', outcome = 'expired', lease_expires_at = NULL,
794
+ outcome_reason = 'claim lease expired', updated_at = ?
795
+ WHERE state = 'claimed' AND lease_expires_at IS NOT NULL
796
+ AND lease_expires_at <= ?
797
+ `);
798
+ const selectSendingContinuations = database.prepare<[], GoalContinuationRow>(`
799
+ ${continuationColumns}
800
+ WHERE state = 'sending'
801
+ ORDER BY updated_at, id
802
+ `);
803
+ const selectUnassessedSentContinuations = database.prepare<[], GoalContinuationRow>(`
804
+ ${continuationColumns}
805
+ WHERE state = 'resolved' AND outcome = 'sent'
806
+ AND progress_assessed_at IS NULL
807
+ ORDER BY created_at, id
808
+ `);
809
+ const recoverClaimedContinuations = database.prepare<[string]>(`
810
+ UPDATE goal_continuations
811
+ SET state = 'pending', outcome = 'expired', lease_expires_at = NULL,
812
+ outcome_reason = 'claim recovered after restart', updated_at = ?
813
+ WHERE state = 'claimed'
814
+ `);
815
+ const claimContinuation = database.prepare<[string, string, string]>(`
816
+ UPDATE goal_continuations
817
+ SET state = 'claimed', attempt = attempt + 1,
818
+ lease_expires_at = ?, updated_at = ?
819
+ WHERE id = ? AND state = 'pending'
820
+ `);
821
+ const markContinuationSending = database.prepare<[string, string, string, string]>(`
822
+ UPDATE goal_continuations
823
+ SET state = 'sending', delivery_marker = ?, lease_expires_at = ?,
824
+ updated_at = ?
825
+ WHERE id = ? AND state = 'claimed'
826
+ `);
827
+ const requeueContinuation = database.prepare<[string, string, string, string]>(`
828
+ UPDATE goal_continuations
829
+ SET state = 'pending', delivery_marker = ?, outcome = 'expired',
830
+ lease_expires_at = NULL, outcome_reason = ?, updated_at = ?
831
+ WHERE id = ? AND state = 'sending'
832
+ `);
833
+ const resolveContinuation = database.prepare<[string, string, string, string]>(`
834
+ UPDATE goal_continuations
835
+ SET state = 'resolved', outcome = ?, lease_expires_at = NULL,
836
+ outcome_reason = ?, updated_at = ?
837
+ WHERE id = ? AND state IN ('claimed', 'sending')
838
+ `);
839
+ const markContinuationAssessed = database.prepare<
840
+ [string, string, string, string]
841
+ >(`UPDATE goal_continuations
842
+ SET progress_assessed_at = ?, progress_evidence_json = ?, updated_at = ?
843
+ WHERE id = ? AND state = 'resolved' AND outcome = 'sent'
844
+ AND progress_assessed_at IS NULL`);
845
+ const resetNoProgress = database.prepare(
846
+ `UPDATE goals
847
+ SET no_progress_consecutive_count = 0,
848
+ no_progress_last_continuation_id = ?,
849
+ no_progress_assistant_result_fingerprint = ?,
850
+ no_progress_evidence_json = ?, updated_at = ?
851
+ WHERE id = ? AND thread_id = ? AND revision = ?
852
+ AND state = 'active' AND finished_at IS NULL`,
853
+ );
854
+ const incrementNoProgress = database.prepare(
855
+ `UPDATE goals
856
+ SET no_progress_consecutive_count = no_progress_consecutive_count + 1,
857
+ no_progress_last_continuation_id = ?,
858
+ no_progress_assistant_result_fingerprint = ?,
859
+ no_progress_evidence_json = ?, updated_at = ?,
860
+ state = CASE WHEN no_progress_consecutive_count + 1 >= 3 THEN 'paused' ELSE state END,
861
+ revision = CASE WHEN no_progress_consecutive_count + 1 >= 3 THEN revision + 1 ELSE revision END,
862
+ pause_reason_code = CASE WHEN no_progress_consecutive_count + 1 >= 3 THEN 'no-progress' ELSE pause_reason_code END,
863
+ pause_reason = CASE WHEN no_progress_consecutive_count + 1 >= 3 THEN 'Paused after 3 consecutive automatic Continuations made no observable progress' ELSE pause_reason END
864
+ WHERE id = ? AND thread_id = ? AND revision = ?
865
+ AND state = 'active' AND finished_at IS NULL`,
866
+ );
867
+ const releasePendingGoalContinuations = database.prepare(
868
+ `UPDATE goal_continuations
869
+ SET state = 'resolved', outcome = 'released', lease_expires_at = NULL,
870
+ outcome_reason = 'Goal paused by no-progress protection', updated_at = ?
871
+ WHERE goal_id = ? AND goal_revision = ?
872
+ AND state IN ('pending', 'claimed', 'sending')`,
873
+ );
874
+
875
+ const readCurrent = (threadId: string): GoalDto | null => {
876
+ const row = selectCurrent.get(threadId);
877
+ return row === undefined ? null : decodeGoalRow(row);
878
+ };
879
+ const readByThreadAndId = (
880
+ goalId: string,
881
+ threadId: string,
882
+ ): GoalDto | null => {
883
+ const row = selectByThreadAndId.get(goalId, threadId);
884
+ return row === undefined ? null : decodeGoalRow(row);
885
+ };
886
+ const readById = (goalId: string): GoalDto | null => {
887
+ const row = selectById.get(goalId);
888
+ return row === undefined ? null : decodeGoalRow(row);
889
+ };
890
+
891
+ const startTransaction = database.transaction(
892
+ (record: StartGoalRecord): GoalDto | { readonly conflict: GoalDto } => {
893
+ const current = readCurrent(record.threadId);
894
+ if (current !== null) return { conflict: current };
895
+
896
+ try {
897
+ insert.run(
898
+ record.id,
899
+ record.threadId,
900
+ record.objective,
901
+ record.now,
902
+ record.now,
903
+ );
904
+ } catch (cause) {
905
+ const winner = readCurrent(record.threadId);
906
+ if (winner !== null) return { conflict: winner };
907
+ throw cause;
908
+ }
909
+
910
+ const counter = nextHistorySequence.get(record.threadId);
911
+ if (counter === undefined) {
912
+ throw new Error("Goal history sequence was not allocated.");
913
+ }
914
+ insertHistoryOrder.run(record.id, record.threadId, counter.sequence);
915
+
916
+ const created = readCurrent(record.threadId);
917
+ if (created === null) {
918
+ throw new Error("Goal insert completed without a readable record.");
919
+ }
920
+ return created;
921
+ },
922
+ );
923
+
924
+ const mutateTransaction = database.transaction(
925
+ ({ command, now }: MutateGoalRecord): GoalDto => {
926
+ const before = readByThreadAndId(command.goalId, command.threadId);
927
+ if (before === null) {
928
+ throw new GoalNotFound({
929
+ threadId: command.threadId,
930
+ goalId: command.goalId,
931
+ });
932
+ }
933
+ if (before.revision !== command.expectedRevision) {
934
+ throw new GoalStaleGuard({
935
+ goalId: command.goalId,
936
+ expectedRevision: command.expectedRevision,
937
+ actualRevision: before.revision,
938
+ });
939
+ }
940
+ if (!permitsMutation(before, command.type)) {
941
+ throw new GoalInvalidTransition({
942
+ goalId: command.goalId,
943
+ action: command.type,
944
+ state: before.state,
945
+ });
946
+ }
947
+
948
+ if (command.type === "block") {
949
+ const qualification = selectBlockageQualification.get(
950
+ command.goalId,
951
+ command.threadId,
952
+ );
953
+ const qualificationForRevision =
954
+ qualification === undefined ||
955
+ qualification.goalRevision !== command.expectedRevision
956
+ ? undefined
957
+ : qualification;
958
+ const expectedTurns =
959
+ qualificationForRevision === undefined
960
+ ? 1
961
+ : qualificationForRevision.repeatedTurns + 1;
962
+ const blockerKey = normalizeBlocker(command.externalAction);
963
+ if (
964
+ qualificationForRevision !== undefined &&
965
+ qualificationForRevision.blockerKey !== blockerKey
966
+ ) {
967
+ throw new GoalInvalidBlockage({
968
+ message:
969
+ "Goal Blockage requires the same external blocker across consecutive reports.",
970
+ });
971
+ }
972
+ if (command.repeatedTurns !== expectedTurns) {
973
+ throw new GoalInvalidBlockage({
974
+ message: `Goal Blockage report ${command.repeatedTurns} is out of sequence; expected report ${expectedTurns}.`,
975
+ });
976
+ }
977
+ saveBlockageQualification.run(
978
+ command.goalId,
979
+ command.threadId,
980
+ command.expectedRevision,
981
+ blockerKey,
982
+ command.externalAction,
983
+ command.evidence,
984
+ command.repeatedTurns,
985
+ now,
986
+ );
987
+ if (command.repeatedTurns < 3) return before;
988
+ }
989
+
990
+ const result = (() => {
991
+ switch (command.type) {
992
+ case "edit":
993
+ return edit.run(
994
+ command.objective,
995
+ now,
996
+ command.goalId,
997
+ command.threadId,
998
+ command.expectedRevision,
999
+ );
1000
+ case "pause":
1001
+ return pause.run(
1002
+ now,
1003
+ command.goalId,
1004
+ command.threadId,
1005
+ command.expectedRevision,
1006
+ );
1007
+ case "resume":
1008
+ return resume.run(
1009
+ now,
1010
+ command.goalId,
1011
+ command.threadId,
1012
+ command.expectedRevision,
1013
+ );
1014
+ case "cancel":
1015
+ return cancel.run(
1016
+ now,
1017
+ now,
1018
+ command.goalId,
1019
+ command.threadId,
1020
+ command.expectedRevision,
1021
+ );
1022
+ case "complete":
1023
+ return complete.run(
1024
+ now,
1025
+ now,
1026
+ command.summary,
1027
+ command.verificationEvidence,
1028
+ command.goalId,
1029
+ command.threadId,
1030
+ command.expectedRevision,
1031
+ );
1032
+ case "block":
1033
+ return block.run(
1034
+ now,
1035
+ now,
1036
+ command.externalAction,
1037
+ command.evidence,
1038
+ command.repeatedTurns,
1039
+ command.goalId,
1040
+ command.threadId,
1041
+ command.expectedRevision,
1042
+ );
1043
+ }
1044
+ })();
1045
+
1046
+ if (result.changes !== 1) {
1047
+ const current = readByThreadAndId(
1048
+ command.goalId,
1049
+ command.threadId,
1050
+ );
1051
+ if (current === null) {
1052
+ throw new GoalNotFound({
1053
+ threadId: command.threadId,
1054
+ goalId: command.goalId,
1055
+ });
1056
+ }
1057
+ if (current.revision !== command.expectedRevision) {
1058
+ throw new GoalStaleGuard({
1059
+ goalId: command.goalId,
1060
+ expectedRevision: command.expectedRevision,
1061
+ actualRevision: current.revision,
1062
+ });
1063
+ }
1064
+ throw new GoalInvalidTransition({
1065
+ goalId: command.goalId,
1066
+ action: command.type,
1067
+ state: current.state,
1068
+ });
1069
+ }
1070
+
1071
+ if (command.type !== "block") {
1072
+ deleteBlockageQualification.run(command.goalId);
1073
+ }
1074
+ const updated = readByThreadAndId(
1075
+ command.goalId,
1076
+ command.threadId,
1077
+ );
1078
+ if (updated === null) {
1079
+ throw new Error("Goal update completed without a readable record.");
1080
+ }
1081
+ return updated;
1082
+ },
1083
+ );
1084
+
1085
+ const recordFailureTransaction = database.transaction(
1086
+ (record: RecordGoalFailure): GoalDto | null => {
1087
+ const previousMaxEventSeq =
1088
+ record.event === undefined
1089
+ ? null
1090
+ : selectMaxFailureEventSeq.get(record.threadId)?.eventSeq ?? null;
1091
+ const observedEvents = [
1092
+ ...(record.observedEvents ?? []),
1093
+ ...(record.event === undefined ? [] : [record.event]),
1094
+ ];
1095
+ const priorTurnEvent =
1096
+ record.event?.turnId === undefined || record.event.turnId === null
1097
+ ? undefined
1098
+ : selectFailureEventForTurn.get(
1099
+ record.threadId,
1100
+ record.event.turnId,
1101
+ );
1102
+ let selectedEventWasNew =
1103
+ record.event === undefined && priorTurnEvent === undefined;
1104
+ const observedEventIds = new Set<string>();
1105
+ for (const event of observedEvents) {
1106
+ if (observedEventIds.has(event.id)) continue;
1107
+ observedEventIds.add(event.id);
1108
+ const inserted = insertFailureEvent.run(
1109
+ record.threadId,
1110
+ event.id,
1111
+ event.seq,
1112
+ event.createdAt,
1113
+ event.turnId ?? null,
1114
+ record.now,
1115
+ );
1116
+ if (record.event?.id === event.id) {
1117
+ selectedEventWasNew =
1118
+ inserted.changes === 1 && priorTurnEvent === undefined;
1119
+ }
1120
+ }
1121
+
1122
+ const current = readCurrent(record.threadId);
1123
+ if (current === null) return current;
1124
+ if (record.event !== undefined && !selectedEventWasNew) return current;
1125
+ if (
1126
+ record.event !== undefined &&
1127
+ record.event.seq !== null &&
1128
+ previousMaxEventSeq !== null &&
1129
+ record.event.seq <= previousMaxEventSeq
1130
+ ) {
1131
+ return current;
1132
+ }
1133
+ if (
1134
+ record.event !== undefined &&
1135
+ record.event.createdAt < Date.parse(current.createdAt)
1136
+ ) {
1137
+ return current;
1138
+ }
1139
+ if (
1140
+ current.state !== "active" &&
1141
+ (current.pauseReasonCode === "manual" || record.event === undefined)
1142
+ ) {
1143
+ return current;
1144
+ }
1145
+ const usageWait =
1146
+ record.failure.kind === "usage-limit" &&
1147
+ record.failure.limitKind === "subscription-window" &&
1148
+ record.failure.resetAt !== null &&
1149
+ record.failure.resetAt > record.now;
1150
+ const result = recordFailure.run(
1151
+ usageWait ? "waiting" : "paused",
1152
+ record.now,
1153
+ "usage-limit" === record.failure.kind
1154
+ ? "usage-limit"
1155
+ : "failure",
1156
+ record.failure.reason,
1157
+ record.failure.kind === "usage-limit"
1158
+ ? record.failure.limitKind
1159
+ : null,
1160
+ usageWait ? record.failure.resetAt : null,
1161
+ current.id,
1162
+ record.threadId,
1163
+ );
1164
+ if (result.changes !== 1) return readCurrent(record.threadId);
1165
+ return readCurrent(record.threadId);
1166
+ },
1167
+ );
1168
+
1169
+ const assessContinuationTransaction = database.transaction(
1170
+ (record: AssessGoalContinuationRecord): GoalDto | null => {
1171
+ const continuation = selectContinuationById.get(
1172
+ record.continuationId,
1173
+ );
1174
+ if (
1175
+ continuation === undefined ||
1176
+ continuation.progressAssessedAt !== null ||
1177
+ continuation.outcome !== "sent" ||
1178
+ continuation.goalId !== record.goalId ||
1179
+ continuation.goalRevision !== record.goalRevision ||
1180
+ continuation.threadId !== record.threadId
1181
+ ) {
1182
+ return readCurrent(record.threadId);
1183
+ }
1184
+
1185
+ const current = readCurrent(record.threadId);
1186
+ const currentEvidence = current?.noProgressEvidence ?? null;
1187
+ const ownsCurrentRevision =
1188
+ current !== null &&
1189
+ current.id === record.goalId &&
1190
+ current.revision === record.goalRevision &&
1191
+ current.state === "active";
1192
+ if (
1193
+ !ownsCurrentRevision ||
1194
+ (currentEvidence !== null &&
1195
+ record.observation.terminalSeq <= currentEvidence.terminalSeq)
1196
+ ) {
1197
+ const ignored = JSON.stringify({
1198
+ assessment: "ignored",
1199
+ continuationId: record.continuationId,
1200
+ terminalEventId: record.observation.terminalEventId,
1201
+ terminalSeq: record.observation.terminalSeq,
1202
+ observedAt: record.now,
1203
+ reason: !ownsCurrentRevision
1204
+ ? "Goal identity, revision, or state changed"
1205
+ : "A later Continuation was already assessed",
1206
+ });
1207
+ markContinuationAssessed.run(
1208
+ record.now,
1209
+ ignored,
1210
+ record.now,
1211
+ record.continuationId,
1212
+ );
1213
+ return current;
1214
+ }
1215
+
1216
+ const previousAssistantResultFingerprint =
1217
+ current.noProgressAssistantResultFingerprint;
1218
+ const changedAssistantResult =
1219
+ record.observation.assistantResultFingerprint !== null &&
1220
+ record.observation.assistantResultFingerprint !==
1221
+ previousAssistantResultFingerprint;
1222
+ const signals: GoalProgressSignalKind[] = [
1223
+ ...record.observation.signals,
1224
+ ...(changedAssistantResult
1225
+ ? (["changed-assistant-result"] as const)
1226
+ : []),
1227
+ ];
1228
+ const evidence: GoalNoProgressEvidence = {
1229
+ continuationId: record.continuationId,
1230
+ ...record.observation,
1231
+ signals,
1232
+ previousAssistantResultFingerprint,
1233
+ assessment: signals.length > 0 ? "progress" : "no-progress",
1234
+ observedAt: record.now,
1235
+ };
1236
+ const evidenceJson = JSON.stringify(evidence);
1237
+ const nextAssistantResultFingerprint =
1238
+ record.observation.assistantResultFingerprint ??
1239
+ previousAssistantResultFingerprint;
1240
+ const result =
1241
+ signals.length > 0
1242
+ ? resetNoProgress.run(
1243
+ record.continuationId,
1244
+ nextAssistantResultFingerprint,
1245
+ evidenceJson,
1246
+ record.now,
1247
+ record.goalId,
1248
+ record.threadId,
1249
+ record.goalRevision,
1250
+ )
1251
+ : incrementNoProgress.run(
1252
+ record.continuationId,
1253
+ nextAssistantResultFingerprint,
1254
+ evidenceJson,
1255
+ record.now,
1256
+ record.goalId,
1257
+ record.threadId,
1258
+ record.goalRevision,
1259
+ );
1260
+ if (result.changes !== 1) {
1261
+ throw new Error("Goal changed while assessing Continuation progress.");
1262
+ }
1263
+ const updated = readById(record.goalId);
1264
+ if (
1265
+ updated !== null &&
1266
+ updated.pauseReasonCode === "no-progress" &&
1267
+ updated.noProgressConsecutiveCount === 3
1268
+ ) {
1269
+ releasePendingGoalContinuations.run(
1270
+ record.now,
1271
+ record.goalId,
1272
+ record.goalRevision,
1273
+ );
1274
+ }
1275
+ if (
1276
+ markContinuationAssessed.run(
1277
+ record.now,
1278
+ evidenceJson,
1279
+ record.now,
1280
+ record.continuationId,
1281
+ ).changes !== 1
1282
+ ) {
1283
+ throw new Error("Continuation assessment was not recorded.");
1284
+ }
1285
+ return updated;
1286
+ },
1287
+ );
1288
+
1289
+ const recoverUsageLimitTransaction = database.transaction(
1290
+ (record: RecoverGoalUsageLimitRecord): GoalDto | null => {
1291
+ const result = recoverUsageLimit.run(
1292
+ record.now,
1293
+ record.goalId,
1294
+ record.threadId,
1295
+ record.expectedRevision,
1296
+ record.now,
1297
+ );
1298
+ return result.changes === 1 ? readById(record.goalId) : null;
1299
+ },
1300
+ );
1301
+
1302
+ const deleteTransaction = database.transaction(
1303
+ (record: DeleteGoalRecord): GoalDto => {
1304
+ const before = readByThreadAndId(record.goalId, record.threadId);
1305
+ if (before === null) {
1306
+ throw new GoalNotFound({
1307
+ threadId: record.threadId,
1308
+ goalId: record.goalId,
1309
+ });
1310
+ }
1311
+ if (before.revision !== record.expectedRevision) {
1312
+ throw new GoalStaleGuard({
1313
+ goalId: record.goalId,
1314
+ expectedRevision: record.expectedRevision,
1315
+ actualRevision: before.revision,
1316
+ });
1317
+ }
1318
+
1319
+ const result = deleteByGuard.run(
1320
+ record.goalId,
1321
+ record.threadId,
1322
+ record.expectedRevision,
1323
+ );
1324
+ if (result.changes !== 1) {
1325
+ const current = readByThreadAndId(record.goalId, record.threadId);
1326
+ if (current === null) {
1327
+ throw new GoalNotFound({
1328
+ threadId: record.threadId,
1329
+ goalId: record.goalId,
1330
+ });
1331
+ }
1332
+ throw new GoalStaleGuard({
1333
+ goalId: record.goalId,
1334
+ expectedRevision: record.expectedRevision,
1335
+ actualRevision: current.revision,
1336
+ });
1337
+ }
1338
+ deleteHistoryOrder.run(record.goalId);
1339
+ deleteBlockageQualification.run(record.goalId);
1340
+ return before;
1341
+ },
1342
+ );
1343
+
1344
+ const archiveThreadTransaction = database.transaction(
1345
+ (record: ArchiveGoalThreadRecord): GoalDto | null => {
1346
+ archiveUnfinishedGoal.run(record.now, record.threadId);
1347
+ releaseThreadContinuations.run(record.now, record.threadId);
1348
+ neutralizeThreadAssessments.run(
1349
+ record.now,
1350
+ record.now,
1351
+ record.threadId,
1352
+ );
1353
+ return readCurrent(record.threadId);
1354
+ },
1355
+ );
1356
+
1357
+ const deleteThreadTransaction = database.transaction((threadId: string) => {
1358
+ deleteThreadContinuations.run(threadId);
1359
+ deleteThreadBlockageQualifications.run(threadId);
1360
+ deleteThreadFailureEvents.run(threadId);
1361
+ deleteThreadHistoryOrder.run(threadId);
1362
+ deleteThreadHistoryCounter.run(threadId);
1363
+ deleteThreadGoals.run(threadId);
1364
+ });
1365
+
1366
+ const current = Effect.fn("GoalRepository.current")((threadId: string) =>
1367
+ Effect.try({
1368
+ try: () => readCurrent(threadId),
1369
+ catch: (cause) =>
1370
+ new GoalPersistenceError({
1371
+ message: `Could not read Goal state: ${messageFromCause(cause)}`,
1372
+ }),
1373
+ }),
1374
+ );
1375
+
1376
+ const history = Effect.fn("GoalRepository.history")(
1377
+ (record: HistoryGoalRecords) =>
1378
+ Effect.try({
1379
+ try: (): GoalHistoryPage => {
1380
+ const rowLimit = record.limit + 1;
1381
+ const rows =
1382
+ record.boundary === null
1383
+ ? selectHistoryFirst.all(record.threadId, rowLimit)
1384
+ : selectHistoryAfter.all(
1385
+ record.threadId,
1386
+ record.boundary.sequence,
1387
+ rowLimit,
1388
+ );
1389
+ const goals = rows
1390
+ .slice(0, record.limit)
1391
+ .map(decodeGoalRow);
1392
+ const lastRow = rows.at(record.limit - 1);
1393
+ return {
1394
+ goals,
1395
+ nextCursor:
1396
+ rows.length > record.limit && lastRow !== undefined
1397
+ ? encodeGoalHistoryCursor({
1398
+ threadId: record.threadId,
1399
+ sequence: lastRow.historySequence,
1400
+ })
1401
+ : null,
1402
+ };
1403
+ },
1404
+ catch: (cause) =>
1405
+ new GoalPersistenceError({
1406
+ message: `Could not read Goal history: ${messageFromCause(cause)}`,
1407
+ }),
1408
+ }),
1409
+ );
1410
+
1411
+ const find = Effect.fn("GoalRepository.find")((goalId: string) =>
1412
+ Effect.try({
1413
+ try: () => readById(goalId),
1414
+ catch: (cause) =>
1415
+ new GoalPersistenceError({
1416
+ message: `Could not read Goal: ${messageFromCause(cause)}`,
1417
+ }),
1418
+ }).pipe(
1419
+ Effect.flatMap((goal) =>
1420
+ goal === null
1421
+ ? Effect.fail(new GoalRecordNotFound({ goalId }))
1422
+ : Effect.succeed(goal),
1423
+ ),
1424
+ ),
1425
+ );
1426
+
1427
+ const start = Effect.fn("GoalRepository.start")((record: StartGoalRecord) =>
1428
+ Effect.try({
1429
+ try: () => startTransaction(record),
1430
+ catch: (cause) =>
1431
+ new GoalPersistenceError({
1432
+ message: `Could not persist Goal state: ${messageFromCause(cause)}`,
1433
+ }),
1434
+ }).pipe(
1435
+ Effect.flatMap((result) =>
1436
+ "conflict" in result
1437
+ ? Effect.fail(
1438
+ new GoalAlreadyExists({
1439
+ threadId: record.threadId,
1440
+ goalId: result.conflict.id,
1441
+ }),
1442
+ )
1443
+ : Effect.succeed(result),
1444
+ ),
1445
+ ),
1446
+ );
1447
+
1448
+ const mutate = Effect.fn("GoalRepository.mutate")(
1449
+ (record: MutateGoalRecord) =>
1450
+ Effect.try({
1451
+ try: () => mutateTransaction(record),
1452
+ catch: mutationErrorFromCause,
1453
+ }),
1454
+ );
1455
+
1456
+ const deleteGoal = Effect.fn("GoalRepository.delete")(
1457
+ (record: DeleteGoalRecord) =>
1458
+ Effect.try({
1459
+ try: () => deleteTransaction(record),
1460
+ catch: deleteErrorFromCause,
1461
+ }),
1462
+ );
1463
+
1464
+ const recordFailureEffect = Effect.fn("GoalRepository.recordFailure")(
1465
+ (record: RecordGoalFailure) =>
1466
+ Effect.try({
1467
+ try: () => recordFailureTransaction(record),
1468
+ catch: (cause) =>
1469
+ new GoalPersistenceError({
1470
+ message: `Could not persist Goal failure: ${messageFromCause(cause)}`,
1471
+ }),
1472
+ }),
1473
+ );
1474
+
1475
+ const dueUsageLimits = Effect.fn("GoalRepository.dueUsageLimits")(
1476
+ (now: string) =>
1477
+ Effect.try({
1478
+ try: () => selectDueUsageLimits.all(now).map(decodeGoalRow),
1479
+ catch: (cause) =>
1480
+ new GoalPersistenceError({
1481
+ message: `Could not read due Goal usage limits: ${messageFromCause(cause)}`,
1482
+ }),
1483
+ }),
1484
+ );
1485
+
1486
+ const recoverUsageLimitEffect = Effect.fn(
1487
+ "GoalRepository.recoverUsageLimit",
1488
+ )((record: RecoverGoalUsageLimitRecord) =>
1489
+ Effect.try({
1490
+ try: () => recoverUsageLimitTransaction(record),
1491
+ catch: (cause) =>
1492
+ new GoalPersistenceError({
1493
+ message: `Could not recover Goal usage limit: ${messageFromCause(cause)}`,
1494
+ }),
1495
+ }),
1496
+ );
1497
+
1498
+ const nextUsageLimitReset = Effect.fn(
1499
+ "GoalRepository.nextUsageLimitReset",
1500
+ )(() =>
1501
+ Effect.try({
1502
+ try: () => selectNextUsageLimitReset.get()?.usageResetAt ?? null,
1503
+ catch: (cause) =>
1504
+ new GoalPersistenceError({
1505
+ message: `Could not read Goal usage resets: ${messageFromCause(cause)}`,
1506
+ }),
1507
+ }),
1508
+ );
1509
+
1510
+ const enqueueContinuation = Effect.fn("GoalRepository.enqueueContinuation")(
1511
+ (record: EnqueueGoalContinuationRecord) =>
1512
+ Effect.try({
1513
+ try: () => {
1514
+ const insertResult = insertContinuation.run(
1515
+ record.id,
1516
+ record.threadId,
1517
+ record.goalId,
1518
+ record.goalRevision,
1519
+ record.opportunityKey,
1520
+ record.deliveryMarker,
1521
+ record.now,
1522
+ record.now,
1523
+ );
1524
+ const row = selectContinuationById.get(record.id);
1525
+ if (row !== undefined) return decodeContinuation(row);
1526
+ if (insertResult.changes === 0) {
1527
+ const existing = database
1528
+ .prepare<[string, string], GoalContinuationRow>(
1529
+ `${continuationColumns}
1530
+ WHERE thread_id = ? AND opportunity_key = ?`,
1531
+ )
1532
+ .get(record.threadId, record.opportunityKey);
1533
+ return existing === undefined ? null : decodeContinuation(existing);
1534
+ }
1535
+ throw new Error("Continuation insert completed without a readable record.");
1536
+ },
1537
+ catch: (cause) =>
1538
+ new GoalPersistenceError({
1539
+ message: `Could not persist Continuation claim: ${messageFromCause(cause)}`,
1540
+ }),
1541
+ }),
1542
+ );
1543
+
1544
+ const recoverContinuations = Effect.fn("GoalRepository.recoverContinuations")(
1545
+ (now: string) =>
1546
+ Effect.try({
1547
+ try: () => {
1548
+ const recover = database.transaction(() => {
1549
+ recoverClaimedContinuations.run(now);
1550
+ });
1551
+ recover();
1552
+ },
1553
+ catch: (cause) =>
1554
+ new GoalPersistenceError({
1555
+ message: `Could not recover Continuations: ${messageFromCause(cause)}`,
1556
+ }),
1557
+ }),
1558
+ );
1559
+
1560
+ const sendingContinuations = Effect.fn(
1561
+ "GoalRepository.sendingContinuations",
1562
+ )(() =>
1563
+ Effect.try({
1564
+ try: () =>
1565
+ selectSendingContinuations.all().map(decodeContinuation),
1566
+ catch: (cause) =>
1567
+ new GoalPersistenceError({
1568
+ message: `Could not list sending Continuations: ${messageFromCause(cause)}`,
1569
+ }),
1570
+ }),
1571
+ );
1572
+
1573
+ const unassessedSentContinuations = Effect.fn(
1574
+ "GoalRepository.unassessedSentContinuations",
1575
+ )(() =>
1576
+ Effect.try({
1577
+ try: () =>
1578
+ selectUnassessedSentContinuations.all().map(decodeContinuation),
1579
+ catch: (cause) =>
1580
+ new GoalPersistenceError({
1581
+ message: `Could not list unassessed Continuations: ${messageFromCause(cause)}`,
1582
+ }),
1583
+ }),
1584
+ );
1585
+
1586
+ const assessContinuation = Effect.fn(
1587
+ "GoalRepository.assessContinuation",
1588
+ )((record: AssessGoalContinuationRecord) =>
1589
+ Effect.try({
1590
+ try: () => assessContinuationTransaction(record),
1591
+ catch: (cause) =>
1592
+ new GoalPersistenceError({
1593
+ message: `Could not assess Continuation progress: ${messageFromCause(cause)}`,
1594
+ }),
1595
+ }),
1596
+ );
1597
+
1598
+ const requeueContinuationClaim = Effect.fn(
1599
+ "GoalRepository.requeueContinuation",
1600
+ )((record: RequeueGoalContinuationRecord) =>
1601
+ Effect.try({
1602
+ try: () =>
1603
+ requeueContinuation.run(
1604
+ record.deliveryMarker,
1605
+ record.reason,
1606
+ record.now,
1607
+ record.id,
1608
+ ).changes === 1,
1609
+ catch: (cause) =>
1610
+ new GoalPersistenceError({
1611
+ message: `Could not requeue Continuation: ${messageFromCause(cause)}`,
1612
+ }),
1613
+ }),
1614
+ );
1615
+
1616
+ const claimNextContinuation = Effect.fn("GoalRepository.claimContinuation")(
1617
+ (record: ClaimGoalContinuationRecord) =>
1618
+ Effect.try({
1619
+ try: () => {
1620
+ const transaction = database.transaction(() => {
1621
+ expireClaimedContinuations.run(record.now, record.now);
1622
+ const pending = selectPendingContinuation.get();
1623
+ if (pending === undefined) return null;
1624
+ const result = claimContinuation.run(
1625
+ record.leaseExpiresAt,
1626
+ record.now,
1627
+ pending.id,
1628
+ );
1629
+ if (result.changes !== 1) return null;
1630
+ const claimed = selectContinuationById.get(pending.id);
1631
+ return claimed === undefined ? null : decodeContinuation(claimed);
1632
+ });
1633
+ return transaction();
1634
+ },
1635
+ catch: (cause) =>
1636
+ new GoalPersistenceError({
1637
+ message: `Could not claim Continuation: ${messageFromCause(cause)}`,
1638
+ }),
1639
+ }),
1640
+ );
1641
+
1642
+ const markContinuationSendingClaim = Effect.fn(
1643
+ "GoalRepository.markContinuationSending",
1644
+ )((record: MarkGoalContinuationSendingRecord) =>
1645
+ Effect.try({
1646
+ try: () =>
1647
+ markContinuationSending.run(
1648
+ record.deliveryMarker,
1649
+ record.leaseExpiresAt,
1650
+ record.now,
1651
+ record.id,
1652
+ ).changes === 1,
1653
+ catch: (cause) =>
1654
+ new GoalPersistenceError({
1655
+ message: `Could not mark Continuation as sending: ${messageFromCause(cause)}`,
1656
+ }),
1657
+ }),
1658
+ );
1659
+
1660
+ const resolveContinuationClaim = Effect.fn("GoalRepository.resolveContinuation")(
1661
+ (record: ResolveGoalContinuationRecord) =>
1662
+ Effect.try({
1663
+ try: () =>
1664
+ resolveContinuation.run(
1665
+ record.outcome,
1666
+ record.reason,
1667
+ record.now,
1668
+ record.id,
1669
+ ).changes === 1,
1670
+ catch: (cause) =>
1671
+ new GoalPersistenceError({
1672
+ message: `Could not resolve Continuation: ${messageFromCause(cause)}`,
1673
+ }),
1674
+ }),
1675
+ );
1676
+
1677
+ const archiveThread = Effect.fn("GoalRepository.archiveThread")(
1678
+ (record: ArchiveGoalThreadRecord) =>
1679
+ Effect.try({
1680
+ try: () => archiveThreadTransaction(record),
1681
+ catch: (cause) =>
1682
+ new GoalPersistenceError({
1683
+ message: `Could not archive thread Goal state: ${messageFromCause(cause)}`,
1684
+ }),
1685
+ }),
1686
+ );
1687
+
1688
+ const deleteThread = Effect.fn("GoalRepository.deleteThread")(
1689
+ (threadId: string) =>
1690
+ Effect.try({
1691
+ try: () => deleteThreadTransaction(threadId),
1692
+ catch: (cause) =>
1693
+ new GoalPersistenceError({
1694
+ message: `Could not delete thread Goal state: ${messageFromCause(cause)}`,
1695
+ }),
1696
+ }),
1697
+ );
1698
+
1699
+ const ownedThreadIds = Effect.fn("GoalRepository.ownedThreadIds")(() =>
1700
+ Effect.try({
1701
+ try: () => selectOwnedThreadIds.all().map((row) => row.threadId),
1702
+ catch: (cause) =>
1703
+ new GoalPersistenceError({
1704
+ message: `Could not list thread-owned Goal state: ${messageFromCause(cause)}`,
1705
+ }),
1706
+ }),
1707
+ );
1708
+
1709
+ return GoalRepository.of({
1710
+ current,
1711
+ history,
1712
+ find,
1713
+ start,
1714
+ mutate,
1715
+ delete: deleteGoal,
1716
+ archiveThread,
1717
+ deleteThread,
1718
+ ownedThreadIds,
1719
+ recordFailure: recordFailureEffect,
1720
+ dueUsageLimits,
1721
+ recoverUsageLimit: recoverUsageLimitEffect,
1722
+ nextUsageLimitReset,
1723
+ enqueueContinuation,
1724
+ recoverContinuations,
1725
+ sendingContinuations,
1726
+ requeueContinuation: requeueContinuationClaim,
1727
+ claimContinuation: claimNextContinuation,
1728
+ markContinuationSending: markContinuationSendingClaim,
1729
+ resolveContinuation: resolveContinuationClaim,
1730
+ unassessedSentContinuations,
1731
+ assessContinuation,
1732
+ });
1733
+ }),
1734
+ );
1735
+ }