@juicesharp/rpiv-workflow 1.19.0 → 1.20.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 (114) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-rows.ts +136 -0
  4. package/audit.ts +139 -126
  5. package/built-ins.ts +20 -45
  6. package/chain-state.ts +169 -0
  7. package/command-run.ts +31 -3
  8. package/command.ts +116 -20
  9. package/docs/workflow-authoring.md +322 -61
  10. package/{lifecycle.ts → events.ts} +119 -35
  11. package/host.ts +30 -0
  12. package/index.ts +25 -81
  13. package/internal-utils.ts +92 -78
  14. package/internal.ts +21 -1
  15. package/judge.ts +229 -0
  16. package/layers.ts +10 -15
  17. package/load/alias.ts +6 -12
  18. package/load/cache.ts +9 -6
  19. package/load/index.ts +16 -109
  20. package/load/issues.ts +31 -0
  21. package/load/legacy.ts +102 -0
  22. package/load/merge.ts +2 -2
  23. package/load/shape-guards.test.ts +4 -1
  24. package/load/shape-guards.ts +3 -6
  25. package/load/skill-contract-phase.ts +94 -0
  26. package/loop-constructors.ts +623 -0
  27. package/loop-def.ts +240 -0
  28. package/loop-kinds.ts +493 -0
  29. package/loop.ts +304 -0
  30. package/messages.ts +225 -157
  31. package/outcomes/collectors/directory-path.ts +7 -3
  32. package/outcomes/collectors/require-opt.ts +11 -0
  33. package/outcomes/collectors/tool-call.test.ts +3 -1
  34. package/outcomes/collectors/tool-call.ts +8 -3
  35. package/outcomes/collectors/transcript-path.ts +2 -3
  36. package/outcomes/collectors/union.test.ts +54 -0
  37. package/outcomes/collectors/union.ts +28 -9
  38. package/outcomes/collectors/url.ts +7 -0
  39. package/outcomes/collectors/workspace-diff.test.ts +13 -0
  40. package/outcomes/collectors/workspace-diff.ts +21 -14
  41. package/outcomes/exec.ts +17 -0
  42. package/outcomes/git-commit.test.ts +76 -30
  43. package/outcomes/git-commit.ts +139 -100
  44. package/outcomes/index.ts +1 -0
  45. package/outcomes/parsers/json-body.ts +2 -2
  46. package/outcomes/side-effect.ts +3 -3
  47. package/output-spec.ts +36 -10
  48. package/output.ts +40 -20
  49. package/package.json +13 -7
  50. package/predicates.ts +11 -8
  51. package/preview.ts +77 -17
  52. package/registration.ts +109 -35
  53. package/routing-dsl.ts +310 -0
  54. package/routing.ts +2 -2
  55. package/runner/by-name.ts +2 -1
  56. package/runner/by-run-id.ts +2 -1
  57. package/runner/chain-advance.ts +59 -44
  58. package/runner/errors.ts +33 -0
  59. package/runner/failure.ts +109 -0
  60. package/runner/header-write-failure.test.ts +64 -0
  61. package/runner/index.ts +7 -13
  62. package/runner/input-validation.ts +11 -21
  63. package/runner/preflight.ts +173 -0
  64. package/runner/resolve-stage.ts +68 -0
  65. package/runner/resume-entry.ts +101 -0
  66. package/runner/resume-loop.test.ts +1410 -0
  67. package/runner/resume-loop.ts +110 -0
  68. package/runner/resume-session.test.ts +400 -0
  69. package/runner/resume.test.ts +881 -206
  70. package/runner/resume.ts +281 -261
  71. package/runner/run-context.ts +161 -0
  72. package/runner/run-stage.ts +456 -0
  73. package/runner/runner.ts +59 -400
  74. package/runner/script-stage.ts +103 -105
  75. package/schema-compat.ts +13 -1
  76. package/sessions/extraction.ts +53 -31
  77. package/sessions/index.ts +3 -1
  78. package/sessions/locate.test.ts +77 -0
  79. package/sessions/locate.ts +90 -0
  80. package/sessions/reattach.ts +63 -0
  81. package/sessions/sessions.ts +130 -127
  82. package/skill-contract.ts +22 -25
  83. package/skill-contracts/composition.ts +88 -37
  84. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  85. package/skill-contracts/harvest.ts +2 -3
  86. package/skill-contracts/index.ts +15 -8
  87. package/skill-contracts/registry.ts +33 -50
  88. package/stage-def.ts +527 -0
  89. package/startup.ts +3 -1
  90. package/state/index.ts +8 -1
  91. package/state/names.ts +91 -65
  92. package/state/paths.ts +12 -0
  93. package/state/raw.ts +78 -0
  94. package/state/reads.ts +103 -85
  95. package/state/resolve.ts +73 -0
  96. package/state/state.ts +112 -15
  97. package/state/writes.ts +29 -12
  98. package/transcript.ts +24 -0
  99. package/triggers.ts +11 -3
  100. package/types.ts +202 -44
  101. package/validate/contract-compat.ts +193 -0
  102. package/validate/graph.ts +125 -0
  103. package/validate/issue.ts +314 -0
  104. package/validate/stage-rules.ts +420 -0
  105. package/validate-output.ts +69 -1
  106. package/validate-workflow.ts +55 -759
  107. package/control-flow.ts +0 -135
  108. package/fanout.ts +0 -102
  109. package/iterate.ts +0 -155
  110. package/runner/resume-fanout.test.ts +0 -331
  111. package/runner/resume-fanout.ts +0 -136
  112. package/runner/resume-iterate.test.ts +0 -444
  113. package/runner/resume-iterate.ts +0 -111
  114. package/runner/stage-lifecycle.ts +0 -500
