@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
package/built-ins.ts CHANGED
@@ -12,46 +12,36 @@
12
12
  * `registerBuiltIns(...)` from their extension entry point with workflows
13
13
  * that name their own bundled skills.
14
14
  *
15
- * The registry array is anchored on a `Symbol.for` slot on `globalThis`.
16
- * Pi may load this module more than once — once for the rpiv-workflow
17
- * extension itself, and once via the rpiv-pi `import { registerBuiltIns }
18
- * from "@juicesharp/rpiv-workflow"` cross-package resolution — and
19
- * module-local state would be siloed between those copies.
20
- * `globalThis[KEY]` is process-wide and survives the dup load.
15
+ * The registry array is anchored on a `Symbol.for` slot on `globalThis`
16
+ * (via `globalSlot`). Pi may load this module more than once — once for the
17
+ * rpiv-workflow extension itself, and once via the rpiv-pi
18
+ * `import { registerBuiltIns } from "@juicesharp/rpiv-workflow"`
19
+ * cross-package resolution — and module-local state would be siloed between
20
+ * those copies. `globalThis[KEY]` is process-wide and survives the dup load.
21
21
  */
22
22
 
23
23
  import type { Workflow } from "./api.js";
24
+ import { globalSlot, lazyProviderRegistry } from "./internal-utils.js";
24
25
 
25
26
  const REGISTRY_KEY = Symbol.for("@juicesharp/rpiv-workflow:built-ins");
26
- const PROVIDERS_KEY = Symbol.for("@juicesharp/rpiv-workflow:built-in-providers");
27
- const FLUSH_KEY = Symbol.for("@juicesharp/rpiv-workflow:built-in-flush");
27
+ const FAILURES_KEY = Symbol.for("@juicesharp/rpiv-workflow:built-in-provider-failures");
28
28
 
29
- /** A lazy contributor of built-in workflows — run once by `flushBuiltInProviders`. */
30
- type BuiltInsProvider = () => void | Promise<void>;
31
-
32
- type Global = Record<symbol, unknown>;
33
-
34
- function getRegistry(): Workflow[] {
35
- const g = globalThis as unknown as Global;
36
- let registry = g[REGISTRY_KEY] as Workflow[] | undefined;
37
- if (!registry) {
38
- registry = [];
39
- g[REGISTRY_KEY] = registry;
40
- }
41
- return registry;
42
- }
43
-
44
- // Provider list + flush latch use the same `Symbol.for` global-slot strategy as
45
- // the registry, so a duplicate module load shares one process-wide state.
46
- function getProviders(): BuiltInsProvider[] {
47
- const g = globalThis as unknown as Global;
48
- let providers = g[PROVIDERS_KEY] as BuiltInsProvider[] | undefined;
49
- if (!providers) {
50
- providers = [];
51
- g[PROVIDERS_KEY] = providers;
52
- }
53
- return providers;
54
- }
29
+ const getRegistry = globalSlot(REGISTRY_KEY, () => [] as Workflow[]);
30
+ const getFailures = globalSlot(FAILURES_KEY, () => [] as unknown[]);
31
+ // Provider lifecycle via the shared `lazyProviderRegistry` — same global-slot
32
+ // strategy as the registry, so a duplicate module load shares one
33
+ // process-wide state. Safe to re-flush: `registerBuiltIns` replaces by name.
34
+ // `onError` RECORDS each provider throw (drained by `drainBuiltInProviderErrors`)
35
+ // instead of propagating, so `loadWorkflows` honors its never-throws contract: a
36
+ // throwing provider degrades to a partial/empty registry instead of crashing
37
+ // `/wf`, but the error is NOT swallowed silently — `loadWorkflows` surfaces it as
38
+ // a LoadIssue so a buggy provider is debuggable. Same posture as the
39
+ // skill-contracts registry.
40
+ const providers = lazyProviderRegistry("@juicesharp/rpiv-workflow:built-in-providers", {
41
+ onError: (err) => {
42
+ getFailures().push(err);
43
+ },
44
+ });
55
45
 
56
46
  /**
57
47
  * Register one or more workflows into the `built-in` layer. Idempotent on
@@ -74,8 +64,8 @@ export function registerBuiltIns(workflows: readonly Workflow[]): void {
74
64
  * defer constructing its workflow definitions off startup and onto first `/wf`.
75
65
  * Register before the first read — `/wf` is the earliest reader.
76
66
  */
