akm-cli 0.9.0-rc.13 → 0.9.0-rc.15

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 (111) hide show
  1. package/CHANGELOG.md +162 -23
  2. package/dist/akm-migrate +3 -1
  3. package/dist/assets/hints/cli-hints-full.md +3 -4
  4. package/dist/assets/hints/cli-hints-short.md +5 -5
  5. package/dist/assets/workflows/workflow-template.md +4 -3
  6. package/dist/cli/invocation.js +3 -2
  7. package/dist/cli/retired-commands.js +5 -0
  8. package/dist/cli/unknown-flags.js +226 -0
  9. package/dist/cli.js +19 -35
  10. package/dist/commands/agent/agent-dispatch.js +7 -3
  11. package/dist/commands/agent/contribute-cli.js +15 -3
  12. package/dist/commands/feedback-cli.js +6 -3
  13. package/dist/commands/health/checks.js +6 -3
  14. package/dist/commands/improve/collapse-detector.js +2 -3
  15. package/dist/commands/improve/reflect.js +5 -3
  16. package/dist/commands/lint/base-linter.js +4 -16
  17. package/dist/commands/lint/index.js +13 -13
  18. package/dist/commands/log.js +6 -1
  19. package/dist/commands/migration-tool.js +4 -5
  20. package/dist/commands/observability-cli.js +1 -1
  21. package/dist/commands/proposal/propose.js +5 -3
  22. package/dist/commands/proposal/repository.js +5 -5
  23. package/dist/commands/read/knowledge.js +2 -0
  24. package/dist/commands/registry-cli.js +5 -3
  25. package/dist/commands/sources/add-cli.js +6 -6
  26. package/dist/commands/sources/init.js +1 -1
  27. package/dist/commands/sources/self-update.js +30 -7
  28. package/dist/commands/sources/source-add.js +17 -2
  29. package/dist/commands/tasks/tasks.js +10 -10
  30. package/dist/commands/workflow-cli.js +133 -259
  31. package/dist/core/adapter/adapters/akm-lint.js +17 -13
  32. package/dist/core/adapter/adapters/akm-task-adapter.js +14 -11
  33. package/dist/core/asset/akm-markdown.js +41 -8
  34. package/dist/core/asset/frontmatter.js +22 -0
  35. package/dist/core/asset/resolve-ref.js +23 -3
  36. package/dist/core/common.js +45 -2
  37. package/dist/core/config/config-schema.js +8 -0
  38. package/dist/core/config/schema/experimental.js +0 -17
  39. package/dist/core/config/schema/sources-bundles.js +11 -0
  40. package/dist/core/config/schema/workflow.js +3 -3
  41. package/dist/core/errors.js +5 -1
  42. package/dist/core/logs-db.js +2 -1
  43. package/dist/core/parse.js +4 -1
  44. package/dist/core/state/migrations.js +11 -14
  45. package/dist/core/state-db.js +4 -6
  46. package/dist/core/subprocess.js +6 -4
  47. package/dist/core/type-presentation.js +1 -1
  48. package/dist/indexer/indexer.js +16 -1
  49. package/dist/indexer/search/search-source.js +1 -1
  50. package/dist/indexer/walk/matchers.js +3 -1
  51. package/dist/integrations/agent/config.js +2 -2
  52. package/dist/integrations/agent/detect.js +49 -19
  53. package/dist/integrations/agent/engine-fallback.js +76 -0
  54. package/dist/integrations/agent/profiles.js +14 -0
  55. package/dist/integrations/agent/spawn.js +1 -2
  56. package/dist/integrations/harnesses/opencode-sdk/sdk-runner.js +13 -4
  57. package/dist/integrations/lockfile.js +11 -56
  58. package/dist/output/shapes/passthrough.js +0 -6
  59. package/dist/output/text/command-format.js +3 -3
  60. package/dist/output/text/helpers.js +1 -1
  61. package/dist/output/text/show-directives.js +4 -6
  62. package/dist/output/text/workflow-format.js +15 -181
  63. package/dist/output/text/workflow.js +1 -6
  64. package/dist/scripts/akm-migrate-node.js +58666 -0
  65. package/dist/scripts/akm-migrate.js +33976 -11498
  66. package/dist/setup/detect.js +42 -15
  67. package/dist/setup/setup.js +1 -1
  68. package/dist/sources/providers/git-stash.js +4 -2
  69. package/dist/sources/providers/website.js +5 -0
  70. package/dist/sources/snapshot-fetchers/bluesky.js +146 -0
  71. package/dist/sources/snapshot-fetchers/content-extract.js +370 -0
  72. package/dist/sources/snapshot-fetchers/fetcher-util.js +40 -0
  73. package/dist/sources/snapshot-fetchers/host-guard.js +199 -0
  74. package/dist/sources/snapshot-fetchers/registry.js +10 -1
  75. package/dist/sources/snapshot-fetchers/robots.js +348 -0
  76. package/dist/sources/snapshot-fetchers/rss.js +279 -0
  77. package/dist/sources/snapshot-fetchers/secret-seam.js +42 -0
  78. package/dist/sources/snapshot-fetchers/website-ingest.js +488 -257
  79. package/dist/sources/snapshot-fetchers/x.js +193 -0
  80. package/dist/storage/engines/sqlite-migrations.js +22 -107
  81. package/dist/storage/repositories/workflow-runs-repository.js +9 -23
  82. package/dist/tasks/runner.js +43 -19
  83. package/dist/tasks/schema.js +24 -1
  84. package/dist/tasks/validator.js +6 -2
  85. package/dist/workflows/exec/frozen-judge.js +28 -2
  86. package/dist/workflows/exec/native-executor.js +44 -28
  87. package/dist/workflows/exec/param-secrets.js +9 -9
  88. package/dist/workflows/exec/run-workflow.js +122 -60
  89. package/dist/workflows/exec/step-work.js +64 -175
  90. package/dist/workflows/exec/unit-dispatch.js +4 -0
  91. package/dist/workflows/ir/compile.js +2 -2
  92. package/dist/workflows/ir/freeze.js +29 -9
  93. package/dist/workflows/ir/params.js +135 -11
  94. package/dist/workflows/ir/plan-hash.js +1 -1
  95. package/dist/workflows/ir/schema.js +6 -2
  96. package/dist/workflows/renderer.js +2 -2
  97. package/dist/workflows/runtime/checkin.js +3 -3
  98. package/dist/workflows/runtime/runs.js +72 -92
  99. package/dist/workflows/runtime/unit-checkin.js +1 -1
  100. package/dist/workflows/runtime/unit-phases.js +2 -2
  101. package/dist/workflows/validate-summary.js +30 -14
  102. package/docs/migration/release-notes/0.9.0.md +31 -4
  103. package/docs/migration/v0.8-to-v0.9.md +70 -100
  104. package/docs/reference/data-and-telemetry.md +5 -5
  105. package/package.json +7 -3
  106. package/schemas/akm-config.json +24 -6
  107. package/schemas/akm-workflow.json +1 -1
  108. package/dist/workflows/cli.js +0 -33
  109. package/dist/workflows/exec/brief.js +0 -450
  110. package/dist/workflows/exec/report.js +0 -1460
  111. package/dist/workflows/exec/workflow-engine-gate.js +0 -67
