@ngockhoale/ukit 2.6.10 → 2.6.11

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.
@@ -540,7 +540,8 @@ async function proposePatternCandidateV2(projectRoot, projectId, candidate) {
540
540
  .filter((record) => record.provenance === 'pattern-candidate'
541
541
  || String(record.provenance ?? '').includes('pattern-candidate'))
542
542
  .find((record) => record.meta?.legacyStatus === 'pending'
543
- && normalizePatternText(record.text) === normalizedText);
543
+ && (normalizePatternText(record.text) === normalizedText
544
+ || (candidate?.signature && record.meta?.signature === candidate.signature)));
544
545
  if (existing) {
545
546
  return patternCandidateFromRecord(existing);
546
547
  }
@@ -553,6 +554,7 @@ async function proposePatternCandidateV2(projectRoot, projectId, candidate) {
553
554
  detectedAt: Date.now(),
554
555
  status: 'pending',
555
556
  };
557
+ if (candidate?.signature) entry.signature = candidate.signature;
556
558
 
557
559
  await v2.addRecord(projectRoot, {
558
560
  type: 'derived_fact',
@@ -626,7 +628,9 @@ export async function proposePatternCandidate(projectRoot, projectId, candidate)
626
628
 
627
629
  const patternCandidates = Array.isArray(memory.patternCandidates) ? memory.patternCandidates : [];
628
630
  const existingPending = patternCandidates.find(
629
- (entry) => entry.status === 'pending' && normalizePatternText(entry.text) === normalizedText,
631
+ (entry) => entry.status === 'pending'
632
+ && (normalizePatternText(entry.text) === normalizedText
633
+ || (candidate?.signature && entry.signature === candidate.signature)),
630
634
  );
631
635
  if (existingPending) {
632
636
  return existingPending;
@@ -640,6 +644,7 @@ export async function proposePatternCandidate(projectRoot, projectId, candidate)
640
644
  detectedAt: Date.now(),
641
645
  status: 'pending',
642
646
  };
647
+ if (candidate?.signature) entry.signature = candidate.signature;
643
648
 
644
649
  memory.patternCandidates = [...patternCandidates, entry];
645
650
  await persistProjectMemoryWithHygiene(projectRoot, runtimePaths, projectId, filePath, memory);
@@ -209,6 +209,14 @@ export function buildDefaultRuntimeConfig(overrides = {}) {
209
209
  maxRetries: 1,
210
210
  confidenceThreshold: 50,
211
211
  },
212
+ // Phase-4 learning loop (SPEC §8a). Advisory only — applyMode 'manual'
213
+ // means suggestions are computed + persisted, never auto-applied.
214
+ learning: {
215
+ feedback: { enabled: true, maxEvents: 200 },
216
+ proposals: { minCount: 3, minSessions: 2 },
217
+ episodes: { autoWrite: false },
218
+ tuning: { enabled: true, applyMode: 'manual' },
219
+ },
212
220
  safePatch: {
213
221
  enabled: true,
214
222
  strictSharedRisk: true,
@@ -564,6 +572,51 @@ export function validateRuntimeConfig(config) {
564
572
  pushPositiveNumberError(errors, config.safePatch.deltaMaxDiffCells, 'safePatch.deltaMaxDiffCells');
565
573
  }
566
574
 
575
+ // learning is optional-present: absent → valid (old configs); present but
576
+ // not an object → error. Per-key checks apply only when the sub-object
577
+ // exists, so partial learning blocks stay valid via defaults merge.
578
+ if (config.learning !== undefined) {
579
+ if (!isPlainObject(config.learning)) {
580
+ errors.push('learning must be an object.');
581
+ } else {
582
+ const learning = config.learning;
583
+ if (learning.feedback !== undefined) {
584
+ if (!isPlainObject(learning.feedback)) {
585
+ errors.push('learning.feedback must be an object.');
586
+ } else {
587
+ pushBooleanError(errors, learning.feedback.enabled, 'learning.feedback.enabled');
588
+ pushPositiveNumberError(errors, learning.feedback.maxEvents, 'learning.feedback.maxEvents');
589
+ }
590
+ }
591
+ if (learning.proposals !== undefined) {
592
+ if (!isPlainObject(learning.proposals)) {
593
+ errors.push('learning.proposals must be an object.');
594
+ } else {
595
+ pushPositiveNumberError(errors, learning.proposals.minCount, 'learning.proposals.minCount');
596
+ pushPositiveNumberError(errors, learning.proposals.minSessions, 'learning.proposals.minSessions');
597
+ }
598
+ }
599
+ if (learning.episodes !== undefined) {
600
+ if (!isPlainObject(learning.episodes)) {
601
+ errors.push('learning.episodes must be an object.');
602
+ } else {
603
+ pushBooleanError(errors, learning.episodes.autoWrite, 'learning.episodes.autoWrite');
604
+ }
605
+ }
606
+ if (learning.tuning !== undefined) {
607
+ if (!isPlainObject(learning.tuning)) {
608
+ errors.push('learning.tuning must be an object.');
609
+ } else {
610
+ pushBooleanError(errors, learning.tuning.enabled, 'learning.tuning.enabled');
611
+ const VALID_APPLY_MODES = new Set(['manual', 'off']);
612
+ if (!VALID_APPLY_MODES.has(learning.tuning.applyMode)) {
613
+ errors.push(`learning.tuning.applyMode must be one of: ${[...VALID_APPLY_MODES].join(', ')}.`);
614
+ }
615
+ }
616
+ }
617
+ }
618
+ }
619
+
567
620
  if (!isPlainObject(config.subagents)) {
568
621
  errors.push('subagents must be an object.');
569
622
  } else {
@@ -19,10 +19,9 @@
19
19
 
20
20
  import fs from 'node:fs/promises';
21
21
  import path from 'node:path';
22
+ import { listLedgerFiles, LEDGER_DIR_REL } from './ledgerFiles.js';
22
23
 
23
- const LEDGER_DIR_REL = path.join('.ukit', 'storage', 'cache', 'exec-ledger');
24
24
  const ARTIFACT_REL = path.join('.ukit', 'storage', 'cache', 'failure-patterns.json');
25
- const NON_LEDGER_FILES = new Set(['gate-crash-counter.json']);
26
25
  const MAX_PATTERNS = 10;
27
26
  const MAX_EXAMPLES = 3;
28
27
 
@@ -33,14 +32,6 @@ function isObject(value) {
33
32
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
34
33
  }
35
34
 
36
- function isLedgerFilename(name) {
37
- if (typeof name !== 'string' || !name.endsWith('.json')) return false;
38
- if (NON_LEDGER_FILES.has(name)) return false;
39
- if (name.includes('.journal')) return false;
40
- if (name.includes('.quarantine')) return false;
41
- return true;
42
- }
43
-
44
35
  // First two whitespace tokens, lowercased; path-like or numeric tokens become `<arg>`.
45
36
  function normalizeSignature(command) {
46
37
  if (typeof command !== 'string') return null;
@@ -74,30 +65,6 @@ function failureCommands(ledger) {
74
65
  return out;
75
66
  }
76
67
 
77
- async function listLedgerFiles(dir, limit) {
78
- let entries;
79
- try {
80
- entries = await fs.readdir(dir, { withFileTypes: true });
81
- } catch {
82
- return [];
83
- }
84
- const files = [];
85
- for (const entry of entries) {
86
- if (!entry.isFile() || !isLedgerFilename(entry.name)) continue;
87
- files.push(entry.name);
88
- }
89
- const withMtime = await Promise.all(files.map(async (name) => {
90
- try {
91
- const stat = await fs.stat(path.join(dir, name));
92
- return { name, mtimeMs: stat.mtimeMs };
93
- } catch {
94
- return { name, mtimeMs: 0 };
95
- }
96
- }));
97
- withMtime.sort((a, b) => b.mtimeMs - a.mtimeMs);
98
- return withMtime.slice(0, limit).map((f) => f.name);
99
- }
100
-
101
68
  async function writeArtifact(filePath, result) {
102
69
  const dir = path.dirname(filePath);
103
70
  const tmp = path.join(dir, `.failure-patterns-${process.pid}.tmp`);
@@ -0,0 +1,196 @@
1
+ // feedbackEvents.js — labeled wrong-route feedback events collector (SPEC C32 §3b).
2
+ //
3
+ // Derives labeled events from telemetry already on disk:
4
+ // * rescue — route-audit entry with `rescueMode != null` → detail = rescueMode
5
+ // * re-route — consecutive same-fingerprint audit entries where the later
6
+ // entry changed executionMode (detail "<prev>→<new>")
7
+ // * repeat-stall — audit `repeatCount >= minRepeat` with no matching
8
+ // ledger `writeSucceeded` (join on requestKey)
9
+ // * user-correction — manual labels appended by `ukit feedback "<text>"` to
10
+ // `.ukit/storage/cache/feedback-manual.jsonl`
11
+ //
12
+ // Contracts:
13
+ // * NEVER THROWS. Missing/malformed telemetry → zeroed result, `error` field
14
+ // on failure. Artifact write failure is non-fatal.
15
+ // * EVIDENCE-ONLY. The only side effect is the advisory artifact
16
+ // `.ukit/storage/learning/feedback-events.json` (tmp+rename).
17
+ // * Gated by config `learning?.feedback?.enabled !== false` (default true;
18
+ // the `learning` namespace lands in TASK-232 so the read is defensive).
19
+
20
+ import fs from 'node:fs/promises';
21
+ import path from 'node:path';
22
+ import { listLedgerFiles, LEDGER_DIR_REL } from './ledgerFiles.js';
23
+
24
+ const CACHE_DIR_REL = path.join('.ukit', 'storage', 'cache');
25
+ const AUDIT_REL = path.join(CACHE_DIR_REL, 'route-audit.json');
26
+ const MANUAL_REL = path.join(CACHE_DIR_REL, 'feedback-manual.jsonl');
27
+ const ARTIFACT_REL = path.join('.ukit', 'storage', 'learning', 'feedback-events.json');
28
+ const CONFIG_REL = path.join('.ukit', 'storage', 'config.json');
29
+ const MAX_EVENTS = 200;
30
+
31
+ function isObject(value) {
32
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
33
+ }
34
+
35
+ function zeroedResult(extra = {}) {
36
+ return {
37
+ generatedAt: new Date().toISOString(),
38
+ auditRowsScanned: 0,
39
+ ledgersScanned: 0,
40
+ byKind: { rescue: 0, 're-route': 0, 'repeat-stall': 0, 'user-correction': 0 },
41
+ events: [],
42
+ ...extra,
43
+ };
44
+ }
45
+
46
+ async function readJson(filePath) {
47
+ try {
48
+ return JSON.parse(await fs.readFile(filePath, 'utf8'));
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ // Default true when `learning`/`feedback` is absent (namespace lands in TASK-232).
55
+ async function feedbackEnabled(projectRoot) {
56
+ const config = await readJson(path.join(projectRoot, CONFIG_REL));
57
+ return config?.learning?.feedback?.enabled !== false;
58
+ }
59
+
60
+ // Manual jsonl is field-tolerant: unknown keys ignored, a legacy `context`
61
+ // key is treated as an optional extra. Bad lines are skipped, not fatal.
62
+ async function readManualEvents(projectRoot, byKind) {
63
+ const events = [];
64
+ let raw;
65
+ try {
66
+ raw = await fs.readFile(path.join(projectRoot, MANUAL_REL), 'utf8');
67
+ } catch {
68
+ return events;
69
+ }
70
+ for (const line of raw.split('\n')) {
71
+ const trimmed = line.trim();
72
+ if (!trimmed) continue;
73
+ let record;
74
+ try {
75
+ record = JSON.parse(trimmed);
76
+ } catch {
77
+ continue;
78
+ }
79
+ if (!isObject(record) || typeof record.text !== 'string') continue;
80
+ const event = {
81
+ ts: typeof record.ts === 'number' ? record.ts : 0,
82
+ kind: 'user-correction',
83
+ detail: record.text,
84
+ source: 'manual',
85
+ };
86
+ if (typeof record.targetFile === 'string') event.targetFile = record.targetFile;
87
+ events.push(event);
88
+ byKind['user-correction'] += 1;
89
+ }
90
+ return events;
91
+ }
92
+
93
+ async function writeArtifact(filePath, result) {
94
+ const dir = path.dirname(filePath);
95
+ const tmp = path.join(dir, `.feedback-events-${process.pid}.tmp`);
96
+ try {
97
+ await fs.mkdir(dir, { recursive: true });
98
+ await fs.writeFile(tmp, JSON.stringify(result, null, 2));
99
+ await fs.rename(tmp, filePath);
100
+ } catch {
101
+ await fs.rm(tmp, { force: true }).catch(() => {});
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Collect labeled wrong-route feedback events.
107
+ *
108
+ * @param {string} projectRoot repository root containing `.ukit/storage/`.
109
+ * @param {{ limitLedgers?: number, minRepeat?: number }} [options]
110
+ * @returns {Promise<{generatedAt: string, auditRowsScanned: number,
111
+ * ledgersScanned: number, byKind: Record<string, number>,
112
+ * events: Array<object>, error?: string}>} never throws.
113
+ */
114
+ export async function collectFeedbackEvents(projectRoot, { limitLedgers = 500, minRepeat = 2 } = {}) {
115
+ const result = zeroedResult();
116
+ try {
117
+ if (!(await feedbackEnabled(projectRoot))) {
118
+ return result;
119
+ }
120
+
121
+ const auditDoc = await readJson(path.join(projectRoot, AUDIT_REL));
122
+ const auditEntries = Array.isArray(auditDoc?.entries)
123
+ ? auditDoc.entries.filter(isObject)
124
+ : [];
125
+ result.auditRowsScanned = auditEntries.length;
126
+
127
+ const ledgerDir = path.join(projectRoot, LEDGER_DIR_REL);
128
+ const ledgerNames = await listLedgerFiles(ledgerDir, limitLedgers);
129
+ const writeOkKeys = new Set();
130
+ for (const name of ledgerNames) {
131
+ const ledger = await readJson(path.join(ledgerDir, name));
132
+ if (!isObject(ledger)) continue;
133
+ result.ledgersScanned += 1;
134
+ if (ledger.writeSucceeded === true && typeof ledger.requestKey === 'string') {
135
+ writeOkKeys.add(ledger.requestKey);
136
+ }
137
+ }
138
+
139
+ const events = [];
140
+ for (const entry of auditEntries) {
141
+ const base = {
142
+ ts: typeof entry.ts === 'number' ? entry.ts : 0,
143
+ requestKey: typeof entry.requestKey === 'string' ? entry.requestKey : undefined,
144
+ targetFile: typeof entry.targetFile === 'string' ? entry.targetFile : undefined,
145
+ taskType: typeof entry.taskType === 'string' ? entry.taskType : undefined,
146
+ executionMode: typeof entry.executionMode === 'string' ? entry.executionMode : undefined,
147
+ source: 'derived',
148
+ };
149
+
150
+ if (entry.rescueMode != null) {
151
+ events.push({ ...base, kind: 'rescue', detail: String(entry.rescueMode) });
152
+ result.byKind.rescue += 1;
153
+ }
154
+
155
+ if ((entry.repeatCount ?? 0) >= minRepeat && !writeOkKeys.has(entry.requestKey)) {
156
+ events.push({ ...base, kind: 'repeat-stall', detail: `repeatCount=${entry.repeatCount}` });
157
+ result.byKind['repeat-stall'] += 1;
158
+ }
159
+ }
160
+
161
+ // re-route: audit is newest-first — entry i is the later entry, i+1 the
162
+ // previous one for the same promptFingerprint + targetFile.
163
+ for (let i = 0; i < auditEntries.length - 1; i += 1) {
164
+ const later = auditEntries[i];
165
+ const prev = auditEntries[i + 1];
166
+ if (typeof later.promptFingerprint !== 'string' || !later.promptFingerprint) continue;
167
+ if (later.promptFingerprint !== prev.promptFingerprint) continue;
168
+ if (later.targetFile !== prev.targetFile) continue;
169
+ if (later.wideningBlocked === true) continue;
170
+ const prevMode = prev.executionMode;
171
+ const newMode = later.executionMode;
172
+ if (prevMode == null || newMode == null || prevMode === newMode) continue;
173
+ events.push({
174
+ ts: typeof later.ts === 'number' ? later.ts : 0,
175
+ kind: 're-route',
176
+ requestKey: typeof later.requestKey === 'string' ? later.requestKey : undefined,
177
+ targetFile: typeof later.targetFile === 'string' ? later.targetFile : undefined,
178
+ taskType: typeof later.taskType === 'string' ? later.taskType : undefined,
179
+ executionMode: typeof later.executionMode === 'string' ? later.executionMode : undefined,
180
+ detail: `${prevMode}→${newMode}`,
181
+ source: 'derived',
182
+ });
183
+ result.byKind['re-route'] += 1;
184
+ }
185
+
186
+ events.push(...await readManualEvents(projectRoot, result.byKind));
187
+
188
+ events.sort((a, b) => b.ts - a.ts);
189
+ result.events = events.slice(0, MAX_EVENTS);
190
+ } catch (error) {
191
+ result.error = error?.message ?? String(error);
192
+ }
193
+
194
+ await writeArtifact(path.join(projectRoot, ARTIFACT_REL), result);
195
+ return result;
196
+ }
@@ -0,0 +1,111 @@
1
+ // laneStats.js — retriever lane contribution stats (SPEC C32 §5b).
2
+ //
3
+ // Reads `.ukit/storage/cache/retriever-lanes.jsonl` emitted by the retriever
4
+ // (FR-202b) and rolls up per-lane counters:
5
+ // retrievals = events where the lane had hits > 0
6
+ // totalHits = sum of lane hits
7
+ // exclusive = events where this lane was the SOLE lane with hits > 0
8
+ // (emitters record per-lane hit counts only, so exclusivity
9
+ // is approximated rather than per-path recomputed)
10
+ // avgWeight = mean weightUsed over events that recorded one
11
+ // contribution = retrievals / max(1, events)
12
+ //
13
+ // Contracts: NEVER THROWS — missing/empty file → `empty: true` + zeroed lanes.
14
+
15
+ import fs from 'node:fs/promises';
16
+ import path from 'node:path';
17
+
18
+ const LANES_REL = path.join('.ukit', 'storage', 'cache', 'retriever-lanes.jsonl');
19
+
20
+ function isObject(value) {
21
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
22
+ }
23
+
24
+ function zeroedResult(extra = {}) {
25
+ return {
26
+ generatedAt: new Date().toISOString(),
27
+ events: 0,
28
+ lanes: {},
29
+ empty: false,
30
+ ...extra,
31
+ };
32
+ }
33
+
34
+ function emptyLaneBucket() {
35
+ return {
36
+ retrievals: 0,
37
+ totalHits: 0,
38
+ exclusive: 0,
39
+ avgWeight: 0,
40
+ contribution: 0,
41
+ _weightSum: 0,
42
+ _weightCount: 0,
43
+ };
44
+ }
45
+
46
+ /**
47
+ * Collect retriever lane contribution stats.
48
+ *
49
+ * @param {string} projectRoot repository root containing `.ukit/storage/`.
50
+ * @param {{ maxEvents?: number }} [options]
51
+ * @returns {Promise<object>} never throws.
52
+ */
53
+ export async function collectLaneStats(projectRoot, { maxEvents = 2000 } = {}) {
54
+ const result = zeroedResult();
55
+ try {
56
+ let raw;
57
+ try {
58
+ raw = await fs.readFile(path.join(projectRoot, LANES_REL), 'utf8');
59
+ } catch {
60
+ return { ...result, empty: true };
61
+ }
62
+ const lines = raw.split('\n');
63
+ const events = [];
64
+ for (const line of lines) {
65
+ const trimmed = line.trim();
66
+ if (!trimmed) continue;
67
+ try {
68
+ const record = JSON.parse(trimmed);
69
+ if (isObject(record) && isObject(record.lanes)) events.push(record);
70
+ } catch {
71
+ // skip malformed line
72
+ }
73
+ if (events.length >= maxEvents) break;
74
+ }
75
+ if (events.length === 0) {
76
+ return { ...result, empty: true };
77
+ }
78
+ result.events = events.length;
79
+
80
+ for (const event of events) {
81
+ const positive = [];
82
+ for (const [lane, stats] of Object.entries(event.lanes)) {
83
+ if (!isObject(stats)) continue;
84
+ const bucket = result.lanes[lane] ??= emptyLaneBucket();
85
+ const hits = typeof stats.hits === 'number' ? stats.hits : 0;
86
+ if (hits > 0) {
87
+ bucket.retrievals += 1;
88
+ bucket.totalHits += hits;
89
+ positive.push(lane);
90
+ }
91
+ if (typeof stats.weightUsed === 'number') {
92
+ bucket._weightSum += stats.weightUsed;
93
+ bucket._weightCount += 1;
94
+ }
95
+ }
96
+ if (positive.length === 1) {
97
+ result.lanes[positive[0]].exclusive += 1;
98
+ }
99
+ }
100
+
101
+ for (const bucket of Object.values(result.lanes)) {
102
+ bucket.avgWeight = bucket._weightCount === 0 ? 0 : bucket._weightSum / bucket._weightCount;
103
+ bucket.contribution = bucket.retrievals / Math.max(1, result.events);
104
+ delete bucket._weightSum;
105
+ delete bucket._weightCount;
106
+ }
107
+ } catch (error) {
108
+ result.error = error?.message ?? String(error);
109
+ }
110
+ return result;
111
+ }
@@ -0,0 +1,47 @@
1
+ // ledgerFiles.js — shared exec-ledger directory helpers (SPEC C32 §3a).
2
+ //
3
+ // Extracted from failurePatterns.js so feedbackEvents (and any future
4
+ // ledger-scanning diagnostics) share one glob/mtime discipline:
5
+ // * glob `*.json`, skip `gate-crash-counter.json`, `*.journal*`,
6
+ // `*.quarantine*`, bound results by mtime-desc order.
7
+
8
+ import fs from 'node:fs/promises';
9
+ import path from 'node:path';
10
+
11
+ export const LEDGER_DIR_REL = path.join('.ukit', 'storage', 'cache', 'exec-ledger');
12
+
13
+ const NON_LEDGER_FILES = new Set(['gate-crash-counter.json']);
14
+
15
+ export function isLedgerFilename(name) {
16
+ if (typeof name !== 'string' || !name.endsWith('.json')) return false;
17
+ if (NON_LEDGER_FILES.has(name)) return false;
18
+ if (name.includes('.journal')) return false;
19
+ if (name.includes('.quarantine')) return false;
20
+ return true;
21
+ }
22
+
23
+ // Returns up to `limit` ledger filenames sorted by mtime descending.
24
+ // Missing/unreadable dir → [] (never throws).
25
+ export async function listLedgerFiles(dir, limit) {
26
+ let entries;
27
+ try {
28
+ entries = await fs.readdir(dir, { withFileTypes: true });
29
+ } catch {
30
+ return [];
31
+ }
32
+ const files = [];
33
+ for (const entry of entries) {
34
+ if (!entry.isFile() || !isLedgerFilename(entry.name)) continue;
35
+ files.push(entry.name);
36
+ }
37
+ const withMtime = await Promise.all(files.map(async (name) => {
38
+ try {
39
+ const stat = await fs.stat(path.join(dir, name));
40
+ return { name, mtimeMs: stat.mtimeMs };
41
+ } catch {
42
+ return { name, mtimeMs: 0 };
43
+ }
44
+ }));
45
+ withMtime.sort((a, b) => b.mtimeMs - a.mtimeMs);
46
+ return withMtime.slice(0, Math.max(0, limit)).map((f) => f.name);
47
+ }
@@ -0,0 +1,158 @@
1
+ // skillAccuracy.js — per-skill trigger accuracy collector (SPEC C32 §5a).
2
+ //
3
+ // Joins route-audit entries carrying `skillIds` (FR-202) to exec-ledger
4
+ // ledgers via `requestKey` (same join discipline as routeOutcomes.js) and
5
+ // aggregates per-skill counters:
6
+ // triggers = audit rows listing the skill
7
+ // joined = those matched to a ledger
8
+ // accuracy = joined === 0 ? null : writeOk / joined
9
+ // verifyOk/verifyFail/rescue reported separately for nuance.
10
+ // Skills with triggers >= 2 && accuracy !== null && accuracy < 0.5 are also
11
+ // copied into `lowAccuracy` for quick scanning.
12
+ //
13
+ // Contracts: NEVER THROWS — missing/malformed telemetry → zeroed result with
14
+ // `error` field. Only side effect is the advisory artifact
15
+ // `.ukit/storage/learning/skill-accuracy.json` (tmp+rename, non-fatal).
16
+ // Gated by config `learning?.feedback?.enabled !== false` (default true).
17
+
18
+ import fs from 'node:fs/promises';
19
+ import path from 'node:path';
20
+ import { listLedgerFiles, LEDGER_DIR_REL } from './ledgerFiles.js';
21
+
22
+ const CACHE_DIR_REL = path.join('.ukit', 'storage', 'cache');
23
+ const AUDIT_REL = path.join(CACHE_DIR_REL, 'route-audit.json');
24
+ const ARTIFACT_REL = path.join('.ukit', 'storage', 'learning', 'skill-accuracy.json');
25
+ const CONFIG_REL = path.join('.ukit', 'storage', 'config.json');
26
+ const MAX_SKILL_IDS = 8;
27
+
28
+ function isObject(value) {
29
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
30
+ }
31
+
32
+ function zeroedResult(extra = {}) {
33
+ return {
34
+ generatedAt: new Date().toISOString(),
35
+ auditRowsScanned: 0,
36
+ ledgersScanned: 0,
37
+ joined: 0,
38
+ skills: {},
39
+ lowAccuracy: [],
40
+ ...extra,
41
+ };
42
+ }
43
+
44
+ function emptySkillBucket() {
45
+ return {
46
+ triggers: 0,
47
+ joined: 0,
48
+ writeOk: 0,
49
+ writeFail: 0,
50
+ verifyOk: 0,
51
+ verifyFail: 0,
52
+ rescue: 0,
53
+ accuracy: null,
54
+ };
55
+ }
56
+
57
+ async function readJson(filePath) {
58
+ try {
59
+ return JSON.parse(await fs.readFile(filePath, 'utf8'));
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+
65
+ // Default true when `learning`/`feedback` is absent (namespace lands in TASK-232).
66
+ async function feedbackEnabled(projectRoot) {
67
+ const config = await readJson(path.join(projectRoot, CONFIG_REL));
68
+ return config?.learning?.feedback?.enabled !== false;
69
+ }
70
+
71
+ function skillIdsOf(entry) {
72
+ if (!Array.isArray(entry?.skillIds)) return [];
73
+ return entry.skillIds
74
+ .filter((id) => typeof id === 'string' && id)
75
+ .slice(0, MAX_SKILL_IDS);
76
+ }
77
+
78
+ async function writeArtifact(filePath, result) {
79
+ const dir = path.dirname(filePath);
80
+ const tmp = path.join(dir, `.skill-accuracy-${process.pid}.tmp`);
81
+ try {
82
+ await fs.mkdir(dir, { recursive: true });
83
+ await fs.writeFile(tmp, JSON.stringify(result, null, 2));
84
+ await fs.rename(tmp, filePath);
85
+ } catch {
86
+ await fs.rm(tmp, { force: true }).catch(() => {});
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Collect per-skill trigger accuracy by joining route-audit `skillIds` to
92
+ * exec-ledger ledgers on `requestKey`.
93
+ *
94
+ * @param {string} projectRoot repository root containing `.ukit/storage/`.
95
+ * @param {{ limitLedgers?: number }} [options]
96
+ * @returns {Promise<object>} never throws.
97
+ */
98
+ export async function collectSkillAccuracy(projectRoot, { limitLedgers = 500 } = {}) {
99
+ const result = zeroedResult();
100
+ try {
101
+ if (!(await feedbackEnabled(projectRoot))) {
102
+ return result;
103
+ }
104
+
105
+ const auditDoc = await readJson(path.join(projectRoot, AUDIT_REL));
106
+ const auditEntries = Array.isArray(auditDoc?.entries)
107
+ ? auditDoc.entries.filter(isObject)
108
+ : [];
109
+ result.auditRowsScanned = auditEntries.length;
110
+
111
+ const ledgerDir = path.join(projectRoot, LEDGER_DIR_REL);
112
+ const ledgerNames = await listLedgerFiles(ledgerDir, limitLedgers);
113
+ const ledgerByKey = new Map();
114
+ for (const name of ledgerNames) {
115
+ const ledger = await readJson(path.join(ledgerDir, name));
116
+ if (!isObject(ledger)) continue;
117
+ result.ledgersScanned += 1;
118
+ if (typeof ledger.requestKey === 'string' && ledger.requestKey) {
119
+ ledgerByKey.set(ledger.requestKey, ledger);
120
+ }
121
+ }
122
+
123
+ for (const entry of auditEntries) {
124
+ const ids = skillIdsOf(entry);
125
+ if (ids.length === 0) continue;
126
+ const ledger = typeof entry.requestKey === 'string'
127
+ ? ledgerByKey.get(entry.requestKey)
128
+ : undefined;
129
+ for (const id of ids) {
130
+ const bucket = result.skills[id] ??= emptySkillBucket();
131
+ bucket.triggers += 1;
132
+ if (!ledger) continue;
133
+ bucket.joined += 1;
134
+ if (ledger.writeSucceeded === true) bucket.writeOk += 1;
135
+ else if (ledger.writeAttempted === true || ledger.writeSucceeded === false) {
136
+ bucket.writeFail += 1;
137
+ }
138
+ if (ledger.verificationSucceeded === true) bucket.verifyOk += 1;
139
+ if (ledger.verificationFailed === true) bucket.verifyFail += 1;
140
+ if (entry.rescueMode != null) bucket.rescue += 1;
141
+ }
142
+ if (ledger) result.joined += 1;
143
+ }
144
+
145
+ for (const [id, bucket] of Object.entries(result.skills)) {
146
+ bucket.accuracy = bucket.joined === 0 ? null : bucket.writeOk / bucket.joined;
147
+ if (bucket.triggers >= 2 && bucket.accuracy !== null && bucket.accuracy < 0.5) {
148
+ result.lowAccuracy.push({ id, accuracy: bucket.accuracy });
149
+ }
150
+ }
151
+ result.lowAccuracy.sort((a, b) => a.accuracy - b.accuracy);
152
+ } catch (error) {
153
+ result.error = error?.message ?? String(error);
154
+ }
155
+
156
+ await writeArtifact(path.join(projectRoot, ARTIFACT_REL), result);
157
+ return result;
158
+ }