@osolmaz/pi-workflows 0.12.1 → 0.13.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 (209) hide show
  1. package/README.md +52 -28
  2. package/dist/builtins/autodoc.workflow.d.ts +4 -4
  3. package/dist/builtins/autoimplement.workflow.d.ts +369 -73
  4. package/dist/builtins/autoplan.workflow.d.ts +126 -13
  5. package/dist/builtins/autoplan.workflow.js +200 -29
  6. package/dist/builtins/autoplan.workflow.js.map +1 -1
  7. package/dist/builtins/catalog.js +6 -4
  8. package/dist/builtins/catalog.js.map +1 -1
  9. package/dist/builtins/index.d.ts +2 -1
  10. package/dist/builtins/index.js +1 -0
  11. package/dist/builtins/index.js.map +1 -1
  12. package/dist/builtins/monitor.workflow.d.ts +56 -21
  13. package/dist/builtins/monitor.workflow.js +497 -216
  14. package/dist/builtins/monitor.workflow.js.map +1 -1
  15. package/dist/builtins/plain-summary.workflow.d.ts +32 -0
  16. package/dist/builtins/plain-summary.workflow.js +134 -0
  17. package/dist/builtins/plain-summary.workflow.js.map +1 -0
  18. package/dist/builtins/plan-change.workflow.d.ts +170 -22
  19. package/dist/builtins/sanity-check.workflow.d.ts +45 -3
  20. package/dist/builtins/sanity-check.workflow.js +45 -7
  21. package/dist/builtins/sanity-check.workflow.js.map +1 -1
  22. package/dist/controllers/effects.d.ts +3 -2
  23. package/dist/controllers/effects.js +8 -1
  24. package/dist/controllers/effects.js.map +1 -1
  25. package/dist/controllers/index.d.ts +1 -1
  26. package/dist/controllers/index.js +1 -1
  27. package/dist/controllers/index.js.map +1 -1
  28. package/dist/controllers/manager.d.ts +1 -0
  29. package/dist/controllers/manager.js +41 -17
  30. package/dist/controllers/manager.js.map +1 -1
  31. package/dist/controllers/sqlite.d.ts +107 -85
  32. package/dist/controllers/sqlite.js +1611 -1486
  33. package/dist/controllers/sqlite.js.map +1 -1
  34. package/dist/controllers/store.d.ts +9 -8
  35. package/dist/controllers/store.js +1 -31
  36. package/dist/controllers/store.js.map +1 -1
  37. package/dist/controllers/types.d.ts +3 -0
  38. package/dist/controllers/workflow-engine-scheduler.d.ts +1 -1
  39. package/dist/controllers/workflow-engine-scheduler.js +3 -5
  40. package/dist/controllers/workflow-engine-scheduler.js.map +1 -1
  41. package/dist/controllers/workflows.d.ts +2 -2
  42. package/dist/controllers/workflows.js +11 -10
  43. package/dist/controllers/workflows.js.map +1 -1
  44. package/dist/extension/controller-host.js +2 -2
  45. package/dist/extension/controller-host.js.map +1 -1
  46. package/dist/extension/decision-channels.d.ts +2 -0
  47. package/dist/extension/decision-channels.js +311 -118
  48. package/dist/extension/decision-channels.js.map +1 -1
  49. package/dist/extension/executor.d.ts +9 -2
  50. package/dist/extension/executor.js +89 -2
  51. package/dist/extension/executor.js.map +1 -1
  52. package/dist/extension/herdr-viewer.d.ts +0 -1
  53. package/dist/extension/herdr-viewer.js +0 -4
  54. package/dist/extension/herdr-viewer.js.map +1 -1
  55. package/dist/extension/index.js +156 -103
  56. package/dist/extension/index.js.map +1 -1
  57. package/dist/extension/recorder.d.ts +3 -10
  58. package/dist/extension/recorder.js +13 -22
  59. package/dist/extension/recorder.js.map +1 -1
  60. package/dist/extension/step-message.d.ts +7 -2
  61. package/dist/extension/step-message.js +94 -2
  62. package/dist/extension/step-message.js.map +1 -1
  63. package/dist/extension/widget.js +6 -0
  64. package/dist/extension/widget.js.map +1 -1
  65. package/dist/host/rpc-executor.d.ts +3 -0
  66. package/dist/host/rpc-executor.js +2 -0
  67. package/dist/host/rpc-executor.js.map +1 -1
  68. package/dist/host/runner.d.ts +3 -6
  69. package/dist/host/runner.js +83 -32
  70. package/dist/host/runner.js.map +1 -1
  71. package/dist/render/graph-render.js +14 -8
  72. package/dist/render/graph-render.js.map +1 -1
  73. package/dist/state/database.d.ts +35 -0
  74. package/dist/state/database.js +287 -0
  75. package/dist/state/database.js.map +1 -0
  76. package/dist/state/index.d.ts +4 -0
  77. package/dist/state/index.js +5 -0
  78. package/dist/state/index.js.map +1 -0
  79. package/dist/state/json.d.ts +6 -0
  80. package/dist/state/json.js +38 -0
  81. package/dist/state/json.js.map +1 -0
  82. package/dist/state/mutation.d.ts +57 -0
  83. package/dist/state/mutation.js +255 -0
  84. package/dist/state/mutation.js.map +1 -0
  85. package/dist/state/schema.d.ts +6 -0
  86. package/dist/state/schema.js +473 -0
  87. package/dist/state/schema.js.map +1 -0
  88. package/dist/viewer/cli.d.ts +2 -2
  89. package/dist/viewer/cli.js +142 -122
  90. package/dist/viewer/cli.js.map +1 -1
  91. package/dist/viewer/render.d.ts +4 -4
  92. package/dist/viewer/render.js +2 -17
  93. package/dist/viewer/render.js.map +1 -1
  94. package/dist/viewer/session-reducer.d.ts +1 -1
  95. package/dist/viewer/session-reducer.js +1 -1
  96. package/dist/viewer/tui.d.ts +3 -3
  97. package/dist/viewer/tui.js +15 -13
  98. package/dist/viewer/tui.js.map +1 -1
  99. package/dist/viewer/watch.d.ts +2 -5
  100. package/dist/viewer/watch.js +13 -13
  101. package/dist/viewer/watch.js.map +1 -1
  102. package/dist/workflows/composition.js +12 -2
  103. package/dist/workflows/composition.js.map +1 -1
  104. package/dist/workflows/definition.d.ts +6 -2
  105. package/dist/workflows/definition.js +17 -0
  106. package/dist/workflows/definition.js.map +1 -1
  107. package/dist/workflows/engine.d.ts +6 -6
  108. package/dist/workflows/engine.js +183 -103
  109. package/dist/workflows/engine.js.map +1 -1
  110. package/dist/workflows/errors.d.ts +3 -3
  111. package/dist/workflows/errors.js +3 -3
  112. package/dist/workflows/human-decision.d.ts +29 -4
  113. package/dist/workflows/human-decision.js +547 -283
  114. package/dist/workflows/human-decision.js.map +1 -1
  115. package/dist/workflows/index.d.ts +4 -5
  116. package/dist/workflows/index.js +3 -4
  117. package/dist/workflows/index.js.map +1 -1
  118. package/dist/workflows/schema.js +17 -1
  119. package/dist/workflows/schema.js.map +1 -1
  120. package/dist/workflows/store.d.ts +83 -103
  121. package/dist/workflows/store.js +902 -951
  122. package/dist/workflows/store.js.map +1 -1
  123. package/dist/workflows/types.d.ts +55 -81
  124. package/docs/CONTROLLERS.md +10 -8
  125. package/docs/DEFERRED_TURNS.md +2 -2
  126. package/docs/DESIGN_PHILOSOPHY.md +4 -2
  127. package/docs/HUMAN_DECISIONS.md +13 -14
  128. package/docs/MONITOR.md +179 -231
  129. package/docs/SQLITE_STATE.md +219 -0
  130. package/docs/WORKFLOW_COMPOSITION.md +19 -19
  131. package/docs/WORKFLOW_STEP_MESSAGES.md +20 -18
  132. package/docs/WORKFLOW_UPDATES.md +10 -9
  133. package/docs/development.md +9 -9
  134. package/docs/live-replay-protocol.md +28 -37
  135. package/docs/plans/2026-08-16-workflow-updates-plan.md +1 -1
  136. package/docs/plans/2026-08-19-human-decision-gates-plan.md +1 -1
  137. package/docs/plans/2026-08-21-autoimplement-timeout-fallback-plan.md +1 -1
  138. package/docs/plans/2026-08-21-plan-change-approval-policy-plan.md +1 -1
  139. package/docs/plans/2026-08-21-sanity-check-plan.md +30 -16
  140. package/docs/plans/2026-08-22-goal-finishing-monitor-plan.md +200 -0
  141. package/docs/plans/2026-08-23-assistant-agent-completion-plan.md +701 -0
  142. package/docs/plans/2026-08-23-sqlite-state-plan.md +970 -0
  143. package/docs/plans/replayable-run-bundles-implementation-plan.md +2 -2
  144. package/docs/plans/session-event-replay-implementation-plan.md +1 -1
  145. package/docs/plans/tui-viewer-implementation-plan.md +1 -1
  146. package/docs/session-event-journal.md +63 -434
  147. package/docs/tui-viewer.md +13 -15
  148. package/docs/workflows.md +104 -50
  149. package/examples/workflows/plain-summary.workflow.ts +1 -0
  150. package/herdr-plugin.toml +1 -1
  151. package/package.json +1 -1
  152. package/plugins/herdr/viewer.mjs +1 -11
  153. package/skills/autoplan/SKILL.md +5 -4
  154. package/skills/monitor/SKILL.md +91 -163
  155. package/skills/pi-workflows/SKILL.md +7 -7
  156. package/skills/sanity-check/SKILL.md +1 -1
  157. package/src/builtins/autoplan.workflow.ts +290 -40
  158. package/src/builtins/catalog.ts +6 -4
  159. package/src/builtins/index.ts +7 -1
  160. package/src/builtins/monitor.workflow.ts +663 -249
  161. package/src/builtins/plain-summary.workflow.ts +185 -0
  162. package/src/builtins/sanity-check.workflow.ts +62 -7
  163. package/src/controllers/effects.ts +7 -0
  164. package/src/controllers/index.ts +0 -6
  165. package/src/controllers/manager.ts +72 -32
  166. package/src/controllers/sqlite.ts +2420 -1948
  167. package/src/controllers/store.ts +17 -38
  168. package/src/controllers/types.ts +3 -0
  169. package/src/controllers/workflow-engine-scheduler.ts +4 -8
  170. package/src/controllers/workflows.ts +45 -21
  171. package/src/extension/controller-host.ts +1 -2
  172. package/src/extension/decision-channels.ts +427 -144
  173. package/src/extension/executor.ts +105 -2
  174. package/src/extension/herdr-viewer.ts +0 -5
  175. package/src/extension/index.ts +180 -118
  176. package/src/extension/recorder.ts +13 -22
  177. package/src/extension/step-message.ts +106 -4
  178. package/src/extension/widget.ts +8 -0
  179. package/src/host/rpc-executor.ts +4 -0
  180. package/src/host/runner.ts +93 -41
  181. package/src/render/graph-render.ts +11 -4
  182. package/src/state/database.ts +375 -0
  183. package/src/state/index.ts +29 -0
  184. package/src/state/json.ts +42 -0
  185. package/src/state/mutation.ts +435 -0
  186. package/src/state/schema.ts +475 -0
  187. package/src/viewer/cli.ts +151 -144
  188. package/src/viewer/render.ts +12 -24
  189. package/src/viewer/session-reducer.ts +1 -1
  190. package/src/viewer/tui.ts +18 -17
  191. package/src/viewer/watch.ts +13 -17
  192. package/src/workflows/composition.ts +12 -3
  193. package/src/workflows/definition.ts +36 -3
  194. package/src/workflows/engine.ts +212 -116
  195. package/src/workflows/errors.ts +3 -3
  196. package/src/workflows/human-decision.ts +795 -340
  197. package/src/workflows/index.ts +15 -19
  198. package/src/workflows/schema.ts +19 -1
  199. package/src/workflows/store.ts +1295 -1163
  200. package/src/workflows/types.ts +61 -81
  201. package/dist/workflows/artifacts.d.ts +0 -40
  202. package/dist/workflows/artifacts.js +0 -155
  203. package/dist/workflows/artifacts.js.map +0 -1
  204. package/dist/workflows/migrate-sources.d.ts +0 -42
  205. package/dist/workflows/migrate-sources.js +0 -133
  206. package/dist/workflows/migrate-sources.js.map +0 -1
  207. package/docs/run-bundles.md +0 -481
  208. package/src/workflows/artifacts.ts +0 -188
  209. package/src/workflows/migrate-sources.ts +0 -178
