substrate-ai 0.20.137 → 0.20.139

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.
@@ -0,0 +1,4 @@
1
+ import { AdapterRegistry } from "./dist-BWCudDcl.js";
2
+ import "./adapter-registry-DIcrxjH8.js";
3
+
4
+ export { AdapterRegistry };
package/dist/cli/index.js CHANGED
@@ -1,20 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import { FileKvStore, SUBSTRATE_OWNED_SETTINGS_KEYS, VALID_PHASES, buildPipelineStatusOutput, createDatabaseAdapter, createDoltOperatorReader, findPackageRoot, formatOutput, formatPipelineStatusHuman, formatPipelineSummary, formatTokenTelemetry, getAllDescendantPids, getAutoHealthData, getSubstrateDefaultSettings, inspectProcessTree, parseDbTimestampAsUtc, registerHealthCommand, resolveBmadMethodSrcPath, resolveBmadMethodVersion } from "../health-BqCpWu2_.js";
2
+ import { FileKvStore, SUBSTRATE_OWNED_SETTINGS_KEYS, VALID_PHASES, buildPipelineStatusOutput, createDatabaseAdapter, createDoltOperatorReader, findPackageRoot, formatOutput, formatPipelineStatusHuman, formatPipelineSummary, formatTokenTelemetry, getAllDescendantPids, getAutoHealthData, getSubstrateDefaultSettings, inspectProcessTree, parseDbTimestampAsUtc, registerHealthCommand, resolveBmadMethodSrcPath, resolveBmadMethodVersion } from "../health-BXVyiLiL.js";
3
3
  import { createLogger } from "../logger-KeHncl-f.js";
4
4
  import { createEventBus } from "../helpers-CElYrONe.js";
5
- import { AdapterRegistry, BudgetConfigSchema, CURRENT_CONFIG_FORMAT_VERSION, CURRENT_TASK_GRAPH_VERSION, ConfigError, CostTrackerConfigSchema, DEFAULT_CONFIG, DoltClient, DoltNotInstalled, GlobalSettingsSchema, InMemoryDatabaseAdapter, IngestionServer, MonitorDatabaseImpl, OPERATIONAL_FINDING, PartialGlobalSettingsSchema, PartialProviderConfigSchema, ProvidersSchema, RoutingRecommender, STORY_METRICS, TelemetryConfigSchema, addTokenUsage, aggregateTokenUsageForRun, checkDoltInstalled, compareRunMetrics, createAmendmentRun, createConfigSystem, createDecision, createPipelineRun, createStderrLogger, getActiveDecisions, getAllCostEntriesFiltered, getBaselineRunMetrics, getDecisionsByCategory, getDecisionsByPhaseForRun, getLatestCompletedRun, getLatestRun, getPipelineRunById, getPlanningCostTotal, getRetryableEscalations, getRunMetrics, getRunningPipelineRuns, getSessionCostSummary, getSessionCostSummaryFiltered, getStoryMetricsForRun, getTokenUsageSummary, incrementRunRestarts, initSchema, initWorkGraphSchema, initializeDolt, listRunMetrics, loadParentRunDecisions, supersedeDecision, swallowDebug, tagRunAsBaseline, updatePipelineRun } from "../dist-BOooz8sb.js";
6
- import { AdapterTelemetryPersistence, AppError, DoltRepoMapMetaRepository, DoltSymbolRepository, ERR_REPO_MAP_STORAGE_WRITE, EpicIngester, GLOBSTAR, GitClient, GrammarLoader, Minimatch, Minipass, RepoMapInjector, RepoMapModule, RepoMapQueryEngine, RepoMapStorage, SymbolParser, createContextCompiler, createDispatcher, createEventEmitter, createGitWorktreeManager, createImplementationOrchestrator, createPackLoader, createPhaseOrchestrator, createStopAfterGate, createTelemetryAdvisor, escape, formatPhaseCompletionSummary, getFactoryRunSummaries, getScenarioResultsForRun, getTwinRunsForRun, listGraphRuns, registerExportCommand, registerFactoryCommand, registerRunCommand, registerScenariosCommand, resolveStoryKeys, runAnalysisPhase, runPlanningPhase, runProbeAuthor, runSolutioningPhase, unescape, validateStopAfterFromConflict } from "../run-Bb39uB9y.js";
5
+ import { AdapterRegistry, BudgetConfigSchema, CURRENT_CONFIG_FORMAT_VERSION, CURRENT_TASK_GRAPH_VERSION, ConfigError, CostTrackerConfigSchema, DEFAULT_CONFIG, DoltClient, DoltNotInstalled, GlobalSettingsSchema, InMemoryDatabaseAdapter, IngestionServer, MonitorDatabaseImpl, OPERATIONAL_FINDING, PartialGlobalSettingsSchema, PartialProviderConfigSchema, ProvidersSchema, RoutingRecommender, STORY_METRICS, TelemetryConfigSchema, addTokenUsage, aggregateTokenUsageForRun, checkDoltInstalled, compareRunMetrics, createAmendmentRun, createConfigSystem, createDecision, createPipelineRun, createStderrLogger, getActiveDecisions, getAllCostEntriesFiltered, getBaselineRunMetrics, getDecisionsByCategory, getDecisionsByPhaseForRun, getLatestCompletedRun, getLatestRun, getPipelineRunById, getPlanningCostTotal, getRetryableEscalations, getRunMetrics, getRunningPipelineRuns, getSessionCostSummary, getSessionCostSummaryFiltered, getStoryMetricsForRun, getTokenUsageSummary, incrementRunRestarts, initSchema, initWorkGraphSchema, initializeDolt, listRunMetrics, loadParentRunDecisions, supersedeDecision, swallowDebug, tagRunAsBaseline, updatePipelineRun } from "../dist-BWCudDcl.js";
6
+ import { AdapterTelemetryPersistence, AppError, DoltRepoMapMetaRepository, DoltSymbolRepository, ERR_REPO_MAP_STORAGE_WRITE, EpicIngester, GLOBSTAR, GitClient, GrammarLoader, Minimatch, Minipass, RepoMapInjector, RepoMapModule, RepoMapQueryEngine, RepoMapStorage, SymbolParser, createContextCompiler, createDispatcher, createEventEmitter, createGitWorktreeManager, createImplementationOrchestrator, createPackLoader, createPhaseOrchestrator, createStopAfterGate, createTelemetryAdvisor, escape, formatPhaseCompletionSummary, getFactoryRunSummaries, getScenarioResultsForRun, getTwinRunsForRun, listGraphRuns, registerExportCommand, registerFactoryCommand, registerRunCommand, registerScenariosCommand, resolveStoryKeys, runAnalysisPhase, runPlanningPhase, runProbeAuthor, runSolutioningPhase, unescape, validateStopAfterFromConflict } from "../run-eaZG_3rN.js";
7
7
  import "../adapter-registry-DIcrxjH8.js";