@@ -2,23 +2,147 @@
2
2
  // License, v. 2.0. If a copy of the MPL was not distributed with this
3
3
  // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
4
  /**
5
- * Run-parameter validation against the frozen plan's param schemas (reviewer
6
- * #12). A program can declare `params.files: { type: array }`; supplying
7
- * `--params '{"files":"not-an-array"}'` must be rejected at start rather than
8
- * silently flowing into a unit prompt. The schemas are frozen into the plan
9
- * ({@link WorkflowPlanGraph.paramSchemas}, program path only) so validation is
10
- * a pure function of the frozen plan and the supplied params — no live-asset
11
- * re-read.
5
+ * Run-parameter validation against the frozen plan's param schemas. A workflow
6
+ * can declare `params.files: { type: array }`; supplying a non-array through
7
+ * the exact-name `--files` flag must be rejected at start rather than silently
8
+ * flowing into a unit prompt. The schemas are frozen into the plan, so
9
+ * validation is a pure function of the frozen plan and supplied params.
12
10
  *
13
11
  * Uses the same bounded {@link validateJsonSchemaSubset} the engine applies to
14
- * unit output: undeclared params are permitted (the schema map only constrains
15
- * the params it names), and a workflow with no declared schemas (every Markdown
16
- * workflow, and programs without a `params:` block) validates trivially.
12
+ * unit output. Internal callers may validate partial parameter objects; the CLI
13
+ * separately rejects flags that do not exactly name declared parameters.
17
14
  *
18
15
  * Pure module: no IO, no engine imports.
19
16
  */
20
17
  import { UsageError } from "../../core/errors.js";
21
18
  import { validateJsonSchemaSubset } from "../../core/json-schema.js";
