@multileaf/ai-workflow 0.15.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 (51) hide show
  1. package/CHANGELOG.md +10 -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/signals.d.ts +21 -0
  24. package/dist/eval/signals.js +155 -0
  25. package/dist/eval/types.d.ts +38 -0
  26. package/dist/eval/types.js +1 -0
  27. package/dist/eval/validate.d.ts +28 -0
  28. package/dist/eval/validate.js +66 -0
  29. package/dist/generator.d.ts +8 -1
  30. package/dist/generator.js +24 -1
  31. package/dist/risk-assess.d.ts +1 -1
  32. package/dist/risk-assess.js +26 -2
  33. package/dist/semantic.d.ts +19 -0
  34. package/dist/semantic.js +57 -0
  35. package/dist/services.d.ts +3 -0
  36. package/dist/telemetry.d.ts +6 -0
  37. package/dist/telemetry.js +14 -7
  38. package/dist/workflow.js +471 -67
  39. package/docs/backlog.md +12 -2
  40. package/docs/decision-model-evaluation.md +7 -2
  41. package/docs/opportunities/OPP-007-decision-findings-triage-scope-watch.md +1 -1
  42. package/docs/opportunities/OPP-008-embedding-covering-tests-judge-context.md +1 -1
  43. package/docs/semantic-mapping.md +9 -0
  44. package/package.json +1 -1
  45. package/resources/evals/scenarios/evaluator-draft-contract.yml +65 -0
  46. package/resources/package.yaml +1 -0
  47. package/resources/skills/resource-evaluator.md +24 -0
  48. package/resources/skills/review-judge-a.md +4 -0
  49. package/resources/skills/review-judge-b.md +4 -0
  50. package/resources/skills/review-refuter.md +4 -0
  51. package/resources/skills/ticket.md +1 -1
package/dist/workflow.js CHANGED
@@ -29,7 +29,15 @@ async function readStdin() {
29
29
  terminal.close();
30
30
  }
31
31
  }
32
- 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";
33
41
  import { detectDrift } from "./drift.js";
34
42
  import { parseManifest, serializeManifest } from "./manifest.js";
35
43
  import { createOwnedFile, parseOwnership, serializeOwnership, } from "./ownership.js";
