@jive-sh/workflow-platform 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +50 -5
  2. package/dist/dashboard/queue-table.js +10 -2
  3. package/dist/dashboard/queue-table.js.map +1 -1
  4. package/dist/dashboard/spending-words.js +32 -0
  5. package/dist/dashboard/spending-words.js.map +1 -0
  6. package/dist/index.js +13 -4
  7. package/dist/index.js.map +1 -1
  8. package/dist/pick-wakes.js +1 -0
  9. package/dist/pick-wakes.js.map +1 -1
  10. package/dist/project.js +0 -4
  11. package/dist/project.js.map +1 -1
  12. package/dist/queue-counts.js +7 -1
  13. package/dist/queue-counts.js.map +1 -1
  14. package/dist/spending-limit.js +87 -0
  15. package/dist/spending-limit.js.map +1 -0
  16. package/dist/steps.js +150 -17
  17. package/dist/steps.js.map +1 -1
  18. package/dist/storage/budgets.js +27 -2
  19. package/dist/storage/budgets.js.map +1 -1
  20. package/dist/storage/sqlite-store.js +14 -3
  21. package/dist/storage/sqlite-store.js.map +1 -1
  22. package/dist/storage/task-store.js +10 -1
  23. package/dist/storage/task-store.js.map +1 -1
  24. package/dist/tasks.js +35 -5
  25. package/dist/tasks.js.map +1 -1
  26. package/dist/views/format.js +2 -0
  27. package/dist/views/format.js.map +1 -1
  28. package/dist/views/runs-now.js +30 -2
  29. package/dist/views/runs-now.js.map +1 -1
  30. package/dist/views/workflows-view.js +9 -2
  31. package/dist/views/workflows-view.js.map +1 -1
  32. package/package.json +1 -1
  33. package/src/dashboard/dashboard.css +5 -0
  34. package/src/dashboard/queue-bar.tsx +5 -5
  35. package/src/dashboard/queue-table.ts +17 -3
  36. package/src/dashboard/spending-limit-control.tsx +50 -0
  37. package/src/dashboard/spending-words.ts +50 -0
  38. package/src/dashboard/workflow-dag.tsx +1 -1
  39. package/src/dashboard/workflow-drilldown.tsx +5 -5
  40. package/src/dashboard/workflows-dashboard.tsx +28 -3
  41. package/src/index.ts +13 -4
  42. package/src/pick-wakes.ts +3 -0
  43. package/src/project.ts +35 -0
  44. package/src/queue-counts.ts +8 -1
  45. package/src/spending-limit.ts +155 -0
  46. package/src/steps.ts +180 -30
  47. package/src/storage/budgets.ts +34 -2
  48. package/src/storage/sqlite-store.ts +15 -4
  49. package/src/storage/step-records.ts +2 -0
  50. package/src/storage/task-store.ts +17 -1
  51. package/src/tasks.ts +43 -5
  52. package/src/views/format.ts +3 -0
  53. package/src/views/runs-now.ts +21 -3
  54. package/src/views/workflows-view.ts +27 -4
