@kontourai/flow-agents 3.6.0 → 3.7.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 (86) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/build/src/builder-flow-run-adapter.d.ts +22 -2
  3. package/build/src/builder-flow-run-adapter.js +93 -28
  4. package/build/src/builder-flow-runtime.d.ts +8 -3
  5. package/build/src/builder-flow-runtime.js +308 -47
  6. package/build/src/cli/assignment-provider.d.ts +4 -7
  7. package/build/src/cli/assignment-provider.js +67 -13
  8. package/build/src/cli/builder-run.js +14 -18
  9. package/build/src/cli/workflow-sidecar.d.ts +28 -4
  10. package/build/src/cli/workflow-sidecar.js +801 -97
  11. package/build/src/cli/workflow.js +290 -42
  12. package/build/src/flow-kit/validate.d.ts +17 -0
  13. package/build/src/flow-kit/validate.js +340 -2
  14. package/build/src/index.js +5 -5
  15. package/build/src/lib/observed-command.d.ts +7 -0
  16. package/build/src/lib/observed-command.js +100 -0
  17. package/build/src/tools/generate-context-map.js +5 -3
  18. package/context/scripts/hooks/lib/kit-catalog.js +1 -1
  19. package/context/scripts/hooks/stop-goal-fit.js +78 -9
  20. package/docs/context-map.md +22 -20
  21. package/docs/developer-architecture.md +1 -1
  22. package/docs/public-workflow-cli.md +76 -7
  23. package/docs/skills-map.md +51 -27
  24. package/docs/spec/builder-flow-runtime.md +41 -40
  25. package/docs/workflow-usage-guide.md +109 -42
  26. package/evals/fixtures/hook-influence/cases.json +2 -2
  27. package/evals/integration/test_builder_entry_enforcement.sh +52 -41
  28. package/evals/integration/test_builder_step_producers.sh +297 -6
  29. package/evals/integration/test_bundle_install.sh +212 -63
  30. package/evals/integration/test_critique_supersession_roundtrip.sh +21 -8
  31. package/evals/integration/test_current_json_per_actor.sh +12 -0
  32. package/evals/integration/test_dual_emit_flow_step.sh +62 -43
  33. package/evals/integration/test_flowdef_session_activation.sh +145 -25
  34. package/evals/integration/test_flowdef_session_history_preservation.sh +23 -21
  35. package/evals/integration/test_gate_lockdown.sh +3 -5
  36. package/evals/integration/test_goal_fit_hook.sh +60 -2
  37. package/evals/integration/test_liveness_verdict.sh +14 -17
  38. package/evals/integration/test_phase_map_and_gate_claim.sh +63 -38
  39. package/evals/integration/test_public_workflow_cli.sh +325 -11
  40. package/evals/integration/test_pull_work_liveness_preflight.sh +22 -66
  41. package/evals/integration/test_sidecar_field_preservation.sh +36 -11
  42. package/evals/integration/test_workflow_sidecar_writer.sh +277 -44
  43. package/evals/integration/test_workflow_steering_hook.sh +15 -38
  44. package/evals/run.sh +2 -0
  45. package/evals/static/test_builder_skill_coherence.sh +247 -0
  46. package/evals/static/test_library_exports.sh +5 -2
  47. package/evals/static/test_workflow_skills.sh +13 -325
  48. package/kits/builder/flows/build.flow.json +22 -0
  49. package/kits/builder/flows/shape.flow.json +9 -9
  50. package/kits/builder/kit.json +70 -16
  51. package/kits/builder/skills/builder-shape/SKILL.md +75 -75
  52. package/kits/builder/skills/continue-work/SKILL.md +45 -106
  53. package/kits/builder/skills/deliver/SKILL.md +96 -442
  54. package/kits/builder/skills/design-probe/SKILL.md +40 -139
  55. package/kits/builder/skills/evidence-gate/SKILL.md +59 -201
  56. package/kits/builder/skills/execute-plan/SKILL.md +54 -125
  57. package/kits/builder/skills/fix-bug/SKILL.md +42 -132
  58. package/kits/builder/skills/gate-review/SKILL.md +60 -211
  59. package/kits/builder/skills/idea-to-backlog/SKILL.md +63 -244
  60. package/kits/builder/skills/learning-review/SKILL.md +63 -170
  61. package/kits/builder/skills/pickup-probe/SKILL.md +54 -111
  62. package/kits/builder/skills/plan-work/SKILL.md +51 -185
  63. package/kits/builder/skills/pull-work/SKILL.md +136 -485
  64. package/kits/builder/skills/release-readiness/SKILL.md +66 -107
  65. package/kits/builder/skills/review-work/SKILL.md +89 -176
  66. package/kits/builder/skills/tdd-workflow/SKILL.md +53 -147
  67. package/kits/builder/skills/verify-work/SKILL.md +101 -113
  68. package/package.json +2 -2
  69. package/scripts/hooks/lib/kit-catalog.js +1 -1
  70. package/scripts/hooks/stop-goal-fit.js +78 -9
  71. package/src/builder-flow-run-adapter.ts +118 -32
  72. package/src/builder-flow-runtime.ts +331 -61
  73. package/src/cli/assignment-provider-lock.test.mjs +83 -0
  74. package/src/cli/assignment-provider.ts +62 -13
  75. package/src/cli/builder-flow-run-adapter.test.mjs +4 -2
  76. package/src/cli/builder-flow-runtime.test.mjs +194 -8
  77. package/src/cli/builder-run.ts +3 -9
  78. package/src/cli/kit-metadata-security.test.mjs +232 -6
  79. package/src/cli/public-api.test.mjs +15 -0
  80. package/src/cli/workflow-sidecar-execution-proof.test.mjs +90 -0
  81. package/src/cli/workflow-sidecar.ts +724 -97
  82. package/src/cli/workflow.ts +277 -40
  83. package/src/flow-kit/validate.ts +320 -2
  84. package/src/index.ts +6 -5
  85. package/src/lib/observed-command.ts +96 -0
  86. package/src/tools/generate-context-map.ts +5 -3