@@ -39,8 +47,8 @@ import { defaultShellRunner, isHarnessAvailable, parseScenarioRegistry, runScena
39
47
  import { executeVercelSkills, installVercelSkill, nodeCommandExecutor } from "./vercel-skills.js";
40
48
  import { scanProject } from "./scanner.js";
41
49
  import { readFactOverrides, saveSettingOverrides, saveSettingsSection } from "./settings.js";
42
- import { buildEvidenceTriageRequest, buildRecommendationRankingRequest, buildSemanticRerankRequest, createOllamaDecisionProvider, loadDecisionConfig, } from "./decision.js";
43
- 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";
44
52
  import { assertKnownPermissions, assertPermissions, assertPackagePermissions, serializePermissionReview, } from "./package-audit.js";
45
53
  import { planPackageUpdate } from "./package-updates.js";
46
54
  import { searchRegistry, serializeRegistry } from "./registry.js";
@@ -53,6 +61,8 @@ import { loadContextDelta, retrieveTaskContext } from "./context-retrieval.js";
53
61
  import { createSummaryCache, isSummaryFresh, parseSummaryCache, serializeSummaryCache, } from "./context-cache.js";
54
62
  import { parseTokenUsage, recordTokenUsage, serializeTokenUsage, summarizeUsageByModel, } from "./token-usage.js";
55
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";
56
66
  import { parse as parseYaml, stringify } from "yaml";
57
67
  import { measureContextQuality, serializeContextQuality } from "./context-quality.js";
58
68
  import { collectContextBench, compareContextBench, parseContextBench, serializeContextBench, } from "./context-benchmark.js";
@@ -89,7 +99,7 @@ function stateMismatch(detail) {
89
99
  import { parseMigrationCheckpoint, planNeutralResourceMigration, readResourceBytes, serializeMigrationPreview, serializeMigrationCheckpoint, validateNeutralResourceDocument, writeResourceBytes, } from "./migration.js";
90
100
  import { parsePrivateRegistries, parseTeamPreset, serializePrivateRegistries, serializeTeamPreset, fetchPrivateRegistryClient, } from "./team-configuration.js";
91
101
  import { enforcePolicyGate, gitPolicyTracking } from "./policy-gate.js";
92
- 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";
93
103
  import { createPluginScaffold, validatePluginDirectory, writePluginScaffold, } from "./plugin-sdk.js";
94
104
  import { createTaskWorktrees, executeOrchestrationPlan, forecastIntegration, listManagedWorktrees, currentBranch, parseOrchestrationResults, removeWorktrees, parseOrchestrationPlan, serializeOrchestrationPreview, serializeOrchestrationResults, validateOrchestrationParallelism, } from "./orchestration.js";
95
105
  function laneAdvisory(root, fs, lightChosen) {
@@ -106,6 +116,68 @@ function laneAdvisory(root, fs, lightChosen) {
106
116
  return "advisory: current changes look passive; the light lane (--lane=light --lane-reason=...) may be viable for small work.";
107
117
  return undefined;
108
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
+ }
109
181
  function beginWorkflowSession(fs, aiw, options) {
110
182
  const sessionPath = join(aiw, "workflow.yml");
111
183
  const ledgerPath = join(aiw, "approvals.yml");
@@ -167,21 +239,17 @@ export async function runCommand(args, root, fs, services = {}) {
167
239
  if (command === "task") {
168
240
  if (!fs.exists(join(aiw, "manifest.yml")))
169
241
  return installationRequired();
170
- 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";
171
243
  const action = args[1];
172
244
  const sessionPath = join(aiw, "workflow.yml");
173
245
  if (action === "start") {
174
- const options = parseNamedOptions(args.slice(2), [
175
- "ticket",
176
- "title",
177
- "id",
178
- "lane",
179
- "lane-reason",
180
- "process",
181
- ]);
182
- 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))
183
249
  return { exitCode: 1, error: usage };
184
- 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);
185
253
  const processName = options.process;
186
254
  if (processName !== undefined) {
187
255
  if (!isWorkflowProcess(processName))
@@ -221,7 +289,7 @@ export async function runCommand(args, root, fs, services = {}) {
221
289
  const lane = options.lane === "light" ? "light" : undefined;
222
290
  const result = beginWorkflowSession(fs, aiw, {
223
291
  ...(options.id ? { id: options.id } : {}),
224
- ticket: options.ticket,
292
+ ticket: resolvedTicket,
225
293
  ...(options.title ? { title: options.title } : {}),
226
294
  ...(lane ? { lane, laneReason: laneReason } : {}),
227
295
  ...(processName ? { process: processName } : {}),
@@ -233,7 +301,7 @@ export async function runCommand(args, root, fs, services = {}) {
233
301
  if (lane)
234
302
  return {
235
303
  exitCode: 0,
236
- 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` +
237
305
  (advisory ? `${advisory}\n` : "") +
238
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" +
239
307
  `Rationale recorded: ${laneReason}\n` +
@@ -241,9 +309,9 @@ export async function runCommand(args, root, fs, services = {}) {
241
309
  };
242
310
  return {
243
311
  exitCode: 0,
244
- output: `Task started for ticket ${options.ticket}${title}: ${result.output}\n` +
312
+ output: `Task started for ticket ${resolvedTicket}${title}: ${result.output}\n` +
245
313
  (advisory ? `${advisory}\n` : "") +
246
- `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=...\`.`,
247
315
  };
248
316
  }
249
317
  if (action === "escalate") {
@@ -441,9 +509,53 @@ export async function runCommand(args, root, fs, services = {}) {
441
509
  status: "complete",
442
510
  updatedAt: new Date().toISOString(),
443
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
+ }
444
550
  return {
445
551
  exitCode: 0,
446
- 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")}` : ""),
447
559
  };
448
560
  }
449
561
  const unresolved = processStages(ledger).filter((stage) => ledger.stages[stage]?.status !== "approved" &&
@@ -458,7 +570,17 @@ export async function runCommand(args, root, fs, services = {}) {
458
570
  status: "complete",
459
571
  updatedAt: new Date().toISOString(),
460
572
  }));
461
- 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
+ };
462
584
  }
463
585
  return {
464
586
  exitCode: 1,
@@ -491,11 +613,11 @@ export async function runCommand(args, root, fs, services = {}) {
491
613
  fs.write(join(aiw, "approvals.yml"), serializeApprovalLedger(updated));
492
614
  return { exitCode: 0, output: `Human-approved skip recorded for ${workflowStage}.` };
493
615
  }
494
- const artifact = approvalArtifactPath(aiw, workflowStage);
616
+ const artifact = approvalArtifactPath(fs, aiw, workflowStage);
495
617
  if (!artifact || !fs.exists(artifact))
496
618
  throw new BlockingError(describeBlockingReason("approval_evidence_missing", {
497
619
  stage: workflowStage,
498
- artifactPath: artifact ?? undefined,
620
+ artifactPath: stageArtifactWritePath(fs, aiw, workflowStage),
499
621
  detail: `Approval evidence is missing for ${workflowStage}.`,
500
622
  }));
501
623
  const artifactHash = stageFingerprint(fs.read(artifact));
@@ -1133,7 +1255,7 @@ export async function runCommand(args, root, fs, services = {}) {
1133
1255
  };
1134
1256
  }
1135
1257
  if (command === "decision") {
1136
- 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";
1137
1259
  const action = args[1];
1138
1260
  const config = loadDecisionConfig(fs, aiw);
1139
1261
  if (action === "status") {
@@ -1177,13 +1299,44 @@ export async function runCommand(args, root, fs, services = {}) {
1177
1299
  ].join("\n"),
1178
1300
  };
1179
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
+ }
1180
1332
  return { exitCode: 1, error: usage };
1181
1333
  }
1182
1334
  if (command === "semantic") {
1183
- 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";
1184
1336
  const action = args[1];
1337
+ const semanticConfig = loadSemanticConfig(fs, aiw);
1185
1338
  if (action === "status") {
1186
- const config = loadSemanticConfig(fs, aiw);
1339
+ const config = semanticConfig;
1187
1340
  if (!config)
1188
1341
  return {
1189
1342
  exitCode: 0,
@@ -1198,6 +1351,50 @@ export async function runCommand(args, root, fs, services = {}) {
1198
1351
  output: `Semantic mapping ${config.enabled ? "enabled" : "disabled"}: model ${config.model} at ${config.baseUrl}\n${built}`,
1199
1352
  };
1200
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
+ }
1201
1398
  if (action === "query") {
1202
1399
  const queryArgs = args.slice(2).filter((arg) => arg !== "--rerank");
1203
1400
  const rerankRequested = args.slice(2).includes("--rerank");
@@ -1826,7 +2023,7 @@ export async function runCommand(args, root, fs, services = {}) {
1826
2023
  return;
1827
2024
  }
1828
2025
  fs.write(destination, content);
1829
- });
2026
+ }, semanticRetrievalAvailable(fs, aiw));
1830
2027
  return {
1831
2028
  exitCode: conflicts.length ? 1 : 0,
1832
2029
  output: conflicts.length
@@ -1911,6 +2108,188 @@ export async function runCommand(args, root, fs, services = {}) {
1911
2108
  output: `${lines.join("\n")}\n${advisory && blocking > 0 ? `${blocking} scenario(s) failed (advisory mode: exit 0).\n` : ""}`,
1912
2109
  };
1913
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
+ }
1914
2293
  if (command === "doctor") {
1915
2294
  const required = ["manifest.yml", "profile.yml", "lock.yml", "ownership.yml"];
1916
2295
  const missing = required.filter((file) => !fs.exists(join(aiw, file)));
@@ -1946,7 +2325,22 @@ export async function runCommand(args, root, fs, services = {}) {
1946
2325
  catch (error) {
1947
2326
  return { exitCode: 1, error: error instanceof Error ? error.message : String(error) };
1948
2327
  }
1949
- 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}` };
1950
2344
  }
1951
2345
  if (command === "repair") {
1952
2346
  if (!fs.exists(join(aiw, "manifest.yml")))
@@ -2053,7 +2447,7 @@ export async function runCommand(args, root, fs, services = {}) {
2053
2447
  return installationRequired();
2054
2448
  assertStageReady(aiw, fs, "brainstorming");
2055
2449
  const title = args.find((arg) => arg.startsWith("--title="))?.slice(8) || "Untitled Brainstorm";
2056
- const path = join(aiw, "generated/specs/brainstorm.md");
2450
+ const path = stageArtifactWritePath(fs, aiw, "brainstorming");
2057
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`);
2058
2452
  return { exitCode: 0, output: `Brainstorm artifact created: ${path}` };
2059
2453
  }
@@ -2065,7 +2459,7 @@ export async function runCommand(args, root, fs, services = {}) {
2065
2459
  const ticket = args.find((arg) => arg.startsWith("--ticket="))?.slice(9);
2066
2460
  if (ticket !== undefined)
2067
2461
  validateTaskTicket(ticket);
2068
- const path = join(aiw, "generated/specs/specification.md");
2462
+ const path = stageArtifactWritePath(fs, aiw, "specification");
2069
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`);
2070
2464
  return { exitCode: 0, output: `Specification artifact created: ${path}` };
2071
2465
  }
@@ -2084,7 +2478,7 @@ export async function runCommand(args, root, fs, services = {}) {
2084
2478
  return installationRequired();
2085
2479
  assertStageReady(aiw, fs, "plan");
2086
2480
  const title = args.find((arg) => arg.startsWith("--title="))?.slice(8) || "Untitled Implementation Plan";
2087
- const path = join(aiw, "generated/plans/implementation-plan.md");
2481
+ const path = stageArtifactWritePath(fs, aiw, "plan");
2088
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`);
2089
2483
  return { exitCode: 0, output: `Implementation plan created: ${path}` };
2090
2484
  }
@@ -2092,8 +2486,8 @@ export async function runCommand(args, root, fs, services = {}) {
2092
2486
  if (!fs.exists(join(aiw, "manifest.yml")))
2093
2487
  return installationRequired();
2094
2488
  assertStageReady(aiw, fs, "verification");
2095
- const specPath = join(aiw, "generated/specs/specification.md");
2096
- 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;
2097
2491
  const issues = [];
2098
2492
  let regressionNotice;
2099
2493
  let specification = "";
@@ -2133,8 +2527,8 @@ export async function runCommand(args, root, fs, services = {}) {
2133
2527
  if (!fs.exists(join(aiw, "manifest.yml")))
2134
2528
  return installationRequired();
2135
2529
  assertStageReady(aiw, fs, "traceability");
2136
- const specPath = join(aiw, "generated/specs/specification.md");
2137
- 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;
2138
2532
  if (!fs.exists(specPath) || !fs.exists(planPath))
2139
2533
  return {
2140
2534
  exitCode: 1,
@@ -2156,7 +2550,7 @@ export async function runCommand(args, root, fs, services = {}) {
2156
2550
  const serialized = serializeTraceabilityGraph(graph, requirement);
2157
2551
  if (requirement)
2158
2552
  return { exitCode: 0, output: serialized };
2159
- const path = join(aiw, "generated/artifacts/traceability.yml");
2553
+ const path = stageArtifactWritePath(fs, aiw, "traceability");
2160
2554
  fs.write(path, serialized);
2161
2555
  return { exitCode: 0, output: `Traceability graph created: ${path}` };
2162
2556
  }
@@ -2329,7 +2723,7 @@ export async function runCommand(args, root, fs, services = {}) {
2329
2723
  const lines = [];
2330
2724
  let served = 0;
2331
2725
  for (const stage of stages) {
2332
- const artifactPath = approvalArtifactPath(aiw, stage);
2726
+ const artifactPath = approvalArtifactPath(fs, aiw, stage);
2333
2727
  const freshness = digestFreshness(aiw, fs, stage, artifactPath ?? undefined);
2334
2728
  if (freshness.state === "missing")
2335
2729
  continue;
@@ -2349,7 +2743,7 @@ export async function runCommand(args, root, fs, services = {}) {
2349
2743
  return installationRequired();
2350
2744
  assertStageReady(aiw, fs, "diagnosis");
2351
2745
  const title = args.find((argument) => argument.startsWith("--title="))?.slice(8) || "Untitled Diagnosis";
2352
- const path = join(aiw, "generated/reports/diagnosis.md");
2746
+ const path = stageArtifactWritePath(fs, aiw, "diagnosis");
2353
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`);
2354
2748
  return { exitCode: 0, output: `Diagnosis artifact created: ${path}` };
2355
2749
  }
@@ -2358,14 +2752,14 @@ export async function runCommand(args, root, fs, services = {}) {
2358
2752
  return installationRequired();
2359
2753
  assertStageReady(aiw, fs, "assessment");
2360
2754
  const title = args.find((argument) => argument.startsWith("--title="))?.slice(8) || "Untitled Assessment";
2361
- const path = join(aiw, "generated/reports/assessment.md");
2755
+ const path = stageArtifactWritePath(fs, aiw, "assessment");
2362
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`);
2363
2757
  return { exitCode: 0, output: `Assessment artifact created: ${path}` };
2364
2758
  }
2365
2759
  if (command === "risk") {
2366
2760
  if (args[1] !== "assess")
2367
2761
  return { exitCode: 1, error: "Usage: aiw risk assess [--base-ref=ref] [--json]" };
2368
- return runRiskAssess(args.slice(2), root, fs);
2762
+ return runRiskAssess(args.slice(2), root, fs, services.embeddingProvider);
2369
2763
  }
2370
2764
  if (command === "gate") {
2371
2765
  if (!fs.exists(join(aiw, "manifest.yml")))
@@ -2378,11 +2772,11 @@ export async function runCommand(args, root, fs, services = {}) {
2378
2772
  };
2379
2773
  const workflowStage = stage;
2380
2774
  assertStageReady(aiw, fs, workflowStage);
2381
- const artifactPath = approvalArtifactPath(aiw, workflowStage);
2775
+ const artifactPath = approvalArtifactPath(fs, aiw, workflowStage);
2382
2776
  if (!artifactPath || !fs.exists(artifactPath))
2383
2777
  throw new BlockingError(describeBlockingReason("gate_evidence_missing", {
2384
2778
  stage,
2385
- artifactPath: artifactPath ?? undefined,
2779
+ artifactPath: stageArtifactWritePath(fs, aiw, workflowStage),
2386
2780
  detail: `Quality gate blocked: required evidence is missing for ${stage}.`,
2387
2781
  }));
2388
2782
  const hasQualityGate = stageDefinition(workflowStage).requiresQualityGate;
@@ -2416,7 +2810,7 @@ export async function runCommand(args, root, fs, services = {}) {
2416
2810
  fs.write(join(aiw, "approvals.yml"), serializeApprovalLedger(updated));
2417
2811
  return {
2418
2812
  exitCode: 0,
2419
- 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.` : ""}`,
2420
2814
  };
2421
2815
  }
2422
2816
  if (command === "validate") {
@@ -2688,7 +3082,7 @@ export async function runCommand(args, root, fs, services = {}) {
2688
3082
  const digestLines = [];
2689
3083
  if (fs.exists(join(aiw, "workflow.yml"))) {
2690
3084
  for (const stage of processStages(readWorkflowState(aiw, fs, false).ledger)) {
2691
- const artifactPath = approvalArtifactPath(aiw, stage);
3085
+ const artifactPath = approvalArtifactPath(fs, aiw, stage);
2692
3086
  const freshness = digestFreshness(aiw, fs, stage, artifactPath ?? undefined);
2693
3087
  if (freshness.state !== "missing")
2694
3088
  digestLines.push(formatDigestLine(freshness));
@@ -2826,7 +3220,7 @@ export async function runCommand(args, root, fs, services = {}) {
2826
3220
  exitCode: 1,
2827
3221
  error: "No usage sidecar recorded yet. Record runs with `aiw usage-sidecar record` or run `aiw scan`.",
2828
3222
  };
2829
- const tracePath = join(aiw, "generated/artifacts/traceability.yml");
3223
+ const tracePath = resolveStageArtifact(fs, aiw, "traceability", activeWorkflowId(fs, aiw)).path;
2830
3224
  if (!fs.exists(tracePath))
2831
3225
  return {
2832
3226
  exitCode: 1,
@@ -2882,6 +3276,30 @@ export async function runCommand(args, root, fs, services = {}) {
2882
3276
  const { state: nextState, outcome } = recordBeat(state, session, new Date(), warnSeconds, ttlSeconds);
2883
3277
  fs.write(statePath, serializeHeartbeatState(nextState));
2884
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
+ }
2885
3303
  if (outcome.checkpoint) {
2886
3304
  const checkpointPath = join(aiw, `checkpoints/heartbeat-${session}-${outcome.checkpoint.index}.yml`);
2887
3305
  fs.write(checkpointPath, serializeHeartbeatCheckpoint(outcome.checkpoint, outcome.gapSeconds ?? 0, ttlSeconds));
@@ -3209,7 +3627,7 @@ function readWorkflowState(aiw, fs, requireActive = true) {
3209
3627
  const record = ledger.stages[stage];
3210
3628
  if (!record?.artifactHash || !["pending-human", "approved"].includes(record.status))
3211
3629
  return false;
3212
- const artifact = approvalArtifactPath(aiw, stage);
3630
+ const artifact = approvalArtifactPath(fs, aiw, stage);
3213
3631
  return (!artifact ||
3214
3632
  !fs.exists(artifact) ||
3215
3633
  stageFingerprint(fs.read(artifact)) !== record.artifactHash);
@@ -3263,7 +3681,7 @@ function normalizeCommand(command) {
3263
3681
  * Legacy plans without pair arrows are accepted unchanged (ratchet).
3264
3682
  */
3265
3683
  export function compareVerificationPairs(aiw, fs, stage) {
3266
- const planPath = join(aiw, "generated/plans/implementation-plan.md");
3684
+ const planPath = resolveStageArtifact(fs, aiw, "plan", activeWorkflowId(fs, aiw)).path;
3267
3685
  if (!fs.exists(planPath))
3268
3686
  return [];
3269
3687
  const plan = fs.read(planPath);
@@ -3287,9 +3705,7 @@ export function compareVerificationPairs(aiw, fs, stage) {
3287
3705
  }
3288
3706
  if (declared.length === 0)
3289
3707
  return [];
3290
- const reportPath = stage === "implementation"
3291
- ? join(aiw, "generated/reports/implementation-report.md")
3292
- : join(aiw, "generated/reports/verification-report.md");
3708
+ const reportPath = resolveStageArtifact(fs, aiw, stage === "implementation" ? "implementation" : "verification", activeWorkflowId(fs, aiw)).path;
3293
3709
  const issues = [];
3294
3710
  const observed = new Map();
3295
3711
  if (fs.exists(reportPath)) {
@@ -3369,21 +3785,8 @@ function assertStageReady(aiw, fs, stage) {
3369
3785
  detail: `${stage} is already approved. Evidence changes require rerunning its gate.`,
3370
3786
  }));
3371
3787
  }
3372
- function approvalArtifactPath(aiw, stage) {
3373
- if (stage === "technical-design")
3374
- return join(aiw, "generated/reports/technical-design.md");
3375
- const paths = {
3376
- brainstorming: "generated/specs/brainstorm.md",
3377
- specification: "generated/specs/specification.md",
3378
- plan: "generated/plans/implementation-plan.md",
3379
- implementation: "generated/reports/implementation-report.md",
3380
- verification: "generated/reports/verification-report.md",
3381
- review: "generated/reports/code-review.md",
3382
- traceability: "generated/artifacts/traceability.yml",
3383
- diagnosis: "generated/reports/diagnosis.md",
3384
- assessment: "generated/reports/assessment.md",
3385
- };
3386
- return resolve(aiw, paths[stage]);
3788
+ function approvalArtifactPath(fs, aiw, stage) {
3789
+ return resolveStageArtifact(fs, aiw, stage, activeWorkflowId(fs, aiw)).path;
3387
3790
  }
3388
3791
  function formatConfidence(confidence) {
3389
3792
  return confidence === undefined ? "unknown" : confidence.toFixed(3);
@@ -3564,6 +3967,7 @@ function syncSelectedResources(fs, root, aiw, profile, selected, apply = false,
3564
3967
  resourceId: id,
3565
3968
  });
3566
3969
  };
3970
+ const semanticRetrieval = semanticRetrievalAvailable(fs, aiw);
3567
3971
  for (const reference of resourceSelections) {
3568
3972
  const key = `${reference.type}/${reference.id}`;
3569
3973
  const resource = bundleByKey.get(key);
@@ -3573,7 +3977,7 @@ function syncSelectedResources(fs, root, aiw, profile, selected, apply = false,
3573
3977
  }
3574
3978
  generateProjectResources(profile, selected, (path, content) => {
3575
3979
  generatedFiles.set(join(aiw, path), content);
3576
- 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$/);
3577
3981
  if (rule)
3578
3982
  addResource("rules", rule[1], content);
3579
3983
  const rootContext = path === "generated/context/root-context.md";
@@ -3595,7 +3999,7 @@ function syncSelectedResources(fs, root, aiw, profile, selected, apply = false,
3595
3999
  });
3596
4000
  }
3597
4001
  }
3598
- });
4002
+ }, semanticRetrieval);
3599
4003
  const ownershipPath = join(aiw, "ownership.yml");
3600
4004
  if (fs.pathType?.(ownershipPath) !== "file")
3601
4005
  return {