@multileaf/ai-workflow 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +11 -0
  3. package/dist/adapter.js +3 -3
  4. package/dist/artifact-paths.d.ts +16 -0
  5. package/dist/artifact-paths.js +51 -0
  6. package/dist/completion-report.d.ts +17 -0
  7. package/dist/completion-report.js +42 -0
  8. package/dist/dashboard.js +7 -1
  9. package/dist/decision.d.ts +15 -0
  10. package/dist/decision.js +63 -0
  11. package/dist/eval/brief.d.ts +7 -0
  12. package/dist/eval/brief.js +28 -0
  13. package/dist/eval/generated.d.ts +17 -0
  14. package/dist/eval/generated.js +41 -0
  15. package/dist/eval/git.d.ts +13 -0
  16. package/dist/eval/git.js +70 -0
  17. package/dist/eval/monitor.d.ts +32 -0
  18. package/dist/eval/monitor.js +66 -0
  19. package/dist/eval/policy.d.ts +8 -0
  20. package/dist/eval/policy.js +9 -0
  21. package/dist/eval/proposals.d.ts +48 -0
  22. package/dist/eval/proposals.js +202 -0
  23. package/dist/eval/scenarios.d.ts +100 -0
  24. package/dist/eval/scenarios.js +374 -0
  25. package/dist/eval/signals.d.ts +21 -0
  26. package/dist/eval/signals.js +155 -0
  27. package/dist/eval/types.d.ts +38 -0
  28. package/dist/eval/types.js +1 -0
  29. package/dist/eval/validate.d.ts +28 -0
  30. package/dist/eval/validate.js +66 -0
  31. package/dist/generator.d.ts +8 -1
  32. package/dist/generator.js +24 -1
  33. package/dist/risk-assess.d.ts +1 -1
  34. package/dist/risk-assess.js +26 -2
  35. package/dist/semantic.d.ts +19 -0
  36. package/dist/semantic.js +57 -0
  37. package/dist/services.d.ts +3 -0
  38. package/dist/telemetry.d.ts +6 -0
  39. package/dist/telemetry.js +14 -7
  40. package/dist/workflow.js +532 -68
  41. package/docs/backlog.md +13 -3
  42. package/docs/decision-model-evaluation.md +7 -2
  43. package/docs/opportunities/OPP-007-decision-findings-triage-scope-watch.md +1 -1
  44. package/docs/opportunities/OPP-008-embedding-covering-tests-judge-context.md +1 -1
  45. package/docs/opportunities/OPP-016-behavioral-eval-scenarios.md +1 -1
  46. package/docs/quality.md +15 -0
  47. package/docs/semantic-mapping.md +9 -0
  48. package/package.json +1 -1
  49. package/resources/evals/README.md +59 -0
  50. package/resources/evals/scenarios/approval-boundary-full.yml +42 -0
  51. package/resources/evals/scenarios/bugfix-process-entry.yml +41 -0
  52. package/resources/evals/scenarios/evaluator-draft-contract.yml +65 -0
  53. package/resources/evals/scenarios/light-lane-skips-durable-artifacts.yml +40 -0
  54. package/resources/evals/scenarios/rejection-regate.yml +74 -0
  55. package/resources/evals/scenarios/risk-escalation-high-risk-area.yml +45 -0
  56. package/resources/package.yaml +1 -0
  57. package/resources/skills/resource-evaluator.md +24 -0
  58. package/resources/skills/review-judge-a.md +4 -0
  59. package/resources/skills/review-judge-b.md +4 -0
  60. package/resources/skills/review-refuter.md +4 -0
  61. package/resources/skills/ticket.md +1 -1
package/dist/workflow.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
2
2
  import { homedir } from "node:os";
3
+ import { fileURLToPath } from "node:url";
3
4
  import { randomUUID } from "node:crypto";
4
5
  import { BASE_DIRECTORIES, WORKFLOW_DIRECTORY } from "./constants.js";
5
6
  import { detectTarget, isTarget, renderAiInit, describeResource, renderAiInitPath, renderResourcePath, } from "./adapter.js";
@@ -28,17 +29,26 @@ async function readStdin() {
28
29
  terminal.close();
29
30
  }
30
31
  }
31
- import { generateProjectResources } from "./generator.js";
32
+ import { generateProjectResources, generateProposalResource } from "./generator.js";
33
+ import { collectSignals, serializeEvidenceBundle, parseEvidenceBundle } from "./eval/signals.js";
34
+ import { renderBrief } from "./eval/brief.js";
35
+ import { harvestApprovalObservations, monitorSession } from "./eval/monitor.js";
36
+ import { collectGitSummary } from "./eval/git.js";
37
+ import { approveProposal, createEmptyStore, compactProposalStore, draftSignatureHash, parseProposalStore, recordOccurrence, rejectProposal, serializeProposalStore, suppressProposal, } from "./eval/proposals.js";
38
+ import { PROPOSAL_KINDS } from "./eval/types.js";
39
+ import { parseDrafts, validateDrafts } from "./eval/validate.js";
40
+ import { validateGeneratedResources } from "./eval/generated.js";
32
41
  import { detectDrift } from "./drift.js";
33
42
  import { parseManifest, serializeManifest } from "./manifest.js";
34
43
  import { createOwnedFile, parseOwnership, serializeOwnership, } from "./ownership.js";
35
44
  import { validatePackageContract } from "./package-contract.js";
36
45
  import { parseLock, resolvePackage, serializeLock } from "./lockfile.js";
46
+ import { defaultShellRunner, isHarnessAvailable, parseScenarioRegistry, runScenarios, serializeScenarioResults, } from "./eval/scenarios.js";
37
47
  import { executeVercelSkills, installVercelSkill, nodeCommandExecutor } from "./vercel-skills.js";
38
48
  import { scanProject } from "./scanner.js";
39
49
  import { readFactOverrides, saveSettingOverrides, saveSettingsSection } from "./settings.js";
40
- import { buildEvidenceTriageRequest, buildRecommendationRankingRequest, buildSemanticRerankRequest, createOllamaDecisionProvider, loadDecisionConfig, } from "./decision.js";
41
- import { buildSemanticIndex, createOllamaEmbeddingProvider, loadSemanticConfig, parseSemanticIndex, querySemanticIndex, rerankSemanticMatches, SEMANTIC_INDEX_PATH, serializeSemanticIndex, } from "./semantic.js";
50
+ import { buildEvidenceTriageRequest, buildFindingsTriageRequest, buildLaneScopeWatchRequest, checkFindingShapes, parseReviewFindings, buildRecommendationRankingRequest, buildSemanticRerankRequest, createOllamaDecisionProvider, loadDecisionConfig, } from "./decision.js";
51
+ import { buildSemanticIndex, createOllamaEmbeddingProvider, loadSemanticConfig, semanticRetrievalAvailable, parseSemanticIndex, buildCoveringTestQuery, querySemanticIndex, renderJudgeContext, rerankSemanticMatches, SEMANTIC_INDEX_PATH, serializeSemanticIndex, } from "./semantic.js";
42
52
  import { assertKnownPermissions, assertPermissions, assertPackagePermissions, serializePermissionReview, } from "./package-audit.js";
43
53
  import { planPackageUpdate } from "./package-updates.js";
44
54
  import { searchRegistry, serializeRegistry } from "./registry.js";
@@ -51,6 +61,8 @@ import { loadContextDelta, retrieveTaskContext } from "./context-retrieval.js";
51
61
  import { createSummaryCache, isSummaryFresh, parseSummaryCache, serializeSummaryCache, } from "./context-cache.js";
52
62
  import { parseTokenUsage, recordTokenUsage, serializeTokenUsage, summarizeUsageByModel, } from "./token-usage.js";
53
63
  import { APPROVAL_STAGES, PROCESS_IDS, processStages, isWorkflowProcess, assertWorkflowId, validateTaskTicket, approveStage, beginStageApproval, createApprovalLedger, getUnresolvedPrerequisites, invalidateStageAndDescendants, parseApprovalLedger, parseWorkflowSession, rejectStage, serializeApprovalLedger, serializeWorkflowSession, skipOptionalStage, stageDefinition, stageFingerprint, effectiveLane, } from "./human-approval.js";
