@ngockhoale/ukit 3.5.3 → 3.5.4

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 (59) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/manifests/documentation.yaml +12 -1
  3. package/manifests/platform.full.yaml +12 -0
  4. package/package.json +27 -1
  5. package/src/cli/commands/doctor.js +41 -0
  6. package/src/cli/commands/indexTools.js +10 -4
  7. package/src/cli/commands/memory.js +77 -6
  8. package/src/core/memory/episodes.js +106 -7
  9. package/src/core/memory/memoryCheck.js +241 -0
  10. package/src/core/memory/memoryCheckRun.js +27 -0
  11. package/src/core/memory/mutateMemory.js +37 -1
  12. package/src/core/memory/observations.js +192 -0
  13. package/src/core/memory/recallEngine.js +120 -7
  14. package/src/core/memory/records.js +23 -0
  15. package/src/core/memory/writeGate.js +137 -0
  16. package/src/core/runtimeConfig.js +11 -1
  17. package/src/index/buildIndex.js +26 -0
  18. package/src/index/paths.js +3 -1
  19. package/src/index/queryIndex.js +225 -10
  20. package/src/index/resolveContext.js +1 -1
  21. package/template_project/.claude/hooks/edit-hint.mjs +64 -17
  22. package/template_project/.claude/hooks/session-episode-start.mjs +35 -0
  23. package/template_project/.claude/hooks/session-episode.sh +9 -4
  24. package/template_project/.claude/settings.json +2 -2
  25. package/template_project/.claude/ukit/index/lib/index-core.mjs +255 -12
  26. package/template_project/.claude/ukit/index/query-index.mjs +14 -3
  27. package/template_project/.claude/ukit/index/route-task.mjs +4 -1
  28. package/template_project/.claude/ukit/runtime/memory-check.mjs +241 -0
  29. package/template_project/.claude/ukit/runtime/memory-recall.mjs +120 -7
  30. package/template_project/.claude/ukit/runtime/memory-validity.mjs +28 -1
  31. package/template_project/.claude/ukit/runtime/self-improve-trigger.mjs +212 -5
  32. package/template_project/.omp/hooks/pre/ukit-bridge.js +2 -1
  33. package/template_project/ukit/storage/config.json +4 -2
  34. package/src/core/agentRuntime/completionGate.js +0 -179
  35. package/src/core/agentRuntime/context.js +0 -571
  36. package/src/core/agentRuntime/qualityComparison.js +0 -112
  37. package/src/core/agentRuntime/resourcePolicy.js +0 -78
  38. package/src/core/agentRuntime/runtimeSupport.js +0 -255
  39. package/src/core/codeintel/manifest.js +0 -176
  40. package/src/core/experiments/deliberation.js +0 -327
  41. package/src/core/experiments/dynamicWorkflow.js +0 -507
  42. package/src/core/handoffDocValidator.js +0 -154
  43. package/src/core/memory/deltaOverlays.js +0 -493
  44. package/src/core/memory/learningCandidates.js +0 -347
  45. package/src/core/observability/emit/sessionBoot.js +0 -407
  46. package/src/core/observability/evaluation/replay.js +0 -149
  47. package/src/core/observability/evaluation/scorecard.js +0 -465
  48. package/src/core/observability/schema/compatibility.js +0 -180
  49. package/src/core/observability/support/renderer.js +0 -130
  50. package/src/core/reviewPanelAggregate.js +0 -204
  51. package/src/core/taskBudgetValidator.js +0 -251
  52. package/src/core/taskProgressGuard.js +0 -227
  53. package/src/decision/reviewVerdict.js +0 -339
  54. package/src/decision/runtimeFilter.js +0 -150
  55. package/src/decision/runtimeScheduler.js +0 -239
  56. package/src/index/contextPack.js +0 -285
  57. package/src/index/impactContext.js +0 -360
  58. package/src/index/reviewPolicy.js +0 -368
  59. package/src/index/sensitivePath.js +0 -21