package/chain-state.ts ADDED
@@ -0,0 +1,169 @@
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, SkillStage, StageDef } from "./api.js";
15
+ import { type Artifact, handleToString } from "./handle.js";
16
+ import type { Output } from "./output.js";
17
+ import type { RunState } from "./types.js";
18
+
19
+ /**
20
+ * Canonical accessor for "the primary artifact the chain is currently
21
+ * carrying." Reads the rolling slot maintained by the runner —
22
+ * produces stages update it on success; side-effect stages leave it
23
+ * alone. Replaces the load-bearing single-string artifact_path mirror
24
+ * from the pre-collector shape.
25
+ */
26
+ export function currentPrimaryArtifact(state: RunState): Artifact | undefined {
27
+ return state.primaryArtifact;
28
+ }
29
+
30
+ /**
31
+ * Resolve the `state.named` key a produces stage appends its `Output`
32
+ * envelope onto. Two layers of fallback, in priority order:
33
+ * 1. `stage.outcome?.name` — categorical name carried by the outcome.
34
+ * 2. The stage's record key — always defined.
35
+ *
36
+ * Single source of truth for the key derivation so the skill-stage path
37
+ * and the script-stage path stay in lockstep, and so `validateWorkflow`
38
+ * can compute the same key set at load time.
39
+ */
40
+ export function resolvePublishName(def: StageDef, stageName: string): string {
41
+ return def.outcome?.name ?? stageName;
42
+ }
43
+
44
+ /**
45
+ * Resolve a stage's effective skill — the contract-registry key. Twin of
46
+ * `resolvePublishName`. Single source of truth so the runtime resolution
47
+ * (`resolveStage`) and the load-time lookups (`validate-workflow.ts`) key the
48
+ * registry identically and can't drift.
49
+ */
50
+ export function resolveSkill(def: StageDef, stageName: string): string {
51
+ return def.skill ?? stageName;
52
+ }
53
+
54
+ /**
55
+ * A stage dispatches a `/skill:<name>` exactly when it carries neither a `run`
56
+ * (script body) nor a `prompt` (raw-text body). `fanout`/`iterate` stages carry
57
+ * neither, so they ARE dispatching stages. The shared predicate for every site
58
+ * that treats `resolveSkill`'s result as a REAL skill identity — the alias
59
+ * remap + its no-op warning, contract harvest, and the validator's contract
60
+ * lookups must all agree, or a script/prompt stage whose record key matches a
61
+ * registered skill inherits that skill's contract by accident.
62
+ *
63
+ * A TYPE GUARD since the StageDef union (T1): a positive narrows to
64
+ * `SkillStage`, so callers that wire skill-derived data onto the stage
65
+ * (the alias remap, outcome derivers) get the writable arm.
66
+ */
67
+ export function isDispatchingStage(stage: StageDef): stage is SkillStage {
68
+ return stage.run == null && stage.prompt == null;
69
+ }
70
+
71
+ /**
72
+ * Resolve a stage's `prompt` dispatch text — the COMPLETE user message a
73
+ * prompt stage sends (no `/skill:` prefix, no implicit arg). The dynamic form
74
+ * receives the same `ScriptContext` script stages get. The ONE resolver for
75
+ * every prompt-dispatch site: the single-shot path (run-stage) and the
76
+ * loop driver's round-0 producer (loop.ts) — resolved at dispatch time, never
77
+ * persisted, so a `PromptFn` on a loop stage joins the loop determinism
78
+ * contract (deterministic w.r.t. the fold-replayed state). Lives here (not
79
+ * runner/) so loop.ts consumes it cycle-free — same posture as
80
+ * `stageEntryArgs` below.
81
+ */
82
+ export async function resolveStagePrompt(prompt: string | PromptFn, cwd: string, state: RunState): Promise<string> {
83
+ if (typeof prompt === "string") return prompt;
84
+ return prompt({ cwd, input: state.output, state });
85
+ }
86
+
87
+ /**
88
+ * The single arg-projection authority: the string a stage's
89
+ * `/skill:<name> <args>` prompt carries, derived purely from
90
+ * (def, stageName, startStage, state). Five cases in priority order:
91
+ * 0. A prompt-dispatch stage (`def.prompt` set) owns its WHOLE message —
92
+ * no skill args exist; returns `""` (never `undefined`: the missing-input
93
+ * refusal arms below must not fire for a stage that doesn't consume the
94
+ * rolling primary or named reads). The round-0 producer message of a
95
+ * prompt-dispatch loop is `resolveStagePrompt`, not this projection.
96
+ * 1. The start stage receives `originalInput` (the user's brief).
97
+ * 2. A stage opting out of inheritance (`inheritsArtifacts: false`,
98
+ * i.e. authored via `terminal()`) also receives `originalInput`.
99
+ * 3. A stage with `reads: [...]` receives the labelled multi-flag form
100
+ * `--<name1> <handle1> --<name2> <handle2> …` — each name resolves
101
+ * against `state.named[name].at(-1)`; a multi-artifact entry repeats
102
+ * the flag.
103
+ * 4. Otherwise: the rolling primary artifact's handle string.
104
+ *
105
+ * Returns `undefined` (instead of non-null-asserting) when a required
106
+ * projection input is missing — the rolling primary is unset, or a `reads`
107
+ * name has no published entry. The LIVE path never sees `undefined`: the
108
+ * preflights (`ensureUpstreamArtifact` / `ensureNamedReads`) guarantee the
109
+ * inputs before `inputForStage` delegates here. The RESUME fold freezes this
110
+ * value at loop-generation open, where replayed state is byte-identical to
111
+ * live loop entry (THE REPLAY CONTRACT); `undefined` there means a
112
+ * truncated/corrupted trail and becomes a recorded refusal.
113
+ */
114
+ export function stageEntryArgs(
115
+ def: StageDef,
116
+ stageName: string,
117
+ startStage: string,
118
+ state: RunState,
119
+ ): string | undefined {
120
+ if (def.prompt !== undefined) return "";
121
+ if (stageName === startStage) return state.originalInput;
122
+ if (def.inheritsArtifacts === false) return state.originalInput;
123
+ if (def.reads?.length) {
124
+ const parts: string[] = [];
125
+ for (const name of def.reads) {
126
+ const latest = state.named[name]?.at(-1);
127
+ if (!latest) return undefined;
128
+ for (const artifact of latest.artifacts) {
129
+ parts.push(`--${name}`, handleToString(artifact.handle));
130
+ }
131
+ }
132
+ return parts.join(" ");
133
+ }
134
+ const primary = currentPrimaryArtifact(state);
135
+ return primary === undefined ? undefined : handleToString(primary.handle);
136
+ }
137
+
138
+ /**
139
+ * The single authority for "a completed produces stage mutates the rolling
140
+ * artifact state." Called by the live skill path (sessions/sessions.ts), the
141
+ * live script path (runner/script-stage.ts), and state reconstruction
142
+ * (runner/resume.ts) — keeping all three in lockstep (parity-tested).
143
+ *
144
+ * Scope: primary slot + named-publish registry ONLY. `state.output` and
145
+ * `state.stagesCompleted` advance through `applyStageSuccess`
146
+ * (audit-rows.ts), which delegates here for the artifact slots.
147
+ *
148
+ * - kind "produces" → first artifact wins the rolling slot; the
149
+ * full Output appends onto state.named[key].
150
+ * - inheritsArtifacts === false → clear the slot (terminal()).
151
+ * - other side-effect → leave the slot untouched.
152
+ */
153
+ export function applyCompletedStage(state: RunState, def: StageDef, stageName: string, output: Output): void {
154
+ if (def.kind === "produces") {
155
+ const next = output.artifacts[0];
156
+ if (next) state.primaryArtifact = next;
157
+ const key = resolvePublishName(def, stageName);
158
+ let slot = state.named[key];
159
+ if (!slot) {
160
+ slot = [];
161
+ state.named[key] = slot;
162
+ }
163
+ slot.push(output);
164
+ return;
165
+ }
166
+ if (def.inheritsArtifacts === false) {
167
+ state.primaryArtifact = undefined;
168
+ }
169
+ }
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");
@@ -101,8 +127,7 @@ export async function handleWorkflowCommand(host: WorkflowHost, args: string, ct
101
127
  ctx.ui.notify(result.error, "error");
102
128
  }
