@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
@@ -22,7 +22,7 @@
22
22
  import fs from 'node:fs';
23
23
  import path from 'node:path';
24
24
  import { spawn } from 'node:child_process';
25
- import { fileURLToPath } from 'node:url';
25
+ import { fileURLToPath, pathToFileURL } from 'node:url';
26
26
 
27
27
  export const MIN_INTERVAL_MS = 10 * 60 * 1000;
28
28
 
@@ -83,16 +83,223 @@ export function triggerSelfImprove({ projectRoot, now = Date.now(), spawnImpl =
83
83
  }
84
84
  }
85
85
 
86
+ // ---- Episode CLI resolution + session-start trigger (3.5.4) ----------------
87
+ // One resolver for every episode/self-improve spawn: the project-pinned CLI
88
+ // (cli.json) wins. Without it the PATH `ukit` is used ONLY when it is not older
89
+ // than the project's installed runtime - an older CLI writes the wrong record
90
+ // shape, so it is refused and the reason is left in episode-cli.json, which
91
+ // `ukit doctor` prints. Async fs only; the PATH version probe is cached by
92
+ // binary path + mtime and only ever runs in a detached worker or the SessionEnd
93
+ // hook's own (already bounded) CLI probe step, never in the SessionStart hook.
94
+ export const EPISODE_START_MIN_INTERVAL_MS = 10 * 60 * 1000;
95
+ const CLI_STATE_REL = path.join('.ukit', 'storage', 'learning', 'episode-cli.json');
96
+ const START_MARKER_REL = path.join('.ukit', 'storage', 'learning', 'episode-start.json');
97
+ const RESULT_REL = path.join('.ukit', 'storage', 'learning', 'episode-start-result.json');
98
+ const PROBE_CACHE_REL = path.join('.ukit', 'storage', 'cache', 'ukit-cli-probe.json');
99
+
100
+ function parseVersion(text) {
101
+ const m = /(\d+)\.(\d+)\.(\d+)/.exec(String(text ?? ''));
102
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
103
+ }
104
+ export function compareVersions(a, b) {
105
+ const x = parseVersion(a); const y = parseVersion(b);
106
+ if (!x || !y) return null;
107
+ for (let i = 0; i < 3; i += 1) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
108
+ return 0;
109
+ }
110
+
111
+ async function readJsonAsync(file) {
112
+ try { return JSON.parse(await fs.promises.readFile(file, 'utf8')); } catch { return null; }
113
+ }
114
+ // Advisory state only, and never a reason to resurrect a project: when `<root>/.ukit/storage`
115
+ // is gone (project deleted, temp dir torn down while a detached worker was still running) the
116
+ // write is dropped instead of `mkdir -p`-ing the whole tree back into existence.
117
+ async function writeJsonAsync(file, value) {
118
+ try {
119
+ const marker = path.join('.ukit', 'storage');
120
+ const at = file.lastIndexOf(marker);
121
+ if (at >= 0) {
122
+ try { await fs.promises.stat(file.slice(0, at + marker.length)); } catch { return; }
123
+ }
124
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
125
+ const tmp = `${file}.${process.pid}.tmp`;
126
+ await fs.promises.writeFile(tmp, `${JSON.stringify(value)}\n`, 'utf8');
127
+ await fs.promises.rename(tmp, file);
128
+ } catch { /* advisory state only */ }
129
+ }
130
+
131
+ // Version of the runtime installed in this project (what the CLI must not be older than).
132
+ async function projectRuntimeVersion(projectRoot) {
133
+ const meta = await readJsonAsync(path.join(projectRoot, '.claude', 'ukit', '.ukit', 'install.json'));
134
+ return typeof meta?.version === 'string' ? meta.version : null;
135
+ }
136
+
137
+ // PATH lookup of `ukit`. On win32 npm installs `ukit.cmd` (and an extensionless sh shim that
138
+ // Windows cannot execute), so the bare name is never tried there: PATHEXT order decides.
139
+ // `platform` is injectable so the Windows branch is unit-testable off Windows.
140
+ async function findOnPath(name, env = process.env, platform = process.platform) {
141
+ const win = platform === 'win32';
142
+ const sep = win ? ';' : path.delimiter;
143
+ const pathVar = win ? (env.PATH ?? env.Path ?? env.path) : env.PATH;
144
+ const exts = win
145
+ ? String(env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean)
146
+ : [''];
147
+ // path.join IS path.win32.join on a real Windows host; keeping it host-native also lets the
148
+ // injected-platform unit test stat real files off Windows.
149
+ const join = path.join;
150
+ for (const dir of String(pathVar ?? '').split(sep).filter(Boolean)) {
151
+ for (const ext of exts) {
152
+ const file = join(dir, `${name}${ext}`);
153
+ try { const st = await fs.promises.stat(file); if (st.isFile()) return { file, mtimeMs: st.mtimeMs }; } catch { /* next */ }
154
+ }
155
+ }
156
+ return null;
157
+ }
158
+
159
+ // How to execute an ABSOLUTE binary path. POSIX and win32 .exe/.com spawn directly (no shell,
160
+ // so a timeout kill reaches the real process). Only win32 .cmd/.bat needs cmd.exe; the path is
161
+ // quoted because shell:true concatenates the command into one string.
162
+ function spawnSpec(file, platform = process.platform) {
163
+ const shell = platform === 'win32' && /\.(cmd|bat)$/i.test(file);
164
+ return { cmd: shell && /\s/.test(file) ? `"${file}"` : file, shell };
165
+ }
166
+
167
+ function runVersion(file, platform) {
168
+ return new Promise((resolve) => {
169
+ let out = '';
170
+ let child;
171
+ const spec = spawnSpec(file, platform);
172
+ try {
173
+ child = spawn(spec.cmd, ['--version'], { stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000, killSignal: 'SIGKILL', ...(spec.shell ? { shell: true } : {}) });
174
+ } catch { resolve(null); return; }
175
+ child.stdout.on('data', (d) => { out += d; });
176
+ child.on('error', () => resolve(null));
177
+ child.on('close', () => resolve(parseVersion(out) ? out.trim() : null));
178
+ });
179
+ }
180
+
181
+ async function pathCliVersion(projectRoot, env = process.env, platform = process.platform) {
182
+ const found = await findOnPath('ukit', env, platform);
183
+ if (!found) return { version: null, file: null };
184
+ const cacheFile = path.join(projectRoot, PROBE_CACHE_REL);
185
+ const cache = await readJsonAsync(cacheFile);
186
+ if (cache?.file === found.file && cache.mtimeMs === found.mtimeMs && cache.version) return { version: cache.version, file: found.file };
187
+ const version = await runVersion(found.file, platform);
188
+ if (version) await writeJsonAsync(cacheFile, { file: found.file, mtimeMs: found.mtimeMs, version });
189
+ return { version, file: found.file };
190
+ }
191
+
192
+ // -> { cmd, pre, shell, source } | { reason }. Records the outcome for doctor. For the PATH
193
+ // source `cmd` is the ABSOLUTE path that was probed (the probed binary is the one executed).
194
+ export async function resolveEpisodeCli(projectRoot, env = process.env, platform = process.platform) {
195
+ const stateFile = path.join(projectRoot, CLI_STATE_REL);
196
+ const located = resolveCliLocator(projectRoot);
197
+ if (located) {
198
+ await writeJsonAsync(stateFile, { ok: true, source: 'cli.json', at: new Date().toISOString() });
199
+ return { cmd: located.node, pre: [located.bin], shell: false, source: 'cli.json' };
200
+ }
201
+ const runtime = await projectRuntimeVersion(projectRoot);
202
+ const probe = await pathCliVersion(projectRoot, env, platform);
203
+ let reason = null;
204
+ if (!probe.file) reason = 'cli.json missing/invalid and no ukit on PATH';
205
+ // Refuse only a CLI PROVABLY older than the runtime; an unreadable version is not proof.
206
+ else if (runtime && probe.version && compareVersions(probe.version, runtime) === -1) {
207
+ reason = `cli.json missing/invalid and PATH ukit ${probe.version} is older than the project runtime ${runtime}`;
208
+ }
209
+ if (reason) {
210
+ await writeJsonAsync(stateFile, { ok: false, reason: `${reason} - rerun ukit install`, at: new Date().toISOString() });
211
+ return { reason };
212
+ }
213
+ await writeJsonAsync(stateFile, { ok: true, source: 'path', at: new Date().toISOString() });
214
+ const spec = spawnSpec(probe.file, platform);
215
+ return { cmd: spec.cmd, pre: [], shell: spec.shell, source: 'path' };
216
+ }
217
+
218
+ // SessionStart (every source): throttled, detached, bounded. Writes the marker BEFORE
219
+ // spawning so a compact storm cannot launch twice. Returns true when a worker was launched.
220
+ export async function triggerEpisodeStart({ projectRoot, now = Date.now(), spawnImpl = spawn } = {}) {
221
+ try {
222
+ if (typeof projectRoot !== 'string' || !projectRoot) return false;
223
+ const root = path.resolve(projectRoot);
224
+ const config = await readJsonAsync(path.join(root, '.ukit', 'storage', 'config.json'));
225
+ if (config?.learning?.episodes?.autoWrite !== true) return false;
226
+ const marker = path.join(root, START_MARKER_REL);
227
+ const last = Number((await readJsonAsync(marker))?.at);
228
+ if (Number.isFinite(last) && last <= now && now - last < EPISODE_START_MIN_INTERVAL_MS) return false;
229
+ await writeJsonAsync(marker, { at: now });
230
+ const env = { ...process.env };
231
+ delete env.UKIT_HOOK_DEADLINE_MS;
232
+ const child = spawnImpl(process.execPath, [fileURLToPath(import.meta.url), '--episode-start', root], {
233
+ cwd: root, env, detached: true, stdio: 'ignore', windowsHide: true,
234
+ });
235
+ child.on?.('error', () => {});
236
+ child.unref?.();
237
+ return true;
238
+ } catch {
239
+ return false;
240
+ }
241
+ }
242
+
243
+ // Detached worker body: resolve the CLI, then `memory episode --start` (bounded).
244
+ // Records its outcome next to the marker (episode-start-result.json) so a failed spawn or
245
+ // dead worker is visible in `ukit doctor` instead of silently costing the throttle window.
246
+ export async function runEpisodeStartWorker(projectRoot) {
247
+ // The project vanished between the trigger and this worker: exit quietly, create nothing.
248
+ try { await fs.promises.stat(path.join(projectRoot, '.ukit', 'storage')); } catch { return { ok: false, reason: 'project gone' }; }
249
+ const resultFile = path.join(projectRoot, RESULT_REL);
250
+ const done = async (outcome) => { await writeJsonAsync(resultFile, { ...outcome, at: new Date().toISOString() }); return outcome; };
251
+ await writeJsonAsync(resultFile, { ok: null, state: 'started', at: new Date().toISOString() });
252
+ const cli = await resolveEpisodeCli(projectRoot);
253
+ if (cli.reason) return done({ ok: false, reason: cli.reason });
254
+ return new Promise((resolve) => {
255
+ let child;
256
+ let out = '';
257
+ try {
258
+ child = spawn(cli.cmd, [...cli.pre, 'memory', 'episode', '--start'], {
259
+ cwd: projectRoot, stdio: ['ignore', 'pipe', 'ignore'], timeout: 20000, killSignal: 'SIGKILL', ...(cli.shell ? { shell: true } : {}),
260
+ });
261
+ } catch (e) { resolve(done({ ok: false, reason: `spawn failed: ${e?.message ?? e}` })); return; }
262
+ child.stdout.on('data', (d) => { if (out.length < 4096) out += d; });
263
+ child.on('error', (e) => resolve(done({ ok: false, reason: `spawn error: ${e?.message ?? e}` })));
264
+ child.on('close', (code, signal) => {
265
+ const m = /recorded=(\d+) skipped=(\d+) failed=(\d+)/.exec(out);
266
+ if (code === 0 && m) resolve(done({ ok: true, recorded: Number(m[1]), skipped: Number(m[2]), failed: Number(m[3]) }));
267
+ else resolve(done({ ok: false, reason: signal ? `killed by ${signal} (timeout)` : `exit ${code}` }));
268
+ });
269
+ });
270
+ }
271
+
272
+ // No fs here: this runs at IMPORT time, which for the SessionStart/route-task paths is inside an
273
+ // armed hook deadline (no sync fs there, ever). Node already resolved the main entry's symlinks
274
+ // when it built import.meta.url, and every launcher (the detached worker, a direct
275
+ // `node self-improve-trigger.mjs`) passes that same resolved path, so a URL compare is exact.
86
276
  function isMainModule() {
87
277
  try {
88
- const self = fs.realpathSync(fileURLToPath(import.meta.url));
89
- const invoked = process.argv[1] ? fs.realpathSync(process.argv[1]) : '';
90
- return self === invoked;
278
+ return Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href;
279
+ } catch {
280
+ return false;
281
+ }
282
+ }
283
+
284
+ // A symlinked entry path (`.codex/ukit/...` -> real dir) keeps its link spelling in argv[1] while
285
+ // import.meta.url is the real path, so the URL compare misses. Only the worker launch (which
286
+ // carries --episode-start, never the hook's plain import) pays an ASYNC realpath to compare again.
287
+ async function isEpisodeStartEntry() {
288
+ if (process.argv[2] !== '--episode-start' || !process.argv[1]) return false;
289
+ try {
290
+ return import.meta.url === pathToFileURL(await fs.promises.realpath(process.argv[1])).href;
91
291
  } catch {
92
292
  return false;
93
293
  }
94
294
  }