@@ -3,19 +3,23 @@ import * as path from "node:path";
3
3
  import { createHash } from "node:crypto";
4
4
  import { createRequire } from "node:module";
5
5
  import { isDeepStrictEqual } from "node:util";
6
- import { loadBuilderBuildRun } from "../builder-flow-run-adapter.js";
6
+ import { fileURLToPath } from "node:url";
7
+ import { validateDefinition } from "@kontourai/flow";
8
+ import { loadBuilderFlowRun } from "../builder-flow-run-adapter.js";
9
+ import { inspectBuilderFlowSession, recoverBuilderFlowSession, syncBuilderFlowSession } from "../builder-flow-runtime.js";
7
10
  import { flowAgentsPackageRoot, flowAgentsPackageVersion } from "../lib/package-version.js";
8
11
  import { pinnedFlowAgentsCommand } from "../lib/pinned-cli-command.js";
9
12
  import { defaultArtifactRootForRead, flowAgentsArtifactRoot } from "../lib/local-artifact-root.js";
10
- import { flagBool, flagString, parseArgs } from "../lib/args.js";
13
+ import { flagBool, flagList, flagString, parseArgs } from "../lib/args.js";
11
14
  import { main as builderRun } from "./builder-run.js";
12
- import { currentWorkflowSessionDir, main as workflowWriter, WORKFLOW_WRITER_CONTRACT_VERSION } from "./workflow-sidecar.js";
15
+ import { currentWorkflowSessionDir, isMeaningfulTestCommand, mainFromPublicWorkflow, WORKFLOW_WRITER_CONTRACT_VERSION } from "./workflow-sidecar.js";
16
+ import { resolveCurrentAssignmentActor, withSubjectLock } from "./assignment-provider.js";
13
17
  export const WORKFLOW_CONTRACT_VERSION = "1.0";
14
18
  const PACKAGE_ROOT = flowAgentsPackageRoot();
15
19
  const REQUIRE = createRequire(import.meta.url);
16
20
  const PACKAGE_METADATA = readJsonFile(path.join(PACKAGE_ROOT, "package.json"), "Flow Agents package metadata");
17
21
  const CLI_VERSION = flowAgentsPackageVersion();