103
129
  } catch (e) {
104
- const reason = e instanceof Error ? e.message : String(e);
105
- ctx.ui.notify(MSG_WORKFLOW_THREW(reason), "error");
130
+ ctx.ui.notify(MSG_WORKFLOW_THREW(formatError(e)), "error");
106
131
  }
107
132
  }
108
133
 
@@ -126,7 +151,7 @@ async function handleResume(host: WorkflowHost, ctx: WorkflowHostContext, ref: s
126
151
  ctx.ui.notify(result.error, "error");
127
152
  }
128
153
  } catch (e) {
129
- ctx.ui.notify(MSG_WORKFLOW_THREW(e instanceof Error ? e.message : String(e)), "error");
154
+ ctx.ui.notify(MSG_WORKFLOW_THREW(formatError(e)), "error");
130
155
  }
131
156
  }
132
157
 
@@ -144,6 +169,9 @@ function surfaceIssues(ctx: WorkflowHostContext, issues: readonly Issue[]): void
144
169
 
145
170
  function formatIssue(issue: Issue): string {
146
171
  if (issue.kind === "load") {
172
+ // "framework" = the loader's own machinery (providers, derivers) — no
173
+ // config file caused it, so no "config" suffix.
174
+ if (issue.layer === "framework") return `[framework] ${issue.message}`;
147
175
  const where = issue.path ? ` (${issue.path})` : "";
148
176
  return `[${renderConfigLayer(issue.layer)} config${where}] ${issue.message}`;
149
177
  }
package/command.ts CHANGED
@@ -1,37 +1,120 @@
1
1
  /**
2
2
  * /wf slash command registration — kept light. The heavy run-path (runner +
3
- * loader, ~530ms) lives in `./command-run.js`, dynamically imported only when
4
- * `/wf` is invoked, so registering the command costs nothing at startup.
3
+ * loader, ~0.9s of module evaluation) lives in `./command-run.js`, dynamically
4
+ * imported only when needed, so registering the command costs nothing at
5
+ * startup. The import promise is memoized in the handler closure: Pi's
6
+ * extension loader runs jiti with `moduleCache: false`, so a bare `import()`
7
+ * here would re-evaluate the entire graph on EVERY `/wf` — a recurring ~0.9s
8
+ * stall. The closure is held by Pi's command registry and survives across
9
+ * invocations; `/reload` re-registers and resets the memo, so edit pickup is
10
+ * preserved. A post-registration pre-warm kicks the same memoized import
11
+ * shortly after startup: jiti evaluation yields between modules (measured
12
+ * max event-loop stall ~0ms at 5ms sampling), so the warm-up causes no
13
+ * perceptible jank and the first real `/wf` finds the graph ready.
5
14
  * `parseArgs` stays here (pure, exported for tests).
6
15
  */
7
16
 
8
17
  import type { WorkflowHost, WorkflowHostContext } from "./host.js";
9
- import { CMD_DESCRIPTION } from "./messages.js";
18
+
19
+ /** Pi command registry — displayed by Pi's `/?` / command list. */
20
+ export const CMD_DESCRIPTION = "Run a skill workflow: /wf [workflow] [description]";
21
+
22
+ /**
23
+ * Cold-path toast — shown only when the user invokes `/wf` before the
24
+ * command-run graph has finished evaluating (i.e. they beat the pre-warm);
25
+ * this line is the only feedback in that ~1s window.
26
+ */
27
+ export const MSG_RUNTIME_LOADING = "rpiv: loading workflow runtime (first /wf after load)…";
28
+
29
+ /**
30
+ * Pre-warm delay — long enough to stay clear of Pi's own startup work,
31
+ * short enough to beat a human typing their first `/wf`.
32
+ */
33
+ export const PREWARM_DELAY_MS = 2000;
10
34
 
11
35
  // ---------------------------------------------------------------------------
12
36
  // Public entry
13
37
  // ---------------------------------------------------------------------------
14
38
 
39
+ type CommandRunModule = typeof import("./command-run.js");
40
+
41
+ export interface WfCommandHandler {
42
+ (args: string, ctx: WorkflowHostContext): Promise<void>;
43
+ /** Kick (or join) the memoized command-run import — the pre-warm entry. */
44
+ prewarm(): Promise<void>;
45
+ }
46
+
47
+ /**
48
+ * Build the `/wf` handler with a per-closure memo of the command-run import,
49
+ * shared between the handler and `prewarm()`. A rejected import is NOT
50
+ * memoized — the memo clears so the next call retries instead of replaying
51
+ * the cached rejection forever (a failed pre-warm therefore degrades to
52
+ * exactly the pre-warm-less behavior). Exported for tests (the importer is
53
+ * injectable); production callers go through `registerWorkflowCommand`.
54
+ */
55
+ export function makeWfHandler(
56
+ host: WorkflowHost,
57
+ importRun: () => Promise<CommandRunModule> = () => import("./command-run.js"),
58
+ ): WfCommandHandler {
59
+ let memo: Promise<CommandRunModule> | undefined;
60
+ let ready = false;
61
+
62
+ const load = async (): Promise<CommandRunModule> => {
63
+ memo ??= importRun();
64
+ try {
65
+ const mod = await memo;
66
+ ready = true;
67
+ return mod;
68
+ } catch (e) {
69
+ memo = undefined;
70
+ throw e;
71
+ }
72
+ };
73
+
74
+ const handler = async (args: string, ctx: WorkflowHostContext): Promise<void> => {
75
+ // `ready`, not `memo`: an in-flight pre-warm still leaves the user
76
+ // waiting, so the toast covers that window too.
77
+ if (!ready && ctx.hasUI) ctx.ui.notify(MSG_RUNTIME_LOADING, "info");
78
+ const mod = await load();
79
+ return mod.handleWorkflowCommand(host, args, ctx);
80
+ };
81
+
82
+ return Object.assign(handler, {
83
+ prewarm: async (): Promise<void> => {
84
+ const mod = await load();
85
+ // Also flush the lazy provider registries (built-ins DSL + skill
86
+ // contracts) — the other ~550ms of first-/wf work. Both are memoized
87
+ // latches; loadWorkflows joins the same promises later.
88
+ await mod.prewarmWorkflowRuntime();
89
+ },
90
+ });
91
+ }
92
+
15
93
  export function registerWorkflowCommand(host: WorkflowHost): void {
94
+ const handler = makeWfHandler(host);
16
95
  host.registerCommand("wf", {
17
96
  description: CMD_DESCRIPTION,
18
- handler: async (args: string, ctx: WorkflowHostContext) => {
19
- // Lazy — runner/loader graph evaluates on first `/wf`, not at startup.
20
- const { handleWorkflowCommand } = await import("./command-run.js");
21
- return handleWorkflowCommand(host, args, ctx);
22
- },
97
+ handler,
23
98
  });
99
+ // Swallowed rejection is safe: load() already cleared the memo, so the
100
+ // first real /wf retries and surfaces the error through its own path.
101
+ // unref keeps the timer from holding a non-TUI embedder's process open.
102
+ const timer = setTimeout(() => void handler.prewarm().catch(() => undefined), PREWARM_DELAY_MS);
103
+ timer.unref?.();
24
104
  }
25
105
 
26
106
  // ---------------------------------------------------------------------------
27
107
  // Arg parsing (pure; exported for tests + consumed by ./command-run.js)
28
108
  // ---------------------------------------------------------------------------
29
109
 
30
- const NAME_FLAG = /--name\s+([^\s]+)/;
110
+ const LEADING_NAME_FLAG = /^--name\s+(\S+)\s*/;
111
+ const TRAILING_NAME_FLAG = /\s+--name\s+(\S+)$/;
112
+ /** Any surviving `--name` token after the leading/trailing extraction — input text, flagged. */
113
+ const MID_NAME_FLAG = /(?:^|\s)--name(?:\s|$)/;
31
114
 
32
115
  export type ParsedCommand =
33
- | { kind: "run"; workflow: string; input: string; name?: string }
34
- | { kind: "resume"; ref: string; droppedName?: string };
116
+ | { kind: "run"; workflow: string; input: string; name?: string; nameFlagIgnored?: boolean }
117
+ | { kind: "resume"; ref: string; droppedName?: string; nameFlagIgnored?: boolean };
35
118
 
36
119
  /**
37
120
  * First token is a workflow name iff recognised; otherwise the whole arg is
@@ -39,6 +122,11 @@ export type ParsedCommand =
39
122
  * empty-registry case), the returned `workflow` is `""` and the orchestrator
40
123
  * surfaces `MSG_NO_WORKFLOWS_REGISTERED`.
41
124
  *
125
+ * `--name <slug>` is honored ONLY in leading or trailing position (leading
126
+ * wins when both are present). A `--name` anywhere else is the user's own
127
+ * prompt text (`/wf fix the --name handling bug`) — it stays in the input
128
+ * untouched and `nameFlagIgnored` is set so the command layer can warn.
129
+ *
42
130
  * `@<ref>` on the first token is the resume sigil — the first whitespace-
43
131
  * delimited token after `@` is the run reference. Leading space after the
44
132
  * sigil is tolerated (`@ ref` === `@ref`); trailing tokens are ignored.
@@ -50,21 +138,29 @@ export function parseArgs(
50
138
  let trimmed = args.trim();
51
139
  let name: string | undefined;
52
140
 
53
- // Extract --name <slug> flag and strip it before further parsing.
54
- const nameMatch = NAME_FLAG.exec(trimmed);
55
- if (nameMatch) {
56
- name = nameMatch[1];
57
- trimmed = trimmed.replace(NAME_FLAG, "").trim();
141
+ // Extract --name <slug> from the leading or trailing token position only.
142
+ const leading = LEADING_NAME_FLAG.exec(trimmed);
143
+ if (leading) {
144
+ name = leading[1];
145
+ trimmed = trimmed.slice(leading[0].length);
146
+ } else {
147
+ const trailing = TRAILING_NAME_FLAG.exec(trimmed);
148
+ if (trailing) {
149
+ name = trailing[1];
150
+ trimmed = trimmed.slice(0, trailing.index);
151
+ }
58
152
  }
153
+ const nameFlagIgnored = MID_NAME_FLAG.test(trimmed);
154
+ const ignored = nameFlagIgnored ? { nameFlagIgnored: true as const } : {};
59
155
 
60
156
  if (trimmed.startsWith("@")) {
61
157
  // @resume — name has no meaning here; carry it as `droppedName` so the
62
158
  // command layer can warn instead of silently dropping it.
63
- return { kind: "resume", ref: trimmed.slice(1).trim().split(/\s+/)[0] ?? "", droppedName: name };
159
+ return { kind: "resume", ref: trimmed.slice(1).trim().split(/\s+/)[0] ?? "", droppedName: name, ...ignored };
64
160
  }
65
161
 
66
162
  if (!trimmed) {
67
- return { kind: "run", workflow: loaded.default ?? "", input: "", name };
163
+ return { kind: "run", workflow: loaded.default ?? "", input: "", name, ...ignored };
68
164
  }
69
165
 
70
166
  const firstSpace = trimmed.indexOf(" ");
@@ -72,8 +168,8 @@ export function parseArgs(
72
168
 
73
169
  if (loaded.workflowNames.has(firstToken)) {
74
170
  const remaining = firstSpace === -1 ? "" : trimmed.slice(firstSpace + 1).trim();
75
- return { kind: "run", workflow: firstToken, input: remaining, name };
171
+ return { kind: "run", workflow: firstToken, input: remaining, name, ...ignored };
76
172
  }
77
173
 
78
- return { kind: "run", workflow: loaded.default ?? "", input: trimmed, name };
174
+ return { kind: "run", workflow: loaded.default ?? "", input: trimmed, name, ...ignored };
79
175
  }