95
295
 
296
+ function runEpisodeStartEntry() {
297
+ runEpisodeStartWorker(path.resolve(process.argv[3] || process.cwd())).catch(() => {}).finally(() => process.exit(0));
298
+ }
299
+
96
300
  if (isMainModule()) {
97
- triggerSelfImprove({ projectRoot: process.argv[2] || process.env.CLAUDE_PROJECT_DIR || process.cwd() });
301
+ if (process.argv[2] === '--episode-start') runEpisodeStartEntry();
302
+ else triggerSelfImprove({ projectRoot: process.argv[2] || process.env.CLAUDE_PROJECT_DIR || process.cwd() });
303
+ } else if (process.argv[2] === '--episode-start') {
304
+ isEpisodeStartEntry().then((yes) => { if (yes) runEpisodeStartEntry(); }).catch(() => {});
98
305
  }
@@ -85,7 +85,7 @@ export const HOOK_EVENT_MAP = {
85
85
  // owns the mandate-first lead (TASK-042 contract); the emit is advisory,
86
86
  // <250ms, and writes the session's `execution.started` record after the
87
87
  // context-producing scripts.
88
- session_start: ['project-important.sh', 'auto-prune-bash.sh', 'reset-compact-pressure.sh', 'handoff-resume.sh', 'observability-emit.mjs'],
88
+ session_start: ['project-important.sh', 'auto-prune-bash.sh', 'reset-compact-pressure.sh', 'handoff-resume.sh', 'observability-emit.mjs', 'session-episode-start.mjs'],
89
89
  // TASK-002 (cycle 45): omp emits `session_stop` (no `session_end`); the chain
90
90
  // runs only on RELEASED stops inside runSessionStop — never on blocked or
91
91
  // dedupe-skipped stops, since `ukit memory episode` dedupes on meta.ledgerKey
@@ -184,6 +184,7 @@ export const ADVISORY_SCRIPTS = new Set([
184
184
  // TASK-003 (FR-003): session-start emit step, advisory — a telemetry fault
185
185
  // can never block or delay session start.
186
186
  'observability-emit.mjs',
187
+ 'session-episode-start.mjs',
187
188
  ]);
188
189
 
189
190
  function classifyFailure(scriptName) {
@@ -343,7 +343,8 @@
343
343
  "maxInjectionTokens": 320,
344
344
  "archiveAfterDays": 30,
345
345
  "maxSessions": 20,
346
- "redactSecrets": true
346
+ "redactSecrets": true,
347
+ "writeGate": "strict"
347
348
  },
348
349
  "validation": {
349
350
  "enabled": true,
@@ -766,7 +767,8 @@
766
767
  "maxInjectionTokens": "S\u1ed1 token memory t\u1ed1i \u0111a \u0111\u01b0\u1ee3c inject v\u00e0o context (clamp th\u1ef1c t\u1ebf trong kho\u1ea3ng 160\u2013640).",
767
768
  "archiveAfterDays": "Sau bao nhi\u00eau ng\u00e0y memory c\u00f3 th\u1ec3 \u0111\u01b0\u1ee3c archive/compact.",
768
769
  "maxSessions": "S\u1ed1 session memory g\u1ea7n \u0111\u00e2y gi\u1eef active.",
769
- "redactSecrets": "C\u1ed1 tr\u00e1nh l\u01b0u secret v\u00e0o memory."
770
+ "redactSecrets": "C\u1ed1 tr\u00e1nh l\u01b0u secret v\u00e0o memory.",
771
+ "writeGate": "strict (default) or off. strict: every non-generated record write is checked for size, secrets, source evidence (an existing file, commit or episode id) and near-duplicates; scope user needs no file evidence."
770
772
  },
771
773
  "validation": {
772
774
  "enabled": "B\u1eadt ki\u1ec3m tra output nh\u1eb9.",
@@ -1,179 +0,0 @@
1
- // Deterministic completion-evidence evaluator (G5 / TASK-003).
2
- // Pure module: no I/O, no runtimeConfig reads, no adapter/context imports.
3
- // Maps requirements × checks × operationRefs (+ optional G4 vmStatus,
4
- // optional modelJudgment) to a frozen CompletionVerdict with precedence
5
- // FAILED > FIX_REQUIRED > MORE_EVIDENCE > PASS.
6
- //
7
- // The installed execution-ledger.mjs remains the completion authority —
8
- // its evaluateCompletion result shape may be fed here as a fixture, but it
9
- // is never imported and never edited. A model-review layer may only ask for
10
- // more evidence: `modelJudgment` is recorded on the verdict and can
11
- // *downgrade* a PASS to MORE_EVIDENCE, but never converts FAIL→PASS.
12
-
13
- import { isTerminal } from './contract.js';
14
-
15
- export const COMPLETION_VERDICTS = Object.freeze([
16
- 'PASS',
17
- 'MORE_EVIDENCE',
18
- 'FIX_REQUIRED',
19
- 'FAILED',
20
- ]);
21
-
22
- // vm terminal states that mean the run itself failed — not merely unproven.
23
- const VM_FAILED_STATES = new Set(['failed', 'cancelled']);
24
- // vm states that mean evidence is unusable until recovery completes.
25
- const VM_FIX_STATES = new Set(['recovery_required']);
26
-
27
- const PASS_STATUSES = new Set(['passed', 'pass', 'ok', 'success']);
28
- const FAIL_STATUSES = new Set(['failed', 'fail', 'error']);
29
- const WARN_STATUSES = new Set(['warning', 'warn', 'skipped', 'indeterminate']);
30
-
31
- function normStatus(status) {
32
- const s = typeof status === 'string' ? status.toLowerCase() : '';
33
- if (PASS_STATUSES.has(s)) return 'passed';
34
- if (FAIL_STATUSES.has(s)) return 'failed';
35
- if (WARN_STATUSES.has(s)) return 'warning';
36
- return 'unproven';
37
- }
38
-
39
- // A check proves a requirement when ids match: check.requirementId → req.id,
40
- // or req.checkId → check.checkId. Either direction is accepted so callers may
41
- // key evidence from whichever side they own.
42
- function checkFor(req, checks) {
43
- return checks.find(
44
- (c) =>
45
- c != null
46
- && typeof c === 'object'
47
- && ((typeof c.requirementId === 'string' && c.requirementId === req.id)
48
- || (typeof req.checkId === 'string' && c.checkId === req.checkId)),
49
- );
50
- }
51
-
52
- // Evidence is stale when it was produced against a different patch/head than
53
- // the operation now carries. Stale ≠ missing: the work must be re-verified,
54
- // which is rework (FIX_REQUIRED), not just more evidence.
55
- function isStale(check, operationRefs) {
56
- if (!check || !operationRefs || typeof operationRefs !== 'object') return false;
57
- if (operationRefs.patchId != null && check.patchId != null
58
- && check.patchId !== operationRefs.patchId) return true;
59
- if (operationRefs.head != null && check.head != null
60
- && check.head !== operationRefs.head) return true;
61
- return false;
62
- }
63
-
64
- export function evaluateCompletionEvidence({
65
- requirements,
66
- checks,
67
- operationRefs,
68
- vmStatus,
69
- modelJudgment,
70
- now,
71
- } = {}) {
72
- const nowMs = typeof now === 'number' ? now : Date.now();
73
- const reqs = Array.isArray(requirements) ? requirements : [];
74
- const checkList = Array.isArray(checks) ? checks : [];
75
- const refs = operationRefs != null && typeof operationRefs === 'object'
76
- ? operationRefs
77
- : null;
78
-
79
- const satisfied = [];
80
- const missing = [];
81
- const unprovenRequirements = [];
82
- const failedChecks = [];
83
- const staleEvidence = [];
84
- const warnings = [];
85
-
86
- for (const req of reqs) {
87
- const reqId = req != null && req.id != null ? String(req.id) : 'unknown';
88
- const check = checkFor(req, checkList);
89
-
90
- if (!check) {
91
- missing.push(reqId);
92
- unprovenRequirements.push(reqId);
93
- continue;
94
- }
95
-
96
- const status = normStatus(check.status);
97
- const stale = isStale(check, refs);
98
-
99
- if (stale) {
100
- staleEvidence.push(Object.freeze({
101
- checkId: check.checkId != null ? String(check.checkId) : reqId,
102
- evidenceRef: check.evidenceRef != null ? String(check.evidenceRef) : null,
103
- patchId: check.patchId != null ? check.patchId : null,
104
- }));
105
- unprovenRequirements.push(reqId);
106
- continue;
107
- }
108
-
109
- if (status === 'failed') {
110
- failedChecks.push(Object.freeze({
111
- checkId: check.checkId != null ? String(check.checkId) : reqId,
112
- evidenceRef: check.evidenceRef != null ? String(check.evidenceRef) : null,
113
- }));
114
- continue;
115
- }
116
-
117
- if (status === 'warning') {
118
- warnings.push(reqId);
119
- unprovenRequirements.push(reqId);
120
- continue;
121
- }
122
-
123
- if (status === 'passed') {
124
- satisfied.push(reqId);
125
- continue;
126
- }
127
-
128
- unprovenRequirements.push(reqId);
129
- }
130
-
131
- // vm state never permits PASS: terminal failure → FAILED, recovery →
132
- // rework, any other non-terminal state → the operation is still in flight
133
- // so evidence cannot yet prove completion.
134
- const vmFailed = typeof vmStatus === 'string' && VM_FAILED_STATES.has(vmStatus);
135
- const vmRecovery = typeof vmStatus === 'string' && VM_FIX_STATES.has(vmStatus);
136
- const vmInFlight = typeof vmStatus === 'string'
137
- && !vmFailed && !vmRecovery && !isTerminal(vmStatus) && vmStatus !== 'completed';
138
-
139
- // Non-zero exit status = failed verification run → rework required.
140
- const exitFailed = refs != null
141
- && typeof refs.exitStatus === 'number'
142
- && refs.exitStatus !== 0;
143
-
144
- let verdict = 'PASS';
145
- if (missing.length > 0 || unprovenRequirements.length > 0 || vmInFlight) {
146
- verdict = 'MORE_EVIDENCE';
147
- }
148
- if (staleEvidence.length > 0 || exitFailed || vmRecovery) {
149
- verdict = 'FIX_REQUIRED';
150
- }
151
- if (failedChecks.length > 0 || vmFailed) {
152
- verdict = 'FAILED';
153
- }
154
-
155
- // modelJudgment may only request more evidence, never promote (enforced
156
- // below: a judgment can downgrade PASS → MORE_EVIDENCE, nothing else). When
157
- // model-backed, the judgment MUST originate from the decision plane
158
- // (unic-decision, a bounded verdict question) — never a general LLM call.
159
- const judgment = modelJudgment != null
160
- ? (typeof modelJudgment === 'string' ? modelJudgment : String(modelJudgment))
161
- : null;
162
- if (verdict === 'PASS' && judgment != null && judgment !== 'pass') {
163
- verdict = 'MORE_EVIDENCE';
164
- }
165
-
166
- return Object.freeze({
167
- verdict,
168
- satisfied: Object.freeze(satisfied),
169
- missing: Object.freeze(missing),
170
- failedChecks: Object.freeze(failedChecks),
171
- unprovenRequirements: Object.freeze(unprovenRequirements),
172
- staleEvidence: Object.freeze(staleEvidence),
173
- warnings: Object.freeze(warnings),
174
- patchId: refs != null && refs.patchId != null ? refs.patchId : undefined,
175
- vmStatus: typeof vmStatus === 'string' ? vmStatus : undefined,
176
- modelJudgment: judgment != null ? judgment : undefined,
177
- evaluatedAt: nowMs,
178
- });
179
- }