19
+ import { PROGRAM_PARAM_NAME_PATTERN } from "../program/schema.js";
20
+ /**
21
+ * Materialize exact-name CLI parameter flags against the plan being frozen for
22
+ * the run. The CLI deliberately carries raw values to this boundary so type
23
+ * coercion cannot race or drift from the persisted plan's schemas.
24
+ */
25
+ export function materializeWorkflowParameterFlags(plan, flags) {
26
+ if (flags.length === 0)
27
+ return {};
28
+ const declared = new Set(plan.params ?? Object.keys(plan.paramSchemas ?? {}));
29
+ const grouped = new Map();
30
+ for (const flag of flags) {
31
+ if (!PROGRAM_PARAM_NAME_PATTERN.test(flag.name) || !declared.has(flag.name)) {
32
+ const available = [...declared]
33
+ .sort()
34
+ .map((name) => `--${name}`)
35
+ .join(", ");
36
+ throw new UsageError(`Unknown workflow parameter "--${flag.name}". Parameter flags must exactly match a declared workflow parameter.`, "UNKNOWN_FLAG", available ? `Declared parameters: ${available}.` : "This workflow declares no parameters.");
37
+ }
38
+ const values = grouped.get(flag.name) ?? [];
39
+ values.push(flag.value);
40
+ grouped.set(flag.name, values);
41
+ }
42
+ const entries = [];
43
+ for (const [name, values] of grouped) {
44
+ const schema = plan.paramSchemas?.[name];
45
+ entries.push([name, materializeFlagValues(name, values, schema)]);
46
+ }
47
+ const params = Object.fromEntries(entries);
48
+ const errors = validateWorkflowParams(plan, params);
49
+ if (errors.length > 0) {
50
+ throw new UsageError(`Workflow parameter flags do not satisfy the workflow's declared schemas:\n${errors.map((error) => ` - ${error}`).join("\n")}`, "INVALID_FLAG_VALUE");
51
+ }
52
+ return params;
53
+ }
54
+ function materializeFlagValues(name, values, schema) {
55
+ const types = schemaTypes(schema);
56
+ if (types.includes("array")) {
57
+ if (values.length === 1 && typeof values[0] === "string" && values[0].trim().startsWith("[")) {
58
+ const parsed = parseJsonFlag(name, values[0]);
59
+ if (!Array.isArray(parsed))
60
+ throw invalidParameter(name, "must be a JSON array");
61
+ return parsed;
62
+ }
63
+ const itemSchema = isRecord(schema?.items) ? schema.items : undefined;
64
+ return values.map((value) => coerceFlagValue(name, value, itemSchema));
65
+ }
66
+ if (values.length > 1) {
67
+ throw invalidParameter(name, "was provided more than once but is not declared as an array");
68
+ }
69
+ return coerceFlagValue(name, values[0], schema);
70
+ }
71
+ function coerceFlagValue(name, raw, schema) {
72
+ const types = schemaTypes(schema);
73
+ if (types.length === 0)
74
+ return raw;
75
+ if (typeof raw === "boolean") {
76
+ if (types.includes("boolean"))
77
+ return raw;
78
+ if (types.includes("string"))
79
+ return String(raw);
80
+ throw invalidParameter(name, `requires a value of type ${types.join(" | ")}`);
81
+ }
82
+ // A union that permits strings keeps the user's exact text. This prevents a
83
+ // value such as "001" from being silently converted to a number.
84
+ if (types.includes("string"))
85
+ return raw;
86
+ for (const type of types) {
87
+ switch (type) {
88
+ case "boolean":
89
+ if (raw === "true")
90
+ return true;
91
+ if (raw === "false")
92
+ return false;
93
+ break;
94
+ case "number": {
95
+ const value = Number(raw);
96
+ if (raw.trim() !== "" && Number.isFinite(value))
97
+ return value;
98
+ break;
99
+ }
100
+ case "integer": {
101
+ const value = Number(raw);
102
+ if (raw.trim() !== "" && Number.isSafeInteger(value))
103
+ return value;
104
+ break;
105
+ }
106
+ case "null":
107
+ if (raw === "null")
108
+ return null;
109
+ break;
110
+ case "object": {
111
+ const parsed = parseJsonFlag(name, raw);
112
+ if (isRecord(parsed))
113
+ return parsed;
114
+ break;
115
+ }
116
+ case "array": {
117
+ const parsed = parseJsonFlag(name, raw);
118
+ if (Array.isArray(parsed))
119
+ return parsed;
120
+ break;
121
+ }
122
+ }
123
+ }
124
+ throw invalidParameter(name, `must be ${types.join(" | ")}; received ${JSON.stringify(raw)}`);
125
+ }
126
+ function schemaTypes(schema) {
127
+ const declared = schema?.type;
128
+ if (typeof declared === "string")
129
+ return [declared];
130
+ return Array.isArray(declared) ? declared.filter((value) => typeof value === "string") : [];
131
+ }
132
+ function parseJsonFlag(name, raw) {
133
+ try {
134
+ return JSON.parse(raw);
135
+ }
136
+ catch {
137
+ throw invalidParameter(name, "must contain valid JSON");
138
+ }
139
+ }
140
+ function invalidParameter(name, message) {
141
+ return new UsageError(`Workflow parameter "--${name}" ${message}.`, "INVALID_FLAG_VALUE");
142
+ }
143
+ function isRecord(value) {
144
+ return typeof value === "object" && value !== null && !Array.isArray(value);
145
+ }
22
146
  /**
23
147
  * Validate a run's supplied params against the plan's frozen param schemas.
24
148
  * Returns a flat list of human-readable, path-prefixed error strings (empty =
@@ -37,7 +161,7 @@ export function validateWorkflowParams(plan, params) {
37
161
  return validateJsonSchemaSubset(params, { type: "object", properties: schemas }).map((e) => e.replace(/^\$/, "params"));
38
162
  }
39
163
  /**
40
- * Brief/report integrity assert (reviewer #12): the journaled `params_json`
164
+ * Run-integrity assert (reviewer #12): the journaled `params_json`
41
165
  * row must STILL satisfy the frozen param schemas. `startWorkflowRun` already
42
166
  * validated the params it stored, so a violation here means the row was edited
43
167
  * after the run started — loud corruption, exactly like the frozen-plan hash
@@ -4,7 +4,7 @@
4
4
  /**
5
5
  * Plan hashing for the frozen-plan contract (redesign addendum, R1).
6
6
  *
7
- * `workflow start` persists `plan_json` + `plan_hash` on the run row
7
+ * `workflow run` persists `plan_json` + `plan_hash` on the run row
8
8
  * (migration 006); every later invocation executes that snapshot. The hash is
9
9
  * the sha256 (hex) of the plan's CANONICAL JSON — object keys recursively
10
10
  * sorted — so two structurally-equal plans hash identically regardless of key
@@ -110,8 +110,12 @@ export function decodeWorkflowPlanV3(input, hooks = {}) {
110
110
  assertUnitEngineCompatibility(step.root, engines);
111
111
  if (step.gate.judge) {
112
112
  const judge = engines[step.gate.judge.engine];
113
- if (!judge || judge.kind !== "llm")
114
- fail(`gate ${step.gate.id} must reference an LLM engine`);
113
+ if (!judge)
114
+ fail(`gate ${step.gate.id} references an unavailable engine`);
115
+ if (judge.kind === "llm" && step.gate.judge.model === null)
116
+ fail(`LLM gate ${step.gate.id} has no exact model`);
117
+ if (judge.kind === "agent" && step.gate.judge.llm !== undefined)
118
+ fail(`agent gate ${step.gate.id} cannot carry LLM invocation settings`);
115
119
  }
116
120
  }
117
121
  return plan;
@@ -16,7 +16,7 @@ function shellQuote(value) {
16
16
  return `'${value.replace(/'/g, `'\\''`)}'`;
17
17
  }
18
18
  export function buildWorkflowAction(ref) {
19
- return `Resume the active run or start a new run with \`akm workflow next ${shellQuote(ref)}\`.`;
19
+ return `Start or resume execution with \`akm workflow run ${shellQuote(ref)}\`.`;
20
20
  }
21
21
  function deriveName(ctx) {
22
22
  const metaName = ctx.matchResult.meta?.name;
@@ -117,7 +117,7 @@ export const workflowMdRenderer = {
117
117
  buildShowResponse(ctx) {
118
118
  const name = deriveName(ctx);
119
119
  const doc = loadDocument(ctx);
120
- // WI-8.5b (display flip): the `akm workflow next <ref>` action is DISPLAY
120
+ // WI-8.5b (display flip): the `akm workflow run <ref>` action is DISPLAY
121
121
  // output — its spelling follows the D-R5 display rule (`displayRef`). A
122
122
  // primary/default-bundle workflow renders the SHORT conceptId
123
123
  // (`workflows/<name>`); a named source qualifies it as
@@ -9,7 +9,7 @@
9
9
  * reconciles #506 (file/command-loop signal) with #501 (background thread) in
10
10
  * favour of the former. There is intentionally NO timer or resident process
11
11
  * here. Arming a check-in writes a timestamp (`checkin_armed_at`) on the run
12
- * row; the next time the agent polls the engine via `workflow next`/`status`,
12
+ * row; the next time the agent polls the engine via `workflow run`/`status`,
13
13
  * {@link evaluateCheckin} is called to decide — purely from timestamps — whether
14
14
  * the run looks stalled and a strong `continue` directive should be surfaced
15
15
  * through the normal command output.
@@ -48,8 +48,8 @@ export function evaluateCheckin(run, now = Date.now(), stallMs = CHECKIN_STALL_M
48
48
  return {
49
49
  signal: "continue",
50
50
  directive: "CONTINUE: this workflow run has stalled with no progress. Resume immediately — " +
51
- "re-read the current step's instructions, finish the outstanding work, then call " +
52
- "`akm workflow complete` with a summary. Do not stop until the step is complete.",
51
+ "inspect its status, then call `akm workflow run` with the run id to finish the outstanding work. " +
52
+ "Do not stop until the run reaches a terminal state or reports a verification rejection.",
53
53
  idleMs,
54
54
  agentHarness: run.agentHarness ?? null,
55
55
  agentSessionId: run.agentSessionId ?? null,
@@ -4,7 +4,7 @@
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { parseBundleRef } from "../../core/asset/asset-ref.js";
6
6
  import { loadConfig } from "../../core/config/config.js";
7
- import { NotFoundError, UsageError } from "../../core/errors.js";
7
+ import { ConfigError, NotFoundError, UsageError } from "../../core/errors.js";
8
8
  import { appendEvent } from "../../core/events.js";
9
9
  import { warn } from "../../core/warn.js";
10
10
  import { insertEventOnce } from "../../storage/repositories/events-repository.js";
@@ -14,7 +14,7 @@ import { frozenSummaryJudge } from "../exec/frozen-judge.js";
14
14
  import { detectSecretShapedParams } from "../exec/param-secrets.js";
15
15
  import { collectWorkflowWarnings } from "../ir/compile.js";
16
16
  import { compileResolveFreezeWorkflow } from "../ir/freeze.js";
17
- import { validateWorkflowParams } from "../ir/params.js";
17
+ import { materializeWorkflowParameterFlags, validateWorkflowParams } from "../ir/params.js";
18
18
  import { canonicalPlanJson, computePlanHash } from "../ir/plan-hash.js";
19
19
  import { decodeWorkflowPlanV3, WORKFLOW_IR_VERSION } from "../ir/schema.js";
20
20
  import { validateStepSummary } from "../validate-summary.js";
@@ -70,21 +70,28 @@ export async function startWorkflowRun(ref, params = {}, options) {
70
70
  // persist it on the run row in the same transaction as the insert. Every
71
71
  // later invocation executes this snapshot — the asset file is never re-read
72
72
  // for an in-flight run; re-planning is an explicit new run.
73
- const plan = decodeWorkflowPlanV3(compileResolveFreezeWorkflow(asset, loadConfig()).plan);
73
+ const frozen = compileResolveFreezeWorkflow(asset, loadConfig());
74
+ const plan = decodeWorkflowPlanV3(frozen.plan);
75
+ if (options?.parameterFlags?.length && Object.keys(params).length > 0) {
76
+ throw new UsageError("Workflow parameters must use either an object or per-parameter flags, not both.");
77
+ }
78
+ const effectiveParams = options?.parameterFlags?.length
79
+ ? materializeWorkflowParameterFlags(plan, options.parameterFlags)
80
+ : params;
74
81
  // Non-fatal WARNINGS: untyped-step and undeclared-param advisories surface
75
82
  // as `warn()` lines at start (stderr, consistent with the repo's other
76
83
  // author-facing warnings) without blocking the run.
77
84
  for (const w of collectWorkflowWarnings(asset.document)) {
78
- warn(`workflow start: ${asset.path}:${w.line} — ${w.message}`);
85
+ warn(`workflow run: ${asset.path}:${w.line} — ${w.message}`);
79
86
  }
80
- // Reviewer #12: validate supplied `--params` against the frozen param
87
+ // Reviewer #12: validate supplied parameters against the frozen param
81
88
  // schemas BEFORE creating the run, so a type-mismatched param (e.g. a string
82
89
  // for a `{ type: array }` param) is rejected with actionable errors instead
83
90
  // of flowing silently into a unit prompt. Programs without declared param
84
91
  // schemas (and every Markdown workflow) validate trivially.
85
- const paramErrors = validateWorkflowParams(plan, params);
92
+ const paramErrors = validateWorkflowParams(plan, effectiveParams);
86
93
  if (paramErrors.length > 0) {
87
- throw new UsageError(`Cannot start ${asset.ref}: the supplied --params do not satisfy the workflow's declared parameter schemas:\n` +
94
+ throw new UsageError(`Cannot start ${asset.ref}: the supplied parameters do not satisfy the workflow's declared schemas:\n` +
88
95
  paramErrors.map((e) => ` - ${e}`).join("\n"), "INVALID_JSON_ARGUMENT");
89
96
  }
90
97
  const planJson = canonicalPlanJson(plan);
@@ -105,8 +112,8 @@ export async function startWorkflowRun(ref, params = {}, options) {
105
112
  // Concurrency guard (#485): if an active run already exists in this
106
113
  // (workflow_ref, scope_key) pair, refuse to create a parallel run unless
107
114
  // `force: true` is set. Previously every call inserted unconditionally,
108
- // so two terminals running `akm workflow start <ref>` left two runs
109
- // racing; `akm workflow next` then non-deterministically picked one. The
115
+ // so two terminals starting the same workflow could leave two runs racing.
116
+ // The
110
117
  // active-alias query and all inserts now share this immediate transaction.
111
118
  // #506: arm a file-signal check-in (a timestamp, NOT a background thread —
112
119
  // per the workflow-agent check-in ADR) so a stalled run can be
@@ -117,7 +124,7 @@ export async function startWorkflowRun(ref, params = {}, options) {
117
124
  const existing = repo.findActiveRunForScope(workflowRefs, scopeKey);
118
125
  if (existing) {
119
126
  throw new UsageError(`Workflow ${asset.ref} already has an active run in this scope (id=${existing.id}, step=${existing.current_step_id ?? "—"}). ` +
120
- `Use 'akm workflow next ${asset.ref}' to resume it, 'akm workflow abandon ${existing.id}' to give up on it, or pass --force to start a parallel run.`, "RESOURCE_ALREADY_EXISTS");
127
+ `Use 'akm workflow run ${asset.ref}' to resume it or 'akm workflow abandon ${existing.id}' to give up on it.`, "RESOURCE_ALREADY_EXISTS");
121
128
  }
122
129
  }
123
130
  repo.insertRun({
@@ -126,7 +133,7 @@ export async function startWorkflowRun(ref, params = {}, options) {
126
133
  scopeKey,
127
134
  workflowEntryId,
128
135
  workflowTitle: asset.title,
129
- paramsJson: JSON.stringify(params),
136
+ paramsJson: JSON.stringify(effectiveParams),
130
137
  currentStepId,
131
138
  createdAt: now,
132
139
  updatedAt: now,
@@ -148,12 +155,17 @@ export async function startWorkflowRun(ref, params = {}, options) {
148
155
  const result = await getWorkflowStatus(runId);
149
156
  // #13: params are declared non-secret (they are copied verbatim into every
150
157
  // unit prompt and hashed into the unit identity, so they cannot be redacted
151
- // without breaking the driver protocol). Surface a loud, best-effort warning
158
+ // without breaking replay determinism). Surface a loud, best-effort warning
152
159
  // when a param LOOKS like a credential so the author moves it to an env
153
160
  // binding. Advisory only — never blocks the start.
154
- const secretWarnings = detectSecretShapedParams(params);
161
+ const secretWarnings = detectSecretShapedParams(effectiveParams);
155
162
  if (secretWarnings.length > 0)
156
163
  result.warnings = [...(result.warnings ?? []), ...secretWarnings];
164
+ // The implicit engine fallback is announced ONCE, here at run creation —
165
+ // the frozen plan records the engine actually used, so a resume never
166
+ // re-announces a decision it did not make.
167
+ if (frozen.engineAnnouncement)
168
+ result.warnings = [...(result.warnings ?? []), frozen.engineAnnouncement];
157
169
  // 07 P1-B: emit only the run id + status — NOT the raw workflowTitle (which
158
170
  // comes verbatim from the workflow asset's frontmatter and is therefore
159
171
  // attacker-influenceable). Keeping raw titles out of the events stream
@@ -177,9 +189,9 @@ export async function getWorkflowStatus(runId, opts) {
177
189
  // project each row, INCLUDING failures whose diagnostic text the
178
190
  // deterministic evidence graph drops. Read-only; never mutates the run.
179
191
  const rows = repo.getUnitsForRun(run.id);
180
- // Codex round-3 finding B: run the SAME pure stale-claim evaluator `brief`
181
- // uses (`now` injected for deterministic tests) so a dead driver's claimed
182
- // `running` unit surfaces as stale here too, not just as raw `running`.
192
+ // Codex round-3 finding B: run the pure stale-claim evaluator (`now`
193
+ // injected for deterministic tests) so a unit left `running` by a process
194
+ // that died surfaces as stale here, not just as raw `running`.
183
195
  const staleById = new Map(evaluateStaleUnits(rows, opts.now ?? Date.now()).map((u) => [u.unitId, u]));
184
196
  const classified = classifyWorkflowRunPlan(run);
185
197
  const engines = classified.support === "supported" ? classified.plan.execution?.engines : undefined;
@@ -230,18 +242,22 @@ export async function listWorkflowRuns(input) {
230
242
  .map(toWorkflowRunSummary),
231
243
  }));
232
244
  }
233
- export async function getNextWorkflowStep(specifier, params) {
245
+ export async function getNextWorkflowStep(specifier, params, options) {
234
246
  return withWorkflowRunsRepo(async (repo) => {
235
- const { run, autoStarted } = await resolveRunSpecifier(repo, specifier, params);
247
+ const { run, autoStarted, startWarnings } = await resolveRunSpecifier(repo, specifier, params, options?.parameterFlags);
236
248
  const steps = readWorkflowRunSteps(repo, run.id);
237
249
  const plan = requireExecutableWorkflowPlan(run);
238
250
  assertWorkflowSpineMatchesPlan(plan, run, steps);
239
- return { ...projectNextResult(run, steps), ...(autoStarted ? { autoStarted: true } : {}) };
251
+ return {
252
+ ...projectNextResult(run, steps),
253
+ ...(autoStarted ? { autoStarted: true } : {}),
254
+ ...(startWarnings?.length ? { startWarnings } : {}),
255
+ };
240
256
  });
241
257
  }
242
258
  /**
243
259
  * Project a run row + its step rows into a {@link WorkflowNextResult}. The pure
244
- * read-shaping half of {@link getNextWorkflowStep}, extracted so the driver
260
+ * read-shaping half of {@link getNextWorkflowStep}, extracted so the run
245
261
  * snapshot below reproduces the exact same projection without re-running the
246
262
  * auto-start-capable {@link resolveRunSpecifier}.
247
263
  */
