substrate-ai 0.20.138 → 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-2Kfa00-H.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-DnvGvKLu.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-Dbwlb4Md.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-DJFbGhSd.js";
9
- import "../errors-i3s5sshZ.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-B91mG5v4.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-yULZIAAW.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";
@@ -7036,7 +7036,7 @@ async function runStatusAction(options) {
7036
7036
  logger$15.debug({ err }, "Work graph query failed, continuing without work graph data");
7037
7037
  }
7038
7038
  if (run === void 0) {
7039
- const { inspectProcessTree: inspectProcessTree$1 } = await import("../health-Caa24SFM.js");
7039
+ const { inspectProcessTree: inspectProcessTree$1 } = await import("../health-D27XuFLF.js");
7040
7040
  const substrateDirPath = join(projectRoot, ".substrate");
7041
7041
  const processInfo = inspectProcessTree$1({
7042
7042
  projectRoot,
@@ -7984,7 +7984,7 @@ function defaultSupervisorDeps() {
7984
7984
  if (cached === null) {
7985
7985
  const { AdapterRegistry: AR } = await import(
7986
7986
  /* @vite-ignore */
7987
- "../adapter-registry-Bpa7ESBV.js"
7987
+ "../adapter-registry-CXIG-OQI.js"
7988
7988
  );
7989
7989
  cached = new AR();
7990
7990
  await cached.discoverAndRegister();
@@ -8551,11 +8551,11 @@ async function runSupervisorAction(options, deps = {}) {
8551
8551
  try {
8552
8552
  const { createExperimenter } = await import(
8553
8553
  /* @vite-ignore */
8554
- "../experimenter-DU2Cv51N.js"
8554
+ "../experimenter-Dn0gGOYl.js"
8555
8555
  );
8556
8556
  const { getLatestRun: getLatest } = await import(
8557
8557
  /* @vite-ignore */
8558
- "../decisions-fBdZmqOK.js"
8558
+ "../decisions-EQtHqewP.js"
8559
8559
  );
8560
8560
  const expAdapter = createDatabaseAdapter({
8561
8561
  backend: "auto",
@@ -8565,7 +8565,7 @@ async function runSupervisorAction(options, deps = {}) {
8565
8565
  await initSchema(expAdapter);
8566
8566
  const { runRunAction: runPipeline } = await import(
8567
8567
  /* @vite-ignore */
8568
- "../run-Ppco-3HT.js"
8568
+ "../run-Cp19x4Xv.js"
8569
8569
  );
8570
8570
  const runStoryFn = async (opts) => {
8571
8571
  const exitCode = await runPipeline({
@@ -9090,7 +9090,7 @@ async function runMetricsAction(options) {
9090
9090
  const routingConfigPath = join(dbDir, "routing.yml");
9091
9091
  let routingConfig = null;
9092
9092
  if (existsSync$1(routingConfigPath)) try {
9093
- const { loadModelRoutingConfig } = await import("../routing-DFIBY9Yk.js");
9093
+ const { loadModelRoutingConfig } = await import("../routing-C0f2cYja.js");
9094
9094
  routingConfig = loadModelRoutingConfig(routingConfigPath);
9095
9095
  } catch {}
9096
9096
  if (routingConfig === null) routingConfig = {
@@ -12376,22 +12376,24 @@ async function readRunEntry(dbRoot, resolvedRunId) {
12376
12376
  * bash-session-drift footgun documented in obs_025.
12377
12377
  */
12378
12378
  function detectAutoCommit(storyKey, startedAt, projectRoot) {
12379
- const grepPattern = `feat(story-${storyKey})`;
12380
- const result = spawnSync("git", [
12381
- "log",
12382
- "--oneline",
12383
- `--since=${startedAt}`,
12384
- `--grep=${grepPattern}`
12385
- ], {
12386
- cwd: projectRoot,
12387
- encoding: "utf-8",
12388
- timeout: 1e4
12389
- });
12390
- if (result.status !== 0 || !result.stdout?.trim()) return void 0;
12391
- const lines = result.stdout.trim().split("\n").filter(Boolean);
12392
- for (const line of lines) {
12393
- const sha = line.split(" ")[0];
12394
- 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
+ }
12395
12397
  }
12396
12398
  return void 0;
12397
12399
  }
@@ -13400,8 +13402,8 @@ async function createProgram() {
13400
13402
  /** Fire-and-forget startup version check (story 8.3, AC3/AC5) */
13401
13403
  function checkForUpdatesInBackground(currentVersion) {
13402
13404
  if (process.env.SUBSTRATE_NO_UPDATE_CHECK === "1") return;
13403
- import("../upgrade-CnIsoLpT.js").then(async () => {
13404
- const { createVersionManager } = await import("../version-manager-impl-C7ZhqLX3.js");
13405
+ import("../upgrade-DHHSy4fQ.js").then(async () => {
13406
+ const { createVersionManager } = await import("../version-manager-impl-CfzcfFwo.js");
13405
13407
  const vm = createVersionManager();
13406
13408
  const result = await vm.checkForUpdates();
13407
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-DnvGvKLu.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 };
@@ -1414,7 +1414,10 @@ var DispatcherImpl = class {
1414
1414
  this._running.delete(id);
1415
1415
  this._drainQueue();
1416
1416
  if (code === 0) {
1417
- 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);
1418
1421
  let parsed = null;
1419
1422
  let parseError = null;
1420
1423
  if (normalizeResult instanceof AdapterFormatError) {
@@ -1423,13 +1426,13 @@ var DispatcherImpl = class {
1423
1426
  normalizeResult.tried_strategies.join(","),
1424
1427
  normalizeResult.raw_output_snippet
1425
1428
  ].join(" | ");
1426
- const quality$1 = estimateOutputQuality(stdout);
1429
+ const quality$1 = estimateOutputQuality(effectiveStdout);
1427
1430
  this._eventBus.emit("agent:completed", {
1428
1431
  dispatchId: id,
1429
1432
  exitCode: code,
1430
- output: stdout,
1433
+ output: effectiveStdout,
1431
1434
  inputTokens,
1432
- outputTokens: Math.ceil(stdout.length / CHARS_PER_TOKEN$3),
1435
+ outputTokens: Math.ceil(effectiveStdout.length / CHARS_PER_TOKEN$3),
1433
1436
  qualityScore: quality$1.qualityScore,
1434
1437
  agent,
1435
1438
  ...effectiveModel !== void 0 && { model: effectiveModel }
@@ -1445,7 +1448,7 @@ var DispatcherImpl = class {
1445
1448
  id,
1446
1449
  status: "completed",
1447
1450
  exitCode: code,
1448
- output: stdout,
1451
+ output: effectiveStdout,
1449
1452
  parsed: null,
1450
1453
  parseError: errMsg,
1451
1454
  adapterError: true,
@@ -1454,16 +1457,17 @@ var DispatcherImpl = class {
1454
1457
  durationMs,
1455
1458
  tokenEstimate: {
1456
1459
  input: inputTokens,
1457
- output: Math.ceil(stdout.length / CHARS_PER_TOKEN$3)
1460
+ output: Math.ceil(effectiveStdout.length / CHARS_PER_TOKEN$3)
1458
1461
  },
1459
- ...finalModel !== void 0 ? { model: finalModel } : {}
1462
+ ...finalModel !== void 0 ? { model: finalModel } : {},
1463
+ ...totalTurns !== void 0 ? { totalTurns } : {}
1460
1464
  });
1461
1465
  return;
1462
1466
  }
1463
1467
  const parseResult = parseYamlResult(normalizeResult.yaml, outputSchema);
1464
1468
  parsed = parseResult.parsed;
1465
1469
  parseError = parseResult.error;
1466
- const quality = estimateOutputQuality(stdout);
1470
+ const quality = estimateOutputQuality(effectiveStdout);
1467
1471
  if (quality.hedgingCount > 0 || quality.qualityScore < 40) this._logger.warn({
1468
1472
  id,
1469
1473
  agent,
@@ -1474,9 +1478,9 @@ var DispatcherImpl = class {
1474
1478
  this._eventBus.emit("agent:completed", {
1475
1479
  dispatchId: id,
1476
1480
  exitCode: code,
1477
- output: stdout,
1481
+ output: effectiveStdout,
1478
1482
  inputTokens,
1479
- outputTokens: Math.ceil(stdout.length / CHARS_PER_TOKEN$3),
1483
+ outputTokens: Math.ceil(effectiveStdout.length / CHARS_PER_TOKEN$3),
1480
1484
  qualityScore: quality.qualityScore,
1481
1485
  agent,
1482
1486
  ...effectiveModel !== void 0 && { model: effectiveModel }
@@ -1492,15 +1496,16 @@ var DispatcherImpl = class {
1492
1496
  id,
1493
1497
  status: "completed",
1494
1498
  exitCode: code,
1495
- output: stdout,
1499
+ output: effectiveStdout,
1496
1500
  parsed,
1497
1501
  parseError,
1498
1502
  durationMs,
1499
1503
  tokenEstimate: {
1500
1504
  input: inputTokens,
1501
- output: Math.ceil(stdout.length / CHARS_PER_TOKEN$3)
1505
+ output: Math.ceil(effectiveStdout.length / CHARS_PER_TOKEN$3)
1502
1506
  },
1503
- ...finalModel !== void 0 ? { model: finalModel } : {}
1507
+ ...finalModel !== void 0 ? { model: finalModel } : {},
1508
+ ...totalTurns !== void 0 ? { totalTurns } : {}
1504
1509
  });
1505
1510
  } else {
1506
1511
  const stderr = Buffer.concat(stderrChunks).toString("utf-8");
@@ -9495,8 +9500,8 @@ var ClaudeCodeAdapter = class ClaudeCodeAdapter {
9495
9500
  */
9496
9501
  static TESTED_CLI_VERSION_RANGE = {
9497
9502
  min: "2.1.152",
9498
- max: "2.1.158",
9499
- note: "Claude Code 2.x silently accepts but does not honor `--max-turns`; substrate no longer passes that flag."
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."
9500
9505
  };
9501
9506
  _logger;
9502
9507
  constructor(logger) {
@@ -9547,6 +9552,7 @@ var ClaudeCodeAdapter = class ClaudeCodeAdapter {
9547
9552
  model,
9548
9553
  "--dangerously-skip-permissions"
9549
9554
  ];
9555
+ args.push("--output-format", "stream-json", "--verbose");
9550
9556
  if (options.additionalFlags && options.additionalFlags.length > 0) args.push(...options.additionalFlags);
9551
9557
  const systemPromptParts = [BASE_SYSTEM_PROMPT];
9552
9558
  if (options.optimizationDirectives) systemPromptParts.push(`\n\n## Optimization Directives\n${options.optimizationDirectives}`);
@@ -9590,6 +9596,51 @@ var ClaudeCodeAdapter = class ClaudeCodeAdapter {
9590
9596
  };
9591
9597
  }
9592
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
+ /**
9593
9644
  * Build spawn command for plan generation.
9594
9645
  */
9595
9646
  buildPlanningCommand(request, options) {
@@ -11433,4 +11484,4 @@ async function callLLM(params) {
11433
11484
 
11434
11485
  //#endregion
11435
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 };
11436
- //# sourceMappingURL=dist-DnvGvKLu.js.map
11487
+ //# sourceMappingURL=dist-BWCudDcl.js.map
@@ -1,4 +1,4 @@
1
- import { AdtError } from "./dist-DnvGvKLu.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-i3s5sshZ.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-DnvGvKLu.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-DnvGvKLu.js";
3
- import { resolveMainRepoRoot, resolveRunManifest } from "./manifest-read-DJFbGhSd.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-2Kfa00-H.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-2Kfa00-H.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-DnvGvKLu.js";
4
- import "./manifest-read-DJFbGhSd.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
 
@@ -1347,6 +1347,30 @@ declare class ClaudeCodeAdapter implements WorkerAdapter {
1347
1347
  * Prompt is delivered via stdin (not CLI arg) to avoid E2BIG on large prompts.
1348
1348
  */
1349
1349
  buildCommand(prompt: string, options: AdapterOptions): SpawnCommand;
1350
+ /**
1351
+ * Pre-process `--output-format stream-json` stdout before YAML extraction (Story 81-9).
1352
+ *
1353
+ * Claude Code CLI with `--output-format stream-json` emits NDJSON events to stdout.
1354
+ * This method parses that stream to extract:
1355
+ * 1. `extractedText` — the full agent response from the terminal result event's
1356
+ * `result` field. Identical to raw text output; passed to AdapterOutputNormalizer.
1357
+ * 2. `totalTurns` — agentic turn count from `num_turns` in the result event.
1358
+ * This is the ONLY synchronous, reliable turn-count source available at
1359
+ * DispatchResult resolution time.
1360
+ *
1361
+ * Graceful fallbacks:
1362
+ * - If the stream cannot be parsed as NDJSON, returns `{ extractedText: stdout }`.
1363
+ * - If the result event is missing, returns `{ extractedText: stdout }`.
1364
+ * - If `num_turns` is absent from the event, returns without `totalTurns` (AC2:
1365
+ * "when the count is genuinely unavailable, leave the field absent, never fabricate").
1366
+ *
1367
+ * @param stdout Raw subprocess stdout (NDJSON event stream from Claude Code CLI)
1368
+ * @returns `{ extractedText, totalTurns? }` — text for YAML extraction and optional turn count
1369
+ */
1370
+ parseStreamOutput(stdout: string): {
1371
+ extractedText: string;
1372
+ totalTurns?: number;
1373
+ };
1350
1374
  /**
1351
1375
  * Build spawn command for plan generation.
1352
1376
  */
@@ -1560,4 +1584,4 @@ interface Recommendation {
1560
1584
 
1561
1585
  //#endregion
1562
1586
  export { AdapterDiscoveryResult, AdapterRegistry as AdapterRegistry$1, AdtError as AdtError$1, ClaudeCodeAdapter as ClaudeCodeAdapter$1, CodexCLIAdapter as CodexCLIAdapter$1, ConfigError as ConfigError$1, ConfigIncompatibleFormatError as ConfigIncompatibleFormatError$1, CoreEvents, DatabaseAdapter, DiscoveryReport, GeminiCLIAdapter as GeminiCLIAdapter$1, Recommendation, TypedEventBus };
1563
- //# sourceMappingURL=index-BJEANS9i.d.ts.map
1587
+ //# sourceMappingURL=index-BqVBOAO0.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AdapterDiscoveryResult, AdapterRegistry$1 as AdapterRegistry, AdtError$1 as AdtError, ClaudeCodeAdapter$1 as ClaudeCodeAdapter, CodexCLIAdapter$1 as CodexCLIAdapter, ConfigError$1 as ConfigError, ConfigIncompatibleFormatError$1 as ConfigIncompatibleFormatError, DiscoveryReport, GeminiCLIAdapter$1 as GeminiCLIAdapter, Recommendation, TypedEventBus } from "./index-BJEANS9i.js";
1
+ import { AdapterDiscoveryResult, AdapterRegistry$1 as AdapterRegistry, AdtError$1 as AdtError, ClaudeCodeAdapter$1 as ClaudeCodeAdapter, CodexCLIAdapter$1 as CodexCLIAdapter, ConfigError$1 as ConfigError, ConfigIncompatibleFormatError$1 as ConfigIncompatibleFormatError, DiscoveryReport, GeminiCLIAdapter$1 as GeminiCLIAdapter, Recommendation, TypedEventBus } from "./index-BqVBOAO0.js";
2
2
  import pino from "pino";
3
3
  import { z } from "zod";
4
4
  import { Readable, Writable } from "node:stream";
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { childLogger, createLogger, logger } from "./logger-KeHncl-f.js";
2
2
  import { assertDefined, createEventBus, createTuiApp, deepClone, formatDuration, generateId, isPlainObject, isTuiCapable, printNonTtyWarning, sleep, withRetry } from "./helpers-CElYrONe.js";
3
- import { AdapterRegistry, AdtError, ClaudeCodeAdapter, CodexCLIAdapter, ConfigError, ConfigIncompatibleFormatError, GeminiCLIAdapter } from "./dist-DnvGvKLu.js";
3
+ import { AdapterRegistry, AdtError, ClaudeCodeAdapter, CodexCLIAdapter, ConfigError, ConfigIncompatibleFormatError, GeminiCLIAdapter } from "./dist-BWCudDcl.js";
4
4
  import "./adapter-registry-DIcrxjH8.js";
5
- import { BudgetExceededError, GitError, RecoveryError, TaskConfigError, TaskGraphCycleError, TaskGraphError, TaskGraphIncompatibleFormatError, WorkerError, WorkerNotFoundError } from "./errors-i3s5sshZ.js";
5
+ import { BudgetExceededError, GitError, RecoveryError, TaskConfigError, TaskGraphCycleError, TaskGraphError, TaskGraphIncompatibleFormatError, WorkerError, WorkerNotFoundError } from "./errors-rZ-lz8U0.js";
6
6
 
7
7
  //#region src/core/di.ts
8
8
  /**
@@ -1,5 +1,5 @@
1
1
  import { createLogger } from "./logger-KeHncl-f.js";
2
- import { readCurrentRunId, resolveMainRepoRoot } from "./manifest-read-DJFbGhSd.js";
2
+ import { readCurrentRunId, resolveMainRepoRoot } from "./manifest-read-IvpNQ6Yy.js";
3
3
  import { join } from "node:path";
4
4
  import { mkdir, readFile, writeFile } from "node:fs/promises";
5
5
  import * as readline from "node:readline";
@@ -180,4 +180,4 @@ async function runInteractivePrompt(decisionContext) {
180
180
 
181
181
  //#endregion
182
182
  export { runInteractivePrompt };
183
- //# sourceMappingURL=interactive-prompt-B91mG5v4.js.map
183
+ //# sourceMappingURL=interactive-prompt-BypNgFHL.js.map
@@ -1,5 +1,5 @@
1
1
  import { createLogger } from "./logger-KeHncl-f.js";
2
- import { LEARNING_FINDING, createDecision, getDecisionsByCategory } from "./dist-DnvGvKLu.js";
2
+ import { LEARNING_FINDING, createDecision, getDecisionsByCategory } from "./dist-BWCudDcl.js";
3
3
  import * as path$1 from "path";
4
4
  import { join } from "path";
5
5
  import { readFile } from "fs/promises";
@@ -4659,9 +4659,23 @@ const PerStoryStateSchema = z.object({
4659
4659
  escalation_reason: z.string().optional(),
4660
4660
  escalation_detail: z.string().optional(),
4661
4661
  commit_sha: z.string().optional(),
4662
+ baseline_sha: z.string().optional(),
4663
+ checkpoint_sha: z.string().optional(),
4662
4664
  story_file: z.string().optional(),
4663
4665
  story_file_input_path: z.string().optional(),
4664
- story_file_sha256: z.string().optional()
4666
+ story_file_sha256: z.string().optional(),
4667
+ verdict: z.union([
4668
+ z.literal("SHIP_IT"),
4669
+ z.literal("LGTM_WITH_NOTES"),
4670
+ z.literal("NEEDS_MINOR_FIXES"),
4671
+ z.literal("NEEDS_MAJOR_REWORK"),
4672
+ z.string()
4673
+ ]).optional(),
4674
+ total_turns: z.number().int().nonnegative().optional(),
4675
+ total_tokens: z.object({
4676
+ input: z.number().int().nonnegative(),
4677
+ output: z.number().int().nonnegative()
4678
+ }).optional()
4665
4679
  });
4666
4680
 
4667
4681
  //#endregion
@@ -5851,4 +5865,4 @@ async function resolveRunManifest(dbRoot, runId) {
5851
5865
 
5852
5866
  //#endregion
5853
5867
  export { FindingsInjector, RunManifest, RuntimeProbeListSchema, SupervisorLock, ZERO_FINDINGS_BY_AUTHOR, ZERO_FINDING_COUNTS, ZERO_PROBE_AUTHOR_METRICS, aggregateProbeAuthorMetrics, applyConfigToGraph, createDefaultVerificationPipeline, createGraphOrchestrator, createSdlcCodeReviewHandler, createSdlcCreateStoryHandler, createSdlcDevStoryHandler, createSdlcPhaseHandler, detectsEventDrivenAC, detectsStateIntegratingAC, extractTargetFilesFromStoryContent, parseRuntimeProbes, readCurrentRunId, renderFindings, resolveGraphPath, resolveMainRepoRoot, resolveRunManifest, rollupFindingCounts, rollupFindingsByAuthor, rollupProbeAuthorByClass, rollupProbeAuthorMetrics, runAcTraceabilityCheck, runStaleVerificationRecovery };
5854
- //# sourceMappingURL=manifest-read-DJFbGhSd.js.map
5868
+ //# sourceMappingURL=manifest-read-IvpNQ6Yy.js.map
@@ -1,6 +1,6 @@
1
1
  import "../../logger-KeHncl-f.js";
2
- import "../../dist-DnvGvKLu.js";
3
- import "../../manifest-read-DJFbGhSd.js";
4
- import { runInteractivePrompt } from "../../interactive-prompt-B91mG5v4.js";
2
+ import "../../dist-BWCudDcl.js";
3
+ import "../../manifest-read-IvpNQ6Yy.js";
4
+ import { runInteractivePrompt } from "../../interactive-prompt-BypNgFHL.js";
5
5
 
6
6
  export { runInteractivePrompt };
@@ -1,4 +1,4 @@
1
- import { ModelRoutingConfigSchema, ProviderPolicySchema, RoutingConfigError, RoutingRecommender, RoutingResolver, RoutingTelemetry, RoutingTokenAccumulator, RoutingTuner, TASK_TYPE_PHASE_MAP, getModelTier, loadModelRoutingConfig } from "./dist-DnvGvKLu.js";
1
+ import { ModelRoutingConfigSchema, ProviderPolicySchema, RoutingConfigError, RoutingRecommender, RoutingResolver, RoutingTelemetry, RoutingTokenAccumulator, RoutingTuner, TASK_TYPE_PHASE_MAP, getModelTier, loadModelRoutingConfig } from "./dist-BWCudDcl.js";
2
2
  import "./routing-DFxoKHDt.js";
3
3
 
4
4
  export { loadModelRoutingConfig };
@@ -1,14 +1,14 @@
1
- import "./health-2Kfa00-H.js";
1
+ import "./health-BXVyiLiL.js";
2
2
  import "./logger-KeHncl-f.js";
3
3
  import "./helpers-CElYrONe.js";
4
- import "./dist-DnvGvKLu.js";
5
- import { normalizeGraphSummaryToStatus, registerRunCommand, resolveMaxReviewCycles, resolveProbeAuthorStateIntegrating, runRunAction, wireNdjsonEmitter } from "./run-Dbwlb4Md.js";
6
- import "./manifest-read-DJFbGhSd.js";
4
+ import "./dist-BWCudDcl.js";
5
+ import { normalizeGraphSummaryToStatus, registerRunCommand, resolveMaxReviewCycles, resolveProbeAuthorStateIntegrating, runRunAction, wireNdjsonEmitter } from "./run-eaZG_3rN.js";
6
+ import "./manifest-read-IvpNQ6Yy.js";
7
7
  import "./routing-DFxoKHDt.js";
8
8
  import "./work-graph-repository-DZyJv5pV.js";
9
9
  import "./decisions-CzSIEeGP.js";
10
10
  import "./decision-router-DblHY8se.js";
11
- import "./interactive-prompt-B91mG5v4.js";
11
+ import "./interactive-prompt-BypNgFHL.js";
12
12
  import "./recovery-engine-BKGBeBnW.js";
13
13
 
14
14
  export { runRunAction };