@multileaf/ai-workflow 0.15.0 → 0.17.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 (58) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +19 -1
  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/blocking-reasons.d.ts +1 -1
  7. package/dist/blocking-reasons.js +6 -0
  8. package/dist/completion-report.d.ts +17 -0
  9. package/dist/completion-report.js +42 -0
  10. package/dist/dashboard.js +7 -1
  11. package/dist/decision.d.ts +15 -0
  12. package/dist/decision.js +63 -0
  13. package/dist/eval/brief.d.ts +7 -0
  14. package/dist/eval/brief.js +28 -0
  15. package/dist/eval/generated.d.ts +17 -0
  16. package/dist/eval/generated.js +41 -0
  17. package/dist/eval/git.d.ts +13 -0
  18. package/dist/eval/git.js +70 -0
  19. package/dist/eval/monitor.d.ts +32 -0
  20. package/dist/eval/monitor.js +66 -0
  21. package/dist/eval/policy.d.ts +8 -0
  22. package/dist/eval/policy.js +9 -0
  23. package/dist/eval/proposals.d.ts +48 -0
  24. package/dist/eval/proposals.js +202 -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/recommendations.js +11 -0
  34. package/dist/risk-assess.d.ts +1 -1
  35. package/dist/risk-assess.js +26 -2
  36. package/dist/semantic.d.ts +19 -0
  37. package/dist/semantic.js +57 -0
  38. package/dist/services.d.ts +3 -0
  39. package/dist/telemetry.d.ts +6 -0
  40. package/dist/telemetry.js +14 -7
  41. package/dist/update.d.ts +42 -0
  42. package/dist/update.js +89 -0
  43. package/dist/workflow.js +583 -71
  44. package/docs/backlog.md +20 -2
  45. package/docs/continuation-inventory.md +24 -23
  46. package/docs/decision-model-evaluation.md +7 -2
  47. package/docs/opportunities/OPP-007-decision-findings-triage-scope-watch.md +1 -1
  48. package/docs/opportunities/OPP-008-embedding-covering-tests-judge-context.md +1 -1
  49. package/docs/semantic-mapping.md +9 -0
  50. package/package.json +1 -1
  51. package/resources/evals/scenarios/evaluator-draft-contract.yml +65 -0
  52. package/resources/package.yaml +2 -0
  53. package/resources/skills/research.md +64 -0
  54. package/resources/skills/resource-evaluator.md +24 -0
  55. package/resources/skills/review-judge-a.md +4 -0
  56. package/resources/skills/review-judge-b.md +4 -0
  57. package/resources/skills/review-refuter.md +4 -0
  58. package/resources/skills/ticket.md +1 -1
package/dist/workflow.js CHANGED
@@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { BASE_DIRECTORIES, WORKFLOW_DIRECTORY } from "./constants.js";
6
6
  import { detectTarget, isTarget, renderAiInit, describeResource, renderAiInitPath, renderResourcePath, } from "./adapter.js";
7
+ import { computeUpdatePlan } from "./update.js";
7
8
  import { loadBundledResources } from "./bundled-resources.js";
8
9
  import { assertSafeProjectPath, withSafeProjectWrites, writeProjectFilesAtomically, } from "./files.js";
9
10
  import { parseProjectProfile, profileProject } from "./profile.js";
@@ -29,7 +30,15 @@ async function readStdin() {
29
30
  terminal.close();
30
31
  }
31
32
  }
32
- import { generateProjectResources } from "./generator.js";
33
+ import { generateProjectResources, generateProposalResource } from "./generator.js";
34
+ import { collectSignals, serializeEvidenceBundle, parseEvidenceBundle } from "./eval/signals.js";
35
+ import { renderBrief } from "./eval/brief.js";
36
+ import { harvestApprovalObservations, monitorSession } from "./eval/monitor.js";
37
+ import { collectGitSummary } from "./eval/git.js";
38
+ import { approveProposal, createEmptyStore, compactProposalStore, draftSignatureHash, parseProposalStore, recordOccurrence, rejectProposal, serializeProposalStore, suppressProposal, } from "./eval/proposals.js";
39
+ import { PROPOSAL_KINDS } from "./eval/types.js";
40
+ import { parseDrafts, validateDrafts } from "./eval/validate.js";
41
+ import { validateGeneratedResources } from "./eval/generated.js";
33
42
  import { detectDrift } from "./drift.js";
34
43
  import { parseManifest, serializeManifest } from "./manifest.js";
35
44
  import { createOwnedFile, parseOwnership, serializeOwnership, } from "./ownership.js";