@@ -269,27 +285,6 @@ function projectNextResult(run, steps) {
269
285
  ...(checkin ? { checkin } : {}),
270
286
  };
271
287
  }
272
- /**
273
- * A consistent point-in-time snapshot of a run for the harness-neutral driver
274
- * protocol (PR #714 review round 2, #14). `brief`/`report` previously read the
275
- * spine (`getNextWorkflowStep`) and then, in a SEPARATE connection, the run row
276
- * + unit journal — so a concurrent `report`/`run`/manual completion could change
277
- * the active step BETWEEN the two reads, leaving the described work-list
278
- * inconsistent with the run row it was stamped against. This reads the run row,
279
- * its steps, AND its unit rows inside ONE transaction (one connection, one
280
- * snapshot) so all three agree. It never auto-starts — `runId` must already
281
- * resolve to a concrete run — because the driver protocol never mutates on read.
282
- */
283
- export async function snapshotRunForDriver(runId) {
284
- return withWorkflowRunsRepo((repo) => repo.transaction(() => {
285
- const run = readWorkflowRun(repo, runId);
286
- const steps = readWorkflowRunSteps(repo, run.id);
287
- const plan = requireExecutableWorkflowPlan(run);
288
- assertWorkflowSpineMatchesPlan(plan, run, steps);
289
- const units = repo.getUnitsForRun(run.id);
290
- return { next: projectNextResult(run, steps), run, units };
291
- }));
292
- }
293
288
  export async function resumeWorkflowRun(runId) {
294
289
  return withWorkflowRunsRepo((repo) => {
295
290
  const run = readWorkflowRun(repo, runId);
@@ -387,15 +382,20 @@ export async function completeWorkflowStep(input) {
387
382
  if (input.status === "completed" && !summary) {
388
383
  throw new UsageError(`Completing step "${input.stepId}" requires a --summary describing the work done.`, "MISSING_REQUIRED_ARGUMENT");
389
384
  }
390
- // #506: validation gate — judge the summary against the step's
391
- // completionCriteria via the configured LLM. Fail-open when no criteria or no
392
- // judge. Only a well-formed `complete: false` blocks completion.
385
+ // #506: validation gate — a criteria-bearing step must have a frozen judge
386
+ // and receive an affirmative verdict before it can advance.
393
387
  if (input.status === "completed" && summary) {
394
388
  const criteria = preflight.stepPlan.gate.criteria;
389
+ if (input.signal?.aborted)
390
+ throw interruptionReason(input.signal);
395
391
  const judge = input.summaryJudge === undefined
396
- ? frozenSummaryJudge(preflight.plan, preflight.stepPlan.gate.judge)
392
+ ? frozenSummaryJudge(preflight.plan, preflight.stepPlan.gate.judge, input.signal)
397
393
  : input.summaryJudge;
398
- const verdict = await validateStepSummary({ stepTitle: preflight.stepPlan.title, completionCriteria: criteria, summary }, judge ?? undefined);
394
+ if (criteria.length > 0 && !judge) {
395
+ throw new ConfigError(`Workflow run ${input.runId} has completion criteria for step "${input.stepId}" but its frozen plan has no judge. ` +
396
+ "Set workflow.judgeEngine, abandon this run, and create a new one with `akm workflow run <ref>`.", "INVALID_CONFIG_FILE");
397
+ }
398
+ const verdict = await validateStepSummary({ stepTitle: preflight.stepPlan.title, completionCriteria: criteria, summary }, judge ?? undefined, input.signal);
399
399
  if (!verdict.complete) {
400
400
  // Re-arm the check-in so a subsequent stall is still nudged, but leave the
401
401
  // step pending and return corrective feedback instead of completing.
@@ -411,6 +411,8 @@ export async function completeWorkflowStep(input) {
411
411
  };
412
412
  }
413
413
  }
414
+ if (input.signal?.aborted)
415
+ throw interruptionReason(input.signal);
414
416
  return withWorkflowRunsRepo((repo) => {
415
417
  let updatedRun;
416
418
  let refreshedSteps = [];
@@ -436,6 +438,8 @@ export async function completeWorkflowStep(input) {
436
438
  if (run.current_step_id !== existing.step_id) {
437
439
  throw new UsageError(`Step "${input.stepId}" is not the current step for workflow run ${run.id}. Complete "${run.current_step_id}" first.`);
438
440
  }
441
+ if (input.signal?.aborted)
442
+ throw interruptionReason(input.signal);
439
443
  const completedAt = new Date().toISOString();
440
444
  repo.updateStepCompletion({
441
445
  status: input.status,
@@ -485,11 +489,12 @@ export async function completeWorkflowStep(input) {
485
489
  return detail;
486
490
  });
487
491
  }
488
- async function resolveRunSpecifier(repo, specifier, params) {
492
+ async function resolveRunSpecifier(repo, specifier, params, parameterFlags) {
493
+ const hasParameters = (params && Object.keys(params).length > 0) || (parameterFlags?.length ?? 0) > 0;
489
494
  const explicitRun = repo.getRunById(specifier);
490
495
  if (explicitRun) {
491
- if (params && Object.keys(params).length > 0) {
492
- throw new UsageError(`--params can only be used when starting a new run from a workflow ref, not with an existing run id ("${specifier}")`);
496
+ if (hasParameters) {
497
+ throw new UsageError(`Workflow parameter flags can only be used when starting a new run, not with existing run id "${specifier}".`);
493
498
  }
494
499
  return { run: explicitRun, autoStarted: false };
495
500
  }
@@ -504,8 +509,8 @@ async function resolveRunSpecifier(repo, specifier, params) {
504
509
  }
505
510
  catch (error) {
506
511
  if (detached) {
507
- if (params && Object.keys(params).length > 0) {
508
- throw new UsageError(`--params can only be set on a new run; ${specifier} already has an active run`);
512
+ if (hasParameters) {
513
+ throw new UsageError(`Workflow parameter flags can only be set on a new run; ${specifier} is already active.`);
509
514
  }
510
515
  return { run: detached, autoStarted: false };
511
516
  }
@@ -516,13 +521,22 @@ async function resolveRunSpecifier(repo, specifier, params) {
516
521
  }
517
522
  const active = repo.getActiveRunRowForScope(await workflowRunRefSet(ref, exactRef), scopeKey);
518
523
  if (active) {
519
- if (params && Object.keys(params).length > 0) {
520
- throw new UsageError(`--params can only be set on a new run; ${ref} already has an active run`);
524
+ if (hasParameters) {
525
+ throw new UsageError(`Workflow parameter flags can only be set on a new run; ${ref} is already active.`);
521
526
  }
522
527
  return { run: active, autoStarted: false };
523
528
  }
524
- const started = await startWorkflowRun(ref, params ?? {});
525
- return { run: readWorkflowRun(repo, started.run.id), autoStarted: true };
529
+ const started = await startWorkflowRun(ref, params ?? {}, {
530
+ ...(parameterFlags !== undefined ? { parameterFlags } : {}),
531
+ });
532
+ return {
533
+ run: readWorkflowRun(repo, started.run.id),
534
+ autoStarted: true,
535
+ ...(started.warnings?.length ? { startWarnings: started.warnings } : {}),
536
+ };
537
+ }
538
+ function interruptionReason(signal) {
539
+ return signal.reason instanceof Error ? signal.reason : new Error("Workflow run interrupted.");
526
540
  }
527
541
  async function canonicalizeWorkflowSpecifier(specifier) {
528
542
  return canonicalizeWorkflowRefInput(specifier);
@@ -546,40 +560,6 @@ async function workflowRunRefSet(canonicalRef, exactRef) {
546
560
  }
547
561
  return [...refs];
548
562
  }
549
- /** Resolve an existing active run without auto-starting or rebinding a detached short ref. */
550
- export async function resolveExistingWorkflowRunId(target) {
551
- return withWorkflowRunsRepo(async (repo) => {
552
- const byId = repo.getRunById(target);
553
- if (byId)
554
- return byId.id;
555
- const scopeKey = getCurrentWorkflowScopeKey();
556
- const exactRef = target.trim();
557
- if (!exactRef.includes(":") && !exactRef.includes("/")) {
558
- throw new NotFoundError(`Workflow run or workflow "${target}" not found.`, "WORKFLOW_NOT_FOUND");
559
- }
560
- const parsedExact = parseBundleRef(exactRef);
561
- const detached = parsedExact.bundle && parsedExact.fragment === undefined
562
- ? repo.getActiveRunRowForScope(exactRef, scopeKey)
563
- : undefined;
564
- let canonicalRef;
565
- try {
566
- canonicalRef = await canonicalizeWorkflowSpecifier(exactRef);
567
- }
568
- catch (error) {
569
- if (detached)
570
- return detached.id;
571
- if (error instanceof NotFoundError) {
572
- throw new NotFoundError(`Workflow run or workflow "${target}" not found.`, "WORKFLOW_NOT_FOUND");
573
- }
574
- throw error;
575
- }
576
- const active = repo.getActiveRunRowForScope(await workflowRunRefSet(canonicalRef, exactRef), scopeKey);
577
- if (!active) {
578
- throw new NotFoundError(`No active workflow run for ${canonicalRef} in this scope.`, "WORKFLOW_NOT_FOUND");
579
- }
580
- return active.id;
581
- });
582
- }
583
563
  function readWorkflowRun(repo, runId) {
584
564
  const run = repo.getRunById(runId);
585
565
  if (!run) {
@@ -592,7 +572,7 @@ function readWorkflowRunSteps(repo, runId) {
592
572
  }
593
573
  function buildWorkflowRunDetail(run, steps) {
594
574
  // Review M1: `workflow status` (and every other detail-shaped response) now
595
- // evaluates the check-in, not just `workflow next`. Pure timestamp check —
575
+ // evaluates the check-in, not just `workflow run`. Pure timestamp check —
596
576
  // no background thread (see checkin.ts).
597
577
  const checkin = evaluateCheckin({
598
578
  status: run.status,
@@ -630,7 +610,7 @@ function toWorkflowRunSummary(run) {
630
610
  planIrVersion: plan.irVersion,
631
611
  executionSupport: plan.support,
632
612
  // Surface the engine lease (holder id + expiry — never workflow-authored
633
- // content) so `workflow next`/`status` show who is driving the run.
613
+ // content) so `workflow run`/`status` show who is driving the run.
634
614
  ...(run.engine_lease_holder && run.engine_lease_until
635
615
  ? { engineLease: { holder: run.engine_lease_holder, until: run.engine_lease_until } }
636
616
  : {}),
@@ -639,7 +619,7 @@ function toWorkflowRunSummary(run) {
639
619
  /**
640
620
  * Single-driver enforcement (R2 run lease): while a LIVE (unexpired) engine
641
621
  * lease is held, only the holding engine may advance the gate spine. Manual
642
- * `akm workflow complete` (no `leaseHolder`) — or a stale engine invocation
622
+ * A call with no `leaseHolder` — or a stale engine invocation
643
623
  * whose lease was claimed by another — is refused with the holder + expiry.
644
624
  * An EXPIRED lease never blocks: the engine that held it is presumed dead.
645
625
  */
@@ -18,7 +18,7 @@ function parseIso(value) {
18
18
  * Pure stale-unit evaluator. Returns every `running` DISPATCH unit whose last
19
19
  * heartbeat (`last_checkin_at`, else the first-claim `started_at`) is older than
20
20
  * `staleMs`. Gate-evaluation rows (`phase = "gate"`) are excluded — they are
21
- * synchronous engine judge calls, never driver-claimed work. A running row with
21
+ * synchronous engine judge calls, never separately claimed work. A running row with
22
22
  * no usable timestamp at all is treated as stale (a claim we can no longer age).
23
23
  * Deterministic in `now` — free of timer flakiness.
24
24
  */
@@ -3,8 +3,8 @@
3
3
  // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
4
  /**
5
5
  * Unit-row phase markers — a leaf module (imports nothing) so both the exec
6
- * drivers (step-work, brief, run-workflow) and the runtime (unit-checkin) can
7
- * key on the phase discriminator without an exec ↔ runtime import cycle.
6
+ * modules (step-work, run-workflow) and the runtime (unit-checkin) can key on
7
+ * the phase discriminator without an exec ↔ runtime import cycle.
8
8
  * Extracting {@link GATE_EVALUATION_PHASE} here broke the last workflows-
9
9
  * runtime knot (step-work → runs → unit-checkin → step-work; chunk-8 WI-8.6,
10
10
  * DoD 11).