@@ -0,0 +1,375 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import Database from "better-sqlite3";
6
+ import { canonicalJson, parseJson, type JsonValue } from "./json.js";
7
+ import {
8
+ STATE_APPLICATION_ID,
9
+ STATE_APP_VERSION,
10
+ STATE_SCHEMA_DIGEST,
11
+ STATE_SCHEMA_NAME,
12
+ STATE_SCHEMA_SQL,
13
+ STATE_SCHEMA_VERSION,
14
+ } from "./schema.js";
15
+
16
+ const DATABASE_FILE = "state.sqlite";
17
+ const BUSY_TIMEOUT_MS = 5_000;
18
+ const JOURNAL_SIZE_LIMIT = 64 * 1024 * 1024;
19
+ const RESET_INSTRUCTION =
20
+ "Pi Workflows durable state is incompatible. Move or remove the old workflow state, then create a new state.sqlite database.";
21
+
22
+ export type StateDatabaseMode = "read-write" | "read-only";
23
+
24
+ export type OpenStateDatabaseOptions = {
25
+ filePath?: string;
26
+ homeDir?: string;
27
+ mode?: StateDatabaseMode;
28
+ checkLegacyState?: boolean;
29
+ };
30
+
31
+ export type BlobRecord = {
32
+ hash: Buffer;
33
+ mediaType: string;
34
+ byteLength: number;
35
+ content: Buffer;
36
+ };
37
+
38
+ type SchemaObjectRow = {
39
+ type: string;
40
+ name: string;
41
+ tableName: string;
42
+ sql: string;
43
+ };
44
+
45
+ type SchemaMetaRow = {
46
+ schemaName: string;
47
+ schemaVersion: number;
48
+ schemaDigest: Buffer;
49
+ appVersion: string;
50
+ };
51
+
52
+ type BlobRow = {
53
+ blobHash: Buffer;
54
+ mediaType: string;
55
+ byteLength: number;
56
+ content: Buffer;
57
+ };
58
+
59
+ let expectedShape: string | undefined;
60
+
61
+ export function workflowStatePath(homeDir: string = os.homedir()): string {
62
+ return path.join(homeDir, ".pi", "agent", "workflows", DATABASE_FILE);
63
+ }
64
+
65
+ export class StateDatabase {
66
+ readonly filePath: string;
67
+ readonly mode: StateDatabaseMode;
68
+ readonly connection: Database.Database;
69
+
70
+ constructor(options: OpenStateDatabaseOptions = {}) {
71
+ this.filePath = path.resolve(options.filePath ?? workflowStatePath(options.homeDir));
72
+ this.mode = options.mode ?? "read-write";
73
+ const existed = fs.existsSync(this.filePath);
74
+ if (this.mode === "read-only" && !existed) {
75
+ throw new Error(`Pi Workflows state database does not exist: ${this.filePath}`);
76
+ }
77
+ if (!existed && this.mode === "read-write") {
78
+ if (options.checkLegacyState ?? options.filePath === undefined) {
79
+ assertNoLegacyState(this.filePath, options.homeDir ?? os.homedir());
80
+ }
81
+ fs.mkdirSync(path.dirname(this.filePath), { recursive: true, mode: 0o700 });
82
+ fs.chmodSync(path.dirname(this.filePath), 0o700);
83
+ }
84
+
85
+ this.connection = new Database(this.filePath, {
86
+ readonly: this.mode === "read-only",
87
+ fileMustExist: this.mode === "read-only",
88
+ timeout: BUSY_TIMEOUT_MS,
89
+ });
90
+
91
+ try {
92
+ this.configure(existed);
93
+ if (this.mode === "read-write") {
94
+ this.prepareSchema(!existed);
95
+ }
96
+ this.verifySchema();
97
+ if (this.mode === "read-only") {
98
+ this.connection.pragma("query_only = ON");
99
+ } else {
100
+ fs.chmodSync(this.filePath, 0o600);
101
+ }
102
+ } catch (error) {
103
+ this.connection.close();
104
+ throw error;
105
+ }
106
+ }
107
+
108
+ close(): void {
109
+ this.connection.close();
110
+ }
111
+
112
+ transaction<T>(operation: () => T): T {
113
+ if (this.mode === "read-only") {
114
+ throw new Error("Cannot mutate a read-only Pi Workflows database");
115
+ }
116
+ this.connection.exec("BEGIN IMMEDIATE");
117
+ try {
118
+ const result = operation();
119
+ this.connection.exec("COMMIT");
120
+ return result;
121
+ } catch (error) {
122
+ if (this.connection.inTransaction) {
123
+ this.connection.exec("ROLLBACK");
124
+ }
125
+ throw error;
126
+ }
127
+ }
128
+
129
+ putJson(value: unknown, now: number = Date.now()): Buffer {
130
+ return this.putBlob(Buffer.from(canonicalJson(value), "utf8"), "application/json", now);
131
+ }
132
+
133
+ putText(value: string, now: number = Date.now()): Buffer {
134
+ return this.putBlob(Buffer.from(value, "utf8"), "text/plain", now);
135
+ }
136
+
137
+ putBlob(content: Buffer, mediaType: string, now: number = Date.now()): Buffer {
138
+ if (this.mode === "read-only") {
139
+ throw new Error("Cannot write a blob through a read-only Pi Workflows database");
140
+ }
141
+ const hash = createHash("sha256").update(content).digest();
142
+ this.connection
143
+ .prepare(
144
+ `INSERT INTO blobs(blob_hash, media_type, byte_length, content, created_at)
145
+ VALUES (?, ?, ?, ?, ?)
146
+ ON CONFLICT(blob_hash) DO NOTHING`,
147
+ )
148
+ .run(hash, mediaType, content.byteLength, content, now);
149
+ const stored = this.readBlob(hash);
150
+ if (
151
+ stored === undefined ||
152
+ stored.mediaType !== mediaType ||
153
+ stored.byteLength !== content.byteLength ||
154
+ !stored.content.equals(content)
155
+ ) {
156
+ throw new Error("Content-addressed blob conflict");
157
+ }
158
+ return hash;
159
+ }
160
+
161
+ readBlob(hash: Buffer): BlobRecord | undefined {
162
+ const row = this.connection
163
+ .prepare(
164
+ `SELECT blob_hash AS blobHash, media_type AS mediaType,
165
+ byte_length AS byteLength, content
166
+ FROM blobs WHERE blob_hash = ?`,
167
+ )
168
+ .get(hash);
169
+ if (!isBlobRow(row)) {
170
+ return undefined;
171
+ }
172
+ return {
173
+ hash: row.blobHash,
174
+ mediaType: row.mediaType,
175
+ byteLength: row.byteLength,
176
+ content: row.content,
177
+ };
178
+ }
179
+
180
+ readJson(hash: Buffer): JsonValue {
181
+ const blob = this.readBlob(hash);
182
+ if (blob === undefined || blob.mediaType !== "application/json") {
183
+ throw new Error("JSON blob is missing or has the wrong media type");
184
+ }
185
+ return parseJson(blob.content.toString("utf8"));
186
+ }
187
+
188
+ integrityCheck(): void {
189
+ const result = this.connection.pragma("integrity_check", { simple: true });
190
+ if (result !== "ok") {
191
+ throw new Error(`Pi Workflows SQLite integrity check failed: ${String(result)}`);
192
+ }
193
+ const foreignKeys = this.connection.pragma("foreign_key_check");
194
+ if (!Array.isArray(foreignKeys) || foreignKeys.length !== 0) {
195
+ throw new Error("Pi Workflows SQLite foreign-key check failed");
196
+ }
197
+ }
198
+
199
+ async backup(destination: string): Promise<void> {
200
+ if (path.resolve(destination) === this.filePath) {
201
+ throw new Error("Backup destination must differ from the live database");
202
+ }
203
+ fs.mkdirSync(path.dirname(path.resolve(destination)), { recursive: true, mode: 0o700 });
204
+ this.integrityCheck();
205
+ await this.connection.backup(destination);
206
+ fs.chmodSync(destination, 0o600);
207
+ const backup = new StateDatabase({ filePath: destination, mode: "read-only" });
208
+ try {
209
+ backup.integrityCheck();
210
+ } finally {
211
+ backup.close();
212
+ }
213
+ }
214
+
215
+ private configure(existed: boolean): void {
216
+ this.connection.pragma("foreign_keys = ON");
217
+ this.connection.pragma(`busy_timeout = ${BUSY_TIMEOUT_MS}`);
218
+ if (this.mode === "read-write") {
219
+ this.connection.pragma("journal_mode = WAL");
220
+ this.connection.pragma("synchronous = FULL");
221
+ this.connection.pragma("wal_autocheckpoint = 1000");
222
+ this.connection.pragma(`journal_size_limit = ${JOURNAL_SIZE_LIMIT}`);
223
+ } else if (existed) {
224
+ this.connection.pragma("synchronous = FULL");
225
+ }
226
+ }
227
+
228
+ private prepareSchema(allowInitialize: boolean): void {
229
+ this.connection.exec("BEGIN EXCLUSIVE");
230
+ try {
231
+ const schema = this.connection
232
+ .prepare(
233
+ "SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'schema_meta'",
234
+ )
235
+ .get();
236
+ if (schema === undefined) {
237
+ if (!allowInitialize) throw new Error(RESET_INSTRUCTION);
238
+ this.initialize();
239
+ }
240
+ this.connection.exec("COMMIT");
241
+ } catch (error) {
242
+ if (this.connection.inTransaction) this.connection.exec("ROLLBACK");
243
+ throw error;
244
+ }
245
+ }
246
+
247
+ private initialize(): void {
248
+ this.connection.exec(STATE_SCHEMA_SQL);
249
+ this.connection.pragma(`application_id = ${STATE_APPLICATION_ID}`);
250
+ this.connection.pragma(`user_version = ${STATE_SCHEMA_VERSION}`);
251
+ const now = Date.now();
252
+ this.connection
253
+ .prepare(
254
+ `INSERT INTO schema_meta(
255
+ id, schema_name, schema_version, schema_digest, app_version, created_at, updated_at
256
+ ) VALUES (1, ?, ?, ?, ?, ?, ?)`,
257
+ )
258
+ .run(
259
+ STATE_SCHEMA_NAME,
260
+ STATE_SCHEMA_VERSION,
261
+ STATE_SCHEMA_DIGEST,
262
+ STATE_APP_VERSION,
263
+ now,
264
+ now,
265
+ );
266
+ }
267
+
268
+ private verifySchema(): void {
269
+ const applicationId = this.connection.pragma("application_id", { simple: true });
270
+ const userVersion = this.connection.pragma("user_version", { simple: true });
271
+ if (applicationId !== STATE_APPLICATION_ID || userVersion !== STATE_SCHEMA_VERSION) {
272
+ throw new Error(RESET_INSTRUCTION);
273
+ }
274
+ const row = this.connection
275
+ .prepare(
276
+ `SELECT schema_name AS schemaName, schema_version AS schemaVersion,
277
+ schema_digest AS schemaDigest, app_version AS appVersion
278
+ FROM schema_meta WHERE id = 1`,
279
+ )
280
+ .get();
281
+ if (
282
+ !isSchemaMetaRow(row) ||
283
+ row.schemaName !== STATE_SCHEMA_NAME ||
284
+ row.schemaVersion !== STATE_SCHEMA_VERSION ||
285
+ !row.schemaDigest.equals(STATE_SCHEMA_DIGEST) ||
286
+ row.appVersion !== STATE_APP_VERSION
287
+ ) {
288
+ throw new Error(RESET_INSTRUCTION);
289
+ }
290
+ if (schemaShape(this.connection) !== expectedSchemaShape()) {
291
+ throw new Error(RESET_INSTRUCTION);
292
+ }
293
+ }
294
+ }
295
+
296
+ function expectedSchemaShape(): string {
297
+ if (expectedShape !== undefined) {
298
+ return expectedShape;
299
+ }
300
+ const database = new Database(":memory:");
301
+ try {
302
+ database.pragma("foreign_keys = ON");
303
+ database.exec(STATE_SCHEMA_SQL);
304
+ expectedShape = schemaShape(database);
305
+ return expectedShape;
306
+ } finally {
307
+ database.close();
308
+ }
309
+ }
310
+
311
+ function schemaShape(database: Database.Database): string {
312
+ const rows = database
313
+ .prepare(
314
+ `SELECT type, name, tbl_name AS tableName, sql
315
+ FROM sqlite_schema
316
+ WHERE name NOT LIKE 'sqlite_%'
317
+ ORDER BY type, name`,
318
+ )
319
+ .all();
320
+ const normalized: SchemaObjectRow[] = [];
321
+ for (const row of rows) {
322
+ if (!isSchemaObjectRow(row)) {
323
+ throw new Error("Pi Workflows database contains an invalid schema object");
324
+ }
325
+ normalized.push(row);
326
+ }
327
+ return createHash("sha256").update(canonicalJson(normalized)).digest("hex");
328
+ }
329
+
330
+ function assertNoLegacyState(databasePath: string, homeDir: string): void {
331
+ const root = path.dirname(databasePath);
332
+ const legacy = [
333
+ path.join(root, "runs"),
334
+ path.join(root, "decisions"),
335
+ path.join(root, "controllers"),
336
+ ];
337
+ const telegramState = path.join(homeDir, ".config", "pi-workflows", "telegram-state.sqlite");
338
+ if (legacy.some((candidate) => fs.existsSync(candidate)) || fs.existsSync(telegramState)) {
339
+ throw new Error(RESET_INSTRUCTION);
340
+ }
341
+ }
342
+
343
+ function isSchemaObjectRow(value: unknown): value is SchemaObjectRow {
344
+ if (!isRecord(value)) return false;
345
+ return (
346
+ typeof value.type === "string" &&
347
+ typeof value.name === "string" &&
348
+ typeof value.tableName === "string" &&
349
+ typeof value.sql === "string"
350
+ );
351
+ }
352
+
353
+ function isSchemaMetaRow(value: unknown): value is SchemaMetaRow {
354
+ if (!isRecord(value)) return false;
355
+ return (
356
+ typeof value.schemaName === "string" &&
357
+ typeof value.schemaVersion === "number" &&
358
+ Buffer.isBuffer(value.schemaDigest) &&
359
+ typeof value.appVersion === "string"
360
+ );
361
+ }
362
+
363
+ function isBlobRow(value: unknown): value is BlobRow {
364
+ if (!isRecord(value)) return false;
365
+ return (
366
+ Buffer.isBuffer(value.blobHash) &&
367
+ typeof value.mediaType === "string" &&
368
+ typeof value.byteLength === "number" &&
369
+ Buffer.isBuffer(value.content)
370
+ );
371
+ }
372
+
373
+ function isRecord(value: unknown): value is Record<string, unknown> {
374
+ return typeof value === "object" && value !== null && !Array.isArray(value);
375
+ }
@@ -0,0 +1,29 @@
1
+ export {
2
+ StateDatabase,
3
+ workflowStatePath,
4
+ type BlobRecord,
5
+ type OpenStateDatabaseOptions,
6
+ type StateDatabaseMode,
7
+ } from "./database.js";
8
+ export { canonicalJson, parseJson, type JsonPrimitive, type JsonValue } from "./json.js";
9
+ export {
10
+ StateMutationStore,
11
+ StaleResourceError,
12
+ resourceIdFor,
13
+ tokenHash,
14
+ type ActorType,
15
+ type LeaseClaim,
16
+ type MutationActor,
17
+ type MutationResult,
18
+ type OwnerType,
19
+ type ResourceType,
20
+ type WritePermit,
21
+ } from "./mutation.js";
22
+ export {
23
+ STATE_APPLICATION_ID,
24
+ STATE_APP_VERSION,
25
+ STATE_SCHEMA_DIGEST,
26
+ STATE_SCHEMA_NAME,
27
+ STATE_SCHEMA_SQL,
28
+ STATE_SCHEMA_VERSION,
29
+ } from "./schema.js";
@@ -0,0 +1,42 @@
1
+ export type JsonPrimitive = string | number | boolean | null;
2
+ export type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
3
+
4
+ export function canonicalJson(value: unknown): string {
5
+ return JSON.stringify(normalizeJson(value));
6
+ }
7
+
8
+ export function parseJson(text: string): JsonValue {
9
+ return normalizeJson(JSON.parse(text) as unknown);
10
+ }
11
+
12
+ function normalizeJson(value: unknown): JsonValue {
13
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
14
+ return value;
15
+ }
16
+ if (typeof value === "number") {
17
+ if (!Number.isFinite(value)) {
18
+ throw new Error("JSON numbers must be finite");
19
+ }
20
+ return Object.is(value, -0) ? 0 : value;
21
+ }
22
+ if (Array.isArray(value)) {
23
+ return value.map((item) => normalizeJson(item));
24
+ }
25
+ if (typeof value === "object") {
26
+ const prototype = Object.getPrototypeOf(value) as object | null;
27
+ if (prototype !== Object.prototype && prototype !== null) {
28
+ throw new Error("Only plain objects can be stored as canonical JSON");
29
+ }
30
+ const input = value as Record<string, unknown>;
31
+ const output: { [key: string]: JsonValue } = {};
32
+ for (const key of Object.keys(input).sort()) {
33
+ const item = input[key];
34
+ if (item === undefined) {
35
+ continue;
36
+ }
37
+ output[key] = normalizeJson(item);
38
+ }
39
+ return output;
40
+ }
41
+ throw new Error(`Unsupported JSON value type: ${typeof value}`);
42
+ }