@@ -39,8 +48,8 @@ import { defaultShellRunner, isHarnessAvailable, parseScenarioRegistry, runScena
39
48
  import { executeVercelSkills, installVercelSkill, nodeCommandExecutor } from "./vercel-skills.js";
40
49
  import { scanProject } from "./scanner.js";
41
50
  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";
51
+ import { buildEvidenceTriageRequest, buildFindingsTriageRequest, buildLaneScopeWatchRequest, checkFindingShapes, parseReviewFindings, buildRecommendationRankingRequest, buildSemanticRerankRequest, createOllamaDecisionProvider, loadDecisionConfig, } from "./decision.js";
52
+ import { buildSemanticIndex, createOllamaEmbeddingProvider, loadSemanticConfig, semanticRetrievalAvailable, parseSemanticIndex, buildCoveringTestQuery, querySemanticIndex, renderJudgeContext, rerankSemanticMatches, SEMANTIC_INDEX_PATH, serializeSemanticIndex, } from "./semantic.js";
44
53
  import { assertKnownPermissions, assertPermissions, assertPackagePermissions, serializePermissionReview, } from "./package-audit.js";
45
54
  import { planPackageUpdate } from "./package-updates.js";
46
55
  import { searchRegistry, serializeRegistry } from "./registry.js";
@@ -53,6 +62,8 @@ import { loadContextDelta, retrieveTaskContext } from "./context-retrieval.js";
53
62
  import { createSummaryCache, isSummaryFresh, parseSummaryCache, serializeSummaryCache, } from "./context-cache.js";
54
63
  import { parseTokenUsage, recordTokenUsage, serializeTokenUsage, summarizeUsageByModel, } from "./token-usage.js";
55
64
  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";
65
+ import { buildCompletionReport } from "./completion-report.js";
66
+ import { archiveWorkflowArtifacts, resolveStageArtifact, stageArtifactPaths, } from "./artifact-paths.js";
56
67
  import { parse as parseYaml, stringify } from "yaml";
57
68
  import { measureContextQuality, serializeContextQuality } from "./context-quality.js";
58
69
  import { collectContextBench, compareContextBench, parseContextBench, serializeContextBench, } from "./context-benchmark.js";
@@ -89,7 +100,7 @@ function stateMismatch(detail) {
89
100
  import { parseMigrationCheckpoint, planNeutralResourceMigration, readResourceBytes, serializeMigrationPreview, serializeMigrationCheckpoint, validateNeutralResourceDocument, writeResourceBytes, } from "./migration.js";
90
101
  import { parsePrivateRegistries, parseTeamPreset, serializePrivateRegistries, serializeTeamPreset, fetchPrivateRegistryClient, } from "./team-configuration.js";
91
102
  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";
103
+ import { DEFAULT_TELEMETRY_CONFIG, loadTelemetryConfig, offerTelemetryConsent, maybeOfferTelemetryConsent, parseTelemetryConfig, purgeTelemetryBuffer, readTelemetryBuffer, serializeTelemetryMapping, TELEMETRY_BUFFER_CAP, TELEMETRY_BUFFER_FILE, } from "./telemetry.js";
93
104
  import { createPluginScaffold, validatePluginDirectory, writePluginScaffold, } from "./plugin-sdk.js";
94
105
  import { createTaskWorktrees, executeOrchestrationPlan, forecastIntegration, listManagedWorktrees, currentBranch, parseOrchestrationResults, removeWorktrees, parseOrchestrationPlan, serializeOrchestrationPreview, serializeOrchestrationResults, validateOrchestrationParallelism, } from "./orchestration.js";
95
106
  function laneAdvisory(root, fs, lightChosen) {
@@ -106,6 +117,164 @@ function laneAdvisory(root, fs, lightChosen) {
106
117
  return "advisory: current changes look passive; the light lane (--lane=light --lane-reason=...) may be viable for small work.";
107
118
  return undefined;
108
119
  }
120
+ /** FRIC-002: allocate the next LOCAL-### ticket from current and archived sessions. */
121
+ function nextLocalTicket(fs, aiw) {
122
+ let max = 0;
123
+ const consider = (text) => {
124
+ for (const match of text.matchAll(/^\s*ticket:\s*(LOCAL-(\d+)\s*)$/gm))
125
+ max = Math.max(max, Number(match[2]));
126
+ };
127
+ const sessionPath = join(aiw, "workflow.yml");
128
+ if (fs.exists(sessionPath))
129
+ consider(fs.read(sessionPath));
130
+ const checkpoints = join(aiw, "checkpoints");
131
+ if (fs.exists(checkpoints) && fs.list)
132
+ for (const name of fs.list(checkpoints) ?? [])
133
+ if (name.startsWith("workflow-") && name.endsWith("-session.yml"))
134
+ consider(fs.read(join(checkpoints, name)));
135
+ return `LOCAL-${String(max + 1).padStart(3, "0")}`;
136
+ }
137
+ /** FRIC-005: workflow id of the recorded session, if any. */
138
+ function activeWorkflowId(fs, aiw) {
139
+ const sessionPath = join(aiw, "workflow.yml");
140
+ if (!fs.exists(sessionPath))
141
+ return undefined;
142
+ try {
143
+ return parseWorkflowSession(fs.read(sessionPath)).workflowId;
144
+ }
145
+ catch {
146
+ return undefined;
147
+ }
148
+ }
149
+ /** FRIC-005: write path for a stage artifact — scoped when a workflow is active. */
150
+ function stageArtifactWritePath(fs, aiw, stage) {
151
+ const { scoped, legacy } = stageArtifactPaths(aiw, stage, activeWorkflowId(fs, aiw));
152
+ return scoped ?? legacy;
153
+ }
154
+ /** FRIC-003: gather recorded usage/cost data and write the completion report. Never blocks completion. */
155
+ async function writeCompletionReport(fs, aiw, session, ledger) {
156
+ const scope = session.ticket ?? session.workflowId;
157
+ let usage;
158
+ let attribution;
159
+ try {
160
+ const sidecarPath = join(aiw, USAGE_SIDECAR_PATH);
161
+ if (fs.exists(sidecarPath))
162
+ usage = summarizeTaskUsage(parseUsageSidecar(fs.read(sidecarPath)), scope);
163
+ const tracePath = resolveStageArtifact(fs, aiw, "traceability", session.workflowId).path;
164
+ if (usage && fs.exists(tracePath))
165
+ attribution = computeCostAttribution(parseUsageSidecar(fs.read(sidecarPath)), parseTraceabilityGraph(fs.read(tracePath)));
166
+ }
167
+ catch {
168
+ // REQ-003: unreadable usage data degrades to an advisory, never blocks completion.
169
+ }
170
+ const report = buildCompletionReport({ session, ledger, usage, attribution });
171
+ try {
172
+ const reportDir = join(aiw, "generated/reports");
173
+ if (!fs.exists(reportDir))
174
+ fs.mkdir(reportDir);
175
+ fs.write(join(reportDir, `usage-${session.workflowId}.md`), report.markdown);
176
+ }
177
+ catch {
178
+ // REQ-003: a failed artifact write never blocks completion.
179
+ }
180
+ return report.consoleSummary;
181
+ }
182
+ /** Monotonic ADR unix-time stamp (distinct ids within the same millisecond). */
183
+ let adrLastStamp = 0;
184
+ /** UPD-001: bundled-resource update — diff, drift-safe apply, additive --add. */
185
+ async function runBundledUpdate(args, root, fs, aiw, services) {
186
+ const dryRun = args.includes("--dry-run");
187
+ const addArg = args.find((argument) => argument.startsWith("--add="))?.slice(6);
188
+ const add = addArg
189
+ ? addArg
190
+ .split(",")
191
+ .map((id) => id.trim())
192
+ .filter(Boolean)
193
+ : [];
194
+ if (args.some((argument) => argument.startsWith("--") &&
195
+ !["--dry-run", "--add", "--json"].some((allowed) => argument === allowed || argument.startsWith(`${allowed}=`))))
196
+ return {
197
+ exitCode: 1,
198
+ error: "Usage: aiw update [--dry-run] [--add=type/id,...] | aiw update --package=path --target=target",
199
+ };
200
+ const target = parseManifest(fs.read(join(aiw, "manifest.yml"))).target.active;
201
+ const profilePath = join(aiw, "profile.yml");
202
+ const profile = /^status:\s*scanned$/m.test(fs.exists(profilePath) ? fs.read(profilePath) : "")
203
+ ? parseProjectProfile(fs.read(profilePath))
204
+ : await (services.profiler?.profile(root) ?? profileProject(root));
205
+ const personalize = (type, id, content) => personalizeBundledResource(type, id, content, profile);
206
+ let plan;
207
+ try {
208
+ plan = computeUpdatePlan({ fs, root, aiw, target, add, personalize });
209
+ }
210
+ catch (error) {
211
+ return { exitCode: 1, error: error instanceof Error ? error.message : String(error) };
212
+ }
213
+ const lines = [
214
+ `updated: ${plan.updated.length}${plan.updated.map((entry) => `\n - ${entry.path}`).join("")}`,
215
+ `new available: ${plan.newIds.length}${plan.newIds.length ? ` (${plan.newIds.slice(0, 12).join(", ")}${plan.newIds.length > 12 ? ", …" : ""})` : ""}`,
216
+ `unchanged: ${plan.unchanged}`,
217
+ plan.conflicts.length ? `conflicts (preserved): ${plan.conflicts.join(", ")}` : "",
218
+ plan.install.length
219
+ ? `installing: ${plan.install.map((r) => `${r.type}/${r.id}`).join(", ")}`
220
+ : "",
221
+ ].filter(Boolean);
222
+ if (dryRun)
223
+ return { exitCode: 0, output: lines.join("\n") };
224
+ if (plan.conflicts.length)
225
+ throw new BlockingError(describeBlockingReason("update_conflict", {
226
+ detail: plan.conflicts.join(", "),
227
+ }));
228
+ // Drift-safe apply: replace unmodified files, refresh their checksums.
229
+ for (const entry of plan.updated)
230
+ fs.write(join(root, entry.path), entry.content);
231
+ const ownershipPath = join(aiw, "ownership.yml");
232
+ const owned = parseOwnership(fs.read(ownershipPath));
233
+ const updatedPaths = new Set(plan.updated.map((entry) => entry.path));
234
+ const nextOwned = owned.map((file) => updatedPaths.has(file.path)
235
+ ? createOwnedFile(file.path, fs.read(join(root, file.path)), {
236
+ kind: file.kind,
237
+ target: file.target,
238
+ resourceType: file.resourceType,
239
+ resourceId: file.resourceId,
240
+ })
241
+ : file);
242
+ // Additive --add: render new resources and register ownership.
243
+ for (const resource of plan.install) {
244
+ const type = resource.type;
245
+ const neutralPath = renderResourcePath("universal", type, resource.id);
246
+ const targetPath = renderResourcePath(target, type, resource.id);
247
+ fs.write(join(root, neutralPath), resource.content);
248
+ nextOwned.push(createOwnedFile(neutralPath, resource.content, {
249
+ kind: "neutral-resource",
250
+ target: "universal",
251
+ resourceType: type,
252
+ resourceId: resource.id,
253
+ }));
254
+ if (targetPath !== neutralPath) {
255
+ fs.write(join(root, targetPath), resource.content);
256
+ nextOwned.push(createOwnedFile(targetPath, resource.content, {
257
+ kind: "target-resource",
258
+ target,
259
+ resourceType: type,
260
+ resourceId: resource.id,
261
+ }));
262
+ }
263
+ }
264
+ fs.write(ownershipPath, serializeOwnership(nextOwned));
265
+ if (plan.install.length) {
266
+ // Record the additive selection so future syncs keep the added resources.
267
+ const recommendations = services.recommender?.recommend(profile) ?? recommendCapabilities(profile);
268
+ const previousSelection = readSelectedRecommendations(fs, aiw);
269
+ const selection = [...new Set([...previousSelection, ...add])];
270
+ fs.write(join(aiw, "recommendations.yml"), serializeRecommendations(recommendations, selection));
271
+ }
272
+ return {
273
+ exitCode: 0,
274
+ output: lines.join("\n") +
275
+ `\nUpdate applied${plan.install.length ? "" : " (no new resources installed; use --add=type/id to install)"}.`,
276
+ };
277
+ }
109
278
  function beginWorkflowSession(fs, aiw, options) {
110
279
  const sessionPath = join(aiw, "workflow.yml");
111
280
  const ledgerPath = join(aiw, "approvals.yml");
@@ -167,21 +336,17 @@ export async function runCommand(args, root, fs, services = {}) {
167
336
  if (command === "task") {
168
337
  if (!fs.exists(join(aiw, "manifest.yml")))
169
338
  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";
339
+ 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
340
  const action = args[1];
172
341
  const sessionPath = join(aiw, "workflow.yml");
173
342
  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)
343
+ const noTicket = args.slice(2).includes("--no-ticket");
344
+ const options = parseNamedOptions(args.slice(2).filter((argument) => argument !== "--no-ticket"), ["ticket", "title", "id", "lane", "lane-reason", "process"]);
345
+ if (!options || (noTicket && options.ticket))
183
346
  return { exitCode: 1, error: usage };
184
- validateTaskTicket(options.ticket);
347
+ // FRIC-002: no ticket given (or --no-ticket) — self-serve a local ticket.
348
+ const resolvedTicket = options.ticket ?? nextLocalTicket(fs, aiw);
349
+ validateTaskTicket(resolvedTicket);
185
350
  const processName = options.process;
186
351
  if (processName !== undefined) {
187
352
  if (!isWorkflowProcess(processName))
@@ -221,7 +386,7 @@ export async function runCommand(args, root, fs, services = {}) {
221
386
  const lane = options.lane === "light" ? "light" : undefined;
222
387
  const result = beginWorkflowSession(fs, aiw, {
223
388
  ...(options.id ? { id: options.id } : {}),
224
- ticket: options.ticket,
389
+ ticket: resolvedTicket,
225
390
  ...(options.title ? { title: options.title } : {}),
226
391
  ...(lane ? { lane, laneReason: laneReason } : {}),
227
392
  ...(processName ? { process: processName } : {}),
@@ -233,7 +398,7 @@ export async function runCommand(args, root, fs, services = {}) {
233
398
  if (lane)
234
399
  return {
235
400
  exitCode: 0,
236
- output: `Task started for ticket ${options.ticket}${title} (light lane): ${result.output}\n` +
401
+ output: `Task started for ticket ${resolvedTicket}${title} (light lane): ${result.output}\n` +
237
402
  (advisory ? `${advisory}\n` : "") +
238
403
  "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
404
  `Rationale recorded: ${laneReason}\n` +
@@ -241,9 +406,9 @@ export async function runCommand(args, root, fs, services = {}) {
241
406
  };
242
407
  return {
243
408
  exitCode: 0,
244
- output: `Task started for ticket ${options.ticket}${title}: ${result.output}\n` +
409
+ output: `Task started for ticket ${resolvedTicket}${title}: ${result.output}\n` +
245
410
  (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=...\`.`,
411
+ `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
412
  };
248
413
  }
249
414
  if (action === "escalate") {
@@ -441,9 +606,53 @@ export async function runCommand(args, root, fs, services = {}) {
441
606
  status: "complete",
442
607
  updatedAt: new Date().toISOString(),
443
608
  }));
609
+ const lightSummary = await writeCompletionReport(fs, aiw, session, ledger);
610
+ const lightArchive = archiveWorkflowArtifacts(fs, aiw, session.workflowId);
611
+ // OPP-007 REQ-003/004: lane mismatch note (always) + optional model scope-watch.
612
+ const laneNotes = [];
613
+ const mismatch = laneAdvisory(root, fs, true);
614
+ if (mismatch)
615
+ laneNotes.push(mismatch);
616
+ const decisionConfig = loadDecisionConfig(fs, aiw);
617
+ if (decisionConfig?.enabled) {
618
+ const provider = services.decisionProvider ?? createOllamaDecisionProvider(decisionConfig);
619
+ try {
620
+ if (await provider.available()) {
621
+ const paths = collectWorkingTreeChanges(root) ?? [];
622
+ const response = await provider.decide(buildLaneScopeWatchRequest(paths.join("\n") || "no working-tree changes"));
623
+ laneNotes.push(`advisory scope-watch: multi_subsystem=${response.answers.multi_subsystem?.choice ?? "unclear"} (advisory-only)`);
624
+ }
625
+ }
626
+ catch {
627
+ // Advisory flow: provider failures degrade silently.
628
+ }
629
+ }
630
+ if (laneNotes.length) {
631
+ const evidenceFile = fs.exists(evidencePath)
632
+ ? parseLightEvidence(fs.read(evidencePath))
633
+ : null;
634
+ const advisories = laneNotes;
635
+ fs.write(evidencePath, stringify({
636
+ ...(evidenceFile ?? {
637
+ schema: 1,
638
+ workflowId: session.workflowId,
639
+ ...(session.ticket ? { ticket: session.ticket } : {}),
640
+ lane: "light",
641
+ ...(session.laneReason ? { laneReason: session.laneReason } : {}),
642
+ entries: [],
643
+ }),
644
+ advisories,
645
+ }, { lineWidth: 0 }));
646
+ }
444
647
  return {
445
648
  exitCode: 0,
446
- output: `Workflow completed (light lane): ${session.workflowId}. Evidence: ${evidencePath}`,
649
+ output: `Workflow completed (light lane): ${session.workflowId}. Evidence: ${evidencePath}\n` +
650
+ `${lightSummary}\n` +
651
+ `Report: ${join(aiw, `generated/reports/usage-${session.workflowId}.md`)}` +
652
+ (lightArchive.length
653
+ ? `\nArchived ${lightArchive.length} workflow artifact(s) to checkpoints/workflow-${session.workflowId}-artifacts/.`
654
+ : "") +
655
+ (laneNotes.length ? `\n${laneNotes.join("\n")}` : ""),
447
656
  };
448
657
  }
449
658
  const unresolved = processStages(ledger).filter((stage) => ledger.stages[stage]?.status !== "approved" &&
@@ -458,7 +667,17 @@ export async function runCommand(args, root, fs, services = {}) {
458
667
  status: "complete",
459
668
  updatedAt: new Date().toISOString(),
460
669
  }));
461
- return { exitCode: 0, output: `Workflow completed: ${session.workflowId}.` };
670
+ const fullSummary = await writeCompletionReport(fs, aiw, session, ledger);
671
+ const fullArchive = archiveWorkflowArtifacts(fs, aiw, session.workflowId);
672
+ return {
673
+ exitCode: 0,
674
+ output: `Workflow completed: ${session.workflowId}.\n` +
675
+ `${fullSummary}\n` +
676
+ `Report: ${join(aiw, `generated/reports/usage-${session.workflowId}.md`)}` +
677
+ (fullArchive.length
678
+ ? `\nArchived ${fullArchive.length} workflow artifact(s) to checkpoints/workflow-${session.workflowId}-artifacts/.`
679
+ : ""),
680
+ };
462
681
  }
463
682
  return {
464
683
  exitCode: 1,
@@ -491,11 +710,11 @@ export async function runCommand(args, root, fs, services = {}) {
491
710
  fs.write(join(aiw, "approvals.yml"), serializeApprovalLedger(updated));
492
711
  return { exitCode: 0, output: `Human-approved skip recorded for ${workflowStage}.` };
493
712
  }
494
- const artifact = approvalArtifactPath(aiw, workflowStage);
713
+ const artifact = approvalArtifactPath(fs, aiw, workflowStage);
495
714
  if (!artifact || !fs.exists(artifact))
496
715
  throw new BlockingError(describeBlockingReason("approval_evidence_missing", {
497
716
  stage: workflowStage,
498
- artifactPath: artifact ?? undefined,
717
+ artifactPath: stageArtifactWritePath(fs, aiw, workflowStage),
499
718
  detail: `Approval evidence is missing for ${workflowStage}.`,
500
719
  }));
501
720
  const artifactHash = stageFingerprint(fs.read(artifact));
@@ -1133,7 +1352,7 @@ export async function runCommand(args, root, fs, services = {}) {
1133
1352
  };
1134
1353
  }
1135
1354
  if (command === "decision") {
1136
- const usage = "Usage: aiw decision triage --artifact=<path> | aiw decision status";
1355
+ const usage = "Usage: aiw decision triage --artifact=<path> | aiw decision findings-triage --findings=<path> | aiw decision status";
1137
1356
  const action = args[1];
1138
1357
  const config = loadDecisionConfig(fs, aiw);
1139
1358
  if (action === "status") {
@@ -1177,13 +1396,44 @@ export async function runCommand(args, root, fs, services = {}) {
1177
1396
  ].join("\n"),
1178
1397
  };
1179
1398
  }
1399
+ if (action === "findings-triage") {
1400
+ const parsed = parseNamedOptions(args.slice(2), ["findings"]);
1401
+ if (!parsed?.findings)
1402
+ return { exitCode: 1, error: usage };
1403
+ const findingsPath = safeProjectFile(root, parsed.findings, fs);
1404
+ if (!fs.exists(findingsPath))
1405
+ return { exitCode: 1, error: `Findings file not found: ${parsed.findings}` };
1406
+ const findings = parseReviewFindings(fs.read(findingsPath));
1407
+ const lines = [];
1408
+ const shapeIssues = checkFindingShapes(findings);
1409
+ lines.push(shapeIssues.length === 0
1410
+ ? "Shape check: all findings are well-formed."
1411
+ : `Shape check failures (deterministic):\n${shapeIssues.map((i) => ` - ${i}`).join("\n")}`);
1412
+ if (config?.enabled) {
1413
+ const provider = services.decisionProvider ?? createOllamaDecisionProvider(config);
1414
+ try {
1415
+ if (await provider.available()) {
1416
+ const decision = await provider.decide(buildFindingsTriageRequest(findings));
1417
+ lines.push("Advisory evidence triage (refuter still owns corroboration):");
1418
+ for (const finding of findings)
1419
+ if (finding.severity.toLowerCase() === "severe")
1420
+ lines.push(` - ${finding.id}: evidence_supported: ${decision.answers[finding.id]?.choice ?? "unclear"}`);
1421
+ }
1422
+ }
1423
+ catch {
1424
+ // Advisory flow: provider failures degrade to shape-check-only output.
1425
+ }
1426
+ }
1427
+ return { exitCode: 0, output: lines.join("\n") };
1428
+ }
1180
1429
  return { exitCode: 1, error: usage };
1181
1430
  }
1182
1431
  if (command === "semantic") {
1183
- const usage = "Usage: aiw semantic query --text=<query> [--rerank] | aiw semantic status";
1432
+ const usage = "Usage: aiw semantic query --text=<query> [--rerank] | aiw semantic judge-context --paths=a.ts,b.ts [--budget=N] | aiw semantic status";
1184
1433
  const action = args[1];
1434
+ const semanticConfig = loadSemanticConfig(fs, aiw);
1185
1435
  if (action === "status") {
1186
- const config = loadSemanticConfig(fs, aiw);
1436
+ const config = semanticConfig;
1187
1437
  if (!config)
1188
1438
  return {
1189
1439
  exitCode: 0,
@@ -1198,6 +1448,50 @@ export async function runCommand(args, root, fs, services = {}) {
1198
1448
  output: `Semantic mapping ${config.enabled ? "enabled" : "disabled"}: model ${config.model} at ${config.baseUrl}\n${built}`,
1199
1449
  };
1200
1450
  }
1451
+ if (action === "judge-context") {
1452
+ const parsed = parseNamedOptions(args.slice(2), ["paths", "budget"]);
1453
+ if (!parsed?.paths)
1454
+ return {
1455
+ exitCode: 1,
1456
+ error: "Usage: aiw semantic judge-context --paths=a.ts,b.ts [--budget=N]",
1457
+ };
1458
+ if (!semanticConfig?.enabled)
1459
+ return {
1460
+ exitCode: 1,
1461
+ error: "Semantic mapping is disabled. Set semantic.enabled=true in .aiw/settings.yml to use judge context.",
1462
+ };
1463
+ const config = semanticConfig;
1464
+ const indexPath = join(aiw, SEMANTIC_INDEX_PATH);
1465
+ if (!fs.exists(indexPath))
1466
+ return {
1467
+ exitCode: 1,
1468
+ error: "Semantic index is missing. Run aiw scan to build it before requesting judge context.",
1469
+ };
1470
+ const provider = services.embeddingProvider ?? createOllamaEmbeddingProvider(config);
1471
+ if (!(await provider.available()))
1472
+ return {
1473
+ exitCode: 1,
1474
+ error: `Semantic model ${config.model} is not available at ${config.baseUrl}. Judges fall back to the raw diff (fail-safe).`,
1475
+ };
1476
+ const paths = parsed.paths
1477
+ .split(",")
1478
+ .map((p) => p.trim())
1479
+ .filter(Boolean);
1480
+ const budget = Number(parsed.budget ?? 4000);
1481
+ if (!Number.isFinite(budget) || budget <= 0)
1482
+ return { exitCode: 1, error: "--budget must be a positive number." };
1483
+ const chunks = [];
1484
+ for (const path of paths) {
1485
+ const matches = await querySemanticIndex(parseSemanticIndex(fs.read(indexPath)), buildCoveringTestQuery(path), provider, config);
1486
+ for (const match of matches)
1487
+ chunks.push({ file: match.file, excerpt: match.excerpt });
1488
+ }
1489
+ return {
1490
+ exitCode: 0,
1491
+ output: renderJudgeContext("## Changed paths\n" + paths.join("\n"), chunks, budget) +
1492
+ "\n(context aids only — retrieval results are never confirmed facts)",
1493
+ };
1494
+ }
1201
1495
  if (action === "query") {
1202
1496
  const queryArgs = args.slice(2).filter((arg) => arg !== "--rerank");
1203
1497
  const rerankRequested = args.slice(2).includes("--rerank");
@@ -1826,7 +2120,7 @@ export async function runCommand(args, root, fs, services = {}) {
1826
2120
  return;
1827
2121
  }
1828
2122
  fs.write(destination, content);
1829
- });
2123
+ }, semanticRetrievalAvailable(fs, aiw));
1830
2124
  return {
1831
2125
  exitCode: conflicts.length ? 1 : 0,
1832
2126
  output: conflicts.length
@@ -1911,6 +2205,188 @@ export async function runCommand(args, root, fs, services = {}) {
1911
2205
  output: `${lines.join("\n")}\n${advisory && blocking > 0 ? `${blocking} scenario(s) failed (advisory mode: exit 0).\n` : ""}`,
1912
2206
  };
1913
2207
  }
2208
+ if (command === "evaluate") {
2209
+ const scanFiles = await (services.scanner?.scan(root) ?? scanProject(root));
2210
+ const gitSummary = await collectGitSummary(root, services.runShell ?? defaultShellRunner);
2211
+ const bundle = collectSignals(scanFiles.files, gitSummary, (path) => fs.exists(join(root, path)) ? fs.read(join(root, path)) : "");
2212
+ const evalDir = join(aiw, "eval");
2213
+ const signalsPath = join(evalDir, "signals.yml");
2214
+ const briefPath = join(evalDir, "brief.md");
2215
+ const draftsPath = join(evalDir, "proposals-draft.yml");
2216
+ // A4: drafts written against a previous signal set must not survive a
2217
+ // re-evaluation; the skill re-drafts from the fresh brief.
2218
+ if (fs.exists(draftsPath))
2219
+ fs.remove?.(draftsPath);
2220
+ fs.write(signalsPath, serializeEvidenceBundle(bundle));
2221
+ fs.write(briefPath, renderBrief(bundle));
2222
+ return {
2223
+ exitCode: 0,
2224
+ output: `signals written to ${relative(root, signalsPath)}\nhand off ${relative(root, briefPath)} to the resource-evaluator skill\n`,
2225
+ };
2226
+ }
2227
+ if (command === "proposals") {
2228
+ const usage = "Usage: aiw proposals <import|list|show|approve|reject|suppress|validate> [--id=id] [--reason=text]";
2229
+ const action = args[1];
2230
+ const storePath = join(aiw, "proposals.yml");
2231
+ const loadStore = () => {
2232
+ if (!fs.exists(storePath))
2233
+ throw new Error("No proposals store found; run `aiw proposals import` first.");
2234
+ return parseProposalStore(fs.read(storePath));
2235
+ };
2236
+ if (action === "import") {
2237
+ const signalsPath = join(aiw, "eval", "signals.yml");
2238
+ const draftsPath = join(aiw, "eval", "proposals-draft.yml");
2239
+ if (!fs.exists(signalsPath) || !fs.exists(draftsPath))
2240
+ return {
2241
+ exitCode: 1,
2242
+ error: "Run `aiw evaluate` and the resource-evaluator skill first.",
2243
+ };
2244
+ const bundle = parseEvidenceBundle(fs.read(signalsPath));
2245
+ let drafts;
2246
+ try {
2247
+ drafts = parseDrafts(fs.read(draftsPath));
2248
+ }
2249
+ catch (error) {
2250
+ return { exitCode: 1, error: error instanceof Error ? error.message : String(error) };
2251
+ }
2252
+ const target = detectTarget(root, fs) || "codex";
2253
+ const catalogIds = loadBundledResources(target).map(({ type, id }) => `${type}/${id}`);
2254
+ const validation = validateDrafts(drafts, bundle, catalogIds);
2255
+ if (validation.errors.length)
2256
+ return {
2257
+ exitCode: 1,
2258
+ error: `${validation.errors.length} draft record(s) failed the contract:\n${validation.errors
2259
+ .map(({ record, reason }) => `- ${record}: ${reason.join("; ")}`)
2260
+ .join("\n")}`,
2261
+ };
2262
+ const store = fs.exists(storePath)
2263
+ ? parseProposalStore(fs.read(storePath))
2264
+ : createEmptyStore();
2265
+ const isUnchanged = (record) => {
2266
+ const hash = draftSignatureHash(record);
2267
+ const existing = store.proposals.find((candidate) => candidate.signature === record.signature);
2268
+ return existing?.draftHash === hash;
2269
+ };
2270
+ const changed = validation.records.filter((record) => !isUnchanged(record));
2271
+ for (const record of validation.records) {
2272
+ if (isUnchanged(record))
2273
+ continue;
2274
+ recordOccurrence(store, {
2275
+ kind: record.kind,
2276
+ signature: record.signature,
2277
+ origin: "onboarding",
2278
+ });
2279
+ const proposal = store.proposals.find((candidate) => candidate.signature === record.signature);
2280
+ if (proposal) {
2281
+ proposal.title = record.title;
2282
+ proposal.outline = record.outline;
2283
+ proposal.evidence = record.evidence;
2284
+ proposal.kind = record.kind;
2285
+ proposal.draftHash = draftSignatureHash(record);
2286
+ }
2287
+ }
2288
+ if (changed.length === 0)
2289
+ return {
2290
+ exitCode: 0,
2291
+ output: `no proposals to import${fs.exists(storePath)
2292
+ ? " — drafts unchanged since the last import"
2293
+ : " — the evaluator proposed nothing for this project"}\n`,
2294
+ };
2295
+ fs.write(storePath, serializeProposalStore(store));
2296
+ const overlapNote = validation.overlaps.length
2297
+ ? `\noverlaps annotated for review: ${validation.overlaps
2298
+ .map(({ signature, catalogId }) => `${signature} ~ ${catalogId}`)
2299
+ .join(", ")}`
2300
+ : "";
2301
+ return {
2302
+ exitCode: 0,
2303
+ output: `imported ${changed.length} proposal(s) into ${relative(root, storePath)}${overlapNote}\n`,
2304
+ };
2305
+ }
2306
+ if (action === "list") {
2307
+ const store = loadStore();
2308
+ if (store.proposals.length === 0)
2309
+ return { exitCode: 0, output: "No proposals recorded.\n" };
2310
+ const lines = store.proposals.map((proposal) => `${proposal.id} [${proposal.kind}] ${proposal.status} (${proposal.occurrences} occurrences) ${proposal.title || proposal.signature}`);
2311
+ return { exitCode: 0, output: `${lines.join("\n")}\n` };
2312
+ }
2313
+ if (action === "validate") {
2314
+ const generatedRoot = join(aiw, "generated");
2315
+ const files = [];
2316
+ for (const kind of PROPOSAL_KINDS) {
2317
+ const dir = join(generatedRoot, `${kind}s`);
2318
+ if (!fs.exists(dir))
2319
+ continue;
2320
+ for (const name of (fs.listFiles?.(dir) ?? fs.list?.(dir) ?? []).sort())
2321
+ if (name.endsWith(".md"))
2322
+ files.push({ path: `${kind}s/${name}`, content: fs.read(join(dir, name)) });
2323
+ }
2324
+ if (files.length === 0)
2325
+ return { exitCode: 0, output: "No generated resources to validate.\n" };
2326
+ if (!fs.exists(storePath))
2327
+ return {
2328
+ exitCode: 1,
2329
+ error: `Generated resources exist but no proposals store was found at ${relative(root, storePath)}.`,
2330
+ };
2331
+ const issues = validateGeneratedResources(files, loadStore());
2332
+ if (issues.length)
2333
+ return {
2334
+ exitCode: 1,
2335
+ error: `${issues.length} generated resource(s) failed validation:\n${issues
2336
+ .map(({ path, reason }) => `- ${path}: ${reason}`)
2337
+ .join("\n")}`,
2338
+ };
2339
+ return {
2340
+ exitCode: 0,
2341
+ output: `valid: ${files.length} generated resource(s) pass the evaluator contract.\n`,
2342
+ };
2343
+ }
2344
+ const options = parseNamedOptions(args.slice(2), ["id", "reason"]);
2345
+ if (options === undefined)
2346
+ return { exitCode: 1, error: usage };
2347
+ const id = options.id;
2348
+ if (action === "show") {
2349
+ if (!id)
2350
+ return { exitCode: 1, error: usage };
2351
+ const proposal = loadStore().proposals.find((candidate) => candidate.id === id);
2352
+ if (!proposal)
2353
+ return { exitCode: 1, error: `Unknown proposal id: ${id}` };
2354
+ return {
2355
+ exitCode: 0,
2356
+ output: [
2357
+ `${proposal.id} [${proposal.kind}] ${proposal.status}`,
2358
+ `title: ${proposal.title}`,
2359
+ `outline: ${proposal.outline}`,
2360
+ `evidence: ${proposal.evidence.join(", ")}`,
2361
+ `occurrences: ${proposal.occurrences}`,
2362
+ `reject_reason: ${proposal.rejectReason ?? "-"}`,
2363
+ ].join("\n") + "\n",
2364
+ };
2365
+ }
2366
+ if (!id)
2367
+ return { exitCode: 1, error: usage };
2368
+ if (action === "approve" || action === "reject" || action === "suppress") {
2369
+ const store = loadStore();
2370
+ if (action === "reject") {
2371
+ if (!options.reason)
2372
+ return { exitCode: 1, error: "--reason is required when rejecting a proposal." };
2373
+ rejectProposal(store, id, options.reason);
2374
+ }
2375
+ else if (action === "approve") {
2376
+ approveProposal(store, id);
2377
+ const approved = store.proposals.find((candidate) => candidate.id === id);
2378
+ if (approved && approved.title && approved.outline) {
2379
+ generateProposalResource(approved, (path, content) => fs.write(join(aiw, path), content));
2380
+ }
2381
+ }
2382
+ else
2383
+ suppressProposal(store, id);
2384
+ compactProposalStore(store);
2385
+ fs.write(storePath, serializeProposalStore(store));
2386
+ return { exitCode: 0, output: `${action} recorded for ${id}\n` };
2387
+ }
2388
+ return { exitCode: 1, error: usage };
2389
+ }
1914
2390
  if (command === "doctor") {
1915
2391
  const required = ["manifest.yml", "profile.yml", "lock.yml", "ownership.yml"];
1916
2392
  const missing = required.filter((file) => !fs.exists(join(aiw, file)));
@@ -1946,7 +2422,22 @@ export async function runCommand(args, root, fs, services = {}) {
1946
2422
  catch (error) {
1947
2423
  return { exitCode: 1, error: error instanceof Error ? error.message : String(error) };
1948
2424
  }
1949
- return { exitCode: 0, output: "AI Workflow health check passed." };
2425
+ // FRIC-004: interactive doctor offers telemetry consent once when unset.
2426
+ let telemetryNote = "";
2427
+ if (stdin.isTTY) {
2428
+ const terminal = createInterface({ input: stdin, output: stdout });
2429
+ try {
2430
+ const consent = await maybeOfferTelemetryConsent(fs, aiw, true, (question) => terminal.question(question));
2431
+ if (consent.prompted)
2432
+ telemetryNote = consent.enabled
2433
+ ? "\nTelemetry enabled. Disable anytime with `aiw telemetry disable`."
2434
+ : "\nTelemetry remains disabled. Enable anytime with `aiw telemetry enable`.";
2435
+ }
2436
+ finally {
2437
+ terminal.close();
2438
+ }
2439
+ }
2440
+ return { exitCode: 0, output: `AI Workflow health check passed.${telemetryNote}` };
1950
2441
  }
1951
2442
  if (command === "repair") {
1952
2443
  if (!fs.exists(join(aiw, "manifest.yml")))
@@ -2053,7 +2544,7 @@ export async function runCommand(args, root, fs, services = {}) {
2053
2544
  return installationRequired();
2054
2545
  assertStageReady(aiw, fs, "brainstorming");
2055
2546
  const title = args.find((arg) => arg.startsWith("--title="))?.slice(8) || "Untitled Brainstorm";
2056
- const path = join(aiw, "generated/specs/brainstorm.md");
2547
+ const path = stageArtifactWritePath(fs, aiw, "brainstorming");
2057
2548
  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
2549
  return { exitCode: 0, output: `Brainstorm artifact created: ${path}` };
2059
2550
  }
@@ -2065,7 +2556,7 @@ export async function runCommand(args, root, fs, services = {}) {
2065
2556
  const ticket = args.find((arg) => arg.startsWith("--ticket="))?.slice(9);
2066
2557
  if (ticket !== undefined)
2067
2558
  validateTaskTicket(ticket);
2068
- const path = join(aiw, "generated/specs/specification.md");
2559
+ const path = stageArtifactWritePath(fs, aiw, "specification");
2069
2560
  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
2561
  return { exitCode: 0, output: `Specification artifact created: ${path}` };
2071
2562
  }
@@ -2073,9 +2564,20 @@ export async function runCommand(args, root, fs, services = {}) {
2073
2564
  if (!fs.exists(join(aiw, "manifest.yml")))
2074
2565
  return installationRequired();
2075
2566
  assertStageReady(aiw, fs, "technical-design");
2076
- const id = args.find((arg) => arg.startsWith("--id="))?.slice(5) || "001";
2567
+ const explicitId = args.find((arg) => arg.startsWith("--id="))?.slice(5);
2077
2568
  const title = args.find((arg) => arg.startsWith("--title="))?.slice(8) || "Untitled Decision";
2078
- const path = join(root, ".context/adrs", `ADR-${id}-${title.toLowerCase().replaceAll(" ", "-")}.md`);
2569
+ // Unix-time (ms) default: chronological sequence, collision-resistant.
2570
+ // A monotonic guard guarantees distinct ids even within the same
2571
+ // millisecond; same-ms creations bump until the path is free.
2572
+ const slug = title.toLowerCase().replaceAll(" ", "-");
2573
+ adrLastStamp = Math.max(adrLastStamp + 1, Date.now());
2574
+ let stamp = adrLastStamp;
2575
+ if (!explicitId)
2576
+ while (fs.exists(join(root, ".context/adrs", `ADR-${stamp}-${slug}.md`)))
2577
+ stamp += 1;
2578
+ adrLastStamp = stamp;
2579
+ const id = explicitId ?? String(stamp);
2580
+ const path = join(root, ".context/adrs", `ADR-${id}-${slug}.md`);
2079
2581
  fs.write(path, `# ADR-${id}: ${title}\n\n- **Status:** proposed\n- **Related artifacts:**\n - .aiw/generated/specs/\n\n## Context\n\n## Alternatives\n\n1. **Alternative A** — Description and trade-offs.\n2. **Alternative B** — Description and trade-offs.\n\n## Decision\n\n## Rationale\n\n## Consequences\n\n`);
2080
2582
  return { exitCode: 0, output: `Architecture decision record created: ${path}` };
2081
2583
  }
@@ -2084,7 +2586,7 @@ export async function runCommand(args, root, fs, services = {}) {
2084
2586
  return installationRequired();
2085
2587
  assertStageReady(aiw, fs, "plan");
2086
2588
  const title = args.find((arg) => arg.startsWith("--title="))?.slice(8) || "Untitled Implementation Plan";
2087
- const path = join(aiw, "generated/plans/implementation-plan.md");
2589
+ const path = stageArtifactWritePath(fs, aiw, "plan");
2088
2590
  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
2591
  return { exitCode: 0, output: `Implementation plan created: ${path}` };
2090
2592
  }
@@ -2092,8 +2594,8 @@ export async function runCommand(args, root, fs, services = {}) {
2092
2594
  if (!fs.exists(join(aiw, "manifest.yml")))
2093
2595
  return installationRequired();
2094
2596
  assertStageReady(aiw, fs, "verification");
2095
- const specPath = join(aiw, "generated/specs/specification.md");
2096
- const planPath = join(aiw, "generated/plans/implementation-plan.md");
2597
+ const specPath = resolveStageArtifact(fs, aiw, "specification", activeWorkflowId(fs, aiw)).path;
2598
+ const planPath = resolveStageArtifact(fs, aiw, "plan", activeWorkflowId(fs, aiw)).path;
2097
2599
  const issues = [];
2098
2600
  let regressionNotice;
2099
2601
  let specification = "";
@@ -2133,8 +2635,8 @@ export async function runCommand(args, root, fs, services = {}) {
2133
2635
  if (!fs.exists(join(aiw, "manifest.yml")))
2134
2636
  return installationRequired();
2135
2637
  assertStageReady(aiw, fs, "traceability");
2136
- const specPath = join(aiw, "generated/specs/specification.md");
2137
- const planPath = join(aiw, "generated/plans/implementation-plan.md");
2638
+ const specPath = resolveStageArtifact(fs, aiw, "specification", activeWorkflowId(fs, aiw)).path;
2639
+ const planPath = resolveStageArtifact(fs, aiw, "plan", activeWorkflowId(fs, aiw)).path;
2138
2640
  if (!fs.exists(specPath) || !fs.exists(planPath))
2139
2641
  return {
2140
2642
  exitCode: 1,
@@ -2156,7 +2658,7 @@ export async function runCommand(args, root, fs, services = {}) {
2156
2658
  const serialized = serializeTraceabilityGraph(graph, requirement);
2157
2659
  if (requirement)
2158
2660
  return { exitCode: 0, output: serialized };
2159
- const path = join(aiw, "generated/artifacts/traceability.yml");
2661
+ const path = stageArtifactWritePath(fs, aiw, "traceability");
2160
2662
  fs.write(path, serialized);
2161
2663
  return { exitCode: 0, output: `Traceability graph created: ${path}` };
2162
2664
  }
@@ -2329,7 +2831,7 @@ export async function runCommand(args, root, fs, services = {}) {
2329
2831
  const lines = [];
2330
2832
  let served = 0;
2331
2833
  for (const stage of stages) {
2332
- const artifactPath = approvalArtifactPath(aiw, stage);
2834
+ const artifactPath = approvalArtifactPath(fs, aiw, stage);
2333
2835
  const freshness = digestFreshness(aiw, fs, stage, artifactPath ?? undefined);
2334
2836
  if (freshness.state === "missing")
2335
2837
  continue;
@@ -2349,7 +2851,7 @@ export async function runCommand(args, root, fs, services = {}) {
2349
2851
  return installationRequired();
2350
2852
  assertStageReady(aiw, fs, "diagnosis");
2351
2853
  const title = args.find((argument) => argument.startsWith("--title="))?.slice(8) || "Untitled Diagnosis";
2352
- const path = join(aiw, "generated/reports/diagnosis.md");
2854
+ const path = stageArtifactWritePath(fs, aiw, "diagnosis");
2353
2855
  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
2856
  return { exitCode: 0, output: `Diagnosis artifact created: ${path}` };
2355
2857
  }
@@ -2358,14 +2860,14 @@ export async function runCommand(args, root, fs, services = {}) {
2358
2860
  return installationRequired();
2359
2861
  assertStageReady(aiw, fs, "assessment");
2360
2862
  const title = args.find((argument) => argument.startsWith("--title="))?.slice(8) || "Untitled Assessment";
2361
- const path = join(aiw, "generated/reports/assessment.md");
2863
+ const path = stageArtifactWritePath(fs, aiw, "assessment");
2362
2864
  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
2865
  return { exitCode: 0, output: `Assessment artifact created: ${path}` };
2364
2866
  }
2365
2867
  if (command === "risk") {
2366
2868
  if (args[1] !== "assess")
2367
2869
  return { exitCode: 1, error: "Usage: aiw risk assess [--base-ref=ref] [--json]" };
2368
- return runRiskAssess(args.slice(2), root, fs);
2870
+ return runRiskAssess(args.slice(2), root, fs, services.embeddingProvider);
2369
2871
  }
2370
2872
  if (command === "gate") {
2371
2873
  if (!fs.exists(join(aiw, "manifest.yml")))
@@ -2378,11 +2880,11 @@ export async function runCommand(args, root, fs, services = {}) {
2378
2880
  };
2379
2881
  const workflowStage = stage;
2380
2882
  assertStageReady(aiw, fs, workflowStage);
2381
- const artifactPath = approvalArtifactPath(aiw, workflowStage);
2883
+ const artifactPath = approvalArtifactPath(fs, aiw, workflowStage);
2382
2884
  if (!artifactPath || !fs.exists(artifactPath))
2383
2885
  throw new BlockingError(describeBlockingReason("gate_evidence_missing", {
2384
2886
  stage,
2385
- artifactPath: artifactPath ?? undefined,
2887
+ artifactPath: stageArtifactWritePath(fs, aiw, workflowStage),
2386
2888
  detail: `Quality gate blocked: required evidence is missing for ${stage}.`,
2387
2889
  }));
2388
2890
  const hasQualityGate = stageDefinition(workflowStage).requiresQualityGate;
@@ -2416,7 +2918,7 @@ export async function runCommand(args, root, fs, services = {}) {
2416
2918
  fs.write(join(aiw, "approvals.yml"), serializeApprovalLedger(updated));
2417
2919
  return {
2418
2920
  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}.`,
2921
+ 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
2922
  };
2421
2923
  }
2422
2924
  if (command === "validate") {
@@ -2570,7 +3072,7 @@ export async function runCommand(args, root, fs, services = {}) {
2570
3072
  return installationRequired();
2571
3073
  const packageArg = args.find((arg) => arg.startsWith("--package="));
2572
3074
  if (!packageArg)
2573
- return { exitCode: 1, error: "Usage: aiw update --package=path --target=target" };
3075
+ return await runBundledUpdate(args, root, fs, aiw, services);
2574
3076
  const manifestPath = resolve(root, packageArg.slice(10));
2575
3077
  const manifestBytes = fs.readBytes?.(manifestPath);
2576
3078
  const manifestContent = manifestBytes
@@ -2688,7 +3190,7 @@ export async function runCommand(args, root, fs, services = {}) {
2688
3190
  const digestLines = [];
2689
3191
  if (fs.exists(join(aiw, "workflow.yml"))) {
2690
3192
  for (const stage of processStages(readWorkflowState(aiw, fs, false).ledger)) {
2691
- const artifactPath = approvalArtifactPath(aiw, stage);
3193
+ const artifactPath = approvalArtifactPath(fs, aiw, stage);
2692
3194
  const freshness = digestFreshness(aiw, fs, stage, artifactPath ?? undefined);
2693
3195
  if (freshness.state !== "missing")
2694
3196
  digestLines.push(formatDigestLine(freshness));
@@ -2826,7 +3328,7 @@ export async function runCommand(args, root, fs, services = {}) {
2826
3328
  exitCode: 1,
2827
3329
  error: "No usage sidecar recorded yet. Record runs with `aiw usage-sidecar record` or run `aiw scan`.",
2828
3330
  };
2829
- const tracePath = join(aiw, "generated/artifacts/traceability.yml");
3331
+ const tracePath = resolveStageArtifact(fs, aiw, "traceability", activeWorkflowId(fs, aiw)).path;
2830
3332
  if (!fs.exists(tracePath))
2831
3333
  return {
2832
3334
  exitCode: 1,
@@ -2882,6 +3384,30 @@ export async function runCommand(args, root, fs, services = {}) {
2882
3384
  const { state: nextState, outcome } = recordBeat(state, session, new Date(), warnSeconds, ttlSeconds);
2883
3385
  fs.write(statePath, serializeHeartbeatState(nextState));
2884
3386
  const lines = [describeHeartbeatOutcome(outcome)];
3387
+ // REQ-003 wiring: a new session is the boundary where the previous
3388
+ // session's rejections become monitor occurrences. Monitor failures
3389
+ // must never break the heartbeat.
3390
+ if (outcome.decision === "session-start") {
3391
+ try {
3392
+ const ledgerPath = join(aiw, "approvals.yml");
3393
+ if (fs.exists(ledgerPath)) {
3394
+ const artifacts = harvestApprovalObservations(fs.read(ledgerPath));
3395
+ if (artifacts.length > 0) {
3396
+ const proposalsPath = join(aiw, "proposals.yml");
3397
+ const store = fs.exists(proposalsPath)
3398
+ ? parseProposalStore(fs.read(proposalsPath))
3399
+ : createEmptyStore();
3400
+ const { surfaced } = monitorSession(store, artifacts);
3401
+ fs.write(proposalsPath, serializeProposalStore(store));
3402
+ if (surfaced.length > 0)
3403
+ lines.push(`monitor: ${surfaced.length} recurring pattern(s) crossed the proposal threshold — run aiw proposals list`);
3404
+ }
3405
+ }
3406
+ }
3407
+ catch {
3408
+ // observation is best-effort; heartbeat stays authoritative
3409
+ }
3410
+ }
2885
3411
  if (outcome.checkpoint) {
2886
3412
  const checkpointPath = join(aiw, `checkpoints/heartbeat-${session}-${outcome.checkpoint.index}.yml`);
2887
3413
  fs.write(checkpointPath, serializeHeartbeatCheckpoint(outcome.checkpoint, outcome.gapSeconds ?? 0, ttlSeconds));
@@ -3180,7 +3706,7 @@ export async function runCommand(args, root, fs, services = {}) {
3180
3706
  }
3181
3707
  return {
3182
3708
  exitCode: 0,
3183
- 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]",
3709
+ 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 [--dry-run] [--add=type/id,...] | update --package=path --target=target | validate [--package=path]",
3184
3710
  };
3185
3711
  }
3186
3712
  catch (error) {
@@ -3209,7 +3735,7 @@ function readWorkflowState(aiw, fs, requireActive = true) {
3209
3735
  const record = ledger.stages[stage];
3210
3736
  if (!record?.artifactHash || !["pending-human", "approved"].includes(record.status))
3211
3737
  return false;
3212
- const artifact = approvalArtifactPath(aiw, stage);
3738
+ const artifact = approvalArtifactPath(fs, aiw, stage);
3213
3739
  return (!artifact ||
3214
3740
  !fs.exists(artifact) ||
3215
3741
  stageFingerprint(fs.read(artifact)) !== record.artifactHash);
@@ -3263,7 +3789,7 @@ function normalizeCommand(command) {
3263
3789
  * Legacy plans without pair arrows are accepted unchanged (ratchet).
3264
3790
  */
3265
3791
  export function compareVerificationPairs(aiw, fs, stage) {
3266
- const planPath = join(aiw, "generated/plans/implementation-plan.md");
3792
+ const planPath = resolveStageArtifact(fs, aiw, "plan", activeWorkflowId(fs, aiw)).path;
3267
3793
  if (!fs.exists(planPath))
3268
3794
  return [];
3269
3795
  const plan = fs.read(planPath);
@@ -3287,9 +3813,7 @@ export function compareVerificationPairs(aiw, fs, stage) {
3287
3813
  }
3288
3814
  if (declared.length === 0)
3289
3815
  return [];
3290
- const reportPath = stage === "implementation"
3291
- ? join(aiw, "generated/reports/implementation-report.md")
3292
- : join(aiw, "generated/reports/verification-report.md");
3816
+ const reportPath = resolveStageArtifact(fs, aiw, stage === "implementation" ? "implementation" : "verification", activeWorkflowId(fs, aiw)).path;
3293
3817
  const issues = [];
3294
3818
  const observed = new Map();
3295
3819
  if (fs.exists(reportPath)) {
@@ -3369,21 +3893,8 @@ function assertStageReady(aiw, fs, stage) {
3369
3893
  detail: `${stage} is already approved. Evidence changes require rerunning its gate.`,
3370
3894
  }));
3371
3895
  }
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]);
3896
+ function approvalArtifactPath(fs, aiw, stage) {
3897
+ return resolveStageArtifact(fs, aiw, stage, activeWorkflowId(fs, aiw)).path;
3387
3898
  }
3388
3899
  function formatConfidence(confidence) {
3389
3900
  return confidence === undefined ? "unknown" : confidence.toFixed(3);
@@ -3564,6 +4075,7 @@ function syncSelectedResources(fs, root, aiw, profile, selected, apply = false,
3564
4075
  resourceId: id,
3565
4076
  });
3566
4077
  };
4078
+ const semanticRetrieval = semanticRetrievalAvailable(fs, aiw);
3567
4079
  for (const reference of resourceSelections) {
3568
4080
  const key = `${reference.type}/${reference.id}`;
3569
4081
  const resource = bundleByKey.get(key);
@@ -3573,7 +4085,7 @@ function syncSelectedResources(fs, root, aiw, profile, selected, apply = false,
3573
4085
  }
3574
4086
  generateProjectResources(profile, selected, (path, content) => {
3575
4087
  generatedFiles.set(join(aiw, path), content);
3576
- const rule = path.match(/^generated\/rules\/(project-quality|tdd-project-policy)\.md$/);
4088
+ const rule = path.match(/^generated\/rules\/(project-quality|tdd-project-policy|semantic-retrieval)\.md$/);
3577
4089
  if (rule)
3578
4090
  addResource("rules", rule[1], content);
3579
4091
  const rootContext = path === "generated/context/root-context.md";
@@ -3595,7 +4107,7 @@ function syncSelectedResources(fs, root, aiw, profile, selected, apply = false,
3595
4107
  });
3596
4108
  }
3597
4109
  }
3598
- });
4110
+ }, semanticRetrieval);
3599
4111
  const ownershipPath = join(aiw, "ownership.yml");
3600
4112
  if (fs.pathType?.(ownershipPath) !== "file")
3601
4113
  return {