@juicesharp/rpiv-workflow 2.1.0 → 2.3.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 (57) hide show
  1. package/audit-ctx.ts +16 -8
  2. package/audit-rows.ts +10 -0
  3. package/audit.ts +48 -26
  4. package/chain-state.ts +26 -1
  5. package/death-scene.ts +232 -0
  6. package/docs/embedding.md +1 -1
  7. package/docs/workflow-authoring.md +2 -2
  8. package/events.ts +3 -27
  9. package/execution-host.ts +9 -0
  10. package/failure-memos.ts +74 -0
  11. package/handle.ts +16 -1
  12. package/host.ts +13 -1
  13. package/internal.ts +1 -0
  14. package/loop-def.ts +9 -5
  15. package/loop-kinds.ts +16 -13
  16. package/loop-parallel.ts +116 -95
  17. package/loop-waves.ts +3 -3
  18. package/loop.ts +46 -43
  19. package/messages.ts +53 -14
  20. package/outcomes/collectors/workspace-diff.ts +3 -3
  21. package/outcomes/git-commit.ts +11 -4
  22. package/output-spec.ts +7 -7
  23. package/package.json +5 -2
  24. package/preview.ts +8 -1
  25. package/registration.ts +8 -3
  26. package/routing.ts +1 -41
  27. package/runner/chain-advance.ts +50 -32
  28. package/runner/errors.ts +1 -1
  29. package/runner/failure.ts +22 -23
  30. package/runner/preflight.ts +3 -6
  31. package/runner/resolve-stage.ts +3 -3
  32. package/runner/resume-entry.ts +5 -5
  33. package/runner/resume-loop.ts +5 -5
  34. package/runner/resume.ts +1 -1
  35. package/runner/run-context.ts +13 -3
  36. package/runner/run-stage.ts +134 -60
  37. package/runner/runner.ts +19 -9
  38. package/runner/script-stage.ts +17 -17
  39. package/sessions/bash-strikes.ts +182 -0
  40. package/sessions/extraction.ts +51 -37
  41. package/sessions/halt-routing.ts +18 -13
  42. package/sessions/index.ts +1 -1
  43. package/sessions/reattach.ts +10 -10
  44. package/sessions/sessions.ts +63 -19
  45. package/sessions/spawn.ts +5 -5
  46. package/sessions/success-persist.ts +9 -3
  47. package/stage-def.ts +2 -2
  48. package/stage-errors.ts +1 -1
  49. package/stage-identity.ts +43 -4
  50. package/state/index.ts +1 -1
  51. package/state/names.ts +1 -1
  52. package/state/reads.ts +1 -1
  53. package/state/state.ts +14 -4
  54. package/state/writes.ts +2 -2
  55. package/transcript.ts +30 -0
  56. package/types.ts +105 -15
  57. package/worktree-digest.ts +148 -0
package/types.ts CHANGED
@@ -16,7 +16,7 @@
16
16
  *
17
17
  * Per-stage / per-phase sessions extend a shared `SessionContext` base
18
18
  * (cwd, runId, state, prompt, skill). The audit layer pins its dependency
19
- * on this base structurally via `AuditCtx = Pick<SessionContext, ...>`.
19
+ * on this base structurally via `AuditContext = Pick<SessionContext, ...>`.
20
20
  *
21
21
  * Lives apart from runner.ts / sessions.ts so both can reference the same