8
- import { RunManifest, SupervisorLock, ZERO_FINDINGS_BY_AUTHOR, ZERO_FINDING_COUNTS, ZERO_PROBE_AUTHOR_METRICS, aggregateProbeAuthorMetrics, parseRuntimeProbes, readCurrentRunId, resolveMainRepoRoot, resolveRunManifest, rollupFindingCounts, rollupFindingsByAuthor, rollupProbeAuthorByClass, rollupProbeAuthorMetrics, runAcTraceabilityCheck } from "../manifest-read-B0XYbIpU.js";
9
- import "../errors-iQa5SrYw.js";
8
+ import { RunManifest, SupervisorLock, ZERO_FINDINGS_BY_AUTHOR, ZERO_FINDING_COUNTS, ZERO_PROBE_AUTHOR_METRICS, aggregateProbeAuthorMetrics, parseRuntimeProbes, readCurrentRunId, resolveMainRepoRoot, resolveRunManifest, rollupFindingCounts, rollupFindingsByAuthor, rollupProbeAuthorByClass, rollupProbeAuthorMetrics, runAcTraceabilityCheck } from "../manifest-read-IvpNQ6Yy.js";
9
+ import "../errors-rZ-lz8U0.js";
10
10
  import "../routing-DFxoKHDt.js";
11
11
  import { WorkGraphRepository } from "../work-graph-repository-DZyJv5pV.js";
12
12
  import "../decisions-CzSIEeGP.js";
13
13
  import "../decision-router-DblHY8se.js";
14
- import "../interactive-prompt-Czlubg4J.js";
14
+ import "../interactive-prompt-BypNgFHL.js";
15
15
  import "../recovery-engine-BKGBeBnW.js";
16
16
  import "../version-manager-impl-qFBiO4Eh.js";
17
- import { registerUpgradeCommand } from "../upgrade-BwitoFQT.js";
17
+ import { registerUpgradeCommand } from "../upgrade-3NTcs1t7.js";
18
18
  import { Command } from "commander";
19
19
  import { fileURLToPath } from "url";
20
20
  import { dirname, join, resolve } from "path";
@@ -406,7 +406,8 @@ function healthResultToJson(adapterId, displayName, healthResult) {
406
406
  cliPath: healthResult.cliPath ?? null,
407
407
  detectedBillingModes: healthResult.detectedBillingModes ?? [],
408
408
  supportsHeadless: healthResult.supportsHeadless,
409
- error: healthResult.error ?? null
409
+ error: healthResult.error ?? null,
410
+ compatibilityWarning: healthResult.compatibilityWarning ?? null
410
411
  };
411
412
  }
412
413
 
@@ -462,6 +463,18 @@ function registerAdaptersCommand(program, version, registry) {
462
463
  if (opts.verbose) for (const result of report.results) {
463
464
  const health = result.healthResult;
464
465
  if (!health.healthy && health.error) process.stdout.write(`\n[${result.adapterId}] Error: ${health.error}\n`);
466
+ if (health.compatibilityWarning !== void 0) process.stdout.write(`\n[${result.adapterId}] Compatibility: ${health.compatibilityWarning}\n`);
467
+ }
468
+ else {
469
+ const drifted = report.results.filter((r) => r.healthResult.compatibilityWarning !== void 0);
470
+ if (drifted.length > 0) {
471
+ process.stdout.write("\nCLI version notes (run with --verbose for full text):\n");
472
+ for (const result of drifted) {
473
+ const w = result.healthResult.compatibilityWarning;
474
+ const oneLine = w.length > 120 ? w.slice(0, 117) + "..." : w;
475
+ process.stdout.write(` ${result.adapterId}: ${oneLine}\n`);
476
+ }
477
+ }
465
478
  }
466
479
  process.exit(EXIT_CODE_SUCCESS);
467
480
  });
@@ -7023,7 +7036,7 @@ async function runStatusAction(options) {
7023
7036
  logger$15.debug({ err }, "Work graph query failed, continuing without work graph data");
7024
7037
  }
