@juicesharp/rpiv-workflow 1.19.1 → 2.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 (136) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +154 -0
  5. package/audit.ts +158 -190
  6. package/built-ins.ts +40 -45
  7. package/chain-state.ts +220 -0
  8. package/command-run.ts +64 -31
  9. package/command.ts +123 -21
  10. package/docs/workflow-authoring.md +356 -63
  11. package/{lifecycle.ts → events.ts} +161 -37
  12. package/execution-host.ts +75 -0
  13. package/host.ts +149 -64
  14. package/index.ts +25 -81
  15. package/internal-utils.ts +171 -71
  16. package/internal.ts +22 -1
  17. package/judge.ts +241 -0
  18. package/layers.ts +10 -15
  19. package/load/alias.ts +6 -12
  20. package/load/cache.ts +9 -6
  21. package/load/index.ts +27 -106
  22. package/load/issues.ts +31 -0
  23. package/load/legacy.ts +102 -0
  24. package/load/merge.ts +2 -2
  25. package/load/resolve-default.ts +3 -4
  26. package/load/shape-guards.ts +3 -6
  27. package/load/skill-contract-phase.ts +94 -0
  28. package/loop-constructors.ts +24 -0
  29. package/loop-def.ts +285 -0
  30. package/loop-kinds.ts +750 -0
  31. package/loop-parallel.ts +250 -0
  32. package/loop-waves.ts +99 -0
  33. package/loop.ts +330 -0
  34. package/loops/constructors.ts +334 -0
  35. package/loops/derivations.ts +65 -0
  36. package/loops/introspection.ts +184 -0
  37. package/loops/panel.ts +196 -0
  38. package/loops/verify.ts +99 -0
  39. package/messages.ts +249 -156
  40. package/outcomes/collectors/directory-path.ts +7 -3
  41. package/outcomes/collectors/index.ts +1 -0
  42. package/outcomes/collectors/require-opt.ts +11 -0
  43. package/outcomes/collectors/text-scan.ts +47 -0
  44. package/outcomes/collectors/tool-call.ts +8 -3
  45. package/outcomes/collectors/transcript-path.ts +4 -18
  46. package/outcomes/collectors/union.ts +30 -10
  47. package/outcomes/collectors/url.ts +9 -14
  48. package/outcomes/collectors/workspace-diff.ts +21 -14
  49. package/outcomes/exec.ts +17 -0
  50. package/outcomes/git-commit.ts +190 -100
  51. package/outcomes/index.ts +1 -0
  52. package/outcomes/parsers/json-body.ts +2 -2
  53. package/outcomes/side-effect.ts +3 -3
  54. package/output-spec.ts +36 -10
  55. package/output.ts +98 -20
  56. package/package.json +27 -11
  57. package/predicates.ts +11 -8
  58. package/preview.ts +81 -21
  59. package/registration.ts +117 -36
  60. package/routing-dsl.ts +322 -0
  61. package/routing.ts +48 -2
  62. package/runner/by-name.ts +2 -1
  63. package/runner/by-run-id.ts +2 -1
  64. package/runner/chain-advance.ts +84 -56
  65. package/runner/errors.ts +10 -0
  66. package/runner/failure.ts +163 -0
  67. package/runner/index.ts +7 -13
  68. package/runner/input-validation.ts +16 -23
  69. package/runner/preflight.ts +169 -0
  70. package/runner/resolve-stage.ts +68 -0
  71. package/runner/resume-entry.ts +121 -0
  72. package/runner/resume-loop.ts +131 -0
  73. package/runner/resume.ts +368 -262
  74. package/runner/run-context.ts +165 -0
  75. package/runner/run-stage.ts +490 -0
  76. package/runner/runner.ts +202 -449
  77. package/runner/script-stage.ts +104 -112
  78. package/schema-compat.ts +12 -1
  79. package/semaphore.ts +55 -0
  80. package/sessions/extraction.ts +146 -81
  81. package/sessions/halt-routing.ts +195 -0
  82. package/sessions/index.ts +3 -1
  83. package/sessions/locate.ts +141 -0
  84. package/sessions/reattach.ts +71 -0
  85. package/sessions/sessions.ts +114 -199
  86. package/sessions/spawn.ts +132 -119
  87. package/sessions/success-persist.ts +89 -0
  88. package/skill-contract.ts +22 -25
  89. package/skill-contracts/composition.ts +86 -37
  90. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  91. package/skill-contracts/harvest.ts +4 -4
  92. package/skill-contracts/index.ts +15 -8
  93. package/skill-contracts/registry.ts +33 -50
  94. package/stage-def.ts +595 -0
  95. package/stage-errors.ts +84 -0
  96. package/stage-identity.ts +56 -0
  97. package/startup.ts +4 -1
  98. package/state/index.ts +8 -1
  99. package/state/names.ts +91 -65
  100. package/state/paths.ts +20 -0
  101. package/state/raw.ts +77 -0
  102. package/state/reads.ts +103 -85
  103. package/state/resolve.ts +73 -0
  104. package/state/state.ts +135 -15
  105. package/state/writes.ts +29 -12
  106. package/transcript.ts +24 -0
  107. package/triggers.ts +11 -3
  108. package/types.ts +290 -78
  109. package/validate/contract-compat.ts +198 -0
  110. package/validate/graph.ts +134 -0
  111. package/validate/issue.ts +328 -0
  112. package/validate/stage-rules.ts +499 -0
  113. package/validate-output.ts +82 -7
  114. package/validate-workflow.ts +57 -759
  115. package/validation-bounds.ts +35 -0
  116. package/control-flow.ts +0 -135
  117. package/fanout.ts +0 -102
  118. package/iterate.ts +0 -155
  119. package/load/cache.test.ts +0 -82
  120. package/load/shape-guards.test.ts +0 -74
  121. package/outcomes/collectors/directory-path.test.ts +0 -64
  122. package/outcomes/collectors/tool-call.test.ts +0 -110
  123. package/outcomes/collectors/transcript-path.test.ts +0 -70
  124. package/outcomes/collectors/union.test.ts +0 -59
  125. package/outcomes/collectors/url.test.ts +0 -67
  126. package/outcomes/collectors/workspace-diff.test.ts +0 -107
  127. package/outcomes/git-commit.test.ts +0 -194
  128. package/outcomes/parsers/json-body.test.ts +0 -80
  129. package/runner/by-name.test.ts +0 -95
  130. package/runner/by-run-id.test.ts +0 -115
  131. package/runner/resume-fanout.test.ts +0 -331
  132. package/runner/resume-fanout.ts +0 -136
  133. package/runner/resume-iterate.test.ts +0 -444
  134. package/runner/resume-iterate.ts +0 -111
  135. package/runner/resume.test.ts +0 -1130
  136. package/runner/stage-lifecycle.ts +0 -500