64
+ import { buildCompletionReport } from "./completion-report.js";
65
+ import { archiveWorkflowArtifacts, resolveStageArtifact, stageArtifactPaths, } from "./artifact-paths.js";
54
66
  import { parse as parseYaml, stringify } from "yaml";
55
67
  import { measureContextQuality, serializeContextQuality } from "./context-quality.js";
56
68
  import { collectContextBench, compareContextBench, parseContextBench, serializeContextBench, } from "./context-benchmark.js";
@@ -87,7 +99,7 @@ function stateMismatch(detail) {
87
99
  import { parseMigrationCheckpoint, planNeutralResourceMigration, readResourceBytes, serializeMigrationPreview, serializeMigrationCheckpoint, validateNeutralResourceDocument, writeResourceBytes, } from "./migration.js";
88
100
  import { parsePrivateRegistries, parseTeamPreset, serializePrivateRegistries, serializeTeamPreset, fetchPrivateRegistryClient, } from "./team-configuration.js";
89
101
  import { enforcePolicyGate, gitPolicyTracking } from "./policy-gate.js";
90
- import { DEFAULT_TELEMETRY_CONFIG, loadTelemetryConfig, offerTelemetryConsent, parseTelemetryConfig, purgeTelemetryBuffer, readTelemetryBuffer, serializeTelemetryMapping, TELEMETRY_BUFFER_CAP, TELEMETRY_BUFFER_FILE, } from "./telemetry.js";
102
+ import { DEFAULT_TELEMETRY_CONFIG, loadTelemetryConfig, offerTelemetryConsent, maybeOfferTelemetryConsent, parseTelemetryConfig, purgeTelemetryBuffer, readTelemetryBuffer, serializeTelemetryMapping, TELEMETRY_BUFFER_CAP, TELEMETRY_BUFFER_FILE, } from "./telemetry.js";
91
103
  import { createPluginScaffold, validatePluginDirectory, writePluginScaffold, } from "./plugin-sdk.js";
92
104
  import { createTaskWorktrees, executeOrchestrationPlan, forecastIntegration, listManagedWorktrees, currentBranch, parseOrchestrationResults, removeWorktrees, parseOrchestrationPlan, serializeOrchestrationPreview, serializeOrchestrationResults, validateOrchestrationParallelism, } from "./orchestration.js";
93
105
  function laneAdvisory(root, fs, lightChosen) {
@@ -104,6 +116,68 @@ function laneAdvisory(root, fs, lightChosen) {
104
116
  return "advisory: current changes look passive; the light lane (--lane=light --lane-reason=...) may be viable for small work.";
105
117
  return undefined;
106
118
  }
119
+ /** FRIC-002: allocate the next LOCAL-### ticket from current and archived sessions. */
120
+ function nextLocalTicket(fs, aiw) {
121
+ let max = 0;
122
+ const consider = (text) => {
123
+ for (const match of text.matchAll(/^\s*ticket:\s*(LOCAL-(\d+)\s*)$/gm))
124
+ max = Math.max(max, Number(match[2]));
125
+ };
126
+ const sessionPath = join(aiw, "workflow.yml");
127
+ if (fs.exists(sessionPath))
128
+ consider(fs.read(sessionPath));
129
+ const checkpoints = join(aiw, "checkpoints");
130
+ if (fs.exists(checkpoints) && fs.list)
131
+ for (const name of fs.list(checkpoints) ?? [])
132
+ if (name.startsWith("workflow-") && name.endsWith("-session.yml"))
133
+ consider(fs.read(join(checkpoints, name)));
134
+ return `LOCAL-${String(max + 1).padStart(3, "0")}`;
135
+ }
136
+ /** FRIC-005: workflow id of the recorded session, if any. */
137
+ function activeWorkflowId(fs, aiw) {
138
+ const sessionPath = join(aiw, "workflow.yml");
139
+ if (!fs.exists(sessionPath))
140
+ return undefined;
141
+ try {
142
+ return parseWorkflowSession(fs.read(sessionPath)).workflowId;
143
+ }
144
+ catch {
145
+ return undefined;
146
+ }
147
+ }
148
+ /** FRIC-005: write path for a stage artifact — scoped when a workflow is active. */
149
+ function stageArtifactWritePath(fs, aiw, stage) {
150
+ const { scoped, legacy } = stageArtifactPaths(aiw, stage, activeWorkflowId(fs, aiw));
151
+ return scoped ?? legacy;
152
+ }
153
+ /** FRIC-003: gather recorded usage/cost data and write the completion report. Never blocks completion. */
154
+ async function writeCompletionReport(fs, aiw, session, ledger) {
155
+ const scope = session.ticket ?? session.workflowId;
156
+ let usage;
157
+ let attribution;
158
+ try {
159
+ const sidecarPath = join(aiw, USAGE_SIDECAR_PATH);
160
+ if (fs.exists(sidecarPath))
161
+ usage = summarizeTaskUsage(parseUsageSidecar(fs.read(sidecarPath)), scope);
162
+ const tracePath = resolveStageArtifact(fs, aiw, "traceability", session.workflowId).path;
163
+ if (usage && fs.exists(tracePath))
164
+ attribution = computeCostAttribution(parseUsageSidecar(fs.read(sidecarPath)), parseTraceabilityGraph(fs.read(tracePath)));
165
+ }
166
+ catch {
167
+ // REQ-003: unreadable usage data degrades to an advisory, never blocks completion.
168
+ }
169
+ const report = buildCompletionReport({ session, ledger, usage, attribution });
170
+ try {
171
+ const reportDir = join(aiw, "generated/reports");
172
+ if (!fs.exists(reportDir))
173
+ fs.mkdir(reportDir);
174
+ fs.write(join(reportDir, `usage-${session.workflowId}.md`), report.markdown);
175
+ }
176
+ catch {
177
+ // REQ-003: a failed artifact write never blocks completion.
178
+ }
179
+ return report.consoleSummary;
180
+ }
107
181
  function beginWorkflowSession(fs, aiw, options) {
108
182
  const sessionPath = join(aiw, "workflow.yml");
109
183
  const ledgerPath = join(aiw, "approvals.yml");
@@ -165,21 +239,17 @@ export async function runCommand(args, root, fs, services = {}) {
165
239
  if (command === "task") {
166
240
  if (!fs.exists(join(aiw, "manifest.yml")))
167
241
  return installationRequired();
168
- const usage = "Usage: aiw task start --ticket=TEAM-123 [--title=text] [--id=workflow-id] [--lane=light --lane-reason=text] | aiw task status | aiw task escalate --reason=text | aiw task evidence --validation=text";
242
+ const usage = "Usage: aiw task start --ticket=TEAM-123 [--title=text] [--id=workflow-id] [--lane=light --lane-reason=text] | aiw task start [--no-ticket] [--title=text] ... | aiw task status | aiw task escalate --reason=text | aiw task evidence --validation=text";
169
243
  const action = args[1];
170
244
  const sessionPath = join(aiw, "workflow.yml");
171
245
  if (action === "start") {
172
- const options = parseNamedOptions(args.slice(2), [
173
- "ticket",
174
- "title",
175
- "id",
176
- "lane",
177
- "lane-reason",
178
- "process",
179
- ]);
180
- if (!options?.ticket)
246
+ const noTicket = args.slice(2).includes("--no-ticket");
247
+ const options = parseNamedOptions(args.slice(2).filter((argument) => argument !== "--no-ticket"), ["ticket", "title", "id", "lane", "lane-reason", "process"]);
248
+ if (!options || (noTicket && options.ticket))
181
249
  return { exitCode: 1, error: usage };
182
- validateTaskTicket(options.ticket);
250
+ // FRIC-002: no ticket given (or --no-ticket) — self-serve a local ticket.
251
+ const resolvedTicket = options.ticket ?? nextLocalTicket(fs, aiw);
252
+ validateTaskTicket(resolvedTicket);
183
253
  const processName = options.process;
184
254
  if (processName !== undefined) {
185
255
  if (!isWorkflowProcess(processName))
@@ -219,7 +289,7 @@ export async function runCommand(args, root, fs, services = {}) {
219
289
  const lane = options.lane === "light" ? "light" : undefined;
220
290
  const result = beginWorkflowSession(fs, aiw, {
221
291
  ...(options.id ? { id: options.id } : {}),
222
- ticket: options.ticket,
292
+ ticket: resolvedTicket,
223
293
  ...(options.title ? { title: options.title } : {}),
224
294
  ...(lane ? { lane, laneReason: laneReason } : {}),
225
295
  ...(processName ? { process: processName } : {}),
@@ -231,7 +301,7 @@ export async function runCommand(args, root, fs, services = {}) {
231
301
  if (lane)
232
302
  return {
233
303
  exitCode: 0,
234
- output: `Task started for ticket ${options.ticket}${title} (light lane): ${result.output}\n` +
304
+ output: `Task started for ticket ${resolvedTicket}${title} (light lane): ${result.output}\n` +
235
305
  (advisory ? `${advisory}\n` : "") +
236
306
  "Resume test: this work is small when it is understood, risk is contained, and the work could be resumed from your request plus `git diff`.\n" +
237
307
  `Rationale recorded: ${laneReason}\n` +
@@ -239,9 +309,9 @@ export async function runCommand(args, root, fs, services = {}) {
239
309
  };
240
310
  return {
241
311
  exitCode: 0,
242
- output: `Task started for ticket ${options.ticket}${title}: ${result.output}\n` +
312
+ output: `Task started for ticket ${resolvedTicket}${title}: ${result.output}\n` +
243
313
  (advisory ? `${advisory}\n` : "") +
244
- `Next steps: ask the user whether the requirement is clear enough to skip brainstorming (record an accepted skip with \`aiw skip brainstorming --reason="Requirement provided by ticket ${options.ticket}"\`), then create the specification with \`aiw spec --ticket=${options.ticket} --title=...\`.`,
314
+ `Next steps: ask the user whether the requirement is clear enough to skip brainstorming (record an accepted skip with \`aiw skip brainstorming --reason="Requirement provided by ticket ${resolvedTicket}"\`), then create the specification with \`aiw spec --ticket=${resolvedTicket} --title=...\`.`,
245
315
  };
246
316
  }
247
317
  if (action === "escalate") {
@@ -439,9 +509,53 @@ export async function runCommand(args, root, fs, services = {}) {
439
509
  status: "complete",
440
510
  updatedAt: new Date().toISOString(),
441
511
  }));
512
+ const lightSummary = await writeCompletionReport(fs, aiw, session, ledger);
513
+ const lightArchive = archiveWorkflowArtifacts(fs, aiw, session.workflowId);
514
+ // OPP-007 REQ-003/004: lane mismatch note (always) + optional model scope-watch.
515
+ const laneNotes = [];
516
+ const mismatch = laneAdvisory(root, fs, true);
517
+ if (mismatch)
518
+ laneNotes.push(mismatch);
519
+ const decisionConfig = loadDecisionConfig(fs, aiw);
520
+ if (decisionConfig?.enabled) {
521
+ const provider = services.decisionProvider ?? createOllamaDecisionProvider(decisionConfig);
522
+ try {
523
+ if (await provider.available()) {
524
+ const paths = collectWorkingTreeChanges(root) ?? [];
525
+ const response = await provider.decide(buildLaneScopeWatchRequest(paths.join("\n") || "no working-tree changes"));
526
+ laneNotes.push(`advisory scope-watch: multi_subsystem=${response.answers.multi_subsystem?.choice ?? "unclear"} (advisory-only)`);
527
+ }
528
+ }
529
+ catch {
530
+ // Advisory flow: provider failures degrade silently.
531
+ }
532
+ }
533
+ if (laneNotes.length) {
534
+ const evidenceFile = fs.exists(evidencePath)
535
+ ? parseLightEvidence(fs.read(evidencePath))
536
+ : null;
537
+ const advisories = laneNotes;
538
+ fs.write(evidencePath, stringify({
539
+ ...(evidenceFile ?? {
540
+ schema: 1,
541
+ workflowId: session.workflowId,
542
+ ...(session.ticket ? { ticket: session.ticket } : {}),
543
+ lane: "light",
544
+ ...(session.laneReason ? { laneReason: session.laneReason } : {}),
545
+ entries: [],
546
+ }),
547
+ advisories,
548
+ }, { lineWidth: 0 }));
549
+ }
442
550
  return {
443
551
  exitCode: 0,
444
- output: `Workflow completed (light lane): ${session.workflowId}. Evidence: ${evidencePath}`,
552
+ output: `Workflow completed (light lane): ${session.workflowId}. Evidence: ${evidencePath}\n` +
553
+ `${lightSummary}\n` +
554
+ `Report: ${join(aiw, `generated/reports/usage-${session.workflowId}.md`)}` +
555
+ (lightArchive.length
556
+ ? `\nArchived ${lightArchive.length} workflow artifact(s) to checkpoints/workflow-${session.workflowId}-artifacts/.`
557
+ : "") +
558
+ (laneNotes.length ? `\n${laneNotes.join("\n")}` : ""),
445
559
  };
446
560
  }
447
561
  const unresolved = processStages(ledger).filter((stage) => ledger.stages[stage]?.status !== "approved" &&
@@ -456,7 +570,17 @@ export async function runCommand(args, root, fs, services = {}) {
456
570
  status: "complete",
457
571
  updatedAt: new Date().toISOString(),
458
572
  }));
459
- return { exitCode: 0, output: `Workflow completed: ${session.workflowId}.` };
573
+ const fullSummary = await writeCompletionReport(fs, aiw, session, ledger);
574
+ const fullArchive = archiveWorkflowArtifacts(fs, aiw, session.workflowId);
575
+ return {
576
+ exitCode: 0,
577
+ output: `Workflow completed: ${session.workflowId}.\n` +
578
+ `${fullSummary}\n` +
579
+ `Report: ${join(aiw, `generated/reports/usage-${session.workflowId}.md`)}` +
580
+ (fullArchive.length
581
+ ? `\nArchived ${fullArchive.length} workflow artifact(s) to checkpoints/workflow-${session.workflowId}-artifacts/.`
582
+ : ""),
583
+ };
460
584
  }
461
585
  return {
462
586
  exitCode: 1,
@@ -489,11 +613,11 @@ export async function runCommand(args, root, fs, services = {}) {
489
613
  fs.write(join(aiw, "approvals.yml"), serializeApprovalLedger(updated));
490
614
  return { exitCode: 0, output: `Human-approved skip recorded for ${workflowStage}.` };
491
615
  }
492
- const artifact = approvalArtifactPath(aiw, workflowStage);
616
+ const artifact = approvalArtifactPath(fs, aiw, workflowStage);
493
617
  if (!artifact || !fs.exists(artifact))
494
618
  throw new BlockingError(describeBlockingReason("approval_evidence_missing", {
495
619
  stage: workflowStage,
496
- artifactPath: artifact ?? undefined,
620
+ artifactPath: stageArtifactWritePath(fs, aiw, workflowStage),
497
621
  detail: `Approval evidence is missing for ${workflowStage}.`,
498
622
  }));
499
623
  const artifactHash = stageFingerprint(fs.read(artifact));
@@ -1131,7 +1255,7 @@ export async function runCommand(args, root, fs, services = {}) {
1131
1255
  };
1132
1256
  }
1133
1257
  if (command === "decision") {
1134
- const usage = "Usage: aiw decision triage --artifact=<path> | aiw decision status";
1258
+ const usage = "Usage: aiw decision triage --artifact=<path> | aiw decision findings-triage --findings=<path> | aiw decision status";
1135
1259
  const action = args[1];
1136
1260
  const config = loadDecisionConfig(fs, aiw);
1137
1261
  if (action === "status") {
@@ -1175,13 +1299,44 @@ export async function runCommand(args, root, fs, services = {}) {
1175
1299
  ].join("\n"),
1176
1300
  };
1177
1301
  }
1302
+ if (action === "findings-triage") {
1303
+ const parsed = parseNamedOptions(args.slice(2), ["findings"]);
1304
+ if (!parsed?.findings)
1305
+ return { exitCode: 1, error: usage };
1306
+ const findingsPath = safeProjectFile(root, parsed.findings, fs);
1307
+ if (!fs.exists(findingsPath))
1308
+ return { exitCode: 1, error: `Findings file not found: ${parsed.findings}` };
1309
+ const findings = parseReviewFindings(fs.read(findingsPath));
1310
+ const lines = [];
1311
+ const shapeIssues = checkFindingShapes(findings);
1312
+ lines.push(shapeIssues.length === 0
1313
+ ? "Shape check: all findings are well-formed."
1314
+ : `Shape check failures (deterministic):\n${shapeIssues.map((i) => ` - ${i}`).join("\n")}`);
1315
+ if (config?.enabled) {
1316
+ const provider = services.decisionProvider ?? createOllamaDecisionProvider(config);
1317
+ try {
1318
+ if (await provider.available()) {
1319
+ const decision = await provider.decide(buildFindingsTriageRequest(findings));
1320
+ lines.push("Advisory evidence triage (refuter still owns corroboration):");
1321
+ for (const finding of findings)
1322
+ if (finding.severity.toLowerCase() === "severe")
1323
+ lines.push(` - ${finding.id}: evidence_supported: ${decision.answers[finding.id]?.choice ?? "unclear"}`);
1324
+ }
1325
+ }
1326
+ catch {
1327
+ // Advisory flow: provider failures degrade to shape-check-only output.
1328
+ }
1329
+ }
1330
+ return { exitCode: 0, output: lines.join("\n") };
1331
+ }
1178
1332
  return { exitCode: 1, error: usage };
1179
1333
  }
1180
1334
  if (command === "semantic") {
1181
- const usage = "Usage: aiw semantic query --text=<query> [--rerank] | aiw semantic status";
1335
+ const usage = "Usage: aiw semantic query --text=<query> [--rerank] | aiw semantic judge-context --paths=a.ts,b.ts [--budget=N] | aiw semantic status";
1182
1336
  const action = args[1];
1337
+ const semanticConfig = loadSemanticConfig(fs, aiw);
1183
1338
  if (action === "status") {
1184
- const config = loadSemanticConfig(fs, aiw);
1339
+ const config = semanticConfig;
1185
1340
  if (!config)
1186
1341
  return {
1187
1342
  exitCode: 0,
@@ -1196,6 +1351,50 @@ export async function runCommand(args, root, fs, services = {}) {
1196
1351
  output: `Semantic mapping ${config.enabled ? "enabled" : "disabled"}: model ${config.model} at ${config.baseUrl}\n${built}`,
1197
1352
  };
1198
1353
  }
1354
+ if (action === "judge-context") {
1355
+ const parsed = parseNamedOptions(args.slice(2), ["paths", "budget"]);
1356
+ if (!parsed?.paths)
1357
+ return {
1358
+ exitCode: 1,
1359
+ error: "Usage: aiw semantic judge-context --paths=a.ts,b.ts [--budget=N]",
1360
+ };
1361
+ if (!semanticConfig?.enabled)
1362
+ return {
1363
+ exitCode: 1,
1364
+ error: "Semantic mapping is disabled. Set semantic.enabled=true in .aiw/settings.yml to use judge context.",
1365
+ };
1366
+ const config = semanticConfig;
1367
+ const indexPath = join(aiw, SEMANTIC_INDEX_PATH);
1368
+ if (!fs.exists(indexPath))
1369
+ return {
1370
+ exitCode: 1,
1371
+ error: "Semantic index is missing. Run aiw scan to build it before requesting judge context.",
1372
+ };
1373
+ const provider = services.embeddingProvider ?? createOllamaEmbeddingProvider(config);
1374
+ if (!(await provider.available()))
1375
+ return {
1376
+ exitCode: 1,
1377
+ error: `Semantic model ${config.model} is not available at ${config.baseUrl}. Judges fall back to the raw diff (fail-safe).`,
1378
+ };
1379
+ const paths = parsed.paths
1380
+ .split(",")
1381
+ .map((p) => p.trim())
1382
+ .filter(Boolean);
1383
+ const budget = Number(parsed.budget ?? 4000);
1384
+ if (!Number.isFinite(budget) || budget <= 0)
1385
+ return { exitCode: 1, error: "--budget must be a positive number." };
1386
+ const chunks = [];
1387
+ for (const path of paths) {
1388
+ const matches = await querySemanticIndex(parseSemanticIndex(fs.read(indexPath)), buildCoveringTestQuery(path), provider, config);
1389
+ for (const match of matches)
1390
+ chunks.push({ file: match.file, excerpt: match.excerpt });
1391
+ }
1392
+ return {
1393
+ exitCode: 0,
1394
+ output: renderJudgeContext("## Changed paths\n" + paths.join("\n"), chunks, budget) +
1395
+ "\n(context aids only — retrieval results are never confirmed facts)",
1396
+ };
1397
+ }
1199
1398
  if (action === "query") {
1200
1399
  const queryArgs = args.slice(2).filter((arg) => arg !== "--rerank");
1201
1400
  const rerankRequested = args.slice(2).includes("--rerank");
@@ -1824,7 +2023,7 @@ export async function runCommand(args, root, fs, services = {}) {
1824
2023
  return;
1825
2024
  }
1826
2025
  fs.write(destination, content);
1827
- });
2026
+ }, semanticRetrievalAvailable(fs, aiw));
1828
2027
  return {
1829
2028
  exitCode: conflicts.length ? 1 : 0,
1830
2029
  output: conflicts.length
@@ -1851,6 +2050,246 @@ export async function runCommand(args, root, fs, services = {}) {
1851
2050
  return { exitCode: 1, error: error instanceof Error ? error.message : String(error) };
1852
2051
  }
1853
2052
  }
2053
+ if (command === "eval") {
2054
+ const usage = "Usage: aiw eval run --scenarios [--registry=dir] [--harness=id] [--filter=id] [--advisory]";
2055
+ if (args[1] !== "run" || !args.includes("--scenarios"))
2056
+ return { exitCode: 1, error: usage };
2057
+ const options = parseNamedOptions(args.slice(2).filter((arg) => arg !== "--scenarios" && arg !== "--advisory"), ["registry", "harness", "filter"]);
2058
+ if (options === undefined)
2059
+ return { exitCode: 1, error: usage };
2060
+ const advisory = args.includes("--advisory");
2061
+ const registryDir = options.registry
2062
+ ? resolve(root, options.registry)
2063
+ : resolve(dirname(fileURLToPath(import.meta.url)), "../resources/evals/scenarios");
2064
+ if (!fs.exists(registryDir))
2065
+ return { exitCode: 1, error: `Scenario registry not found: ${registryDir}` };
2066
+ const files = (fs.list?.(registryDir) ?? []).filter((name) => name.endsWith(".yml")).sort();
2067
+ let scenarios;
2068
+ try {
2069
+ scenarios = parseScenarioRegistry(files.map((name) => ({
2070
+ path: name,
2071
+ content: fs.read(join(registryDir, name)),
2072
+ })));
2073
+ }
2074
+ catch (error) {
2075
+ return { exitCode: 1, error: error instanceof Error ? error.message : String(error) };
2076
+ }
2077
+ if (options.harness)
2078
+ scenarios = scenarios.filter(({ harness }) => harness === options.harness);
2079
+ if (options.filter)
2080
+ scenarios = scenarios.filter(({ id, family }) => id.includes(options.filter) || family.includes(options.filter));
2081
+ if (scenarios.length === 0)
2082
+ return { exitCode: 0, output: "No scenarios matched; nothing to run.\n" };
2083
+ const budgetsPath = join(aiw, "budgets.yml");
2084
+ let poolTokenCeiling;
2085
+ if (fs.exists(budgetsPath)) {
2086
+ const budgets = parseYaml(fs.read(budgetsPath));
2087
+ const evals = budgets?.evals;
2088
+ const ceiling = Number(evals?.tokenCeiling);
2089
+ if (Number.isFinite(ceiling) && ceiling > 0)
2090
+ poolTokenCeiling = ceiling;
2091
+ }
2092
+ const report = await runScenarios({
2093
+ scenarios,
2094
+ runShell: defaultShellRunner,
2095
+ isAvailable: (harness) => isHarnessAvailable(harness),
2096
+ poolTokenCeiling,
2097
+ });
2098
+ const resultsPath = join(aiw, "generated", "evals", "scenario-results.yml");
2099
+ fs.write(resultsPath, serializeScenarioResults(report));
2100
+ const lines = report.results.map((result) => `${result.scenario}: ${result.status}${result.usage ? ` (tokens in ${result.usage.tokensIn}, out ${result.usage.tokensOut})` : ""} — ${result.detail}`);
2101
+ if (report.missingHarnesses.length)
2102
+ lines.push(`skipped for missing harness CLIs: ${report.missingHarnesses.join(", ")} — install them to run those scenarios`);
2103
+ lines.push(`results written to ${relative(root, resultsPath)}`);
2104
+ const blocking = report.results.filter(({ status }) => status === "failed" || status.startsWith("aborted-")).length;
2105
+ const exitCode = blocking > 0 && !advisory ? 1 : 0;
2106
+ return {
2107
+ exitCode,
2108
+ output: `${lines.join("\n")}\n${advisory && blocking > 0 ? `${blocking} scenario(s) failed (advisory mode: exit 0).\n` : ""}`,
2109
+ };
2110
+ }
2111
+ if (command === "evaluate") {
2112
+ const scanFiles = await (services.scanner?.scan(root) ?? scanProject(root));
2113
+ const gitSummary = await collectGitSummary(root, services.runShell ?? defaultShellRunner);
2114
+ const bundle = collectSignals(scanFiles.files, gitSummary, (path) => fs.exists(join(root, path)) ? fs.read(join(root, path)) : "");
2115
+ const evalDir = join(aiw, "eval");
2116
+ const signalsPath = join(evalDir, "signals.yml");
2117
+ const briefPath = join(evalDir, "brief.md");
2118
+ const draftsPath = join(evalDir, "proposals-draft.yml");
2119
+ // A4: drafts written against a previous signal set must not survive a
2120
+ // re-evaluation; the skill re-drafts from the fresh brief.
2121
+ if (fs.exists(draftsPath))
2122
+ fs.remove?.(draftsPath);
2123
+ fs.write(signalsPath, serializeEvidenceBundle(bundle));
2124
+ fs.write(briefPath, renderBrief(bundle));
2125
+ return {
2126
+ exitCode: 0,
2127
+ output: `signals written to ${relative(root, signalsPath)}\nhand off ${relative(root, briefPath)} to the resource-evaluator skill\n`,
2128
+ };
2129
+ }
2130
+ if (command === "proposals") {
2131
+ const usage = "Usage: aiw proposals <import|list|show|approve|reject|suppress|validate> [--id=id] [--reason=text]";
2132
+ const action = args[1];
2133
+ const storePath = join(aiw, "proposals.yml");
2134
+ const loadStore = () => {
2135
+ if (!fs.exists(storePath))
2136
+ throw new Error("No proposals store found; run `aiw proposals import` first.");
2137
+ return parseProposalStore(fs.read(storePath));
2138
+ };
2139
+ if (action === "import") {
2140
+ const signalsPath = join(aiw, "eval", "signals.yml");
2141
+ const draftsPath = join(aiw, "eval", "proposals-draft.yml");
2142
+ if (!fs.exists(signalsPath) || !fs.exists(draftsPath))
2143
+ return {
2144
+ exitCode: 1,
2145
+ error: "Run `aiw evaluate` and the resource-evaluator skill first.",
2146
+ };
2147
+ const bundle = parseEvidenceBundle(fs.read(signalsPath));
2148
+ let drafts;
2149
+ try {
2150
+ drafts = parseDrafts(fs.read(draftsPath));
2151
+ }
2152
+ catch (error) {
2153
+ return { exitCode: 1, error: error instanceof Error ? error.message : String(error) };
2154
+ }
2155
+ const target = detectTarget(root, fs) || "codex";
2156
+ const catalogIds = loadBundledResources(target).map(({ type, id }) => `${type}/${id}`);
2157
+ const validation = validateDrafts(drafts, bundle, catalogIds);
2158
+ if (validation.errors.length)
2159
+ return {
2160
+ exitCode: 1,
2161
+ error: `${validation.errors.length} draft record(s) failed the contract:\n${validation.errors
2162
+ .map(({ record, reason }) => `- ${record}: ${reason.join("; ")}`)
2163
+ .join("\n")}`,
2164
+ };
2165
+ const store = fs.exists(storePath)
2166
+ ? parseProposalStore(fs.read(storePath))
2167
+ : createEmptyStore();
2168
+ const isUnchanged = (record) => {
2169
+ const hash = draftSignatureHash(record);
2170
+ const existing = store.proposals.find((candidate) => candidate.signature === record.signature);
2171
+ return existing?.draftHash === hash;
2172
+ };
2173
+ const changed = validation.records.filter((record) => !isUnchanged(record));
2174
+ for (const record of validation.records) {
2175
+ if (isUnchanged(record))
2176
+ continue;
2177
+ recordOccurrence(store, {
2178
+ kind: record.kind,
2179
+ signature: record.signature,
2180
+ origin: "onboarding",
2181
+ });
2182
+ const proposal = store.proposals.find((candidate) => candidate.signature === record.signature);
2183
+ if (proposal) {
2184
+ proposal.title = record.title;
2185
+ proposal.outline = record.outline;
2186
+ proposal.evidence = record.evidence;
2187
+ proposal.kind = record.kind;
2188
+ proposal.draftHash = draftSignatureHash(record);
2189
+ }
2190
+ }
2191
+ if (changed.length === 0)
2192
+ return {
2193
+ exitCode: 0,
2194
+ output: `no proposals to import${fs.exists(storePath)
2195
+ ? " — drafts unchanged since the last import"
2196
+ : " — the evaluator proposed nothing for this project"}\n`,
2197
+ };
2198
+ fs.write(storePath, serializeProposalStore(store));
2199
+ const overlapNote = validation.overlaps.length
2200
+ ? `\noverlaps annotated for review: ${validation.overlaps
2201
+ .map(({ signature, catalogId }) => `${signature} ~ ${catalogId}`)
2202
+ .join(", ")}`
2203
+ : "";
2204
+ return {
2205
+ exitCode: 0,
2206
+ output: `imported ${changed.length} proposal(s) into ${relative(root, storePath)}${overlapNote}\n`,
2207
+ };
2208
+ }
2209
+ if (action === "list") {
2210
+ const store = loadStore();
2211
+ if (store.proposals.length === 0)
2212
+ return { exitCode: 0, output: "No proposals recorded.\n" };
2213
+ const lines = store.proposals.map((proposal) => `${proposal.id} [${proposal.kind}] ${proposal.status} (${proposal.occurrences} occurrences) ${proposal.title || proposal.signature}`);
2214
+ return { exitCode: 0, output: `${lines.join("\n")}\n` };
2215
+ }
2216
+ if (action === "validate") {
2217
+ const generatedRoot = join(aiw, "generated");
2218
+ const files = [];
2219
+ for (const kind of PROPOSAL_KINDS) {
2220
+ const dir = join(generatedRoot, `${kind}s`);
2221
+ if (!fs.exists(dir))
2222
+ continue;
2223
+ for (const name of (fs.listFiles?.(dir) ?? fs.list?.(dir) ?? []).sort())
2224
+ if (name.endsWith(".md"))
2225
+ files.push({ path: `${kind}s/${name}`, content: fs.read(join(dir, name)) });
2226
+ }
2227
+ if (files.length === 0)
2228
+ return { exitCode: 0, output: "No generated resources to validate.\n" };
2229
+ if (!fs.exists(storePath))
2230
+ return {
2231
+ exitCode: 1,
2232
+ error: `Generated resources exist but no proposals store was found at ${relative(root, storePath)}.`,
2233
+ };
2234
+ const issues = validateGeneratedResources(files, loadStore());
2235
+ if (issues.length)
2236
+ return {
2237
+ exitCode: 1,
2238
+ error: `${issues.length} generated resource(s) failed validation:\n${issues
2239
+ .map(({ path, reason }) => `- ${path}: ${reason}`)
2240
+ .join("\n")}`,
2241
+ };
2242
+ return {
2243
+ exitCode: 0,
2244
+ output: `valid: ${files.length} generated resource(s) pass the evaluator contract.\n`,
2245
+ };
2246
+ }
2247
+ const options = parseNamedOptions(args.slice(2), ["id", "reason"]);
2248
+ if (options === undefined)
2249
+ return { exitCode: 1, error: usage };
2250
+ const id = options.id;
2251
+ if (action === "show") {
2252
+ if (!id)
2253
+ return { exitCode: 1, error: usage };
2254
+ const proposal = loadStore().proposals.find((candidate) => candidate.id === id);
2255
+ if (!proposal)
2256
+ return { exitCode: 1, error: `Unknown proposal id: ${id}` };
2257
+ return {
2258
+ exitCode: 0,
2259
+ output: [
2260
+ `${proposal.id} [${proposal.kind}] ${proposal.status}`,
2261
+ `title: ${proposal.title}`,
2262
+ `outline: ${proposal.outline}`,
2263
+ `evidence: ${proposal.evidence.join(", ")}`,
2264
+ `occurrences: ${proposal.occurrences}`,
2265
+ `reject_reason: ${proposal.rejectReason ?? "-"}`,
2266
+ ].join("\n") + "\n",
2267
+ };
2268
+ }
2269
+ if (!id)
2270
+ return { exitCode: 1, error: usage };
2271
+ if (action === "approve" || action === "reject" || action === "suppress") {
2272
+ const store = loadStore();
2273
+ if (action === "reject") {
2274
+ if (!options.reason)
2275
+ return { exitCode: 1, error: "--reason is required when rejecting a proposal." };
2276
+ rejectProposal(store, id, options.reason);
2277
+ }
2278
+ else if (action === "approve") {
2279
+ approveProposal(store, id);
2280
+ const approved = store.proposals.find((candidate) => candidate.id === id);
2281
+ if (approved && approved.title && approved.outline) {
2282
+ generateProposalResource(approved, (path, content) => fs.write(join(aiw, path), content));
2283
+ }
2284
+ }
2285
+ else
2286
+ suppressProposal(store, id);
2287
+ compactProposalStore(store);
2288
+ fs.write(storePath, serializeProposalStore(store));
2289
+ return { exitCode: 0, output: `${action} recorded for ${id}\n` };
2290
+ }
2291
+ return { exitCode: 1, error: usage };
2292
+ }
1854
2293
  if (command === "doctor") {
1855
2294
  const required = ["manifest.yml", "profile.yml", "lock.yml", "ownership.yml"];
1856
2295
  const missing = required.filter((file) => !fs.exists(join(aiw, file)));
@@ -1886,7 +2325,22 @@ export async function runCommand(args, root, fs, services = {}) {
1886
2325
  catch (error) {
1887
2326
  return { exitCode: 1, error: error instanceof Error ? error.message : String(error) };
1888
2327
  }
1889
- return { exitCode: 0, output: "AI Workflow health check passed." };
2328
+ // FRIC-004: interactive doctor offers telemetry consent once when unset.
2329
+ let telemetryNote = "";
2330
+ if (stdin.isTTY) {
2331
+ const terminal = createInterface({ input: stdin, output: stdout });
2332
+ try {
2333
+ const consent = await maybeOfferTelemetryConsent(fs, aiw, true, (question) => terminal.question(question));
2334
+ if (consent.prompted)
2335
+ telemetryNote = consent.enabled
2336
+ ? "\nTelemetry enabled. Disable anytime with `aiw telemetry disable`."
2337
+ : "\nTelemetry remains disabled. Enable anytime with `aiw telemetry enable`.";
2338
+ }
2339
+ finally {
2340
+ terminal.close();
2341
+ }
2342
+ }
2343
+ return { exitCode: 0, output: `AI Workflow health check passed.${telemetryNote}` };
1890
2344
  }
1891
2345
  if (command === "repair") {
1892
2346
  if (!fs.exists(join(aiw, "manifest.yml")))
@@ -1993,7 +2447,7 @@ export async function runCommand(args, root, fs, services = {}) {
1993
2447
  return installationRequired();
1994
2448
  assertStageReady(aiw, fs, "brainstorming");
1995
2449
  const title = args.find((arg) => arg.startsWith("--title="))?.slice(8) || "Untitled Brainstorm";
1996
- const path = join(aiw, "generated/specs/brainstorm.md");
2450
+ const path = stageArtifactWritePath(fs, aiw, "brainstorming");
1997
2451
  fs.write(path, `# ${title}\n\n## Goal\n\n## Users\n\n## Facts\n\n## Assumptions\n\n## Hypotheses\n\n## Constraints\n\n## Risks\n\n## Non-goals\n\n## Open Questions\n\n`);
1998
2452
  return { exitCode: 0, output: `Brainstorm artifact created: ${path}` };
1999
2453
  }
@@ -2005,7 +2459,7 @@ export async function runCommand(args, root, fs, services = {}) {
2005
2459
  const ticket = args.find((arg) => arg.startsWith("--ticket="))?.slice(9);
2006
2460
  if (ticket !== undefined)
2007
2461
  validateTaskTicket(ticket);
2008
- const path = join(aiw, "generated/specs/specification.md");
2462
+ const path = stageArtifactWritePath(fs, aiw, "specification");
2009
2463
  fs.write(path, `# ${title}\n${ticket ? `\n> Ticket: ${ticket}\n` : ""}\n## Context\n\n## Requirements\n\n### REQ-001: Requirement title\n\n- **Description:**\n- **Acceptance criteria:**\n - Given\n - When\n - Then\n\n## Non-functional Requirements\n\n## Constraints\n\n## Open Questions\n\n`);
2010
2464
  return { exitCode: 0, output: `Specification artifact created: ${path}` };
2011
2465
  }
@@ -2024,7 +2478,7 @@ export async function runCommand(args, root, fs, services = {}) {
2024
2478
  return installationRequired();
2025
2479
  assertStageReady(aiw, fs, "plan");
2026
2480
  const title = args.find((arg) => arg.startsWith("--title="))?.slice(8) || "Untitled Implementation Plan";
2027
- const path = join(aiw, "generated/plans/implementation-plan.md");
2481
+ const path = stageArtifactWritePath(fs, aiw, "plan");
2028
2482
  fs.write(path, `# ${title}\n\n## Linked Requirements\n\n- REQ-001: Link to the specification requirement.\n\n## Tasks\n\n- [ ] TASK-001: Implement the first increment.\n - Requirement: REQ-001\n - Code: src/\n - Tests: src/**/*.test.ts\n - Validation: npm test → exit 0\n - Regression: <optional — touched existing behavior → the test proving it holds>\n - Evidence: Record the passing command output and changed files.\n\n## Validation Commands\n\n- npm run check\n\n## Risks and Dependencies\n\n- Dependencies: List prerequisite tasks, packages, or decisions.\n- Risks: Record delivery, compatibility, and validation risks with mitigations.\n\n## Completion Evidence\n\n- TASK-001: Link code changes, test results, and validation output.\n\n`);
2029
2483
  return { exitCode: 0, output: `Implementation plan created: ${path}` };
2030
2484
  }
@@ -2032,8 +2486,8 @@ export async function runCommand(args, root, fs, services = {}) {
2032
2486
  if (!fs.exists(join(aiw, "manifest.yml")))
2033
2487
  return installationRequired();
2034
2488
  assertStageReady(aiw, fs, "verification");
2035
- const specPath = join(aiw, "generated/specs/specification.md");
2036
- const planPath = join(aiw, "generated/plans/implementation-plan.md");
2489
+ const specPath = resolveStageArtifact(fs, aiw, "specification", activeWorkflowId(fs, aiw)).path;
2490
+ const planPath = resolveStageArtifact(fs, aiw, "plan", activeWorkflowId(fs, aiw)).path;
2037
2491
  const issues = [];
2038
2492
  let regressionNotice;
2039
2493
  let specification = "";
@@ -2073,8 +2527,8 @@ export async function runCommand(args, root, fs, services = {}) {
2073
2527
  if (!fs.exists(join(aiw, "manifest.yml")))
2074
2528
  return installationRequired();
2075
2529
  assertStageReady(aiw, fs, "traceability");
2076
- const specPath = join(aiw, "generated/specs/specification.md");
2077
- const planPath = join(aiw, "generated/plans/implementation-plan.md");
2530
+ const specPath = resolveStageArtifact(fs, aiw, "specification", activeWorkflowId(fs, aiw)).path;
2531
+ const planPath = resolveStageArtifact(fs, aiw, "plan", activeWorkflowId(fs, aiw)).path;
2078
2532
  if (!fs.exists(specPath) || !fs.exists(planPath))
2079
2533
  return {
2080
2534
  exitCode: 1,
@@ -2096,7 +2550,7 @@ export async function runCommand(args, root, fs, services = {}) {
2096
2550
  const serialized = serializeTraceabilityGraph(graph, requirement);
2097
2551
  if (requirement)
2098
2552
  return { exitCode: 0, output: serialized };
2099
- const path = join(aiw, "generated/artifacts/traceability.yml");
2553
+ const path = stageArtifactWritePath(fs, aiw, "traceability");
2100
2554
  fs.write(path, serialized);
2101
2555
  return { exitCode: 0, output: `Traceability graph created: ${path}` };
2102
2556
  }
@@ -2269,7 +2723,7 @@ export async function runCommand(args, root, fs, services = {}) {
2269
2723
  const lines = [];
2270
2724
  let served = 0;
2271
2725
  for (const stage of stages) {
2272
- const artifactPath = approvalArtifactPath(aiw, stage);
2726
+ const artifactPath = approvalArtifactPath(fs, aiw, stage);
2273
2727
  const freshness = digestFreshness(aiw, fs, stage, artifactPath ?? undefined);
2274
2728
  if (freshness.state === "missing")
2275
2729
  continue;
@@ -2289,7 +2743,7 @@ export async function runCommand(args, root, fs, services = {}) {
2289
2743
  return installationRequired();
2290
2744
  assertStageReady(aiw, fs, "diagnosis");
2291
2745
  const title = args.find((argument) => argument.startsWith("--title="))?.slice(8) || "Untitled Diagnosis";
2292
- const path = join(aiw, "generated/reports/diagnosis.md");
2746
+ const path = stageArtifactWritePath(fs, aiw, "diagnosis");
2293
2747
  fs.write(path, `# ${title}\n\n## Reproduction\n\n- Command: \`<command that reproduces the bug>\`\n- Observed: <what actually happens>\n\n## Expected\n\n- <the correct behavior>\n\n## Root Cause\n\n- <evidence-backed cause, file:line when known>\n\n## Scope\n\n- In scope: <files and behavior this fix touches>\n- Out of scope: <explicitly excluded>\n`);
2294
2748
  return { exitCode: 0, output: `Diagnosis artifact created: ${path}` };
2295
2749
  }
@@ -2298,14 +2752,14 @@ export async function runCommand(args, root, fs, services = {}) {
2298
2752
  return installationRequired();
2299
2753
  assertStageReady(aiw, fs, "assessment");
2300
2754
  const title = args.find((argument) => argument.startsWith("--title="))?.slice(8) || "Untitled Assessment";
2301
- const path = join(aiw, "generated/reports/assessment.md");
2755
+ const path = stageArtifactWritePath(fs, aiw, "assessment");
2302
2756
  fs.write(path, `# ${title}\n\n## Evidence\n\n- <attributed evidence: source, finding>\n\n## Outcome\n\ngo | clarify | stop\n\n## Rationale\n\n- <why this outcome follows from the evidence>\n\n## Next Step\n\n- <go: recommended feature scope · clarify: the open questions · stop: conditions that would reopen>\n`);
2303
2757
  return { exitCode: 0, output: `Assessment artifact created: ${path}` };
2304
2758
  }
2305
2759
  if (command === "risk") {
2306
2760
  if (args[1] !== "assess")
2307
2761
  return { exitCode: 1, error: "Usage: aiw risk assess [--base-ref=ref] [--json]" };
2308
- return runRiskAssess(args.slice(2), root, fs);
2762
+ return runRiskAssess(args.slice(2), root, fs, services.embeddingProvider);
2309
2763
  }
2310
2764
  if (command === "gate") {
2311
2765
  if (!fs.exists(join(aiw, "manifest.yml")))
@@ -2318,11 +2772,11 @@ export async function runCommand(args, root, fs, services = {}) {
2318
2772
  };
2319
2773
  const workflowStage = stage;
2320
2774
  assertStageReady(aiw, fs, workflowStage);
2321
- const artifactPath = approvalArtifactPath(aiw, workflowStage);
2775
+ const artifactPath = approvalArtifactPath(fs, aiw, workflowStage);
2322
2776
  if (!artifactPath || !fs.exists(artifactPath))
2323
2777
  throw new BlockingError(describeBlockingReason("gate_evidence_missing", {
2324
2778
  stage,
2325
- artifactPath: artifactPath ?? undefined,
2779
+ artifactPath: stageArtifactWritePath(fs, aiw, workflowStage),
2326
2780
  detail: `Quality gate blocked: required evidence is missing for ${stage}.`,
2327
2781
  }));
2328
2782
  const hasQualityGate = stageDefinition(workflowStage).requiresQualityGate;
@@ -2356,7 +2810,7 @@ export async function runCommand(args, root, fs, services = {}) {
2356
2810
  fs.write(join(aiw, "approvals.yml"), serializeApprovalLedger(updated));
2357
2811
  return {
2358
2812
  exitCode: 0,
2359
- output: `${hasQualityGate ? `Quality gate passed for ${stage}.` : `Evidence recorded for ${stage}; no automated quality gate applies.`} Human approval is still required: run aiw approve ${stage}.`,
2813
+ output: `${hasQualityGate ? `Quality gate passed for ${stage}.` : `Evidence recorded for ${stage}; no automated quality gate applies.`} Human approval is still required: run aiw approve ${stage}.${resolveStageArtifact(fs, aiw, workflowStage, activeWorkflowId(fs, aiw)).legacyFallback ? ` Advisory: ${stage} artifact read from the legacy fixed path; new writes go to the workflow-scoped path.` : ""}`,
2360
2814
  };
2361
2815
  }
2362
2816
  if (command === "validate") {
@@ -2628,7 +3082,7 @@ export async function runCommand(args, root, fs, services = {}) {
2628
3082
  const digestLines = [];
2629
3083
  if (fs.exists(join(aiw, "workflow.yml"))) {
2630
3084
  for (const stage of processStages(readWorkflowState(aiw, fs, false).ledger)) {
2631
- const artifactPath = approvalArtifactPath(aiw, stage);
3085
+ const artifactPath = approvalArtifactPath(fs, aiw, stage);
2632
3086
  const freshness = digestFreshness(aiw, fs, stage, artifactPath ?? undefined);
2633
3087
  if (freshness.state !== "missing")
2634
3088
  digestLines.push(formatDigestLine(freshness));
@@ -2766,7 +3220,7 @@ export async function runCommand(args, root, fs, services = {}) {
2766
3220
  exitCode: 1,
2767
3221
  error: "No usage sidecar recorded yet. Record runs with `aiw usage-sidecar record` or run `aiw scan`.",
2768
3222
  };
2769
- const tracePath = join(aiw, "generated/artifacts/traceability.yml");
3223
+ const tracePath = resolveStageArtifact(fs, aiw, "traceability", activeWorkflowId(fs, aiw)).path;
2770
3224
  if (!fs.exists(tracePath))
2771
3225
  return {
2772
3226
  exitCode: 1,
@@ -2822,6 +3276,30 @@ export async function runCommand(args, root, fs, services = {}) {
2822
3276
  const { state: nextState, outcome } = recordBeat(state, session, new Date(), warnSeconds, ttlSeconds);
2823
3277
  fs.write(statePath, serializeHeartbeatState(nextState));
2824
3278
  const lines = [describeHeartbeatOutcome(outcome)];
3279
+ // REQ-003 wiring: a new session is the boundary where the previous
3280
+ // session's rejections become monitor occurrences. Monitor failures
3281
+ // must never break the heartbeat.
3282
+ if (outcome.decision === "session-start") {
3283
+ try {
3284
+ const ledgerPath = join(aiw, "approvals.yml");
3285
+ if (fs.exists(ledgerPath)) {
3286
+ const artifacts = harvestApprovalObservations(fs.read(ledgerPath));
3287
+ if (artifacts.length > 0) {
3288
+ const proposalsPath = join(aiw, "proposals.yml");
3289
+ const store = fs.exists(proposalsPath)
3290
+ ? parseProposalStore(fs.read(proposalsPath))
3291
+ : createEmptyStore();
3292
+ const { surfaced } = monitorSession(store, artifacts);
3293
+ fs.write(proposalsPath, serializeProposalStore(store));
3294
+ if (surfaced.length > 0)
3295
+ lines.push(`monitor: ${surfaced.length} recurring pattern(s) crossed the proposal threshold — run aiw proposals list`);
3296
+ }
3297
+ }
3298
+ }
3299
+ catch {
3300
+ // observation is best-effort; heartbeat stays authoritative
3301
+ }
3302
+ }
2825
3303
  if (outcome.checkpoint) {
2826
3304
  const checkpointPath = join(aiw, `checkpoints/heartbeat-${session}-${outcome.checkpoint.index}.yml`);
2827
3305
  fs.write(checkpointPath, serializeHeartbeatCheckpoint(outcome.checkpoint, outcome.gapSeconds ?? 0, ttlSeconds));
@@ -3120,7 +3598,7 @@ export async function runCommand(args, root, fs, services = {}) {
3120
3598
  }
3121
3599
  return {
3122
3600
  exitCode: 0,
3123
- output: "aiw install [--target target] | workflow <start|status|complete> [--id=id] | task <start|status> --ticket=TEAM-123 [--title=text] | approve <stage> | reject <stage> --reason=text | skip <optional-stage> --reason=text | ui [--port=number] | orchestrate --plan=path [--execute] [--max-parallel=number] | telemetry <status|show|enable|disable> [privacy options] | plugin <create|validate> [options] | scan | semantic <status|query> | decision <status|triage> | self-validate --ticket=TYPE-000 | organization-policy --file=path [--replace] | policy-check --package=path [--package=path] | preset --file=path [--replace] | context | context-summary | context-quality | capabilities [--target=target] | token-usage [--stage=name --budget=number --used=number] | registry [--search=query] [--private=name] | registry configure --file=path [--replace] | skills <search|inspect|install|check|update> [options] | audit-package --package=path | verify-package --package=path --checksum=sha256 | brainstorm [--title=title] | spec [--title=title] | adr [--id=id --title=title] | plan [--title=title] | verify | trace | gate <stage> | standards <extract|list|confirm|reject> | recommend [--select=id,id] | status | doctor | repair | uninstall [--dry-run] | target <target> | rollback | confirm | resolve --package=path | update --package=path --target=target | validate [--package=path]",
3601
+ output: "aiw install [--target target] | workflow <start|status|complete> [--id=id] | task <start|status> --ticket=TEAM-123 [--title=text] | approve <stage> | reject <stage> --reason=text | skip <optional-stage> --reason=text | ui [--port=number] | orchestrate --plan=path [--execute] [--max-parallel=number] | telemetry <status|show|enable|disable> [privacy options] | plugin <create|validate> [options] | scan | semantic <status|query> | decision <status|triage> | self-validate --ticket=TYPE-000 | organization-policy --file=path [--replace] | policy-check --package=path [--package=path] | preset --file=path [--replace] | context | context-summary | context-quality | capabilities [--target=target] | token-usage [--stage=name --budget=number --used=number] | registry [--search=query] [--private=name] | registry configure --file=path [--replace] | skills <search|inspect|install|check|update> [options] | audit-package --package=path | verify-package --package=path --checksum=sha256 | brainstorm [--title=title] | spec [--title=title] | adr [--id=id --title=title] | plan [--title=title] | verify | trace | gate <stage> | standards <extract|list|confirm|reject> | recommend [--select=id,id] | eval run --scenarios [--registry=dir] [--harness=id] [--filter=id] [--advisory] | status | doctor | repair | uninstall [--dry-run] | target <target> | rollback | confirm | resolve --package=path | update --package=path --target=target | validate [--package=path]",
3124
3602
  };
3125
3603
  }
3126
3604
  catch (error) {
@@ -3149,7 +3627,7 @@ function readWorkflowState(aiw, fs, requireActive = true) {
3149
3627
  const record = ledger.stages[stage];
3150
3628
  if (!record?.artifactHash || !["pending-human", "approved"].includes(record.status))
3151
3629
  return false;
3152
- const artifact = approvalArtifactPath(aiw, stage);
3630
+ const artifact = approvalArtifactPath(fs, aiw, stage);
3153
3631
  return (!artifact ||
3154
3632
  !fs.exists(artifact) ||
3155
3633
  stageFingerprint(fs.read(artifact)) !== record.artifactHash);
@@ -3203,7 +3681,7 @@ function normalizeCommand(command) {
3203
3681
  * Legacy plans without pair arrows are accepted unchanged (ratchet).
3204
3682
  */
3205
3683
  export function compareVerificationPairs(aiw, fs, stage) {
3206
- const planPath = join(aiw, "generated/plans/implementation-plan.md");
3684
+ const planPath = resolveStageArtifact(fs, aiw, "plan", activeWorkflowId(fs, aiw)).path;
3207
3685
  if (!fs.exists(planPath))
3208
3686
  return [];
3209
3687
  const plan = fs.read(planPath);
@@ -3227,9 +3705,7 @@ export function compareVerificationPairs(aiw, fs, stage) {
3227
3705
  }
3228
3706
  if (declared.length === 0)
3229
3707
  return [];
3230
- const reportPath = stage === "implementation"
3231
- ? join(aiw, "generated/reports/implementation-report.md")
3232
- : join(aiw, "generated/reports/verification-report.md");
3708
+ const reportPath = resolveStageArtifact(fs, aiw, stage === "implementation" ? "implementation" : "verification", activeWorkflowId(fs, aiw)).path;
3233
3709
  const issues = [];
3234
3710
  const observed = new Map();
3235
3711
  if (fs.exists(reportPath)) {
@@ -3309,21 +3785,8 @@ function assertStageReady(aiw, fs, stage) {
3309
3785
  detail: `${stage} is already approved. Evidence changes require rerunning its gate.`,
3310
3786
  }));
3311
3787
  }
3312
- function approvalArtifactPath(aiw, stage) {
3313
- if (stage === "technical-design")
3314
- return join(aiw, "generated/reports/technical-design.md");
3315
- const paths = {
3316
- brainstorming: "generated/specs/brainstorm.md",
3317
- specification: "generated/specs/specification.md",
3318
- plan: "generated/plans/implementation-plan.md",
3319
- implementation: "generated/reports/implementation-report.md",
3320
- verification: "generated/reports/verification-report.md",
3321
- review: "generated/reports/code-review.md",
3322
- traceability: "generated/artifacts/traceability.yml",
3323
- diagnosis: "generated/reports/diagnosis.md",
3324
- assessment: "generated/reports/assessment.md",
3325
- };
3326
- return resolve(aiw, paths[stage]);
3788
+ function approvalArtifactPath(fs, aiw, stage) {
3789
+ return resolveStageArtifact(fs, aiw, stage, activeWorkflowId(fs, aiw)).path;
3327
3790
  }
3328
3791
  function formatConfidence(confidence) {
3329
3792
  return confidence === undefined ? "unknown" : confidence.toFixed(3);
@@ -3504,6 +3967,7 @@ function syncSelectedResources(fs, root, aiw, profile, selected, apply = false,
3504
3967
  resourceId: id,
3505
3968
  });
3506
3969
  };
3970
+ const semanticRetrieval = semanticRetrievalAvailable(fs, aiw);
3507
3971
  for (const reference of resourceSelections) {
3508
3972
  const key = `${reference.type}/${reference.id}`;
3509
3973
  const resource = bundleByKey.get(key);
@@ -3513,7 +3977,7 @@ function syncSelectedResources(fs, root, aiw, profile, selected, apply = false,
3513
3977
  }
3514
3978
  generateProjectResources(profile, selected, (path, content) => {
3515
3979
  generatedFiles.set(join(aiw, path), content);
3516
- const rule = path.match(/^generated\/rules\/(project-quality|tdd-project-policy)\.md$/);
3980
+ const rule = path.match(/^generated\/rules\/(project-quality|tdd-project-policy|semantic-retrieval)\.md$/);
3517
3981
  if (rule)
3518
3982
  addResource("rules", rule[1], content);
3519
3983
  const rootContext = path === "generated/context/root-context.md";
@@ -3535,7 +3999,7 @@ function syncSelectedResources(fs, root, aiw, profile, selected, apply = false,
3535
3999
  });
3536
4000
  }
3537
4001
  }
3538
- });
4002
+ }, semanticRetrieval);
3539
4003
  const ownershipPath = join(aiw, "ownership.yml");
3540
4004
  if (fs.pathType?.(ownershipPath) !== "file")
3541
4005
  return {