18
- const PUBLIC_VERBS = ["start", "status", "evidence", "pause", "resume", "release", "cancel", "archive", "doctor"];
22
+ const PUBLIC_VERBS = ["start", "status", "evidence", "critique", "pause", "resume", "release", "cancel", "archive", "doctor"];
19
23
  function usage() {
20
24
  console.log(`Usage: flow-agents workflow <verb> [options]
21
25
 
@@ -23,6 +27,7 @@ Public workflow verbs:
23
27
  start Start or resume a workflow for a Work Item.
24
28
  status Show the current canonical run and projected next action.
25
29
  evidence Record evidence for the current Flow gate and synchronize it.
30
+ critique Record review critique directly into the current trust bundle.
26
31
  pause Pause the current run as its assignment actor.
27
32
  resume Resume the current paused run as its assignment actor.
28
33
  release Release the current assignment without canceling the run.
@@ -53,6 +58,8 @@ export async function main(argv) {
53
58
  return status(sessionDir, flagBool(parsed.flags, "json"));
54
59
  if (verb === "evidence")
55
60
  return evidence(sessionDir, argv.slice(1), flagBool(parsed.flags, "json"));
61
+ if (verb === "critique")
62
+ return critique(sessionDir, argv.slice(1), flagBool(parsed.flags, "json"));
56
63
  const forwarded = stripPublicFlags(argv.slice(1), new Set(["artifact-root", "session-dir", "json"]));
57
64
  if (verb === "release" && !flagString(parsed.flags, "reason"))
58
65
  throw new Error("workflow release requires --reason <text>");
@@ -60,16 +67,34 @@ export async function main(argv) {
60
67
  }
61
68
  async function start(argv) {
62
69
  const parsed = parseArgs(argv);
63
- assertOnlyFlags(parsed.flags, new Set(["flow", "work-item", "task-slug", "artifact-root", "source-request", "summary", "title", "criterion"]), "workflow start");
70
+ assertOnlyFlags(parsed.flags, new Set(["flow", "work-item", "task-slug", "artifact-root", "source-request", "summary", "title", "criterion", "assignment-provider", "effective-state-json"]), "workflow start");
64
71
  const flow = flagString(parsed.flags, "flow", "builder.build");
65
- if (flow !== "builder.build")
66
- throw new Error("workflow start currently supports only --flow builder.build");
72
+ if (flow !== "builder.build" && flow !== "builder.shape")
73
+ throw new Error("workflow start supports only --flow builder.build or builder.shape");
67
74
  const workItem = flagString(parsed.flags, "work-item");
68
- if (!workItem)
69
- throw new Error("workflow start requires --work-item <owner/repo#id>");
70
75
  const artifactRoot = path.resolve(flagString(parsed.flags, "artifact-root", flowAgentsArtifactRoot()));
71
76
  const taskSlug = flagString(parsed.flags, "task-slug");
72
- if (workItem.startsWith("local:")) {
77
+ if (flow === "builder.shape") {
78
+ if (!taskSlug || !isSafeSlug(taskSlug))
79
+ throw new Error("workflow start --flow builder.shape requires an explicit safe --task-slug");
80
+ if (workItem)
81
+ throw new Error("workflow start --flow builder.shape creates a local Work Item; omit --work-item");
82
+ }
83
+ else if (!workItem) {
84
+ throw new Error("workflow start requires --work-item <provider-ref>");
85
+ }
86
+ const assignmentProvider = flagString(parsed.flags, "assignment-provider", flow === "builder.shape" || workItem?.startsWith("local:") ? "local-file" : undefined);
87
+ const effectiveStateJson = flagString(parsed.flags, "effective-state-json");
88
+ if (flow === "builder.build" && workItem && !workItem.startsWith("local:") && !assignmentProvider) {
89
+ throw new Error("workflow start requires --assignment-provider <kind> for a provider-backed Work Item; provider identity is never inferred from its reference");
90
+ }
91
+ if (assignmentProvider !== "local-file" && !effectiveStateJson) {
92
+ throw new Error(`workflow start requires --effective-state-json <path> for assignment provider ${assignmentProvider}`);
93
+ }
94
+ if (assignmentProvider === "local-file" && effectiveStateJson) {
95
+ throw new Error("workflow start --effective-state-json is only valid for a non-local assignment provider");
96
+ }
97
+ if (workItem?.startsWith("local:")) {
73
98
  const localSlug = workItem.slice("local:".length);
74
99
  if (!taskSlug || taskSlug !== localSlug || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(localSlug)) {
75
100
  throw new Error("local Work Item retries require the exact existing --task-slug binding");
@@ -80,28 +105,57 @@ async function start(argv) {
80
105
  throw new Error("local Work Item retry does not match the existing session binding");
81
106
  }
82
107
  }
83
- else if (taskSlug) {
108
+ else if (taskSlug && flow !== "builder.shape") {
84
109
  throw new Error("--task-slug is reserved for an existing local Work Item retry");
85
110
  }
86
- const sourceRequest = flagString(parsed.flags, "source-request", `Start ${flow} for ${workItem}`);
87
- const summary = flagString(parsed.flags, "summary", `Deliver ${workItem} through ${flow}.`);
111
+ const existingSlug = taskSlug ?? (workItem ? workItemSlug(workItem) : null);
112
+ if (existingSlug && fs.existsSync(path.join(artifactRoot, existingSlug, "state.json"))) {
113
+ try {
114
+ const existing = await loadBuilderFlowRun({ cwd: path.dirname(path.dirname(artifactRoot)), runId: existingSlug });
115
+ if (existing.definitionId !== flow) {
116
+ throw new Error(`workflow start cannot resume ${existing.definitionId} as ${flow}; local shape sessions are not build retries. Create or claim a provider Work Item for the builder.build handoff.`);
117
+ }
118
+ }
119
+ catch (error) {
120
+ if (error.code !== "flow.run_location.not_found")
121
+ throw error;
122
+ }
123
+ }
124
+ if (flow === "builder.build" && workItem && !workItem.startsWith("local:")) {
125
+ const slug = workItemSlug(workItem);
126
+ const report = path.join(artifactRoot, slug, `${slug}--pull-work.md`);
127
+ try {
128
+ const stat = fs.lstatSync(report);
129
+ if (stat.isSymbolicLink() || !stat.isFile() || !fs.readFileSync(report, "utf8").includes(workItem)) {
130
+ throw new Error("invalid");
131
+ }
132
+ }
133
+ catch {
134
+ throw new Error(`workflow start requires concrete pull-work selection evidence at ${report} naming ${workItem} before it can produce selected-work`);
135
+ }
136
+ }
137
+ const sourceRequest = flagString(parsed.flags, "source-request", `Start ${flow} for ${workItem ?? `local:${taskSlug}`}`);
138
+ const summary = flagString(parsed.flags, "summary", `Deliver ${workItem ?? `local:${taskSlug}`} through ${flow}.`);
88
139
  const forwarded = keepFlags(argv, new Set(["title", "criterion"]));
89
- return workflowWriter([
140
+ return mainFromPublicWorkflow([
90
141
  "ensure-session",
91
142
  "--artifact-root", artifactRoot,
92
143
  "--flow-id", flow,
93
- "--work-item", workItem,
144
+ ...(workItem ? ["--work-item", workItem] : []),
94
145
  ...(taskSlug ? ["--task-slug", taskSlug] : []),
146
+ ...(assignmentProvider ? ["--assignment-provider", assignmentProvider] : []),
147
+ ...(effectiveStateJson ? ["--effective-state-json", path.resolve(effectiveStateJson)] : []),
95
148
  "--source-request", sourceRequest,
96
149
  "--summary", summary,
97
150
  ...forwarded,
98
151
  ]);
99
152
  }
153
+ function workItemSlug(workItem) {
154
+ return workItem.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
155
+ }
100
156
  async function status(sessionDir, json) {
101
- const sidecar = readJsonFile(path.join(sessionDir, "state.json"), "workflow state");
102
- const slug = String(sidecar.task_slug ?? path.basename(sessionDir));
103
- const projectRoot = path.dirname(path.dirname(path.dirname(sessionDir)));
104
- const result = await loadBuilderBuildRun({ cwd: projectRoot, runId: slug });
157
+ const inspected = await inspectBuilderFlowSession({ sessionDir });
158
+ const result = inspected.run;
105
159
  const report = {
106
160
  run_id: result.runId,
107
161
  definition_id: result.definitionId,
@@ -109,7 +163,7 @@ async function status(sessionDir, json) {
109
163
  status: result.state.status,
110
164
  current_step: result.state.current_step,
111
165
  session_dir: sessionDir,
112
- next_action: sidecar.next_action ?? null,
166
+ next_action: inspected.projection.next_action ?? null,
113
167
  };
114
168
  if (json)
115
169
  console.log(JSON.stringify(report));
@@ -123,7 +177,7 @@ async function status(sessionDir, json) {
123
177
  }
124
178
  async function evidence(sessionDir, argv, json) {
125
179
  const parsed = parseArgs(argv);
126
- assertOnlyFlags(parsed.flags, new Set(["artifact-root", "session-dir", "json", "expectation", "status", "summary", "evidence-ref-json", "accepted-gap-reason", "waived-by"]), "workflow evidence");
180
+ assertOnlyFlags(parsed.flags, new Set(["artifact-root", "session-dir", "json", "expectation", "status", "summary", "route-reason", "evidence-ref-json", "criterion-json", "accepted-gap-reason", "waived-by", "command"]), "workflow evidence");
127
181
  if (!flagString(parsed.flags, "expectation"))
128
182
  throw new Error("workflow evidence requires --expectation <gate-expectation-id>");
129
183
  if (!flagString(parsed.flags, "status"))
@@ -131,23 +185,104 @@ async function evidence(sessionDir, argv, json) {
131
185
  if (!flagString(parsed.flags, "summary"))
132
186
  throw new Error("workflow evidence requires --summary <text>");
133
187
  const forwarded = stripPublicFlags(argv, new Set(["artifact-root", "session-dir", "json"]));
134
- await workflowWriter(["record-gate-claim", sessionDir, ...forwarded]);
135
- const sidecar = readJsonFile(path.join(sessionDir, "state.json"), "workflow state");
136
- const projectRoot = path.dirname(path.dirname(path.dirname(sessionDir)));
137
- const result = await loadBuilderBuildRun({ cwd: projectRoot, runId: String(sidecar.task_slug ?? path.basename(sessionDir)) });
138
- const report = {
139
- run_id: result.runId,
140
- status: result.state.status,
141
- current_step: result.state.current_step,
142
- attached: result.attachedEvidence.length > 0,
143
- next_action: sidecar.next_action ?? null,
144
- };
188
+ const { slug, projectRoot } = readBoundSession(sessionDir);
189
+ const commands = flagList(parsed.flags, "command");
190
+ if (Object.hasOwn(parsed.flags, "command") && commands.length === 0) {
191
+ throw new Error("workflow evidence --command requires a shell command value");
192
+ }
193
+ const requiresTestEvidence = flagString(parsed.flags, "expectation") === "tests-evidence" && flagString(parsed.flags, "status") === "pass";
194
+ // Argument and command-shape rejection must be read-only. Recovery below may
195
+ // repair stale projections, so it runs only after every command is accepted.
196
+ assertRunnableEvidenceCommands(commands, projectRoot, requiresTestEvidence);
197
+ const report = await withSubjectLock(path.dirname(sessionDir), slug, async () => {
198
+ // Validate the owner after the lock is held, then keep the lock through command
199
+ // execution, evidence recording, and postcondition capture so assignment and
200
+ // session state cannot change mid-invocation.
201
+ const caller = assertMatchingAssignmentActor(sessionDir, slug);
202
+ const repaired = await recoverBuilderFlowSession({ sessionDir });
203
+ const beforeEvidence = manifestEvidenceDigests(repaired.run.manifest);
204
+ await mainFromPublicWorkflow([
205
+ "record-gate-claim",
206
+ sessionDir,
207
+ ...forwarded,
208
+ "--actor",
209
+ caller.actorKey,
210
+ ]);
211
+ await syncBuilderFlowSession({ sessionDir });
212
+ const digest = fileSha256(path.join(sessionDir, "trust.bundle"));
213
+ const run = await loadBuilderFlowRun({ cwd: repaired.projectRoot, runId: slug });
214
+ const afterEvidence = manifestEvidenceDigests(run.manifest);
215
+ const newEvidence = afterEvidence.filter((value) => !beforeEvidence.includes(value));
216
+ if (newEvidence.length !== 1 || newEvidence[0] !== digest) {
217
+ throw new Error("workflow evidence did not attach exactly this invocation's resulting trust.bundle digest");
218
+ }
219
+ const updatedSidecar = readBoundSession(sessionDir).sidecar;
220
+ return immutableReport({
221
+ run_id: run.runId,
222
+ status: run.state.status,
223
+ current_step: run.state.current_step,
224
+ attached: true,
225
+ next_action: updatedSidecar.next_action ?? null,
226
+ });
227
+ });
145
228
  if (json)
146
229
  console.log(JSON.stringify(report));
147
230
  else
148
231
  console.log(`Recorded evidence; canonical run is ${report.status} at ${report.current_step}.`);
149
232
  return 0;
150
233
  }
234
+ async function critique(sessionDir, argv, json) {
235
+ const parsed = parseArgs(argv);
236
+ assertOnlyFlags(parsed.flags, new Set(["artifact-root", "session-dir", "json", "id", "verdict", "summary", "artifact-ref", "finding-json", "lane-json", "timestamp"]), "workflow critique");
237
+ if (!flagString(parsed.flags, "summary"))
238
+ throw new Error("workflow critique requires --summary <text>");
239
+ if (Object.hasOwn(parsed.flags, "reviewer"))
240
+ throw new Error("workflow critique derives reviewer identity from the authenticated assignment actor; --reviewer is not accepted");
241
+ const { slug, projectRoot } = readBoundSession(sessionDir);
242
+ const forwarded = stripPublicFlags(argv, new Set(["artifact-root", "session-dir", "json"]));
243
+ const report = await withSubjectLock(path.dirname(sessionDir), slug, async () => {
244
+ const caller = assertDistinctReviewActor(sessionDir, slug);
245
+ const current = await loadBuilderFlowRun({ cwd: projectRoot, runId: slug });
246
+ if (current.definitionId !== "builder.build" || current.state.current_step !== "verify")
247
+ throw new Error("workflow critique is allowed only for the canonical builder.build verify step");
248
+ const beforeManifest = JSON.parse(JSON.stringify(current.manifest));
249
+ const beforeTrustBundle = optionalFileDigest(path.join(sessionDir, "trust.bundle"));
250
+ const legacySidecars = ["critique.json", "evidence.json"].map((name) => ({ name, digest: optionalFileDigest(path.join(sessionDir, name)) }));
251
+ await mainFromPublicWorkflow(["record-critique", sessionDir, ...forwarded, "--reviewer", caller.actorKey]);
252
+ const result = await recoverBuilderFlowSession({ sessionDir });
253
+ const digest = fileSha256(path.join(sessionDir, "trust.bundle"));
254
+ if (!isDeepStrictEqual(result.run.manifest, beforeManifest)) {
255
+ throw new Error("workflow critique must not attach or otherwise mutate the Flow manifest");
256
+ }
257
+ if (beforeTrustBundle === digest) {
258
+ throw new Error("workflow critique did not change trust.bundle");
259
+ }
260
+ if (legacySidecars.some(({ name, digest: legacyDigest }) => optionalFileDigest(path.join(sessionDir, name)) !== legacyDigest)) {
261
+ throw new Error("workflow critique must persist only through trust.bundle");
262
+ }
263
+ return immutableReport({ run_id: slug, recorded: true });
264
+ });
265
+ if (json)
266
+ console.log(JSON.stringify(report));
267
+ else
268
+ console.log("Recorded critique in the trust bundle.");
269
+ return 0;
270
+ }
271
+ function assertRunnableEvidenceCommands(commands, projectRoot, requiresTestEvidence) {
272
+ const helperPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../scripts/hooks/lib/runnable-command.js");
273
+ const { isRunnableCommandText } = REQUIRE(helperPath);
274
+ if (commands.length > 1 && new Set(commands).size !== commands.length) {
275
+ throw new Error("workflow evidence --command values must be unique because observations are matched by exact command text");
276
+ }
277
+ for (const command of commands) {
278
+ if (!isRunnableCommandText(command)) {
279
+ throw new Error(`workflow evidence --command ${JSON.stringify(command)} is not a runnable shell command — prose belongs in --summary, which is never executed.`);
280
+ }
281
+ if (requiresTestEvidence && !isMeaningfulTestCommand(command, projectRoot)) {
282
+ throw new Error("workflow evidence tests-evidence command must resolve through a non-vacuous package script or a known test/check/verify/eval runner or project-local test path; shell wrappers, no-ops, version/help commands, and arbitrary node -e commands are not evidence");
283
+ }
284
+ }
285
+ }
151
286
  function resolveSessionDir(flags) {
152
287
  const explicit = flagString(flags, "session-dir");
153
288
  if (explicit)
@@ -170,11 +305,16 @@ function doctor(argv) {
170
305
  const install = readOptionalJson(installFile);
171
306
  const state = readCurrentState(artifactRoot);
172
307
  const packageKit = readOptionalJson(path.join(packageRoot, "kits", "builder", "kit.json"));
173
- const packageFlow = readOptionalJson(path.join(packageRoot, "kits", "builder", "flows", "build.flow.json"));
174
308
  const installedKitFile = path.join(projectRoot, "kits", "builder", "kit.json");
175
- const installedFlowFile = path.join(projectRoot, "kits", "builder", "flows", "build.flow.json");
176
309
  const installedKit = readOptionalJson(installedKitFile);
177
- const installedFlow = readOptionalJson(installedFlowFile);
310
+ const definitions = [
311
+ { id: "builder.build", file: "build.flow.json" },
312
+ { id: "builder.shape", file: "shape.flow.json" },
313
+ ].map(({ id, file }) => {
314
+ const packageFile = path.join(packageRoot, "kits", "builder", "flows", file);
315
+ const installedFile = path.join(projectRoot, "kits", "builder", "flows", file);
316
+ return { id, packageFile, installedFile, packageDefinition: readOptionalJson(packageFile), installedDefinition: readOptionalJson(installedFile) };
317
+ });
178
318
  const resolvedFlowPackage = readOptionalJson(resolveDependencyPackageJson("@kontourai/flow"));
179
319
  const installedVersion = typeof install?.version === "string" ? install.version : null;
180
320
  const staleInstall = installedVersion !== null && installedVersion !== cliVersion;
@@ -195,19 +335,39 @@ function doctor(argv) {
195
335
  warnings.push(`Repository-local Flow Agents ${String(localDependency.version)} differs from executing CLI ${cliVersion}; keep automation explicitly versioned.`);
196
336
  if (activeKitIds.includes("builder") && !installedKit)
197
337
  warnings.push(`Activated Builder Kit is missing at ${installedKitFile}. Run: ${remediation}`);
198
- if (activeKitIds.includes("builder") && !installedFlow)
199
- warnings.push(`Activated builder.build definition is missing at ${installedFlowFile}. Run: ${remediation}`);
338
+ for (const definition of definitions) {
339
+ if (activeKitIds.includes("builder") && !definition.installedDefinition) {
340
+ warnings.push(`Activated ${definition.id} definition is missing at ${definition.installedFile}. Run: ${remediation}`);
341
+ continue;
342
+ }
343
+ if (!definition.installedDefinition)
344
+ continue;
345
+ const validationError = validateFlowDefinition(definition.id, definition.installedDefinition);
346
+ if (validationError)
347
+ warnings.push(`Installed ${definition.id} definition is invalid: ${validationError}. Run: ${remediation}`);
348
+ if (definition.installedDefinition.id !== definition.packageDefinition?.id) {
349
+ warnings.push(`Installed ${definition.id} definition id ${String(definition.installedDefinition.id)} differs from CLI definition ${String(definition.packageDefinition?.id)}. Run: ${remediation}`);
350
+ }
351
+ if (definition.installedDefinition.version !== definition.packageDefinition?.version) {
352
+ warnings.push(`Installed ${definition.id} version ${String(definition.installedDefinition.version)} differs from CLI version ${String(definition.packageDefinition?.version)}. Run: ${remediation}`);
353
+ }
354
+ else if (fileSha256(definition.installedFile) !== fileSha256(definition.packageFile)) {
355
+ warnings.push(`Installed ${definition.id} content differs from Flow Agents ${cliVersion}. Run: ${remediation}`);
356
+ }
357
+ }
200
358
  if (installedKit && installedKit.schema_version !== packageKit?.schema_version) {
201
359
  warnings.push(`Installed Builder Kit schema ${String(installedKit.schema_version)} differs from CLI schema ${String(packageKit?.schema_version)}. Run: ${remediation}`);
202
360
  }
203
361
  if (installedKit && fileSha256(installedKitFile) !== fileSha256(path.join(packageRoot, "kits", "builder", "kit.json"))) {
204
362
  warnings.push(`Installed Builder Kit content differs from Flow Agents ${cliVersion}. Run: ${remediation}`);
205
363
  }
206
- if (installedFlow && installedFlow.version !== packageFlow?.version) {
207
- warnings.push(`Installed builder.build version ${String(installedFlow.version)} differs from CLI version ${String(packageFlow?.version)}. Run: ${remediation}`);
364
+ const currentRun = state?.flow_run && typeof state.flow_run === "object" ? state.flow_run : null;
365
+ const currentDefinition = definitions.find((definition) => definition.id === currentRun?.definition_id);
366
+ if (currentRun?.definition_id && !currentDefinition) {
367
+ warnings.push(`Current run uses unsupported Flow definition ${String(currentRun.definition_id)}; recover or migrate before mutation.`);
208
368
  }
209
- if (state?.flow_run && state.flow_run.definition_version !== packageFlow?.version) {
210
- warnings.push(`Current run uses builder.build@${String(state.flow_run.definition_version)} while CLI resolves ${String(packageFlow?.version)}; recover or migrate before mutation.`);
369
+ else if (currentRun && currentDefinition && currentRun.definition_version !== currentDefinition.packageDefinition?.version) {
370
+ warnings.push(`Current run uses ${currentDefinition.id}@${String(currentRun.definition_version)} while CLI resolves ${currentDefinition.id}@${String(currentDefinition.packageDefinition?.version)}; recover or migrate before mutation.`);
211
371
  }
212
372
  if (state && state.schema_version !== "1.0")
213
373
  warnings.push(`Artifact schema ${String(state.schema_version)} is unsupported; recreate or migrate the session with CLI ${cliVersion}.`);
@@ -245,7 +405,13 @@ function doctor(argv) {
245
405
  source: installedKit ? installedKitFile : path.join(packageRoot, "kits", "builder", "kit.json"),
246
406
  },
247
407
  flow_runtime: { package_version: resolvedFlowVersion, expected_range: expectedFlowRange, compatible: resolvedFlowVersion ? flowVersionCompatible(resolvedFlowVersion, expectedFlowRange) : false },
248
- definition: { id: state?.flow_run?.definition_id ?? packageFlow?.id ?? null, version: state?.flow_run?.definition_version ?? packageFlow?.version ?? null },
408
+ definition: { id: currentRun?.definition_id ?? definitions[0].packageDefinition?.id ?? null, version: currentRun?.definition_version ?? definitions[0].packageDefinition?.version ?? null },
409
+ definitions: definitions.map((definition) => ({
410
+ id: definition.id,
411
+ resolved_version: definition.packageDefinition?.version ?? null,
412
+ installed_version: definition.installedDefinition?.version ?? null,
413
+ installed_valid: definition.installedDefinition ? validateFlowDefinition(definition.id, definition.installedDefinition) === null : false,
414
+ })),
249
415
  artifact: {
250
416
  state_schema_version: state?.schema_version ?? null,
251
417
  trust_bundle_schema_version: trustBundleSchema,
@@ -309,6 +475,88 @@ function readOptionalJson(file) {
309
475
  throw error;
310
476
  }
311
477
  }
478
+ function validateFlowDefinition(expectedId, definition) {
479
+ if (definition.id !== expectedId)
480
+ return `expected id ${expectedId}, received ${String(definition.id)}`;
481
+ try {
482
+ validateDefinition(definition);
483
+ return null;
484
+ }
485
+ catch (error) {
486
+ return error instanceof Error ? error.message : String(error);
487
+ }
488
+ }
489
+ function isSafeSlug(value) {
490
+ return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value);
491
+ }
492
+ function readBoundSession(sessionDir) {
493
+ const slug = path.basename(sessionDir);
494
+ if (!isSafeSlug(slug))
495
+ throw new Error("workflow session basename must be a safe task slug");
496
+ const sidecar = readJsonFile(path.join(sessionDir, "state.json"), "workflow state");
497
+ if (sidecar.task_slug !== slug)
498
+ throw new Error("workflow state task_slug must exactly match the safe session basename");
499
+ return { sidecar, slug, projectRoot: path.dirname(path.dirname(path.dirname(sessionDir))) };
500
+ }
501
+ function readAssignment(sessionDir, slug) {
502
+ const artifactRoot = path.dirname(sessionDir);
503
+ const assignmentRoot = path.join(artifactRoot, "assignment");
504
+ const stat = fs.lstatSync(assignmentRoot);
505
+ if (stat.isSymbolicLink() || !stat.isDirectory())
506
+ throw new Error("workflow assignment directory must be a non-symlink directory");
507
+ const file = path.join(assignmentRoot, `${slug}.json`);
508
+ const fileStat = fs.lstatSync(file);
509
+ if (fileStat.isSymbolicLink() || !fileStat.isFile())
510
+ throw new Error("workflow assignment must be a non-symlink regular file");
511
+ return readJsonFile(file, "workflow assignment");
512
+ }
513
+ function assertMatchingAssignmentActor(sessionDir, slug) {
514
+ const assignment = readActiveAssignment(sessionDir, slug);
515
+ const caller = resolveCurrentAssignmentActor();
516
+ const normalizeActor = (value) => value && typeof value === "object" ? { ...value, human: value.human ?? null } : null;
517
+ if (assignment.actor_key !== caller.actorKey || !isDeepStrictEqual(normalizeActor(assignment.actor), normalizeActor(caller.actor))) {
518
+ throw new Error("workflow mutation requires the session's active, matching assignment actor");
519
+ }
520
+ return caller;
521
+ }
522
+ function readActiveAssignment(sessionDir, slug) {
523
+ const assignment = readAssignment(sessionDir, slug);
524
+ if (assignment.status !== "claimed" || assignment.artifact_dir !== slug || typeof assignment.actor_key !== "string" || !assignment.actor_key || !assignment.actor || typeof assignment.actor !== "object" || Array.isArray(assignment.actor)) {
525
+ throw new Error("workflow mutation requires the session's active implementation assignment");
526
+ }
527
+ return assignment;
528
+ }
529
+ function assertDistinctReviewActor(sessionDir, slug) {
530
+ const assignment = readActiveAssignment(sessionDir, slug);
531
+ const caller = resolveCurrentAssignmentActor();
532
+ if (assignment.actor_key === caller.actorKey) {
533
+ throw new Error("workflow critique requires a reviewer identity distinct from the active implementation assignment actor");
534
+ }
535
+ return caller;
536
+ }
537
+ function immutableReport(value) {
538
+ if (!value || typeof value !== "object")
539
+ return value;
540
+ for (const nested of Object.values(value))
541
+ immutableReport(nested);
542
+ return Object.freeze(value);
543
+ }
544
+ function manifestEvidenceDigests(manifest) {
545
+ const evidence = Array.isArray(manifest.evidence) ? manifest.evidence : [];
546
+ return evidence
547
+ .map((entry) => entry && typeof entry === "object" ? entry.sha256 : null)
548
+ .filter((digest) => typeof digest === "string");
549
+ }
550
+ function optionalFileDigest(file) {
551
+ try {
552
+ return fileSha256(file);
553
+ }
554
+ catch (error) {
555
+ if (error.code === "ENOENT")
556
+ return null;
557
+ throw error;
558
+ }
559
+ }
312
560
  function stripPublicFlags(argv, removed) {
313
561
  const result = [];
314
562
  for (let index = 0; index < argv.length; index += 1) {
@@ -28,6 +28,19 @@ export interface KitFlowStepActionEntry {
28
28
  step_id: string;
29
29
  skills: string[];
30
30
  operations: string[];
31
+ /** Gate expectations produced by this action's explicit operation(s). */
32
+ expectation_ids?: string[];
33
+ /** Durable artifacts produced by an operation-only action. */
34
+ artifacts: string[];
35
+ }
36
+ export type KitSkillRole = "entrypoint" | "profile" | "step" | "shared-primitive" | "extension";
37
+ export interface KitSkillRoleEntry {
38
+ skill_id: string;
39
+ role: KitSkillRole;
40
+ flow_id?: string;
41
+ step_ids: string[];
42
+ artifacts: string[];
43
+ expectation_ids: string[];
31
44
  }
32
45
  /**
33
46
  * Parse and shape-validate a kit manifest's `dependencies` field (Flow Agents
@@ -60,6 +73,10 @@ export declare function parseKitFlowStepActions(manifest: Record<string, unknown
60
73
  entries: KitFlowStepActionEntry[];
61
74
  errors: string[];
62
75
  };
76
+ export declare function parseKitSkillRoles(manifest: Record<string, unknown>, manifestPath: string): {
77
+ entries: KitSkillRoleEntry[];
78
+ errors: string[];
79
+ };
63
80
  export type KitTargetConsumer = "flow" | "flow-agents" | string;
64
81
  export interface KitConformanceLevel {
65
82
  /** K0: valid core Flow Kit container with at least one flow (gates evaluable agentlessly). */