@@ -22,6 +22,7 @@ import type { Artifact } from "../../handle.js";
22
22
  import type { ArtifactCollector } from "../../output-spec.js";
23
23
  import { defineCollector } from "../../output-spec.js";
24
24
  import { iterToolUses } from "../../transcript.js";
25
+ import { requireOpt } from "./require-opt.js";
25
26
 
26
27
  export interface ToolCall {
27
28
  name: string;
@@ -45,9 +46,13 @@ export interface ToolCallCollectorOpts {
45
46
  }
46
47
 
47
48
  export function toolCallCollector(opts: ToolCallCollectorOpts): ArtifactCollector {
48
- if (typeof opts.match !== "function" || typeof opts.toArtifact !== "function") {
49
- throw new Error("toolCallCollector: `match` and `toArtifact` are required functions");
50
- }
49
+ requireOpt("toolCallCollector", "match", "is required and must be a function", typeof opts.match === "function");
50
+ requireOpt(
51
+ "toolCallCollector",
52
+ "toArtifact",
53
+ "is required and must be a function",
54
+ typeof opts.toArtifact === "function",
55
+ );
51
56
  const { match, toArtifact } = opts;
52
57
  return defineCollector({
53
58
  collect: (ctx) => {
@@ -20,8 +20,8 @@
20
20
 
21
21
  import { fs } from "../../handle.js";
22
22
  import type { ArtifactCollector } from "../../output-spec.js";
23
- import { defineCollector } from "../../output-spec.js";
24
- import { lastMatchInBranch } from "../../transcript.js";
23
+ import { requireOpt } from "./require-opt.js";
24
+ import { textScanCollector } from "./text-scan.js";
25
25
 
26
26
  export interface TranscriptPathCollectorOpts {
27
27
  /**
@@ -34,20 +34,6 @@ export interface TranscriptPathCollectorOpts {
34
34
  }
35
35
 
36
36
  export function transcriptPathCollector(opts: TranscriptPathCollectorOpts): ArtifactCollector {
37
- if (!(opts.pattern instanceof RegExp)) {
38
- throw new Error("transcriptPathCollector: `pattern` is required and must be a RegExp");
39
- }
40
- const pattern = opts.pattern;
41
- return defineCollector({
42
- collect: (ctx) => {
43
- const path = lastMatchInBranch(ctx.branch, pattern, ctx.branchOffset);
44
- if (!path) {
45
- return {
46
- kind: "fatal",
47
- message: `${ctx.skill} finished without producing a path matching ${pattern.source}`,
48
- };
49
- }
50
- return { kind: "ok", artifacts: [{ handle: fs(path), role: "primary" }] };
51
- },
52
- });
37
+ requireOpt("transcriptPathCollector", "pattern", "is required and must be a RegExp", opts.pattern instanceof RegExp);
38
+ return textScanCollector({ pattern: opts.pattern, toHandle: fs, noun: "path" });
53
39
  }
@@ -2,11 +2,18 @@
2
2
  * Union collector — runs N collectors and concatenates their artifacts.
3
3
  *
4
4
  * Useful for the "look in transcript OR tool calls" pattern, or for
5
- * combining a workspace-diff scan with a transcript URL scan. The
6
- * sub-collectors run sequentially; their `snapshot` hooks are NOT
7
- * threaded (each collector gets its own snapshot only if it declares
8
- * one and is invoked through `OutputSpec.collector` directly — wrapping
9
- * collectors inside a union loses individual snapshots today).
5
+ * combining a workspace-diff scan with a transcript URL scan.
6
+ *
7
+ * Snapshot fanout: when any sub-collector declares a `snapshot` hook, the
8
+ * union declares one too — it captures every sub-collector's snapshot into a
9
+ * positional array and threads `snapshots[i]` back into sub-collector *i*'s
10
+ * `collect`. A diff-based collector (workspace-diff, git-commit) composed
11
+ * into a union therefore behaves exactly as it would standalone. When no
12
+ * sub-collector snapshots, the union declares no hook (zero cost). A
13
+ * sub-collector snapshot throw propagates to the runner's
14
+ * `captureStageSnapshot` (which warns once and degrades the WHOLE capture to
15
+ * `undefined`) — sub-collectors must tolerate an `undefined` snapshot, the
16
+ * same contract they honor standalone.
10
17
  *
11
18
  * Fatal policy: `unionCollectors` returns `fatal` only when EVERY
12
19
  * sub-collector returned fatal (carries the last fatal message for
@@ -22,20 +29,33 @@
22
29
  */
23
30
 
24
31
  import type { Artifact } from "../../handle.js";
32
+ import { throwInvalid } from "../../internal-utils.js";
25
33
  import type { ArtifactCollector, CollectResult } from "../../output-spec.js";
26
34
  import { defineCollector } from "../../output-spec.js";
27
35
 
28
- export function unionCollectors(...collectors: ArtifactCollector[]): ArtifactCollector {
36
+ /** Positional sub-collector snapshots; `undefined` when capture degraded or no sub declared one. */
37
+ export type UnionSnapshot = unknown[] | undefined;
38
+
39
+ export function unionCollectors(...collectors: ArtifactCollector[]): ArtifactCollector<UnionSnapshot> {
29
40
  if (collectors.length === 0) {
30
- throw new Error("unionCollectors: at least one collector is required");
41
+ throwInvalid("unionCollectors", "at least one collector is required");
31
42
  }
32
- return defineCollector({
43
+ const anySnapshots = collectors.some((c) => typeof c.snapshot === "function");
44
+ return defineCollector<UnionSnapshot>({
45
+ ...(anySnapshots
46
+ ? {
47
+ snapshot: async (ctx): Promise<unknown[]> =>
48
+ Promise.all(collectors.map(async (c) => (c.snapshot ? await c.snapshot(ctx) : undefined))),
49
+ }
50
+ : {}),
33
51
  collect: async (ctx) => {
52
+ const snapshots = Array.isArray(ctx.snapshot) ? ctx.snapshot : undefined;
34
53
  const all: Artifact[] = [];
35
54
  let lastFatalMessage: string | undefined;
36
55
  let everySubCollectorFatal = true;
37
- for (const c of collectors) {
38
- const result: CollectResult = await c.collect(ctx);
56
+ for (let i = 0; i < collectors.length; i++) {
57
+ const c = collectors[i]!;
58
+ const result: CollectResult = await c.collect({ ...ctx, snapshot: snapshots?.[i] });
39
59
  if (result.kind === "fatal") {
40
60
  lastFatalMessage = result.message;
41
61
  continue;
@@ -12,8 +12,8 @@
12
12
 
13
13
  import { url } from "../../handle.js";
14
14
  import type { ArtifactCollector } from "../../output-spec.js";
15
- import { defineCollector } from "../../output-spec.js";
16
- import { lastMatchInBranch } from "../../transcript.js";
15
+ import { requireOpt } from "./require-opt.js";
16
+ import { textScanCollector } from "./text-scan.js";
17
17
 
18
18
  /**
19
19
  * Conservative URL matcher — `https?://` plus non-whitespace, stopping
@@ -29,17 +29,12 @@ export interface UrlCollectorOpts {
29
29
  }
30
30
 
31
31
  export function urlCollector(opts: UrlCollectorOpts = {}): ArtifactCollector {
32
+ requireOpt(
33
+ "urlCollector",
34
+ "pattern",
35
+ "must be a RegExp when provided",
36
+ opts.pattern === undefined || opts.pattern instanceof RegExp,
37
+ );
32
38
  const pattern = opts.pattern ?? DEFAULT_URL_PATTERN;
33
- return defineCollector({
34
- collect: (ctx) => {
35
- const href = lastMatchInBranch(ctx.branch, pattern, ctx.branchOffset);
36
- if (!href) {
37
- return {
38
- kind: "fatal",
39
- message: `${ctx.skill} finished without producing a URL matching ${pattern.source}`,
40
- };
41
- }
42
- return { kind: "ok", artifacts: [{ handle: url(href), role: "primary" }] };
43
- },
44
- });
39
+ return textScanCollector({ pattern, toHandle: url, noun: "URL" });
45
40
  }
@@ -7,10 +7,13 @@
7
7
  * files whose status changed both count. Pure git — no transcript
8
8
  * scanning, no tool-use observation, no agent narration involved.
9
9
  *
10
- * Fail-soft: cwd is not a git repo OR git isn't on PATH → snapshot is
11
- * `undefined`, collector returns `ok` with an empty list (the runner's
12
- * completion-strategy check then decides whether that's a halt). Same
13
- * posture as `gitCommitCollector`.
10
+ * "Nothing found" posture (see `CollectResult`'s convention doc): a snapshot
11
+ * that found no working git (not a repo, git not on PATH) degrades — the
12
+ * collector returns `ok []` and the workflow keeps moving (same posture as
13
+ * `gitCommitCollector`'s `baselineMissing`). But when git WORKED at snapshot
14
+ * time and fails after the stage, that's an environment break mid-stage —
15
+ * the collector returns `fatal` with the cause instead of conflating it
16
+ * with "no changes."
14
17
  *
15
18
  * Optional `filter(path)` narrows the set — useful for "only `.ts`
16
19
  * files," "only files under `src/`," etc. Authors who want more
@@ -19,16 +22,10 @@
19
22
  * thin diff primitive.
20
23
  */
21
24
 
22
- import { execFile } from "node:child_process";
23
- import { promisify } from "node:util";
24
25
  import { type Artifact, fs as fsHandle } from "../../handle.js";
25
- import type { ArtifactCollector, CollectCtx, SnapshotCtx } from "../../output-spec.js";
26
+ import type { ArtifactCollector, CollectCtx, CollectResult, SnapshotCtx } from "../../output-spec.js";
26
27
  import { defineCollector } from "../../output-spec.js";
27
-
28
- const execFileAsync = promisify(execFile);
29
-
30
- /** Same budget as gitCommitCollector — generous for local repos, short enough that a hung mount can't pin the stage. */
31
- const GIT_EXEC_TIMEOUT_MS = 5_000;
28
+ import { execFileAsync, GIT_EXEC_TIMEOUT_MS } from "../exec.js";
32
29
 
33
30
  export interface WorkspaceDiffSnapshot {
34
31
  /** Post-stage diff compares against this set of (path, statusCode) pairs captured pre-stage. */
@@ -65,12 +62,22 @@ async function capturePorcelainSnapshot(ctx: SnapshotCtx): Promise<WorkspaceDiff
65
62
  async function collectDiffArtifacts(
66
63
  ctx: CollectCtx<WorkspaceDiffSnapshot | undefined>,
67
64
  filter: ((path: string) => boolean) | undefined,
68
- ): Promise<{ kind: "ok"; artifacts: readonly Artifact[] }> {
65
+ ): Promise<CollectResult> {
69
66
  const snapshot = ctx.snapshot;
67
+ // No baseline = the stage ran outside a (working) git repo — documented
68
+ // degrade, not an error (see the module header).
70
69
  if (!snapshot) return { kind: "ok", artifacts: [] };
71
70
 
72
71
  const status = await runGitStatus(ctx.cwd);
73
- if (status === undefined) return { kind: "ok", artifacts: [] };
72
+ if (status === undefined) {
73
+ // git worked at snapshot time and fails now — an environment break,
74
+ // not "no changes." `ok []` here would route downstream logic on
75
+ // fabricated nothing-happened data.
76
+ return {
77
+ kind: "fatal",
78
+ message: `${ctx.skill}: git status worked at snapshot time but failed after the stage — cannot diff the workspace`,
79
+ };
80
+ }
74
81
  const post = parsePorcelain(status);
75
82
 
76
83
  const artifacts: Artifact[] = [];
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Shared async `execFile` plumbing for the git-backed outcomes
3
+ * (`git-commit.ts`, `collectors/workspace-diff.ts`). One promisified
4
+ * instance + one timeout budget so the two collectors can't drift.
5
+ */
6
+
7
+ import { execFile } from "node:child_process";
8
+ import { promisify } from "node:util";
9
+
10
+ export const execFileAsync = promisify(execFile);
11
+
12
+ /**
13
+ * Per git command. 5 s is generous for `rev-parse` / `log -1` /
14
+ * `diff --shortstat` / `status --porcelain` on local repos, short enough
15
+ * that a hung network mount can't pin the stage.
16
+ */
17
+ export const GIT_EXEC_TIMEOUT_MS = 5_000;
@@ -1,53 +1,89 @@
1
1
  /**
2
2
  * Git commit outcome + pre-stage git HEAD snapshot.
3
3
  *
4
- * Split into a collector (detects the commit and emits an `opaque(sha)`
5
- * handle) and a parser (parses commit metadata into `GitCommitData`).
6
- * `gitCommitOutcome` is the wired-up pair authors plug into a stage;
7
- * `gitCommitCollector` and `gitCommitParser` are individually exposed
8
- * so authors can compose them with other parsers / collectors.
4
+ * Split along the ENUMERATE/INTERPRET seam: the collector owns ALL git I/O
5
+ * (HEAD detection plus subject/files-changed interrogation, recorded on the
6
+ * artifact's `meta`); the parser is PURE — it validates the `meta` shape and
7
+ * projects it into `GitCommitData`, never re-shelling git at parse time
8
+ * (parse may re-run during validation retries, when the working tree has
9
+ * already moved on).
10
+ *
11
+ * Failure posture follows the package-wide "nothing found" convention
12
+ * (`CollectResult` doc, output-spec.ts) — with ONE documented exception:
13
+ * this collector always emits a single sentinel artifact (even on no-op)
14
+ * carrying the complete fact in `meta`, so the parser stays pure and total.
15
+ * The three cases:
16
+ * - not a git repo / git unavailable at snapshot time → no-op data
17
+ * (`baselineMissing`), the workflow keeps moving;
18
+ * - HEAD unchanged after the stage → honest no-op data;
19
+ * - git WORKED at snapshot time but fails after the stage → `fatal` (the
20
+ * environment broke mid-stage; fabricating `noOp: true` here would let
21
+ * `gate` route on invented data).
9
22
  *
10
23
  * Shells out asynchronously via `execFile` so a slow `git` invocation
11
24
  * (network-backed working tree, hung FS, large `--shortstat`) can't
12
25
  * pin the event loop.
13
26
  */
14
27
 
15
- import { execFile } from "node:child_process";
16
- import { promisify } from "node:util";
17
28
  import { type Artifact, opaque } from "../handle.js";
18
- import type {
19
- ArtifactCollector,
20
- ArtifactParser,
21
- CollectCtx,
22
- OutputSpec,
23
- ParseCtx,
24
- SnapshotCtx,
25
- } from "../output-spec.js";
26
-
27
- const execFileAsync = promisify(execFile);
29
+ import type { Output } from "../output.js";
30
+ import type { ArtifactCollector, ArtifactParser, CollectCtx, Outcome, ParseCtx, SnapshotCtx } from "../output-spec.js";
31
+ import { execFileAsync, GIT_EXEC_TIMEOUT_MS } from "./exec.js";
28
32
 
29
33
  /**
30
- * Output data shape produced by `gitCommitParser` — co-located with
31
- * the outcome that emits it. The `GitCommitOutput` alias in
32
- * `output.ts` re-imports this type so downstream stages can narrow on
33
- * `output.kind === "git-commit"` without reaching into per-outcome
34
- * paths.
34
+ * Output data shape produced by `gitCommitParser` — co-located with the
35
+ * outcome that emits it, as is the `GitCommitOutput` narrowing alias below.
35
36
  */
37
+ /** One commit the stage produced, journaled so earlier-phase commits stay visible. */
38
+ export interface GitCommitRecord {
39
+ sha: string;
40
+ subject: string;
41
+ }
42
+
36
43
  export interface GitCommitData {
37
44
  sha: string;
38
45
  prevSha: string;
39
46
  subject: string;
40
47
  filesChanged: number;
41
48
  noOp?: boolean;
49
+ /**
50
+ * EVERY commit in `prevSha..sha`, oldest-first — not just the head. A stage
51
+ * that lands several commits (an incremental implement pass) journaled only
52
+ * the head sha + an aggregate file count, leaving the earlier commits
53
+ * invisible in the trail; this preserves each one. Absent on a no-op.
54
+ */
55
+ commits?: readonly GitCommitRecord[];
42
56
  }
43
57
 
58
+ /** Tagged-union narrowing alias: `output.kind === "git-commit"` ⇒ `data: GitCommitData`. */
59
+ export type GitCommitOutput = Output<"git-commit", GitCommitData>;
60
+
44
61
  /** Snapshot captured before the stage runs. */
45
62
  export interface GitHeadSnapshot {
46
63
  baselineSha: string;
47
64
  }
48
65
 
49
- /** Per git command. 5 s is generous for `rev-parse` / `log -1` / `diff --shortstat` on local repos. */
50
- const GIT_EXEC_TIMEOUT_MS = 5_000;
66
+ /**
67
+ * The complete fact the collector records on its artifact's `meta` — the
68
+ * parser's ONLY input (it never shells git). `subject`/`filesChanged` are
69
+ * interrogated at collect time, while the SHAs still resolve.
70
+ */
71
+ export interface GitCommitArtifactMeta {
72
+ baselineSha: string;
73
+ headSha: string;
74
+ /** Snapshot found no baseline — not a git repo / git unavailable before the stage. */
75
+ baselineMissing: boolean;
76
+ /** HEAD did not move (or no baseline existed) — `subject`/`filesChanged` are empty/zero. */
77
+ noOp: boolean;
78
+ subject: string;
79
+ filesChanged: number;
80
+ /**
81
+ * Every commit in `baselineSha..headSha`, oldest-first, interrogated at
82
+ * collect time while the SHAs still resolve. Optional so a pre-existing
83
+ * (pre-`commits`) meta still passes `isGitCommitMeta`; empty/absent on a no-op.
84
+ */
85
+ commits?: readonly GitCommitRecord[];
86
+ }
51
87
 
52
88
  /** Run a git command from `cwd`, returning trimmed stdout. */
53
89
  async function git(cwd: string, ...args: string[]): Promise<string> {
@@ -78,66 +114,158 @@ export async function gitHeadSnapshot(ctx: SnapshotCtx): Promise<GitHeadSnapshot
78
114
  }
79
115
 
80
116
  // ---------------------------------------------------------------------------
81
- // Collector — detect "did HEAD move during this stage?"
117
+ // Collector — detect "did HEAD move during this stage?" + interrogate the fact
82
118
  // ---------------------------------------------------------------------------
83
119
 
84
120
  /**
85
- * Collector always emits exactly one artifact — even on no-op (HEAD
86
- * unchanged) or git-unavailable, with the handle's `id` carrying the
87
- * post-stage SHA (or empty string). The parser interprets the
88
- * `noOp` flag from the artifact's `meta`. This shape keeps the
89
- * collector's contract uniform (always one fact) while letting the
90
- * parser produce the rich `GitCommitData` downstream consumers expect.
121
+ * Collector emits exactly one artifact on every non-fatal path — no-op (HEAD
122
+ * unchanged) and git-unavailable-at-snapshot included — with the COMPLETE
123
+ * `GitCommitArtifactMeta` fact attached, so the parser stays pure. Fatal only
124
+ * when git worked at snapshot time and then failed after the stage: that's an
125
+ * environment break, not a no-op, and routing must not see fabricated data.
91
126
  */
92
127
  export const gitCommitCollector: ArtifactCollector<GitHeadSnapshot | undefined> = {
93
128
  snapshot: gitHeadSnapshot,
94
129
  async collect(ctx: CollectCtx<GitHeadSnapshot | undefined>) {
95
- const baselineSha = ctx.snapshot?.baselineSha ?? "";
96
- const headSha = await safeHead(ctx.cwd);
97
- const artifact: Artifact = {
98
- handle: opaque(headSha || baselineSha),
99
- role: "commit",
100
- meta: { baselineSha, headSha, baselineMissing: !ctx.snapshot },
101
- };
102
- return { kind: "ok", artifacts: [artifact] };
130
+ const baselineSha = ctx.snapshot?.baselineSha;
131
+ if (!baselineSha) {
132
+ // Deliberate degrade: the stage ran outside a (working) git repo.
133
+ return ok(noOpMeta("", "", { baselineMissing: true }));
134
+ }
135
+ let headSha: string;
136
+ try {
137
+ headSha = await git(ctx.cwd, "rev-parse", "HEAD");
138
+ } catch (e) {
139
+ return fatal(ctx.skill, `git rev-parse HEAD failed after the stage: ${describeError(e)}`);
140
+ }
141
+ if (!headSha || headSha === baselineSha) {
142
+ // Honest no-op — HEAD genuinely did not move.
143
+ return ok(noOpMeta(baselineSha, headSha));
144
+ }
145
+ try {
146
+ const [subject, filesChanged, commits] = await Promise.all([
147
+ git(ctx.cwd, "log", "-1", "--format=%s", headSha),
148
+ countFilesChanged(ctx.cwd, baselineSha, headSha),
149
+ listCommits(ctx.cwd, baselineSha, headSha),
150
+ ]);
151
+ return ok({ baselineSha, headSha, baselineMissing: false, noOp: false, subject, filesChanged, commits });
152
+ } catch (e) {
153
+ // A commit LANDED but its interrogation failed — fabricating noOp
154
+ // would route `gate` on invented data; halt with the real cause.
155
+ return fatal(ctx.skill, `commit ${headSha} landed but interrogating it failed: ${describeError(e)}`);
156
+ }
103
157
  },
104
158
  };
105
159
 
106
- async function safeHead(cwd: string): Promise<string> {
107
- try {
108
- return await git(cwd, "rev-parse", "HEAD");
109
- } catch {
110
- return "";
111
- }
160
+ const ok = (meta: GitCommitArtifactMeta): { kind: "ok"; artifacts: readonly Artifact[] } => ({
161
+ kind: "ok",
162
+ artifacts: [{ handle: opaque(meta.headSha || meta.baselineSha), role: "commit", meta: { ...meta } }],
163
+ });
164
+
165
+ const fatal = (skill: string, reason: string): { kind: "fatal"; message: string } => ({
166
+ kind: "fatal",
167
+ message: `${skill}: ${reason}`,
168
+ });
169
+
170
+ const noOpMeta = (
171
+ baselineSha: string,
172
+ headSha: string,
173
+ opts?: { baselineMissing?: boolean },
174
+ ): GitCommitArtifactMeta => ({
175
+ baselineSha,
176
+ headSha,
177
+ baselineMissing: opts?.baselineMissing ?? false,
178
+ noOp: true,
179
+ subject: "",
180
+ filesChanged: 0,
181
+ });
182
+
183
+ const describeError = (e: unknown): string => (e instanceof Error ? e.message : String(e));
184
+
185
+ /** Parse `git diff --shortstat` output for the "N files changed" count. */
186
+ async function countFilesChanged(cwd: string, baselineSha: string, headSha: string): Promise<number> {
187
+ const diffStat = await git(cwd, "diff", "--shortstat", baselineSha, headSha);
188
+ const match = diffStat.match(/^(\d+) files? changed/);
189
+ return match ? parseInt(match[1]!, 10) : 0;
190
+ }
191
+
192
+ /**
193
+ * Enumerate every commit in `baselineSha..headSha`, oldest-first — the full
194
+ * list a multi-commit stage produced, so the trail reflects each commit and not
195
+ * just the head. `%x1f` (unit separator) delimits sha↔subject so a subject
196
+ * containing spaces or tabs never mis-splits.
197
+ */
198
+ async function listCommits(cwd: string, baselineSha: string, headSha: string): Promise<GitCommitRecord[]> {
199
+ const raw = await git(cwd, "log", "--reverse", "--format=%H%x1f%s", `${baselineSha}..${headSha}`);
200
+ if (!raw) return [];
201
+ return raw.split("\n").flatMap((line) => {
202
+ const [sha, subject] = line.split("\x1f");
203
+ return sha ? [{ sha, subject: subject ?? "" }] : [];
204
+ });
112
205
  }
113
206
 
114
207
  // ---------------------------------------------------------------------------
115
- // Parser — turn the collected commit handle into typed GitCommitData
208
+ // Parser — PURE projection of the collected meta into typed GitCommitData
116
209
  // ---------------------------------------------------------------------------
117
210
 
211
+ /** Structural guard for the collector-emitted meta — the parser's input contract. */
212
+ function isGitCommitMeta(meta: unknown): meta is GitCommitArtifactMeta {
213
+ const m = meta as Partial<GitCommitArtifactMeta> | undefined;
214
+ return (
215
+ typeof m?.baselineSha === "string" &&
216
+ typeof m.headSha === "string" &&
217
+ typeof m.baselineMissing === "boolean" &&
218
+ typeof m.noOp === "boolean" &&
219
+ typeof m.subject === "string" &&
220
+ typeof m.filesChanged === "number" &&
221
+ // Optional (back-compat): a pre-`commits` meta omits it; when present it
222
+ // must be a well-formed record list.
223
+ (m.commits === undefined || (Array.isArray(m.commits) && m.commits.every(isGitCommitRecord)))
224
+ );
225
+ }
226
+
227
+ /** Structural guard for one journaled commit record. */
228
+ function isGitCommitRecord(r: unknown): r is GitCommitRecord {
229
+ const c = r as Partial<GitCommitRecord> | undefined;
230
+ return typeof c?.sha === "string" && typeof c.subject === "string";
231
+ }
232
+
233
+ /**
234
+ * Pure: validates the artifact's `meta` shape (fatal on mismatch — a blind
235
+ * cast here would coerce a foreign collector's artifact into fabricated
236
+ * commit data) and projects it into `GitCommitData`. No I/O.
237
+ */
118
238
  export const gitCommitParser: ArtifactParser<GitHeadSnapshot | undefined, "git-commit", GitCommitData> = {
119
- async parse(ctx: ParseCtx<GitHeadSnapshot | undefined>) {
239
+ parse(ctx: ParseCtx<GitHeadSnapshot | undefined>) {
120
240
  const artifact = ctx.artifacts[0];
121
- if (!artifact) {
122
- // Defensive — gitCommitCollector always emits one, but a composed
123
- // collector may not. Treat as no-op against the baseline.
124
- return { kind: "ok", payload: { kind: "git-commit", data: noOpData(ctx.snapshot?.baselineSha ?? "") } };
125
- }
126
- const meta = artifact.meta as { baselineSha: string; headSha: string; baselineMissing: boolean } | undefined;
127
- const baselineSha = meta?.baselineSha ?? "";
128
- const headSha = meta?.headSha ?? "";
129
-
130
- if (meta?.baselineMissing) {
131
- return { kind: "ok", payload: { kind: "git-commit", data: noOpData("") } };
241
+ const meta = artifact?.meta;
242
+ if (!isGitCommitMeta(meta)) {
243
+ return {
244
+ kind: "fatal",
245
+ message:
246
+ `${ctx.skill}: gitCommitParser requires the meta gitCommitCollector emits ` +
247
+ `(baselineSha/headSha/baselineMissing/noOp/subject/filesChanged) — ` +
248
+ (artifact ? "got an artifact with a foreign meta shape" : "got no artifact") +
249
+ "; compose it with gitCommitCollector",
250
+ };
132
251
  }
133
-
134
- const data = (await collectCommitData(ctx.cwd, baselineSha, headSha)) ?? noOpData(baselineSha);
252
+ const data: GitCommitData = meta.noOp
253
+ ? { sha: meta.headSha, prevSha: meta.baselineSha, subject: "", filesChanged: 0, noOp: true }
254
+ : {
255
+ sha: meta.headSha,
256
+ prevSha: meta.baselineSha,
257
+ subject: meta.subject,
258
+ filesChanged: meta.filesChanged,
259
+ // Project the per-commit journal through only when the collector
260
+ // recorded it — a pre-`commits` meta stays byte-identical.
261
+ ...(meta.commits ? { commits: meta.commits } : {}),
262
+ };
135
263
  return { kind: "ok", payload: { kind: "git-commit", data } };
136
264
  },
137
265
  };
138
266
 
139
267
  // ---------------------------------------------------------------------------
140
- // OutputSpec — the wired-up pair
268
+ // Outcome — the wired-up pair
141
269
  // ---------------------------------------------------------------------------
142
270
 
143
271
  /**
@@ -148,45 +276,7 @@ export const gitCommitParser: ArtifactParser<GitHeadSnapshot | undefined, "git-c
148
276
  * (undefined when not in a git repo), output kind is `"git-commit"`,
149
277
  * data is `GitCommitData`.
150
278
  */
151
- export const gitCommitOutcome: OutputSpec<GitHeadSnapshot | undefined, "git-commit", GitCommitData> = {
279
+ export const gitCommitOutcome: Outcome<GitHeadSnapshot | undefined, "git-commit", GitCommitData> = {
152
280
  collector: gitCommitCollector,
153
281
  parser: gitCommitParser,
154
282
  };
155
-
156
- // ---------------------------------------------------------------------------
157
- // Commit-data collection
158
- // ---------------------------------------------------------------------------
159
-
160
- /**
161
- * Build `GitCommitData` given pre/post SHAs already gathered by the
162
- * collector. Returns `null` if any follow-up git call throws — caller
163
- * substitutes a baseline-aware no-op payload so the workflow keeps
164
- * moving.
165
- */
166
- async function collectCommitData(cwd: string, baselineSha: string, headSha: string): Promise<GitCommitData | null> {
167
- try {
168
- if (!headSha || headSha === baselineSha) return noOpData(baselineSha, headSha);
169
- const [subject, filesChanged] = await Promise.all([
170
- git(cwd, "log", "-1", "--format=%s", headSha),
171
- countFilesChanged(cwd, baselineSha, headSha),
172
- ]);
173
- return { sha: headSha, prevSha: baselineSha, subject, filesChanged };
174
- } catch {
175
- return null;
176
- }
177
- }
178
-
179
- /** Parse `git diff --shortstat` output for the "N files changed" count. */
180
- async function countFilesChanged(cwd: string, baselineSha: string, headSha: string): Promise<number> {
181
- const diffStat = await git(cwd, "diff", "--shortstat", baselineSha, headSha);
182
- const match = diffStat.match(/^(\d+) files? changed/);
183
- return match ? parseInt(match[1]!, 10) : 0;
184
- }
185
-
186
- const noOpData = (prevSha: string, sha = ""): GitCommitData => ({
187
- sha,
188
- prevSha,
189
- subject: "",
190
- filesChanged: 0,
191
- noOp: true,
192
- });
package/outcomes/index.ts CHANGED
@@ -12,6 +12,7 @@
12
12
  export * from "./collectors/index.js";
13
13
  export {
14
14
  type GitCommitData,
15
+ type GitCommitOutput,
15
16
  type GitHeadSnapshot,
16
17
  gitCommitCollector,
17
18
  gitCommitOutcome,
@@ -20,6 +20,7 @@
20
20
 
21
21
  import { existsSync, readFileSync } from "node:fs";
22
22
  import { isAbsolute, join } from "node:path";
23
+ import { formatError } from "../../internal-utils.js";
23
24
  import type { ArtifactParser } from "../../output-spec.js";
24
25
  import { defineParser } from "../../output-spec.js";
25
26
 
@@ -40,10 +41,9 @@ export const jsonBodyParser: ArtifactParser<unknown, "json", unknown> = definePa
40
41
  const data = JSON.parse(readFileSync(abs, "utf-8"));
41
42
  return { kind: "ok", payload: { kind: "json", data } };
42
43
  } catch (e) {
43
- const reason = e instanceof Error ? e.message : String(e);
44
44
  return {
45
45
  kind: "fatal",
46
- message: `${ctx.skill}: failed to parse JSON from ${primary.handle.path} — ${reason}`,
46
+ message: `${ctx.skill}: failed to parse JSON from ${primary.handle.path} — ${formatError(e)}`,
47
47
  };
48
48
  }
49
49
  },
@@ -3,7 +3,7 @@
3
3
  * "no artifacts produced" primitive.
4
4
  *
5
5
  * Collector always returns `{ kind: "ok", artifacts: [] }`. The chain
6
- * semantics (see `runner/stage-lifecycle.ts:inputForStage`) then
6
+ * semantics (see `runner/run-stage.ts:inputForStage`) then
7
7
  * inherit the upstream artifact list forward — an action skill
8
8
  * between two produces skills doesn't need its own collector.
9
9
  *
@@ -14,13 +14,13 @@
14
14
  * No snapshot — side-effect stages have no pre-stage state to capture.
15
15
  */
16
16
 
17
- import type { ArtifactCollector, OutputSpec } from "../output-spec.js";
17
+ import type { ArtifactCollector, Outcome } from "../output-spec.js";
18
18
 
19
19
  /** Collector primitive: always returns zero artifacts, never fatal. */
20
20
  export const noopCollector: ArtifactCollector = {
21
21
  collect: () => ({ kind: "ok", artifacts: [] }),
22
22
  };
23
23
 
24
- export const sideEffectOutcome: OutputSpec = {
24
+ export const sideEffectOutcome: Outcome = {
25
25
  collector: noopCollector,
26
26
  };