22
22
  * shapes without a runtime import cycle (type-only refs back via this
@@ -30,6 +30,7 @@ import type { ModelSelection, WorkflowHost, WorkflowHostContext } from "./host.j
30
30
  import type { Output } from "./output.js";
31
31
  import type { SkillContractMap } from "./skill-contract.js";
32
32
  import type { SessionRef } from "./state/index.js";
33
+ import type { BranchEntry } from "./transcript.js";
33
34
  import type { RunTrigger } from "./triggers.js";
34
35
 
35
36
  // Re-export the host port so runtime layers can pull `RunContext`,
@@ -95,6 +96,17 @@ export interface RunState {
95
96
  */
96
97
  lastSession?: SessionRef;
97
98
 
99
+ /**
100
+ * Validation-retry gate memory — the digest captured the last time a
101
+ * schema-validated produces stage was dispatched, keyed with the stage name
102
+ * + `stagesCompleted` at capture. TRANSIENT: not persisted to JSONL (the
103
+ * resume fold reconstructs `RunState` from rows, not from a serialized
104
+ * blob), so operator resume starts with a fresh gate — matching the
105
+ * fresh-strike-budget policy. `undefined` until a qualifying stage is
106
+ * dispatched (the gate's no-regression short-circuit).
107
+ */
108
+ lastGatedDispatch?: { stage: string; digest: string; stagesCompleted: number };
109
+
98
110
  // ── Telemetry (post-hoc only; not consulted by chain advancement) ──
99
111
  telemetry: {
100
112
  /**
@@ -123,6 +135,18 @@ export interface RunState {
123
135
  droppedFailureRows: string[];
124
136
  };
125
137
 
138
+ // ── Failure memos (consumed by chain advancement — next prompt) ─────
139
+ /**
140
+ * Bounded log of stage/unit failures this run has already incurred,
141
+ * surfaced as an additive prompt suffix on every subsequently-built
142
+ * stage/unit session via `failureMemoSuffix`. Empty on a clean run ⇒ the
143
+ * suffix is `""` ⇒ byte-identical prompt. Capped at `MAX_FAILURE_MEMOS`
144
+ * (oldest dropped); each entry's `errMsg` is length-bounded. NOT telemetry:
145
+ * it is mutable bookkeeping the next agent's prompt reads, so it sits
146
+ * between the telemetry block and `termination`.
147
+ */
148
+ failureMemos: FailureMemo[];
149
+
126
150
  // ── Termination (set once at end-of-run) ───────────────────────────
127
151
  /**
128
152
  * How the run ended — `"running"` until the single end-of-run write via
@@ -156,6 +180,21 @@ export type RunTermination =
156
180
  | { status: "aborted"; error: string }
157
181
  | { status: "cancelled"; error: string };
158
182
 
183
+ /**
184
+ * One entry in `RunState.failureMemos` — a bounded record of a stage/unit
185
+ * failure this run has already incurred, surfaced to the next agent's prompt
186
+ * as an additive suffix so the run does not repeat a dead end. `stage` is the
187
+ * machine identity (a loop unit's parent, or the audit `stageName` for a
188
+ * non-unit failure); `unitId` is set only for a loop-unit failure (the unit's
189
+ * stable audit id). `ts` is an ISO-8601 timestamp.
190
+ */
191
+ export interface FailureMemo {
192
+ stage: string;
193
+ unitId?: string;
194
+ errMsg: string;
195
+ ts: string;
196
+ }
197
+
159
198
  // ---------------------------------------------------------------------------
160
199
  // Public run envelope — options in, result out
161
200
  // ---------------------------------------------------------------------------
@@ -200,10 +239,16 @@ export interface RunWorkflowOptions {
200
239
  signal?: AbortSignal;
201
240
  /**
202
241
  * Per-stage model-override resolver, injected by the embedder. Threaded onto
203
- * `RunContext.resolveModel` → every `StageSession.model`; the host applies it
242
+ * `RunContext.resolveModel` → every `StageSessionContext.model`; the host applies it
204
243
  * at child-session creation. Undefined ⇒ host default for every stage.
205
244
  */
206
245
  resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
246
+ /**
247
+ * Worktree-digest override for the validation-retry gate — threaded
248
+ * onto `RunContext.worktreeDigest` → every `StageSessionContext.worktreeDigest`.
249
+ * Undefined ⇒ the built-in `computeWorktreeDigest` (git + artifacts).
250
+ */
251
+ worktreeDigest?: (cwd: string) => string | undefined;
207
252
  /**
208
253
  * Human-readable alias for this run. Stored in the JSONL header and the
209
254
  * sidecar names.json index. Rejected if already in use — the error
@@ -271,12 +316,10 @@ export interface RunContext {
271
316
  runId: string;
272
317
  workflow: Workflow;
273
318
  /**
274
- * Upper bound for stage-progress display — count of stages reachable from
275
- * `workflow.start`, computed once at run start. The actual stage count
276
- * is path-dependent (a predicate edge may short-circuit), so this is the
277
- * denominator surfaced through the lifecycle `LifecycleContext.totalStages`
278
- * (e.g. the lane-dock `visited/totalStages` progress bar); the numerator is
279
- * the live stage index.
319
+ * Count of stages reachable from `workflow.start`, computed once at run
320
+ * start. The actual stage count is path-dependent (a predicate edge may
321
+ * short-circuit); surfaced as run metadata through the lifecycle
322
+ * `LifecycleContext.totalStages`.
280
323
  */
281
324
  totalStages: number;
282
325
  state: RunState;
@@ -318,7 +361,7 @@ export interface RunContext {
318
361
  * lacks a stage `inputSchema` (a harvested `consumes.data` is the
319
362
  * stage's own `inputSchema` re-derived, already covered by
320
363
  * `ensureInputValid`);
321
- * - `effectiveOutputSchema` (threaded onto `StageSession`) sources a
364
+ * - `effectiveOutputSchema` (threaded onto `StageSessionContext`) sources a
322
365
  * declared `produces.data` as the output schema when the stage carries
323
366
  * no `outputSchema` of its own.
324
367
  * Fail-soft: both degrade (no validation, never throw) when absent.
@@ -327,10 +370,30 @@ export interface RunContext {
327
370
  /**
328
371
  * Resolve a per-stage model override, injected by the embedder (rpiv-pi maps
329
372
  * each `{ stage, skill }` to its model/effort override). The runner threads
330
- * the result onto every `StageSession.model`; the host applies it at child
373
+ * the result onto every `StageSessionContext.model`; the host applies it at child
331
374
  * creation (NOT via global mutation). Undefined ⇒ host default.
332
375
  */
333
376
  resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
377
+ /**
378
+ * Host-injected reader that re-opens a persisted child-session JSONL and
379
+ * returns its branch (`SessionManager.open(file).getBranch()` on the rpiv-pi
380
+ * side, narrowed to `BranchEntry[]`). Consumed by the death-scene artifact
381
+ * writer at failure time (death-scene.ts) — the ONLY reader. Undefined for
382
+ * programmatic embedders / no provider, in which case the writer degrades
383
+ * silently (no artifact, no warning). Threaded provider → executor →
384
+ * `RunContext` → `SessionContext` → `AuditContext` → `auditFor`.
385
+ */
386
+ readSessionBranch?: (file: string) => BranchEntry[] | undefined;
387
+ /**
388
+ * Worktree-digest resolver injected by the embedder (tests / programmatic
389
+ * embedders that want to stub the filesystem). Threaded onto every
390
+ * `StageSessionContext.worktreeDigest` and read by the validation-retry gate
391
+ * (`packages/rpiv-workflow/sessions/extraction.ts` mechanism-1 +
392
+ * `packages/rpiv-workflow/runner/run-stage.ts` mechanism-2) via
393
+ * `resolveDigest` (`worktree-digest.ts`). Undefined ⇒ the built-in
394
+ * `computeWorktreeDigest` (git + `.rpiv/artifacts/` recipe).
395
+ */
396
+ worktreeDigest?: (cwd: string) => string | undefined;
334
397
  maxBackwardJumps: number;
335
398
  /**
336
399
  * Run-wide safety cap on loop units — clamps the effective cap of EVERY
@@ -346,7 +409,7 @@ export interface RunContext {
346
409
  lifecycle: LifecycleDispatcher;
347
410
  /**
348
411
  * Optional cooperative-cancellation signal from `RunWorkflowOptions.signal`.
349
- * Checked at the between-stage seam (top of `runStageOrRecordFailure`, before
412
+ * Checked at the between-stage seam (top of `dispatchStageOrRecordFailure`, before
350
413
  * the start stage and before every routed next stage). An aborted signal
351
414
  * records an `"aborted"` terminal row and unwinds — it does NOT interrupt a
352
415
  * stage already streaming (Pi owns the live session).
@@ -355,9 +418,9 @@ export interface RunContext {
355
418
  }
356
419
 
357
420
  /**
358
- * Per-stage / per-unit common base. Extended by `StageSession` (loop units
359
- * thread their identity through `StageSession.unit`); consumed in pick form by
360
- * `AuditCtx` (audit.ts) so the audit layer pins its dependency on this shape
421
+ * Per-stage / per-unit common base. Extended by `StageSessionContext` (loop units
422
+ * thread their identity through `StageSessionContext.unit`); consumed in pick form by
423
+ * `AuditContext` (audit.ts) so the audit layer pins its dependency on this shape
361
424
  * structurally instead of duplicating the field list.
362
425
  *
363
426
  * `stageName` is the workflow stage's record key — the value that lands
@@ -398,6 +461,15 @@ export interface SessionContext {
398
461
  * output production; pre-output halts allocate at record time instead.
399
462
  */
400
463
  allocatedStageNumber?: number;
464
+ /**
465
+ * Host-injected persisted-session branch reader, threaded from
466
+ * `RunContext.readSessionBranch`. Read by the death-scene artifact writer
467
+ * (`writeDeathSceneArtifact`) via `AuditContext`; absent for programmatic
468
+ * embedders (the writer degrades silently). Travels FURTHER than
469
+ * `resolveModel` — into `SessionContext` → `AuditContext` → `auditFor` —
470
+ * because the writer reads it from `AuditContext` at failure time.
471
+ */
472
+ readSessionBranch?: (file: string) => BranchEntry[] | undefined;
401
473
  }
402
474
 
403
475
  /**
@@ -418,7 +490,7 @@ export interface UnitRef {
418
490
  label: string;
419
491
  }
420
492
 
421
- export interface StageSession extends SessionContext {
493
+ export interface StageSessionContext extends SessionContext {
422
494
  stage: StageDef;
423
495
  /**
424
496
  * Registered skill-contract registry, threaded from
@@ -438,6 +510,13 @@ export interface StageSession extends SessionContext {
438
510
  * ⇒ host default.
439
511
  */
440
512
  model?: ModelSelection;
513
+ /**
514
+ * Worktree-digest resolver threaded from `RunContext.worktreeDigest` — read
515
+ * by the validation-retry mechanism-1 gate in `packages/rpiv-workflow/sessions/extraction.ts`
516
+ * (`resolveDigest(s.worktreeDigest, s.cwd)`). Undefined ⇒ built-in git +
517
+ * artifacts recipe.
518
+ */
519
+ worktreeDigest?: (cwd: string) => string | undefined;
441
520
  /**
442
521
  * Per-child cooperative-abort signal. Threaded from `RunContext.signal` (the
443
522
  * fanout dispatcher narrows it to a per-generation controller) so
@@ -465,6 +544,17 @@ export interface StageSession extends SessionContext {
465
544
  laneUnitIndex?: number;
466
545
  /** Only set for continue stages — branch slice offset. */
467
546
  branchOffset?: number;
547
+ /**
548
+ * Per-activation bash-overrun strike-ceiling override (testability) —
549
+ * `undefined` ⇒ the `BASH_TIMEOUT_STRIKES` module default. Pin to `0` in a
550
+ * watchdog-contract test to force immediate exhaustion; pin to `N` to drive
551
+ * a multi-strike recovery without mutating env. Now the SOLE strike surface
552
+ * on `StageSessionContext`: the mutable accounting (used counter + reasons
553
+ * accumulator) lives in the private `StrikeBudget` value object held in
554
+ * `sessions/bash-strikes.ts`, keyed off this session (read once at first
555
+ * consume to resolve the budget's ceiling). Immutable per-activation.
556
+ */
557
+ bashTimeoutStrikes?: number;
468
558
  /**
469
559
  * Present iff this session IS one loop unit. Pre-decorated at session
470
560
  * construction by the driver (`stageName` carries the DISPLAY decoration;
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Worktree digest — fail-soft content fingerprint of `cwd`'s working tree.
3
+ *
4
+ * Used by the validation-retry gate to detect whether a stage's fix
5
+ * actually mutated anything observable between a failed validate and the retry
6
+ * (mechanism-1, captured around `askAgentToFix` in sessions/extraction.ts) or
7
+ * across a re-dispatch of an already-run `produces` stage (mechanism-2, at
8
+ * `runSingleStage` dispatch in runner/run-stage.ts). An UNCHANGED digest ⇒ the
9
+ * agent asked to fix changed nothing observable ⇒ the retry is skipped
10
+ * (fail fast) instead of re-running the same failing validation.
11
+ *
12
+ * Two components concatenated then hashed (a tracked-only digest
13
+ * misses a fix that touches ONLY a gitignored file under `.rpiv/artifacts/`,
14
+ * which `.gitignore` ignores, and would false-skip the gate):
15
+ * 1. the default git recipe — `git status --porcelain` + `git diff` (the same
16
+ * `execFileSync("git", [...], { stdio: ["ignore","pipe","ignore"] })`
17
+ * posture built-in-workflows.ts's `writeCommitBaseline` uses);
18
+ * 2. `hashArtifactsTree(cwd)` — a recursive walk of `<cwd>/.rpiv/artifacts/`
19
+ * hashing each file's relative path + contents so a gitignored-only
20
+ * artifact revision DOES change the digest.
21
+ *
22
+ * The whole `computeWorktreeDigest` is wrapped in try/catch → `undefined`
23
+ * (non-repo / git missing / unreadable tree), so BOTH gates degrade to
24
+ * "always proceed" on a missing signal — never skip on a missing signal.
25
+ *
26
+ * Leaf module: imports only `node:child_process` + `node:fs` + `node:crypto` +
27
+ * `node:path` (no back-edges), so the value-import DAG stays acyclic.
28
+ */
29
+
30
+ import { execFileSync } from "node:child_process";
31
+ import { createHash } from "node:crypto";
32
+ import { type Dirent, readdirSync, readFileSync } from "node:fs";
33
+ import { join, relative } from "node:path";
34
+
35
+ /** Wall-clock ceiling per git subprocess. The digest runs SYNCHRONOUSLY on the
36
+ * validation-retry critical path and the bash watchdog cannot cover it (not a
37
+ * tool call, and `execFileSync` blocks the event loop) — so a wedged git (e.g.
38
+ * a contended `index.lock` from a concurrent commit) must be killed here. On
39
+ * expiry `execFileSync` throws → the digest degrades to `undefined` → both
40
+ * gates proceed, the documented missing-signal behavior. */
41
+ const GIT_DIGEST_TIMEOUT_MS = 10_000;
42
+
43
+ /** Subtree of `.rpiv/artifacts/` excluded from the digest: death-scene sidecars
44
+ * are FORENSIC output of failures, not a fix an agent applied. In a concurrent
45
+ * collect-all fanout a sibling unit's failure writes here mid-window; hashing
46
+ * it would flip another unit's unchanged-digest verdict and defeat the
47
+ * fail-fast gate with a spurious "tree changed". */
48
+ const DIGEST_EXCLUDED_ARTIFACT_DIRS: ReadonlySet<string> = new Set(["failures"]);
49
+
50
+ /**
51
+ * Walk `<cwd>/.rpiv/artifacts/` recursively, hashing each file's relative
52
+ * path + contents so a revision to ANY artifact (incl. a gitignored-only one)
53
+ * changes the digest. Absent / empty / unreadable tree contributes nothing
54
+ * (fail-soft) — the digest then equals the git-only digest. Symlinks are NOT
55
+ * followed (a `Dirent.isDirectory()` is false for a symlink-to-dir) so a
56
+ * looping symlink cannot recurse unboundedly; an unreadable / broken-link
57
+ * target contributes a stable `<unreadable>` token.
58
+ */
59
+ function hashArtifactsTree(cwd: string): string {
60
+ const artifactsRoot = join(cwd, ".rpiv", "artifacts");
61
+ const entries = readdirRecursively(artifactsRoot, DIGEST_EXCLUDED_ARTIFACT_DIRS);
62
+ const hash = createHash("sha256");
63
+ for (const abs of entries.sort()) {
64
+ hash.update(relative(artifactsRoot, abs));
65
+ hash.update("\0");
66
+ try {
67
+ hash.update(readFileSync(abs));
68
+ } catch {
69
+ hash.update("<unreadable>");
70
+ }
71
+ hash.update("\0");
72
+ }
73
+ return hash.digest("hex");
74
+ }
75
+
76
+ /** Recursive `readdir` returning absolute file paths under `root` (symlinks not
77
+ * followed). `excludedTopDirs` names TOP-LEVEL subdirectories of `root` that are
78
+ * skipped entirely (deeper same-named dirs are not affected). */
79
+ function readdirRecursively(root: string, excludedTopDirs?: ReadonlySet<string>): string[] {
80
+ const out: string[] = [];
81
+ const walk = (dir: string, isRoot: boolean): void => {
82
+ let entries: Dirent[];
83
+ try {
84
+ entries = readdirSync(dir, { withFileTypes: true });
85
+ } catch {
86
+ return; // absent / unreadable dir — contributes nothing
87
+ }
88
+ for (const entry of entries) {
89
+ const abs = join(dir, entry.name);
90
+ if (entry.isDirectory()) {
91
+ if (isRoot && excludedTopDirs?.has(entry.name)) continue;
92
+ walk(abs, false);
93
+ } else out.push(abs); // files + symlinks (target read fail-soft, below)
94
+ }
95
+ };
96
+ walk(root, true);
97
+ return out;
98
+ }
99
+
100
+ /**
101
+ * Content fingerprint of `cwd`'s working tree — `git status --porcelain` +
102
+ * `git diff` concatenated with `hashArtifactsTree(cwd)`, then SHA-256 hashed.
103
+ * Mirrors built-in-workflows.ts's `writeCommitBaseline` git posture
104
+ * (`execFileSync` with stderr ignored so a non-repo cwd degrades silently).
105
+ *
106
+ * Returns `undefined` on ANY failure (non-repo / git missing / unreadable
107
+ * tree) so callers degrade to "proceed" rather than "skip" — a missing digest
108
+ * is NEVER a signal to gate.
109
+ */
110
+ export function computeWorktreeDigest(cwd: string): string | undefined {
111
+ try {
112
+ const status = execFileSync("git", ["status", "--porcelain"], {
113
+ cwd,
114
+ encoding: "utf-8",
115
+ stdio: ["ignore", "pipe", "ignore"],
116
+ timeout: GIT_DIGEST_TIMEOUT_MS,
117
+ });
118
+ // `diff HEAD` (not bare `diff`) so STAGED content changes the digest too — a fix
119
+ // that edits-and-stages leaves the porcelain status line and the unstaged diff
120
+ // both unchanged between two different staged states. In a repo with no commits
121
+ // yet, `HEAD` is unresolvable and the throw degrades to `undefined` (proceed).
122
+ const diff = execFileSync("git", ["diff", "HEAD"], {
123
+ cwd,
124
+ encoding: "utf-8",
125
+ stdio: ["ignore", "pipe", "ignore"],
126
+ timeout: GIT_DIGEST_TIMEOUT_MS,
127
+ });
128
+ const artifacts = hashArtifactsTree(cwd);
129
+ return createHash("sha256").update(status).update("\0").update(diff).update("\0").update(artifacts).digest("hex");
130
+ } catch {
131
+ return undefined;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Resolve the digest for a session — the per-session override (`s.worktreeDigest`,
137
+ * injected by tests / programmatic embedders) wins WHENEVER PRESENT, including
138
+ * when it returns `undefined` (an override simulating a non-repo must not fall
139
+ * through to the real computation). No override ⇒ the default
140
+ * `computeWorktreeDigest`. Exposed so the two gate sites share one
141
+ * override-vs-default resolution instead of re-spelling it.
142
+ */
143
+ export function resolveDigest(
144
+ computer: ((cwd: string) => string | undefined) | undefined,
145
+ cwd: string,
146
+ ): string | undefined {
147
+ return computer ? computer(cwd) : computeWorktreeDigest(cwd);
148
+ }