@@ -0,0 +1,155 @@
1
+ /**
2
+ * THE SPENDING LIMIT: ONE SETTING FOR THE WHOLE ACCOUNT, "AGENTS STOP AT X% OF THE WEEK". Alex, 2026-11-20: "ideally the
3
+ * workflow platform offers a configurable spending limit", and, of this design, "yes to building the spending limit".
4
+ *
5
+ * While the project's newest good reading of its week (`WorkflowProject.weekUsage`) is at or past X, every agent step of
6
+ * every workflow waits before its agent call, as it waits at an agents' limit of 0 (`steps.ts` `untilAgentSlot`), its record
7
+ * saying why in words (`spendingWait`). An agent call already going is never cut off. The steps go on by themselves once a
8
+ * reading is below X, which the week's reset brings: the project tells the platform of each reading it takes
9
+ * (`readingTaken`), and a verdict that changed wakes every waiting step. None is set: X is 95 (`DEFAULT_SPENDING_LIMIT_PERCENT`).
10
+ *
11
+ * IT JUDGES THE ACCOUNT'S WEEK, NOT A COUNT OF TOKENS, because the week is the one figure that also counts spending the
12
+ * platform cannot see: agent threads run by hand, outside any workflow, which no step record holds. They were 73% of the
13
+ * spending of the week that ran out on 2026-11-01, 57 hours before its reset (the first project's `usage/pace.ts`).
14
+ *
15
+ * A READING THAT FAILS OR GROWS OLD NEVER LIFTS IT. The rule judges the newest good reading, however old, so a hold stands
16
+ * until a good reading below X, and a page says the reading is stale and why. That holds past the reset the reading named
17
+ * too: with every read failing, agents wait until one succeeds, rather than spend on a week nobody can see. A reading that
18
+ * cannot be read at all holds every agent step, as limits that cannot be read hold their runs. With no good reading yet
19
+ * there is nothing to judge, and nothing is held. A project that reads no week has no spending limit.
20
+ */
21
+ import { Effect, pipe, Result } from 'effect';
22
+ import type { PickWakes } from './pick-wakes';
23
+ import type { WeekUsage, WeekUsageNow, WeekUsageReading } from './project';
24
+ import { SET_SPENDING_LIMIT_SQL, type LimitStore, type StoredSpendingLimit } from './storage/budgets';
25
+ import type { StorageError } from './storage/storage-error';
26
+ import { percentCut } from './views/format';
27
+
28
+ /** The percent of the week at which agents stop where none is set. */
29
+ export const DEFAULT_SPENDING_LIMIT_PERCENT = 95;
30
+
31
+ /** The spending limit against the newest reading of the week, for a page and for the rule. */
32
+ export interface SpendingLimitState {
33
+ /** The percent of the week at which agents stop. */
34
+ readonly limitPercent: number;
35
+ /** When it was set, unix seconds; none while it is the default. */
36
+ readonly setAt: number | null;
37
+ /** The newest good reading, which the verdict rests on; none before the first. */
38
+ readonly reading: WeekUsageReading | null;
39
+ /** The newest read, where it failed after that one. */
40
+ readonly failedSince: WeekUsageNow['failedSince'];
41
+ /** Whether the reading is stale: a read failed since, or it is older than the project's time between readings allows. */
42
+ readonly stale: boolean;
43
+ /** Whether every agent step waits now. */
44
+ readonly holds: boolean;
45
+ }
46
+
47
+ /** What every agent step's record says while the limit holds it. */
48
+ export const spendingWait = (r: { readonly usedPercent: number; readonly limitPercent: number }): string =>
49
+ `waits: the week's use is ${percentCut(r.usedPercent)}, at or past the spending limit of ${r.limitPercent}%`;
50
+
51
+ /** How every wait the spending limit gives starts, its unreadable one included. */
52
+ const SPENDING_WAIT_START = "waits: the week's use ";
53
+
54
+ /** Whether what a step waits on is the spending limit: what a page counts its waiting steps by. Pure. */
55
+ export const isSpendingLimitWait = (why: string): boolean => why.startsWith(SPENDING_WAIT_START);
56
+
57
+ /** The limit against the week now. Pure. */
58
+ export const judgeSpending = (input: {
59
+ readonly limit: StoredSpendingLimit | null;
60
+ readonly usage: WeekUsageNow;
61
+ readonly staleAfterSeconds: number;
62
+ readonly now: number;
63
+ }): SpendingLimitState => {
64
+ const limitPercent = input.limit === null ? DEFAULT_SPENDING_LIMIT_PERCENT : input.limit.weekPercent;
65
+ const good = input.usage.good;
66
+ return {
67
+ limitPercent,
68
+ setAt: input.limit === null ? null : input.limit.changedAt,
69
+ reading: good,
70
+ failedSince: input.usage.failedSince,
71
+ stale: good !== null && (input.usage.failedSince !== null || input.now - good.readAt > input.staleAfterSeconds),
72
+ holds: good !== null && good.usedPercent >= limitPercent,
73
+ };
74
+ };
75
+
76
+ /**
77
+ * What the limit does to an agent step now. `why` is what its record says (`spendingWait`); `unavailable`, in words, is why
78
+ * no agent can be had until a reading or the limit changes, the reason a run with a task ends and marks it as needing an
79
+ * agent (`steps.ts` `untilAgentSlot`). An unreadable week has none: the step waits, since the next read may well succeed.
80
+ */
81
+ export interface SpendingHold {
82
+ readonly why: string;
83
+ readonly unavailable: string | null;
84
+ }
85
+
86
+ export interface SpendingLimit {
87
+ /** What the limit does to an agent step now; none while it holds nothing. */
88
+ readonly holdsAgents: () => Effect.Effect<SpendingHold | null>;
89
+ /** The limit against the newest reading, for a page; none for a project that reads no week. */
90
+ readonly state: (now: number) => Effect.Effect<SpendingLimitState | null, StorageError>;
91
+ /**
92
+ * The project took a reading of its week. Where the verdict changed since the last one, or a step found the week
93
+ * unreadable since, every waiting step is woken to judge it again: a reading below the limit lets them go.
94
+ */
95
+ readonly readingTaken: () => Effect.Effect<void>;
96
+ /**
97
+ * THE ONE WAY TO SET IT, for the project's route: checks the percent asked, stores it with the platform's statement
98
+ * through the project's `write`, wakes every waiting step (relayed to the process its runs wait in), and says in the log
99
+ * who asked (`from`), as the routes that set a workflow's limits do. A refused one changes nothing.
100
+ */
101
+ readonly set: <E>(r: {
102
+ readonly weekPercent: unknown;
103
+ readonly from: string;
104
+ readonly write: (statement: { readonly sql: string; readonly params: ReadonlyArray<number> }) => Effect.Effect<unknown, E>;
105
+ }) => Effect.Effect<{ readonly ok: true; readonly weekPercent: number } | { readonly ok: false; readonly error: string }, E>;
106
+ }
107
+
108
+ export const makeSpendingLimit = (deps: { readonly store: LimitStore; readonly usage: WeekUsage | null; readonly wakes: PickWakes }): SpendingLimit => {
109
+ const { usage } = deps;
110
+ const state = (now: number): Effect.Effect<SpendingLimitState | null, StorageError> =>
111
+ usage === null ? Effect.succeed(null) : Effect.map(
112
+ Effect.all({ limit: deps.store.spendingLimit(), week: usage.now() }),
113
+ ({ limit, week }) => judgeSpending({ limit, usage: week, staleAfterSeconds: usage.staleAfterSeconds, now }),
114
+ );
115
+ /** What the last reading told held, in this process; none before the first. */
116
+ let heldAtLastReading: boolean | null = null;
117
+ /** A step found the week unreadable since the last reading, so it waits for a wake that a changed verdict alone may not bring. */
118
+ let unreadSinceLastReading = false;
119
+ return {
120
+ holdsAgents: () => pipe(
121
+ state(Date.now() / 1000),
122
+ Effect.map((s): SpendingHold | null => (s === null || !s.holds || s.reading === null ? null : {
123
+ why: spendingWait({ usedPercent: s.reading.usedPercent, limitPercent: s.limitPercent }),
124
+ unavailable: `the week's use is ${percentCut(s.reading.usedPercent)}, at or past the spending limit of ${s.limitPercent}%`,
125
+ })),
126
+ Effect.catchTag('StorageError', (e) => Effect.sync((): SpendingHold => {
127
+ unreadSinceLastReading = true;
128
+ return { why: `waits: the week's use could not be read (${e.reason}), so the spending limit holds every agent step`, unavailable: null };
129
+ })),
130
+ ),
131
+ state,
132
+ readingTaken: () => Effect.gen(function* () {
133
+ const judged = yield* Effect.result(state(Date.now() / 1000));
134
+ if (Result.isFailure(judged)) return yield* Effect.logError(`[spending limit] a reading was taken and could not be judged: ${judged.failure.reason}`);
135
+ const holds = judged.success !== null && judged.success.holds;
136
+ if (holds === heldAtLastReading && !unreadSinceLastReading) return;
137
+ if (holds !== heldAtLastReading && judged.success !== null) {
138
+ yield* Effect.log(`[spending limit] ${holds ? 'holds every agent step' : 'holds nothing'}: the week's use is ${judged.success.reading === null ? 'not read yet' : percentCut(judged.success.reading.usedPercent)}, the limit ${judged.success.limitPercent}%`);
139
+ }
140
+ heldAtLastReading = holds;
141
+ unreadSinceLastReading = false;
142
+ deps.wakes.wakeEveryPick(holds ? 'a reading at or past the spending limit' : 'a reading below the spending limit');
143
+ }),
144
+ set: (r) => Effect.gen(function* () {
145
+ const weekPercent = r.weekPercent;
146
+ if (typeof weekPercent !== 'number' || !Number.isInteger(weekPercent) || weekPercent < 0 || weekPercent > 100) {
147
+ return { ok: false as const, error: 'weekPercent must be a whole number from 0 to 100' };
148
+ }
149
+ yield* r.write({ sql: SET_SPENDING_LIMIT_SQL, params: [weekPercent, Date.now() / 1000] });
150
+ deps.wakes.wakeEveryPick('the spending limit set');
151
+ yield* Effect.log(`[spending limit] ${weekPercent}%, from ${r.from}`);
152
+ return { ok: true as const, weekPercent };
153
+ }),
154
+ };
155
+ };
package/src/steps.ts CHANGED
@@ -54,7 +54,8 @@ import type { EngineRecords } from './storage/engine-records';
54
54
  import { AGENT_BEAT_MS, noSpend, type StepRecords, type StepScope, type StepSpend } from './storage/step-records';
