@jive-sh/workflow-platform 0.7.0 → 1.0.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 (195) hide show
  1. package/README.md +66 -435
  2. package/component/_generated/api.ts +72 -0
  3. package/component/_generated/component.ts +621 -0
  4. package/component/_generated/dataModel.ts +60 -0
  5. package/component/_generated/server.ts +169 -0
  6. package/component/convex.config.ts +3 -0
  7. package/component/engine.ts +755 -0
  8. package/component/errors.ts +66 -0
  9. package/component/events.ts +17 -0
  10. package/component/notes.ts +13 -0
  11. package/component/places.ts +136 -0
  12. package/component/retention.ts +205 -0
  13. package/component/runEngine.ts +25 -0
  14. package/component/schema.ts +132 -0
  15. package/component/steps.ts +188 -0
  16. package/component/store.ts +512 -0
  17. package/component/tasks.ts +289 -0
  18. package/component/worker.ts +109 -0
  19. package/component/workflows.ts +83 -0
  20. package/dist/definition/agent-runner.js +9 -0
  21. package/dist/definition/agent-runner.js.map +1 -0
  22. package/dist/definition/file-store.js +9 -0
  23. package/dist/definition/file-store.js.map +1 -0
  24. package/dist/definition/program-build.js +10 -0
  25. package/dist/definition/program-build.js.map +1 -0
  26. package/dist/definition/step.js +1 -0
  27. package/dist/definition/step.js.map +1 -0
  28. package/dist/definition/task-schema.js +5 -0
  29. package/dist/definition/task-schema.js.map +1 -0
  30. package/dist/definition/tasks.js +9 -0
  31. package/dist/definition/tasks.js.map +1 -0
  32. package/dist/definition/workflow.js +111 -0
  33. package/dist/definition/workflow.js.map +1 -0
  34. package/dist/graph.js +301 -9
  35. package/dist/graph.js.map +1 -1
  36. package/dist/index.js +7 -196
  37. package/dist/index.js.map +1 -1
  38. package/package.json +9 -4
  39. package/src/definition/agent-runner.ts +59 -0
  40. package/src/definition/file-store.ts +20 -0
  41. package/src/definition/program-build.ts +30 -0
  42. package/src/definition/step.ts +106 -0
  43. package/src/definition/task-schema.ts +15 -0
  44. package/src/definition/tasks.ts +43 -0
  45. package/src/definition/workflow.ts +255 -0
  46. package/src/graph.ts +341 -19
  47. package/src/index.ts +8 -238
  48. package/worker/directory-file-store.ts +42 -0
  49. package/worker/index.ts +12 -0
  50. package/worker/platform-client.ts +138 -0
  51. package/worker/step-meter.ts +80 -0
  52. package/worker/worker-tasks.ts +27 -0
  53. package/worker/worker.test.ts +200 -0
  54. package/worker/worker.ts +240 -0
  55. package/dist/budget-states.js +0 -30
  56. package/dist/budget-states.js.map +0 -1
  57. package/dist/cpu-limit/limiter.js +0 -839
  58. package/dist/cpu-limit/limiter.js.map +0 -1
  59. package/dist/cpu-limit/use.js +0 -139
  60. package/dist/cpu-limit/use.js.map +0 -1
  61. package/dist/dashboard/agent-usage.js +0 -25
  62. package/dist/dashboard/agent-usage.js.map +0 -1
  63. package/dist/dashboard/dashboard.css +0 -148
  64. package/dist/dashboard/drilldown.js +0 -47
  65. package/dist/dashboard/drilldown.js.map +0 -1
  66. package/dist/dashboard/queue-lines.js +0 -44
  67. package/dist/dashboard/queue-lines.js.map +0 -1
  68. package/dist/dashboard/queue-table.js +0 -16
  69. package/dist/dashboard/queue-table.js.map +0 -1
  70. package/dist/dashboard/run-doing-words.js +0 -29
  71. package/dist/dashboard/run-doing-words.js.map +0 -1
  72. package/dist/dashboard/setting-words.js +0 -18
  73. package/dist/dashboard/setting-words.js.map +0 -1
  74. package/dist/dashboard/spending-words.js +0 -24
  75. package/dist/dashboard/spending-words.js.map +0 -1
  76. package/dist/failure.js +0 -35
  77. package/dist/failure.js.map +0 -1
  78. package/dist/keep-running.js +0 -79
  79. package/dist/keep-running.js.map +0 -1
  80. package/dist/outside-failure.js +0 -31
  81. package/dist/outside-failure.js.map +0 -1
  82. package/dist/pick-wakes.js +0 -125
  83. package/dist/pick-wakes.js.map +0 -1
  84. package/dist/project.js +0 -1
  85. package/dist/project.js.map +0 -1
  86. package/dist/queue-counts.js +0 -51
  87. package/dist/queue-counts.js.map +0 -1
  88. package/dist/reasons.js +0 -33
  89. package/dist/reasons.js.map +0 -1
  90. package/dist/retention.js +0 -59
  91. package/dist/retention.js.map +0 -1
  92. package/dist/settings.js +0 -88
  93. package/dist/settings.js.map +0 -1
  94. package/dist/spending-limit.js +0 -82
  95. package/dist/spending-limit.js.map +0 -1
  96. package/dist/step-files.js +0 -200
  97. package/dist/step-files.js.map +0 -1
  98. package/dist/step-meter.js +0 -97
  99. package/dist/step-meter.js.map +0 -1
  100. package/dist/step-times.js +0 -114
  101. package/dist/step-times.js.map +0 -1
  102. package/dist/step-usage.js +0 -19
  103. package/dist/step-usage.js.map +0 -1
  104. package/dist/steps.js +0 -1205
  105. package/dist/steps.js.map +0 -1
  106. package/dist/storage/agent-claims.js +0 -3
  107. package/dist/storage/agent-claims.js.map +0 -1
  108. package/dist/storage/budgets.js +0 -121
  109. package/dist/storage/budgets.js.map +0 -1
  110. package/dist/storage/engine-records.js +0 -91
  111. package/dist/storage/engine-records.js.map +0 -1
  112. package/dist/storage/engine-storage.js +0 -67
  113. package/dist/storage/engine-storage.js.map +0 -1
  114. package/dist/storage/input-records.js +0 -12
  115. package/dist/storage/input-records.js.map +0 -1
  116. package/dist/storage/move-store.js +0 -251
  117. package/dist/storage/move-store.js.map +0 -1
  118. package/dist/storage/sqlite-store.js +0 -901
  119. package/dist/storage/sqlite-store.js.map +0 -1
  120. package/dist/storage/step-records.js +0 -11
  121. package/dist/storage/step-records.js.map +0 -1
  122. package/dist/storage/storage-error.js +0 -19
  123. package/dist/storage/storage-error.js.map +0 -1
  124. package/dist/storage/task-store.js +0 -30
  125. package/dist/storage/task-store.js.map +0 -1
  126. package/dist/system-workflows.js +0 -54
  127. package/dist/system-workflows.js.map +0 -1
  128. package/dist/tasks.js +0 -500
  129. package/dist/tasks.js.map +0 -1
  130. package/dist/views/format.js +0 -37
  131. package/dist/views/format.js.map +0 -1
  132. package/dist/views/runs-now.js +0 -117
  133. package/dist/views/runs-now.js.map +0 -1
  134. package/dist/views/step-funnel.js +0 -98
  135. package/dist/views/step-funnel.js.map +0 -1
  136. package/dist/views/step-graph.js +0 -39
  137. package/dist/views/step-graph.js.map +0 -1
  138. package/dist/views/workflows-view.js +0 -236
  139. package/dist/views/workflows-view.js.map +0 -1
  140. package/src/budget-states.ts +0 -54
  141. package/src/cpu-limit/limiter.ts +0 -935
  142. package/src/cpu-limit/use.ts +0 -166
  143. package/src/dashboard/agent-usage-line.tsx +0 -28
  144. package/src/dashboard/agent-usage.ts +0 -48
  145. package/src/dashboard/dashboard.css +0 -148
  146. package/src/dashboard/drilldown.ts +0 -70
  147. package/src/dashboard/index.tsx +0 -4
  148. package/src/dashboard/limits-and-runs.tsx +0 -191
  149. package/src/dashboard/machine-controls.tsx +0 -53
  150. package/src/dashboard/queue-bar.tsx +0 -62
  151. package/src/dashboard/queue-chart.tsx +0 -149
  152. package/src/dashboard/queue-lines.ts +0 -87
  153. package/src/dashboard/queue-table.ts +0 -37
  154. package/src/dashboard/run-doing-words.ts +0 -41
  155. package/src/dashboard/setting-words.ts +0 -30
  156. package/src/dashboard/spending-limit-control.tsx +0 -47
  157. package/src/dashboard/spending-words.ts +0 -32
  158. package/src/dashboard/time-distribution.tsx +0 -61
  159. package/src/dashboard/workflow-dag.tsx +0 -322
  160. package/src/dashboard/workflow-drilldown.tsx +0 -31
  161. package/src/dashboard/workflows-dashboard.tsx +0 -532
  162. package/src/failure.ts +0 -36
  163. package/src/keep-running.ts +0 -85
  164. package/src/outside-failure.ts +0 -39
  165. package/src/pick-wakes.ts +0 -182
  166. package/src/project.ts +0 -127
  167. package/src/queue-counts.ts +0 -64
  168. package/src/reasons.ts +0 -30
  169. package/src/retention.ts +0 -90
  170. package/src/settings.ts +0 -171
  171. package/src/spending-limit.ts +0 -139
  172. package/src/step-files.ts +0 -208
  173. package/src/step-meter.ts +0 -120
  174. package/src/step-times.ts +0 -151
  175. package/src/step-usage.ts +0 -23
  176. package/src/steps.ts +0 -1616
  177. package/src/storage/agent-claims.ts +0 -63
  178. package/src/storage/budgets.ts +0 -152
  179. package/src/storage/engine-records.ts +0 -119
  180. package/src/storage/engine-storage.ts +0 -82
  181. package/src/storage/input-records.ts +0 -43
  182. package/src/storage/move-store.ts +0 -265
  183. package/src/storage/sqlite-store.ts +0 -1022
  184. package/src/storage/step-records.ts +0 -358
  185. package/src/storage/storage-error.ts +0 -35
  186. package/src/storage/task-store.ts +0 -235
  187. package/src/system-workflows.ts +0 -70
  188. package/src/tasks.ts +0 -586
  189. package/src/views/format.ts +0 -40
  190. package/src/views/runs-now.ts +0 -188
  191. package/src/views/step-funnel.ts +0 -163
  192. package/src/views/step-graph.ts +0 -77
  193. package/src/views/workflows-view.ts +0 -484
  194. package/src/workflow-dag.test.tsx +0 -89
  195. package/src/workflow-page.test.tsx +0 -170
