@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/CHANGELOG.md CHANGED
@@ -4,6 +4,28 @@ All notable changes to this project are documented in this file. The format foll
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.17.0] - 2026-11-27
8
+
9
+ ### Added
10
+
11
+ - Bounded `research` skill (RES-001): evidence-first, budget-capped investigations from a single question — scope gate with human confirmation, stop conditions and escalation, verifiable citations (`file:line` / log line / URL + consultation date) with fact/hypothesis/unverified states, secret redaction before host-side external queries, and a durable workflow-scoped `research.md` artifact recorded through light-lane evidence. Offered as the advisory `bounded-research` recommendation; covered by the packaged-skill eval contracts.
12
+ - Bundled-resource update command (UPD-001): `aiw update [--dry-run] [--add=type/id,...]` diffs installed resources against the CLI's catalog (updated/new/unchanged), replaces only files whose ownership checksum proves they are unmodified (manual edits are preserved as typed `update_conflict` blocks with continuations), installs catalog resources additively via `--add` without re-running the recommendation wizard, and is non-interactive, deterministic, and idempotent.
13
+ - `aiw adr` now defaults to monotonic unix-time (millisecond) ids — chronological, collision-resistant numbering for parallel or rapid ADR creation; explicit `--id=` is unchanged.
14
+
15
+ ### Fixed
16
+
17
+ - Blocking errors from the new update flow are returned as typed results like every other blocking path (latent `return` vs `return await` in the update branch).
18
+
19
+ ## [0.16.0] - 2026-11-18
20
+
21
+ ### Added
22
+
23
+ - Adaptive resource evaluator: dynamic skill/agent/rule proposals from deterministic project signals — signal collection into `.aiw/eval/signals.yml`, a lifecycle-managed anti-spam proposal store, `aiw eval` brief emitter, session-boundary monitor, and human-gated approval with provenance-marked generation under `generated/`.
24
+ - Workflow friction review (dogfooding fixes): a semantic-retrieval-first rule is generated when semantic mapping is enabled (FRIC-001); `task start` works without a ticket, self-serving local `LOCAL-###` identifiers sequenced across archived sessions (FRIC-002); interactive `doctor` offers telemetry consent once when unset, with the privacy summary and reversible enable/disable (FRIC-004); `workflow complete` (full and light lanes) prints a usage/cost summary and writes `.aiw/generated/reports/usage-<workflowId>.md` from sidecar/traceability data, degrading to advisories when absent (FRIC-003).
25
+ - Per-workflow generated artifacts (FRIC-005): stage artifacts live under `generated/<kind>/<workflowId>/` so sequential workflows never overwrite each other; gates, approval fingerprints, verification pairs, traceability, and the dashboard resolve the scoped path first and read legacy fixed paths with an advisory; completion archives the workflow's artifacts to `checkpoints/workflow-<id>-artifacts/` (ADR-002).
26
+ - Decision-model findings triage and lane scope-watch (OPP-007, advisory-only): `aiw decision findings-triage --findings=<path>` runs the deterministic shape check always and, when enabled, one batched evidence-supported question per severe finding (the refuter still owns corroboration); light-lane completion records the tier-vs-lane mismatch advisory and an optional semantic scope-watch line. Routing categories `review.findings-triage` and `workflow.lane-watch` follow the evidence-linked contract.
27
+ - Embedding covering-test detection and judge context scoping (OPP-008, fail-safe): `aiw risk assess` consults the semantic index before asserting `untested_regression` — retrieval can only prevent false flags (`covering: semantic-retrieval` audit label; tiers stay rule-based; no config/`index` or an unreachable model keeps the deterministic sibling heuristic byte-identical); `aiw semantic judge-context --paths=…` renders bounded, labeled context aids for review judges and the refuter.
28
+
7
29
  ## [0.15.0] - 2026-11-04
8
30
 
9
31
  ### Added
package/README.md CHANGED
@@ -64,7 +64,7 @@ For a Codex installation, the base layout is:
64
64
 
65
65
  `.aiw/` stores the provider-neutral manifest, profile, lockfile, checkpoints, bootstrap skill, selected resources, and generated working artifacts. ADRs are stored under `.context/adrs/`. The installer intentionally adds only `ai-init` and the base project state.
66
66
 