55
55
  import type { InputRecords } from './storage/input-records';
56
56
  import type { StorageError } from './storage/storage-error';
57
- import { inPickOrder, listOf, queueOrder, type PendingWork, type TaskInputs, type Tasks, type TaskSummary } from './tasks';
57
+ import type { SpendingHold } from './spending-limit';
58
+ import { inPickOrder, listOf, queueOrder, type PendingWork, type TaskInputs, type TaskRef, type Tasks, type TaskSummary } from './tasks';
58
59
 
59
60
  export { A_STEP_FAILS, edgeDeclared, isRetry, RUN_ENDS, RUN_STARTS, type StepEdge } from './graph';
60
61
 
@@ -94,7 +95,29 @@ export const STOOD_DOWN = 'stood down: its workflow has more runs going than its
94
95
  * (`pick-wakes.ts` `releaseWaiting`): its run stands down untried, and the next process starts one.
95
96
  */
96
97
  export const HANDED_OVER = 'stood down: its process is handing its runs to the next';
97
- export const isStoodDown = (failure: unknown): boolean => failure === STOOD_DOWN || failure === HANDED_OVER;
98
+ /**
99
+ * What a step of a run a sub-workflow step started fails with once the run above it has ended: nothing is left to read its
100
+ * result, so it does no more work. Two runs of Write C went on writing, an agent each, for ten minutes after the runs of
101
+ * Decompile above them had failed (2026-11-19).
102
+ */
103
+ export const ABOVE_ENDED = 'stood down: the run above it has ended';
104
+ /**
105
+ * What an agent step of a run with a task fails with where no agent can be had (`untilAgentSlot`): its task went to the
106
+ * back of its queue, marked as needing an agent, and the run gives its slot up untried.
107
+ */
108
+ export const NEEDS_AN_AGENT_STOOD_DOWN = 'stood down: no agent can be had, so its task went to the back of its queue, marked as needing one';
109
+ export const isStoodDown = (failure: unknown): boolean =>
110
+ failure === STOOD_DOWN || failure === HANDED_OVER || failure === ABOVE_ENDED || failure === NEEDS_AN_AGENT_STOOD_DOWN;
111
+
112
+ /** Why no agent can be had at an agents' limit of 0, in words. */
113
+ export const AGENTS_LIMIT_ZERO = "its agents' limit is 0";
114
+
115
+ /**
116
+ * Whether an agent step may take an agent now. Where not, `why` is what its record says, and `unavailable`, in words, is why
117
+ * none can be had until a limit or a reading changes (an agents' limit of 0, the spending limit); none where one may free
118
+ * when another run's agent step ends, or the limits could not be read.
119
+ */
120
+ export type AgentSlot = { readonly free: true } | { readonly free: false; readonly why: string; readonly unavailable: string | null };
98
121
 
99
122
  /** Whether a run is surplus: it is past the budget in the workflow's runs, oldest first. A run not listed is not counted. Pure. */
100
123
  export const surplusRun = (oldestFirst: ReadonlyArray<string>, run: string, budget: number): boolean => oldestFirst.indexOf(run) >= budget;
@@ -149,6 +172,8 @@ export interface StepDeclaration {
149
172
  readonly perItem?: boolean;
150
173
  /** Whether it picks its run's work, waiting while there is none. */
151
174
  readonly picks?: boolean;
175
+ /** Whether its result names the item its run works on (`subject`), which later steps inherit. */
176
+ readonly namesItem?: boolean;
152
177
  /** The paths, from the project's root, whose changed files are counted to it: where it may write and where it writes. */
153
178
  readonly writes?: ReadonlyArray<string>;
154
179
  }
@@ -295,7 +320,7 @@ export interface AgentBudgetRules {
295
320
  readonly standsDown: (workflow: string, run: string) => Effect.Effect<boolean>;
296
321
  readonly waitsForWork: (workflow: string, run: string) => Effect.Effect<boolean>;
297
322
  /** Its workflow's other runs in an agent step now are fewer than its agents' limit; why not, when they are not. */
298
- readonly agentSlot: (workflow: string, run: string) => Effect.Effect<{ readonly free: true } | { readonly free: false; readonly why: string }>;
323
+ readonly agentSlot: (workflow: string, run: string) => Effect.Effect<AgentSlot>;
299
324
  }
300
325
 
301
326
  /** A workflow: what it states about itself, then `Workflow.make`'s own name and options. */
@@ -322,6 +347,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
322
347
  readonly inputs: InputRecords;
323
348
  /** A workflow's queue changed with no wake of its Picks: one of them claimed an item (`queue-counts.ts`). */
324
349
  readonly queueChanged: (workflow: string) => void;
