@osolmaz/pi-workflows 0.11.1 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,449 @@
1
+ ---
2
+ title: Make deferred workflow launches durable
3
+ author: Onur Solmaz <2453968+osolmaz@users.noreply.github.com>
4
+ date: 2026-08-20
5
+ ---
6
+
7
+ # Make deferred workflow launches durable
8
+
9
+ ## Goal
10
+
11
+ A successful `workflow start` call must create a real queued workflow before it returns. The model
12
+ must receive the final run ID, and Pi Workflows must start that run only after the current agent turn
13
+ settles.
14
+
15
+ If startup then fails, Pi Workflows must save the failure and start one new model turn with an
16
+ actionable error. The model can correct the request and call `workflow start` again. A failed launch
17
+ must release the session reservation so the corrected run can start.
18
+
19
+ This change stays inside Pi Workflows. It uses the existing project-scoped SQLite controller store
20
+ and documented Pi extension APIs. It does not change Pi, add a service, or add another database.
21
+
22
+ ## Current failure
23
+
24
+ The current tool path stores a pending launch only in `pendingToolLaunch`. It returns:
25
+
26
+ ```text
27
+ Workflow <name> will start after this turn finishes.
28
+ ```
29
+
30
+ After the agent turn settles, the `agent_settled` handler clears `pendingToolLaunch` and calls
31
+ `startRun`. If `startRun` fails, the handler sends only a TUI notification. No run ID was returned,
32
+ `workflow status` has no durable launch to inspect, and the model receives no new turn.
33
+
34
+ This happened twice while starting `autoimplement`. The tool reported a queued launch, but no run
35
+ became active. The initiating model could not see the startup error and incorrectly reported that
36
+ the workflow had started.
37
+
38
+ ## Decision
39
+
40
+ Use a durable prepared run and one model-visible failure follow-up.
41
+
42
+ During the `workflow start` tool call, Pi Workflows will:
43
+
44
+ 1. Resolve and validate the workflow and all available start conditions.
45
+ 2. Allocate the final run ID.
46
+ 3. Save a queued record in the existing SQLite workflow queue.
47
+ 4. Reserve the initiating Pi session.
48
+ 5. Return the run ID and say that the workflow is queued.
49
+
50
+ After the current agent turn settles, Pi Workflows will:
51
+
52
+ 1. Claim the queued record.
53
+ 2. Change it to `starting`.
54
+ 3. Build the engine and executor without running a node.
55
+ 4. Change the record to `running`.
56
+ 5. Release the engine to run the first node.
57
+
58
+ If startup fails, Pi Workflows will:
59
+
60
+ 1. Change the record to `failed`.
61
+ 2. Save a bounded safe error.
62
+ 3. Release the session reservation.
63
+ 4. Queue one durable failure notification for the owning Pi session.
64
+ 5. Send that notification through `pi.sendMessage` with `triggerTurn: true` and
65
+ `deliverAs: "followUp"`.
66
+
67
+ The new model turn will contain the failed run ID and an actionable error. The model can fix the
68
+ workflow reference, input, source, or local condition and call `workflow start` again. Each retry is
69
+ an explicit model action with a new run ID. Pi Workflows does not perform a blind automatic retry.
70
+
71
+ ## Alpha compatibility contract
72
+
73
+ Pi Workflows is in alpha. Change the current storage and tool contracts in place.
74
+
75
+ - Keep `pi-workflows.controller-store.v1`.
76
+ - Keep existing run-bundle schema identifiers.
77
+ - Do not add a v2 schema.
78
+ - Do not add a compatibility reader, data migration, dual path, alias, feature flag, or fallback to
79
+ `pendingToolLaunch`.
80
+ - Change the SQLite table definitions and TypeScript types directly.
81
+ - Remove the superseded status values and launch path in the same change.
82
+
83
+ An existing controller store with the old alpha table layout is incompatible. On open, Pi Workflows
84
+ must verify the required table columns and status contract. If the layout is old, it must stop with a
85
+ clear instruction to preserve any needed run evidence and reset the project-scoped controller store.
86
+ It must not silently reinterpret or delete old state.
87
+
88
+ Run bundles remain separate evidence. Resetting an incompatible controller queue must not delete run
89
+ bundle directories.
90
+
91
+ ## Public behavior
92
+
93
+ ### Start
94
+
95
+ A successful tool result becomes:
96
+
97
+ ```text
98
+ Workflow autoimplement queued (run autoimplement-...).
99
+ ```
100
+
101
+ The structured result contains:
102
+
103
+ ```json
104
+ {
105
+ "action": "start",
106
+ "workflow": "autoimplement",
107
+ "runId": "autoimplement-...",
108
+ "queued": true
109
+ }
110
+ ```
111
+
112
+ Queued means that the durable reservation exists. It does not mean that the engine is running.
113
+
114
+ Every check that can run before acknowledgement must run before the queue record is committed. This
115
+ includes:
116
+
117
+ - Workflow resolution and definition validation.
118
+ - Declared input validation.
119
+ - Parent checkpoint and source checks for continuations.
120
+ - Controller-store access.
121
+ - Existing active or queued session reservation.
122
+ - Pending final presentation conflicts.
123
+
124
+ A preflight error returns through the original tool call. The model can correct it in the same turn.
125
+ No queued record remains after a failed preflight.
126
+
127
+ ### Activation
128
+
129
+ Interactive activation starts only from a safe idle boundary:
130
+
131
+ - `agent_settled` after the initiating turn.
132
+ - `session_start` recovery when no agent turn is active.
133
+ - The next `agent_settled` event when recovery starts during an active turn.
134
+
135
+ Repeated lifecycle events must not start the same run twice. Claims use compare-and-set updates, a
136
+ claim token, a bounded lease, and a final fence before the engine starts its first node.
137
+
138
+ No compute node, shell action, function action, agent node, or presentation starts while the
139
+ initiating agent turn is active.
140
+
141
+ ### Failure and model iteration
142
+
143
+ A deferred startup failure becomes a terminal queued-run state. The safe follow-up message is:
144
+
145
+ ```text
146
+ Workflow autoimplement failed to start (run autoimplement-...): <safe reason>.
147
+ Inspect the error and call workflow start again only after you correct the cause.
148
+ ```
149
+
150
+ The message does not contain raw workflow input, prompt text, credentials, request headers, or a
151
+ stack trace.
152
+
153
+ The failure notification has a deterministic ID derived from the run ID. Pi Workflows records its
154
+ delivery in the existing notification outbox. Before a delivery retry, it checks the native Pi
155
+ session for that notification ID. This prevents a duplicate after a crash between session append and
156
+ outbox acknowledgement.
157
+
158
+ A failed launch releases the one-workflow session reservation before it sends the follow-up. The
159
+ model can therefore call `workflow start` during the new turn. If that launch also fails, the same
160
+ process repeats with a new run ID. The regular Pi loop and user control remain the bounds; Pi
161
+ Workflows does not create an internal retry loop.
162
+
163
+ ### Status
164
+
165
+ `workflow status` with a run ID reads the queued-run record before a run bundle exists. After the
166
+ engine starts, it also reads the normal run bundle.
167
+
168
+ Status reports these launch states:
169
+
170
+ ```text
171
+ queued
172
+ starting
173
+ running
174
+ failed
175
+ cancelled
176
+ parked
177
+ done
178
+ ```
179
+
180
+ A failed status includes only the bounded safe error. Status without a run ID shows the current
181
+ session reservation or the displayed run.
182
+
183
+ ### Cancellation
184
+
185
+ `workflow cancel` accepts the queued run ID. Cancellation changes `queued` or `starting` to
186
+ `cancelled` atomically and invalidates the activation fence. A race cannot release the executor after
187
+ cancellation wins.
188
+
189
+ A cancelled launch releases the session reservation and sends no failure follow-up. A later start
190
+ can create a new run.
191
+
192
+ ## Storage contract
193
+
194
+ Use the existing `workflow_run_queue` table as the source of truth for launch state.
195
+
196
+ Change its alpha v1 layout in place to store:
197
+
198
+ - Final run ID.
199
+ - Workflow name and immutable source identity.
200
+ - Definition digest.
201
+ - Private workflow input while activation needs it.
202
+ - Launch state.
203
+ - Owning Pi session.
204
+ - Claim token and lease expiry.
205
+ - Safe failure code and message.
206
+ - Created, updated, started, and finished times.
207
+
208
+ Replace the current `claimed`, `parked`, and `done` launch-state contract with:
209
+
210
+ ```text
211
+ queued | starting | running | parked | done | failed | cancelled
212
+ ```
213
+
214
+ Keep `parked` and `done` for current resume and terminal queue behavior. Remove `claimed`; `starting`
215
+ and `running` state its meaning directly.
216
+
217
+ Clear private queue input when the launch becomes `running`, `failed`, or `cancelled`. The normal run
218
+ bundle owns input after the engine starts.
219
+
220
+ Extend the existing `workflow_notifications` table in place so a notification can be run-level.
221
+ Add `launch_failure` to its kind contract and allow node and attempt identity to be absent for a
222
+ run-level notification. Reuse its delivery claim, lease, and delivered timestamp.
223
+
224
+ The project-scoped controller store remains private local state. Tests must verify restrictive file
225
+ and directory permissions.
226
+
227
+ ## State transitions
228
+
229
+ Only these launch transitions are valid:
230
+
231
+ ```text
232
+ queued -> starting
233
+ queued -> cancelled
234
+ starting -> running
235
+ starting -> failed
236
+ starting -> cancelled
237
+ starting -> queued # expired lease with no run bundle
238
+ running -> parked
239
+ running -> done
240
+ running -> failed
241
+ running -> cancelled
242
+ parked -> starting # explicit resume
243
+ parked -> cancelled
244
+ ```
245
+
246
+ Every transition uses an expected current state and claim token when applicable. A stale handler gets
247
+ no ownership and performs no side effect.
248
+
249
+ When recovery finds `starting` after a lease expires:
250
+
251
+ - No run bundle: return to `queued`.
252
+ - Valid running bundle: reconcile to `running` and use existing run recovery.
253
+ - Waiting bundle: reconcile to `parked`.
254
+ - Terminal bundle: reconcile to `done`, `failed`, or `cancelled`.
255
+ - Changed workflow source or unreadable bundle: record `failed` and notify the owning session.
256
+
257
+ ## Error contract
258
+
259
+ Classify startup failures into a small set of stable codes, such as:
260
+
261
+ ```text
262
+ workflow_not_found
263
+ workflow_invalid
264
+ input_invalid
265
+ source_changed
266
+ store_unavailable
267
+ activation_failed
268
+ cancelled
269
+ ```
270
+
271
+ Persist a plain safe message with a strict byte limit. Keep the original error only in transient
272
+ process memory for local debug logging. Never persist or send the stack, causes, raw input, prompt,
273
+ credential, or unbounded provider text.
274
+
275
+ A failure must remain useful. The safe message should name the check that failed and the action that
276
+ can correct it without including secret values.
277
+
278
+ ## Implementation plan
279
+
280
+ ### 1. Replace the alpha controller-store layout
281
+
282
+ Update `src/controllers/sqlite.ts` and its exported queue and notification types.
283
+
284
+ - Keep `CONTROLLER_STORE_SCHEMA` at `pi-workflows.controller-store.v1`.
285
+ - Change `SCHEMA_SQL` directly.
286
+ - Remove old alpha `ALTER TABLE` compatibility logic for the workflow queue.
287
+ - Add exact-layout validation after table creation.
288
+ - Add the launch states and safe failure fields.
289
+ - Generalize workflow notifications for run-level failure notices.
290
+ - Add a partial unique index for one `queued`, `starting`, or `running` interactive reservation per
291
+ origin session.
292
+
293
+ For an incompatible existing table, return a clear alpha reset error. Do not mutate it.
294
+
295
+ ### 2. Add atomic launch operations
296
+
297
+ Add focused SQLite methods:
298
+
299
+ - `reservePreparedRun`
300
+ - `claimPreparedRun`
301
+ - `markPreparedRunRunning`
302
+ - `failPreparedRun`
303
+ - `cancelPreparedRun`
304
+ - `parkRunningRun`
305
+ - `finishRunningRun`
306
+ - `findSessionReservation`
307
+ - `listRecoverableRuns`
308
+ - `recoverExpiredStartingRun`
309
+
310
+ Use `BEGIN IMMEDIATE`, expected states, claim tokens, and lease checks.
311
+
312
+ ### 3. Split preparation from activation
313
+
314
+ Refactor `src/extension/index.ts`.
315
+
316
+ Create a small `src/extension/launch-coordinator.ts` if it keeps state transitions and recovery out of
317
+ the extension entry point.
318
+
319
+ Preparation owns resolution, validation, run ID allocation, immutable source identity, definition
320
+ digest, and reservation. Activation owns claims, engine construction, recorder setup, `activeRun`,
321
+ running state, and executor release.
322
+
323
+ Controller child workflows remain on their controller scheduler path. Share pure workflow-resolution
324
+ helpers where useful, but do not make controller children wait for an interactive agent boundary.
325
+
326
+ ### 4. Change the start tool
327
+
328
+ Update `src/extension/workflow-tool.ts` and the extension start handler.
329
+
330
+ Return the queued run ID only after the SQLite transaction commits. Remove the old “will start”
331
+ result and every success message that says the workflow already started.
332
+
333
+ ### 5. Add the failure follow-up
334
+
335
+ Create a versioned custom message for launch results. Store only:
336
+
337
+ - Notification schema.
338
+ - Notification ID.
339
+ - Run ID.
340
+ - Workflow name.
341
+ - `failed` state.
342
+ - Safe error code and message.
343
+
344
+ Deliver it through public `pi.sendMessage` after settlement with `triggerTurn: true` and
345
+ `deliverAs: "followUp"`.
346
+
347
+ The notification asks the model to inspect and correct the cause. It does not automatically call
348
+ `workflow start`.
349
+
350
+ ### 6. Update status, cancellation, and recovery
351
+
352
+ Status must read the queue before a run bundle exists. Cancellation must target queued and starting
353
+ runs by ID. Session startup and agent settlement must ask the launch coordinator for recoverable work
354
+ owned by that session.
355
+
356
+ Delete `pendingToolLaunch` and all status, cancel, shutdown, and `agent_settled` branches that depend
357
+ on it.
358
+
359
+ ### 7. Keep rendering secondary
360
+
361
+ Render queued, starting, failed, and cancelled launch state in the TUI from durable storage. A TUI
362
+ notification can announce failure, but it is not the source of truth and is not the only delivery
363
+ surface.
364
+
365
+ ### 8. Update documentation
366
+
367
+ Update `docs/workflows.md` with the queued start contract, run ID, status, cancellation, failure
368
+ follow-up, and model retry behavior. Update controller-store documentation with the alpha reset rule.
369
+ Do not document a v2 schema or migration path.
370
+
371
+ ## Tests
372
+
373
+ Add or update these tests:
374
+
375
+ 1. Clean alpha v1 store creation with the new exact layout.
376
+ 2. Old alpha v1 layout rejection with a clear reset instruction.
377
+ 3. No automatic table migration or silent deletion.
378
+ 4. One-session reservation and different-session independence.
379
+ 5. Durable run ID before the start tool returns.
380
+ 6. Synchronous preflight failure with no queue record.
381
+ 7. Zero engine activity before `agent_settled`.
382
+ 8. Duplicate `agent_settled` and `session_start` events with one activation.
383
+ 9. Lease expiry and recovery at every activation boundary.
384
+ 10. Cancellation before claim, during `starting`, and before executor release.
385
+ 11. Source change between preparation and activation.
386
+ 12. Safe error redaction and byte bounds.
387
+ 13. One durable launch-failure notification.
388
+ 14. Crash before session append, after append, and before outbox acknowledgement.
389
+ 15. Failed reservation release followed by a corrected model start.
390
+ 16. Repeated model correction attempts with one active reservation at a time.
391
+ 17. Status for every launch and run state.
392
+ 18. Current child workflow, continuation, parking, resume, recorder, widget, and presentation
393
+ behavior.
394
+
395
+ Add a real Pi end-to-end test in `test/e2e/workflow.e2e.test.ts` with the existing mock provider:
396
+
397
+ 1. The model calls `workflow start` for a valid file workflow.
398
+ 2. The tool returns a durable queued run ID.
399
+ 3. The test changes or removes the workflow source before the initiating turn settles.
400
+ 4. Activation records `failed`.
401
+ 5. Pi sends one follow-up model turn with the safe error.
402
+ 6. The model corrects the request and calls `workflow start` again.
403
+ 7. The new run starts and reaches its first workflow step.
404
+ 8. The first failed run remains inspectable by ID.
405
+
406
+ The test must use the packaged extension and real Pi lifecycle events. It must not call a real model
407
+ or external service.
408
+
409
+ ## Acceptance criteria
410
+
411
+ - The start tool never reports success without a committed queued record and final run ID.
412
+ - The model can correct synchronous start errors in the same turn.
413
+ - A deferred startup failure always becomes durable before notification.
414
+ - One failure notification starts one new model turn.
415
+ - The model can correct the cause and start a new run.
416
+ - Failed and cancelled launches release the session reservation.
417
+ - No two runs activate for one reservation.
418
+ - Reload, restart, compaction, and repeated settlement do not lose or duplicate a launch.
419
+ - Status and cancellation work before a run bundle exists.
420
+ - Private input and error details do not leak.
421
+ - No Pi change, new service, new database, v2 schema, compatibility path, or migration exists.
422
+ - The old `pendingToolLaunch` path is gone.
423
+
424
+ ## Verification
425
+
426
+ Run the canonical repository gates:
427
+
428
+ ```bash
429
+ npm run check
430
+ npm run test:e2e
431
+ npx slophammer-ts@latest dry .
432
+ npx slophammer-ts@latest check . --only ts.dependency-boundaries-required
433
+ git diff --check
434
+ ```
435
+
436
+ Run Pi Reviewer against the base branch and fix all valid P0 and P1 findings before release work.
437
+
438
+ Package publication and OnurPi adoption are separate tasks. Do not edit an installed `node_modules`
439
+ copy as the implementation source.
440
+
441
+ ## Non-goals
442
+
443
+ - Do not change Pi or propose a new Pi API.
444
+ - Do not add a service, daemon, remote queue, telemetry endpoint, or second database.
445
+ - Do not preserve old alpha controller-store layouts.
446
+ - Do not add a migration or v2 schema.
447
+ - Do not add blind automatic workflow retries.
448
+ - Do not change built-in workflow behavior except for test fixtures needed to verify startup.
449
+ - Do not publish or adopt a package as part of this documentation change.
package/docs/workflows.md CHANGED
@@ -556,6 +556,13 @@ possible. Defaults worth knowing:
556
556
  held without nudges and the engine pauses at the next boundary. Node