67
- Run `/ai-init` in the selected coding agent to scan the project and review evidence-based recommendations for skills, rules, agents, hooks, and templates. AI Workflow installs only the resources the user selects, then generates project-specific quality guidance from the detected stack and tools. Syncing a non-empty selection also renders a root context file for the active target — `AGENTS.md` (Codex/Cursor), `CLAUDE.md` (Claude Code), `GEMINI.md` (Gemini CLI) — with the confirmed profile, quality commands, and pointers to `.aiw/` state; `aiw target` migrates it between targets. An existing hand-written root context file is reported as a conflict and never overwritten. Existing user files are preserved; conflicts are reported instead of overwritten. Hook resources are rendered according to each adapter's native or compatibility support.
67
+ Run `/ai-init` in the selected coding agent to scan the project and review evidence-based recommendations for skills, rules, agents, hooks, and templates. AI Workflow installs only the resources the user selects, then generates project-specific quality guidance from the detected stack and tools. Among the packaged skills, `research` runs a bounded, evidence-first investigation from a single question (logs, errors, code, or host-side external sources) and records a durable workflow-scoped artifact for later stages. Syncing a non-empty selection also renders a root context file for the active target — `AGENTS.md` (Codex/Cursor), `CLAUDE.md` (Claude Code), `GEMINI.md` (Gemini CLI) — with the confirmed profile, quality commands, and pointers to `.aiw/` state; `aiw target` migrates it between targets. An existing hand-written root context file is reported as a conflict and never overwritten. Existing user files are preserved; conflicts are reported instead of overwritten. Hook resources are rendered according to each adapter's native or compatibility support.
68
68
 
69
69
  The installer does not modify `.gitignore`. Add `.aiw/generated/` yourself if generated specifications, plans, and artifacts should remain local. Versioned files under `.aiw/checkpoints/` are designed to remain reviewable project history.
70
70
 
@@ -203,6 +203,13 @@ npx @multileaf/ai-workflow recommend
203
203
  # In CI, provide comma-separated recommendation IDs detected for that project.
204
204
  npx @multileaf/ai-workflow recommend --select=typescript-quality,verification
205
205
 
206
+ # Bring installed bundled resources to the current CLI version, drift-safe
207
+ # (manual edits are preserved as conflicts), and add catalog resources
208
+ # additively without re-running the recommendation wizard.
209
+ npx @multileaf/ai-workflow update --dry-run
210
+ npx @multileaf/ai-workflow update
211
+ npx @multileaf/ai-workflow update --add=skills/research
212
+
206
213
  # Track a feature from its first artifact through final human approval.
207
214
  npx @multileaf/ai-workflow workflow start
208
215
 
@@ -213,6 +220,17 @@ npx @multileaf/ai-workflow task evidence --validation="npm test: passed"
213
220
  npx @multileaf/ai-workflow workflow complete
214
221
  # If scope grows: aiw task escalate --reason=...
215
222
 
223
+ # Stage artifacts live under workflow-scoped paths
224
+ # (.aiw/generated/<kind>/<workflowId>/…) so concurrent or sequential workflows
225
+ # never overwrite each other; legacy fixed paths are still read with an advisory,
226
+ # and completion archives the workflow's artifacts to
227
+ # .aiw/checkpoints/workflow-<id>-artifacts/.
228
+
229
+ # Completion prints a usage/cost summary (tokens, models, cost attribution when
230
+ # a traceability graph exists, stage timeline) and writes a durable report to
231
+ # .aiw/generated/reports/usage-<workflowId>.md. With no recorded usage it says
232
+ # so and suggests `aiw usage-sidecar record --workflow=<id-or-ticket>`.
233
+
216
234
  # Classify the risk of current changes (read-only; content, not size).
217
235
  npx @multileaf/ai-workflow risk assess [--base-ref=<ref>] [--escalate-item=1-6 --escalate-reason=text] [--json]
218
236
 
