@operad-io/dev 0.0.0-stage → 0.0.1

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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +795 -2
  3. package/dev.schema.json +602 -0
  4. package/flows/chat-worktree.flow.ts +18 -0
  5. package/flows/dev.flow.ts +7 -0
  6. package/package.json +29 -4
  7. package/src/actions.ts +591 -0
  8. package/src/announce.ts +225 -0
  9. package/src/chat.ts +234 -0
  10. package/src/check.ts +80 -0
  11. package/src/commands.ts +417 -0
  12. package/src/editor.ts +55 -0
  13. package/src/flaky.ts +716 -0
  14. package/src/flow-compiler.ts +858 -0
  15. package/src/followups.ts +223 -0
  16. package/src/gate.ts +2897 -0
  17. package/src/git.ts +138 -0
  18. package/src/index.ts +226 -0
  19. package/src/integrate.ts +1201 -0
  20. package/src/integration-queue.ts +393 -0
  21. package/src/lock.ts +36 -0
  22. package/src/mainclone.ts +102 -0
  23. package/src/marks.ts +126 -0
  24. package/src/model.ts +1165 -0
  25. package/src/notcode.ts +266 -0
  26. package/src/place-order.ts +161 -0
  27. package/src/place-wait.ts +64 -0
  28. package/src/places.ts +368 -0
  29. package/src/prepare.ts +106 -0
  30. package/src/progress.ts +115 -0
  31. package/src/project-flows.ts +160 -0
  32. package/src/project-settings.ts +185 -0
  33. package/src/refusals.ts +336 -0
  34. package/src/rerun.ts +378 -0
  35. package/src/reruns.ts +62 -0
  36. package/src/retry.ts +212 -0
  37. package/src/rework.ts +366 -0
  38. package/src/schedule.ts +1052 -0
  39. package/src/service.ts +2160 -0
  40. package/src/settings.ts +1463 -0
  41. package/src/standing.ts +87 -0
  42. package/src/stdin.ts +105 -0
  43. package/src/steps.ts +1775 -0
  44. package/src/stops.ts +103 -0
  45. package/src/throughput.ts +347 -0
  46. package/src/timeouts.ts +60 -0
  47. package/src/views.ts +1167 -0
  48. package/src/waits.ts +105 -0
