@multileaf/ai-workflow 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/README.md +11 -0
- package/dist/adapter.js +3 -3
- package/dist/artifact-paths.d.ts +16 -0
- package/dist/artifact-paths.js +51 -0
- package/dist/completion-report.d.ts +17 -0
- package/dist/completion-report.js +42 -0
- package/dist/dashboard.js +7 -1
- package/dist/decision.d.ts +15 -0
- package/dist/decision.js +63 -0
- package/dist/eval/brief.d.ts +7 -0
- package/dist/eval/brief.js +28 -0
- package/dist/eval/generated.d.ts +17 -0
- package/dist/eval/generated.js +41 -0
- package/dist/eval/git.d.ts +13 -0
- package/dist/eval/git.js +70 -0
- package/dist/eval/monitor.d.ts +32 -0
- package/dist/eval/monitor.js +66 -0
- package/dist/eval/policy.d.ts +8 -0
- package/dist/eval/policy.js +9 -0
- package/dist/eval/proposals.d.ts +48 -0
- package/dist/eval/proposals.js +202 -0
- package/dist/eval/signals.d.ts +21 -0
- package/dist/eval/signals.js +155 -0
- package/dist/eval/types.d.ts +38 -0
- package/dist/eval/types.js +1 -0
- package/dist/eval/validate.d.ts +28 -0
- package/dist/eval/validate.js +66 -0
- package/dist/generator.d.ts +8 -1
- package/dist/generator.js +24 -1
- package/dist/risk-assess.d.ts +1 -1
- package/dist/risk-assess.js +26 -2
- package/dist/semantic.d.ts +19 -0
- package/dist/semantic.js +57 -0
- package/dist/services.d.ts +3 -0
- package/dist/telemetry.d.ts +6 -0
- package/dist/telemetry.js +14 -7
- package/dist/workflow.js +471 -67
- package/docs/backlog.md +12 -2
- package/docs/decision-model-evaluation.md +7 -2
- package/docs/opportunities/OPP-007-decision-findings-triage-scope-watch.md +1 -1
- package/docs/opportunities/OPP-008-embedding-covering-tests-judge-context.md +1 -1
- package/docs/semantic-mapping.md +9 -0
- package/package.json +1 -1
- package/resources/evals/scenarios/evaluator-draft-contract.yml +65 -0
- package/resources/package.yaml +1 -0
- package/resources/skills/resource-evaluator.md +24 -0
- package/resources/skills/review-judge-a.md +4 -0
- package/resources/skills/review-judge-b.md +4 -0
- package/resources/skills/review-refuter.md +4 -0
- package/resources/skills/ticket.md +1 -1
|
@@ -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
|
+
}
|
package/dist/generator.d.ts
CHANGED
|
@@ -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;
|
package/dist/generator.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { resolveGeneratedPath } from "./drift.js";
|
|
2
|
-
export function generateProjectResources(profile, selected, write) {
|
|
2
|
+
export function generateProjectResources(profile, selected, write, semanticRetrieval = false) {
|
|
3
3
|
const linterCommand = safeInlineValue(profile.quality.linter?.command);
|
|
4
4
|
const formatterCommand = safeInlineValue(profile.quality.formatter?.command);
|
|
5
5
|
const testCommands = [
|
|
@@ -22,6 +22,8 @@ export function generateProjectResources(profile, selected, write) {
|
|
|
22
22
|
selected.includes("rules/architecture-policy"))
|
|
23
23
|
write(resolveGeneratedPath("agents/project-context.md"), `# Project Context\n\nThis project uses ${profile.frameworks.map((framework) => (framework === "nextjs" ? "Next.js" : framework)).join(", ")}. Follow the detected project structure and existing framework conventions.\n`);
|
|
24
24
|
if (selected.length > 0) {
|
|
25
|
+
if (semanticRetrieval)
|
|
26
|
+
write(resolveGeneratedPath("rules/semantic-retrieval.md"), "# Semantic Retrieval First\n\n- Prefer `aiw semantic query <terms>` over raw grep/rg when exploring unfamiliar context or locating relevant code; ranked semantic matches point at the most relevant chunks for a question.\n- Still use grep/rg (or git grep) for exact-string matches such as identifiers, error messages, and literal paths.\n- Semantic results are retrieval aids, never confirmed facts; verify against file contents before relying on them.\n");
|
|
25
27
|
write(resolveGeneratedPath("context/project-profile.md"), `# Confirmed Project Profile\n\n- Languages: ${profile.runtime.languages.join(", ") || "none detected"}\n- Frameworks: ${profile.frameworks.join(", ") || "none detected"}\n- Package manager: ${profile.packageManager}\n- All generated content is in English.\n`);
|
|
26
28
|
write(resolveGeneratedPath("context/root-context.md"), `# AI Workflow Project Context\n\nThis repository is managed by AI Workflow (\`.aiw/\` holds the neutral project state).\n\n- Languages: ${profile.runtime.languages.join(", ") || "none detected"}\n- Frameworks: ${profile.frameworks.join(", ") || "none detected"}\n- Package manager: ${profile.packageManager}${linterCommand ? `\n- Lint: \`${linterCommand}\`` : ""}${formatterCommand ? `\n- Format: \`${formatterCommand}\`` : ""}${uniqueTestCommands.map(({ scope, command }) => `\n- Tests (${scope}): \`${command}\``).join("")}\n\nBefore completing changes, run the project quality commands listed above. Follow installed AI Workflow skills, rules, and agents; the confirmed profile lives in \`.aiw/profile.yml\` and workflow evidence in \`.aiw/checkpoints/\`.\n\n## Context recovery (managed by AI Workflow)\n\nAfter any context compaction, reset, resume, or handoff: run \`aiw task status\`, read the stage artifacts this workflow declares under \`.aiw/generated/\`, and do not rely on compacted chat as the source of project state.\n`);
|
|
27
29
|
write(resolveGeneratedPath("hooks/quality-check.md"), `# Quality Check Hook\n\nRun the available project quality commands before completion.${linterCommand ? `\n\n- Linter: \`${linterCommand}\`` : ""}${formatterCommand ? `\n- Formatter: \`${formatterCommand}\`` : ""}${uniqueTestCommands.map(({ scope, command }) => `\n- ${scope} tests: \`${command}\``).join("")}\n`);
|
|
@@ -37,3 +39,24 @@ function safeInlineValue(value) {
|
|
|
37
39
|
.replace(/\s+/g, " ")
|
|
38
40
|
.slice(0, 180);
|
|
39
41
|
}
|
|
42
|
+
/**
|
|
43
|
+
* Materialize an approved evaluator proposal as a project-local resource with
|
|
44
|
+
* provenance frontmatter. Only the approve path may call this (REQ-004);
|
|
45
|
+
* output is always under generated/ via resolveGeneratedPath (REQ-006).
|
|
46
|
+
*/
|
|
47
|
+
export function generateProposalResource(proposal, write) {
|
|
48
|
+
if (proposal.status !== "approved")
|
|
49
|
+
throw new Error(`Refusing to materialize proposal ${proposal.id}: only approved proposals can be materialized (status: ${proposal.status})`);
|
|
50
|
+
const directory = `${proposal.kind}s`;
|
|
51
|
+
write(resolveGeneratedPath(`${directory}/${proposal.signature}.md`), [
|
|
52
|
+
"---",
|
|
53
|
+
"provenance: aiw-evaluator",
|
|
54
|
+
`proposal: ${proposal.id}`,
|
|
55
|
+
"---",
|
|
56
|
+
"",
|
|
57
|
+
`# ${proposal.title}`,
|
|
58
|
+
"",
|
|
59
|
+
proposal.outline,
|
|
60
|
+
"",
|
|
61
|
+
].join("\n"));
|
|
62
|
+
}
|
package/dist/risk-assess.d.ts
CHANGED
|
@@ -45,7 +45,7 @@ export declare function assessRisk(changes: readonly ChangedFile[], options?: As
|
|
|
45
45
|
export declare function collectWorkingTreeChanges(root: string): string[] | undefined;
|
|
46
46
|
/** Deterministic covering-test probe: sibling *.test.* / *.spec.* variants. */
|
|
47
47
|
export declare function hasCoveringTest(root: string, fs: FileSystem): (path: string) => boolean;
|
|
48
|
-
export declare function runRiskAssess(args: string[], root: string, fs: FileSystem): Promise<CommandResult>;
|
|
48
|
+
export declare function runRiskAssess(args: string[], root: string, fs: FileSystem, embeddingProvider?: import("./semantic.js").EmbeddingProvider): Promise<CommandResult>;
|
|
49
49
|
/**
|
|
50
50
|
* Agent escalation (RDD parity): an agent may raise — never lower — the tier
|
|
51
51
|
* citing one of the six high-risk items. Item must be 1..6; the reason is a
|
package/dist/risk-assess.js
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
*/
|
|
13
13
|
import { execFileSync } from "node:child_process";
|
|
14
14
|
import { join } from "node:path";
|
|
15
|
+
import { semanticCoveringEvidence } from "./semantic.js";
|
|
15
16
|
export const RISK_CATEGORIES = [
|
|
16
17
|
{
|
|
17
18
|
item: 1,
|
|
@@ -187,7 +188,7 @@ function parseRiskAssessArgs(rest) {
|
|
|
187
188
|
return undefined;
|
|
188
189
|
return parsed;
|
|
189
190
|
}
|
|
190
|
-
export async function runRiskAssess(args, root, fs) {
|
|
191
|
+
export async function runRiskAssess(args, root, fs, embeddingProvider) {
|
|
191
192
|
const jsonRequested = args.includes("--json");
|
|
192
193
|
const parsed = parseRiskAssessArgs(args.filter((argument) => argument !== "--json"));
|
|
193
194
|
if (!parsed)
|
|
@@ -206,7 +207,27 @@ export async function runRiskAssess(args, root, fs) {
|
|
|
206
207
|
exitCode: 1,
|
|
207
208
|
error: `git failed to enumerate changes${parsed.baseRef ? ` for --base-ref=${parsed.baseRef}` : ""}; verify the reference exists.`,
|
|
208
209
|
};
|
|
209
|
-
|
|
210
|
+
const siblingProbe = hasCoveringTest(root, fs);
|
|
211
|
+
let assessment = assessRisk(changedPaths.map((path) => ({ path })), {
|
|
212
|
+
hasCoveringTest: siblingProbe,
|
|
213
|
+
});
|
|
214
|
+
// OPP-008 REQ-001: retrieval can only prevent false `untested_regression`
|
|
215
|
+
// flags; tiers stay rule-based (REQ-002); undefined evidence keeps the
|
|
216
|
+
// deterministic floor byte-identical.
|
|
217
|
+
let coveringEvidence = [];
|
|
218
|
+
const untested = assessment.reasons
|
|
219
|
+
.filter((reason) => reason.code === "untested_regression" && reason.path)
|
|
220
|
+
.map((reason) => reason.path);
|
|
221
|
+
if (untested.length > 0) {
|
|
222
|
+
const evidence = await semanticCoveringEvidence(fs, join(root, ".aiw"), untested, embeddingProvider);
|
|
223
|
+
if (evidence && evidence.covering.length > 0) {
|
|
224
|
+
const covered = new Set(evidence.covering);
|
|
225
|
+
coveringEvidence = [...covered];
|
|
226
|
+
assessment = assessRisk(changedPaths.map((path) => ({ path })), {
|
|
227
|
+
hasCoveringTest: (path) => siblingProbe(path) || covered.has(path),
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
}
|
|
210
231
|
if (parsed.escalateItem !== undefined && parsed.escalateReason !== undefined) {
|
|
211
232
|
try {
|
|
212
233
|
assessment = applyEscalation(assessment, parsed.escalateItem, parsed.escalateReason);
|
|
@@ -228,6 +249,7 @@ export async function runRiskAssess(args, root, fs) {
|
|
|
228
249
|
reasons: assessment.reasons,
|
|
229
250
|
changed_paths: assessment.changedPaths.length,
|
|
230
251
|
risk_due: riskDue,
|
|
252
|
+
...(coveringEvidence.length ? { covering_evidence: coveringEvidence } : {}),
|
|
231
253
|
};
|
|
232
254
|
if (parsed.ticket)
|
|
233
255
|
envelope.ticket = parsed.ticket;
|
|
@@ -240,6 +262,8 @@ export async function runRiskAssess(args, root, fs) {
|
|
|
240
262
|
const lines = [`risk: ${assessment.tier}`];
|
|
241
263
|
for (const reason of assessment.reasons)
|
|
242
264
|
lines.push(` - ${reason.code}${reason.path ? `: ${reason.path}` : reason.detail ? ` (${reason.detail})` : ""}`);
|
|
265
|
+
if (coveringEvidence.length)
|
|
266
|
+
lines.push(`covering: semantic-retrieval (${coveringEvidence.join(", ")})`);
|
|
243
267
|
const next = nextCommand
|
|
244
268
|
? `risk due: yes -> ${nextCommand}`
|
|
245
269
|
: nextAction
|