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
@@ -0,0 +1,193 @@
1
+ // This Source Code Form is subject to the terms of the Mozilla Public
2
+ // License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
+ import { warn } from "../../core/warn.js";
5
+ import { avoidReservedBasename, coerceString, escapeMarkdownStructure } from "./fetcher-util.js";
6
+ import { fetchPinnedJson } from "./host-guard.js";
7
+ import rssFetcher from "./rss.js";
8
+ /**
9
+ * X / Twitter profile fetcher.
10
+ *
11
+ * Strategy chain, in order:
12
+ * 1. X API v2, when a bearer token is available.
13
+ * 2. An RSS template (e.g. a self-hosted Nitter instance), delegating to the
14
+ * RSS fetcher.
15
+ * 3. Return `null` with a single warning naming both options.
16
+ *
17
+ * Step 3 is deliberately not an error: `matches` fires on any x.com profile
18
+ * URL, and a hard failure there would break the generic website-crawl
19
+ * fall-through for users who never asked for X ingestion.
20
+ *
21
+ * The bearer token is read but never rendered — it appears in no snapshot,
22
+ * no frontmatter, and no log line, including on the failure paths.
23
+ */
24
+ const X_HOSTS = new Set(["x.com", "www.x.com", "twitter.com", "www.twitter.com"]);
25
+ const X_API_BASE = "https://api.x.com/2";
26
+ const DEFAULT_TWEET_LIMIT = 50;
27
+ /** Bound the JSON read: fetch timeouts cover only the header phase. */
28
+ const X_BYTE_CAP = 4 * 1024 * 1024;
29
+ const X_BODY_TIMEOUT_MS = 30_000;
30
+ /** Reserved x.com paths that are not user profiles. */
31
+ const RESERVED_X_PATHS = new Set([
32
+ "home",
33
+ "explore",
34
+ "notifications",
35
+ "messages",
36
+ "search",
37
+ "settings",
38
+ "i",
39
+ "intent",
40
+ "share",
41
+ "compose",
42
+ "login",
43
+ "signup",
44
+ "about",
45
+ "tos",
46
+ "privacy",
47
+ ]);
48
+ export function extractXUsername(url) {
49
+ if (!X_HOSTS.has(url.hostname.toLowerCase()))
50
+ return null;
51
+ const segments = url.pathname.split("/").filter(Boolean);
52
+ if (segments.length !== 1)
53
+ return null;
54
+ const username = segments[0]?.trim().replace(/^@/, "");
55
+ if (!username || !/^[A-Za-z0-9_]{1,15}$/.test(username))
56
+ return null;
57
+ if (RESERVED_X_PATHS.has(username.toLowerCase()))
58
+ return null;
59
+ return username;
60
+ }
61
+ /** Secret ref consulted when `X_BEARER_TOKEN` is not in the environment. */
62
+ export const X_BEARER_TOKEN_SECRET_REF = "secrets/x-bearer-token";
63
+ /**
64
+ * Resolve the bearer token: `X_BEARER_TOKEN` first, then akm's secret store
65
+ * via the injected {@link FetcherContext.resolveSecret} seam.
66
+ *
67
+ * The seam is injected rather than imported because `core/env-secret-ref`
68
+ * transitively imports the source providers, which import this fetcher's own
69
+ * registry — reading the store directly here would form an import cycle (and
70
+ * laundering it through a dynamic `import()` is rejected by the repo's
71
+ * import-cycle ratchet, correctly).
72
+ *
73
+ * Returns the token or null; never logs the value. A throwing resolver is
74
+ * swallowed — a broken secret store means "no token", not a crash.
75
+ */
76
+ export function resolveXBearerToken(context) {
77
+ const fromEnv = process.env.X_BEARER_TOKEN?.trim();
78
+ if (fromEnv)
79
+ return fromEnv;
80
+ try {
81
+ return context?.resolveSecret?.(X_BEARER_TOKEN_SECRET_REF)?.trim() || null;
82
+ }
83
+ catch {
84
+ return null;
85
+ }
86
+ }
87
+ async function xApiJson(url, token, context) {
88
+ return (await fetchPinnedJson(url, {
89
+ headers: {
90
+ Accept: "application/json",
91
+ Authorization: `Bearer ${token}`,
92
+ "User-Agent": "akm-cli x fetcher",
93
+ },
94
+ byteCap: X_BYTE_CAP,
95
+ bodyTimeoutMs: X_BODY_TIMEOUT_MS,
96
+ timeoutMs: context.timeoutMs,
97
+ signal: context.signal,
98
+ }));
99
+ }
100
+ async function fetchViaApi(username, token, context) {
101
+ const lookup = await xApiJson(`${X_API_BASE}/users/by/username/${encodeURIComponent(username)}`, token, context);
102
+ const userId = coerceString(lookup?.data?.id);
103
+ if (!userId)
104
+ return null;
105
+ const timeline = await xApiJson(`${X_API_BASE}/users/${encodeURIComponent(userId)}/tweets` +
106
+ `?max_results=${DEFAULT_TWEET_LIMIT}&tweet.fields=created_at`, token, context);
107
+ const data = timeline?.data;
108
+ if (!Array.isArray(data))
109
+ return null;
110
+ return data.map((raw) => {
111
+ const tweet = (raw ?? {});
112
+ return { id: coerceString(tweet.id), text: coerceString(tweet.text), createdAt: coerceString(tweet.created_at) };
113
+ });
114
+ }
115
+ function renderMarkdown(username, tweets) {
116
+ const sections = [];
117
+ for (const tweet of tweets) {
118
+ if (!tweet.text)
119
+ continue;
120
+ const when = tweet.createdAt ? new Date(tweet.createdAt) : null;
121
+ const iso = when && !Number.isNaN(when.getTime()) ? when.toISOString() : "";
122
+ sections.push(`## ${iso || "(undated)"}`, "", escapeMarkdownStructure(tweet.text), "");
123
+ if (tweet.id)
124
+ sections.push(`https://x.com/${username}/status/${tweet.id}`, "");
125
+ }
126
+ return sections.join("\n").trimEnd();
127
+ }
128
+ /**
129
+ * Build the RSS fallback URL from a template containing `{username}`.
130
+ * Returns null when the template is absent or does not produce a valid URL.
131
+ */
132
+ export function buildXRssUrl(template, username) {
133
+ const raw = template?.trim();
134
+ if (!raw)
135
+ return null;
136
+ // Without the placeholder every profile would import the same fixed feed and
137
+ // then be relabelled as the requested user — silent provenance corruption.
138
+ if (!raw.includes("{username}")) {
139
+ warn('[akm] x-profile: X_RSS_TEMPLATE must contain the "{username}" placeholder; ignoring it.');
140
+ return null;
141
+ }
142
+ try {
143
+ const url = new URL(raw.replaceAll("{username}", encodeURIComponent(username)));
144
+ if (url.protocol !== "http:" && url.protocol !== "https:")
145
+ return null;
146
+ return url;
147
+ }
148
+ catch {
149
+ return null;
150
+ }
151
+ }
152
+ const xFetcher = {
153
+ name: "x-profile",
154
+ matches(url) {
155
+ return extractXUsername(url) !== null;
156
+ },
157
+ async fetch(url, context) {
158
+ const username = extractXUsername(url);
159
+ if (!username)
160
+ return null;
161
+ const token = resolveXBearerToken(context);
162
+ if (token) {
163
+ const tweets = await fetchViaApi(username, token, context);
164
+ const markdown = tweets ? renderMarkdown(username, tweets) : "";
165
+ if (markdown) {
166
+ return {
167
+ url: `https://x.com/${username}`,
168
+ title: `X — @${username}`,
169
+ markdown,
170
+ preferredName: avoidReservedBasename(`x/${username}`),
171
+ tags: ["x", "twitter", "social"],
172
+ };
173
+ }
174
+ }
175
+ const rssUrl = buildXRssUrl(process.env.X_RSS_TEMPLATE, username);
176
+ if (rssUrl) {
177
+ const snapshot = await rssFetcher.fetch(rssUrl, context);
178
+ if (snapshot) {
179
+ return {
180
+ ...snapshot,
181
+ url: `https://x.com/${username}`,
182
+ title: `X — @${username}`,
183
+ preferredName: avoidReservedBasename(`x/${username}`),
184
+ tags: ["x", "twitter", "social"],
185
+ };
186
+ }
187
+ }
188
+ warn("[akm] x-profile: no content for @%s. Set X_BEARER_TOKEN, or store the token as the " +
189
+ "secrets/x-bearer-token akm secret, or set X_RSS_TEMPLATE to an RSS bridge URL containing {username}.", username);
190
+ return null;
191
+ },
192
+ };
193
+ export default xFetcher;
@@ -1,113 +1,47 @@
1
1
  // This Source Code Form is subject to the terms of the Mozilla Public
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
- /**
5
- * Shared SQLite migration engine.
6
- *
7
- * state.db (`src/core/state-db.ts`) evolves its schema through this idempotent,
8
- * transaction-per-migration runner backed by a `schema_migrations` ledger. The
9
- * migrator's frozen pre-cutover workflow-schema roll
10
- * (`scripts/akm-migrate/migrate/legacy/workflow-migrations-bodies.ts`, driven by
11
- * `scripts/akm-migrate/config-migrate.ts`) reuses the SAME runner.
12
- *
13
- * This module factors that runner out once. Each caller supplies only its own
14
- * `MIGRATIONS` array.
15
- *
16
- * Migration-safety contract:
17
- * - `id` is permanent and must never be reused.
18
- * - `up` must be idempotent (use IF NOT EXISTS, INSERT OR IGNORE, etc.).
19
- * - `up` must not DROP any table that holds durable (non-regenerable) data.
20
- * - `up` must not RENAME or change the type of an existing column.
21
- * - To add a column: use `ALTER TABLE … ADD COLUMN … DEFAULT …`.
22
- * - Applied IDs must be an exact ordered prefix of the registry.
23
- * - Released migration bodies are sealed by SHA-256 in the same ledger.
24
- */
25
- import crypto from "node:crypto";
26
- export function migrationChecksum(migration) {
27
- return crypto.createHash("sha256").update(migration.id).update("\0").update(migration.up).digest("hex");
4
+ export function assertMigrationRegistry(migrations) {
5
+ const seen = new Set();
6
+ for (const migration of migrations) {
7
+ if (seen.has(migration.id))
8
+ throw new Error(`Migration registry contains duplicate ID ${migration.id}.`);
9
+ seen.add(migration.id);
10
+ }
28
11
  }
29
12
  function migrationsTableExists(db) {
30
13
  return !!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'").get();
31
14
  }
32
- function ledgerHasChecksum(db) {
33
- return db.prepare("PRAGMA table_info(schema_migrations)").all().some((column) => column.name === "checksum");
34
- }
35
- /**
36
- * Core ledger inspection against the expected ordered `{ id, checksum }`
37
- * registry. Both {@link inspectMigrationLedger} (bodies → checksums) and
38
- * {@link inspectSealedMigrationLedger} (frozen pre-computed checksums) route
39
- * here so the two entry points can never diverge.
40
- */
41
- function inspectLedgerAgainst(db, expected) {
42
- const registryIds = expected.map((entry) => entry.id);
43
- if (new Set(registryIds).size !== registryIds.length) {
44
- return {
45
- status: "inconsistent",
46
- migrationIds: [],
47
- checksums: [],
48
- detail: "migration registry contains duplicate IDs",
49
- };
50
- }
15
+ /** Inspect the database's applied IDs against the exact ordered registry prefix. */
16
+ function inspectLedgerAgainst(db, registryIds) {
51
17
  if (!migrationsTableExists(db))
52
- return { status: registryIds.length === 0 ? "current" : "old", migrationIds: [], checksums: [] };
53
- const hasChecksum = ledgerHasChecksum(db);
54
- const rows = db
55
- .prepare(`SELECT id${hasChecksum ? ", checksum" : ""} FROM schema_migrations ORDER BY rowid`)
56
- .all();
18
+ return { status: registryIds.length === 0 ? "current" : "old", migrationIds: [] };
19
+ const rows = db.prepare("SELECT id FROM schema_migrations ORDER BY rowid").all();
57
20
  const migrationIds = rows.map((row) => row.id);
58
- const checksums = rows.map((row) => row.checksum ?? null);
59
- for (let index = 0; index < rows.length; index += 1) {
60
- const entry = expected[index];
61
- const row = rows[index];
62
- if (!entry) {
63
- return { status: "newer", migrationIds, checksums, detail: `unknown migration ID ${row.id}` };
21
+ for (const [index, row] of rows.entries()) {
22
+ const expectedId = registryIds[index];
23
+ if (!expectedId) {
24
+ return { status: "newer", migrationIds, detail: `unknown migration ID ${row.id}` };
64
25
  }
65
- if (row.id !== entry.id) {
26
+ if (row.id !== expectedId) {
66
27
  const knownLater = registryIds.includes(row.id);
67
28
  return {
68
29
  status: knownLater ? "inconsistent" : "newer",
69
30
  migrationIds,
70
- checksums,
71
31
  detail: knownLater
72
32
  ? `migration ledger is not an exact ordered prefix at position ${index + 1}`
73
33
  : `unknown migration ID ${row.id}`,
74
34
  };
75
35
  }
76
- if (row.checksum && row.checksum !== entry.checksum) {
77
- return {
78
- status: "inconsistent",
79
- migrationIds,
80
- checksums,
81
- detail: `migration ${row.id} checksum does not match the released migration body`,
82
- };
83
- }
84
- }
85
- const missingChecksum = checksums.indexOf(null);
86
- if (missingChecksum >= 0) {
87
- return {
88
- status: "old",
89
- migrationIds,
90
- checksums,
91
- detail: `migration ${migrationIds[missingChecksum]} has not been sealed with a checksum`,
92
- };
93
36
  }
94
37
  return {
95
- status: rows.length === expected.length ? "current" : "old",
38
+ status: rows.length === registryIds.length ? "current" : "old",
96
39
  migrationIds,
97
- checksums,
98
40
  };
99
41
  }
100
42
  export function inspectMigrationLedger(db, migrations) {
101
- return inspectLedgerAgainst(db, migrations.map((migration) => ({ id: migration.id, checksum: migrationChecksum(migration) })));
102
- }
103
- /**
104
- * Ledger inspection against a FROZEN `{ id, checksum }` copy of a migration
105
- * array whose live source is gone (plan §3.3 item 1). Behaviourally identical
106
- * to {@link inspectMigrationLedger} — the checksums are simply pre-computed
107
- * rather than derived from `up` bodies.
108
- */
109
- export function inspectSealedMigrationLedger(db, sealed) {
110
- return inspectLedgerAgainst(db, sealed);
43
+ assertMigrationRegistry(migrations);
44
+ return inspectLedgerAgainst(db, migrations.map((migration) => migration.id));
111
45
  }
112
46
  export function assertMigrationLedger(db, migrations) {
113
47
  const state = inspectMigrationLedger(db, migrations);
@@ -134,12 +68,9 @@ export function ensureMigrationsTable(db) {
134
68
  db.exec(`
135
69
  CREATE TABLE IF NOT EXISTS schema_migrations (
136
70
  id TEXT PRIMARY KEY,
137
- applied_at TEXT NOT NULL DEFAULT (datetime('now')),
138
- checksum TEXT
71
+ applied_at TEXT NOT NULL DEFAULT (datetime('now'))
139
72
  );
140
73
  `);
141
- if (!ledgerHasChecksum(db))
142
- db.exec("ALTER TABLE schema_migrations ADD COLUMN checksum TEXT");
143
74
  }
144
75
  /**
145
76
  * Apply every pending migration, one transaction per migration.
@@ -155,6 +86,7 @@ export function ensureMigrationsTable(db) {
155
86
  * @param opts Migration execution options.
156
87
  */
157
88
  export function runMigrations(db, migrations, opts) {
89
+ assertMigrationRegistry(migrations);
158
90
  if (opts?.applyPending === false) {
159
91
  assertMigrationLedger(db, migrations);
160
92
  return;
@@ -162,23 +94,6 @@ export function runMigrations(db, migrations, opts) {
162
94
  if (migrationsTableExists(db))
163
95
  assertMigrationLedger(db, migrations);
164
96
  ensureMigrationsTable(db);
165
- const ledger = assertMigrationLedger(db, migrations);
166
- db.transaction(() => {
167
- const update = db.prepare("UPDATE schema_migrations SET checksum = ? WHERE id = ? AND checksum IS NULL");
168
- for (let index = 0; index < ledger.migrationIds.length; index += 1) {
169
- update.run(migrationChecksum(migrations[index]), ledger.migrationIds[index]);
170
- }
171
- if (opts?.generationMarker) {
172
- db.exec(`
173
- CREATE TABLE IF NOT EXISTS akm_migration_generation (
174
- singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
175
- operation_id TEXT NOT NULL,
176
- phase TEXT NOT NULL
177
- )
178
- `);
179
- db.prepare("INSERT INTO akm_migration_generation(singleton, operation_id, phase) VALUES (1, ?, ?) ON CONFLICT(singleton) DO UPDATE SET operation_id=excluded.operation_id, phase=excluded.phase").run(opts.generationMarker.operationId, opts.generationMarker.phase);
180
- }
181
- })();
182
97
  const appliedRows = db.prepare("SELECT id FROM schema_migrations ORDER BY rowid").all();
183
98
  const applied = new Set(appliedRows.map((r) => r.id));
184
99
  for (const migration of migrations) {
@@ -187,7 +102,7 @@ export function runMigrations(db, migrations, opts) {
187
102
  opts?.beforeMigration?.(migration);
188
103
  db.transaction(() => {
189
104
  db.exec(migration.up);
190
- db.prepare("INSERT INTO schema_migrations (id, checksum) VALUES (?, ?)").run(migration.id, migrationChecksum(migration));
105
+ db.prepare("INSERT INTO schema_migrations (id) VALUES (?)").run(migration.id);
191
106
  })();
192
107
  }
193
108
  }
@@ -226,25 +226,11 @@ export class WorkflowRunsRepository {
226
226
  .prepare("SELECT * FROM workflow_run_units WHERE run_id = ? AND step_id = ? ORDER BY started_at ASC, unit_id ASC")
227
227
  .all(runId, stepId);
228
228
  }
229
- /** One unit row by primary key, or undefined. Used by the R3 report path's
230
- * guarded read-then-write (idempotency / replay-divergence / claim checks). */
229
+ /** One unit row by primary key, or undefined. Used for guarded read-then-write
230
+ * (idempotency / replay-divergence / claim checks). */
231
231
  getUnit(runId, unitId) {
232
232
  return this.db.prepare("SELECT * FROM workflow_run_units WHERE run_id = ? AND unit_id = ?").get(runId, unitId);
233
233
  }
234
- /**
235
- * Stamp a unit-level check-in heartbeat (migration 007, R3 driver protocol):
236
- * a driver executing a unit calls `report --status running` to claim (first
237
- * call) or heartbeat (subsequent) it. Sets `status = 'running'` and
238
- * `last_checkin_at`; NEVER touches `started_at` (the first-claim marker set by
239
- * {@link insertUnit}) so the heartbeat window advances without resetting the
240
- * claim time. The caller guards against re-claiming a terminal unit inside its
241
- * transaction.
242
- */
243
- updateUnitCheckin(runId, unitId, lastCheckinAt) {
244
- this.db
245
- .prepare("UPDATE workflow_run_units SET status = 'running', last_checkin_at = ? WHERE run_id = ? AND unit_id = ?")
246
- .run(lastCheckinAt, runId, unitId);
247
- }
248
234
  /**
249
235
  * Insert a unit row in `running` state (a dispatch is starting now).
250
236
  *
@@ -291,13 +277,13 @@ export class WorkflowRunsRepository {
291
277
  .run(input.runId, input.unitId, input.stepId, input.nodeId, input.parentUnitId, input.phase, input.runner, input.engine ?? null, input.model, input.inputHash, input.worktreePath ?? null, input.startedAt, input.claimHolder ?? null, input.claimExpiresAt ?? null);
292
278
  }
293
279
  /**
294
- * Stamp a `--status running` claim + heartbeat on a unit row (migration 009,
295
- * PR #714 review round 2). Sets `status = 'running'`, refreshes the heartbeat
296
- * (`last_checkin_at`), and (re)writes the claim owner + expiry. Called inside
297
- * the report path's running-claim transaction AFTER it has validated that the
298
- * claim is free / expired / already held by this holder, so the write is the
299
- * final step of a checked reclaim. Never touches `started_at` (the first-claim
300
- * marker set by {@link insertUnit}).
280
+ * Stamp a `running` claim + heartbeat on a unit row (migration 009, PR #714
281
+ * review round 2). Sets `status = 'running'`, refreshes the heartbeat
282
+ * (`last_checkin_at`), and (re)writes the claim owner + expiry. Must be called
283
+ * inside a transaction that has ALREADY validated the claim is free / expired
284
+ * / already held by this holder, so the write is the final step of a checked
285
+ * reclaim. Never touches `started_at` (the first-claim marker set by
286
+ * {@link insertUnit}).
301
287
  */
302
288
  updateUnitClaim(runId, unitId, holder, expiresAt, lastCheckinAt) {
303
289
  const result = this.db
@@ -15,7 +15,7 @@
15
15
  * 3. Skip disabled tasks only when the invocation is scheduler-generated;
16
16
  * explicit manual runs are allowed for catch-up and testing.
17
17
  * 4. Dispatch by target kind:
18
- * • workflow → `startWorkflowRun(ref, params)`
18
+ * • workflow → `runWorkflowSteps({ target: ref, params })`
19
19
  * • prompt → `executeRunner(engine, prompt, { stdio: "captured" })`
20
20
  * 5. Capture stdout / stderr as structured rows in logs.db (task_logs) and,
21
21
  * transitionally, as a flat text tail at `<cacheDir>/tasks/logs/<id>/<ts>.log`
@@ -39,13 +39,14 @@ import { getTaskLogDir } from "../core/paths.js";
39
39
  import { redactCredentialPatterns } from "../core/redaction.js";
40
40
  import { withStateDb } from "../core/state-db.js";
41
41
  import { runManagedSubprocess } from "../core/subprocess.js";
42
+ import { fallbackAnnouncement, NO_ENGINE_MESSAGE_SUFFIX, NO_ENGINE_REMEDY, withEngineFallback, } from "../integrations/agent/engine-fallback.js";
42
43
  import { resolveEngine, resolveLlmEngineUse } from "../integrations/agent/engine-resolution.js";
43
44
  import { resolveModel } from "../integrations/agent/model-aliases.js";
44
45
  import { executeRunner } from "../integrations/agent/runner-dispatch.js";
45
46
  import { chatCompletion } from "../llm/client.js";
46
47
  import { resolveAssetPath } from "../sources/resolve.js";
47
48
  import { decodeTaskHistoryMetadata, finalizeTaskHistoryAttempt, getTaskHistory, queryTaskHistory, reserveTaskHistoryAttempt, upsertTaskHistory, } from "../storage/repositories/task-history-repository.js";
48
- import { startWorkflowRun } from "../workflows/runtime/runs.js";
49
+ import { runWorkflowSteps } from "../workflows/exec/run-workflow.js";
49
50
  import { findBareAkmExecutableIndex } from "./command-executable.js";
50
51
  import { parseTaskDocument } from "./parser.js";
51
52
  import { resolveAkmInvocation } from "./resolve-akm-bin.js";
@@ -53,7 +54,7 @@ import { validateTaskId } from "./task-id.js";
53
54
  export const INVALID_TASK_ATTEMPT_ID = "_invalid-task-id";
54
55
  export async function runTask(id, options) {
55
56
  const runAgentImpl = options.runAgentImpl;
56
- const startWorkflowRunImpl = options.startWorkflowRunImpl ?? startWorkflowRun;
57
+ const runWorkflowStepsImpl = options.runWorkflowStepsImpl ?? runWorkflowSteps;
57
58
  const now = options.now ?? (() => new Date());
58
59
  const requestedStartedAt = now();
59
60
  try {
@@ -118,7 +119,7 @@ export async function runTask(id, options) {
118
119
  logPath,
119
120
  startedAt,
120
121
  now,
121
- startWorkflowRunImpl,
122
+ runWorkflowStepsImpl,
122
123
  historyReserved: attempt.historyReserved,
123
124
  });
124
125
  }
@@ -248,7 +249,7 @@ function resolveNestedAkmCommand(cmd) {
248
249
  }
249
250
  // ── workflow target ─────────────────────────────────────────────────────────
250
251
  async function runWorkflowTask(input) {
251
- const { task, logPath, startedAt, now, startWorkflowRunImpl, historyReserved } = input;
252
+ const { task, logPath, startedAt, now, runWorkflowStepsImpl, historyReserved } = input;
252
253
  if (task.target.kind !== "workflow")
253
254
  throw new Error("invariant: workflow target");
254
255
  const ref = parseRefInput(task.target.ref);
@@ -256,9 +257,18 @@ async function runWorkflowTask(input) {
256
257
  throw new NotFoundError(`Task "${task.id}" workflow target must be a workflow ref (got "${task.target.ref}").`, "WORKFLOW_NOT_FOUND");
257
258
  }
258
259
  let detail;
260
+ let gateError;
259
261
  let error;
262
+ // The prompt path logs the engine-fallback announcement; a workflow-backed
263
+ // task must leave the same trace rather than silently using a chosen engine.
264
+ let runWarnings = [];
260
265
  try {
261
- detail = await startWorkflowRunImpl(task.target.ref, task.target.params);
266
+ const execution = await runWorkflowStepsImpl({ target: task.target.ref, params: task.target.params });
267
+ detail = execution.run;
268
+ runWarnings = execution.warnings ?? [];
269
+ if (execution.gateRejection) {
270
+ gateError = `Verification rejected step "${execution.gateRejection.stepId}": ${execution.gateRejection.feedback}`;
271
+ }
262
272
  }
263
273
  catch (e) {
264
274
  if (e instanceof AkmError && e.kind === "config")
@@ -266,8 +276,13 @@ async function runWorkflowTask(input) {
266
276
  error = e instanceof Error ? e : new Error(String(e));
267
277
  }
268
278
  const finishedAt = finishAttempt(startedAt, now());
269
- const status = error ? "failed" : mapWorkflowStatus(detail?.run.status);
270
- const log = renderWorkflowLog({ task, detail, error });
279
+ const status = error || gateError ? "failed" : mapWorkflowStatus(detail?.status);
280
+ const log = renderWorkflowLog({
281
+ task,
282
+ detail,
283
+ error: error ?? (gateError ? new Error(gateError) : undefined),
284
+ warnings: runWarnings,
285
+ });
271
286
  persistRunLog({
272
287
  taskId: task.id,
273
288
  startedAtIso: startedAt.toISOString(),
@@ -285,8 +300,8 @@ async function runWorkflowTask(input) {
285
300
  log: logPath,
286
301
  target: { kind: "workflow", ref: task.target.ref },
287
302
  detail: {
288
- runId: detail?.run.id,
289
- ...(error ? { error: error.message } : {}),
303
+ runId: detail?.id,
304
+ ...(error ? { error: error.message } : gateError ? { error: gateError } : {}),
290
305
  },
291
306
  };
292
307
  appendHistory(result, historyReserved);
@@ -299,10 +314,8 @@ async function runWorkflowTask(input) {
299
314
  }
300
315
  /**
301
316
  * Map the workflow runtime's status into the task-runner status space.
302
- * Workflows can legitimately remain `active` after `startWorkflowRun`
303
- * returns (multi-step workflows pause for user input); recording them as
304
- * "completed" would be misleading. We preserve "active" as a first-class
305
- * task status with exit code 0 — the OS scheduler treats it as success.
317
+ * A workflow normally reaches completed or failed in one orchestration call.
318
+ * Active remains representable for explicit engine stops such as a gate.
306
319
  *
307
320
  * The parameter is typed as the runtime's `WorkflowRunStatus` union (plus the
308
321
  * `undefined` that `detail?.run.status` can produce when no detail is present).
@@ -330,9 +343,11 @@ function renderWorkflowLog(input) {
330
343
  const dbLines = [
331
344
  { line: `[akm task] task=${input.task.id} kind=workflow ref=${input.task.target.ref}` },
332
345
  ];
346
+ for (const warning of input.warnings ?? [])
347
+ dbLines.push({ level: "warn", line: warning });
333
348
  if (input.detail) {
334
- dbLines.push({ line: `run_id=${input.detail.run.id} status=${input.detail.run.status}` });
335
- dbLines.push({ line: `workflow_title=${input.detail.run.workflowTitle}` });
349
+ dbLines.push({ line: `run_id=${input.detail.id} status=${input.detail.status}` });
350
+ dbLines.push({ line: `workflow_title=${input.detail.workflowTitle}` });
336
351
  }
337
352
  if (input.error) {
338
353
  dbLines.push({ level: "error", line: `error=${input.error.message}` });
@@ -345,10 +360,15 @@ async function runPromptTask(input) {
345
360
  if (task.target.kind !== "prompt")
346
361
  throw new Error("invariant: prompt target");
347
362
  const promptTarget = task.target;
348
- const config = loadConfig();
363
+ // Same implicit opencode-sdk fallback the workflow freeze boundary applies,
364
+ // so a scheduled prompt task on an engine-less install behaves identically.
365
+ const { config, fallbackEngineName } = withEngineFallback(loadConfig());
349
366
  const engineName = promptTarget.engine ?? config.defaults?.engine;
367
+ // `promptTarget.engine` outranks `defaults.engine`, so the fallback is only
368
+ // reportable when it is the engine actually selected.
369
+ const engineAnnouncement = fallbackAnnouncement(fallbackEngineName, engineName);
350
370
  if (!engineName)
351
- throw new NotFoundError(`Task "${task.id}" has no selected engine.`, "ASSET_NOT_FOUND");
371
+ throw new NotFoundError(`Task "${task.id}" ${NO_ENGINE_MESSAGE_SUFFIX} ${NO_ENGINE_REMEDY}`, "ASSET_NOT_FOUND");
352
372
  let runner = resolveEngine(engineName, config);
353
373
  if (runner.kind === "llm") {
354
374
  const resolved = resolveLlmEngineUse(config, [
@@ -404,7 +424,7 @@ async function runPromptTask(input) {
404
424
  },
405
425
  });
406
426
  const finishedAt = finishAttempt(startedAt, now());
407
- const log = renderPromptLog({ task, engineName, result });
427
+ const log = renderPromptLog({ task, engineName, result, engineAnnouncement });
408
428
  persistRunLog({
409
429
  taskId: task.id,
410
430
  startedAtIso: startedAt.toISOString(),
@@ -461,6 +481,10 @@ function renderPromptLog(input) {
461
481
  const summary = `ok=${input.result.ok} exit_code=${input.result.exitCode ?? "null"} duration_ms=${input.result.durationMs}`;
462
482
  lines.push(header, summary);
463
483
  dbLines.push({ line: header }, { level: input.result.ok ? "info" : "error", line: summary });
484
+ if (input.engineAnnouncement) {
485
+ lines.push(input.engineAnnouncement);
486
+ dbLines.push({ level: "warn", line: input.engineAnnouncement });
487
+ }
464
488
  if (!input.result.ok) {
465
489
  const failure = `reason=${input.result.reason ?? ""} error=${input.result.error ?? ""}`;
466
490
  lines.push(failure);
@@ -4,7 +4,7 @@
4
4
  /**
5
5
  * Task asset schema. A task pairs a cron-style schedule with exactly one of:
6
6
  *
7
- * • a workflow target — invoked via `startWorkflowRun()`
7
+ * • a workflow target — executed via `runWorkflowSteps()`
8
8
  * • a prompt target — invoked via `runAgent()` against the configured
9
9
  * agent harness (e.g. `opencode run`)
10
10
  * • a command target — invoked directly via `Bun.spawn()`, no AI agent
@@ -13,3 +13,26 @@
13
13
  * inline prompts use a YAML block scalar (`prompt: |`).
14
14
  */
15
15
  export const TASK_SCHEMA_VERSION = 2;
16
+ /**
17
+ * Lint-level shape problems for a parsed task YAML mapping: the field rules
18
+ * `src/tasks/parser.ts` enforces at load time, phrased as diagnostics. The ONE
19
+ * definition shared by both task linters (`core/adapter/adapters/akm-lint.ts`
20
+ * and `akm-task-adapter.ts`) so lint and runtime cannot disagree — they
21
+ * previously did, in both directions: lint demanded `enabled` (which the
22
+ * parser defaults to `true`, so a runnable task was flagged) and never checked
23
+ * `version` (which the parser hard-requires as `2`, so a lint-clean task died
24
+ * at runtime with TASK_SCHEMA_VERSION_UNSUPPORTED). `schemas/akm-task.json`
25
+ * agrees with the parser: `required: [version, schedule]`, `version:
26
+ * {const: 2}`, `enabled` optional but boolean. Target-arity rules stay with
27
+ * each caller (they legitimately differ: at-least-one vs exactly-one).
28
+ */
29
+ export function taskFieldProblems(data) {
30
+ const problems = [];
31
+ if (data.version !== TASK_SCHEMA_VERSION)
32
+ problems.push(`version (must be ${TASK_SCHEMA_VERSION})`);
33
+ if (typeof data.schedule !== "string" || data.schedule.trim() === "")
34
+ problems.push("schedule");
35
+ if ("enabled" in data && typeof data.enabled !== "boolean")
36
+ problems.push("enabled (must be a boolean when present)");
37
+ return problems;
38
+ }
@@ -20,6 +20,7 @@ import { placementSpecFor } from "../core/asset/asset-placement.js";
20
20
  import { parseRefInput } from "../core/asset/resolve-ref.js";
21
21
  import { loadConfig } from "../core/config/config.js";
22
22
  import { NotFoundError } from "../core/errors.js";
23
+ import { NO_ENGINE_MESSAGE_SUFFIX, withEngineFallback } from "../integrations/agent/engine-fallback.js";
23
24
  import { resolveEngine } from "../integrations/agent/engine-resolution.js";
24
25
  import { resolveAssetPath } from "../sources/resolve.js";
25
26
  import { parseSchedule } from "./schedule.js";
@@ -42,10 +43,13 @@ export async function validateTaskDocument(task, options) {
42
43
  // set on the task, defaults.engine is required. Catching this at
43
44
  // `task add` / `task sync` time is much more useful than failing only
44
45
  // when the OS scheduler fires.
45
- const config = loadConfig();
46
+ // Resolve against the SAME effective config the runner will use
47
+ // (`tasks/runner.ts`), or validation rejects at `task add` / `task sync` a
48
+ // task the runner would have happily executed via the implicit fallback.
49
+ const { config } = withEngineFallback(loadConfig());
46
50
  const engine = task.target.engine ?? config.defaults?.engine;
47
51
  if (!engine)
48
- throw new NotFoundError(`Task "${task.id}" has no selected engine.`, "ASSET_NOT_FOUND");
52
+ throw new NotFoundError(`Task "${task.id}" ${NO_ENGINE_MESSAGE_SUFFIX}`, "ASSET_NOT_FOUND");
49
53
  const resolved = resolveEngine(engine, config);
50
54
  if (task.target.llm !== undefined && resolved.kind !== "llm") {
51
55
  throw new NotFoundError(`Task "${task.id}" uses llm overrides with non-LLM engine "${engine}".`, "ASSET_NOT_FOUND");