package/dist/adapter.js CHANGED
@@ -67,9 +67,9 @@ For every CLI command below, use \`npx --yes --package=@multileaf/ai-workflow --
67
67
 
68
68
  - Use the brainstorming skill when scope, users, constraints, or assumptions are unclear; create its artifact with \`npx --yes --package=@multileaf/ai-workflow -- aiw brainstorm\`, validate it with \`npx --yes --package=@multileaf/ai-workflow -- aiw gate brainstorming\`, present it, wait, then record the reply with \`npx --yes --package=@multileaf/ai-workflow -- aiw approve brainstorming\` before specification. If unnecessary, ask to skip and record explicit acceptance with \`npx --yes --package=@multileaf/ai-workflow -- aiw skip brainstorming --reason=...\`.
69
69
  - Create a specification with stable requirement IDs and Given/When/Then acceptance criteria; pass \`npx --yes --package=@multileaf/ai-workflow -- aiw gate specification\`, present it, wait, and record approval before design or planning.
70
- - For changes with architecture impact, write \`.aiw/generated/reports/technical-design.md\` using the technical-design template, record consequential choices as ADRs, pass \`npx --yes --package=@multileaf/ai-workflow -- aiw gate technical-design\`, and obtain/record approval before planning. If design is unnecessary, obtain explicit acceptance and record a reasoned skip. Then create an implementation plan with \`npx --yes --package=@multileaf/ai-workflow -- aiw plan\`, pass \`npx --yes --package=@multileaf/ai-workflow -- aiw gate plan\`, present it, wait, and record approval before coding.
71
- - When TDD resources are installed and the project has a test workflow, follow the TDD policy; otherwise use the project's existing validation methods. Follow installed project quality rules and use specialist agents only when useful. After implementation, write \`.aiw/generated/reports/implementation-report.md\` with changed files, tests, validation, and deviations; pass \`npx --yes --package=@multileaf/ai-workflow -- aiw gate implementation\`, present the diff/evidence, wait, and record approval before verification.
72
- - Run declared checks, write \`.aiw/generated/reports/verification-report.md\`, pass \`npx --yes --package=@multileaf/ai-workflow -- aiw gate verification\`, run \`npx --yes --package=@multileaf/ai-workflow -- aiw verify\`, present results, wait, and record approval before review. Write \`.aiw/generated/reports/code-review.md\` with findings/checks/risks/decision, pass \`npx --yes --package=@multileaf/ai-workflow -- aiw gate review\`, present findings, wait, and record approval before \`npx --yes --package=@multileaf/ai-workflow -- aiw trace\`. Pass \`npx --yes --package=@multileaf/ai-workflow -- aiw gate traceability\`, present the final graph, wait, record approval, then complete the workflow. Do not claim completion without evidence.
70
+ - For changes with architecture impact, write the technical-design report at the workflow-scoped path printed by the CLI, record consequential choices as ADRs, pass \`npx --yes --package=@multileaf/ai-workflow -- aiw gate technical-design\`, and obtain/record approval before planning. If design is unnecessary, obtain explicit acceptance and record a reasoned skip. Then create an implementation plan with \`npx --yes --package=@multileaf/ai-workflow -- aiw plan\`, pass \`npx --yes --package=@multileaf/ai-workflow -- aiw gate plan\`, present it, wait, and record approval before coding.
71
+ - When TDD resources are installed and the project has a test workflow, follow the TDD policy; otherwise use the project's existing validation methods. Follow installed project quality rules and use specialist agents only when useful. After implementation, write the implementation report at the workflow-scoped path printed by the CLI with changed files, tests, validation, and deviations; pass \`npx --yes --package=@multileaf/ai-workflow -- aiw gate implementation\`, present the diff/evidence, wait, and record approval before verification.
72
+ - Run declared checks, write the verification report at the workflow-scoped path printed by the CLI, pass \`npx --yes --package=@multileaf/ai-workflow -- aiw gate verification\`, run \`npx --yes --package=@multileaf/ai-workflow -- aiw verify\`, present results, wait, and record approval before review. Write the code-review report at the workflow-scoped path printed by the CLI with findings/checks/risks/decision, pass \`npx --yes --package=@multileaf/ai-workflow -- aiw gate review\`, present findings, wait, and record approval before \`npx --yes --package=@multileaf/ai-workflow -- aiw trace\`. Pass \`npx --yes --package=@multileaf/ai-workflow -- aiw gate traceability\`, present the final graph, wait, record approval, then complete the workflow. Do not claim completion without evidence.
73
73
 
74
74
  ## Language policy
75
75
 
@@ -0,0 +1,16 @@
1
+ import type { FileSystem } from "./types.js";
2
+ import type { HumanApprovalStage } from "./types.js";
3
+ export type StageArtifactPaths = {
4
+ scoped: string | undefined;
5
+ legacy: string;
6
+ };
7
+ /** Scoped layout: generated/<kind>/<workflowId>/<name> (ADR-002). */
8
+ export declare function stageArtifactPaths(aiw: string, stage: HumanApprovalStage, workflowId?: string): StageArtifactPaths;
9
+ export type ResolvedStageArtifact = {
10
+ path: string;
11
+ legacyFallback: boolean;
12
+ };
13
+ /** Prefer the workflow-scoped artifact; fall back to the legacy fixed path (REQ-004). */
14
+ export declare function resolveStageArtifact(fs: FileSystem, aiw: string, stage: HumanApprovalStage, workflowId?: string): ResolvedStageArtifact;
15
+ /** Archive generated/<kind>/<workflowId>/ trees to checkpoints/workflow-<id>-artifacts/ (REQ-005). */
16
+ export declare function archiveWorkflowArtifacts(fs: FileSystem, aiw: string, workflowId: string): string[];
@@ -0,0 +1,51 @@
1
+ import { join } from "path";
2
+ /** FRIC-005: legacy fixed artifact path per stage (pre-namespacing layout). */
3
+ const LEGACY_STAGE_PATHS = {
4
+ brainstorming: "generated/specs/brainstorm.md",
5
+ specification: "generated/specs/specification.md",
6
+ "technical-design": "generated/reports/technical-design.md",
7
+ plan: "generated/plans/implementation-plan.md",
8
+ implementation: "generated/reports/implementation-report.md",
9
+ verification: "generated/reports/verification-report.md",
10
+ review: "generated/reports/code-review.md",
11
+ traceability: "generated/artifacts/traceability.yml",
12
+ diagnosis: "generated/reports/diagnosis.md",
13
+ assessment: "generated/reports/assessment.md",
14
+ };
15
+ /** Scoped layout: generated/<kind>/<workflowId>/<name> (ADR-002). */
16
+ export function stageArtifactPaths(aiw, stage, workflowId) {
17
+ const legacy = join(aiw, LEGACY_STAGE_PATHS[stage]);
18
+ if (!workflowId)
19
+ return { scoped: undefined, legacy };
20
+ const [, kind, name] = LEGACY_STAGE_PATHS[stage].split("/");
21
+ return { scoped: join(aiw, "generated", kind, workflowId, name), legacy };
22
+ }
23
+ /** Prefer the workflow-scoped artifact; fall back to the legacy fixed path (REQ-004). */
24
+ export function resolveStageArtifact(fs, aiw, stage, workflowId) {
25
+ const { scoped, legacy } = stageArtifactPaths(aiw, stage, workflowId);
26
+ if (scoped && fs.exists(scoped))
27
+ return { path: scoped, legacyFallback: false };
28
+ return { path: legacy, legacyFallback: Boolean(scoped) && fs.exists(legacy) };
29
+ }
30
+ const KINDS = ["specs", "plans", "reports", "artifacts"];
31
+ /** Archive generated/<kind>/<workflowId>/ trees to checkpoints/workflow-<id>-artifacts/ (REQ-005). */
32
+ export function archiveWorkflowArtifacts(fs, aiw, workflowId) {
33
+ const archived = [];
34
+ const destinationRoot = join(aiw, "checkpoints", `workflow-${workflowId}-artifacts`);
35
+ for (const kind of KINDS) {
36
+ const sourceDir = join(aiw, "generated", kind, workflowId);
37
+ if (!fs.exists(sourceDir) || !fs.list)
38
+ continue;
39
+ const destinationDir = join(destinationRoot, kind);
40
+ const names = fs.list(sourceDir) ?? [];
41
+ if (names.length === 0)
42
+ continue;
43
+ fs.mkdir(destinationDir);
44
+ for (const name of names) {
45
+ const content = fs.read(join(sourceDir, name));
46
+ fs.write(join(destinationDir, name), content);
47
+ archived.push(`${kind}/${name}`);
48
+ }
49
+ }
50
+ return archived;
51
+ }
@@ -7,7 +7,7 @@
7
7
  * command resolves the block it was printed for. See ADR-001 and
8
8
  * docs/opportunities/OPP-004-exact-continuation-commands.md.
9
9
  */
10
- export declare const BLOCKING_REASON_CODES: readonly ["gate_evidence_missing", "gate_incomplete", "stage_prerequisite_pending", "stage_prerequisite_unresolved", "stage_awaiting_approval", "stage_already_approved", "approval_evidence_missing", "approval_stale", "approval_gate_missing", "lane_escalation_required", "light_evidence_missing", "workflow_still_active", "workflow_not_active", "workflow_complete", "installation_required", "state_mismatch", "context_budget_exceeded", "stage_not_in_process", "migration_required", "worktrees_leaked", "orchestration_not_executed"];
10
+ export declare const BLOCKING_REASON_CODES: readonly ["gate_evidence_missing", "gate_incomplete", "stage_prerequisite_pending", "stage_prerequisite_unresolved", "stage_awaiting_approval", "stage_already_approved", "approval_evidence_missing", "approval_stale", "approval_gate_missing", "lane_escalation_required", "light_evidence_missing", "workflow_still_active", "workflow_not_active", "workflow_complete", "installation_required", "state_mismatch", "context_budget_exceeded", "stage_not_in_process", "migration_required", "worktrees_leaked", "orchestration_not_executed", "update_conflict"];
11
11
  export type BlockingReasonCode = (typeof BLOCKING_REASON_CODES)[number];
12
12
  /** How the user or agent gets past a block. Exactly one of three kinds. */
13
13
  export type BlockingContinuation =
@@ -29,6 +29,7 @@ export const BLOCKING_REASON_CODES = [
29
29
  "migration_required",
30
30
  "worktrees_leaked",
31
31
  "orchestration_not_executed",
32
+ "update_conflict",
32
33
  ];
33
34
  function command(commandText) {
34
35
  return { kind: "command", command: commandText };
@@ -172,6 +173,11 @@ export const BLOCKING_REASON_INVENTORY = {
172
173
  description: "The plan has not been executed yet; there is no checkpoint to integrate.",
173
174
  continuation: () => action("Run `aiw orchestrate --plan=<path> --execute` first; integration forecasts need the checkpoint evidence."),
174
175
  },
176
+ update_conflict: {
177
+ code: "update_conflict",
178
+ description: "Manually edited installed resources conflict with a bundled update; they are preserved, never overwritten.",
179
+ continuation: (context) => action(`Review the conflicted file(s)${context.detail ? ` (${context.detail})` : ""}, port your edits onto the new version manually or discard them, then rerun \`aiw update\`.`),
180
+ },
175
181
  };
