@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
@@ -0,0 +1,66 @@
1
+ import { parseDocument } from "yaml";
2
+ import { recordOccurrence, shouldSurfaceProposal } from "./proposals.js";
3
+ /**
4
+ * Deterministic observation extraction from AIW's own session artifacts only —
5
+ * never chat transcripts (portability + privacy, REQ-007). Gate failures and
6
+ * recorded rejections are the strongest "this keeps going wrong" signals.
7
+ */
8
+ export function extractObservations(artifacts) {
9
+ return artifacts.map((artifact) => {
10
+ if (artifact.type === "gate-failure")
11
+ return {
12
+ kind: "rule",
13
+ signature: `gate-${artifact.stage}-quality`,
14
+ origin: "monitor",
15
+ evidence: artifact.ref,
16
+ };
17
+ return {
18
+ kind: "rule",
19
+ signature: `rejection-${artifact.stage}`,
20
+ origin: "monitor",
21
+ evidence: artifact.ref,
22
+ };
23
+ });
24
+ }
25
+ /**
26
+ * Harvest monitor observations from the AIW approval ledger: every stage a
27
+ * human rejected is a "this keeps going wrong" signal, cited by reason.
28
+ */
29
+ export function harvestApprovalObservations(content) {
30
+ const trimmed = content.trim();
31
+ if (!trimmed)
32
+ return [];
33
+ let raw;
34
+ try {
35
+ raw = parseDocument(trimmed).toJS();
36
+ }
37
+ catch {
38
+ return [];
39
+ }
40
+ const stages = raw?.stages;
41
+ if (!stages || typeof stages !== "object")
42
+ return [];
43
+ return Object.entries(stages)
44
+ .filter(([, entry]) => entry?.status === "rejected")
45
+ .map(([stage, entry]) => ({
46
+ type: "rejection",
47
+ stage,
48
+ reason: String(entry?.reason ?? ""),
49
+ ref: "approvals.yml",
50
+ }));
51
+ }
52
+ /**
53
+ * Observe one session boundary: record occurrences into the store and report
54
+ * which signatures may now surface to the human (threshold + cooldown +
55
+ * suppression all enforced by the store policy). Mutates only the store.
56
+ */
57
+ export function monitorSession(store, artifacts) {
58
+ const observations = extractObservations(artifacts);
59
+ for (const observation of observations)
60
+ recordOccurrence(store, observation);
61
+ const surfaced = [];
62
+ for (const observation of observations)
63
+ if (shouldSurfaceProposal(store, observation.signature).surface)
64
+ surfaced.push(observation.signature);
65
+ return { surfaced };
66
+ }
@@ -0,0 +1,8 @@
1
+ import type { ProposalPolicy } from "./types.js";
2
+ /**
3
+ * Default anti-spam policy. `threshold` is the minimum number of observed
4
+ * occurrences before a pattern may surface; `cooldown` is the minimum number
5
+ * of sequence numbers (store events) between two surfacings. Both are
6
+ * deterministic counters, never wall-clock durations.
7
+ */
8
+ export declare function defaultPolicy(): ProposalPolicy;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Default anti-spam policy. `threshold` is the minimum number of observed
3
+ * occurrences before a pattern may surface; `cooldown` is the minimum number
4
+ * of sequence numbers (store events) between two surfacings. Both are
5
+ * deterministic counters, never wall-clock durations.
6
+ */
7
+ export function defaultPolicy() {
8
+ return { threshold: 3, cooldown: 5, suppressed: [] };
9
+ }
@@ -0,0 +1,48 @@
1
+ import { type ProposalKind, type ProposalStore, type SurfaceVerdict } from "./types.js";
2
+ export declare const PROPOSALS_STORE_SCHEMA = 1;
3
+ /** Evidence refs kept per proposal: bounded growth, most recent first-class. */
4
+ export declare const MAX_EVIDENCE_REFS = 20;
5
+ /** Evidence refs kept after a proposal reaches a terminal state. */
6
+ export declare const COMPACT_EVIDENCE_REFS = 5;
7
+ export declare function createEmptyStore(): ProposalStore;
8
+ export type Occurrence = {
9
+ kind: ProposalKind;
10
+ signature: string;
11
+ origin?: "onboarding" | "monitor";
12
+ /** Artifact reference for this occurrence; defaults to a sequence marker. */
13
+ evidence?: string;
14
+ };
15
+ /** Stable content hash of a draft record: identical re-imports are no-ops. */
16
+ export declare function draftSignatureHash(record: {
17
+ kind: string;
18
+ signature: string;
19
+ title: string;
20
+ outline: string;
21
+ evidence: string[];
22
+ }): string;
23
+ /**
24
+ * Record one observation of a pattern. Occurrences deduplicate by signature:
25
+ * the proposal is created once and its evidence list grows per occurrence.
26
+ */
27
+ export declare function recordOccurrence(store: ProposalStore, occurrence: Occurrence): void;
28
+ /** Record `count` occurrences of one pattern in a single call (test/batch helper). */
29
+ export declare function recordMany(store: ProposalStore, occurrence: Occurrence, count: number): void;
30
+ /**
31
+ * Compact terminal proposals (approved/rejected/suppressed): their evidence
32
+ * already served the human review, so only the most recent refs are kept.
33
+ * Deterministic normalization — does not advance the sequence.
34
+ */
35
+ export declare function compactProposalStore(store: ProposalStore): void;
36
+ /**
37
+ * Decide whether a pattern may surface to the human. Pure check plus one
38
+ * honest side effect: a positive verdict records the surface event
39
+ * (`lastSurfacedSeq`), which is what makes the cooldown gap measurable.
40
+ * Callers that only inspect state should read the returned reason.
41
+ */
42
+ export declare function shouldSurfaceProposal(store: ProposalStore, signature: string): SurfaceVerdict;
43
+ export declare function approveProposal(store: ProposalStore, id: string): void;
44
+ export declare function rejectProposal(store: ProposalStore, id: string, reason: string): void;
45
+ export declare function suppressProposal(store: ProposalStore, id: string): void;
46
+ /** Deterministic serialization: same store state yields byte-identical YAML. */
47
+ export declare function serializeProposalStore(store: ProposalStore): string;
48
+ export declare function parseProposalStore(content: string): ProposalStore;
@@ -0,0 +1,202 @@
1
+ import { createHash } from "node:crypto";
2
+ import { parseDocument } from "yaml";
3
+ import { defaultPolicy } from "./policy.js";
4
+ import { PROPOSAL_KINDS, } from "./types.js";
5
+ export const PROPOSALS_STORE_SCHEMA = 1;
6
+ /** Evidence refs kept per proposal: bounded growth, most recent first-class. */
7
+ export const MAX_EVIDENCE_REFS = 20;
8
+ /** Evidence refs kept after a proposal reaches a terminal state. */
9
+ export const COMPACT_EVIDENCE_REFS = 5;
10
+ export function createEmptyStore() {
11
+ return {
12
+ schema: PROPOSALS_STORE_SCHEMA,
13
+ seq: 0,
14
+ lastSurfacedSeq: 0,
15
+ policy: defaultPolicy(),
16
+ proposals: [],
17
+ };
18
+ }
19
+ /** Stable content hash of a draft record: identical re-imports are no-ops. */
20
+ export function draftSignatureHash(record) {
21
+ return createHash("sha256")
22
+ .update([record.kind, record.signature, record.title, record.outline, record.evidence.join(",")].join("\u0000"))
23
+ .digest("hex");
24
+ }
25
+ /**
26
+ * Record one observation of a pattern. Occurrences deduplicate by signature:
27
+ * the proposal is created once and its evidence list grows per occurrence.
28
+ */
29
+ export function recordOccurrence(store, occurrence) {
30
+ store.seq += 1;
31
+ const existing = store.proposals.find((proposal) => proposal.signature === occurrence.signature);
32
+ if (existing) {
33
+ existing.occurrences += 1;
34
+ existing.lastSeq = store.seq;
35
+ existing.evidence.push(occurrence.evidence ?? `occurrences/${store.seq}`);
36
+ if (existing.evidence.length > MAX_EVIDENCE_REFS)
37
+ existing.evidence.splice(0, existing.evidence.length - MAX_EVIDENCE_REFS);
38
+ return;
39
+ }
40
+ const number = store.proposals.length + 1;
41
+ store.proposals.push({
42
+ id: `prop-${String(number).padStart(3, "0")}`,
43
+ kind: occurrence.kind,
44
+ origin: occurrence.origin ?? "monitor",
45
+ signature: occurrence.signature,
46
+ status: "proposed",
47
+ title: "",
48
+ outline: "",
49
+ evidence: [occurrence.evidence ?? `occurrences/${store.seq}`],
50
+ occurrences: 1,
51
+ lastSeq: store.seq,
52
+ rejectReason: null,
53
+ rejectedAtOccurrences: null,
54
+ provenance: "",
55
+ draftHash: null,
56
+ });
57
+ }
58
+ /** Record `count` occurrences of one pattern in a single call (test/batch helper). */
59
+ export function recordMany(store, occurrence, count) {
60
+ for (let index = 0; index < count; index += 1)
61
+ recordOccurrence(store, occurrence);
62
+ }
63
+ /**
64
+ * Compact terminal proposals (approved/rejected/suppressed): their evidence
65
+ * already served the human review, so only the most recent refs are kept.
66
+ * Deterministic normalization — does not advance the sequence.
67
+ */
68
+ export function compactProposalStore(store) {
69
+ for (const proposal of store.proposals)
70
+ if (proposal.status !== "proposed" && proposal.evidence.length > COMPACT_EVIDENCE_REFS)
71
+ proposal.evidence.splice(0, proposal.evidence.length - COMPACT_EVIDENCE_REFS);
72
+ }
73
+ /**
74
+ * Decide whether a pattern may surface to the human. Pure check plus one
75
+ * honest side effect: a positive verdict records the surface event
76
+ * (`lastSurfacedSeq`), which is what makes the cooldown gap measurable.
77
+ * Callers that only inspect state should read the returned reason.
78
+ */
79
+ export function shouldSurfaceProposal(store, signature) {
80
+ const proposal = store.proposals.find((candidate) => candidate.signature === signature);
81
+ if (!proposal)
82
+ return { surface: false, reason: "no proposal recorded for this signature" };
83
+ if (store.policy.suppressed.includes(signature) || proposal.status === "suppressed")
84
+ return { surface: false, reason: "suppressed by do-not-suggest-again policy" };
85
+ if (proposal.status === "approved")
86
+ return { surface: false, reason: "already approved" };
87
+ if (proposal.status === "rejected") {
88
+ const cited = proposal.rejectedAtOccurrences ?? proposal.occurrences;
89
+ if (proposal.occurrences <= cited)
90
+ return { surface: false, reason: "rejected without new occurrences since rejection" };
91
+ }
92
+ if (proposal.occurrences < store.policy.threshold)
93
+ return {
94
+ surface: false,
95
+ reason: `below threshold: ${proposal.occurrences}/${store.policy.threshold} occurrences`,
96
+ };
97
+ if (store.lastSurfacedSeq > 0 && store.seq - store.lastSurfacedSeq < store.policy.cooldown)
98
+ return {
99
+ surface: false,
100
+ reason: `cooldown: ${store.seq - store.lastSurfacedSeq}/${store.policy.cooldown} sequence gap since last surfacing`,
101
+ };
102
+ store.lastSurfacedSeq = store.seq;
103
+ return { surface: true, reason: `threshold met with ${proposal.occurrences} occurrences` };
104
+ }
105
+ function byId(store, id) {
106
+ const proposal = store.proposals.find((candidate) => candidate.id === id);
107
+ if (!proposal)
108
+ throw new Error(`Unknown proposal id: ${id}`);
109
+ return proposal;
110
+ }
111
+ export function approveProposal(store, id) {
112
+ store.seq += 1;
113
+ byId(store, id).status = "approved";
114
+ }
115
+ export function rejectProposal(store, id, reason) {
116
+ store.seq += 1;
117
+ const proposal = byId(store, id);
118
+ proposal.status = "rejected";
119
+ proposal.rejectReason = reason;
120
+ proposal.rejectedAtOccurrences = proposal.occurrences;
121
+ }
122
+ export function suppressProposal(store, id) {
123
+ store.seq += 1;
124
+ const proposal = byId(store, id);
125
+ proposal.status = "suppressed";
126
+ if (!store.policy.suppressed.includes(proposal.signature))
127
+ store.policy.suppressed.push(proposal.signature);
128
+ }
129
+ function scalar(value) {
130
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n")}"`;
131
+ }
132
+ /** Deterministic serialization: same store state yields byte-identical YAML. */
133
+ export function serializeProposalStore(store) {
134
+ const lines = [
135
+ `schema: ${store.schema}`,
136
+ `seq: ${store.seq}`,
137
+ `last_surfaced_seq: ${store.lastSurfacedSeq}`,
138
+ "policy:",
139
+ ` threshold: ${store.policy.threshold}`,
140
+ ` cooldown: ${store.policy.cooldown}`,
141
+ ` suppressed: [${store.policy.suppressed.join(", ")}]`,
142
+ "proposals:",
143
+ ];
144
+ for (const proposal of store.proposals) {
145
+ lines.push(` - id: ${proposal.id}`, ` kind: ${proposal.kind}`, ` origin: ${proposal.origin}`, ` signature: ${scalar(proposal.signature)}`, ` status: ${proposal.status}`, ` title: ${scalar(proposal.title)}`, ` outline: ${scalar(proposal.outline)}`, ` evidence: [${proposal.evidence.map(scalar).join(", ")}]`, ` occurrences: ${proposal.occurrences}`, ` last_seq: ${proposal.lastSeq}`, ` reject_reason: ${proposal.rejectReason === null ? "null" : scalar(proposal.rejectReason)}`, ` rejected_at_occurrences: ${proposal.rejectedAtOccurrences ?? "null"}`, ` provenance: ${scalar(proposal.provenance)}`, ` draft_hash: ${proposal.draftHash === null ? "null" : scalar(proposal.draftHash)}`);
146
+ }
147
+ return `${lines.join("\n")}\n`;
148
+ }
149
+ function parseProposal(raw, index) {
150
+ const kind = String(raw.kind);
151
+ if (!PROPOSAL_KINDS.includes(kind))
152
+ throw new Error(`Invalid proposal kind: ${kind}`);
153
+ const status = raw.status;
154
+ if (!["proposed", "approved", "rejected", "suppressed"].includes(String(status)))
155
+ throw new Error(`Invalid proposal status: ${status}`);
156
+ return {
157
+ id: String(raw.id ?? `prop-${String(index + 1).padStart(3, "0")}`),
158
+ kind: kind,
159
+ origin: (raw.origin === "onboarding" ? "onboarding" : "monitor"),
160
+ signature: String(raw.signature ?? ""),
161
+ status: status,
162
+ title: String(raw.title ?? ""),
163
+ outline: String(raw.outline ?? ""),
164
+ evidence: Array.isArray(raw.evidence) ? raw.evidence.map(String) : [],
165
+ occurrences: Number(raw.occurrences ?? 0),
166
+ lastSeq: Number(raw.last_seq ?? 0),
167
+ rejectReason: raw.reject_reason === null || raw.reject_reason === undefined
168
+ ? null
169
+ : String(raw.reject_reason),
170
+ rejectedAtOccurrences: raw.rejected_at_occurrences === null || raw.rejected_at_occurrences === undefined
171
+ ? null
172
+ : Number(raw.rejected_at_occurrences),
173
+ provenance: String(raw.provenance ?? ""),
174
+ draftHash: raw.draft_hash === null || raw.draft_hash === undefined ? null : String(raw.draft_hash),
175
+ };
176
+ }
177
+ export function parseProposalStore(content) {
178
+ const document = parseDocument(content);
179
+ const raw = document.toJS();
180
+ if (!raw || Number(raw.schema) !== PROPOSALS_STORE_SCHEMA)
181
+ throw new Error(`Unsupported proposal store schema: ${String(raw?.schema)}`);
182
+ const policy = defaultPolicy();
183
+ const rawPolicy = raw.policy;
184
+ if (rawPolicy) {
185
+ if (Number.isFinite(Number(rawPolicy.threshold)))
186
+ policy.threshold = Number(rawPolicy.threshold);
187
+ if (Number.isFinite(Number(rawPolicy.cooldown)))
188
+ policy.cooldown = Number(rawPolicy.cooldown);
189
+ if (Array.isArray(rawPolicy.suppressed))
190
+ policy.suppressed = rawPolicy.suppressed.map(String);
191
+ }
192
+ const proposals = Array.isArray(raw.proposals)
193
+ ? raw.proposals.map((entry, index) => parseProposal(entry, index))
194
+ : [];
195
+ return {
196
+ schema: PROPOSALS_STORE_SCHEMA,
197
+ seq: Number(raw.seq ?? 0),
198
+ lastSurfacedSeq: Number(raw.last_surfaced_seq ?? 0),
199
+ policy,
200
+ proposals,
201
+ };
202
+ }
@@ -0,0 +1,21 @@
1
+ export declare const EVIDENCE_BUNDLE_SCHEMA = 1;
2
+ export type GitSummary = {
3
+ available: boolean;
4
+ topPaths: string[];
5
+ commitTypeRatio: Record<string, number>;
6
+ hotspots: string[];
7
+ };
8
+ export type SignalFact = {
9
+ id: string;
10
+ key: string;
11
+ value: string;
12
+ evidence: string[];
13
+ };
14
+ export type EvidenceBundle = {
15
+ schema: 1;
16
+ facts: SignalFact[];
17
+ limitations: string[];
18
+ };
19
+ export declare function collectSignals(files: string[], git?: GitSummary, readFile?: (path: string) => string): EvidenceBundle;
20
+ export declare function serializeEvidenceBundle(bundle: EvidenceBundle): string;
21
+ export declare function parseEvidenceBundle(content: string): EvidenceBundle;
@@ -0,0 +1,155 @@
1
+ import { parseDocument } from "yaml";
2
+ export const EVIDENCE_BUNDLE_SCHEMA = 1;
3
+ /**
4
+ * Deterministic stack detection over a sorted file listing. Evidence always
5
+ * names real files so downstream proposals cannot cite imaginary tooling.
6
+ * `evidenceFiles` are filtered by presence, so a rule matched by any of its
7
+ * files (for example gradlew without build.gradle.kts) still cites what exists.
8
+ */
9
+ const BUILD_RULES = [
10
+ {
11
+ match: (files) => files.some((file) => /^build\.gradle(\.kts)?$/.test(file) || file === "gradlew"),
12
+ rule: {
13
+ keys: [
14
+ ["build.system", "gradle"],
15
+ ["test.command", "./gradlew test"],
16
+ ],
17
+ evidenceFiles: ["build.gradle.kts", "build.gradle", "gradlew"],
18
+ },
19
+ },
20
+ {
21
+ match: (files) => files.includes("pom.xml"),
22
+ rule: {
23
+ keys: [
24
+ ["build.system", "maven"],
25
+ ["test.command", "mvn test"],
26
+ ],
27
+ evidenceFiles: ["pom.xml"],
28
+ },
29
+ },
30
+ {
31
+ match: (files) => files.includes("pyproject.toml") || files.includes("setup.py") || files.includes("setup.cfg"),
32
+ rule: {
33
+ keys: [
34
+ ["build.system", "python-pyproject"],
35
+ ["test.command", "pytest"],
36
+ ],
37
+ evidenceFiles: ["pyproject.toml", "setup.py", "setup.cfg"],
38
+ },
39
+ },
40
+ {
41
+ match: (files) => files.includes("CMakeLists.txt"),
42
+ rule: {
43
+ keys: [
44
+ ["build.system", "cmake"],
45
+ ["language", "cpp"],
46
+ ["test.command", "ctest --output-on-failure"],
47
+ ],
48
+ evidenceFiles: ["CMakeLists.txt"],
49
+ },
50
+ },
51
+ {
52
+ match: (files) => files.includes("go.mod"),
53
+ rule: {
54
+ keys: [
55
+ ["build.system", "go-modules"],
56
+ ["test.command", "go test ./..."],
57
+ ],
58
+ evidenceFiles: ["go.mod"],
59
+ },
60
+ },
61
+ {
62
+ match: (files) => files.includes("package.json"),
63
+ rule: {
64
+ keys: [
65
+ ["build.system", "node-npm"],
66
+ ["test.command", "npm test"],
67
+ ],
68
+ evidenceFiles: ["package.json"],
69
+ },
70
+ },
71
+ ];
72
+ const PYTHON_FRAMEWORKS = ["django", "flask", "fastapi"];
73
+ /**
74
+ * Framework facts come from declared dependencies (file content), never from
75
+ * file presence alone — a plain pyproject or Gradle project gets no framework
76
+ * fact instead of a guess.
77
+ */
78
+ function frameworkFor(files, readFile) {
79
+ if (!readFile)
80
+ return undefined;
81
+ const pythonManifest = ["pyproject.toml", "requirements.txt", "setup.py"].find((file) => files.includes(file));
82
+ if (pythonManifest) {
83
+ const content = readFile(pythonManifest).toLowerCase();
84
+ const match = PYTHON_FRAMEWORKS.find((framework) => content.includes(framework));
85
+ if (match)
86
+ return { value: match, evidence: pythonManifest };
87
+ return undefined;
88
+ }
89
+ const jvmManifest = ["build.gradle.kts", "build.gradle", "pom.xml"].find((file) => files.includes(file));
90
+ if (jvmManifest && readFile(jvmManifest).toLowerCase().includes("spring"))
91
+ return { value: "spring", evidence: jvmManifest };
92
+ return undefined;
93
+ }
94
+ export function collectSignals(files, git, readFile) {
95
+ const sorted = [...files].sort();
96
+ const facts = [];
97
+ let index = 0;
98
+ const push = (key, value, evidence) => {
99
+ index += 1;
100
+ facts.push({ id: `fact-${String(index).padStart(3, "0")}`, key, value, evidence });
101
+ };
102
+ for (const { match, rule } of BUILD_RULES) {
103
+ if (!match(sorted))
104
+ continue;
105
+ const evidence = rule.evidenceFiles.filter((file) => sorted.includes(file));
106
+ for (const [key, value] of rule.keys)
107
+ push(key, value, evidence);
108
+ break;
109
+ }
110
+ const framework = frameworkFor(sorted, readFile);
111
+ if (framework)
112
+ push("framework", framework.value, [framework.evidence]);
113
+ if (sorted.some((file) => file.startsWith(".github/workflows/") && file.endsWith(".yml")))
114
+ push("ci.provider", "github-actions", [".github/workflows"]);
115
+ const limitations = [];
116
+ if (git?.available) {
117
+ for (const path of git.topPaths.slice(0, 5))
118
+ push("git.top-path", path, ["git log"]);
119
+ for (const [type, ratio] of Object.entries(git.commitTypeRatio).sort(([a], [b]) => a.localeCompare(b)))
120
+ push(`git.commit-ratio.${type}`, String(ratio), ["git log"]);
121
+ for (const hotspot of git.hotspots.slice(0, 5))
122
+ push("git.hotspot", hotspot, ["git log"]);
123
+ }
124
+ else {
125
+ limitations.push("git-history-unavailable");
126
+ }
127
+ return { schema: EVIDENCE_BUNDLE_SCHEMA, facts, limitations };
128
+ }
129
+ function scalar(value) {
130
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n")}"`;
131
+ }
132
+ export function serializeEvidenceBundle(bundle) {
133
+ const lines = [`schema: ${bundle.schema}`];
134
+ if (bundle.limitations.length)
135
+ lines.push(`limitations: [${bundle.limitations.map(scalar).join(", ")}]`);
136
+ lines.push("facts:");
137
+ for (const fact of bundle.facts)
138
+ lines.push(` - id: ${fact.id}`, ` key: ${fact.key}`, ` value: ${scalar(fact.value)}`, ` evidence: [${fact.evidence.map(scalar).join(", ")}]`);
139
+ return `${lines.join("\n")}\n`;
140
+ }
141
+ export function parseEvidenceBundle(content) {
142
+ const raw = parseDocument(content).toJS();
143
+ if (!raw || Number(raw.schema) !== EVIDENCE_BUNDLE_SCHEMA)
144
+ throw new Error(`Unsupported evidence bundle schema: ${String(raw?.schema)}`);
145
+ const facts = Array.isArray(raw.facts)
146
+ ? raw.facts.map((entry) => ({
147
+ id: String(entry.id ?? ""),
148
+ key: String(entry.key ?? ""),
149
+ value: String(entry.value ?? ""),
150
+ evidence: Array.isArray(entry.evidence) ? entry.evidence.map(String) : [],
151
+ }))
152
+ : [];
153
+ const limitations = Array.isArray(raw.limitations) ? raw.limitations.map(String) : [];
154
+ return { schema: EVIDENCE_BUNDLE_SCHEMA, facts, limitations };
155
+ }
@@ -0,0 +1,38 @@
1
+ export declare const PROPOSAL_KINDS: readonly ["skill", "agent", "rule", "hook", "template"];
2
+ export type ProposalKind = (typeof PROPOSAL_KINDS)[number];
3
+ export type ProposalStatus = "proposed" | "approved" | "rejected" | "suppressed";
4
+ export type ProposalOrigin = "onboarding" | "monitor";
5
+ export type ProposalRecord = {
6
+ id: string;
7
+ kind: ProposalKind;
8
+ origin: ProposalOrigin;
9
+ signature: string;
10
+ status: ProposalStatus;
11
+ title: string;
12
+ outline: string;
13
+ evidence: string[];
14
+ occurrences: number;
15
+ lastSeq: number;
16
+ rejectReason: string | null;
17
+ rejectedAtOccurrences: number | null;
18
+ provenance: string;
19
+ /** Content hash of the last imported draft; identical re-imports are no-ops. */
20
+ draftHash: string | null;
21
+ };
22
+ export type ProposalPolicy = {
23
+ threshold: number;
24
+ cooldown: number;
25
+ suppressed: string[];
26
+ };
27
+ export type ProposalStore = {
28
+ schema: 1;
29
+ /** Monotonic sequence number: every mutation advances it (no wall timestamps). */
30
+ seq: number;
31
+ lastSurfacedSeq: number;
32
+ policy: ProposalPolicy;
33
+ proposals: ProposalRecord[];
34
+ };
35
+ export type SurfaceVerdict = {
36
+ surface: boolean;
37
+ reason: string;
38
+ };
@@ -0,0 +1 @@
1
+ export const PROPOSAL_KINDS = ["skill", "agent", "rule", "hook", "template"];
@@ -0,0 +1,28 @@
1
+ import { type ProposalKind } from "./types.js";
2
+ import type { EvidenceBundle } from "./signals.js";
3
+ export type DraftRecord = {
4
+ kind: ProposalKind | string;
5
+ signature: string;
6
+ title: string;
7
+ outline: string;
8
+ evidence: string[];
9
+ };
10
+ export type DraftFailure = {
11
+ record: string;
12
+ reason: string[];
13
+ };
14
+ export type DraftValidation = {
15
+ records: DraftRecord[];
16
+ errors: DraftFailure[];
17
+ overlaps: {
18
+ signature: string;
19
+ catalogId: string;
20
+ }[];
21
+ };
22
+ export declare function parseDrafts(content: string): DraftRecord[];
23
+ /**
24
+ * Contract check run after the host agent writes its drafts: required fields,
25
+ * evidence refs must resolve into the EvidenceBundle, kinds must be known, and
26
+ * overlap with existing catalog resources is annotated for the reviewer.
27
+ */
28
+ export declare function validateDrafts(drafts: DraftRecord[], bundle: EvidenceBundle, catalogIds: string[]): DraftValidation;
@@ -0,0 +1,66 @@
1
+ import { parseDocument } from "yaml";
2
+ import { PROPOSAL_KINDS } from "./types.js";
3
+ const REQUIRED = ["kind", "signature", "title", "outline", "evidence"];
4
+ function slugTokens(value) {
5
+ return value
6
+ .toLowerCase()
7
+ .replace(/[^a-z0-9]+/g, " ")
8
+ .trim()
9
+ .split(/\s+/)
10
+ .filter(Boolean);
11
+ }
12
+ export function parseDrafts(content) {
13
+ const trimmed = content.trim();
14
+ if (!trimmed)
15
+ return [];
16
+ const raw = parseDocument(trimmed).toJS();
17
+ if (!Array.isArray(raw))
18
+ throw new Error("Drafts file must contain a YAML list of records");
19
+ return raw.map((entry) => ({
20
+ kind: String(entry.kind ?? ""),
21
+ signature: String(entry.signature ?? ""),
22
+ title: String(entry.title ?? ""),
23
+ outline: String(entry.outline ?? ""),
24
+ evidence: Array.isArray(entry.evidence) ? entry.evidence.map(String) : [],
25
+ }));
26
+ }
27
+ /**
28
+ * Contract check run after the host agent writes its drafts: required fields,
29
+ * evidence refs must resolve into the EvidenceBundle, kinds must be known, and
30
+ * overlap with existing catalog resources is annotated for the reviewer.
31
+ */
32
+ export function validateDrafts(drafts, bundle, catalogIds) {
33
+ const knownFactIds = new Set(bundle.facts.map((fact) => fact.id));
34
+ const records = [];
35
+ const errors = [];
36
+ const overlaps = [];
37
+ for (const draft of drafts) {
38
+ const reason = [];
39
+ for (const field of REQUIRED)
40
+ if (field === "evidence"
41
+ ? draft.evidence.length === 0
42
+ : draft[field] === undefined || draft[field] === null || !String(draft[field]).trim())
43
+ reason.push(`missing required field: ${field}`);
44
+ if (!PROPOSAL_KINDS.includes(draft.kind))
45
+ reason.push(`unknown kind: ${draft.kind}`);
46
+ const dangling = draft.evidence.filter((ref) => !knownFactIds.has(ref));
47
+ if (dangling.length)
48
+ reason.push(`evidence refs not present in bundle: ${dangling.join(", ")}`);
49
+ if (reason.length) {
50
+ errors.push({ record: draft.signature || "(unnamed)", reason });
51
+ continue;
52
+ }
53
+ records.push(draft);
54
+ const tokens = slugTokens(draft.title);
55
+ for (const catalogId of catalogIds) {
56
+ const [type, ...rest] = catalogId.split("/");
57
+ const slug = rest.join(" ").replaceAll("-", " ");
58
+ const slugTokensList = slugTokens(slug);
59
+ if (type.replace(/s$/, "") === draft.kind &&
60
+ slugTokensList.length > 0 &&
61
+ slugTokensList.every((token) => tokens.includes(token)))
62
+ overlaps.push({ signature: draft.signature, catalogId });
63
+ }
64
+ }
65
+ return { records, errors, overlaps };
66
+ }
@@ -1,3 +1,10 @@
1
1
  import type { ProjectProfile } from "./profile.js";
2
+ import type { ProposalRecord } from "./eval/types.js";
2
3
  export type ResourceWriter = (path: string, content: string) => void;
3
- export declare function generateProjectResources(profile: ProjectProfile, selected: string[], write: ResourceWriter): void;
4
+ export declare function generateProjectResources(profile: ProjectProfile, selected: string[], write: ResourceWriter, semanticRetrieval?: boolean): void;
5
+ /**
6
+ * Materialize an approved evaluator proposal as a project-local resource with
7
+ * provenance frontmatter. Only the approve path may call this (REQ-004);
8
+ * output is always under generated/ via resolveGeneratedPath (REQ-006).
9
+ */
10
+ export declare function generateProposalResource(proposal: ProposalRecord, write: ResourceWriter): void;