package/src/settings.ts DELETED
@@ -1,171 +0,0 @@
1
- /**
2
- * THE SETTINGS A WORKFLOW TREE INHERITS: how long its records are kept, the fewest of its runs kept however old, and the
3
- * model its agent steps run on. Alex, 2026-11-21: "time based retention is a good idea. it should be configurable at the
4
- * highest level with allowed step level overrides. and the same should be true for model. i think 7 days sounds
5
- * reasonable." Then, 2026-11-22: "retention is supposed to be configurable at the platform layer and something configurable
6
- * for all tasks"; "can retention actually be a # of tasks thing or a time thing ... because I realized a project might
7
- * complete or stall but we shouldn't lose run data in that case" ("10k runs"); and "like it needs to be configurable".
8
- *
9
- * The highest level is the app: what it gives the platform once (`WorkflowProject.settings`) holds for every workflow and
10
- * step, its own and the platform's (`system-workflows.ts`), over the platform's defaults. Below it, each is set, where it is
11
- * set, on a workflow (`defineWorkflow`) or on a step (`defineStep`, `defineSubWorkflow`, `defineWorkflowStep`). A step's
12
- * value is its own, else its workflow's. A workflow's is its own, else what the step that holds it in the workflow above
13
- * sets, else that workflow's, up to the top, else the app's, else the platform's default. So a step that is a workflow
14
- * hands its value down to every step under it.
15
- *
16
- * THE RETENTION SETTINGS ARE ALSO SET WHILE THE APP RUNS (`RUNTIME_SETTINGS`): a value stored on the app, a workflow or a step
17
- * (`StoredSetting`, the `workflow_settings` table, `storage/budgets.ts`) is that level's own and wins over the code's value
18
- * there, which is its default. The model is set in code alone. Pure, so a page and a run read the same answer.
19
- */
20
- import type { StepDeclaration, WorkflowDeclaration } from './steps';
21
-
22
- /** What the app, a workflow or a step may set for the steps under it. */
23
- export interface InheritedSettings {
24
- /** How many days a run's records are kept after the run ended (`retention.ts`). */
25
- readonly retentionDays?: number;
26
- /** How many of a step's newest runs keep their records however long ago they ended (`retention.ts`). */
27
- readonly keepAtLeastRuns?: number;
28
- /** The model an agent step runs on (`AgentStep.model`). */
29
- readonly model?: string;
30
- }
31
-
32
- export type SettingName = keyof InheritedSettings;
33
-
34
- /** Each setting's value once resolved: a model may be set nowhere. */
35
- export interface SettingValues {
36
- readonly retentionDays: number;
37
- readonly keepAtLeastRuns: number;
38
- readonly model: string | null;
39
- }
40
-
41
- /**
42
- * Each setting where neither the app nor any workflow or step sets it: records kept 7 days, and each step's newest 10,000
43
- * runs however old (Alex, 2026-11-22: "10k runs"); no model, which an agent step cannot run without.
44
- */
45
- export const PLATFORM_DEFAULTS: SettingValues = { retentionDays: 7, keepAtLeastRuns: 10_000, model: null };
46
-
47
- /** The settings a page may set while the app runs; the model is set in code alone. */
48
- export const RUNTIME_SETTINGS = ['retentionDays', 'keepAtLeastRuns'] as const;
49
- export type RuntimeSettingName = (typeof RUNTIME_SETTINGS)[number];
50
-
51
- /** Where a setting is set: the app, one workflow, or one step of one workflow. */
52
- export type SettingLevel =
53
- | { readonly kind: 'app' }
54
- | { readonly kind: 'workflow'; readonly workflow: string }
55
- | { readonly kind: 'step'; readonly workflow: string; readonly step: string };
56
-
57
- /** A value set while the app runs, at one level, and when; none (`value: null`) puts that level back to the code's value. */
58
- export interface StoredSetting {
59
- readonly level: SettingLevel;
60
- readonly name: RuntimeSettingName;
61
- readonly value: number | null;
62
- readonly changedAt: number;
63
- }
64
-
65
- /** Where an effective value is set. */
66
- export type SetOn = SettingLevel | { readonly kind: 'platform default' };
67
-
68
- /** A setting's value for a step or a workflow, and where it is set. */
69
- export interface Effective<A> {
70
- readonly value: A;
71
- readonly setOn: SetOn;
72
- }
73
-
74
- /** What the resolution reads of each declared workflow. */
75
- export type SettingsDeclared = Pick<WorkflowDeclaration<unknown>, 'name' | SettingName> & {
76
- readonly steps: () => ReadonlyArray<Pick<StepDeclaration, 'name' | 'workflow' | SettingName>>;
77
- };
78
-
79
- /**
80
- * Everything a setting is resolved from: every declared workflow, what the app sets above them all, and the values set while
81
- * the app runs (none where nothing reads them, as for the model).
82
- */
83
- export interface SettingsTree {
84
- readonly declared: ReadonlyArray<SettingsDeclared>;
85
- readonly app: InheritedSettings;
86
- readonly stored: ReadonlyArray<StoredSetting>;
87
- }
88
-
89
- /** A level as one comparable text, each part its own segment. Pure. */
90
- const levelKey = (l: SettingLevel): string => (l.kind === 'app' ? 'app' : l.kind === 'workflow' ? `workflow\u0000${l.workflow}` : `step\u0000${l.workflow}\u0000${l.step}`);
91
-
92
- /** Whether two levels are one. Pure. */
93
- export const sameLevel = (a: SettingLevel, b: SettingLevel): boolean => levelKey(a) === levelKey(b);
94
-
95
- /** The value stored at a level now, where one is and it is not back to the code's. Pure. */
96
- export const storedAt = (stored: ReadonlyArray<StoredSetting>, level: SettingLevel, name: SettingName): number | null => {
97
- const found = stored.find((s) => s.name === name && sameLevel(s.level, level));
98
- return found === undefined ? null : found.value;
99
- };
100
-
101
- /** A level's own value: what is stored there now, else what its code sets. */
102
- const ownAt = <N extends SettingName>(tree: SettingsTree, level: SettingLevel, name: N, code: InheritedSettings[N] | undefined): SettingValues[N] | undefined => {
103
- const stored = storedAt(tree.stored, level, name);
104
- return (stored !== null ? stored : code) as SettingValues[N] | undefined;
105
- };
106
-
107
- /** A setting above every workflow: the app's, stored or in code, else the platform's default. Pure. */
108
- export const appSetting = <N extends SettingName>(tree: Pick<SettingsTree, 'app' | 'stored'>, name: N): Effective<SettingValues[N]> => {
109
- const own = ownAt({ ...tree, declared: [] }, { kind: 'app' }, name, tree.app[name]);
110
- return own !== undefined ? { value: own, setOn: { kind: 'app' } } : { value: PLATFORM_DEFAULTS[name], setOn: { kind: 'platform default' } };
111
- };
112
-
113
- /** Two parents of a workflow that would hand it different values: the declarations are at fault, said once. */
114
- const faultsSaid = new Set<string>();
115
-
116
- /**
117
- * A WORKFLOW'S VALUE OF A SETTING: its own, else from the step that holds it in the workflow above (that step's own, else
118
- * that workflow's), up to the top, else the app's, else the platform's default. A workflow held by two workflows that hand
119
- * it different values is a fault in their declarations: in tests it throws; live, it is said once, and the first, in the
120
- * order declared, holds. Pure but for that.
121
- */
122
- export const workflowSetting = <N extends SettingName>(tree: SettingsTree, r: { readonly workflow: string; readonly name: N }, seen: ReadonlySet<string> = new Set()): Effective<SettingValues[N]> => {
123
- const own = ownAt(tree, { kind: 'workflow', workflow: r.workflow }, r.name, tree.declared.find((x) => x.name === r.workflow)?.[r.name]);
124
- if (own !== undefined) return { value: own, setOn: { kind: 'workflow', workflow: r.workflow } };
125
- const fallback = appSetting(tree, r.name);
126
- if (seen.has(r.workflow)) return fallback;
127
- const under = new Set([...seen, r.workflow]);
128
- const fromAbove = tree.declared.flatMap((parent) => parent.steps().filter((s) => s.workflow === r.workflow).map((s): Effective<SettingValues[N]> => {
129
- const set = ownAt(tree, { kind: 'step', workflow: parent.name, step: s.name }, r.name, s[r.name]);
130
- return set !== undefined ? { value: set, setOn: { kind: 'step', workflow: parent.name, step: s.name } } : workflowSetting(tree, { workflow: parent.name, name: r.name }, under);
131
- }));
132
- const first = fromAbove[0];
133
- if (first === undefined) return fallback;
134
- const other = fromAbove.find((x) => x.value !== first.value);
135
- if (other !== undefined) {
136
- const fault = `${r.workflow} is a step of workflows that hand it different values of ${r.name}: ${String(first.value)} and ${String(other.value)}`;
137
- if (process.env.NODE_ENV === 'test') throw new Error(fault);
138
- if (!faultsSaid.has(fault)) {
139
- faultsSaid.add(fault);
140
- console.error(`[settings] ${fault}; the first holds`);
141
- }
142
- }
143
- return first;
144
- };
145
-
146
- /** A step's value of a setting: its own, else its workflow's (`workflowSetting`). */
147
- export const stepSetting = <N extends SettingName>(tree: SettingsTree, r: { readonly workflow: string; readonly step: string; readonly name: N }): Effective<SettingValues[N]> => {
148
- const own = ownAt(tree, { kind: 'step', workflow: r.workflow, step: r.step }, r.name, tree.declared.find((x) => x.name === r.workflow)?.steps().find((s) => s.name === r.step)?.[r.name]);
149
- if (own !== undefined) return { value: own, setOn: { kind: 'step', workflow: r.workflow, step: r.step } };
150
- return workflowSetting(tree, { workflow: r.workflow, name: r.name });
151
- };
152
-
153
- /** Why a retention setting's value is refused, none where it is good: days a positive number, runs a whole number from 0. Pure. */
154
- export const settingValueRefusal = (name: RuntimeSettingName, value: number): string | null =>
155
- name === 'retentionDays'
156
- ? (Number.isFinite(value) && value > 0 ? null : `its records must be kept a positive number of days, not ${value}`)
157
- : (Number.isInteger(value) && value >= 0 ? null : `the runs it keeps at least must be a whole number from 0, not ${value}`);
158
-
159
- /** Settings as written on the app, a workflow or a step, checked there (`settingValueRefusal`), a model a name. */
160
- export const checkedSettings = (d: { readonly [K in SettingName]?: InheritedSettings[K] | undefined } & { readonly what: string }): InheritedSettings => {
161
- for (const name of RUNTIME_SETTINGS) {
162
- const value = d[name];
163
- const refusal = value === undefined ? null : settingValueRefusal(name, value);
164
- if (refusal !== null) throw new Error(`${d.what}: ${refusal}`);
165
- }
166
- if (d.model !== undefined && d.model.trim() === '') throw new Error(`${d.what}: its model is an empty name`);
167
- return {
168
- ...(d.retentionDays === undefined ? {} : { retentionDays: d.retentionDays }), ...(d.keepAtLeastRuns === undefined ? {} : { keepAtLeastRuns: d.keepAtLeastRuns }),
169
- ...(d.model === undefined ? {} : { model: d.model }),
170
- };
171
- };
@@ -1,139 +0,0 @@
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, no run of any workflow
6
- * is given an agent claim (`steps.ts` `claimAgentsOrEnd`), and a run already holding one ends before its next agent call
7
- * (`beforeAgentCall`), as at an agents' limit of 0: its task goes to the back of its queue, marked as needing an agent,
8
- * with why in words. Nothing waits, and an agent call already going is never cut off. Runs take claims again once a reading
9
- * is below X, which the week's reset brings: the project tells the platform of each reading it takes (`readingTaken`), and
10
- * a verdict that changed has the run planner plan again and wakes every Pick. None is set: X is 95
11
- * (`DEFAULT_SPENDING_LIMIT_PERCENT`).
12
- *
13
- * IT JUDGES THE ACCOUNT'S WEEK, NOT A COUNT OF TOKENS, because the week is the one figure that also counts spending the
14
- * platform cannot see: agent threads run by hand, outside any workflow, which no step record holds. They were 73% of the
15
- * spending of the week that ran out on 2026-11-01, 57 hours before its reset (the first project's `usage/pace.ts`).
16
- *
17
- * A READING THAT FAILS OR GROWS OLD NEVER LIFTS IT. The rule judges the newest good reading, however old, so a hold stands
18
- * until a good reading below X, and a page says the reading is stale and why. That holds past the reset the reading named
19
- * too: with every read failing, no agent is given until one succeeds, rather than spend on a week nobody can see. A week that
20
- * cannot be read at all holds the same way. With no good reading yet there is nothing to judge, and nothing is held. A
21
- * project that reads no week has no spending limit.
22
- */
23
- import { Effect, pipe, Result } from 'effect';
24
- import type { PickWakes } from './pick-wakes';
25
- import type { WeekUsage, WeekUsageNow, WeekUsageReading } from './project';
26
- import { SET_SPENDING_LIMIT_SQL, type LimitStore, type StoredSpendingLimit } from './storage/budgets';
27
- import type { StorageError } from './storage/storage-error';
28
- import { percentCut } from './views/format';
29
-
30
- /** The percent of the week at which agents stop where none is set. */
31
- export const DEFAULT_SPENDING_LIMIT_PERCENT = 95;
32
-
33
- /** The spending limit against the newest reading of the week, for a page and for the rule. */
34
- export interface SpendingLimitState {
35
- /** The percent of the week at which agents stop. */
36
- readonly limitPercent: number;
37
- /** When it was set, unix seconds; none while it is the default. */
38
- readonly setAt: number | null;
39
- /** The newest good reading, which the verdict rests on; none before the first. */
40
- readonly reading: WeekUsageReading | null;
41
- /** The newest read, where it failed after that one. */
42
- readonly failedSince: WeekUsageNow['failedSince'];
43
- /** Whether the reading is stale: a read failed since, or it is older than the project's time between readings allows. */
44
- readonly stale: boolean;
45
- /** Whether it withholds every agent now. */
46
- readonly holds: boolean;
47
- }
48
-
49
- /** The limit against the week now. Pure. */
50
- export const judgeSpending = (input: {
51
- readonly limit: StoredSpendingLimit | null;
52
- readonly usage: WeekUsageNow;
53
- readonly staleAfterSeconds: number;
54
- readonly now: number;
55
- }): SpendingLimitState => {
56
- const limitPercent = input.limit === null ? DEFAULT_SPENDING_LIMIT_PERCENT : input.limit.weekPercent;
57
- const good = input.usage.good;
58
- return {
59
- limitPercent,
60
- setAt: input.limit === null ? null : input.limit.changedAt,
61
- reading: good,
62
- failedSince: input.usage.failedSince,
63
- stale: good !== null && (input.usage.failedSince !== null || input.now - good.readAt > input.staleAfterSeconds),
64
- holds: good !== null && good.usedPercent >= limitPercent,
65
- };
66
- };
67
-
68
- export interface SpendingLimit {
69
- /**
70
- * Why no agent can be had now, in words, until a reading or the limit changes; none while it holds nothing. The reason a
71
- * run ends and marks its task as needing an agent (`steps.ts` `claimAgentsOrEnd`).
72
- */
73
- readonly holdsAgents: () => Effect.Effect<string | null>;
74
- /** The limit against the newest reading, for a page; none for a project that reads no week. */
75
- readonly state: (now: number) => Effect.Effect<SpendingLimitState | null, StorageError>;
76
- /**
77
- * The project took a reading of its week. Where the verdict changed since the last one, or a run found the week
78
- * unreadable since, the run planner plans again and every Pick is woken: a reading below the limit lets runs claim again.
79
- */
80
- readonly readingTaken: () => Effect.Effect<void>;
81
- /**
82
- * THE ONE WAY TO SET IT, for the project's route: checks the percent asked, stores it with the platform's statement
83
- * through the project's `write`, wakes every Pick (relayed to the process its runs go in), and says in the log
84
- * who asked (`from`), as the routes that set a workflow's limits do. A refused one changes nothing.
85
- */
86
- readonly set: <E>(r: {
87
- readonly weekPercent: unknown;
88
- readonly from: string;
89
- readonly write: (statement: { readonly sql: string; readonly params: ReadonlyArray<number> }) => Effect.Effect<unknown, E>;
90
- }) => Effect.Effect<{ readonly ok: true; readonly weekPercent: number } | { readonly ok: false; readonly error: string }, E>;
91
- }
92
-
93
- export const makeSpendingLimit = (deps: { readonly store: LimitStore; readonly usage: WeekUsage | null; readonly wakes: PickWakes }): SpendingLimit => {
94
- const { usage } = deps;
95
- const state = (now: number): Effect.Effect<SpendingLimitState | null, StorageError> =>
96
- usage === null ? Effect.succeed(null) : Effect.map(
97
- Effect.all({ limit: deps.store.spendingLimit(), week: usage.now() }),
98
- ({ limit, week }) => judgeSpending({ limit, usage: week, staleAfterSeconds: usage.staleAfterSeconds, now }),
99
- );
100
- /** What the last reading told held, in this process; none before the first. */
101
- let heldAtLastReading: boolean | null = null;
102
- /** A run found the week unreadable since the last reading, so the next reading wakes every Pick, whatever its verdict. */
103
- let unreadSinceLastReading = false;
104
- return {
105
- holdsAgents: () => pipe(
106
- state(Date.now() / 1000),
107
- Effect.map((s): string | null => (s === null || !s.holds || s.reading === null ? null
108
- : `the week's use is ${percentCut(s.reading.usedPercent)}, at or past the spending limit of ${s.limitPercent}%`)),
109
- Effect.catchTag('StorageError', (e) => Effect.sync((): string => {
110
- unreadSinceLastReading = true;
111
- return `the week's use could not be read (${e.reason}), so the spending limit holds`;
112
- })),
113
- ),
114
- state,
115
- readingTaken: () => Effect.gen(function* () {
116
- const judged = yield* Effect.result(state(Date.now() / 1000));
117
- if (Result.isFailure(judged)) return yield* Effect.logError(`[spending limit] a reading was taken and could not be judged: ${judged.failure.reason}`);
118
- const holds = judged.success !== null && judged.success.holds;
119
- if (holds === heldAtLastReading && !unreadSinceLastReading) return;
120
- if (holds !== heldAtLastReading && judged.success !== null) {
121
- yield* Effect.log(`[spending limit] ${holds ? 'withholds every agent' : 'holds nothing'}: the week's use is ${judged.success.reading === null ? 'not read yet' : percentCut(judged.success.reading.usedPercent)}, the limit ${judged.success.limitPercent}%`);
122
- }
123
- heldAtLastReading = holds;
124
- unreadSinceLastReading = false;
125
- // It changes whether any run can take work (`steps.ts` `whyNoRunCanTakeWork`): the run planner plans again too.
126
- deps.wakes.runPlanChanged({ workflow: null, source: holds ? 'a reading at or past the spending limit' : 'a reading below the spending limit' });
127
- }),
128
- set: (r) => Effect.gen(function* () {
129
- const weekPercent = r.weekPercent;
130
- if (typeof weekPercent !== 'number' || !Number.isInteger(weekPercent) || weekPercent < 0 || weekPercent > 100) {
131
- return { ok: false as const, error: 'weekPercent must be a whole number from 0 to 100' };
132
- }
133
- yield* r.write({ sql: SET_SPENDING_LIMIT_SQL, params: [weekPercent, Date.now() / 1000] });
134
- deps.wakes.runPlanChanged({ workflow: null, source: 'the spending limit set' });
135
- yield* Effect.log(`[spending limit] ${weekPercent}%, from ${r.from}`);
136
- return { ok: true as const, weekPercent };
137
- }),
138
- };
139
- };
package/src/step-files.ts DELETED
@@ -1,208 +0,0 @@
1
- /**
2
- * WHAT AN AGENT STEP CHANGED, read from the tree and not from what the agent said.
3
- *
4
- * A step with tools declares where it may write (`mayWrite`), and the definer hashes the project's tree before and after
5
- * it. Other sessions edit the same checkout, so a change outside those paths is refused when the agent's own tool calls name
6
- * the file, and recorded as not attributable when they do not: the record says which, and never guesses. (The first
7
- * project's Fix browser stop agents ran with no transcript kept, so what they edited was stored nowhere: 2026-11-04.)
8
- */
9
- import { createHash } from 'node:crypto';
10
- import fs from 'node:fs';
11
- import path from 'node:path';
12
- import type { ProjectTree, RunLightNow } from './project';
13
-
14
- const SKIPPED_NAMES = new Set(['node_modules', '.next', '.git', '.DS_Store']);
15
-
16
- export type TreeHashes = ReadonlyMap<string, string>;
17
-
18
- /** Files read at once: read one after another on the runner's thread, the walk held it up to 6.5 s (2026-11-04). */
19
- const READS_AT_ONCE = 64;
20
-
21
- export interface Undone {
22
- readonly restored: ReadonlyArray<string>;
23
- /** Changed again since, in lines that overlap what is being taken back: left as they are, and named. */
24
- readonly conflicts: ReadonlyArray<string>;
25
- }
26
-
27
- export interface FilesChanged {
28
- /** Everything that differs from before, in the paths it may write or not. */
29
- readonly changed: ReadonlyArray<string>;
30
- /** Outside those paths, and named by the agent's own tool calls. */
31
- readonly refused: ReadonlyArray<string>;
32
- /** Outside those paths, with nothing tying them to this agent. */
33
- readonly notAttributable: ReadonlyArray<string>;
34
- /** Everything it changed that its own tool calls name, inside the paths or out: what an undo takes back. */
35
- readonly attributed: ReadonlyArray<string>;
36
- }
37
-
38
- /** What changed between two readings of the tree, and which of it a step may have written. Pure. */
39
- export const filesChanged = (before: TreeHashes, after: TreeHashes, mayWrite: ReadonlyArray<string>, toolInputs: ReadonlyArray<string>): FilesChanged => {
40
- const changed = [...new Set([...before.keys(), ...after.keys()])].filter((f) => before.get(f) !== after.get(f)).sort();
41
- const outside = changed.filter((f) => !mayWrite.some((p) => f === p || f.startsWith(`${p}/`)));
42
- const named = (f: string) => toolInputs.some((input) => input.includes(path.basename(f)));
43
- return { changed, refused: outside.filter(named), notAttributable: outside.filter((f) => !named(f)), attributed: changed.filter(named) };
44
- };
45
-
46
- const AFTER = '.after';
47
- const MANIFEST = 'hashes.json';
48
- const SNAPSHOT_KEPT_MS = 86_400_000;
49
- const blobOf = (dir: string, hash: string): string => path.join(path.dirname(dir), 'blobs', hash.slice(0, 2), hash);
50
-
51
- /** A step's snapshots of the project's tree, and taking back what it changed. */
52
- export const makeStepFiles = (options: { readonly tree: ProjectTree; readonly runLightNow: RunLightNow }) => {
53
- const root = options.tree.root;
54
- const snapshots = options.tree.snapshots;
55
-
56
- const treeHashes = async (): Promise<TreeHashes> => {
57
- const files: string[] = [];
58
- const walk = async (dir: string): Promise<void> => {
59
- for (const entry of await fs.promises.readdir(path.join(root, dir), { withFileTypes: true })) {
60
- const rel = dir === '' ? entry.name : `${dir}/${entry.name}`;
61
- if (SKIPPED_NAMES.has(entry.name) || options.tree.notTree.includes(rel)) continue;
62
- if (entry.isDirectory()) await walk(rel);
63
- else if (entry.isFile()) files.push(rel);
64
- }
65
- };
66
- await walk('');
67
- const hashes = new Map<string, string>();
68
- let next = 0;
69
- const reader = async () => {
70
- while (next < files.length) {
71
- const rel = files[next++]!;
72
- // Others edit this checkout: a file gone since the walk is simply not there.
73
- const content = await fs.promises.readFile(path.join(root, rel)).catch(() => null);
74
- if (content !== null) hashes.set(rel, createHash('sha1').update(content).digest('hex'));
75
- }
76
- };
77
- await Promise.all(Array.from({ length: READS_AT_ONCE }, reader));
78
- return hashes;
79
- };
80
-
81
- /**
82
- * Where a step's record of the tree goes: its file hashes, and `.after` for what it changed. A file's content is kept
83
- * once, by its hash, in `blobs` beside the steps, so a step stores only what no earlier step has. Copying the whole tree
84
- * per step wrote about 39,000 files in 5 minutes (2026-11-04).
85
- */
86
- const snapshotOf = (stepRun: number | string): string => path.join(snapshots, String(stepRun));
87
-
88
- /**
89
- * One snapshot at a time in this process: a blob dropped as unused while another step's record was being written could be
90
- * one that record names, and an undo with its blob gone deletes the file it should restore.
91
- */
92
- let snapshotting: Promise<void> = Promise.resolve();
93
-
94
- /**
95
- * BLOBS NO STEP RECORD NAMES ARE DROPPED: a record a day old goes, and nothing else reads a blob, so one no remaining
96
- * `hashes.json` names can never be restored from. Before this the blobs were never dropped (984 MB on 2026-11-11).
97
- */
98
- const dropUnusedBlobs = async (): Promise<{ readonly dropped: number; readonly bytes: number }> => {
99
- const named = new Set<string>();
100
- for (const record of await fs.promises.readdir(snapshots)) {
101
- if (record === 'blobs') continue;
102
- const manifest = await fs.promises.readFile(path.join(snapshots, record, MANIFEST), 'utf8').catch(() => null);
103
- if (manifest === null) continue;
104
- let hashes: Record<string, string>;
105
- try {
106
- hashes = JSON.parse(manifest) as Record<string, string>;
107
- } catch {
108
- // A record whose names cannot be read may name any blob: none is dropped.
109
- return { dropped: 0, bytes: 0 };
110
- }
111
- for (const hash of Object.values(hashes)) named.add(hash);
112
- }
113
- const blobs = path.join(snapshots, 'blobs');
114
- let dropped = 0, bytes = 0;
115
- for (const prefix of await fs.promises.readdir(blobs).catch(() => [] as string[])) {
116
- for (const hash of await fs.promises.readdir(path.join(blobs, prefix))) {
117
- if (named.has(hash)) continue;
118
- const at = path.join(blobs, prefix, hash);
119
- bytes += (await fs.promises.stat(at)).blocks * 512;
120
- await fs.promises.rm(at, { force: true });
121
- dropped += 1;
122
- }
123
- }
124
- return { dropped, bytes };
125
- };
126
-
127
- const snapshotTreeNow = async (dir: string, hashes: TreeHashes): Promise<void> => {
128
- if (fs.existsSync(snapshots) && dir.startsWith(snapshots)) {
129
- for (const old of await fs.promises.readdir(snapshots)) {
130
- if (old === 'blobs') continue;
131
- const at = path.join(snapshots, old);
132
- if (Date.now() - (await fs.promises.stat(at)).mtimeMs > SNAPSHOT_KEPT_MS) await fs.promises.rm(at, { recursive: true, force: true });
133
- }
134
- }
135
- await fs.promises.mkdir(dir, { recursive: true });
136
- await fs.promises.writeFile(path.join(dir, MANIFEST), JSON.stringify(Object.fromEntries(hashes)));
137
- if (dir.startsWith(snapshots)) {
138
- const unused = await dropUnusedBlobs();
139
- if (unused.dropped > 0) console.log(`[step files] dropped ${unused.dropped} blobs no step record names, ${Math.round(unused.bytes / 1e6)} MB`);
140
- }
141
- const missing = [...hashes].filter(([, hash]) => !fs.existsSync(blobOf(dir, hash)));
142
- let next = 0;
143
- await Promise.all(Array.from({ length: READS_AT_ONCE }, async () => {
144
- while (next < missing.length) {
145
- const [rel, hash] = missing[next++]!;
146
- const to = blobOf(dir, hash);
147
- await fs.promises.mkdir(path.dirname(to), { recursive: true });
148
- await fs.promises.copyFile(path.join(root, rel), to, fs.constants.COPYFILE_FICLONE).catch(() => undefined);
149
- }
150
- }));
151
- };
152
-
153
- /** The tree as a step starts: its hashes, and the content of any file not stored yet. Older step records are dropped. */
154
- const snapshotTree = (dir: string, hashes: TreeHashes): Promise<void> => {
155
- const run = snapshotting.then(() => snapshotTreeNow(dir, hashes));
156
- snapshotting = run.catch(() => undefined);
157
- return run;
158
- };
159
-
160
- /** What the step left in the files it changed, so a later undo can tell its change from anyone's after it. */
161
- const keepWhatItChanged = (dir: string, files: ReadonlyArray<string>): void => {
162
- for (const rel of files) {
163
- if (!fs.existsSync(path.join(root, rel))) continue;
164
- const to = path.join(dir, AFTER, rel);
165
- fs.mkdirSync(path.dirname(to), { recursive: true });
166
- fs.copyFileSync(path.join(root, rel), to);
167
- }
168
- };
169
-
170
- /**
171
- * TAKES BACK WHAT A REFUSED STEP CHANGED, from the copy of the tree it started with. Others edit this checkout, so a file
172
- * changed again since the step ended has only the step's change taken out of it (`diff3`), and one where the two overlap is
173
- * left and named rather than overwritten. A change another session made to the same file while the step ran cannot be told
174
- * from the step's, and goes with it: the record names the file either way.
175
- */
176
- const undoFiles = (dir: string, files: ReadonlyArray<string>): Undone => {
177
- const restored: string[] = [];
178
- const conflicts: string[] = [];
179
- const read = (at: string): Buffer | null => (fs.existsSync(at) ? fs.readFileSync(at) : null);
180
- const same = (a: Buffer | null, b: Buffer | null) => (a === null || b === null ? a === b : a.equals(b));
181
- // A record from before hashes were kept has nothing to restore from: named, never guessed.
182
- const manifest = read(path.join(dir, MANIFEST));
183
- if (manifest === null) return { restored, conflicts: [...files] };
184
- const hashes = JSON.parse(manifest.toString()) as Readonly<Record<string, string>>;
185
- for (const rel of files) {
186
- const here = path.join(root, rel);
187
- const hash = hashes[rel];
188
- const beforeAt = hash === undefined ? path.join(dir, '.none') : blobOf(dir, hash);
189
- const afterAt = path.join(dir, AFTER, rel);
190
- const [now, before, after] = [read(here), read(beforeAt), read(afterAt)];
191
- if (same(now, before)) continue;
192
- if (same(now, after)) {
193
- if (before === null) fs.rmSync(here, { force: true });
194
- else { fs.mkdirSync(path.dirname(here), { recursive: true }); fs.writeFileSync(here, before); }
195
- restored.push(rel);
196
- continue;
197
- }
198
- if (now === null || before === null || after === null) { conflicts.push(rel); continue; }
199
- const merged = options.runLightNow(['diff3', '-m', here, afterAt, beforeAt]);
200
- if (merged.code === 0) { fs.writeFileSync(here, merged.stdoutBytes); restored.push(rel); } else conflicts.push(rel);
201
- }
202
- return { restored, conflicts };
203
- };
204
-
205
- return { treeHashes, snapshotOf, snapshotTree, dropUnusedBlobs, keepWhatItChanged, undoFiles };
206
- };
207
-
208
- export type StepFiles = ReturnType<typeof makeStepFiles>;
package/src/step-meter.ts DELETED
@@ -1,120 +0,0 @@
1
- /**
2
- * WHAT A STEP USES, MEASURED, so no step reports its own: Alex, 2026-11-05, "why to this day are steps not being profiled
3
- * by time, token usage, compute usage, all per function?". `steps.ts` holds one meter per step run, and one per item
4
- * in a batch step (`eachItem`), and writes their figures on the records.
5
- *
6
- * child CPU each process the step started, from its own usage when it exits (`startProcess`): exact.
7
- * own CPU the job runner's own CPU since the last step opened or closed, shared evenly among the steps with no
8
- * agent open then. An agent step's work is in its agent's process, which is measured as a child; an item's
9
- * meter takes its step's share while it runs.
10
- * peak memory the largest of its processes' peaks and the runner's size while it ran.
11
- * compiles its processes labelled as compiles.
12
- * files every file changed under the paths it declared while it ran (the project's file watcher calls `fileWritten`). The system says what
13
- * changed, never who changed it, so a write under no open step's paths is counted by folder instead
14
- * (`undeclared_writes`): shared evenly among the open steps, it charged them with writes nothing
15
- * showed were theirs: 1,982 files to one step in an hour on 2026-11-05.
16
- */
17
- import type { ProcessUsage, UsageSink } from './project';
18
- import type { StepUsed } from './storage/step-records';
19
-
20
- /** What makes a process a compile on its step's record: its label, in one place. */
21
- export const isCompile = (usage: ProcessUsage): boolean => usage.label.startsWith('compile');
22
-
23
- const MB = 1024 * 1024;
24
-
25
- export class StepMeter implements UsageSink {
26
- childCpuSeconds = 0;
27
- ownCpuSeconds = 0;
28
- peakBytes = 0;
29
- compiles = 0;
30
- filesWritten = 0;
31
- /** Items recorded under it, and how many are going now. */
32
- items = 0;
33
- itemsOpen = 0;
34
-
35
- constructor(
36
- readonly record: number | null,
37
- /** An agent step's own work is in its agent's process, and only its declared paths are its files. */
38
- readonly agent: boolean,
39
- readonly writes: ReadonlyArray<string>,
40
- readonly parent: StepMeter | null,
41
- ) {}
42
-
43
- readonly add = (u: ProcessUsage): void => {
44
- this.childCpuSeconds += u.cpuSeconds;
45
- this.peakBytes = Math.max(this.peakBytes, u.peakBytes);
46
- if (isCompile(u)) this.compiles += 1;
47
- };
48
-
49
- used(): StepUsed {
50
- return {
51
- childCpuSeconds: this.childCpuSeconds,
52
- ownCpuSeconds: this.ownCpuSeconds,
53
- peakMemoryMb: Math.round((this.peakBytes / MB) * 10) / 10,
54
- filesWritten: Math.round(this.filesWritten),
55
- compiles: this.compiles,
56
- };
57
- }
58
- }
59
-
60
- const open = new Set<StepMeter>();
61
- let cpuAt = process.cpuUsage();
62
-
63
- /** The meters taking a share now: a step with an item going has it in that item's meter. */
64
- const sharing = (): ReadonlyArray<StepMeter> => [...open].filter((m) => !m.agent && m.itemsOpen === 0);
65
-
66
- /** Shares out the runner's CPU since the last look. */
67
- const settle = (): void => {
68
- const since = process.cpuUsage(cpuAt);
69
- cpuAt = process.cpuUsage();
70
- const rss = process.memoryUsage().rss;
71
- const those = sharing();
72
- for (const m of those) {
73
- m.ownCpuSeconds += (since.user + since.system) / 1e6 / those.length;
74
- m.peakBytes = Math.max(m.peakBytes, rss);
75
- }
76
- };
77
-
78
- export const meterOpened = (meter: StepMeter): void => {
79
- settle();
80
- open.add(meter);
81
- if (meter.parent !== null) {
82
- meter.parent.items += 1;
83
- meter.parent.itemsOpen += 1;
84
- }
85
- };
86
-
87
- /** Closes a meter: an item's figures go into its step's as well. */
88
- export const meterClosed = (meter: StepMeter): void => {
89
- settle();
90
- open.delete(meter);
91
- const parent = meter.parent;
92
- if (parent === null) return;
93
- parent.itemsOpen -= 1;
94
- parent.childCpuSeconds += meter.childCpuSeconds;
95
- parent.ownCpuSeconds += meter.ownCpuSeconds;
96
- parent.peakBytes = Math.max(parent.peakBytes, meter.peakBytes);
97
- parent.compiles += meter.compiles;
98
- parent.filesWritten += meter.filesWritten;
99
- };
100
-
101
- /** Writes no open step declared, by folder (the path's first two parts), until they are stored (`takeUndeclaredWrites`). */
102
- const undeclared = new Map<string, number>();
103
-
104
- /** A file changed: `relative` is its path from the package's root. Counted to the open steps that declared its path, if any. */
105
- export const fileWritten = (relative: string): void => {
106
- const declared = [...open].filter((m) => m.writes.some((w) => relative === w || relative.startsWith(w.endsWith('/') ? w : `${w}/`)));
107
- if (declared.length > 0) {
108
- for (const m of declared) m.filesWritten += 1 / declared.length;
109
- return;
110
- }
111
- const folder = relative.split('/').slice(0, 2).join('/');
112
- undeclared.set(folder, (undeclared.get(folder) ?? 0) + 1);
113
- };
114
-
115
- /** The undeclared writes since the last call, by folder. */
116
- export const takeUndeclaredWrites = (): ReadonlyMap<string, number> => {
117
- const taken = new Map(undeclared);
118
- undeclared.clear();
119
- return taken;
120
- };