7025
7038
  if (run === void 0) {
7026
- const { inspectProcessTree: inspectProcessTree$1 } = await import("../health-xmLvQgb4.js");
7039
+ const { inspectProcessTree: inspectProcessTree$1 } = await import("../health-D27XuFLF.js");
7027
7040
  const substrateDirPath = join(projectRoot, ".substrate");
7028
7041
  const processInfo = inspectProcessTree$1({
7029
7042
  projectRoot,
@@ -7971,7 +7984,7 @@ function defaultSupervisorDeps() {
7971
7984
  if (cached === null) {
7972
7985
  const { AdapterRegistry: AR } = await import(
7973
7986
  /* @vite-ignore */
7974
- "../adapter-registry-DxomlVMx.js"
7987
+ "../adapter-registry-CXIG-OQI.js"
7975
7988
  );
7976
7989
  cached = new AR();
7977
7990
  await cached.discoverAndRegister();
@@ -8538,11 +8551,11 @@ async function runSupervisorAction(options, deps = {}) {
8538
8551
  try {
8539
8552
  const { createExperimenter } = await import(
8540
8553
  /* @vite-ignore */
8541
- "../experimenter-B7NPkaQ8.js"
8554
+ "../experimenter-Dn0gGOYl.js"
8542
8555
  );
8543
8556
  const { getLatestRun: getLatest } = await import(
8544
8557
  /* @vite-ignore */
8545
- "../decisions-DVuBgwlc.js"
8558
+ "../decisions-EQtHqewP.js"
8546
8559
  );
8547
8560
  const expAdapter = createDatabaseAdapter({
8548
8561
  backend: "auto",
@@ -8552,7 +8565,7 @@ async function runSupervisorAction(options, deps = {}) {
8552
8565
  await initSchema(expAdapter);
8553
8566
  const { runRunAction: runPipeline } = await import(
8554
8567
  /* @vite-ignore */
8555
- "../run-DBifBbYW.js"
8568
+ "../run-Cp19x4Xv.js"
8556
8569
  );
8557
8570
  const runStoryFn = async (opts) => {
8558
8571
  const exitCode = await runPipeline({
@@ -9077,7 +9090,7 @@ async function runMetricsAction(options) {
9077
9090
  const routingConfigPath = join(dbDir, "routing.yml");
9078
9091
  let routingConfig = null;
9079
9092
  if (existsSync$1(routingConfigPath)) try {
9080
- const { loadModelRoutingConfig } = await import("../routing-DkRxOHcc.js");
9093
+ const { loadModelRoutingConfig } = await import("../routing-C0f2cYja.js");
9081
9094
  routingConfig = loadModelRoutingConfig(routingConfigPath);
9082
9095
  } catch {}
9083
9096
  if (routingConfig === null) routingConfig = {
@@ -12363,22 +12376,24 @@ async function readRunEntry(dbRoot, resolvedRunId) {
12363
12376
  * bash-session-drift footgun documented in obs_025.
12364
12377
  */
12365
12378
  function detectAutoCommit(storyKey, startedAt, projectRoot) {
12366
- const grepPattern = `feat(story-${storyKey})`;
12367
- const result = spawnSync("git", [
12368
- "log",
12369
- "--oneline",
12370
- `--since=${startedAt}`,
12371
- `--grep=${grepPattern}`
12372
- ], {
12373
- cwd: projectRoot,
12374
- encoding: "utf-8",
12375
- timeout: 1e4
12376
- });
12377
- if (result.status !== 0 || !result.stdout?.trim()) return void 0;
12378
- const lines = result.stdout.trim().split("\n").filter(Boolean);
12379
- for (const line of lines) {
12380
- const sha = line.split(" ")[0];
12381
- if (sha) return sha;
12379
+ for (const prefix of ["feat", "wip"]) {
12380
+ const grepPattern = `${prefix}(story-${storyKey})`;
12381
+ const result = spawnSync("git", [
12382
+ "log",
12383
+ "--oneline",
12384
+ `--since=${startedAt}`,
12385
+ `--grep=${grepPattern}`
12386
+ ], {
12387
+ cwd: projectRoot,
12388
+ encoding: "utf-8",
12389
+ timeout: 1e4
12390
+ });
12391
+ if (result.status !== 0 || !result.stdout?.trim()) continue;
12392
+ const lines = result.stdout.trim().split("\n").filter(Boolean);
12393
+ for (const line of lines) {
12394
+ const sha = line.split(" ")[0];
12395
+ if (sha) return sha;
12396
+ }
12382
12397
  }
12383
12398
  return void 0;
12384
12399
  }
@@ -13387,8 +13402,8 @@ async function createProgram() {
13387
13402
  /** Fire-and-forget startup version check (story 8.3, AC3/AC5) */
13388
13403
  function checkForUpdatesInBackground(currentVersion) {
13389
13404
  if (process.env.SUBSTRATE_NO_UPDATE_CHECK === "1") return;
13390
- import("../upgrade-GFHZ2nsS.js").then(async () => {
13391
- const { createVersionManager } = await import("../version-manager-impl-CPbTqr0B.js");
13405
+ import("../upgrade-DHHSy4fQ.js").then(async () => {
13406
+ const { createVersionManager } = await import("../version-manager-impl-CfzcfFwo.js");
13392
13407
  const vm = createVersionManager();
13393
13408
  const result = await vm.checkForUpdates();
13394
13409
  if (result.updateAvailable) {
@@ -1,4 +1,4 @@
1
- import { addTokenUsage, createDecision, createPipelineRun, createRequirement, getArtifactByTypeForRun, getArtifactsByRun, getDecisionsByCategory, getDecisionsByPhase, getDecisionsByPhaseForRun, getLatestRun, getPipelineRunById, getRunningPipelineRuns, getTokenUsageSummary, listRequirements, registerArtifact, updateDecision, updatePipelineRun, updatePipelineRunConfig, upsertDecision } from "./dist-BOooz8sb.js";
1
+ import { addTokenUsage, createDecision, createPipelineRun, createRequirement, getArtifactByTypeForRun, getArtifactsByRun, getDecisionsByCategory, getDecisionsByPhase, getDecisionsByPhaseForRun, getLatestRun, getPipelineRunById, getRunningPipelineRuns, getTokenUsageSummary, listRequirements, registerArtifact, updateDecision, updatePipelineRun, updatePipelineRunConfig, upsertDecision } from "./dist-BWCudDcl.js";
2
2
  import "./decisions-CzSIEeGP.js";
3
3
 
4
4
  export { getLatestRun };
@@ -14,11 +14,12 @@ import { homedir } from "os";
14
14
  import { createServer } from "node:http";
15
15
  import { createGunzip, createInflate } from "node:zlib";
16
16
  import { promisify } from "node:util";
17
- import { createRequire } from "node:module";
18
- import { fileURLToPath } from "node:url";
19
17
  import * as semver$2 from "semver";
20
18
  import * as semver$1 from "semver";
21
19
  import * as semver from "semver";
20
+ import { coerce, compare, valid } from "semver";
21
+ import { createRequire } from "node:module";
22
+ import { fileURLToPath } from "node:url";
22
23
  import https from "node:https";
23
24
 
24
25
  //#region packages/core/dist/dispatch/types.js
@@ -1413,7 +1414,10 @@ var DispatcherImpl = class {
1413
1414
  this._running.delete(id);
1414
1415
  this._drainQueue();
1415
1416
  if (code === 0) {
1416
- const normalizeResult = this._normalizer.normalize(stdout, agent);
1417
+ const streamOutput = adapter.parseStreamOutput?.(stdout);
1418
+ const effectiveStdout = streamOutput?.extractedText ?? stdout;
1419
+ const totalTurns = streamOutput?.totalTurns;
1420
+ const normalizeResult = this._normalizer.normalize(effectiveStdout, agent);
1417
1421
  let parsed = null;
1418
1422
  let parseError = null;
1419
1423
  if (normalizeResult instanceof AdapterFormatError) {
@@ -1422,13 +1426,13 @@ var DispatcherImpl = class {
1422
1426
  normalizeResult.tried_strategies.join(","),
1423
1427
  normalizeResult.raw_output_snippet
1424
1428
  ].join(" | ");
1425
- const quality$1 = estimateOutputQuality(stdout);
1429
+ const quality$1 = estimateOutputQuality(effectiveStdout);
1426
1430
  this._eventBus.emit("agent:completed", {
1427
1431
  dispatchId: id,
1428
1432
  exitCode: code,
1429
- output: stdout,
1433
+ output: effectiveStdout,
1430
1434
  inputTokens,
1431
- outputTokens: Math.ceil(stdout.length / CHARS_PER_TOKEN$3),
1435
+ outputTokens: Math.ceil(effectiveStdout.length / CHARS_PER_TOKEN$3),
1432
1436
  qualityScore: quality$1.qualityScore,
1433
1437
  agent,
1434
1438
  ...effectiveModel !== void 0 && { model: effectiveModel }
@@ -1444,7 +1448,7 @@ var DispatcherImpl = class {
1444
1448
  id,
1445
1449
  status: "completed",
1446
1450
  exitCode: code,
1447
- output: stdout,
1451
+ output: effectiveStdout,
1448
1452
  parsed: null,
1449
1453
  parseError: errMsg,
1450
1454
  adapterError: true,
@@ -1453,16 +1457,17 @@ var DispatcherImpl = class {
1453
1457
  durationMs,
1454
1458
  tokenEstimate: {
1455
1459
  input: inputTokens,
1456
- output: Math.ceil(stdout.length / CHARS_PER_TOKEN$3)
1460
+ output: Math.ceil(effectiveStdout.length / CHARS_PER_TOKEN$3)
1457
1461
  },
1458
- ...finalModel !== void 0 ? { model: finalModel } : {}
1462
+ ...finalModel !== void 0 ? { model: finalModel } : {},
1463
+ ...totalTurns !== void 0 ? { totalTurns } : {}
1459
1464
  });
1460
1465
  return;
1461
1466
  }
1462
1467
  const parseResult = parseYamlResult(normalizeResult.yaml, outputSchema);
1463
1468
  parsed = parseResult.parsed;
1464
1469
  parseError = parseResult.error;
1465
- const quality = estimateOutputQuality(stdout);
1470
+ const quality = estimateOutputQuality(effectiveStdout);
1466
1471
  if (quality.hedgingCount > 0 || quality.qualityScore < 40) this._logger.warn({
1467
1472
  id,
1468
1473
  agent,
@@ -1473,9 +1478,9 @@ var DispatcherImpl = class {
1473
1478
  this._eventBus.emit("agent:completed", {
1474
1479
  dispatchId: id,
1475
1480
  exitCode: code,
1476
- output: stdout,
1481
+ output: effectiveStdout,
1477
1482
  inputTokens,
1478
- outputTokens: Math.ceil(stdout.length / CHARS_PER_TOKEN$3),
1483
+ outputTokens: Math.ceil(effectiveStdout.length / CHARS_PER_TOKEN$3),
1479
1484
  qualityScore: quality.qualityScore,
1480
1485
  agent,
1481
1486
  ...effectiveModel !== void 0 && { model: effectiveModel }
@@ -1491,15 +1496,16 @@ var DispatcherImpl = class {
1491
1496
  id,
1492
1497
  status: "completed",
1493
1498
  exitCode: code,
1494
- output: stdout,
1499
+ output: effectiveStdout,
1495
1500
  parsed,
1496
1501
  parseError,
1497
1502
  durationMs,
1498
1503
  tokenEstimate: {
1499
1504
  input: inputTokens,
1500
- output: Math.ceil(stdout.length / CHARS_PER_TOKEN$3)
1505
+ output: Math.ceil(effectiveStdout.length / CHARS_PER_TOKEN$3)
1501
1506
  },
1502
- ...finalModel !== void 0 ? { model: finalModel } : {}
1507
+ ...finalModel !== void 0 ? { model: finalModel } : {},
1508
+ ...totalTurns !== void 0 ? { totalTurns } : {}
1503
1509
  });
1504
1510
  } else {
1505
1511
  const stderr = Buffer.concat(stderrChunks).toString("utf-8");
@@ -9414,6 +9420,43 @@ var Recommender = class Recommender {
9414
9420
  }
9415
9421
  };
9416
9422
 
9423
+ //#endregion
9424
+ //#region packages/core/dist/adapters/version-compat.js
9425
+ function normalize(version) {
9426
+ return valid(version) ?? valid(coerce(version) ?? "") ?? null;
9427
+ }
9428
+ /**
9429
+ * Compare a live CLI binary's reported version against the tested range. Pure.
9430
+ *
9431
+ * Three outcomes:
9432
+ * - actual within range → `{ compatible: true }`
9433
+ * - actual outside range → `{ compatible: false, warning }` with a message
9434
+ * naming the adapter + drift + suggested operator action
9435
+ * - actual unparseable → `{ compatible: false, warning }` flagging that
9436
+ * the version couldn't be compared (degrade gracefully; never throw)
9437
+ */
9438
+ function checkAdapterVersionCompat(adapterName, actualVersion, tested) {
9439
+ const actual = normalize(actualVersion);
9440
+ const min = normalize(tested.min);
9441
+ const max = normalize(tested.max);
9442
+ if (actual === null || min === null || max === null) return {
9443
+ compatible: false,
9444
+ warning: `${adapterName}: CLI version '${actualVersion}' could not be parsed for comparison against substrate's tested range (${tested.min}–${tested.max}). Flag behavior may differ; report any dispatch failures.`
9445
+ };
9446
+ if (compare(actual, min) < 0) return {
9447
+ compatible: false,
9448
+ warning: `${adapterName}: CLI version ${actualVersion} is below substrate's tested range (${tested.min}–${tested.max}). Older flag forms may be required; consider upgrading the CLI to a version within range, or upgrading substrate.` + (tested.note !== void 0 ? ` Range note: ${tested.note}` : "")
9449
+ };
9450
+ if (compare(actual, max) > 0) return {
9451
+ compatible: false,
9452
+ warning: `${adapterName}: CLI version ${actualVersion} is newer than substrate's tested range (${tested.min}–${tested.max}). Flag behavior may have changed since substrate was tested; consider upgrading substrate or reporting any dispatch failures.` + (tested.note !== void 0 ? ` Range note: ${tested.note}` : "")
9453
+ };
9454
+ return tested.note !== void 0 ? {
9455
+ compatible: true,
9456
+ warning: `${adapterName}: ${tested.note}`
9457
+ } : { compatible: true };
9458
+ }
9459
+
9417
9460
  //#endregion
9418
9461
  //#region packages/core/dist/adapters/claude-adapter.js
9419
9462
  const execAsync$2 = promisify(exec);
@@ -9440,10 +9483,26 @@ function stripCodeFences$2(raw) {
9440
9483
  * Health check: runs `claude --version` to verify install.
9441
9484
  * Billing detection: detects subscription vs API via version output or env.
9442
9485
  */
9443
- var ClaudeCodeAdapter = class {
9486
+ var ClaudeCodeAdapter = class ClaudeCodeAdapter {
9444
9487
  id = "claude-code";
9445
9488
  displayName = "Claude Code";
9446
9489
  adapterVersion = "1.0.0";
9490
+ /**
9491
+ * Claude Code CLI version range substrate's `buildCommand` has been
9492
+ * empirically verified against (as of substrate v0.20.138 on 2026-05-31).
9493
+ * `healthCheck` compares the live `claude --version` against this range
9494
+ * and surfaces a warning when the operator's CLI is outside it.
9495
+ *
9496
+ * The `note` flags `--max-turns`: the flag is silently accepted by clap
9497
+ * but not honored — substrate's `options.maxTurns` has no effect on
9498
+ * Claude Code 2.x dispatches. Bumping the upper bound requires re-running
9499
+ * the empirical audit (see `feedback_cli_adapter_empirical_version_match`).
9500
+ */
9501
+ static TESTED_CLI_VERSION_RANGE = {
9502
+ min: "2.1.152",
9503
+ max: "2.1.168",
9504
+ note: "Claude Code 2.x silently accepts but does not honor `--max-turns`; substrate no longer passes that flag. `-p --output-format stream-json` REQUIRES `--verbose` (hard error otherwise) — empirically verified against 2.1.168 (2026-06-07): with --verbose, NDJSON events emitted and `num_turns` present on the terminal result event."
9505
+ };
9447
9506
  _logger;
9448
9507
  constructor(logger) {
9449
9508
  this._logger = logger ?? createStderrLogger("claude-adapter");
@@ -9462,12 +9521,14 @@ var ClaudeCodeAdapter = class {
9462
9521
  const whichResult = await execAsync$2("which claude", { timeout: 5e3 });
9463
9522
  cliPath = whichResult.stdout.trim();
9464
9523
  } catch {}
9524
+ const compat = checkAdapterVersionCompat("claude-code", output, ClaudeCodeAdapter.TESTED_CLI_VERSION_RANGE);
9465
9525
  return {
9466
9526
  healthy: true,
9467
9527
  version: output,
9468
9528
  ...cliPath !== void 0 ? { cliPath } : {},
9469
9529
  detectedBillingModes,
9470
- supportsHeadless: true
9530
+ supportsHeadless: true,
9531
+ ...compat.warning !== void 0 ? { compatibilityWarning: compat.warning } : {}
9471
9532
  };
9472
9533
  } catch (err) {
9473
9534
  const message = err instanceof Error ? err.message : String(err);
@@ -9491,7 +9552,7 @@ var ClaudeCodeAdapter = class {
9491
9552
  model,
9492
9553
  "--dangerously-skip-permissions"
9493
9554
  ];
9494
- if (options.maxTurns !== void 0) args.push("--max-turns", String(options.maxTurns));
9555
+ args.push("--output-format", "stream-json", "--verbose");
9495
9556
  if (options.additionalFlags && options.additionalFlags.length > 0) args.push(...options.additionalFlags);
9496
9557
  const systemPromptParts = [BASE_SYSTEM_PROMPT];
9497
9558
  if (options.optimizationDirectives) systemPromptParts.push(`\n\n## Optimization Directives\n${options.optimizationDirectives}`);
@@ -9535,6 +9596,51 @@ var ClaudeCodeAdapter = class {
9535
9596
  };
9536
9597
  }
9537
9598
  /**
9599
+ * Pre-process `--output-format stream-json` stdout before YAML extraction (Story 81-9).
9600
+ *
9601
+ * Claude Code CLI with `--output-format stream-json` emits NDJSON events to stdout.
9602
+ * This method parses that stream to extract:
9603
+ * 1. `extractedText` — the full agent response from the terminal result event's
9604
+ * `result` field. Identical to raw text output; passed to AdapterOutputNormalizer.
9605
+ * 2. `totalTurns` — agentic turn count from `num_turns` in the result event.
9606
+ * This is the ONLY synchronous, reliable turn-count source available at
9607
+ * DispatchResult resolution time.
9608
+ *
9609
+ * Graceful fallbacks:
9610
+ * - If the stream cannot be parsed as NDJSON, returns `{ extractedText: stdout }`.
9611
+ * - If the result event is missing, returns `{ extractedText: stdout }`.
9612
+ * - If `num_turns` is absent from the event, returns without `totalTurns` (AC2:
9613
+ * "when the count is genuinely unavailable, leave the field absent, never fabricate").
9614
+ *
9615
+ * @param stdout Raw subprocess stdout (NDJSON event stream from Claude Code CLI)
9616
+ * @returns `{ extractedText, totalTurns? }` — text for YAML extraction and optional turn count
9617
+ */
9618
+ parseStreamOutput(stdout) {
9619
+ try {
9620
+ const lines = stdout.split("\n");
9621
+ for (const line of lines) {
9622
+ const trimmed = line.trim();
9623
+ if (trimmed === "") continue;
9624
+ let event;
9625
+ try {
9626
+ event = JSON.parse(trimmed);
9627
+ } catch {
9628
+ continue;
9629
+ }
9630
+ if (event !== null && typeof event === "object" && event["type"] === "result") {
9631
+ const resultEvent = event;
9632
+ const extractedText = typeof resultEvent.result === "string" && resultEvent.result.length > 0 ? resultEvent.result : stdout;
9633
+ const totalTurns = typeof resultEvent.num_turns === "number" && resultEvent.num_turns >= 0 ? resultEvent.num_turns : void 0;
9634
+ return totalTurns !== void 0 ? {
9635
+ extractedText,
9636
+ totalTurns
9637
+ } : { extractedText };
9638
+ }
9639
+ }
9640
+ } catch {}
9641
+ return { extractedText: stdout };
9642
+ }
9643
+ /**
9538
9644
  * Build spawn command for plan generation.
9539
9645
  */
9540
9646
  buildPlanningCommand(request, options) {
@@ -9744,10 +9850,30 @@ function detectCodexSandboxBlock(output) {
9744
9850
  * Codex CLI uses stdin for the prompt and outputs JSON when --json flag is used.
9745
9851
  * Codex supports subscription billing (via `codex login`) and API key billing.
9746
9852
  */
9747
- var CodexCLIAdapter = class {
9853
+ var CodexCLIAdapter = class CodexCLIAdapter {
9748
9854
  id = "codex";
9749
9855
  displayName = "Codex CLI";
9750
9856
  adapterVersion = "1.0.0";
9857
+ /**
9858
+ * Codex CLI version range substrate's `buildCommand` has been empirically
9859
+ * verified against (as of substrate v0.20.138 on 2026-05-31). The range
9860
+ * is narrow because the v0.20.131→137 arc taught us how much can drift
9861
+ * between minor versions — `--full-auto` changed meaning between 0.111.0
9862
+ * and 0.128.0 (deprecated, semantics shifted) and almost certainly will
9863
+ * drift again.
9864
+ *
9865
+ * The `note` flags the structural truth: `codex exec` hardcodes
9866
+ * `approval_policy=Never` and ignores `-c approval_policy=...` overrides
9867
+ * (codex-rs/exec/src/lib.rs:407). On enterprise managed configs that
9868
+ * disallow `Never`, dispatch will fail at the apply_patch layer regardless
9869
+ * of substrate's flag — see CODEX_SANDBOX_BLOCK_HINT and the policy ask
9870
+ * document in `docs/2026-05-29-codex-managed-config-policy-ask.md`.
9871
+ */
9872
+ static TESTED_CLI_VERSION_RANGE = {
9873
+ min: "0.135.0",
9874
+ max: "0.135.0",
9875
+ note: "`codex exec` hardcodes approval_policy=Never (cannot be overridden); on enterprise managed configs disallowing Never, dispatch fails at apply_patch."
9876
+ };
9751
9877
  _logger;
9752
9878
  constructor(logger) {
9753
9879
  this._logger = logger ?? createStderrLogger("codex-adapter");
@@ -9764,12 +9890,14 @@ var CodexCLIAdapter = class {
9764
9890
  const whichResult = await execAsync$1("which codex", { timeout: 5e3 });
9765
9891
  cliPath = whichResult.stdout.trim();
9766
9892
  } catch {}
9893
+ const compat = checkAdapterVersionCompat("codex", output, CodexCLIAdapter.TESTED_CLI_VERSION_RANGE);
9767
9894
  return {
9768
9895
  healthy: true,
9769
9896
  version: output,
9770
9897
  ...cliPath !== void 0 ? { cliPath } : {},
9771
9898
  detectedBillingModes: CODEX_BILLING_MODES,
9772
- supportsHeadless: true
9899
+ supportsHeadless: true,
9900
+ ...compat.warning !== void 0 ? { compatibilityWarning: compat.warning } : {}
9773
9901
  };
9774
9902
  } catch (err) {
9775
9903
  const message = err instanceof Error ? err.message : String(err);
@@ -10005,10 +10133,22 @@ function stripCodeFences(raw) {
10005
10133
  * Gemini CLI follows similar patterns to Claude Code: prompt via `-p` flag,
10006
10134
  * JSON output via `--output-format json`, and model via `--model`.
10007
10135
  */
10008
- var GeminiCLIAdapter = class {
10136
+ var GeminiCLIAdapter = class GeminiCLIAdapter {
10009
10137
  id = "gemini";
10010
10138
  displayName = "Gemini CLI";
10011
10139
  adapterVersion = "1.0.0";
10140
+ /**
10141
+ * Gemini CLI version range substrate's `buildCommand` has been empirically
10142
+ * verified against (as of substrate v0.20.138 on 2026-05-31). Empirical
10143
+ * audit confirmed `-p`, `-m/--model`, `-o/--output-format` (with choices
10144
+ * `text|json|stream-json`) and the planning command's positional-prompt form
10145
+ * all parse cleanly on both 0.33.0 and 0.44.1 — same flag layer across a
10146
+ * meaningful version span.
10147
+ */
10148
+ static TESTED_CLI_VERSION_RANGE = {
10149
+ min: "0.33.0",
10150
+ max: "0.44.1"
10151
+ };
10012
10152
  _logger;
10013
10153
  constructor(logger) {
10014
10154
  this._logger = logger ?? createStderrLogger("gemini-adapter");
@@ -10027,12 +10167,14 @@ var GeminiCLIAdapter = class {
10027
10167
  const whichResult = await execAsync("which gemini", { timeout: 5e3 });
10028
10168
  cliPath = whichResult.stdout.trim();
10029
10169
  } catch {}
10170
+ const compat = checkAdapterVersionCompat("gemini", output, GeminiCLIAdapter.TESTED_CLI_VERSION_RANGE);
10030
10171
  return {
10031
10172
  healthy: true,
10032
10173
  version: output,
10033
10174
  ...cliPath !== void 0 ? { cliPath } : {},
10034
10175
  detectedBillingModes,
10035
- supportsHeadless: true
10176
+ supportsHeadless: true,
10177
+ ...compat.warning !== void 0 ? { compatibilityWarning: compat.warning } : {}
10036
10178
  };
10037
10179
  } catch (err) {
10038
10180
  const message = err instanceof Error ? err.message : String(err);
@@ -11342,4 +11484,4 @@ async function callLLM(params) {
11342
11484
 
11343
11485
  //#endregion
11344
11486
  export { ADVISORY_NOTES, AdapterRegistry, AdtError, BudgetConfigSchema, CODEX_SANDBOX_BLOCK_HINT, CURRENT_CONFIG_FORMAT_VERSION, CURRENT_TASK_GRAPH_VERSION, Categorizer, ClaudeCodeAdapter, CodexCLIAdapter, ConfigError, ConfigIncompatibleFormatError, ConsumerAnalyzer, CostTrackerConfigSchema, DEFAULT_CONFIG, DEFAULT_GLOBAL_SETTINGS, DispatcherImpl, DoltClient, DoltNotInstalled, DoltQueryError, ESCALATION_DIAGNOSIS, EXPERIMENT_RESULT, EfficiencyScorer, GeminiCLIAdapter, GlobalSettingsSchema, InMemoryDatabaseAdapter, IngestionServer, LEARNING_FINDING, LogTurnAnalyzer, ModelRoutingConfigSchema, MonitorDatabaseImpl, OPERATIONAL_FINDING, PartialGlobalSettingsSchema, PartialProviderConfigSchema, ProviderPolicySchema, ProvidersSchema, Recommender, RoutingConfigError, RoutingRecommender, RoutingResolver, RoutingTelemetry, RoutingTokenAccumulator, RoutingTuner, STORY_METRICS, STORY_OUTCOME, SubstrateConfigSchema, TASK_TYPE_PHASE_MAP, TEST_EXPANSION_FINDING, TEST_PLAN, TelemetryConfigSchema, TelemetryNormalizer, TelemetryPipeline, TurnAnalyzer, VersionManagerImpl, addTokenUsage, aggregateTokenUsageForRun, aggregateTokenUsageForStory, buildAuditLogEntry, buildBranchName, buildModificationDirective, buildPRBody, buildWorktreePath, callLLM, checkDoltInstalled, classifyVersionGap, compareRunMetrics, createAmendmentRun, createConfigSystem, createDatabaseAdapter as createDatabaseAdapter$1, createDecision, createExperimenter, createPipelineRun, createRequirement, createStderrLogger, createVersionManager, detectCodexSandboxBlock, detectInterfaceChanges, determineVerdict, getActiveDecisions, getAllCostEntriesFiltered, getArtifactByTypeForRun, getArtifactsByRun, getBaselineRunMetrics, getDecisionsByCategory, getDecisionsByPhase, getDecisionsByPhaseForRun, getLatestCompletedRun, getLatestRun, getModelTier, getPipelineRunById, getPlanningCostTotal, getRetryableEscalations, getRunMetrics, getRunningPipelineRuns, getSessionCostSummary, getSessionCostSummaryFiltered, getStoryMetricsForRun, getTokenUsageSummary, incrementRunRestarts, initSchema, initWorkGraphSchema, initializeDolt, listRequirements, listRunMetrics, loadModelRoutingConfig, loadParentRunDecisions, registerArtifact, resolvePromptFile, supersedeDecision, swallowDebug, tagRunAsBaseline, updateDecision, updatePipelineRun, updatePipelineRunConfig, upsertDecision, writeRunMetrics, writeStoryMetrics };
11345
- //# sourceMappingURL=dist-BOooz8sb.js.map
11487
+ //# sourceMappingURL=dist-BWCudDcl.js.map
@@ -1,4 +1,4 @@
1
- import { AdtError } from "./dist-BOooz8sb.js";
1
+ import { AdtError } from "./dist-BWCudDcl.js";
2
2
 
3
3
  //#region src/core/errors.ts
4
4
  /** Error thrown when task configuration is invalid */
@@ -71,4 +71,4 @@ var TaskGraphIncompatibleFormatError = class extends AdtError {
71
71
 
72
72
  //#endregion
73
73
  export { BudgetExceededError, GitError, RecoveryError, TaskConfigError, TaskGraphCycleError, TaskGraphError, TaskGraphIncompatibleFormatError, WorkerError, WorkerNotFoundError };
74
- //# sourceMappingURL=errors-iQa5SrYw.js.map
74
+ //# sourceMappingURL=errors-rZ-lz8U0.js.map
@@ -1,3 +1,3 @@
1
- import { buildAuditLogEntry, buildBranchName, buildModificationDirective, buildPRBody, buildWorktreePath, createExperimenter, determineVerdict, resolvePromptFile } from "./dist-BOooz8sb.js";
1
+ import { buildAuditLogEntry, buildBranchName, buildModificationDirective, buildPRBody, buildWorktreePath, createExperimenter, determineVerdict, resolvePromptFile } from "./dist-BWCudDcl.js";
2
2
 
3
3
  export { createExperimenter };
@@ -1,6 +1,6 @@
1
1
  import { createLogger } from "./logger-KeHncl-f.js";
2
- import { DoltClient, DoltQueryError, createDatabaseAdapter$1 as createDatabaseAdapter, getLatestRun, getPipelineRunById, initSchema } from "./dist-BOooz8sb.js";
3
- import { resolveMainRepoRoot, resolveRunManifest } from "./manifest-read-B0XYbIpU.js";
2
+ import { DoltClient, DoltQueryError, createDatabaseAdapter$1 as createDatabaseAdapter, getLatestRun, getPipelineRunById, initSchema } from "./dist-BWCudDcl.js";
3
+ import { resolveMainRepoRoot, resolveRunManifest } from "./manifest-read-IvpNQ6Yy.js";
4
4
  import { createRequire } from "module";
5
5
  import { dirname, join } from "path";
6
6
  import { existsSync, readFileSync } from "node:fs";
@@ -1000,4 +1000,4 @@ function registerHealthCommand(program, _version = "0.0.0", projectRoot = proces
1000
1000
 
1001
1001
  //#endregion
1002
1002
  export { BMAD_BASELINE_TOKENS_FULL, DEFAULT_STALL_THRESHOLD_SECONDS, FileKvStore, STOP_AFTER_VALID_PHASES, STORY_KEY_PATTERN, SUBSTRATE_OWNED_SETTINGS_KEYS, VALID_PHASES, __commonJS, __require, __toESM, buildPipelineStatusOutput, createDatabaseAdapter$1 as createDatabaseAdapter, createDoltOperatorReader, findPackageRoot, formatOutput, formatPipelineStatusHuman, formatPipelineSummary, formatTokenTelemetry, getAllDescendantPids, getAutoHealthData, getSubstrateDefaultSettings, inspectProcessTree, isOrchestratorProcessLine, parseDbTimestampAsUtc, registerHealthCommand, resolveBmadMethodSrcPath, resolveBmadMethodVersion, runHealthAction, validateStoryKey };
1003
- //# sourceMappingURL=health-BqCpWu2_.js.map
1003
+ //# sourceMappingURL=health-BXVyiLiL.js.map
@@ -1,7 +1,7 @@
1
- import { DEFAULT_STALL_THRESHOLD_SECONDS, getAllDescendantPids, getAutoHealthData, inspectProcessTree, isOrchestratorProcessLine, registerHealthCommand, runHealthAction } from "./health-BqCpWu2_.js";
1
+ import { DEFAULT_STALL_THRESHOLD_SECONDS, getAllDescendantPids, getAutoHealthData, inspectProcessTree, isOrchestratorProcessLine, registerHealthCommand, runHealthAction } from "./health-BXVyiLiL.js";
2
2
  import "./logger-KeHncl-f.js";
3
- import "./dist-BOooz8sb.js";
4
- import "./manifest-read-B0XYbIpU.js";
3
+ import "./dist-BWCudDcl.js";
4
+ import "./manifest-read-IvpNQ6Yy.js";
5
5
  import "./work-graph-repository-DZyJv5pV.js";
6
6
  import "./decisions-CzSIEeGP.js";
7
7