350
+ /** What the spending limit does to an agent step now; none while it holds nothing (`spending-limit.ts`). */
351
+ readonly spendingHoldsAgents: () => Effect.Effect<SpendingHold | null>;
325
352
  }) => {
326
353
  const { stepRecords: records, stepFiles } = deps;
327
354
  type Declaration = WorkflowDeclaration<Phase, R>;
@@ -329,6 +356,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
329
356
  const PICKING = new Map<string, Semaphore.Semaphore>();
330
357
  const RUN_ENDED = new Set<() => void>();
331
358
  const undeclaredSaid = new Set<string>();
359
+ /** Each workflow's run items a mark was refused for, said once (`markedAsNeedingAnAgent`). */
360
+ const offItsListSaid = new Set<string>();
332
361
  /**
333
362
  * EACH RUN'S LAST STEP, as this process ran it, until the run ends. A run resumed from another process has none here, and
334
363
  * the records of that process say; a record this process wrote for a run that has ended is no step of this one. Read from
@@ -442,39 +471,95 @@ export const makeSteps = <Phase extends string, R>(deps: {
442
471
  ),
443
472
  waitsForWork: (workflow, run) => pipe(pastItsRunLimit(workflow, run), Effect.map((past) => !past), Effect.catchTag('StorageError', unreadLimits(workflow, () => true))),
444
473
  // The other runs of the workflow at its top that an agent works for, a waiting one not counted, against that
445
- // workflow's agents' limit: at 0 none is ever free, and its runs wait at their first agent step until the limit is raised.
474
+ // workflow's agents' limit: at 0 none is ever free, which no agent ending changes.
446
475
  agentSlot: (workflow, run) => pipe(
447
476
  topOf(workflow, run),
448
- Effect.flatMap((top) => Effect.flatMap(limitsOf(top.workflow), (w): Effect.Effect<{ readonly free: true } | { readonly free: false; readonly why: string }, StorageError> => {
477
+ Effect.flatMap((top) => Effect.flatMap(limitsOf(top.workflow), (w): Effect.Effect<AgentSlot, StorageError> => {
449
478
  const agents = w === null ? null : w.agents;
450
479
  if (agents === null) return Effect.succeed({ free: true });
451
- if (agents === 0) return Effect.succeed({ free: false, why: 'waits for an agent: its agents\x27 limit is 0' });
452
- return Effect.map(Effect.all({ runs: runsOldestFirst([top.workflow]), inAgentStep: records.runsInAgentStep(top.workflow) }), ({ runs, inAgentStep }) => {
480
+ if (agents === 0) return Effect.succeed({ free: false, why: `waits for an agent: ${AGENTS_LIMIT_ZERO}`, unavailable: AGENTS_LIMIT_ZERO });
481
+ return Effect.map(Effect.all({ runs: runsOldestFirst([top.workflow]), inAgentStep: records.runsInAgentStep(top.workflow) }), ({ runs, inAgentStep }): AgentSlot => {
453
482
  const going = new Set(runs);
454
483
  const busy = inAgentStep.filter((r) => r !== top.run && going.has(r)).length;
455
- return busy < agents ? { free: true } : { free: false, why: `waits for an agent: ${busy} of its ${agents} in use` };
484
+ return busy < agents ? { free: true } : { free: false, why: `waits for an agent: ${busy} of its ${agents} in use`, unavailable: null };
456
485
  });
457
486
  })),
458
- Effect.catchTag('StorageError', unreadLimits(workflow, (why) => ({ free: false as const, why: `waits for an agent: its limits could not be read (${why})` }))),
487
+ Effect.catchTag('StorageError', unreadLimits(workflow, (why): AgentSlot => ({ free: false, why: `waits for an agent: its limits could not be read (${why})`, unavailable: null }))),
459
488
  ),
460
489
  }),
461
490
  });
462
491
 
492
+ /** The task a run at the top works on: its workflow's, where that workflow has a list, on the run's item; none otherwise. */
493
+ const taskOfTop = (top: { readonly run: string; readonly workflow: string }): Effect.Effect<TaskRef | null> => {
494
+ const d = DECLARED.get(top.workflow);
495
+ if (d === undefined || !hasAList(d)) return Effect.succeed(null);
496
+ return Effect.map(Effect.orElseSucceed(records.subjectOfRun(top.run), () => null), (item) => (item === null ? null : { workflow: top.workflow, item }));
497
+ };
498
+
499
+ /**
500
+ * Marks the task of the run at the top as needing an agent; whether it was marked (a run with no task, or no store, is not).
501
+ *
502
+ * ONLY A TASK ITS PICK READS IS MARKED (`tasks.ts` `readByItsPick`). A mark on any other passes over nothing: the run
503
+ * ends, the next takes the same work and ends the same way. Fix conflicts' runs named conflicts while its list named
504
+ * functions, and it took the same 3 names 907 times in 75 minutes (2026-11-20). Such a run is a fault in its workflow,
505
+ * which names its run's item differently from its list: in a test it fails the run, and live it is said once, and the
506
+ * run waits for an agent as a run with no task does. A task whose state cannot be read is marked as before.
507
+ */
508
+ const markedAsNeedingAnAgent = (top: { readonly run: string; readonly workflow: string }, step: string, why: string): Effect.Effect<boolean> =>
509
+ Effect.flatMap(taskOfTop(top), (task) => {
510
+ if (task === null) return Effect.succeed(false);
511
+ return Effect.flatMap(Effect.orElseSucceed(deps.tasks.readByItsPick(task), () => true), (read) => {
512
+ if (read) return deps.tasks.markNeedsAgent({ task, by: { workflow: top.workflow, run: top.run, step }, why });
513
+ const fault = `${top.workflow}: its run ${top.run} works on ${task.item}, which is not a task its Pick reads (not on its list, nor returned to its queue), so a mark at ${step} would pass over nothing; it waits for an agent instead`;
514
+ if (process.env.NODE_ENV === 'test') return Effect.die(new Error(fault));
515
+ if (!offItsListSaid.has(`${top.workflow}\n${task.item}`)) {
516
+ offItsListSaid.add(`${top.workflow}\n${task.item}`);
517
+ console.error(`[agents] ${fault}`);
518
+ }
519
+ return Effect.succeed(false);
520
+ });
521
+ });
522
+
523
+ /**
524
+ * WHY NO AGENT CAN BE HAD FOR A WORKFLOW'S RUNS NOW, in words; none where one can: the spending limit holds, or its
525
+ * agents' limit is 0. While it says so, its Pick passes over its tasks marked as needing an agent (`queueNow`,
526
+ * `pickOrder`), and takes them in their queue's order again once an agent can be had. A limit that cannot be read passes
527
+ * over none.
528
+ */
529
+ const agentsUnavailable = (workflow: string): Effect.Effect<string | null> => Effect.gen(function* () {
530
+ const held = yield* deps.spendingHoldsAgents();
531
+ if (held !== null && held.unavailable !== null) return held.unavailable;
532
+ const limits = yield* Effect.orElseSucceed(limitsOf(workflow), () => null);
533
+ return limits !== null && limits.agents === 0 ? AGENTS_LIMIT_ZERO : null;
534
+ });
535
+
463
536
  /**
464
537
  * AN AGENT STEP TAKES AN AGENT SLOT FIRST: with its workflow's agents' limit in use by its other runs it waits, its record
465
538
  * saying so, until an agent step ends or a limit changes (`pick-wakes.ts`), and never polls. Its record starts again when
466
539
  * it has a slot, since the wait was no work. A limit lowered meanwhile to 0 agents, or below its run, stands it down.
540
+ * While the spending limit holds (`spending-limit.ts`) every agent step waits the same way, in every workflow, until a
541
+ * reading below it or a new limit wakes it.
542
+ *
543
+ * A RUN WITH A TASK DOES NOT WAIT WHERE NO AGENT CAN BE HAD (its workflow's agents' limit is 0, or the spending limit
544
+ * holds): it marks its task as needing an agent, which puts it at the back of its queue (`tasks.ts` `markNeedsAgent`),
545
+ * and ends, giving its run slot to work that needs none. Its Pick passes over such tasks while no agent is available
546
+ * (`agentsUnavailable`). Waiting, a few such runs filled every run slot of Decompile and nothing behind them moved
547
+ * (2026-11-20). A run with no task, or one waiting for an agent another run holds, still waits here.
548
+ *
549
+ * A step that gets past it took an agent, and clears its task's mark when it ends (`measured`, `agentStepRan`).
467
550
  */
468
- const untilAgentSlot = (instance: { readonly workflow: { readonly _tag: string }; readonly executionId: string }, record: () => number | null) => Effect.gen(function* () {
551
+ const untilAgentSlot = (instance: { readonly workflow: { readonly _tag: string }; readonly executionId: string }, step: string, record: () => number | null) => Effect.gen(function* () {
469
552
  const rules = yield* AgentBudgets;
470
553
  const workflow = instance.workflow._tag;
471
554
  // An agent is freed, and a limit set, on the workflow at the top of this run: its wakes are the ones this wait hears.
472
- const heardOn = (yield* Effect.orElseSucceed(topOf(workflow, instance.executionId), () => ({ run: instance.executionId, workflow }))).workflow;
555
+ const top = yield* Effect.orElseSucceed(topOf(workflow, instance.executionId), () => ({ run: instance.executionId, workflow }));
556
+ const heardOn = top.workflow;
473
557
  let waited = false;
474
558
  for (;;) {
475
559
  const wakes = deps.wakes.pickWakesSoFar(heardOn);
476
560
  if (yield* rules.standsDown(workflow, instance.executionId)) return yield* Effect.fail(STOOD_DOWN);
477
- const slot = yield* rules.agentSlot(workflow, instance.executionId);
561
+ const spendingHeld = yield* deps.spendingHoldsAgents();
562
+ const slot: AgentSlot = spendingHeld !== null ? { free: false, why: spendingHeld.why, unavailable: spendingHeld.unavailable } : yield* rules.agentSlot(workflow, instance.executionId);
478
563
  const id = record();
479
564
  if (slot.free) {
480
565
  if (waited && id !== null) {
@@ -483,12 +568,34 @@ export const makeSteps = <Phase extends string, R>(deps: {
483
568
  }
484
569
  return;
485
570
  }
571
+ if (slot.unavailable !== null && (yield* markedAsNeedingAnAgent(top, step, slot.unavailable))) {
572
+ console.log(`[agents] ${workflow} run ${instance.executionId} ended at its agent step: no agent can be had (${slot.unavailable}); its task goes to the back of its queue, marked as needing one`);
573
+ return yield* Effect.fail(NEEDS_AN_AGENT_STOOD_DOWN);
574
+ }
486
575
  if (id !== null) yield* recorded('say what it waits on', records.setStepWaiting({ id, waiting: slot.why }));
487
576
  waited = true;
488
577
  if ((yield* deps.wakes.untilPickWoken({ workflow: heardOn, after: wakes })) === 'released') return yield* Effect.fail(HANDED_OVER);
489
578
  }
490
579
  });
491
580
 
581
+ /**
582
+ * A RUN OF A WORKFLOW WITH A LIST WORKS ON ONE OF ITS TASKS: the item its Pick named, which every later step inherits. A
583
+ * step naming another is the fault `markedAsNeedingAnAgent` guards against, caught where it is made: in tests it fails
584
+ * the run; live, it is said once.
585
+ */
586
+ const checkItem = (workflow: string, run: string, step: string, item: string | null): Effect.Effect<void> => Effect.gen(function* () {
587
+ const d = DECLARED.get(workflow);
588
+ if (item === null || d === undefined || !hasAList(d)) return;
589
+ const named = yield* Effect.orElseSucceed(records.subjectOfRun(run), () => null);
590
+ if (named === null || named.toLowerCase() === item.toLowerCase()) return;
591
+ const fault = `${workflow}: its step ${step} names ${item}, while its run works on ${named}: a run of a workflow with a list works on one of its tasks`;
592
+ if (process.env.NODE_ENV === 'test') throw new Error(fault);
593
+ if (!undeclaredSaid.has(fault)) {
594
+ undeclaredSaid.add(fault);
595
+ console.error(`[steps] ${fault}`);
596
+ }
597
+ });
598
+
492
599
  /** Checks the move to `step` against its workflow's graph: in tests an undeclared one fails the run; live, it is said once. */
493
600
  const checkEdge = (workflow: string, run: string, step: string): Effect.Effect<void> => Effect.gen(function* () {
494
601
  const graph = DECLARED.get(workflow)?.graph?.();
@@ -540,9 +647,12 @@ export const makeSteps = <Phase extends string, R>(deps: {
540
647
  let before: TreeHashes | null = null;
541
648
  let recordId: number | null = null;
542
649
  let meter = new StepMeter(null, (step.runs === 'agentic'), [], null);
650
+ /** Whether this agent step took an agent: past its slot, its task's mark as needing one clears when it ends. */
651
+ let tookAnAgent = false;
543
652
  return Effect.acquireUseRelease(
544
653
  Effect.flatMap(Effect.gen(function* () {
545
654
  yield* checkEdge(instance.workflow._tag, instance.executionId, step.name);
655
+ yield* checkItem(instance.workflow._tag, instance.executionId, step.name, subject);
546
656
  // A sub-workflow step is run again when its workflow has ended: it takes its open record up again, and names the run it started.
547
657
  const id = yield* recorded('open its record', records.openStepRun({ workflow: instance.workflow._tag, run: instance.executionId, step: step.name, call, agent: (step.runs === 'agentic'), subject, ...(childRun === null ? {} : { resume: true as const }) }));
548
658
  if (id !== null && childRun !== null) yield* recorded('name the run it started', records.setStepChild({ id, childRun }));
@@ -562,7 +672,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
562
672
  return opened;
563
673
  }))),
564
674
  () => pipe(
565
- (step.runs === 'agentic') ? Effect.andThen(untilAgentSlot(instance, () => recordId), execute) : execute,
675
+ (step.runs === 'agentic') ? Effect.andThen(untilAgentSlot(instance, step.name, () => recordId), Effect.andThen(Effect.sync(() => { tookAnAgent = true; }), execute)) : execute,
566
676
  // What it changed, on its record, and a change it named outside where it may write refuses the step.
567
677
  Effect.tap(() => Effect.suspend(() => {
568
678
  const earlier = before;
@@ -583,6 +693,12 @@ export const makeSteps = <Phase extends string, R>(deps: {
583
693
  ) as Effect.Effect<A, E, Exclude<R2, AgentStep>>,
584
694
  ({ id, beat }, exit) => Effect.gen(function* () {
585
695
  if (beat !== null) clearInterval(beat);
696
+ // An agent step that ran on a task marked as needing an agent clears the mark: it may need none now.
697
+ if (tookAnAgent && (Exit.isSuccess(exit) || !Cause.hasInterrupts(exit.cause))) {
698
+ const top = TOPS.get(instance.executionId) ?? { run: instance.executionId, workflow: instance.workflow._tag };
699
+ const task = yield* taskOfTop(top);
700
+ if (task !== null) yield* deps.tasks.agentStepRan({ task, by: { workflow: top.workflow, run: top.run, step: step.name } });
701
+ }
586
702
  // Its agent slot is free for its workflow's next run waiting on one.
587
703
  if ((step.runs === 'agentic')) deps.wakes.wakePicksOf(TOPS.get(instance.executionId)?.workflow ?? instance.workflow._tag, 'an agent step ended');
588
704
  // An interrupted step is no move: the run does it again.
@@ -592,6 +708,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
592
708
  const spend = spendNow();
593
709
  const used = meter.used();
594
710
  const named = Exit.isSuccess(exit) ? subjectOf?.(exit.value) ?? null : null;
711
+ yield* checkItem(instance.workflow._tag, instance.executionId, step.name, named);
595
712
  // A batch that started no process and recorded no item had none to do; one that worked outside `eachItem` stays undeclared.
596
713
  const idleBatch = step.perItem === true && Exit.isSuccess(exit) && used.childCpuSeconds === 0 && used.compiles === 0;
597
714
  const scope: StepScope = meter.items > 0 ? 'functions' : step.shared === true ? 'shared' : idleBatch ? 'none due' : subjectOf !== undefined && Exit.isSuccess(exit) && named === null ? 'nothing' : 'undeclared';
@@ -630,16 +747,25 @@ export const makeSteps = <Phase extends string, R>(deps: {
630
747
  const standDownIfSurplus = (step: { readonly agent: boolean; readonly picks: boolean }) => Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) =>
631
748
  // A run a sub-workflow step started is its top run's work: its steps stand down as that run's own would, by that
632
749
  // workflow's budget. Asked of its own, a step with no agent stood the run above down where that run's own never would.
633
- Effect.flatMap(Effect.orElseSucceed(topOf(instance.workflow._tag, instance.executionId), () => ({ run: instance.executionId, workflow: instance.workflow._tag })), (top) => {
634
- const declared = DECLARED.get(top.workflow);
635
- const budgetKeepsIt = declared !== undefined && keptRunningByItsBudget(declared);
636
- if (!step.agent && (budgetKeepsIt || (!step.picks && lastStepRan.has(instance.executionId)))) return Effect.void;
637
- return Effect.flatMap(AgentBudgets, (budgets) => Effect.flatMap(budgets.standsDown(instance.workflow._tag, instance.executionId), (surplus) => {
638
- if (!surplus) return Effect.void;
639
- console.log(`[run limit] ${instance.workflow._tag} run ${instance.executionId} stood down: its workflow has more runs going than its run limit`);
640
- return Effect.fail(STOOD_DOWN);
641
- }));
642
- }));
750
+ Effect.flatMap(Effect.orElseSucceed(topOf(instance.workflow._tag, instance.executionId), () => ({ run: instance.executionId, workflow: instance.workflow._tag })), (top) => Effect.flatMap(
751
+ // IT ENDS WITH THE RUN ABOVE IT. Once that run has ended (failed, or stopped), no step of this one starts: its result
752
+ // would be read by nothing. A read of the engine's records that fails stops no step.
753
+ top.run === instance.executionId ? Effect.succeed(false) : Effect.orElseSucceed(Effect.map(runsOldestFirst([top.workflow]), (unfinished) => !unfinished.includes(top.run)), () => false),
754
+ (aboveEnded) => {
755
+ if (aboveEnded) {
756
+ console.log(`[run limit] ${instance.workflow._tag} run ${instance.executionId} stood down: the ${top.workflow} run above it, ${top.run}, has ended`);
757
+ return Effect.fail(ABOVE_ENDED);
758
+ }
759
+ const declared = DECLARED.get(top.workflow);
760
+ const budgetKeepsIt = declared !== undefined && keptRunningByItsBudget(declared);
761
+ if (!step.agent && (budgetKeepsIt || (!step.picks && lastStepRan.has(instance.executionId)))) return Effect.void;
762
+ return Effect.flatMap(AgentBudgets, (budgets) => Effect.flatMap(budgets.standsDown(instance.workflow._tag, instance.executionId), (surplus) => {
763
+ if (!surplus) return Effect.void;
764
+ console.log(`[run limit] ${instance.workflow._tag} run ${instance.executionId} stood down: its workflow has more runs going than its run limit`);
765
+ return Effect.fail(STOOD_DOWN);
766
+ }));
767
+ },
768
+ )));
643
769
 
644
770
  /** One run of a workflow picks at a time: its choice is on its step record before the next reads what is taken. */
645
771
  const pickingOneAtATime = <A, E, R2>(workflow: string, pick: Effect.Effect<A, E, R2>): Effect.Effect<A, E, R2> => {
@@ -651,7 +777,11 @@ export const makeSteps = <Phase extends string, R>(deps: {
651
777
  /** Why a Pick waits, on its open record: its queued tasks, none of which it can claim now, and what wakes it. */
652
778
  const nothingToClaim = (workflow: string): Effect.Effect<string> => pipe(
653
779
  deps.tasks.taskSummaries({ workflow }),
654
- Effect.map((tasks) => `${queueOrder(tasks).length} queued${queueOrder(tasks).length === 0 ? '' : ', none it can claim now'}`),
780
+ Effect.map((tasks) => {
781
+ const queued = queueOrder(tasks);
782
+ const needAnAgent = queued.filter((t) => t.needsAgent !== null).length;
783
+ return `${queued.length} queued${queued.length === 0 ? '' : ', none it can claim now'}${needAnAgent === 0 ? '' : `, ${needAnAgent} of them passed over as needing an agent`}`;
784
+ }),
655
785
  Effect.catchTag('StorageError', (e) => Effect.succeed(`its tasks could not be read: ${e.reason}`)),
656
786
  Effect.map((queued) => `no task it can claim (${queued}); it waits for a task returned to its queue, a new item, a run ending or a limit change`),
657
787
  );
@@ -724,7 +854,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
724
854
  }) => {
725
855
  const writes = [...(d.mayWrite ?? []), ...(d.writes ?? [])];
726
856
  const declaration: StepDeclaration = {
727
- name: d.name, runs: d.runs, description: d.description, ...(d.kind === undefined ? {} : { kind: d.kind }), ...(d.test === undefined ? {} : { test: true }), ...(d.shared === undefined ? {} : { shared: true }), ...(d.perItem === undefined ? {} : { perItem: true }), ...(d.picked === undefined ? {} : { picks: true }),
857
+ name: d.name, runs: d.runs, description: d.description, ...(d.kind === undefined ? {} : { kind: d.kind }), ...(d.test === undefined ? {} : { test: true }), ...(d.shared === undefined ? {} : { shared: true }), ...(d.perItem === undefined ? {} : { perItem: true }), ...(d.picked === undefined ? {} : { picks: true }), ...(d.subject === undefined ? {} : { namesItem: true }),
728
858
  ...(writes.length === 0 ? {} : { writes }),
729
859
  source: d.prompt ?? { path: sourcePath(d.at), anchor: `'${d.name}'` },
730
860
  };
@@ -803,6 +933,20 @@ export const makeSteps = <Phase extends string, R>(deps: {
803
933
  const given = (result: unknown): Effect.Effect<A, string> => (isDeclared(result) ? Effect.succeed(result) : Effect.fail(`${child} gave a result that is not what this step declares`));
804
934
  const name = d.as ?? child;
805
935
  const startAsAStep = (payload: P): Effect.Effect<unknown, unknown, R2> => ((STARTS_AS_A_STEP.get(child) ?? d.workflow.execute) as (payload: P) => Effect.Effect<unknown, unknown, R2>)(payload);
936
+ /**
937
+ * ITS WORKFLOW STARTED, AND WAITED FOR. In a process handing its runs to the next, the wait is cut: its workflow's run
938
+ * has gone to the next process, which this one's engine can no longer reach, so the call is interrupted. Left to the
939
+ * engine's activity, that interrupt was tried again 10 times and then failed the run above, while its workflow went on
940
+ * in the next process with a result nothing would read: two runs of Decompile ended so on 2026-11-19, their agents
941
+ * still writing. The run above is suspended instead, as it is whenever its workflow has not ended: the next process
942
+ * resumes it when that workflow ends, this step runs again there and reads the result, and its record stays the one.
943
+ */
944
+ const startedAndWaitedFor = (payload: P): Effect.Effect<unknown, unknown, R2 | WorkflowEngine.WorkflowInstance> => pipe(
945
+ startAsAStep(payload),
946
+ Effect.sandbox,
947
+ Effect.catch((cause) => Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) =>
948
+ (Cause.hasInterruptsOnly(cause) && !instance.suspended && deps.wakes.handingOver() ? Workflow.suspend(instance) : Effect.failCause(cause)))),
949
+ );
806
950
  const declaration: StepDeclaration = {
807
951
  name, runs: null, kind: 'sub-workflow', workflow: child,
808
952
  description: DECLARED.get(child)?.description ?? `Runs ${child}.`,
@@ -827,7 +971,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
827
971
  execute: pipe(
828
972
  standDownIfSurplus({ agent: false, picks: false }),
829
973
  Effect.andThen(Effect.flatMap(d.workflow.executionId(payload), (childRun) =>
830
- measured(declaration, options?.call ?? null, null, undefined, undefined, undefined, Effect.flatMap(startAsAStep(payload), given), childRun))),
974
+ measured(declaration, options?.call ?? null, null, undefined, undefined, undefined, Effect.flatMap(startedAndWaitedFor(payload), given), childRun))),
831
975
  Effect.mapError(describeFailure),
832
976
  ),
833
977
  }),
@@ -868,7 +1012,9 @@ export const makeSteps = <Phase extends string, R>(deps: {
868
1012
  */
869
1013
  const queueNow = (input: { readonly workflow: string; readonly run: string }): Effect.Effect<ReadonlyArray<TaskSummary>, unknown, R> => Effect.gen(function* () {
870
1014
  yield* readTaskInputs(input.workflow);
871
- return queueOrder(yield* deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }));
1015
+ const queue = queueOrder(yield* deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }));
1016
+ // While no agent can be had, a task marked as needing one is passed over (`agentsUnavailable`).
1017
+ return (yield* agentsUnavailable(input.workflow)) === null ? queue : queue.filter((t) => t.needsAgent === null);
872
1018
  });
873
1019
 
874
1020
  /** A workflow: what it states about itself, then `Workflow.make`'s own name and options. */
@@ -1016,8 +1162,12 @@ export const makeSteps = <Phase extends string, R>(deps: {
1016
1162
  * returned to the queue that the candidates do not hold.
1017
1163
  */
1018
1164
  const pickOrder = <C>(input: { readonly workflow: string; readonly run: string; readonly candidates: ReadonlyArray<C>; readonly subjectOf: (c: C) => string; readonly fromItem?: (item: string) => C | null }): Effect.Effect<ReadonlyArray<C>, StorageError> =>
1019
- Effect.map(deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }), (tasks) =>
1020
- inPickOrder({ candidates: input.candidates, subjectOf: input.subjectOf, tasks, ...(input.fromItem === undefined ? {} : { fromItem: input.fromItem }) }));
1165
+ Effect.map(Effect.all({ tasks: deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }), unavailable: agentsUnavailable(input.workflow) }), ({ tasks, unavailable }) =>
1166
+ inPickOrder({
1167
+ candidates: input.candidates, subjectOf: input.subjectOf, tasks, ...(input.fromItem === undefined ? {} : { fromItem: input.fromItem }),
1168
+ // While no agent can be had, a task marked as needing one is passed over (`agentsUnavailable`).
1169
+ ...(unavailable === null ? {} : { alsoLeaveOut: new Set(tasks.filter((t) => t.status === 'queued' && t.needsAgent !== null).map((t) => t.ref.item)) }),
1170
+ }));
1021
1171
 
1022
1172
  /**
1023
1173
  * A workflow of one code step, run each turn of its trigger: `run` waits for the run to finish (a heavy one, in line with
@@ -1047,7 +1197,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
1047
1197
  return {
1048
1198
  defineStep, defineItemTest, defineSubWorkflow, defineWorkflow, oneStepWorkflow, declaredWorkflows, onRunEnded,
1049
1199
  eachItem, undoAgentStep, AgentBudgets, pickingOneAtATime, pickOrder, itemsOfOtherRuns,
1050
- runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs,
1200
+ runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs, agentsUnavailable,
1051
1201
  };
1052
1202
  };
1053
1203
 
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * runs how many runs it keeps going, and nothing else does. None stored means the default: its agents' limit.
5
5
  * agents how many of its runs may be in an agent step at once: its budget, as its owner sets it. A run at an agent step
6
- * with none free waits there for one (`steps.ts` `agentSlot`), its task kept and no CPU used, until a limit is set.
7
- * 0 is the owner's decision and no fault: nothing gets past a first agent step.
6
+ * whose agents are all in use waits there for one (`steps.ts` `agentSlot`), its task kept and no CPU used.
7
+ * 0 is the owner's decision and no fault: nothing gets past a first agent step, and a run with a task ends there,
8
+ * its task marked as needing an agent (`steps.ts` `untilAgentSlot`).
8
9
  *
9
10
  * Alex, 2026-11-14: "there was supposed to be a number of runs concurrently allowed setting per workflow and also a number
10
11
  * of concurrent agents allowed per workflow setting". One number did both until 2026-11-12; until 2026-11-14 the default
@@ -26,6 +27,23 @@ export const SET_WORKFLOW_BUDGET_SQL =
26
27
  export const SET_WORKFLOW_RUNS_SQL =
27
28
  'INSERT INTO workflow_budgets(workflow, budget, runs, changed_at) VALUES (?, 0, ?, ?) ON CONFLICT(workflow) DO UPDATE SET runs = excluded.runs, changed_at = excluded.changed_at';
28
29
 
30
+ /**
31
+ * THE ONE SPENDING LIMIT (`spending-limit.ts`): a table of one row beside `workflow_budgets`, since it is the account's and
32
+ * no workflow's: `spending_limit(id INTEGER PRIMARY KEY CHECK (id = 1), week_percent INTEGER NOT NULL, changed_at REAL NOT
33
+ * NULL)`. None stored is the default. As with `workflow_budgets`, the project makes the table and writes it through the
34
+ * statement below.
35
+ */
36
+ export const SPENDING_LIMIT_SQL = 'SELECT week_percent, changed_at FROM spending_limit WHERE id = 1';
37
+ /** Sets the spending limit: the percent of the week at which agents stop. */
38
+ export const SET_SPENDING_LIMIT_SQL =
39
+ 'INSERT INTO spending_limit(id, week_percent, changed_at) VALUES (1, ?, ?) ON CONFLICT(id) DO UPDATE SET week_percent = excluded.week_percent, changed_at = excluded.changed_at';
40
+
41
+ /** The spending limit as stored: the percent of the week at which agents stop, and when it was set, unix seconds. */
42
+ export interface StoredSpendingLimit {
43
+ readonly weekPercent: number;
44
+ readonly changedAt: number;
45
+ }
46
+
29
47
  export interface WorkflowBudgetRow {
30
48
  readonly workflow: string;
31
49
  /** The agents' limit. */
@@ -46,6 +64,8 @@ export interface LimitStore {
46
64
  readonly limitsOf: (workflow: string) => Effect.Effect<WorkflowLimits | null, StorageError>;
47
65
  /** Every stored workflow's limits, by name, in one read: one with none stored is absent. None where there is no store. */
48
66
  readonly storedLimits: () => Effect.Effect<ReadonlyMap<string, WorkflowLimits> | null, StorageError>;
67
+ /** The spending limit as set; none where none was set or there is no store, which is the default. */
68
+ readonly spendingLimit: () => Effect.Effect<StoredSpendingLimit | null, StorageError>;
49
69
  }
50
70
 
51
71
  /**
@@ -78,4 +98,16 @@ export const sqliteBudgets = (options: { readonly file: () => string }): LimitSt
78
98
  db.close();
79
99
  }
80
100
  }),
101
+ spendingLimit: () => storeCall('limits: spendingLimit', () => {
102
+ const file = options.file();
103
+ if (!fs.existsSync(file)) return null;
104
+ const db = new Database(file, { readonly: true });
105
+ try {
106
+ if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'spending_limit'`).get() === null) return null;
107
+ const row = db.query(SPENDING_LIMIT_SQL).get() as { week_percent: number; changed_at: number } | null;
108
+ return row === null ? null : { weekPercent: row.week_percent, changedAt: row.changed_at };
109
+ } finally {
110
+ db.close();
111
+ }
112
+ }),
81
113
  });