557
557
  timeouts keep ticking while held, so a long-abandoned step still times out.
558
558
  `/workflow resume` re-delivers the pending step prompt.
559
+ - A model-started workflow is persisted as `queued` with its final run ID before the start tool
560
+ returns. Activation waits for the initiating agent turn to settle, then moves through `starting`
561
+ and `running`. `workflow status` and `workflow cancel` accept the run ID before a run bundle
562
+ exists.
563
+ - If deferred activation fails, the queue stores a bounded safe error, releases the session
564
+ reservation, and sends one follow-up turn to the initiating model. The model can correct the
565
+ cause and make a new explicit start call. Pi Workflows does not retry blindly.
559
566
  - `/workflow cancel` aborts the current node and marks the run `cancelled`.
560
567
  When no run is live but the widget still shows a parked or finished run,
561
568
  the same command clears the widget.
package/herdr-plugin.toml CHANGED
@@ -1,6 +1,6 @@
1
1
  id = "osolmaz.pi-workflows"
2
2
  name = "Pi Workflows"
3
- version = "0.11.1"
3
+ version = "0.11.2"
4
4
  min_herdr_version = "0.7.0"
5
5
  description = "Open the active Pi Workflows run in piw from a managed Herdr pane."
6
6
  platforms = ["linux", "macos"]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@osolmaz/pi-workflows",
3
- "version": "0.11.1",
3
+ "version": "0.11.2",
4
4
  "description": "Workflow and controller runtime with a live terminal viewer for the pi coding agent",
5
5
  "keywords": [
6
6
  "pi-package"