176
182
  export function getBlockingReasonDefinition(code) {
177
183
  const definition = BLOCKING_REASON_INVENTORY[code];
@@ -0,0 +1,17 @@
1
+ import type { CostAttribution, TaskUsageSummary } from "./cost-attribution.js";
2
+ import type { ApprovalLedger, WorkflowSession } from "./human-approval.js";
3
+ export type CompletionReportInput = {
4
+ session: WorkflowSession;
5
+ ledger: ApprovalLedger;
6
+ usage?: TaskUsageSummary;
7
+ attribution?: CostAttribution;
8
+ };
9
+ export type CompletionReport = {
10
+ markdown: string;
11
+ consoleSummary: string;
12
+ };
13
+ /**
14
+ * FRIC-003: build the usage/cost completion report from data AI Workflow
15
+ * already records. Pure function — no filesystem access.
16
+ */
17
+ export declare function buildCompletionReport(input: CompletionReportInput): CompletionReport;
@@ -0,0 +1,42 @@
1
+ import { serializeCostAttribution, serializeTaskUsage } from "./cost-attribution.js";
2
+ /**
3
+ * FRIC-003: build the usage/cost completion report from data AI Workflow
4
+ * already records. Pure function — no filesystem access.
5
+ */
6
+ export function buildCompletionReport(input) {
7
+ const { session, ledger, usage, attribution } = input;
8
+ const scope = session.ticket ?? session.workflowId;
9
+ const usageSection = usage
10
+ ? serializeTaskUsage(usage)
11
+ : `No usage recorded for workflow ${scope}. Record runs with \`aiw usage-sidecar record --workflow=${scope}\`.`;
12
+ const attributionSection = attribution
13
+ ? serializeCostAttribution(attribution)
14
+ : "Cost attribution skipped: no traceability graph available for this workflow.";
15
+ const timeline = Object.entries(ledger.stages)
16
+ .map(([stage, record]) => `- ${stage}: ${record.status} (${record.updatedAt})`)
17
+ .join("\n");
18
+ const markdown = [
19
+ `# Usage and Cost Report — Workflow ${session.workflowId}`,
20
+ "",
21
+ `- Ticket: ${session.ticket ?? "(none)"}`,
22
+ `- Started: ${session.startedAt}`,
23
+ `- Completed: ${session.updatedAt}`,
24
+ "",
25
+ "## Usage",
26
+ "",
27
+ usageSection,
28
+ "",
29
+ "## Cost attribution",
30
+ "",
31
+ attributionSection,
32
+ "",
33
+ "## Stage timeline",
34
+ "",
35
+ timeline || "(no recorded stages)",
36
+ "",
37
+ ].join("\n");
38
+ const consoleSummary = usage
39
+ ? serializeTaskUsage(usage)
40
+ : `No usage recorded for workflow ${scope}. Record runs with \`aiw usage-sidecar record --workflow=${scope}\`.`;
41
+ return { markdown, consoleSummary };
42
+ }
package/dist/dashboard.js CHANGED
@@ -17,7 +17,13 @@ export function buildDashboardModel(root, fs) {
17
17
  const manifest = read(join(aiw, "manifest.yml"));
18
18
  const profile = read(join(aiw, "profile.yml"));
19
19
  const recommendations = read(join(aiw, "recommendations.yml"));
20
- const traceability = read(join(aiw, "generated/artifacts/traceability.yml"));
20
+ const workflowId = fs.exists(join(aiw, "workflow.yml"))
21
+ ? /^workflowId: ([0-9a-f-]+)/m.exec(read(join(aiw, "workflow.yml")))?.[1]
22
+ : undefined;
23
+ const scopedTraceability = workflowId
24
+ ? read(join(aiw, "generated/artifacts", workflowId, "traceability.yml"))
25
+ : "";
26
+ const traceability = scopedTraceability || read(join(aiw, "generated/artifacts/traceability.yml"));
21
27
  return {
22
28
  project: manifest.match(/^\s{2}name:\s*(.+)$/m)?.[1]?.trim() ?? root.split("/").at(-1) ?? root,
23
29
  target: manifest.match(/^\s{2}active:\s*(.+)$/m)?.[1]?.trim() ?? "not configured",
@@ -62,4 +62,19 @@ export type SemanticRerankCandidate = {
62
62
  };
63
63
  export declare function buildSemanticRerankRequest(query: string, candidates: SemanticRerankCandidate[]): DecisionRequest;
64
64
  export declare function buildEvidenceTriageRequest(artifact: string): DecisionRequest;
65
+ /** OPP-007: a review finding as produced by adversarial-review judges. */
66
+ export type ReviewFinding = {
67
+ id: string;
68
+ severity: string;
69
+ claim: string;
70
+ evidence: string[];
71
+ };
72
+ /** Parse a findings document (YAML `---`-separated entries). Fail-closed: garbage → []. */
73
+ export declare function parseReviewFindings(text: string): ReviewFinding[];
74
+ /** REQ-001: deterministic shape check — severity present; evidence or file:line non-empty. */
75
+ export declare function checkFindingShapes(findings: ReviewFinding[]): string[];
76
+ /** REQ-002: batched triage — one choice question per SEVERE finding, single request. */
77
+ export declare function buildFindingsTriageRequest(findings: ReviewFinding[]): DecisionRequest;
78
+ /** REQ-004: lane scope-watch — one advisory question about subsystem footprint. */
79
+ export declare function buildLaneScopeWatchRequest(changeSummary: string): DecisionRequest;
65
80
  export {};
package/dist/decision.js CHANGED
@@ -152,3 +152,66 @@ export function buildEvidenceTriageRequest(artifact) {
152
152
  },
153
153
  };
154
154
  }
155
+ /** Parse a findings document (YAML `---`-separated entries). Fail-closed: garbage → []. */
156
+ export function parseReviewFindings(text) {
157
+ const findings = [];
158
+ for (const block of text.split(/^---$/m)) {
159
+ const trimmed = block.trim();
160
+ if (!trimmed)
161
+ continue;
162
+ const id = /^id:\s*(\S+)/m.exec(trimmed)?.[1];
163
+ if (!id)
164
+ continue;
165
+ const severity = /^severity:\s*(.+)$/m.exec(trimmed)?.[1]?.trim() ?? "";
166
+ const claim = /^claim:\s*(.+)$/m.exec(trimmed)?.[1]?.trim() ?? "";
167
+ const evidence = [...trimmed.matchAll(/^\s*-\s*(\S+:\d+|\S+)$/gm)].map((m) => m[1]);
168
+ findings.push({ id, severity, claim, evidence: evidence.filter((e) => !e.startsWith("id:")) });
169
+ }
170
+ return findings;
171
+ }
172
+ /** REQ-001: deterministic shape check — severity present; evidence or file:line non-empty. */
173
+ export function checkFindingShapes(findings) {
174
+ if (findings.length === 0)
175
+ return ["No parsable findings: every entry fails the shape check."];
176
+ const issues = [];
177
+ for (const finding of findings) {
178
+ if (!finding.severity)
179
+ issues.push(`${finding.id}: severity is missing`);
180
+ if (finding.evidence.length === 0)
181
+ issues.push(`${finding.id}: no proof references or file:line`);
182
+ }
183
+ return issues;
184
+ }
185
+ /** REQ-002: batched triage — one choice question per SEVERE finding, single request. */
186
+ export function buildFindingsTriageRequest(findings) {
187
+ const questions = {};
188
+ for (const finding of findings)
189
+ if (finding.severity.toLowerCase() === "severe")
190
+ questions[finding.id] = {
191
+ type: "choice",
192
+ instructions: `Does the cited evidence support the claim "${finding.claim}"?`,
193
+ criteria: {
194
+ yes: "The cited evidence clearly supports the claim",
195
+ no: "The cited evidence does not support the claim",
196
+ unclear: "The evidence is insufficient to decide",
197
+ },
198
+ };
199
+ return { state: JSON.stringify(findings), questions };
200
+ }
201
+ /** REQ-004: lane scope-watch — one advisory question about subsystem footprint. */
202
+ export function buildLaneScopeWatchRequest(changeSummary) {
203
+ return {
204
+ state: changeSummary,
205
+ questions: {
206
+ multi_subsystem: {
207
+ type: "choice",
208
+ instructions: "Does this change footprint span multiple subsystems?",
209
+ criteria: {
210
+ yes: "The change touches more than one subsystem",
211
+ no: "The change is contained in a single subsystem",
212
+ unclear: "The footprint cannot be determined from the summary",
213
+ },
214
+ },
215
+ },
216
+ };
217
+ }
@@ -0,0 +1,7 @@
1
+ import type { EvidenceBundle } from "./signals.js";
2
+ /**
3
+ * Deterministic handoff brief for the host-agent `resource-evaluator` skill:
4
+ * summarizes the EvidenceBundle and states the strict draft contract. Rendering
5
+ * is a pure function of the bundle (no timestamps, no paths).
6
+ */
7
+ export declare function renderBrief(bundle: EvidenceBundle): string;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Deterministic handoff brief for the host-agent `resource-evaluator` skill:
3
+ * summarizes the EvidenceBundle and states the strict draft contract. Rendering
4
+ * is a pure function of the bundle (no timestamps, no paths).
5
+ */
6
+ export function renderBrief(bundle) {
7
+ const lines = [
8
+ "# Resource Evaluator Brief",
9
+ "",
10
+ "Analyze the signals below and draft resource proposals for this project.",
11
+ "Write each proposal as a YAML record in `.aiw/eval/proposals-draft.yml`.",
12
+ "",
13
+ "## Signals",
14
+ "",
15
+ "| id | key | value | evidence |",
16
+ "| --- | --- | --- | --- |",
17
+ ];
18
+ for (const fact of bundle.facts)
19
+ lines.push(`| ${fact.id} | ${fact.key} | ${fact.value} | ${fact.evidence.join(", ")} |`);
20
+ lines.push("", "## Limitations", "");
21
+ if (bundle.limitations.length)
22
+ for (const limitation of bundle.limitations)
23
+ lines.push(`- ${limitation}`);
24
+ else
25
+ lines.push("- none");
26
+ lines.push("", "## Instructions", "", "1. Propose only resources this project needs; cite the fact ids above as `evidence`.", "2. Every proposal record must define: `kind`, `signature`, `title`, `outline`, `evidence`.", "3. Allowed kinds: skill | agent | rule | hook | template.", "4. `evidence` entries must reference existing signal fact ids (for example `fact-001`);", " proposals citing unknown ids are rejected by `aiw proposals import`.", "5. `outline` sketches the resource content grounded in the detected tooling —", " never generic advice.", "6. Do not create or modify any other file; drafting is the only allowed write.", "", "Example record:", "", "```yaml", "- kind: rule", " signature: gradle-test-before-done", ' title: "Run Gradle tests before completing"', ' outline: "Rule requiring ./gradlew test before any task completion, with the detected wrapper."', " evidence: [fact-001, fact-002]", "```", "");
27
+ return lines.join("\n");
28
+ }
@@ -0,0 +1,17 @@
1
+ import type { ProposalStore } from "./types.js";
2
+ export type GeneratedResourceFile = {
3
+ path: string;
4
+ content: string;
5
+ };
6
+ export type GeneratedResourceIssue = {
7
+ path: string;
8
+ reason: string;
9
+ };
10
+ /**
11
+ * Validate project-local generated resources (`.aiw/generated/{kind}s/*.md`)
12
+ * against the evaluator contract: frontmatter with `provenance: aiw-evaluator`,
13
+ * a `proposal:` reference that exists in the store and is approved, and a
14
+ * non-empty body. Closes the REQ-006 substitution: generated files now have
15
+ * their own dedicated validator.
16
+ */
17
+ export declare function validateGeneratedResources(files: GeneratedResourceFile[], store: ProposalStore): GeneratedResourceIssue[];
@@ -0,0 +1,41 @@
1
+ const FRONTMATTER = /^---\n([\s\S]*?)\n---\n/;
2
+ /**
3
+ * Validate project-local generated resources (`.aiw/generated/{kind}s/*.md`)
4
+ * against the evaluator contract: frontmatter with `provenance: aiw-evaluator`,
5
+ * a `proposal:` reference that exists in the store and is approved, and a
6
+ * non-empty body. Closes the REQ-006 substitution: generated files now have
7
+ * their own dedicated validator.
8
+ */
9
+ export function validateGeneratedResources(files, store) {
10
+ const issues = [];
11
+ for (const file of files) {
12
+ const frontmatter = FRONTMATTER.exec(file.content);
13
+ if (!frontmatter) {
14
+ issues.push({ path: file.path, reason: "missing frontmatter block" });
15
+ continue;
16
+ }
17
+ const fields = frontmatter[1];
18
+ if (!/^provenance:\s*aiw-evaluator$/m.test(fields))
19
+ issues.push({
20
+ path: file.path,
21
+ reason: "frontmatter must declare provenance: aiw-evaluator",
22
+ });
23
+ const id = /^proposal:\s*(\S+)$/m.exec(fields)?.[1];
24
+ if (!id) {
25
+ issues.push({ path: file.path, reason: "frontmatter must declare proposal: <id>" });
26
+ continue;
27
+ }
28
+ const proposal = store.proposals.find((candidate) => candidate.id === id);
29
+ if (!proposal)
30
+ issues.push({ path: file.path, reason: `unknown proposal id: ${id}` });
31
+ else if (proposal.status !== "approved")
32
+ issues.push({
33
+ path: file.path,
34
+ reason: `proposal ${id} is ${proposal.status}, not approved`,
35
+ });
36
+ const body = file.content.slice(frontmatter[0].length).trim();
37
+ if (!body)
38
+ issues.push({ path: file.path, reason: "empty body" });
39
+ }
40
+ return issues;
41
+ }
@@ -0,0 +1,13 @@
1
+ import type { GitSummary } from "./signals.js";
2
+ import { type ShellRunner } from "./scenarios.js";
3
+ /**
4
+ * Deterministic summary of `git log --name-only --pretty=format:@@%s`:
5
+ * commit-type ratios, most-changed files, and hotspot directories. Subjects
6
+ * are marked with @@ so file paths can never be mistaken for subjects.
7
+ */
8
+ export declare function summarizeGitLog(output: string): GitSummary;
9
+ /**
10
+ * Run the git summary in `root`. Any failure (no git, not a repository, empty
11
+ * history) maps to `undefined` so the caller degrades to tree+CI signals.
12
+ */
13
+ export declare function collectGitSummary(root: string, runShell?: ShellRunner): Promise<GitSummary | undefined>;
@@ -0,0 +1,70 @@
1
+ import { defaultShellRunner } from "./scenarios.js";
2
+ const COMMIT_TYPES = new Set([
3
+ "feat",
4
+ "fix",
5
+ "chore",
6
+ "docs",
7
+ "test",
8
+ "refactor",
9
+ "perf",
10
+ "build",
11
+ "ci",
12
+ "style",
13
+ ]);
14
+ const LOG_COMMAND = 'git log --name-only --pretty=format:"@@%s" -n 500';
15
+ const LIST_CAP = 5;
16
+ function typeOf(subject) {
17
+ const match = /^([a-z]+)(\([^)]*\))?:/.exec(subject);
18
+ const type = match?.[1];
19
+ return type && COMMIT_TYPES.has(type) ? type : "other";
20
+ }
21
+ /**
22
+ * Deterministic summary of `git log --name-only --pretty=format:@@%s`:
23
+ * commit-type ratios, most-changed files, and hotspot directories. Subjects
24
+ * are marked with @@ so file paths can never be mistaken for subjects.
25
+ */
26
+ export function summarizeGitLog(output) {
27
+ const typeCounts = new Map();
28
+ const fileCounts = new Map();
29
+ const dirCounts = new Map();
30
+ let commits = 0;
31
+ for (const line of output.split("\n")) {
32
+ const trimmed = line.trim();
33
+ if (!trimmed)
34
+ continue;
35
+ if (trimmed.startsWith("@@")) {
36
+ commits += 1;
37
+ const type = typeOf(trimmed.slice(2));
38
+ typeCounts.set(type, (typeCounts.get(type) ?? 0) + 1);
39
+ continue;
40
+ }
41
+ fileCounts.set(trimmed, (fileCounts.get(trimmed) ?? 0) + 1);
42
+ const dir = trimmed.includes("/") ? trimmed.slice(0, trimmed.lastIndexOf("/")) : undefined;
43
+ if (dir)
44
+ dirCounts.set(dir, (dirCounts.get(dir) ?? 0) + 1);
45
+ }
46
+ const commitTypeRatio = {};
47
+ for (const type of [...typeCounts.keys()].sort())
48
+ commitTypeRatio[type] =
49
+ Math.round(((typeCounts.get(type) ?? 0) / Math.max(commits, 1)) * 10000) / 10000;
50
+ const rank = (counts) => [...counts.entries()]
51
+ .sort(([pathA, countA], [pathB, countB]) => countB - countA || pathA.localeCompare(pathB))
52
+ .slice(0, LIST_CAP)
53
+ .map(([path]) => path);
54
+ return {
55
+ available: true,
56
+ topPaths: rank(fileCounts),
57
+ commitTypeRatio,
58
+ hotspots: rank(dirCounts),
59
+ };
60
+ }
61
+ /**
62
+ * Run the git summary in `root`. Any failure (no git, not a repository, empty
63
+ * history) maps to `undefined` so the caller degrades to tree+CI signals.
64
+ */
65
+ export async function collectGitSummary(root, runShell = defaultShellRunner) {
66
+ const result = await runShell(root, LOG_COMMAND, 10000);
67
+ if (result.exitCode !== 0 || !result.stdout.trim())
68
+ return undefined;
69
+ return summarizeGitLog(result.stdout);
70
+ }
@@ -0,0 +1,32 @@
1
+ import { type Occurrence } from "./proposals.js";
2
+ import type { ProposalStore } from "./types.js";
3
+ export type SessionArtifact = {
4
+ type: "gate-failure";
5
+ stage: string;
6
+ ref: string;
7
+ } | {
8
+ type: "rejection";
9
+ stage: string;
10
+ reason: string;
11
+ ref: string;
12
+ };
13
+ export type MonitorResult = {
14
+ surfaced: string[];
15
+ };
16
+ /**
17
+ * Deterministic observation extraction from AIW's own session artifacts only —
18
+ * never chat transcripts (portability + privacy, REQ-007). Gate failures and
19
+ * recorded rejections are the strongest "this keeps going wrong" signals.
20
+ */
21
+ export declare function extractObservations(artifacts: SessionArtifact[]): Occurrence[];
22
+ /**
23
+ * Harvest monitor observations from the AIW approval ledger: every stage a
24
+ * human rejected is a "this keeps going wrong" signal, cited by reason.
25
+ */
26
+ export declare function harvestApprovalObservations(content: string): SessionArtifact[];
27
+ /**
28
+ * Observe one session boundary: record occurrences into the store and report
29
+ * which signatures may now surface to the human (threshold + cooldown +
30
+ * suppression all enforced by the store policy). Mutates only the store.
31
+ */
32
+ export declare function monitorSession(store: ProposalStore, artifacts: SessionArtifact[]): MonitorResult;