package/src/model.ts ADDED
@@ -0,0 +1,1165 @@
1
+ /** The objects the dev plugin owns, and the pure rules that change them. */
2
+
3
+ import type { FlowDefinition, ObjectStore, StoredObject } from "@operad-io/engine";
4
+ import type { ReviewHistoryEntry, ReviewSettingsUsed } from "./rework.ts";
5
+ import type { WaitKind } from "./waits.ts";
6
+ import { isRecord, oneLine } from "@operad-io/engine";
7
+
8
+ /**
9
+ * Every object of a type, following the store's pages. The store returns one
10
+ * page at a time; an id scan must not stop at its default limit.
11
+ */
12
+ export async function listAll(
13
+ store: ObjectStore,
14
+ type: string,
15
+ ): Promise<StoredObject[]> {
16
+ const objects: StoredObject[] = [];
17
+ let cursor: string | undefined;
18
+ for (;;) {
19
+ const page = await store.list(type, cursor === undefined ? {} : { cursor });
20
+ objects.push(...page.objects);
21
+ if (page.next === undefined) return objects;
22
+ cursor = page.next;
23
+ }
24
+ }
25
+
26
+ /** A plan is a request the owner confirmed into work. */
27
+ export type PlanStatus = "draft" | "confirmed" | "paused" | "cancelled";
28
+
29
+ /** Every state a plan row shows: its status, or `finished` once its tasks ended. */
30
+ export const PLAN_STATES = ["draft", "confirmed", "paused", "finished", "cancelled"] as const;
31
+ export type PlanState = (typeof PLAN_STATES)[number];
32
+
33
+ /** How far a plan may run without a person. */
34
+ export type AutoMode = "off" | "run" | "merge";
35
+
36
+ /** The five priorities, most urgent first. */
37
+ export const PRIORITIES = ["P0", "P1", "P2", "P3", "P4", "P5"] as const;
38
+ export type Priority = (typeof PRIORITIES)[number];
39
+
40
+ /** Every phase a task can be in, in the order it usually passes through them. */
41
+ export const TASK_PHASES = [
42
+ "proposed",
43
+ "ready",
44
+ "running",
45
+ "review",
46
+ "waiting",
47
+ "paused",
48
+ "merged",
49
+ "cancelled",
50
+ ] as const;
51
+
52
+ /** Where a task is. */
53
+ export type TaskPhase = (typeof TASK_PHASES)[number];
54
+
55
+ /**
56
+ * Every state a task row shows: its phase, or `integrating` while its
57
+ * integrate step works. The views and the filters read this one list, so a
58
+ * state a row can show cannot be missing from a filter.
59
+ */
60
+ export type TaskRowState = TaskPhase | "integrating";
61
+
62
+ export const TASK_ROW_STATES: readonly TaskRowState[] = TASK_PHASES.flatMap(
63
+ (phase) => (phase === "review" ? [phase, "integrating" as const] : [phase]),
64
+ );
65
+
66
+ /** The state a task row shows. */
67
+ export function taskRowState(task: TaskData): TaskRowState {
68
+ return isIntegrating(task) ? "integrating" : task.phase;
69
+ }
70
+
71
+ /**
72
+ * The list filters of plans and tasks. The declaration and the tests read
73
+ * these; no state name is copied anywhere else.
74
+ */
75
+ /** The task phases that end a task; a view row marks them `final`. */
76
+ export const TASK_FINAL_STATES: readonly string[] = ["merged", "cancelled"];
77
+
78
+ /** The plan states that end a plan. */
79
+ export const PLAN_FINAL_STATES: readonly string[] = ["finished", "cancelled"];
80
+
81
+ export const TASK_FILTERS = [
82
+ {
83
+ name: "active",
84
+ default: true,
85
+ states: TASK_ROW_STATES.filter(
86
+ (state) => !TASK_FINAL_STATES.includes(state),
87
+ ),
88
+ },
89
+ { name: "done", states: ["merged"] },
90
+ { name: "cancelled", states: ["cancelled"] },
91
+ ] as const;
92
+
93
+ export const PLAN_FILTERS = [
94
+ {
95
+ name: "active",
96
+ default: true,
97
+ states: PLAN_STATES.filter((state) => state !== "finished" && state !== "cancelled"),
98
+ },
99
+ { name: "done", states: ["finished"] },
100
+ { name: "cancelled", states: ["cancelled"] },
101
+ ] as const;
102
+
103
+ /** The repository states a row shows; a removed repository is hidden by default. */
104
+ export const REPO_FILTERS = [
105
+ { name: "active", default: true, states: ["active"] },
106
+ { name: "removed", states: ["removed"] },
107
+ ] as const;
108
+
109
+ /** Micros and task counts of the costed tasks of a plan, per cost quality. */
110
+ export interface PlanCostTotals {
111
+ readonly [key: string]: unknown;
112
+ readonly exactMicros: number;
113
+ readonly estimatedMicros: number;
114
+ readonly incompleteMicros: number;
115
+ readonly exactTasks: number;
116
+ readonly estimatedTasks: number;
117
+ readonly incompleteTasks: number;
118
+ }
119
+
120
+ /** The data of a plan object. Counts are a cache over its tasks. */
121
+ export type PlanData = {
122
+ readonly [key: string]: unknown;
123
+ readonly repository: string;
124
+ readonly title: string;
125
+ readonly request: string;
126
+ readonly status: PlanStatus;
127
+ readonly auto: AutoMode;
128
+ readonly priority: Priority;
129
+ readonly concurrency: number;
130
+ readonly taskCount: number;
131
+ readonly mergedCount: number;
132
+ readonly cancelledCount: number;
133
+ /**
134
+ * The cost of the plan's tasks, kept per quality so the weakest is known
135
+ * after a task's cost changes. Absent on a plan stored before it existed.
136
+ */
137
+ readonly costTotals?: PlanCostTotals | undefined;
138
+ /** Tasks being worked or reviewed now; the scheduler keeps it current. */
139
+ readonly activeCount?: number | undefined;
140
+ /** Tasks waiting for a person (proposed, or stopped and asking); the scheduler keeps it current. */
141
+ readonly waitingCount?: number | undefined;
142
+ /** True once the scheduler has reported that every task ended. */
143
+ readonly finishedReported?: boolean | undefined;
144
+ /** When the scheduler last started one of the plan's tasks (ms); the order within a priority reads it. */
145
+ readonly lastStartedAt?: number | undefined;
146
+ /** The flow the plan's tasks start with; absent means `default`. */
147
+ readonly flow?: string | undefined;
148
+ /** Why a ready task of this plan cannot start for its flow; the scheduler keeps it current. */
149
+ readonly flowHeld?: string | undefined;
150
+ };
151
+
152
+ /** What the verify step found when it ran the gate commands. */
153
+ export type VerifyResult = "pass" | "fail";
154
+
155
+ /** One run of a task's gate commands on a commit. */
156
+ export interface VerifyRecord {
157
+ readonly [key: string]: unknown;
158
+ readonly result: VerifyResult;
159
+ readonly run?: string | null;
160
+ /** The command that failed, when one did. */
161
+ readonly command?: string | null;
162
+ /** The file the failed command's output was written to. */
163
+ readonly log?: string | null;
164
+ readonly message?: string | null;
165
+ readonly lineNumber?: number | null;
166
+ /** The gate commands this verify ran, as they were when it ran. */
167
+ readonly commands?: readonly string[];
168
+ }
169
+
170
+ /** A finding the reviewer reported. */
171
+ export interface ReviewFinding {
172
+ readonly [key: string]: unknown;
173
+ readonly file: string;
174
+ readonly line: number;
175
+ readonly severity: string;
176
+ readonly summary: string;
177
+ readonly trigger: string;
178
+ /** True for a finding on a file the change did not touch. */
179
+ readonly preExisting?: boolean;
180
+ /** The same mark as `preExisting`, in the wording the gate reports. */
181
+ readonly pre_existing?: boolean;
182
+ }
183
+
184
+ /**
185
+ * The decision a review round records once. A round may use more than one
186
+ * model run (a fallback, a retry), but it has one decision.
187
+ */
188
+ export type ReviewDecision =
189
+ | "passed"
190
+ | "findings"
191
+ | "unavailable"
192
+ | "timed_out";
193
+
194
+ /** What the review step found. The old `pass`/`fail` records still read. */
195
+ export type ReviewResult =
196
+ | "pass"
197
+ | "fail"
198
+ | "passed"
199
+ | "findings"
200
+ | "failed"
201
+ | "unavailable"
202
+ | "timed_out";
203
+
204
+ /** What one model run of a review round did. */
205
+ export type ReviewRunOutcome =
206
+ | "report"
207
+ | "invalid"
208
+ | "no_report"
209
+ | "unavailable"
210
+ | "timed_out"
211
+ | "failed";
212
+
213
+ /** Which settings a review run used. */
214
+ export type ReviewRunRole = "primary" | "fallback";
215
+
216
+ /** Why a review run happened. */
217
+ export type ReviewRunReason =
218
+ | "initial"
219
+ | "retry"
220
+ | "fallback";
221
+
222
+ /** One model run inside a review round. */
223
+ export interface ReviewRunRecord {
224
+ readonly [key: string]: unknown;
225
+ /** The task attempt this run belongs to. */
226
+ readonly attempt?: number | null;
227
+ /** The review round this run belongs to. */
228
+ readonly round: number;
229
+ readonly role: ReviewRunRole;
230
+ /** The harness step this run used. */
231
+ readonly use: string;
232
+ readonly args: readonly string[];
233
+ /** The model the run named, or its harness step when it named none. */
234
+ readonly model: string;
235
+ readonly reason: ReviewRunReason;
236
+ readonly outcome: ReviewRunOutcome;
237
+ readonly run?: string | null;
238
+ readonly message?: string | null;
239
+ /** The findings a report run returned, with pre-existing marks. */
240
+ readonly findings?: readonly ReviewFinding[] | null;
241
+ readonly verified?: readonly string[] | null;
242
+ /** How many of the findings are at or above the fix level. */
243
+ readonly counted?: number | null;
244
+ }
245
+
246
+ /**
247
+ * A model run of a review round that was asked for but not recorded yet. It is
248
+ * written before the reviewer is called, so a crash after the model answered
249
+ * resumes that run instead of asking the same model again.
250
+ */
251
+ export interface PendingReviewRun {
252
+ readonly [key: string]: unknown;
253
+ readonly attempt?: number | null;
254
+ readonly round: number;
255
+ readonly role: ReviewRunRole;
256
+ readonly use: string;
257
+ readonly args: readonly string[];
258
+ readonly model: string;
259
+ readonly reason: ReviewRunReason;
260
+ readonly run?: string | null;
261
+ /** The report path inside the gate worktree this call was given. */
262
+ readonly report?: string | null;
263
+ }
264
+
265
+ /** One review of a task's verified commit: one decision for the round. */
266
+ export interface ReviewRecord {
267
+ readonly [key: string]: unknown;
268
+ readonly result: ReviewResult;
269
+ readonly run?: string | null;
270
+ /** The decision of the round; absent on a report that failed outright. */
271
+ readonly decision?: ReviewDecision | null;
272
+ /** The round number inside the attempt; the first round is 1. */
273
+ readonly round?: number | null;
274
+ /** The model that produced the decision. */
275
+ readonly model?: string | null;
276
+ /** Which round (first or rework) ran and which block each setting came from. */
277
+ readonly reviewSettings?: ReviewSettingsUsed | null;
278
+ /** When an unavailable round may run again, in epoch milliseconds. */
279
+ readonly retryAt?: number | null;
280
+ /** Every run of this round, in order. */
281
+ readonly runs?: readonly ReviewRunRecord[] | null;
282
+ readonly findings?: readonly ReviewFinding[];
283
+ readonly verified?: readonly string[];
284
+ readonly log?: string | null;
285
+ readonly message?: string | null;
286
+ readonly reason?: string | null;
287
+ /** The commit the reviewer saw. */
288
+ readonly sha?: string | null;
289
+ }
290
+
291
+ /** What the integrate step found while landing the verified commit. */
292
+ export type IntegrationResult = "merged" | "conflict" | "fail" | "failed";
293
+
294
+ /** A record written before the push says the candidate is not landed yet. */
295
+ export type IntegrationPhase = IntegrationResult | "pending";
296
+
297
+ /** One attempt at landing a task's verified commit on main. */
298
+ export interface IntegrationRecord {
299
+ readonly [key: string]: unknown;
300
+ readonly run?: string | null;
301
+ readonly result: IntegrationPhase;
302
+ readonly style?: string | null;
303
+ /** The verified commit the candidate was built from. */
304
+ readonly verified?: string | null;
305
+ /** The commit built on main, before or after the push. */
306
+ readonly candidate?: string | null;
307
+ /** The main commit the candidate was built on. */
308
+ readonly base?: string | null;
309
+ /** The branch head when the step ran, which may be past the verified sha. */
310
+ readonly head?: string | null;
311
+ /** True when the branch head was no longer the verified commit. */
312
+ readonly headMoved?: boolean | null;
313
+ readonly pushed?: boolean | null;
314
+ readonly message?: string | null;
315
+ readonly command?: string | null;
316
+ readonly log?: string | null;
317
+ readonly lineNumber?: number | null;
318
+ readonly files?: readonly string[] | null;
319
+ }
320
+
321
+ /** One cleanup hook line that failed. */
322
+ export interface CleanupFailure {
323
+ readonly [key: string]: unknown;
324
+ readonly line: number;
325
+ readonly text: string;
326
+ readonly message: string;
327
+ }
328
+
329
+ /** What the cleanup step ran after a merge. */
330
+ export interface CleanupRecord {
331
+ readonly [key: string]: unknown;
332
+ readonly run?: string | null;
333
+ readonly failures: readonly CleanupFailure[];
334
+ }
335
+
336
+ /** One rework section the step appended; a replay reads it and appends nothing. */
337
+ export interface ReworkRecord {
338
+ readonly [key: string]: unknown;
339
+ readonly run?: string | null;
340
+ readonly source: string;
341
+ readonly streak: number;
342
+ /** The automatic rework limit in force when the record was written. */
343
+ readonly limit?: number;
344
+ readonly result: "again" | "ask";
345
+ /** True when the wait is because review failed twice in a row. */
346
+ readonly twice?: boolean;
347
+ }
348
+
349
+ /** One run of a task's worker, with what the worktree step learned. */
350
+ export type TaskAttempt = {
351
+ readonly [key: string]: unknown;
352
+ readonly number: number;
353
+ readonly run?: string | null;
354
+ readonly worktree?: string | null;
355
+ readonly branch?: string | null;
356
+ readonly base?: string | null;
357
+ readonly sessionId?: string | null;
358
+ /** The cost in dollars, when the harness reported one. */
359
+ readonly cost?: number | null;
360
+ /** The same cost in micros, as the harness reports it. */
361
+ readonly costMicros?: number | null;
362
+ /** How far to trust the cost: `exact`, `estimated` or `incomplete`. */
363
+ readonly costQuality?: "exact" | "estimated" | "incomplete" | null;
364
+ /** The worker the pool ran for this attempt's work (the fallback one when it fell back). */
365
+ readonly worker?: string | null;
366
+ /** The worker that failed over to `worker`, when the pool fell back. */
367
+ readonly fallbackFrom?: string | null;
368
+ /** The worker of the attempt before, which this attempt's work asks for again. */
369
+ readonly previousWorker?: string | null;
370
+ readonly previousSession?: string | null;
371
+ /** The earlier worker that was no longer in the pool, when the work changed hands. */
372
+ readonly workerChanged?: string | null;
373
+ /** Whether the work step consumed this attempt; a later worktree visit is new work. */
374
+ readonly worked?: boolean;
375
+ /** The file the worker's own log was written to. */
376
+ readonly workLog?: string | null;
377
+ /** The worker's last message of this attempt's work, in full, as the harness reported it. */
378
+ readonly finalMessage?: string | null;
379
+ /** Tokens the worker used, when the harness reported them. */
380
+ readonly tokens?: { readonly input: number; readonly output: number } | null;
381
+ /** How long the worker ran, in milliseconds, as the harness measured it. */
382
+ readonly workMs?: number | null;
383
+ /** Why the work step did not finish cleanly, in the harness's words. */
384
+ readonly workNote?: string | null;
385
+ /** How many times the work step waited for an unavailable model in this attempt. */
386
+ readonly workWaits?: number | null;
387
+ /** When a work step that found its model unavailable may run again (epoch ms). */
388
+ readonly workRetryAt?: number | null;
389
+ readonly result?: string | null;
390
+ /** The branch head the gate verified; review reads this and not the branch. */
391
+ readonly verified?: string | null;
392
+ readonly verify?: VerifyRecord | null;
393
+ readonly review?: ReviewRecord | null;
394
+ /** Every model run of every review round in this attempt. */
395
+ readonly reviewRuns?: readonly ReviewRunRecord[] | null;
396
+ /** The run this review asked for and has not recorded yet. */
397
+ readonly reviewPending?: PendingReviewRun | null;
398
+ /** How many review rounds this attempt has finished. */
399
+ readonly reviews?: number | null;
400
+ /** The rework this run appended; a replay of the same run reads it. */
401
+ readonly rework?: ReworkRecord | null;
402
+ /** What the integrate step did on main. */
403
+ readonly integration?: IntegrationRecord | null;
404
+ /** The run whose integrate step is working now; null once it wrote its result. */
405
+ readonly integrating?: string | null;
406
+ /** While the work step waits for its named worker: what it waits for and who holds it. */
407
+ readonly workerWait?: string | null;
408
+ /** While a step waits for a check place: the place group, since when, and how many wait ahead. */
409
+ readonly placeWait?: { readonly key: string; readonly since: number; readonly ahead: number } | null;
410
+ /** While the integrate step waits for its turn: who is integrating. */
411
+ readonly integrationWait?: string | null;
412
+ /** What the cleanup step ran after the merge. */
413
+ readonly cleanup?: CleanupRecord | null;
414
+ };
415
+
416
+ /**
417
+ * The claim a scheduler start holds on a task until its run records itself.
418
+ * The token lets a step prove that its run is the one that made the claim.
419
+ */
420
+ export interface TaskClaim {
421
+ readonly [key: string]: unknown;
422
+ readonly token: string;
423
+ /** The phase the claim wrote; the first step expects to find it there. */
424
+ readonly phase: TaskPhase;
425
+ }
426
+
427
+ /** The data of a task object. */
428
+ /** Why a step just stopped, in dev's own words; the retry step reads it once. */
429
+ export interface StopRecord {
430
+ readonly [key: string]: unknown;
431
+ readonly step: string;
432
+ readonly result: string;
433
+ readonly reason: string;
434
+ /** The step that was not loaded, when the reason says so. */
435
+ readonly use?: string | undefined;
436
+ }
437
+
438
+ /** The one automatic retry a task's attempt used for a failure outside its work. */
439
+ export interface RetryRecord {
440
+ readonly [key: string]: unknown;
441
+ readonly attempt: number;
442
+ readonly step: string;
443
+ /** What was wrong, as the waiting line says it. */
444
+ readonly cause: string;
445
+ /** When the retry began, in epoch milliseconds. */
446
+ readonly at: number;
447
+ /** What the retry waits for before it runs; absent when it runs at once. */
448
+ readonly waitFor?: "step" | "settings" | undefined;
449
+ readonly use?: string | undefined;
450
+ /** `ready`: the wait is over; `expired`: it ran out; `asked`: a person decides. */
451
+ readonly state: "retrying" | "waiting" | "ready" | "expired" | "asked";
452
+ }
453
+
454
+ export type TaskData = {
455
+ readonly [key: string]: unknown;
456
+ readonly repository: string;
457
+ readonly plan: string;
458
+ readonly title: string;
459
+ readonly brief: string;
460
+ readonly after: readonly string[];
461
+ /** Tasks with the same area in one repository never run at once. */
462
+ readonly area?: string | undefined;
463
+ /** The running task that holds this ready task's area; the scheduler sets it. */
464
+ readonly areaHeldBy?: string | undefined;
465
+ /** How many ready tasks of the same area are ahead in the queue; the scheduler sets it. */
466
+ readonly areaAhead?: number | undefined;
467
+ /** True while this task holds the repository's one slot kept for the plan that has gone longest without starting a task. */
468
+ readonly oldestPlanSlot?: boolean | undefined;
469
+ /** True while a task this ready task follows is not merged; the scheduler sets it. */
470
+ readonly dependencyHeld?: boolean | undefined;
471
+ /** What the held task waits for, as a note names it; set with `dependencyHeld`. */
472
+ readonly dependencyHeldFor?: readonly string[] | undefined;
473
+ /** The note a ready task shows when a slot limit or a missing plugin holds it back; the scheduler sets it. */
474
+ readonly slotHeld?: string | undefined;
475
+ readonly phase: TaskPhase;
476
+ /**
477
+ * The wait the task is in while it waits for a person. A review wait writes
478
+ * its own kind and an announce step writes `person`, so an older review
479
+ * record cannot name the wait the task is in now.
480
+ */
481
+ readonly waitKind?: WaitKind | undefined;
482
+ readonly attempts: number;
483
+ readonly run: string | null;
484
+ /** The flow this task starts with; absent inherits the plan's flow. */
485
+ readonly flow?: string | undefined;
486
+ /** The chat worktree (`chat-<id>`) this task works in instead of one of its own; set when the task is added. */
487
+ readonly worktree?: string | undefined;
488
+ /** The flow a row and the brief name, set only while the repository defines more than one. */
489
+ readonly flowShown?: string | undefined;
490
+ /** Why this ready task does not start, or why this waiting task lost its run: its flow is not defined in the repository's dev.json. */
491
+ readonly flowHeld?: string | undefined;
492
+ /** The flow this attempt runs; absent for a run that started before flows had names. */
493
+ readonly flowName?: string | undefined;
494
+ /** The compiled graph this attempt started with, so a later config cannot change it midway. */
495
+ readonly flowGraph?: FlowDefinition | undefined;
496
+ readonly attempt?: TaskAttempt | undefined;
497
+ /** What each review reported, newest last; the next review follows it. */
498
+ readonly reviewHistory?: readonly ReviewHistoryEntry[] | undefined;
499
+ readonly cost?: number | string | undefined;
500
+ /** How far to trust `cost`; absent for a cost written before it was recorded. */
501
+ readonly costQuality?: "exact" | "estimated" | "incomplete" | null | undefined;
502
+ /** How many automatic reworks ran in a row; a passing gate resets it. */
503
+ readonly reworkStreak?: number | undefined;
504
+ /**
505
+ * The findings text of the last review failure when the attempt before the
506
+ * current rework also ended in one; absent after anything else.
507
+ */
508
+ readonly reviewFailed?: string | undefined;
509
+ /** Why the last step that records one stopped; the retry step consumes it. */
510
+ readonly stop?: StopRecord | null | undefined;
511
+ /** The automatic retry this task's attempt used. */
512
+ readonly retry?: RetryRecord | null | undefined;
513
+ /** The owner asked the scheduler to start this ready task. */
514
+ readonly startRequested?: boolean | undefined;
515
+ /** When an unavailable review may run again, in epoch milliseconds. */
516
+ readonly retryAt?: number | null | undefined;
517
+ /** What the scheduler claimed while it waits for the run to record itself. */
518
+ readonly claim?: TaskClaim | null | undefined;
519
+ /** The attempt whose review the scheduler already answered for auto merge. */
520
+ readonly autoMergeAttempt?: number | undefined;
521
+ /** The attempt whose integration result the scheduler already reported. */
522
+ readonly mergeReportedAttempt?: number | undefined;
523
+ /** The findings that did not fail each review round, oldest first. */
524
+ readonly reviewNotes?: readonly ReviewNotes[] | undefined;
525
+ /** Set when the task merged with notes to collect; absent on older merges. */
526
+ readonly followups?: FollowupMark | undefined;
527
+ /** The tasks a follow-up task collects; set only on a follow-up. */
528
+ readonly followupOf?: readonly string[] | undefined;
529
+ /** Set when dev itself proposed the task (the flaky detector, a follow-up), not a person. */
530
+ readonly openedBy?: "dev" | undefined;
531
+ };
532
+
533
+ /** A finding that did not fail its review round. */
534
+ export interface ReviewNote {
535
+ readonly severity: string;
536
+ readonly file: string;
537
+ readonly line: number | null;
538
+ readonly summary: string;
539
+ }
540
+
541
+ /** The notes of one review round. */
542
+ export interface ReviewNotes {
543
+ readonly attempt: number;
544
+ readonly round: number;
545
+ readonly findings: readonly ReviewNote[];
546
+ }
547
+
548
+ /** A merged task whose notes the plan's follow-up has not collected yet. */
549
+ export interface FollowupMark {
550
+ /** When the task merged, in epoch milliseconds; orders the follow-up's `after`. */
551
+ readonly mergedAt: number;
552
+ readonly state: "collect" | "collected";
553
+ }
554
+
555
+ /** A repository registered with the dev plugin. */
556
+ export type RepositoryData = {
557
+ readonly [key: string]: unknown;
558
+ readonly name: string;
559
+ readonly path: string;
560
+ readonly removed: boolean;
561
+ /** Plans and tasks not yet ended; a cache the repository's row reads. */
562
+ readonly openPlans?: number | undefined;
563
+ readonly openTasks?: number | undefined;
564
+ /** Tasks with a run in progress (working or in review); a cache for the row's mark. */
565
+ readonly activeTasks?: number | undefined;
566
+ };
567
+
568
+ /** The two kinds of object the dev plugin numbers. */
569
+ export type IdKind = "plan" | "task";
570
+
571
+ /** The slug part every id carries: 1-48 of a-z, 0-9 and -, no edge -. */
572
+ const SLUG_SOURCE = "[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
573
+
574
+ /** `P-0001-slug`, or the older `PL0001-slug`, which existing objects keep. */
575
+ export const PLAN_ID = new RegExp(
576
+ `^(?:PL(\\d{4})|P-(\\d{4}))-(${SLUG_SOURCE})$`,
577
+ );
578
+
579
+ /** `T-0001-slug`, or the older `TK0001-slug`, which existing objects keep. */
580
+ export const TASK_ID = new RegExp(
581
+ `^(?:TK(\\d{4})|T-(\\d{4}))-(${SLUG_SOURCE})$`,
582
+ );
583
+
584
+ export type IdMatch = {
585
+ readonly number: number;
586
+ readonly slug: string;
587
+ };
588
+
589
+ /** A rule of the dev plugin was broken; the message starts with the field. */
590
+ export class DevError extends Error {
591
+ readonly field: string;
592
+
593
+ constructor(field: string, message: string) {
594
+ super(`${field}: ${message}`);
595
+ this.name = "DevError";
596
+ this.field = field;
597
+ }
598
+ }
599
+
600
+ /**
601
+ * An action cannot run, or a race made it stale. The message is the line a
602
+ * person reads, as it is: no field name in front, no status.
603
+ */
604
+ export class DevRefusal extends DevError {
605
+ constructor(line: string) {
606
+ super("", line);
607
+ this.name = "DevRefusal";
608
+ this.message = line;
609
+ }
610
+ }
611
+
612
+ /** Reads a stored plan; the store already validated the object when it wrote it. */
613
+ export function planData(data: Record<string, unknown>): PlanData {
614
+ return data as unknown as PlanData;
615
+ }
616
+
617
+ export function taskData(data: Record<string, unknown>): TaskData {
618
+ // A task paused before the phase was renamed is stored as "held".
619
+ if (data.phase === "held") return { ...data, phase: "paused" } as unknown as TaskData;
620
+ return data as unknown as TaskData;
621
+ }
622
+
623
+ export function repositoryData(
624
+ data: Record<string, unknown>,
625
+ ): RepositoryData {
626
+ return data as unknown as RepositoryData;
627
+ }
628
+
629
+ /** `1-48` characters of `a-z0-9-`, with no leading or trailing `-`. */
630
+ export function validateSlug(slug: unknown): string {
631
+ if (typeof slug !== "string" || slug.length < 1 || slug.length > 48) {
632
+ throw new DevError("slug", "must be 1-48 characters of a-z, 0-9 and -");
633
+ }
634
+ if (!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(slug)) {
635
+ throw new DevError(
636
+ "slug",
637
+ "must use only a-z, 0-9 and -, with no leading or trailing -",
638
+ );
639
+ }
640
+ return slug;
641
+ }
642
+
643
+ export function validateTitle(title: unknown): string {
644
+ if (typeof title !== "string" || title.trim().length === 0) {
645
+ throw new DevError("title", "must be a non-empty string");
646
+ }
647
+ return title.trim();
648
+ }
649
+
650
+ /** An area is a short single-line label; the empty string means none. */
651
+ export function validateArea(area: unknown): string | undefined {
652
+ if (typeof area !== "string") {
653
+ throw new DevError("area", "must be a string");
654
+ }
655
+ const trimmed = area.trim();
656
+ if (trimmed.length === 0) return undefined;
657
+ if (trimmed.length > 64 || /[\r\n\u0000]/.test(trimmed)) {
658
+ throw new DevError("area", "must be one short line of at most 64 characters");
659
+ }
660
+ return trimmed;
661
+ }
662
+
663
+ export function validateRepositoryName(name: unknown): string {
664
+ if (typeof name !== "string" || name.trim().length === 0) {
665
+ throw new DevError("name", "must be a non-empty string");
666
+ }
667
+ if (name.includes("/") || name.includes("\\") || name.includes("\u0000")) {
668
+ throw new DevError("name", 'must not contain "/", "\\" or a NUL');
669
+ }
670
+ return name.trim();
671
+ }
672
+
673
+ export function parseId(id: string, kind: IdKind): IdMatch | undefined {
674
+ const pattern = kind === "plan" ? PLAN_ID : TASK_ID;
675
+ const match = pattern.exec(id);
676
+ if (match === null) return undefined;
677
+ const number = Number(match[1] ?? match[2]);
678
+ const slug = match[3] ?? "";
679
+ return { number, slug };
680
+ }
681
+
682
+ /** A new id always uses the short form, whatever form the existing ids use. */
683
+ export function formatId(
684
+ kind: IdKind,
685
+ number: number,
686
+ slug: string,
687
+ ): string {
688
+ if (!Number.isInteger(number) || number < 1 || number > 9999) {
689
+ throw new DevError("id", `no ${kind} number is left`);
690
+ }
691
+ const prefix = kind === "plan" ? "P" : "T";
692
+ return `${prefix}-${String(number).padStart(4, "0")}-${slug}`;
693
+ }
694
+
695
+ function numberById(
696
+ objects: readonly { readonly id: string }[],
697
+ kind: IdKind,
698
+ ): number {
699
+ let highest = 0;
700
+ for (const object of objects) {
701
+ // The store key carries the repository; the number lives in the bare id.
702
+ const parsed = parseId(bareId(object.id), kind);
703
+ if (parsed !== undefined && parsed.number > highest) {
704
+ highest = parsed.number;
705
+ }
706
+ }
707
+ return highest;
708
+ }
709
+
710
+ /**
711
+ * The store key of a plan or task. Ids are unique within a repository only, so
712
+ * the repository name namespaces the key and two repositories may both hold
713
+ * `T-0001-work`.
714
+ */
715
+ export function storeKey(repository: string, id: string): string {
716
+ return `${repository}/${id}`;
717
+ }
718
+
719
+ /** The id a person sees and types: the key without its repository prefix. */
720
+ export function bareId(key: string): string {
721
+ const at = key.indexOf("/");
722
+ return at < 0 ? key : key.slice(at + 1);
723
+ }
724
+
725
+ /**
726
+ * The store key a task's `after` entry names: an entry with a repository
727
+ * prefix is already a key; a bare id (also what older tasks stored) is a task
728
+ * of the task's own repository.
729
+ */
730
+ export function dependencyKey(repository: string, entry: string): string {
731
+ return entry.includes("/") ? entry : storeKey(repository, entry);
732
+ }
733
+
734
+ /** How a dependency is named in a note: bare in its own repository. */
735
+ export function dependencyLabel(repository: string, key: string): string {
736
+ return keyRepository(key) === repository ? bareId(key) : key;
737
+ }
738
+
739
+ /** The repository part of a store key. */
740
+ export function keyRepository(key: string): string {
741
+ const at = key.indexOf("/");
742
+ return at < 0 ? "" : key.slice(0, at);
743
+ }
744
+
745
+ /**
746
+ * The next id for a repository. Numbers count up per repository and are never
747
+ * reused; the scan reads only that repository's objects, because the store key
748
+ * namespaces them.
749
+ */
750
+ export async function nextId(
751
+ store: ObjectStore,
752
+ type: "plan" | "task",
753
+ repository: string,
754
+ slug: string,
755
+ ): Promise<string> {
756
+ const all = await listAll(store, type);
757
+ const mine = all.filter(
758
+ (object) =>
759
+ isRecord(object.data) && object.data.repository === repository,
760
+ );
761
+ let number = numberById(mine, type) + 1;
762
+ for (;;) {
763
+ const id = formatId(type, number, slug);
764
+ if ((await store.get(type, storeKey(repository, id))) === undefined) {
765
+ return id;
766
+ }
767
+ number += 1;
768
+ }
769
+ }
770
+
771
+ /* ---------------------------------------------------------------------------
772
+ * The brief: a body, rework sections and a trailing changes section.
773
+ * ------------------------------------------------------------------------- */
774
+
775
+ interface Fence {
776
+ readonly char: "`" | "~";
777
+ readonly length: number;
778
+ }
779
+
780
+ function openingFence(line: string): Fence | undefined {
781
+ const match = /^\s{0,3}(`{3,}|~{3,})/.exec(line);
782
+ if (match === null) return undefined;
783
+ const run = match[1] ?? "";
784
+ const char = run[0];
785
+ if (char !== "`" && char !== "~") return undefined;
786
+ return { char, length: run.length };
787
+ }
788
+
789
+ function closesFence(line: string, fence: Fence): boolean {
790
+ const match = /^\s{0,3}(`{3,}|~{3,})\s*$/.exec(line);
791
+ if (match === null) return false;
792
+ const run = match[1] ?? "";
793
+ return run[0] === fence.char && run.length >= fence.length;
794
+ }
795
+
796
+ interface BriefHeadings {
797
+ readonly rework: number;
798
+ readonly changes: number;
799
+ }
800
+
801
+ /** Finds the first rework and changes headings that are not inside a fence. */
802
+ export function briefHeadings(brief: string): BriefHeadings {
803
+ const lines = brief.replace(/\r\n/g, "\n").split("\n");
804
+ let fence: Fence | undefined;
805
+ let rework = -1;
806
+ let changes = -1;
807
+ for (let index = 0; index < lines.length; index += 1) {
808
+ const line = lines[index] ?? "";
809
+ if (fence !== undefined) {
810
+ if (closesFence(line, fence)) fence = undefined;
811
+ continue;
812
+ }
813
+ const opened = openingFence(line);
814
+ if (opened !== undefined) {
815
+ fence = opened;
816
+ continue;
817
+ }
818
+ if (rework < 0 && /^##\s+Rework(?:\s|$)/.test(line)) rework = index;
819
+ if (changes < 0 && /^##\s+Changes\s*$/.test(line)) changes = index;
820
+ }
821
+ return { rework, changes };
822
+ }
823
+
824
+ export interface BriefParts {
825
+ readonly body: string;
826
+ readonly reworks: string;
827
+ readonly changes: string;
828
+ }
829
+
830
+ export function splitBrief(brief: string): BriefParts {
831
+ const text = brief.replace(/\r\n/g, "\n");
832
+ const lines = text.split("\n");
833
+ const { rework, changes } = briefHeadings(text);
834
+ const boundaries = [rework, changes].filter((index) => index >= 0);
835
+ const bodyEnd = boundaries.length === 0 ? lines.length : Math.min(...boundaries);
836
+ const tailStart = bodyEnd;
837
+ const body = lines.slice(0, bodyEnd).join("\n").trimEnd();
838
+ const changesStart = changes;
839
+ const reworksEnd =
840
+ changesStart > tailStart ? changesStart : lines.length;
841
+ const reworks =
842
+ rework >= 0
843
+ ? lines.slice(rework, reworksEnd).join("\n").trim()
844
+ : "";
845
+ const changeText =
846
+ changes >= 0 ? lines.slice(changes).join("\n").trimEnd() : "";
847
+ return { body, reworks, changes: changeText };
848
+ }
849
+
850
+ export function hasRework(brief: string): boolean {
851
+ return briefHeadings(brief).rework >= 0;
852
+ }
853
+
854
+ function tailStartOf(brief: string): number {
855
+ const { rework, changes } = briefHeadings(brief);
856
+ const indexes = [rework, changes].filter((index) => index >= 0);
857
+ return indexes.length === 0 ? -1 : Math.min(...indexes);
858
+ }
859
+
860
+ /**
861
+ * Replaces the text before the first real `## Rework` (or, when there is none,
862
+ * before the trailing `## Changes`). A heading inside a fenced block is text.
863
+ */
864
+ export function replaceBriefBody(brief: string, body: string): string {
865
+ const text = brief.replace(/\r\n/g, "\n");
866
+ const lines = text.split("\n");
867
+ const start = tailStartOf(text);
868
+ const tail = start < 0 ? "" : lines.slice(start).join("\n").trimEnd();
869
+ const next = body.replace(/\r\n/g, "\n").trimEnd();
870
+ if (tail.length === 0) return next;
871
+ return next.length === 0 ? tail : `${next}\n\n${tail}`;
872
+ }
873
+
874
+ /** Inserts a block before the trailing changes section, or at the end. */
875
+ function insertBeforeChanges(brief: string, block: string): string {
876
+ const text = brief.replace(/\r\n/g, "\n").trimEnd();
877
+ const { changes } = briefHeadings(text);
878
+ if (changes < 0) {
879
+ if (text.length === 0) return block;
880
+ return `${text}\n\n${block}`;
881
+ }
882
+ const lines = text.split("\n");
883
+ const before = lines.slice(0, changes).join("\n").trimEnd();
884
+ const after = lines.slice(changes).join("\n");
885
+ if (before.length === 0) return `${block}\n\n${after}`;
886
+ return `${before}\n\n${block}\n\n${after}`;
887
+ }
888
+
889
+ /** The clock a Changes entry's time comes from; a test replaces it. */
890
+ export const changeClock: { now: () => number } = { now: () => Date.now() };
891
+
892
+ const REASON_LIMIT = 160;
893
+
894
+ /**
895
+ * Appends one line to the trailing `## Changes` section, creating it. The
896
+ * entry keeps the time it happened (UTC, ISO) and the reason when there is one.
897
+ */
898
+ export function appendChange(
899
+ brief: string,
900
+ line: string,
901
+ reason?: string,
902
+ ): string {
903
+ const text = brief.replace(/\r\n/g, "\n").trimEnd();
904
+ const { changes } = briefHeadings(text);
905
+ const why = reason === undefined ? "" : oneLine(reason, REASON_LIMIT, true);
906
+ const said = oneLine(line);
907
+ const at = new Date(changeClock.now()).toISOString();
908
+ const entry = `- [${at}] ${said}${why.length === 0 ? "" : ` — ${why}`}`;
909
+ if (changes < 0) {
910
+ return text.length === 0
911
+ ? `## Changes\n${entry}`
912
+ : `${text}\n\n## Changes\n${entry}`;
913
+ }
914
+ return `${text}\n${entry}`;
915
+ }
916
+
917
+ const TIMED_ENTRY = /^- \[(\d{4}-\d{2}-\d{2}T[^\]]+Z)\] (.*)$/;
918
+
919
+ function two(value: number): string {
920
+ return String(value).padStart(2, "0");
921
+ }
922
+
923
+ /**
924
+ * The Changes section for a reader: each timed entry as `HH:MM text` in this
925
+ * host's local time, with a date line before the first entry of each day.
926
+ * An entry without a time stays as it was written.
927
+ */
928
+ export function renderChanges(changes: string): string {
929
+ const out: string[] = [];
930
+ let day = "";
931
+ for (const line of changes.split("\n")) {
932
+ if (/^##\s+Changes\s*$/.test(line)) continue;
933
+ const match = TIMED_ENTRY.exec(line);
934
+ const when = match === null ? new Date(Number.NaN) : new Date(match[1] ?? "");
935
+ if (match === null || Number.isNaN(when.getTime())) {
936
+ if (line.trim().length > 0) out.push(line);
937
+ continue;
938
+ }
939
+ const date = `${when.getFullYear()}-${two(when.getMonth() + 1)}-${two(when.getDate())}`;
940
+ if (date !== day) {
941
+ day = date;
942
+ if (out.length > 0) out.push("");
943
+ out.push(`**${date}**`, "");
944
+ }
945
+ out.push(`- ${two(when.getHours())}:${two(when.getMinutes())} ${match[2] ?? ""}`);
946
+ }
947
+ return out.join("\n");
948
+ }
949
+
950
+ function reworkCount(brief: string): number {
951
+ const lines = brief.replace(/\r\n/g, "\n").split("\n");
952
+ let fence: Fence | undefined;
953
+ let count = 0;
954
+ for (const line of lines) {
955
+ if (fence !== undefined) {
956
+ if (closesFence(line, fence)) fence = undefined;
957
+ continue;
958
+ }
959
+ const opened = openingFence(line);
960
+ if (opened !== undefined) {
961
+ fence = opened;
962
+ continue;
963
+ }
964
+ if (/^##\s+Rework(?:\s|$)/.test(line)) count += 1;
965
+ }
966
+ return count;
967
+ }
968
+
969
+ /** The word a Changes entry uses for who asked, where it differs from the section's source. */
970
+ const ASKER: Readonly<Record<string, string>> = {
971
+ "conflict with main": "conflict",
972
+ integration: "integrate",
973
+ };
974
+
975
+ /** Appends `## Rework <n> (<source>)`, then records the change. */
976
+ export function appendRework(
977
+ brief: string,
978
+ source: string,
979
+ text: string,
980
+ reason?: string,
981
+ ): string;
982
+ export function appendRework(
983
+ task: TaskData,
984
+ source: string,
985
+ text: string,
986
+ reason?: string,
987
+ ): TaskData;
988
+ export function appendRework(
989
+ value: string | TaskData,
990
+ source: string,
991
+ text: string,
992
+ reason?: string,
993
+ ): string | TaskData {
994
+ const cleanSource = source.trim();
995
+ if (cleanSource.length === 0) {
996
+ throw new DevError("source", "must be a non-empty string");
997
+ }
998
+ const brief = typeof value === "string" ? value : value.brief;
999
+ const number = reworkCount(brief) + 1;
1000
+ const body = text.trim();
1001
+ const block = `## Rework ${number} (${cleanSource})${body.length === 0 ? "" : `\n\n${body}`}`;
1002
+ const withRework = insertBeforeChanges(brief, block);
1003
+ const asked = ASKER[cleanSource] ?? cleanSource;
1004
+ const firstLine =
1005
+ body.split("\n").find((line) => line.trim().length > 0) ?? "";
1006
+ const why = oneLine(reason ?? firstLine.replace(/^\s*[-*]\s+/, ""), REASON_LIMIT, true);
1007
+ const next = appendChange(
1008
+ withRework,
1009
+ `rework ${number} — ${asked}${why.length === 0 ? "" : `: ${why}`}`,
1010
+ );
1011
+ return typeof value === "string" ? next : { ...value, brief: next };
1012
+ }
1013
+
1014
+ /** The Markdown of the brief body, without rework or changes. */
1015
+ export function briefBody(brief: string): string {
1016
+ return splitBrief(brief).body;
1017
+ }
1018
+
1019
+ /** The Markdown of the rework sections, without the changes section. */
1020
+ export function reworkBody(brief: string): string {
1021
+ return splitBrief(brief).reworks;
1022
+ }
1023
+
1024
+ /** The Markdown of the trailing changes section. */
1025
+ export function changesBody(brief: string): string {
1026
+ return splitBrief(brief).changes;
1027
+ }
1028
+
1029
+ /** Replaces the body and records the edit, unless the body did not change. */
1030
+ export function editBrief(brief: string, body: string): string {
1031
+ if (briefBody(brief) === body.replace(/\r\n/g, "\n").trimEnd()) return brief;
1032
+ return appendChange(replaceBriefBody(brief, body), "brief edited");
1033
+ }
1034
+
1035
+ /* ---------------------------------------------------------------------------
1036
+ * States and dependencies.
1037
+ * ------------------------------------------------------------------------- */
1038
+
1039
+ /** The state a plan row shows: `finished` is derived from its tasks. */
1040
+ export function planState(plan: PlanData): PlanState {
1041
+ if (plan.status === "cancelled") return "cancelled";
1042
+ if (
1043
+ plan.status === "confirmed" &&
1044
+ plan.taskCount > 0 &&
1045
+ plan.mergedCount + plan.cancelledCount === plan.taskCount
1046
+ ) {
1047
+ return "finished";
1048
+ }
1049
+ return plan.status;
1050
+ }
1051
+
1052
+ /** What a task adds to a plan's cost: micros and quality, or none. */
1053
+ export function taskCostShare(
1054
+ task: TaskData,
1055
+ ): { readonly micros: number; readonly quality: "exact" | "estimated" | "incomplete" } | undefined {
1056
+ if (typeof task.cost !== "number" || !Number.isFinite(task.cost)) return undefined;
1057
+ // A cost written before its quality was recorded counts as estimated.
1058
+ const quality =
1059
+ task.costQuality === "exact" || task.costQuality === "incomplete"
1060
+ ? task.costQuality
1061
+ : "estimated";
1062
+ return { micros: Math.round(task.cost * 1_000_000), quality };
1063
+ }
1064
+
1065
+ /** The totals after a task's share changes from `before` to `after`. */
1066
+ export function shiftCostTotals(
1067
+ totals: PlanCostTotals | undefined,
1068
+ before: TaskData | undefined,
1069
+ after: TaskData | undefined,
1070
+ ): PlanCostTotals {
1071
+ const next: Record<string, number> = {
1072
+ exactMicros: totals?.exactMicros ?? 0,
1073
+ estimatedMicros: totals?.estimatedMicros ?? 0,
1074
+ incompleteMicros: totals?.incompleteMicros ?? 0,
1075
+ exactTasks: totals?.exactTasks ?? 0,
1076
+ estimatedTasks: totals?.estimatedTasks ?? 0,
1077
+ incompleteTasks: totals?.incompleteTasks ?? 0,
1078
+ };
1079
+ const apply = (task: TaskData | undefined, sign: 1 | -1): void => {
1080
+ const share = task === undefined ? undefined : taskCostShare(task);
1081
+ if (share === undefined) return;
1082
+ next[`${share.quality}Micros`] = (next[`${share.quality}Micros`] ?? 0) + sign * share.micros;
1083
+ next[`${share.quality}Tasks`] = (next[`${share.quality}Tasks`] ?? 0) + sign;
1084
+ };
1085
+ apply(before, -1);
1086
+ apply(after, 1);
1087
+ return {
1088
+ exactMicros: next.exactMicros ?? 0,
1089
+ estimatedMicros: next.estimatedMicros ?? 0,
1090
+ incompleteMicros: next.incompleteMicros ?? 0,
1091
+ exactTasks: next.exactTasks ?? 0,
1092
+ estimatedTasks: next.estimatedTasks ?? 0,
1093
+ incompleteTasks: next.incompleteTasks ?? 0,
1094
+ };
1095
+ }
1096
+
1097
+ /** The plan's total cost in `costNote` form, or undefined with no costed task. */
1098
+ function planCost(plan: PlanData): string | undefined {
1099
+ const t = plan.costTotals;
1100
+ if (t === undefined) return undefined;
1101
+ const fields = [
1102
+ t.exactMicros, t.estimatedMicros, t.incompleteMicros,
1103
+ t.exactTasks, t.estimatedTasks, t.incompleteTasks,
1104
+ ];
1105
+ // A stored plan may carry a malformed total; show no cost rather than NaN.
1106
+ if (!fields.every((n) => typeof n === "number" && Number.isFinite(n))) return undefined;
1107
+ const tasks = t.exactTasks + t.estimatedTasks + t.incompleteTasks;
1108
+ if (tasks <= 0) return undefined;
1109
+ const micros = t.exactMicros + t.estimatedMicros + t.incompleteMicros;
1110
+ const symbol = t.incompleteTasks > 0 ? "≥" : t.estimatedTasks > 0 ? "~" : "";
1111
+ return `${symbol}$${(micros / 1_000_000).toFixed(2)}`;
1112
+ }
1113
+
1114
+ /** `<merged>/<total> · <cost> · <priority> // <concurrency>`; the badge carries auto. */
1115
+ export function planNote(plan: PlanData): string {
1116
+ // Cancelled tasks are not part of the total the owner is working through.
1117
+ const progress = `${plan.mergedCount}/${plan.taskCount - plan.cancelledCount}`;
1118
+ const cost = planCost(plan);
1119
+ // Only a confirmed plan says how many tasks wait for the owner.
1120
+ const waiting =
1121
+ planState(plan) === "confirmed" && (plan.waitingCount ?? 0) > 0
1122
+ ? [`${plan.waitingCount} waiting`]
1123
+ : [];
1124
+ const parts = [
1125
+ progress,
1126
+ ...waiting,
1127
+ ...(cost === undefined ? [] : [cost]),
1128
+ plan.priority,
1129
+ ...(plan.flowHeld === undefined ? [] : [plan.flowHeld]),
1130
+ ];
1131
+ return `${parts.join(" · ")} // ${plan.concurrency}`;
1132
+ }
1133
+
1134
+ export function planDataOf(data: Record<string, unknown>): PlanData {
1135
+ return planData(data);
1136
+ }
1137
+
1138
+ export function taskDataOf(data: Record<string, unknown>): TaskData {
1139
+ return taskData(data);
1140
+ }
1141
+
1142
+ export function priorityIndex(priority: Priority): number {
1143
+ return PRIORITIES.indexOf(priority);
1144
+ }
1145
+
1146
+ export function higherPriority(priority: Priority): Priority | undefined {
1147
+ const index = priorityIndex(priority);
1148
+ return index <= 0 ? undefined : PRIORITIES[index - 1];
1149
+ }
1150
+
1151
+ /** A task is open until it merged or was cancelled. */
1152
+ export function isOpenTask(task: TaskData): boolean {
1153
+ return task.phase !== "merged" && task.phase !== "cancelled";
1154
+ }
1155
+
1156
+ /**
1157
+ * The integrate step is working: it marks the attempt until it writes a result.
1158
+ * A task that ended (cancelled while it queued or checked) is not integrating,
1159
+ * whatever mark its attempt still carries.
1160
+ */
1161
+ export function isIntegrating(task: TaskData): boolean {
1162
+ if (!isOpenTask(task)) return false;
1163
+ const run = task.attempt?.integrating;
1164
+ return typeof run === "string" && run.length > 0;
1165
+ }