@@ -1,227 +0,0 @@
1
- // Pure checker for the executor milestone protocol.
2
- //
3
- // A TASK-xxx.md that carries an `## Executor Report` must also carry a `## Progress` section.
4
- // Each `## Progress` entry uses a fixed format:
5
- //
6
- // - <ISO-8601 timestamp> · milestone: <name> · last-green: <what passed> · files: <paths> · drift: none|<reason>
7
- //
8
- // Rules implemented here (canonical wording for the planner/executor contract):
9
- //
10
- // 1. A task carrying an Executor Report must have ≥1 `## Progress` entry.
11
- // Violation type: 'no-progress'.
12
- //
13
- // 2. The newest entry (max parsed timestamp, not last line) must be within
14
- // `2 × milestoneIntervalMin` of `now`. The boundary is INCLUSIVE at exactly
15
- // `2 × milestoneIntervalMin` old (still OK) and EXCLUSIVE one minute past
16
- // (stale). "Strictly beyond" the boundary is stale.
17
- // Violation type: 'stale-milestone'.
18
- //
19
- // 3. Every `files:` path in an entry must appear under `## Target Files`
20
- // unless that entry's `drift:` field carries a non-`none` reason.
21
- // Violation type: 'undeclared-drift'.
22
- //
23
- // 4. Entries with unparseable timestamps are reported as 'malformed-entry'
24
- // and never throw.
25
- //
26
- // The module is intentionally tiny and pure: no fs, no Date.now() side effects.
27
- // `now` defaults to Date.now() so call sites that want determinism (tests,
28
- // future watchdog integration) can inject a fixed timestamp.
29
-
30
- const PROGRESS_HEADING = /^##\s+Progress\s*$/m;
31
- const PROGRESS_HEADING_GLOBAL = /^##\s+Progress\s*$/gm;
32
- const REPORT_HEADING = /^##\s+Executor Report\s*$/m;
33
- const TARGET_HEADING = /^##\s+Target Files\s*$/m;
34
- const ENTRY_RE = /^-\s+(\S+)\s+·\s+milestone:\s*([^·]*)·\s+last-green:\s*([^·]*)·\s+files:\s*([^·]*)·\s+drift:\s*(.*)$/;
35
-
36
- function parseEntry(line) {
37
- const m = ENTRY_RE.exec(line);
38
- if (!m) return null;
39
- const [, ts, milestone, lastGreen, filesField, drift] = m;
40
- const files = filesField
41
- .split(',')
42
- .map((s) => s.trim())
43
- .filter(Boolean);
44
- const tsNum = Date.parse(ts);
45
- if (Number.isNaN(tsNum)) {
46
- return { ok: false, raw: line };
47
- }
48
- return {
49
- ok: true,
50
- timestamp: tsNum,
51
- milestone: milestone.trim(),
52
- lastGreen: lastGreen.trim(),
53
- files,
54
- drift: drift.trim(),
55
- };
56
- }
57
-
58
- function sliceSection(markdown, headingRe) {
59
- const match = headingRe.exec(markdown);
60
- if (!match) return null;
61
- const start = match.index + match[0].length;
62
- const rest = markdown.slice(start);
63
- // Section ends at the next `## ` heading or EOF.
64
- const nextHeading = /\n##\s+/.exec(rest);
65
- const end = nextHeading ? start + nextHeading.index : markdown.length;
66
- return markdown.slice(start, end);
67
- }
68
-
69
- // Target-file entries may carry brace alternation (`src/core/{a,b}.js`) or glob
70
- // stars (`src/core/compact/*.js`) — planners write both. Expand them so a
71
- // progress entry naming a covered file is not a false undeclared-drift.
72
- function escapeRegExp(text) {
73
- return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
74
- }
75
-
76
- function targetPatternToRegExp(pattern) {
77
- // `{a,b}` → alternation; `**` → any path; `*` → any non-separator run.
78
- let source = '';
79
- for (let i = 0; i < pattern.length; i += 1) {
80
- const ch = pattern[i];
81
- if (ch === '*') {
82
- if (pattern[i + 1] === '*') {
83
- source += '.*';
84
- i += 1;
85
- } else {
86
- source += '[^/]*';
87
- }
88
- } else if (ch === '{') {
89
- const close = pattern.indexOf('}', i + 1);
90
- if (close === -1) {
91
- source += '\\{';
92
- } else {
93
- source += `(?:${pattern.slice(i + 1, close).split(',').map(escapeRegExp).join('|')})`;
94
- i = close;
95
- }
96
- } else {
97
- source += escapeRegExp(ch);
98
- }
99
- }
100
- return new RegExp(`^${source}$`);
101
- }
102
-
103
- function collectTargetFiles(markdown) {
104
- const section = sliceSection(markdown, TARGET_HEADING);
105
- const files = new Set();
106
- const patterns = [];
107
- if (section) {
108
- for (const line of section.split('\n')) {
109
- // Lines look like "- `path/to/file.js` — what changes"
110
- const m = /^\s*-\s+`?([^`\s]+(?:\.[^`\s]+)?)`?/.exec(line);
111
- if (!m) continue;
112
- const target = m[1];
113
- if (/[{*]/.test(target)) patterns.push(targetPatternToRegExp(target));
114
- else files.add(target);
115
- }
116
- }
117
- return {
118
- has(file) {
119
- return files.has(file) || patterns.some((re) => re.test(file));
120
- },
121
- };
122
- }
123
-
124
- function collectProgressEntries(progressSection) {
125
- const entries = [];
126
- for (const line of progressSection.split('\n')) {
127
- const trimmed = line.trim();
128
- if (!trimmed.startsWith('- ')) continue;
129
- const parsed = parseEntry(trimmed);
130
- if (parsed) {
131
- entries.push(parsed);
132
- } else if (trimmed.includes('milestone:')) {
133
- // A bullet that looks like a progress entry but fails the entry grammar is
134
- // malformed — report it rather than silently dropping it.
135
- entries.push({ ok: false, raw: trimmed });
136
- }
137
- }
138
- return entries;
139
- }
140
-
141
- function collectAllProgressEntries(markdown) {
142
- const headings = [...markdown.matchAll(PROGRESS_HEADING_GLOBAL)];
143
- return headings.flatMap((heading, index) => {
144
- const start = heading.index + heading[0].length;
145
- const nextHeading = /\n##\s+/.exec(markdown.slice(start));
146
- const end = nextHeading ? start + nextHeading.index : markdown.length;
147
- return collectProgressEntries(markdown.slice(start, end));
148
- });
149
- }
150
-
151
- export function checkMilestoneProgress({
152
- markdown,
153
- now = Date.now(),
154
- milestoneIntervalMin = 5,
155
- } = {}) {
156
- const violations = [];
157
-
158
- if (typeof markdown !== 'string' || markdown.length === 0) {
159
- return { ok: false, violations: [{ type: 'no-progress', detail: 'markdown is empty' }] };
160
- }
161
-
162
- if (!REPORT_HEADING.test(markdown)) {
163
- // No Executor Report — nothing to check.
164
- return { ok: true, violations: [] };
165
- }
166
-
167
- if (!PROGRESS_HEADING.test(markdown)) {
168
- return {
169
- ok: false,
170
- violations: [{ type: 'no-progress', detail: '## Progress section missing' }],
171
- };
172
- }
173
-
174
- const entries = collectAllProgressEntries(markdown);
175
-
176
- if (entries.length === 0) {
177
- violations.push({ type: 'no-progress', detail: '## Progress section has no entries' });
178
- return { ok: false, violations };
179
- }
180
-
181
- let newestTs = -Infinity;
182
- for (const entry of entries) {
183
- if (!entry.ok) {
184
- violations.push({ type: 'malformed-entry', detail: `unparseable timestamp: ${entry.raw}` });
185
- continue;
186
- }
187
- if (entry.timestamp > newestTs) newestTs = entry.timestamp;
188
- }
189
-
190
- if (Number.isFinite(newestTs)) {
191
- const intervalMs = milestoneIntervalMin * 60 * 1000;
192
- const limitMs = 2 * intervalMs;
193
- const ageMs = now - newestTs;
194
- // Boundary: ageMs === limitMs is still OK; ageMs > limitMs is stale.
195
- if (ageMs > limitMs) {
196
- violations.push({
197
- type: 'stale-milestone',
198
- detail: `newest entry is ${Math.round(ageMs / 60000)} min old; threshold is ${2 * milestoneIntervalMin} min`,
199
- });
200
- }
201
- // W2-C7: a timestamp in the future would yield negative age and silently
202
- // never fire staleness. Rule: >1 interval in the future counts as
203
- // stale-milestone (same vocabulary); <=1 interval is tolerated clock skew.
204
- if (newestTs - now > intervalMs) {
205
- violations.push({
206
- type: 'stale-milestone',
207
- detail: `newest entry is ${Math.round((newestTs - now) / 60000)} min in the future; allowed skew is ${milestoneIntervalMin} min`,
208
- });
209
- }
210
- }
211
-
212
- const targetFiles = collectTargetFiles(markdown);
213
- for (const entry of entries) {
214
- if (!entry.ok) continue;
215
- const driftReason = entry.drift && entry.drift !== 'none' ? entry.drift : null;
216
- for (const file of entry.files) {
217
- if (!targetFiles.has(file) && !driftReason) {
218
- violations.push({
219
- type: 'undeclared-drift',
220
- detail: `file '${file}' not in ## Target Files and entry has no drift reason`,
221
- });
222
- }
223
- }
224
- }
225
-
226
- return { ok: violations.length === 0, violations };
227
- }
@@ -1,339 +0,0 @@
1
- /**
2
- * reviewVerdict.js (S2 / UNIC_DECISION_MIGRATION)
3
- *
4
- * Review-verdict producer for the `review` decision family. Reviewers (the
5
- * general-LLM code-reviewer agents) still generate findings; when
6
- * `decisionPlane.families.review.stage` is promoted past 'off', the FINAL
7
- * verdict and per-finding bucket pass runs through unic-decision instead.
8
- * Deterministic severity aggregation stays authoritative on 'off' and on
9
- * every failure path — never another LLM for the verdict.
10
- *
11
- * Registered keys (src/decision/registry.js):
12
- * review.verdict.v1 — solo reviewer verdict (choice)
13
- * review.finding-bucket.v1 — per-finding triage bucket (choice; asked once
14
- * per finding, wire name carries `#<id>`)
15
- * review.panel-verdict.v1 — aggregated panel verdict (choice)
16
- *
17
- * Transport discipline (C13/statePacket conventions): only whitelisted,
18
- * truncated finding fields cross the wire — {id, severity, location, claim}.
19
- * No diff hunks, no prose, no secrets. Everything below is pure — no I/O —
20
- * and never throws (client.js precedent).
21
- */
22
-
23
- export const VERDICT_CANDIDATES = Object.freeze([
24
- 'APPROVED',
25
- 'APPROVED-WITH-MINOR',
26
- 'CHANGES-REQUESTED',
27
- 'CRITICAL',
28
- ]);
29
-
30
- export const BUCKET_CANDIDATES = Object.freeze([
31
- 'Act on',
32
- 'Consider',
33
- 'Noted',
34
- 'Dismissed',
35
- ]);
36
-
37
- export const REVIEW_VERDICT_KEYS = Object.freeze({
38
- solo: 'review.verdict.v1',
39
- bucket: 'review.finding-bucket.v1',
40
- panel: 'review.panel-verdict.v1',
41
- });
42
-
43
- // Bounds keep the batch inside the state budget and the tool list small.
44
- // MAX_FINDINGS mirrors statePacket.js MAX_ARRAY_ITEMS (24); a question plus a
45
- // verdict slot means at most MAX_FINDINGS bucket questions per batch.
46
- export const MAX_FINDINGS = 24;
47
- export const MAX_CLAIM_LENGTH = 160;
48
- const MAX_LOCATION_LENGTH = 160;
49
- const MAX_ID_LENGTH = 64;
50
- const MAX_SEVERITY_LENGTH = 24;
51
-
52
- const KNOWN_SEVERITIES = new Set(['critical', 'important', 'minor']);
53
-
54
- const BUCKET_INSTRUCTION =
55
- 'Triage this single review finding into exactly one bucket: '
56
- + '"Act on" feeds the auto-fix loop; "Consider" is advisory but worth the '
57
- + 'author\'s attention; "Noted" is informational only; "Dismissed" is '
58
- + 'rejected as not actionable.';
59
-
60
- function isPlainObject(value) {
61
- return value !== null && typeof value === 'object' && !Array.isArray(value);
62
- }
63
-
64
- function collapseWhitespace(text) {
65
- return String(text).replace(/\s+/g, ' ').trim();
66
- }
67
-
68
- function truncate(text, max) {
69
- return text.length > max ? `${text.slice(0, max - 1)}…` : text;
70
- }
71
-
72
- function normalizeSeverity(raw) {
73
- const severity = typeof raw === 'string'
74
- ? raw.trim().toLowerCase().slice(0, MAX_SEVERITY_LENGTH)
75
- : '';
76
- return KNOWN_SEVERITIES.has(severity) ? severity : 'unknown';
77
- }
78
-
79
- // Whitelist one finding down to the exact fields the verdict pass is allowed
80
- // to see. Location collapses file:line into a single label; every other
81
- // field on the input object is dropped silently.
82
- function sanitizeFinding(raw, index, usedIds) {
83
- const source = isPlainObject(raw) ? raw : {};
84
- let id = typeof source.id === 'string' && source.id.trim().length > 0
85
- ? source.id.trim().replace(/[^A-Za-z0-9._-]/g, '_').slice(0, MAX_ID_LENGTH)
86
- : `F${index + 1}`;
87
- if (id.length === 0 || usedIds.has(id)) {
88
- // Collision fallback must itself be unique — two findings both claiming
89
- // 'F2' must not collapse into one wire name / one bucket row.
90
- let suffix = '';
91
- while (usedIds.has(`F${index + 1}${suffix}`)) suffix = `${suffix}x`;
92
- id = `F${index + 1}${suffix}`;
93
- }
94
- usedIds.add(id);
95
-
96
- let file = typeof source.file === 'string' ? collapseWhitespace(source.file) : '';
97
- const line = Number.isInteger(source.line) && source.line > 0 ? source.line : null;
98
- if (file.length > 0) file = truncate(file, MAX_LOCATION_LENGTH - 8);
99
- const location = file.length > 0
100
- ? (line !== null ? `${file}:${line}` : file)
101
- : (line !== null ? `line ${line}` : '-');
102
-
103
- const claimSource = [source.claim, source.title, source.summary, source.message]
104
- .find((v) => typeof v === 'string' && v.trim().length > 0);
105
-
106
- return {
107
- id,
108
- severity: normalizeSeverity(source.severity),
109
- location,
110
- claim: truncate(collapseWhitespace(claimSource ?? ''), MAX_CLAIM_LENGTH),
111
- };
112
- }
113
-
114
- // Stable short fingerprint for the batch id — same findings → same batchId
115
- // across runs, so receipts and logs reconcile.
116
- function stableBatchId(findings) {
117
- let h = 0x811c9dc5;
118
- const text = JSON.stringify(findings.map((f) => [f.id, f.severity, f.location, f.claim]));
119
- for (let i = 0; i < text.length; i += 1) {
120
- h ^= text.charCodeAt(i);
121
- h = Math.imul(h, 0x01000193);
122
- }
123
- return `rv-${(h >>> 0).toString(16).padStart(8, '0')}`;
124
- }
125
-
126
- /**
127
- * Build the C13 question batch for the review verdict pass.
128
- *
129
- * @param {object} [input]
130
- * @param {Array} [input.findings] extracted review findings (whitelisted
131
- * fields only: id/severity/file/line/claim|title|summary|message).
132
- * @param {string} [input.mode] 'solo' → review.verdict.v1 question;
133
- * 'panel' → review.panel-verdict.v1 instead.
134
- * @returns {{questions: object[], statePacket: object, batch: object,
135
- * findings: object[], verdictDecisionKey: string}}
136
- * Never throws — garbage input sanitizes to an empty finding list.
137
- */
138
- export function buildReviewVerdictBatch({ findings = [], mode = 'solo', maxQuestions = Infinity } = {}) {
139
- const usedIds = new Set();
140
- // Sanitize the FULL finding set — MAX_FINDINGS is a display/transport bound
141
- // for the batch, not a verdict bound. The deterministic verdict and the
142
- // truncation clamp both run on `fullFindings` (W3-RV1).
143
- const sanitized = (Array.isArray(findings) ? findings : [])
144
- .map((raw, index) => sanitizeFinding(raw, index, usedIds));
145
- const batchFindings = sanitized.slice(0, MAX_FINDINGS);
146
- const truncated = sanitized.length > batchFindings.length;
147
-
148
- // Request-cap handling (no extra call): when verdict + one bucket question per
149
- // finding would exceed `maxQuestions`, ask only findings whose bucket the model
150
- // can actually change. `Act on` is a deterministic floor the model cannot
151
- // lower, so critical/important/unknown findings carry no semantic value in the
152
- // batch; the rest keep their deterministic bucket and are reported as skipped.
153
- const slots = Number.isInteger(maxQuestions) && maxQuestions > 0
154
- ? maxQuestions - 1 : Infinity;
155
- const askedFindings = batchFindings.length <= slots
156
- ? batchFindings
157
- : batchFindings.filter((f) => deriveDeterministicBucket(f) !== 'Act on').slice(0, slots);
158
- const askedIds = new Set(askedFindings.map((f) => f.id));
159
- const skippedFindingIds = batchFindings.filter((f) => !askedIds.has(f.id)).map((f) => f.id);
160
-
161
- const verdictDecisionKey = mode === 'panel'
162
- ? REVIEW_VERDICT_KEYS.panel
163
- : REVIEW_VERDICT_KEYS.solo;
164
-
165
- const counts = { critical: 0, important: 0, minor: 0, unknown: 0 };
166
- for (const f of batchFindings) counts[f.severity] += 1;
167
-
168
- const verdictQuestion = {
169
- decisionKey: verdictDecisionKey,
170
- schemaVersion: 1,
171
- family: 'review',
172
- owner: 'handoffReview',
173
- kind: 'choice',
174
- instruction:
175
- 'Pick the bounded review verdict for this finding set. '
176
- + 'APPROVED = clean; APPROVED-WITH-MINOR = ship with nits logged; '
177
- + 'CHANGES-REQUESTED = must fix before merge; CRITICAL = unsafe to ship.',
178
- candidates: [...VERDICT_CANDIDATES],
179
- hardConstraintRefs: ['verdict-vocabulary'],
180
- };
181
-
182
- // One bucket question per finding. The shared registered key cannot repeat
183
- // in one batch (name-based reconciliation), so each wire name carries
184
- // `#<findingId>`; parseVerdictAnswer splits it back off.
185
- const bucketQuestions = askedFindings.map((f) => ({
186
- decisionKey: `${REVIEW_VERDICT_KEYS.bucket}#${f.id}`,
187
- schemaVersion: 1,
188
- family: 'review',
189
- owner: 'handoffReview',
190
- kind: 'choice',
191
- instruction: `${BUCKET_INSTRUCTION} Finding ${f.id} [${f.severity}] ${f.location}: ${f.claim || '(no claim text)'}`,
192
- candidates: [...BUCKET_CANDIDATES],
193
- hardConstraintRefs: ['bucket-vocabulary'],
194
- }));
195
-
196
- const questions = [verdictQuestion, ...bucketQuestions];
197
-
198
- // Producer-owned packet — only sanitized whitelisted fields. `findingCount`
199
- // is the only aggregate the model needs; severities ride the findings array.
200
- const statePacket = {
201
- kind: 'review-verdict',
202
- mode: mode === 'panel' ? 'panel' : 'solo',
203
- findingCount: batchFindings.length,
204
- severityCounts: counts,
205
- findings: batchFindings,
206
- };
207
-
208
- const batch = {
209
- batchVersion: 1,
210
- batchId: stableBatchId(batchFindings),
211
- boundary: 'review-verdict',
212
- questions,
213
- statePacket,
214
- };
215
-
216
- return {
217
- questions,
218
- statePacket,
219
- batch,
220
- findings: batchFindings,
221
- fullFindings: sanitized,
222
- truncated,
223
- skippedFindingIds,
224
- verdictDecisionKey,
225
- };
226
- }
227
-
228
- /**
229
- * Deterministic verdict from finding severities — the authoritative path at
230
- * stage 'off' and the fallback on every failure (unic-decision unavailable,
231
- * malformed/invalid answers). Rule (documented in review-verdict.mjs):
232
- * any critical → CHANGES-REQUESTED
233
- * ≥1 important or ≥1 unclassified → APPROVED-WITH-MINOR
234
- * else → APPROVED
235
- */
236
- export function deriveDeterministicVerdict(findings) {
237
- const list = Array.isArray(findings) ? findings : [];
238
- let importantish = false;
239
- for (const raw of list) {
240
- const severity = isPlainObject(raw) ? normalizeSeverity(raw.severity) : 'unknown';
241
- if (severity === 'critical') return 'CHANGES-REQUESTED';
242
- if (severity === 'important' || severity === 'unknown') importantish = true;
243
- }
244
- return importantish ? 'APPROVED-WITH-MINOR' : 'APPROVED';
245
- }
246
-
247
- /**
248
- * Deterministic per-finding bucket — the fallback the lead reviewer's
249
- * bucketing judgment replaces only when the family stage is enabled.
250
- * critical | important | unclassified → 'Act on'
251
- * minor → 'Noted'
252
- * Conservative: an unknown severity feeds the auto-fix loop rather than
253
- * being silently dismissed.
254
- */
255
- export function deriveDeterministicBucket(finding) {
256
- const severity = normalizeSeverity(isPlainObject(finding) ? finding.severity : null);
257
- return severity === 'minor' ? 'Noted' : 'Act on';
258
- }
259
-
260
- // Wire name → {decisionKey, findingId}: 'review.finding-bucket.v1#F3' splits
261
- // into the registered key plus the finding the bucket answer belongs to.
262
- function splitWireName(name) {
263
- const text = String(name ?? '');
264
- const hash = text.lastIndexOf('#');
265
- if (hash > 0 && text.slice(0, hash) === REVIEW_VERDICT_KEYS.bucket) {
266
- return { decisionKey: REVIEW_VERDICT_KEYS.bucket, findingId: text.slice(hash + 1) };
267
- }
268
- return { decisionKey: text, findingId: null };
269
- }
270
-
271
- /**
272
- * Fold a DecisionBatchResult (from client.requestBatch or an offline
273
- * parseBatchResponse) into the review-verdict shape. Never throws; every
274
- * invalid/missing answer degrades to `null`/deterministic-bucket so callers
275
- * can substitute deriveDeterministicVerdict as the authoritative fallback.
276
- *
277
- * @param {object} [result] DecisionBatchResult — {status, answers}.
278
- * @param {object} [opts]
279
- * @param {Array} [opts.findings] sanitized or raw findings — supplies the
280
- * bucket fold order and per-finding fallback values.
281
- * @returns {{status: string, verdict: string|null, verdictStatus: string,
282
- * buckets: Array<{findingId, bucket, bucketStatus}>}}
283
- */
284
- export function parseVerdictAnswer(result, { findings = [] } = {}) {
285
- const status = typeof result?.status === 'string' ? result.status : 'invalid';
286
- const answers = Array.isArray(result?.answers) ? result.answers : [];
287
- const list = Array.isArray(findings) ? findings : [];
288
- let verdict = null;
289
- let verdictStatus = 'missing';
290
- // findingId → {bucket, bucketStatus}; 'default' marks the deterministic
291
- // fallback standing in because the batch never produced an answer for it.
292
- const bucketByFinding = new Map();
293
- for (const raw of list) {
294
- if (!isPlainObject(raw)) continue;
295
- const id = typeof raw.id === 'string' && raw.id.length > 0 ? raw.id : null;
296
- if (id === null) continue;
297
- bucketByFinding.set(id, {
298
- bucket: deriveDeterministicBucket(raw),
299
- bucketStatus: 'default',
300
- });
301
- }
302
-
303
- for (const answer of answers) {
304
- if (!isPlainObject(answer)) continue;
305
- const { decisionKey, findingId } = splitWireName(answer.decisionKey);
306
- const valid = answer.validationStatus === 'valid'
307
- && typeof answer.value === 'string';
308
- if (decisionKey === REVIEW_VERDICT_KEYS.solo
309
- || decisionKey === REVIEW_VERDICT_KEYS.panel) {
310
- if (valid && VERDICT_CANDIDATES.includes(answer.value)) {
311
- verdict = answer.value;
312
- verdictStatus = 'valid';
313
- } else {
314
- // The pair stays consistent: an invalid answer for the verdict key
315
- // clears any earlier valid verdict — never leave a stale APPROVED
316
- // standing behind verdictStatus 'invalid' (W3-RV2).
317
- verdict = null;
318
- verdictStatus = 'invalid';
319
- }
320
- continue;
321
- }
322
- if (decisionKey === REVIEW_VERDICT_KEYS.bucket && findingId !== null) {
323
- bucketByFinding.set(
324
- findingId,
325
- valid && BUCKET_CANDIDATES.includes(answer.value)
326
- ? { bucket: answer.value, bucketStatus: 'valid' }
327
- : { bucket: deriveDeterministicBucket({ severity: 'unknown' }), bucketStatus: 'invalid' },
328
- );
329
- }
330
- }
331
-
332
- const buckets = [...bucketByFinding.entries()].map(([findingId, entry]) => ({
333
- findingId,
334
- bucket: entry.bucket,
335
- bucketStatus: entry.bucketStatus,
336
- }));
337
-
338
- return { status, verdict, verdictStatus, buckets };
339
- }