77
- export function registerBuiltInsProvider(provider: BuiltInsProvider): void {
78
- getProviders().push(provider);
67
+ export function registerBuiltInsProvider(provider: () => void | Promise<void>): void {
68
+ providers.register(provider);
79
69
  }
80
70
 
81
71
  /**
@@ -84,13 +74,18 @@ export function registerBuiltInsProvider(provider: BuiltInsProvider): void {
84
74
  * first flush won't run — acceptable, all register at extension load.
85
75
  */
86
76
  export function flushBuiltInProviders(): Promise<void> {
87
- const g = globalThis as unknown as Global;
88
- const existing = g[FLUSH_KEY] as Promise<void> | undefined;
89
- if (existing) return existing;
90
- const pending = getProviders().splice(0);
91
- const flush = Promise.all(pending.map((p) => p())).then(() => undefined);
92
- g[FLUSH_KEY] = flush;
93
- return flush;
77
+ return providers.flush();
78
+ }
79
+
80
+ /**
81
+ * Drain (return + clear) the errors recorded by failed built-in providers since
82
+ * the last drain. `loadWorkflows` calls this right after the flush and maps each
83
+ * into a `LoadIssue`, so a provider bug surfaces in `loaded.issues` instead of
84
+ * vanishing. Internal — not on the public barrel (mirrors
85
+ * `drainSkillContractProviderErrors`).
86
+ */
87
+ export function drainBuiltInProviderErrors(): unknown[] {
88
+ return getFailures().splice(0);
94
89
  }
95
90
 
96
91
  /** Read-only view of the registry — consumed by `load.ts`. */
@@ -104,6 +99,6 @@ export function getBuiltIns(): readonly Workflow[] {
104
99
  */
105
100
  export function __resetBuiltIns(): void {
106
101
  getRegistry().length = 0;
107
- getProviders().length = 0;
108
- (globalThis as unknown as Global)[FLUSH_KEY] = undefined;
102
+ providers.reset();
103
+ getFailures().length = 0;
109
104
  }
package/chain-state.ts ADDED
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Chain-state authorities — the ONLY exported way to read or advance the
3
+ * rolling artifact/output slots a run carries from stage to stage, plus the
4
+ * shared stage-identity derivations the runtime and the load-time validators
5
+ * must agree on.
6
+ *
7
+ * Every helper here is consumed by BOTH the live chain and the resume fold
8
+ * (or by both the runtime and load-time validation), so each is a
9
+ * single-construction-site guard: live and resume can't drift, runtime and
10
+ * load can't disagree. Generic, domain-free utilities live in
11
+ * `internal-utils.ts`; anything in this file is workflow-chain domain logic.
12
+ */
13
+
14
+ import type { PromptFn, StageDef } from "./api.js";
15
+ import { type Artifact, handleToString } from "./handle.js";
16
+ import { isFailedOutput, type Output } from "./output.js";
17
+ import { readName, readsAll } from "./stage-def.js";
18
+ import { resolvePublishName } from "./stage-identity.js";
19
+ import type { RunState } from "./types.js";
20
+
21
+ // Stage-identity projections live in the dependency-free `stage-identity.ts`
22
+ // leaf so the load-time validators can consume them without importing this
23
+ // runtime-state module. Re-exported here so this module's own runtime callers
24
+ // (runner/*, registration) keep a single chain-state import.
25
+ export { isDispatchingStage, resolvePublishName, resolveSkill } from "./stage-identity.js";
26
+
27
+ /**
28
+ * Canonical accessor for "the primary artifact the chain is currently
29
+ * carrying." Reads the rolling slot maintained by the runner —
30
+ * produces stages update it on success; side-effect stages leave it
31
+ * alone. Replaces the load-bearing single-string artifact_path mirror
32
+ * from the pre-collector shape.
33
+ */
34
+ export function currentPrimaryArtifact(state: RunState): Artifact | undefined {
35
+ return state.primaryArtifact;
36
+ }
37
+
38
+ /**
39
+ * Resolve a stage's `prompt` dispatch text — the COMPLETE user message a
40
+ * prompt stage sends (no `/skill:` prefix, no implicit arg). The dynamic form
41
+ * receives the same `ScriptContext` script stages get. The ONE resolver for
42
+ * every prompt-dispatch site: the single-shot path (run-stage) and the
43
+ * loop driver's round-0 producer (loop.ts) — resolved at dispatch time, never
44
+ * persisted, so a `PromptFn` on a loop stage joins the loop determinism
45
+ * contract (deterministic w.r.t. the fold-replayed state). Lives here (not
46
+ * runner/) so loop.ts consumes it cycle-free — same posture as
47
+ * `stageEntryArgs` below.
48
+ */
49
+ export async function resolveStagePrompt(prompt: string | PromptFn, cwd: string, state: RunState): Promise<string> {
50
+ if (typeof prompt === "string") return prompt;
51
+ return prompt({ cwd, input: state.output, state });
52
+ }
53
+
54
+ const isPromptStage = (def: StageDef): boolean => def.prompt !== undefined;
55
+
56
+ const usesOriginalInput = (def: StageDef, stageName: string, startStage: string): boolean =>
57
+ stageName === startStage || def.inheritsArtifacts === false;
58
+
59
+ const hasReads = (def: StageDef): def is StageDef & { reads: NonNullable<StageDef["reads"]> } =>
60
+ def.reads !== undefined && def.reads.length > 0;
61
+
62
+ /**
63
+ * The single arg-projection authority: the string a stage's
64
+ * `/skill:<name> <args>` prompt carries, derived purely from
65
+ * (def, stageName, startStage, state).
66
+ *
67
+ * Returns `undefined` (instead of non-null-asserting) when a required
68
+ * projection input is missing — the rolling primary is unset, or a `reads`
69
+ * name has no published entry. The LIVE path never sees `undefined`: the
70
+ * preflights (`ensureUpstreamArtifact` / `ensureNamedReads`) guarantee the
71
+ * inputs before `inputForStage` delegates here. The RESUME fold freezes this
72
+ * value at loop-generation open, where replayed state is byte-identical to
73
+ * live loop entry (THE REPLAY CONTRACT); `undefined` there means a
74
+ * truncated/corrupted trail and becomes a recorded refusal.
75
+ */
76
+ export function stageEntryArgs(
77
+ def: StageDef,
78
+ stageName: string,
79
+ startStage: string,
80
+ state: RunState,
81
+ ): string | undefined {
82
+ if (isPromptStage(def)) return "";
83
+ if (usesOriginalInput(def, stageName, startStage)) return state.originalInput;
84
+ if (hasReads(def)) {
85
+ const parts: string[] = [];
86
+ for (const read of def.reads) {
87
+ const name = readName(read);
88
+ const slot = state.named[name];
89
+ if (!slot?.length) return undefined;
90
+ // `all` → every accumulated entry (fan-in); bare string → latest-wins.
91
+ // A produces-fanout channel is PRE-SIZED (length === total) and
92
+ // positionally filled, so a slot can carry `undefined` (pending) or a
93
+ // failed sentinel. The latest-wins branch must NOT `slot[length-1]!`
94
+ // blindly: scan backward for the last REAL entry, and the per-entry loop
95
+ // skips unfilled/failed slots so a `fanin(...)` read contributes no args
96
+ // for them (the `.filter(Boolean)` convention needs no widening).
97
+ //
98
+ // ALL-FAILED FANIN CONTRACT: pre-sizing means the channel is
99
+ // always present once the fold ran, so the `!slot?.length` bail no longer
100
+ // fires for a fanout channel; when EVERY unit failed/unfilled this read
101
+ // contributes ZERO `--name` args and `stageEntryArgs` returns the
102
+ // assembled (possibly empty) string — NEVER `undefined`. Collect-all
103
+ // fanout runs synthesis even when all units failed.
104
+ const entries = readsAll(read) ? slot : [lastReal(slot)];
105
+ for (const entry of entries) {
106
+ if (!entry || isFailedOutput(entry)) continue; // unfilled (pending) or failed → no args
107
+ for (const artifact of entry.artifacts) {
108
+ parts.push(`--${name}`, handleToString(artifact.handle));
109
+ }
110
+ }
111
+ }
112
+ return parts.join(" ");
113
+ }
114
+ const primary = currentPrimaryArtifact(state);
115
+ return primary === undefined ? undefined : handleToString(primary.handle);
116
+ }
117
+
118
+ /** The last REAL (filled, non-failed) entry of a channel slot — the latest-wins
119
+ * source. A produces-fanout channel is pre-sized + positionally filled, so its
120
+ * tail can be `undefined` (pending) or a failed sentinel; scan backward instead
121
+ * of asserting `slot[length-1]`. Returns `undefined` for an all-failed/empty slot. */
122
+ function lastReal(slot: readonly (Output | undefined)[]): Output | undefined {
123
+ for (let i = slot.length - 1; i >= 0; i--) {
124
+ const o = slot[i];
125
+ if (o && !isFailedOutput(o)) return o;
126
+ }
127
+ return undefined;
128
+ }
129
+
130
+ /**
131
+ * The single authority for "a completed produces stage mutates the rolling
132
+ * artifact state." Called by the live skill path (sessions/sessions.ts), the
133
+ * live script path (runner/script-stage.ts), and state reconstruction
134
+ * (runner/resume.ts) — keeping all three in lockstep (parity-tested).
135
+ *
136
+ * Scope: primary slot + named-publish registry ONLY. `state.output` and
137
+ * `state.stagesCompleted` advance through `applyStageSuccess`
138
+ * (audit-rows.ts), which delegates here for the artifact slots.
139
+ *
140
+ * - kind "produces" → first artifact wins the rolling slot; the
141
+ * full Output appends onto state.named[key].
142
+ * - inheritsArtifacts === false → clear the slot (terminal()).
143
+ * - other side-effect → leave the slot untouched.
144
+ */
145
+ export function applyCompletedStage(state: RunState, def: StageDef, stageName: string, output: Output): void {
146
+ // Fanout owns its channel through the index-addressed `placeFanoutOutput`
147
+ // fold (foldFanoutCompletion), so the produces-channel push here would
148
+ // double-write. Early-return for fanout. But the acts/side-effect
149
+ // PRIMARY-CLEAR (`inheritsArtifacts === false`) is IDEMPOTENT (it only sets
150
+ // primary = undefined), so run it here for fanout TOO: the SEQUENTIAL path (a
151
+ // resumed/non-pristine acts-fanout that routes through `step` → `dispatchUnit`
152
+ // → `recordStageSuccess` → here, not through foldFanoutCompletion until parallel
153
+ // resume is wired) would otherwise lose the primary-clear the only
154
+ // shipped fanout kind (acts) relies on. Live acts-fanout calls BOTH this and
155
+ // placeFanoutOutput — both set primary = undefined, harmless. Produces-fanout's
156
+ // channel push stays fold-only (non-idempotent → must not double-write).
157
+ if (def.loop?.kind === "fanout") {
158
+ clearPrimaryForActs(state, def);
159
+ return;
160
+ }
161
+ if (def.kind === "produces") {
162
+ const next = output.artifacts[0];
163
+ if (next) state.primaryArtifact = next;
164
+ const key = resolvePublishName(def, stageName);
165
+ let slot = state.named[key];
166
+ if (!slot) {
167
+ slot = [];
168
+ state.named[key] = slot;
169
+ }
170
+ slot.push(output);
171
+ return;
172
+ }
173
+ clearPrimaryForActs(state, def);
174
+ }
175
+
176
+ /**
177
+ * The acts/side-effect primary-clear rule, in ONE place: a `terminal()` stage
178
+ * (`inheritsArtifacts === false`) drops the rolling primary; every other
179
+ * side-effect leaves it. Idempotent and produces-safe (the `kind` guard makes it
180
+ * a no-op for produces stages, whose channel arm owns the primary). Shared by
181
+ * `applyCompletedStage` (the fanout early-return AND the sequential acts arm) and
182
+ * `placeFanoutOutput`, so the rule can't drift across the three sites.
183
+ */
184
+ function clearPrimaryForActs(state: RunState, def: StageDef): void {
185
+ if (def.kind !== "produces" && def.inheritsArtifacts === false) state.primaryArtifact = undefined;
186
+ }
187
+
188
+ // The fanout fold's SINGLE state-effect site. It subsumes BOTH
189
+ // arms of applyCompletedStage (which early-returns for fanout),
190
+ // index-addressed:
191
+ // • produces-fanout (collecting): pre-size the channel slot to `total`, assign
192
+ // the unit's output at its declared `index`; set primaryArtifact from
193
+ // artifacts[0] unless this is a failed sentinel (no artifacts).
194
+ // • acts-fanout (side-effect, def.kind !== "produces"): no channel; mirror the
195
+ // applyCompletedStage `inheritsArtifacts === false ⇒ clear primary` rule so
196
+ // today's acts-fanout semantics are preserved.
197
+ // Called ONLY by foldFanoutCompletion (live + resume).
198
+ export function placeFanoutOutput(
199
+ state: RunState,
200
+ def: StageDef,
201
+ stageName: string,
202
+ index: number,
203
+ total: number,
204
+ output: Output,
205
+ ): void {
206
+ if (def.kind === "produces") {
207
+ const key = resolvePublishName(def, stageName);
208
+ let slot = state.named[key];
209
+ if (!slot || slot.length !== total) {
210
+ slot = new Array<Output | undefined>(total) as Output[];
211
+ state.named[key] = slot;
212
+ }
213
+ slot[index] = output;
214
+ const next = output.artifacts[0];
215
+ if (next && !isFailedOutput(output)) state.primaryArtifact = next;
216
+ return;
217
+ }
218
+ // acts/side-effect fanout — same primary-clear rule as the sequential path.
219
+ clearPrimaryForActs(state, def);
220
+ }
package/command-run.ts CHANGED
@@ -4,13 +4,16 @@
4
4
  * `./command.ts`, so it evaluates lazily on first `/wf`, not at startup.
5
5
  */
6
6
 
7
+ import { flushBuiltInProviders } from "./built-ins.js";
7
8
  import { parseArgs } from "./command.js";
8
9
  import type { WorkflowHost, WorkflowHostContext } from "./host.js";
10
+ import { formatError } from "./internal-utils.js";
9
11
  import { renderConfigLayer } from "./layers.js";
10
12
  import { findWorkflow, type Issue, loadWorkflows } from "./load/index.js";
11
13
  import {
12
14
  MSG_INTERACTIVE_ONLY,
13
15
  MSG_LOAD_ABORTED,
16
+ MSG_NAME_FLAG_MID_INPUT,
14
17
  MSG_NAME_IGNORED_ON_RESUME,
15
18
  MSG_NAME_INVALID,
16
19
  MSG_NO_WORKFLOWS_REGISTERED,
@@ -20,8 +23,27 @@ import {
20
23
  } from "./messages.js";
21
24
  import { formatWorkflowDetails, formatWorkflowList } from "./preview.js";
22
25
  import { resumeWorkflowByRunId, runWorkflow } from "./runner/index.js";
26
+ import { flushSkillContractProviders } from "./skill-contracts/index.js";
23
27
  import { isValidName } from "./state/index.js";
24
28
 
29
+ // ---------------------------------------------------------------------------
30
+ // Pre-warm
31
+ // ---------------------------------------------------------------------------
32
+
33
+ /**
34
+ * Flush the lazy provider registries ahead of the first `/wf` — both are
35
+ * memoized one-shot latches, so `loadWorkflows` later awaits the same
36
+ * settled promises. Built-in providers carry the heaviest first-call work
37
+ * (the sibling's authoring-DSL graph builds here); measured ~550ms of the
38
+ * first `/wf`'s `loadWorkflows` is dominated by these flushes. Called by
39
+ * the post-registration pre-warm in `command.ts` right after the module
40
+ * graph import; never from the run path (loadWorkflows flushes on its own).
41
+ */
42
+ export async function prewarmWorkflowRuntime(): Promise<void> {
43
+ await flushBuiltInProviders();
44
+ await flushSkillContractProviders();
45
+ }
46
+
25
47
  // ---------------------------------------------------------------------------
26
48
  // Orchestrator
27
49
  // ---------------------------------------------------------------------------
@@ -38,6 +60,10 @@ export async function handleWorkflowCommand(host: WorkflowHost, args: string, ct
38
60
  const workflowNames = new Set(loaded.workflows.map((w) => w.name));
39
61
  const parsed = parseArgs(args, { workflowNames, default: loaded.default });
40
62
 
63
+ if (parsed.nameFlagIgnored) {
64
+ ctx.ui.notify(MSG_NAME_FLAG_MID_INPUT, "warning");
65
+ }
66
+
41
67
  if (parsed.kind === "resume") {
42
68
  if (parsed.droppedName !== undefined) {
43
69
  ctx.ui.notify(MSG_NAME_IGNORED_ON_RESUME, "warning");
@@ -85,25 +111,27 @@ export async function handleWorkflowCommand(host: WorkflowHost, args: string, ct
85
111
  return;
86
112
  }
87
113
 
88
- // runWorkflow returns a result envelope rather than throwing — but a
89
- // thrown predicate or invariant could still bubble. Catch so Pi's
90
- // dispatcher doesn't print a raw stack.
91
- try {
92
- const result = await runWorkflow(ctx, {
93
- workflow,
94
- input,
95
- host,
96
- trigger: { kind: "command", name: "wf" },
97
- name,
114
+ // Float the run off the prompt: /wf returns immediately; the run executes
115
+ // detached and appears as a lane. runWorkflow returns an envelope (never throws on
116
+ // run failure), but a thrown predicate/invariant could still bubble — .catch keeps
117
+ // Pi's dispatcher from printing a raw stack AND a floated promise from going
118
+ // unhandled (NFR).
119
+ void runWorkflow(ctx, {
120
+ workflow,
121
+ input,
122
+ host,
123
+ trigger: { kind: "command", name: "wf" },
124
+ name,
125
+ })
126
+ .then((result) => {
127
+ // Surface pre-flight rejections (collision, etc.) — no runId means no JSONL on disk.
128
+ if (!result.success && result.runId === undefined && result.error) {
129
+ ctx.ui.notify(result.error, "error");
130
+ }
131
+ })
132
+ .catch((e) => {
133
+ ctx.ui.notify(MSG_WORKFLOW_THREW(formatError(e)), "error");
98
134
  });
99
- // Surface pre-flight rejections (collision, etc.) — no runId means no JSONL on disk.
100
- if (!result.success && result.runId === undefined && result.error) {
101
- ctx.ui.notify(result.error, "error");
102
- }
103
- } catch (e) {
104
- const reason = e instanceof Error ? e.message : String(e);
105
- ctx.ui.notify(MSG_WORKFLOW_THREW(reason), "error");
106
- }
107
135
  }
108
136
 
109
137
  // ---------------------------------------------------------------------------
@@ -115,19 +143,21 @@ async function handleResume(host: WorkflowHost, ctx: WorkflowHostContext, ref: s
115
143
  ctx.ui.notify(MSG_RESUME_USAGE, "error");
116
144
  return;
117
145
  }
118
- try {
119
- const result = await resumeWorkflowByRunId(ctx, ref, { host });
120
- // A failure with no runId is a no-JSONL refusal (run-id didn't resolve,
121
- // load error, workflow gone, or an unreconstructable trail) — nothing else
122
- // surfaces it, so notify here. An in-run failure carries a runId and was
123
- // already notified by the stage machinery via its JSONL failure row;
124
- // re-notifying would double up.
125
- if (!result.success && result.runId === undefined && result.error) {
126
- ctx.ui.notify(result.error, "error");
127
- }
128
- } catch (e) {
129
- ctx.ui.notify(MSG_WORKFLOW_THREW(e instanceof Error ? e.message : String(e)), "error");
130
- }
146
+ // Float the resume off the prompt — identical shape to the run path.
147
+ void resumeWorkflowByRunId(ctx, ref, { host })
148
+ .then((result) => {
149
+ // A failure with no runId is a no-JSONL refusal (run-id didn't resolve,
150
+ // load error, workflow gone, or an unreconstructable trail) — nothing else
151
+ // surfaces it, so notify here. An in-run failure carries a runId and was
152
+ // already notified by the stage machinery via its JSONL failure row;
153
+ // re-notifying would double up.
154
+ if (!result.success && result.runId === undefined && result.error) {
155
+ ctx.ui.notify(result.error, "error");
156
+ }
157
+ })
158
+ .catch((e) => {
159
+ ctx.ui.notify(MSG_WORKFLOW_THREW(formatError(e)), "error");
160
+ });
131
161
  }
132
162
 
133
163
  // ---------------------------------------------------------------------------
@@ -144,6 +174,9 @@ function surfaceIssues(ctx: WorkflowHostContext, issues: readonly Issue[]): void
144
174
 
145
175
  function formatIssue(issue: Issue): string {
146
176
  if (issue.kind === "load") {
177
+ // "framework" = the loader's own machinery (providers, derivers) — no
178
+ // config file caused it, so no "config" suffix.
179
+ if (issue.layer === "framework") return `[framework] ${issue.message}`;
147
180
  const where = issue.path ? ` (${issue.path})` : "";
148
181
  return `[${renderConfigLayer(issue.layer)} config${where}] ${issue.message}`;
149
182
  }