@ngockhoale/ukit 3.5.2 → 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 (75) hide show
  1. package/CHANGELOG.md +38 -90
  2. package/README.md +1 -0
  3. package/manifests/documentation.yaml +12 -1
  4. package/manifests/platform.full.yaml +12 -0
  5. package/package.json +34 -1
  6. package/src/cli/commands/doctor.js +55 -2
  7. package/src/cli/commands/indexTools.js +10 -4
  8. package/src/cli/commands/memory.js +107 -8
  9. package/src/core/memory/episodes.js +106 -7
  10. package/src/core/memory/memoryCheck.js +241 -0
  11. package/src/core/memory/memoryCheckRun.js +27 -0
  12. package/src/core/memory/memoryHit.js +2 -0
  13. package/src/core/memory/mutateMemory.js +46 -1
  14. package/src/core/memory/observations.js +192 -0
  15. package/src/core/memory/projectIdentity.js +9 -2
  16. package/src/core/memory/recallEngine.js +204 -9
  17. package/src/core/memory/records.js +23 -0
  18. package/src/core/memory/registryPrune.js +230 -0
  19. package/src/core/memory/retrieval.js +12 -3
  20. package/src/core/memory/writeGate.js +137 -0
  21. package/src/core/runtimeConfig.js +12 -2
  22. package/src/index/buildIndex.js +26 -0
  23. package/src/index/paths.js +3 -1
  24. package/src/index/queryIndex.js +372 -26
  25. package/src/index/resolveContext.js +1 -1
  26. package/template_project/.claude/hooks/edit-hint.mjs +64 -17
  27. package/template_project/.claude/hooks/session-episode-start.mjs +35 -0
  28. package/template_project/.claude/hooks/session-episode.sh +9 -4
  29. package/template_project/.claude/settings.json +2 -2
  30. package/template_project/.claude/ukit/index/edit-graph.mjs +141 -11
  31. package/template_project/.claude/ukit/index/lib/index-core.mjs +400 -27
  32. package/template_project/.claude/ukit/index/query-index.mjs +14 -3
  33. package/template_project/.claude/ukit/index/resolve-context.mjs +1 -1
  34. package/template_project/.claude/ukit/index/route-task.mjs +8 -2
  35. package/template_project/.claude/ukit/runtime/memory-check.mjs +241 -0
  36. package/template_project/.claude/ukit/runtime/memory-lanes.mjs +44 -22
  37. package/template_project/.claude/ukit/runtime/memory-recall.mjs +204 -9
  38. package/template_project/.claude/ukit/runtime/memory-validity.mjs +259 -0
  39. package/template_project/.claude/ukit/runtime/reinject-context.mjs +4 -2
  40. package/template_project/.claude/ukit/runtime/self-improve-trigger.mjs +212 -5
  41. package/template_project/.omp/hooks/pre/ukit-bridge.js +2 -1
  42. package/template_project/ukit/storage/config.json +4 -2
  43. package/src/core/agentRuntime/completionGate.js +0 -179
  44. package/src/core/agentRuntime/context.js +0 -571
  45. package/src/core/agentRuntime/qualityComparison.js +0 -112
  46. package/src/core/agentRuntime/resourcePolicy.js +0 -78
  47. package/src/core/agentRuntime/runtimeSupport.js +0 -255
  48. package/src/core/codeintel/manifest.js +0 -176
  49. package/src/core/experiments/deliberation.js +0 -327
  50. package/src/core/experiments/dynamicWorkflow.js +0 -507
  51. package/src/core/handoffDocValidator.js +0 -154
  52. package/src/core/memory/deltaOverlays.js +0 -493
  53. package/src/core/memory/learningCandidates.js +0 -347
  54. package/src/core/observability/emit/sessionBoot.js +0 -407
  55. package/src/core/observability/evaluation/experimentPlan.js +0 -95
  56. package/src/core/observability/evaluation/perturbation.js +0 -273
  57. package/src/core/observability/evaluation/replay.js +0 -149
  58. package/src/core/observability/evaluation/scorecard.js +0 -465
  59. package/src/core/observability/schema/compatibility.js +0 -180
  60. package/src/core/observability/support/renderer.js +0 -130
  61. package/src/core/reviewPanelAggregate.js +0 -204
  62. package/src/core/taskBudgetValidator.js +0 -251
  63. package/src/core/taskProgressGuard.js +0 -227
  64. package/src/decision/reviewVerdict.js +0 -339
  65. package/src/decision/runtimeFilter.js +0 -150
  66. package/src/decision/runtimeScheduler.js +0 -239
  67. package/src/diagnostics/classifyHang.js +0 -246
  68. package/src/diagnostics/ompStallSnapshot.js +0 -199
  69. package/src/index/contextPack.js +0 -285
  70. package/src/index/impactContext.js +0 -360
  71. package/src/index/reviewPolicy.js +0 -368
  72. package/src/index/sensitivePath.js +0 -21
  73. package/src/render/instructionRenderer.js +0 -290
  74. package/src/skill/auditSkill.js +0 -140
  75. package/template_project/instructions/overlays/repo.md +0 -9
@@ -1,150 +0,0 @@
1
- // src/decision/runtimeFilter.js — pure (no I/O, no config, no gateway).
2
- // C65 G3-FR01 — deterministic pre-filter for G1/G2 SemanticEvents.
3
- // Known signals are decided locally and must NEVER produce a model call
4
- // downstream; only genuinely ambiguous items return action 'model_decision'
5
- // with a registered `runtime.*.v1` decisionKey.
6
- //
7
- // Interface (SPEC §4, frozen):
8
- // classifyRuntimeEvent(event, policy?) -> {
9
- // action: 'local_transition'|'local_observation'|'local_action'
10
- // |'model_decision'|'escalate'|'ignore',
11
- // priority: 'critical'|'decision'|'progress',
12
- // coalesceKey?: string, // only for coalescible progress
13
- // decisionKey?: string, // only when action='model_decision'
14
- // reason: string }
15
- //
16
- // Consumes: SemanticEvent { eventType, safePayload, operationId, seq, ... }
17
- // from src/core/agentRuntime/contract.js; liveness class vocabulary from
18
- // src/core/agentRuntime/liveness.js.
19
- // Consumed by: runtimeScheduler.submit (TASK-002), runtimeDecide (TASK-003).
20
-
21
- import { TERMINAL_STATES } from '../core/agentRuntime/contract.js';
22
- import { LIVENESS_CLASSES } from '../core/agentRuntime/liveness.js';
23
-
24
- const TERMINAL_SET = new Set(TERMINAL_STATES);
25
- const LIVENESS_SET = new Set(LIVENESS_CLASSES);
26
-
27
- // Observation classes that represent redundant progress — safe to coalesce
28
- // by key, latest wins (SPEC §5).
29
- const COALESCIBLE_CLASSES = new Set(['live_progressing', 'silent_live']);
30
-
31
- // Observation classes where a stall decision may be needed: with an explicit
32
- // spec/policy stallAction the action is deterministic; without one the item
33
- // is ambiguous and goes to the model via runtime.stall_action.v1.
34
- const STALL_CLASSES = new Set(['stalled', 'timeout']);
35
-
36
- // Ambiguous items that need a semantic decision: which decision key each
37
- // maps to. Keys must be registered in the decision registry (TASK-003).
38
- const DECISION_KEYS = Object.freeze({
39
- stall: 'runtime.stall_action.v1',
40
- ambiguous: 'runtime.wake_needed.v1',
41
- });
42
-
43
- // Signals that a human/authorization boundary must resolve — never dropped,
44
- // never coalesced, never auto-acted-on.
45
- const ESCALATION_EVENT_TYPE = /permission|input[_-]?required|authoriz/i;
46
- const ESCALATION_CLASS = /permission|input[_-]?required|authoriz|approval/i;
47
-
48
- function result(action, priority, reason, extra) {
49
- return { action, priority, reason, ...extra };
50
- }
51
-
52
- const ignore = (reason) => result('ignore', 'progress', reason);
53
-
54
- /**
55
- * Classify one runtime SemanticEvent into a local action, a model-decision
56
- * candidate, an escalation, or ignore. Pure: no I/O, no config import.
57
- *
58
- * @param {object} event G1 SemanticEvent envelope
59
- * @param {object} [policy] { stallAction?: string } — explicit spec policy
60
- * @returns {{action:string,priority:string,coalesceKey?:string,
61
- * decisionKey?:string,reason:string}}
62
- */
63
- export function classifyRuntimeEvent(event, policy) {
64
- if (event === null || typeof event !== 'object' || Array.isArray(event)) {
65
- return ignore('malformed_event');
66
- }
67
- const eventType = event.eventType;
68
- if (typeof eventType !== 'string' || eventType.length === 0) {
69
- return ignore('malformed_event');
70
- }
71
-
72
- // Permission / user-input / authorization signals escalate deterministically,
73
- // regardless of the channel they arrive on.
74
- if (ESCALATION_EVENT_TYPE.test(eventType)) {
75
- return result('escalate', 'critical', `escalation_signal:${eventType}`);
76
- }
77
-
78
- const safePayload = event.safePayload;
79
- const operationId =
80
- typeof event.operationId === 'string' && event.operationId.length > 0
81
- ? event.operationId
82
- : 'unknown';
83
-
84
- switch (eventType) {
85
- case 'operation.transition': {
86
- if (typeof safePayload !== 'object' || safePayload === null) {
87
- return result('model_decision', 'decision', 'unparseable_payload', {
88
- decisionKey: DECISION_KEYS.ambiguous,
89
- });
90
- }
91
- const to = safePayload.to;
92
- if (TERMINAL_SET.has(to)) {
93
- return result('local_transition', 'critical', `terminal_transition:${to}`);
94
- }
95
- // Non-terminal transition (queued→running, recovery_required, …):
96
- // known signal, decided locally; never reaches the model.
97
- return result('local_transition', 'progress', `transition:${to ?? 'unknown'}`);
98
- }
99
-
100
- case 'operation.observation': {
101
- if (typeof safePayload !== 'object' || safePayload === null) {
102
- return result('model_decision', 'decision', 'unparseable_payload', {
103
- decisionKey: DECISION_KEYS.ambiguous,
104
- });
105
- }
106
- const cls = safePayload.class;
107
-
108
- if (typeof cls === 'string' && ESCALATION_CLASS.test(cls)) {
109
- return result('escalate', 'critical', `escalation_signal:${cls}`);
110
- }
111
-
112
- if (COALESCIBLE_CLASSES.has(cls)) {
113
- return result('local_observation', 'progress', `observation:${cls}`, {
114
- coalesceKey: `obs:${operationId}:${cls}`,
115
- });
116
- }
117
-
118
- if (STALL_CLASSES.has(cls)) {
119
- const stallAction =
120
- policy && typeof policy === 'object' && typeof policy.stallAction === 'string'
121
- ? policy.stallAction
122
- : null;
123
- if (stallAction) {
124
- return result('local_action', 'critical', `policy_stall_action:${stallAction}:${cls}`);
125
- }
126
- return result('model_decision', 'decision', `ambiguous_stall:${cls}`, {
127
- decisionKey: DECISION_KEYS.stall,
128
- });
129
- }
130
-
131
- if (LIVENESS_SET.has(cls)) {
132
- // 'exited' — the only remaining liveness class. Terminal-adjacent
133
- // sample signal: critical so it is never dropped/starved by progress.
134
- return result('local_observation', 'critical', `observation:${cls}`);
135
- }
136
-
137
- // Unrecognized observation class — ambiguous.
138
- return result('model_decision', 'decision', `unknown_observation_class:${cls ?? 'none'}`, {
139
- decisionKey: DECISION_KEYS.ambiguous,
140
- });
141
- }
142
-
143
- default:
144
- // Valid envelope shape but a vocabulary the filter does not own —
145
- // ambiguous, candidate for a semantic decision.
146
- return result('model_decision', 'decision', `unknown_event_type:${eventType}`, {
147
- decisionKey: DECISION_KEYS.ambiguous,
148
- });
149
- }
150
- }
@@ -1,239 +0,0 @@
1
- /**
2
- * runtimeScheduler.js (G3-FR02)
3
- *
4
- * Bounded 3-tier queue for classified runtime items (SPEC §4):
5
- * - critical : terminal/failure/cancel/permission — emitted directly via
6
- * emitFn at flush; never dropped, never coalesced, never
7
- * counted against maxQueue, always drained first.
8
- * - decision : ambiguous items awaiting decideFn.
9
- * - progress : redundant progress — coalesced by coalesceKey while an
10
- * entry is pending (latest wins); eligible for drain after
11
- * coalesceWindowMs from first arrival.
12
- *
13
- * Serial drain (maxInFlight = 1 — the gateway is a single local model).
14
- * decideFn failures convert to typed Fallback objects emitted via emitFn;
15
- * a decideFn that never resolves yields { code:'timeout' }.
16
- *
17
- * Pure module: no I/O, no config. All dependencies injected via opts.
18
- */
19
-
20
- import { resolveConfigStage } from '../core/runtimeConfig.js';
21
- import { selectResourcePolicy } from '../core/agentRuntime/resourcePolicy.js';
22
-
23
- // G6 (DR-09): `decisionRuntime.resourcePolicy.stage` — absent/malformed →
24
- // 'off'; 'shadow' consults selectResourcePolicy on submit and records a
25
- // bounded receipt WITHOUT changing enqueue behavior. A policy throw or
26
- // malformed decision deterministically falls back to the prior path.
27
- const RESOURCE_FLAG = 'decisionRuntime.resourcePolicy.stage';
28
- const RESOURCE_RECEIPT_CAP = 128;
29
-
30
- // priority → eventClass for the resource consult. Scheduler-internal,
31
- // fail-open: unknown priorities consult as 'progress' (the only coalescible
32
- // class); malformed input still resolves emit downstream.
33
- const EVENT_CLASS_BY_PRIORITY = Object.freeze({
34
- critical: 'terminal',
35
- progress: 'progress',
36
- decision: 'progress',
37
- });
38
-
39
- const DEFAULT_COALESCE_WINDOW_MS = 250;
40
- const DEFAULT_MAX_QUEUE = 256;
41
- const DEFAULT_DECISION_TIMEOUT_MS = 5000;
42
-
43
- function fallback(code, item) {
44
- return { decidedBy: 'fallback', code, action: item?.action ?? 'ignore' };
45
- }
46
-
47
- export function createScheduler(opts = {}) {
48
- const decideFn = opts.decideFn ?? (async () => fallback('unavailable'));
49
- const emitFn = opts.emitFn ?? (() => {});
50
- const now = opts.now ?? (() => Date.now());
51
- const coalesceWindowMs = opts.coalesceWindowMs ?? DEFAULT_COALESCE_WINDOW_MS;
52
- const maxQueue = opts.maxQueue ?? DEFAULT_MAX_QUEUE;
53
- const decisionTimeoutMs = opts.decisionTimeoutMs ?? DEFAULT_DECISION_TIMEOUT_MS;
54
- // maxInFlight accepted for forward-compat; drain is serial regardless.
55
- void (opts.maxInFlight ?? 1);
56
-
57
- const resourceStage = () => resolveConfigStage(opts.config ?? null, RESOURCE_FLAG);
58
- const resourcePolicyFn = typeof opts.resourcePolicyFn === 'function'
59
- ? opts.resourcePolicyFn
60
- : selectResourcePolicy;
61
- const resourcesFn = typeof opts.resourcesFn === 'function'
62
- ? opts.resourcesFn
63
- : () => ({});
64
- const resourceReceipts = [];
65
-
66
- function recordResourceReceipt(entry) {
67
- if (resourceReceipts.length >= RESOURCE_RECEIPT_CAP) resourceReceipts.shift();
68
- resourceReceipts.push(Object.freeze(entry));
69
- }
70
-
71
- /**
72
- * Shadow consult: evaluate the resource policy for this submit and record
73
- * a bounded receipt. Never changes enqueue behavior; never throws.
74
- */
75
- function consultResourcePolicy(item) {
76
- let decision;
77
- let error;
78
- try {
79
- const resources = resourcesFn() ?? {};
80
- decision = resourcePolicyFn({
81
- cpuPressure: typeof resources.cpuPressure === 'string' ? resources.cpuPressure : 'normal',
82
- eventClass: EVENT_CLASS_BY_PRIORITY[item?.priority] ?? 'progress',
83
- queueDepth: boundedSize(),
84
- });
85
- } catch (err) {
86
- error = String(err?.message ?? err);
87
- }
88
- const valid = decision !== null && typeof decision === 'object'
89
- && (decision.action === 'emit' || decision.action === 'coalesce' || decision.action === 'defer');
90
- recordResourceReceipt({
91
- priority: item?.priority ?? null,
92
- stage: resourceStage(),
93
- decision: valid ? { action: decision.action, reason: decision.reason } : null,
94
- error: error ?? null,
95
- });
96
- }
97
-
98
- const critical = [];
99
- const decision = [];
100
- const progressPending = new Map(); // coalesceKey -> { item, firstArrival }
101
- const timers = new Set();
102
- let closed = false;
103
- let closedWith = 0;
104
- const counters = { submitted: 0, coalesced: 0, dropped: 0, deferred: 0, emitted: 0 };
105
-
106
- function boundedSize() {
107
- return decision.length + progressPending.size;
108
- }
109
-
110
- function submit(item) {
111
- if (closed || !item || typeof item !== 'object') {
112
- return { accepted: false, code: closed ? 'closed' : 'invalid' };
113
- }
114
- // G6 resource consult — shadow evaluates+records a bounded receipt;
115
- // enqueue below is always the prior path (throw/malformed → prior
116
- // behavior deterministically).
117
- if (resourceStage() !== 'off') {
118
- consultResourcePolicy(item);
119
- }
120
- if (item.priority === 'critical') {
121
- critical.push(item);
122
- counters.submitted++;
123
- return { accepted: true };
124
- }
125
- if (item.priority === 'progress' && item.coalesceKey) {
126
- const existing = progressPending.get(item.coalesceKey);
127
- if (existing) {
128
- existing.item = item; // latest wins
129
- counters.coalesced++;
130
- counters.submitted++;
131
- return { accepted: true };
132
- }
133
- if (boundedSize() >= maxQueue) {
134
- counters.dropped++;
135
- return { accepted: false, code: 'queue_full' };
136
- }
137
- progressPending.set(item.coalesceKey, { item, firstArrival: now() });
138
- counters.submitted++;
139
- return { accepted: true };
140
- }
141
- // decision tier (or progress without a key — cannot coalesce)
142
- if (boundedSize() >= maxQueue) {
143
- counters.dropped++;
144
- return { accepted: false, code: 'queue_full' };
145
- }
146
- decision.push(item);
147
- counters.submitted++;
148
- return { accepted: true };
149
- }
150
-
151
- function scheduleTimeout(ms) {
152
- let handle;
153
- const p = new Promise((resolve) => {
154
- handle = setTimeout(() => {
155
- timers.delete(handle);
156
- resolve('timeout');
157
- }, ms);
158
- if (typeof handle.unref === 'function') handle.unref();
159
- });
160
- timers.add(handle);
161
- return { promise: p, cancel: () => { clearTimeout(handle); timers.delete(handle); } };
162
- }
163
-
164
- async function decide(item) {
165
- const t = scheduleTimeout(decisionTimeoutMs);
166
- try {
167
- const result = await Promise.race([Promise.resolve().then(() => decideFn(item)), t.promise]);
168
- t.cancel();
169
- if (result === 'timeout') return fallback('timeout', item);
170
- if (result && result.decidedBy === 'fallback') return result;
171
- if (result === undefined || result === null) return fallback('invalid', item);
172
- return result;
173
- } catch {
174
- t.cancel();
175
- return fallback('invalid', item);
176
- }
177
- }
178
-
179
- async function flush() {
180
- const report = { processed: 0, emitted: 0, coalesced: 0, dropped: 0, deferred: 0 };
181
- if (closed) return report;
182
-
183
- while (critical.length) {
184
- const item = critical.shift();
185
- emitFn(item);
186
- counters.emitted++;
187
- report.processed++;
188
- report.emitted++;
189
- }
190
- while (decision.length) {
191
- const item = decision.shift();
192
- emitFn(await decide(item));
193
- counters.emitted++;
194
- report.processed++;
195
- report.emitted++;
196
- }
197
- const t = now();
198
- for (const [key, entry] of progressPending) {
199
- if (t - entry.firstArrival < coalesceWindowMs) {
200
- counters.deferred++;
201
- report.deferred++;
202
- continue;
203
- }
204
- progressPending.delete(key);
205
- emitFn(await decide(entry.item));
206
- counters.emitted++;
207
- report.processed++;
208
- report.emitted++;
209
- }
210
- return report;
211
- }
212
-
213
- function stats() {
214
- return {
215
- ...counters,
216
- pending: critical.length + decision.length + progressPending.size,
217
- closedWith,
218
- closed,
219
- };
220
- }
221
-
222
- async function close() {
223
- if (closed) return;
224
- closed = true;
225
- closedWith = critical.length + decision.length + progressPending.size;
226
- critical.length = 0;
227
- decision.length = 0;
228
- progressPending.clear();
229
- for (const h of timers) clearTimeout(h);
230
- timers.clear();
231
- }
232
-
233
- /** Bounded frozen receipts of shadow-stage resource-policy consults (G6). */
234
- function resourcePolicyReceipts() {
235
- return [...resourceReceipts];
236
- }
237
-
238
- return { submit, flush, stats, close, resourcePolicyReceipts };
239
- }
@@ -1,246 +0,0 @@
1
- // classifyHang.js — evidence-only hang classifier for the C19 liveness wave (TASK-032).
2
- //
3
- // What this is for: C19 removed a family of unbounded paths, and the remaining failure
4
- // mode is telling ONE stall class apart from another. A prompt freeze used to be
5
- // indistinguishable from an indexing freeze or a gateway stall, so operators had no
6
- // evidence-based next step. This module turns an evidence bundle into exactly one
7
- // declared lane, or `unknown` when the evidence cannot prove any of them.
8
- //
9
- // Contracts (asserted by tests/liveness/classifyHang.test.js):
10
- // * PURE and CLOCK-FREE. Every rule is a function of the bundle only, so identical
11
- // evidence always produces byte-identical output. No Date.now(), no randomness, no
12
- // I/O — the caller supplies both the measurement and the clock.
13
- // * NEVER GUESSES. A lane is only named when the evidence PROVES it:
14
- // - `deadline` with zero survivors is a clean reap, not a process-tree leak;
15
- // - survivors beside `failureKind: 'signal'` are NOT a leak: `signal` is documented
16
- // by the runner as a signal IT DID NOT SEND, so there is no escalation to blame
17
- // and the bundle is `unknown` (the runner's own `deadline` verdict is the only
18
- // escalation proof);
19
- // - a non-zero hook exit that finished inside its budget is a verdict, not a hang;
20
- // - a non-typed index error is not a discovery deadline.
21
- // Everything else is `unknown` with a concrete next check.
22
- // * The UPSTREAM lane is never a hook. Stream idle with no hook active classifies
23
- // `gateway-stream-idle`; the presence of hook evidence removes that lane entirely, so
24
- // a gateway stall can no longer be reported as UKit's fault (or the reverse).
25
- // * Exactly four fields, always: `{class, confidence, evidenceIds, recommendedNextCheck}`.
26
- // `evidenceIds` names the fields the decision rests on, so a reviewer can re-derive it.
27
-
28
- /**
29
- * The six declared stall lanes. One bundle resolves to at most one of these.
30
- * Ordered by decision precedence (see LANE_PRECEDENCE) — the first lane whose evidence
31
- * is present AND conclusive owns the classification.
32
- */
33
- export const HANG_CLASSES = Object.freeze([
34
- 'process-tree-leak',
35
- 'hook-overrun',
36
- 'index-deadline',
37
- 'lock-contention',
38
- 'context-capacity',
39
- 'gateway-stream-idle',
40
- ]);
41
-
42
- /** The explicit "could not prove a lane" result. Never a member of HANG_CLASSES. */
43
- export const UNKNOWN_CLASS = 'unknown';
44
-
45
- /**
46
- * Evidence kinds a bundle may carry. Exported so callers and diagnostics can enumerate
47
- * what the classifier understands instead of guessing at field names.
48
- */
49
- export const EVIDENCE_KINDS = Object.freeze([
50
- 'hook-telemetry',
51
- 'hook-active',
52
- 'process-result',
53
- 'index-error',
54
- 'lock-outcome',
55
- 'context-capacity',
56
- 'stream-idle',
57
- ]);
58
-
59
- // Hook-runner outcomes that PROVE the runner ended the child (TASK-018 taxonomy). These
60
- // are kill verdicts, so they name a lane; `ok` / `exit-code` are verdicts about the hook's
61
- // own decision and prove nothing about liveness.
62
- const KILL_OUTCOMES = new Set(['timeout', 'output-overflow', 'budget-exhausted']);
63
-
64
- // A leak only exists AFTER the runner's OWN escalation attempt, and only if something is
65
- // still alive. `failureKind: 'deadline'` is the runner's kill verdict — the deadline timer
66
- // armed the TERM → KILL sequence, so survivors beside it really are an escapee (H03).
67
- //
68
- // `signal` is explicitly NOT escalation evidence: the runner documents it as "the child
69
- // died from a signal this runner did not send" (hook-process.mjs), which is an unprompted
70
- // EXTERNAL kill. Survivors beside an external signal may be unrelated processes, and naming
71
- // a lane off it would fabricate a TERM → KILL diagnosis the evidence cannot support. Such a
72
- // bundle is `unknown`, never `process-tree-leak`.
73
- const RUNNER_ESCALATION_KINDS = new Set(['deadline']);
74
-
75
- const UNKNOWN_CHECK = 'Collect hook telemetry, process-exit evidence, or an index/lock/context measurement for this stall — none of the current evidence proves a lane.';
76
-
77
- const NEXT_CHECK = Object.freeze({
78
- 'process-tree-leak': 'Re-run the failing command with the process-tree runner and list the surviving PIDs: a process group survived its TERM→KILL escalation (check for a child that ignores or detaches from SIGTERM).',
79
- 'hook-overrun': 'Inspect the cited hook telemetry row: the hook was killed at its deadline or overflowed its output cap. Measure that hook alone and reduce its work below its budget.',
80
- 'index-deadline': 'Re-run discovery with a bounded deadline and inspect the recorded phase: git enumeration or the filesystem fallback consumed the whole budget.',
81
- 'lock-contention': 'Inspect the lock holder state for the named target: the acquisition budget expired or was aborted before the critical section ran (fail-closed, no mutation happened).',
82
- 'context-capacity': 'Re-check the negotiated context capacity against the estimate: the session reached its advisory cap, so compaction must run before more context is added.',
83
- 'gateway-stream-idle': 'Watch the stream idle window: no hook was active while the stream went silent, so treat this as an upstream/gateway stall and verify CLAUDE_STREAM_IDLE_TIMEOUT_MS and the non-streaming fallback.',
84
- });
85
-
86
- function isObject(value) {
87
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
88
- }
89
-
90
- function isPositiveNumber(value) {
91
- return typeof value === 'number' && Number.isFinite(value) && value > 0;
92
- }
93
-
94
- function resultFor(cls, confidence, evidenceIds, recommendedNextCheck) {
95
- return { class: cls, confidence, evidenceIds, recommendedNextCheck };
96
- }
97
-
98
- function unknown(evidenceIds = []) {
99
- return resultFor(UNKNOWN_CLASS, 'none', evidenceIds, UNKNOWN_CHECK);
100
- }
101
-
102
- // ─── per-lane evidence evaluators ────────────────────────────────────────────
103
- // Each returns { evidenceIds, confidence } when the evidence PROVES the lane, else null.
104
-
105
- function detectProcessTreeLeak(bundle) {
106
- const processResult = bundle.processResult;
107
- if (!isObject(processResult)) return null;
108
- const survivors = processResult.survivors;
109
- // `survivors` must be an explicit, non-empty array: a missing field is unknown
110
- // evidence (the caller never probed), and an empty array is a clean reap.
111
- if (!Array.isArray(survivors) || survivors.length === 0) return null;
112
- // Survivors alone proves nothing — the runner must have escalated. `signal` is an
113
- // external kill, so it stays `unknown` rather than claiming a leak.
114
- if (!RUNNER_ESCALATION_KINDS.has(processResult.failureKind)) return null;
115
- return { evidenceIds: ['process-result'], confidence: 'high' };
116
- }
117
-
118
- function detectHookOverrun(bundle) {
119
- const rows = bundle.hookTelemetry;
120
- if (!Array.isArray(rows)) return null;
121
- for (let i = 0; i < rows.length; i += 1) {
122
- const row = rows[i];
123
- if (isObject(row) && KILL_OUTCOMES.has(row.outcome)) {
124
- // Cite only the failing row — the row index is the evidence locator.
125
- return { evidenceIds: [`hook-telemetry[${i}]`], confidence: 'high' };
126
- }
127
- }
128
- return null;
129
- }
130
-
131
- function detectIndexDeadline(bundle) {
132
- const indexError = bundle.indexError;
133
- if (!isObject(indexError)) return null;
134
- // Only the typed liveness failure is proof; a message alone could be anything.
135
- const typed = indexError.name === 'IndexDiscoveryTimeoutError'
136
- || indexError.code === 'INDEX_DISCOVERY_TIMEOUT';
137
- if (!typed) return null;
138
- return { evidenceIds: ['index-error'], confidence: 'high' };
139
- }
140
-
141
- function detectLockContention(bundle) {
142
- const lockOutcome = bundle.lockOutcome;
143
- if (!isObject(lockOutcome) || lockOutcome.ok !== false) return null;
144
- // TASK-028's typed envelope: the callback never ran, so no mutation was lost.
145
- if (lockOutcome.reason !== 'busy' && lockOutcome.reason !== 'aborted') return null;
146
- return { evidenceIds: ['lock-outcome'], confidence: 'high' };
147
- }
148
-
149
- function detectContextCapacity(bundle) {
150
- const context = bundle.context;
151
- if (!isObject(context)) return null;
152
- const capTokens = context.capTokens;
153
- const estimatedTokens = context.estimatedTokens;
154
- if (!isPositiveNumber(capTokens) || !isPositiveNumber(estimatedTokens)) return null;
155
- if (estimatedTokens < capTokens) return null;
156
- return { evidenceIds: ['context-capacity'], confidence: 'high' };
157
- }
158
-
159
- function detectGatewayStreamIdle(bundle) {
160
- const stream = bundle.stream;
161
- if (!isObject(stream)) return null;
162
- const idleMs = stream.idleMs;
163
- const idleTimeoutMs = stream.idleTimeoutMs;
164
- // Both numbers are required: without the negotiated timeout there is nothing to
165
- // compare against, and an idle duration alone proves no stall.
166
- if (!isPositiveNumber(idleMs) || !isPositiveNumber(idleTimeoutMs)) return null;
167
- if (idleMs < idleTimeoutMs) return null;
168
- // A hook was active while the stream was silent → the silence may be UKit's, so the
169
- // upstream lane is removed entirely. Never blame the gateway over hook evidence.
170
- // `null`/`undefined` both mean "no hook was active" — only a real value withholds it.
171
- if (bundle.hookActive !== null && bundle.hookActive !== undefined) return null;
172
- return { evidenceIds: ['stream-idle'], confidence: 'high' };
173
- }
174
-
175
- // Precedence: the most specific, evidence-backed lane wins. The upstream lane is LAST —
176
- // it is the only lane whose proof is the ABSENCE of other evidence, so it may only be
177
- // reached once every hook/index/lock/context claim had its chance.
178
- const LANE_PRECEDENCE = Object.freeze([
179
- ['process-tree-leak', detectProcessTreeLeak],
180
- ['hook-overrun', detectHookOverrun],
181
- ['index-deadline', detectIndexDeadline],
182
- ['lock-contention', detectLockContention],
183
- ['context-capacity', detectContextCapacity],
184
- ['gateway-stream-idle', detectGatewayStreamIdle],
185
- ]);
186
-
187
- // Evidence that was considered but is NOT sufficient to name a lane. Reported on the
188
- // `unknown` result so a caller sees what was looked at, never just "nothing".
189
- function inconclusiveEvidenceIds(bundle) {
190
- const ids = [];
191
- if (Array.isArray(bundle.hookTelemetry) && bundle.hookTelemetry.length > 0) {
192
- ids.push('hook-telemetry');
193
- }
194
- if (isObject(bundle.hookActive)) ids.push('hook-active');
195
- if (isObject(bundle.stream)) ids.push('stream-idle');
196
- if (isObject(bundle.processResult)) ids.push('process-result');
197
- if (isObject(bundle.indexError)) ids.push('index-error');
198
- if (isObject(bundle.lockOutcome)) ids.push('lock-outcome');
199
- if (isObject(bundle.context)) ids.push('context-capacity');
200
- return ids;
201
- }
202
-
203
- /**
204
- * Classify ONE stall from an evidence bundle.
205
- *
206
- * @param {object} [bundle] evidence collected by a scenario or a live diagnostic:
207
- * `hookTelemetry` — redacted telemetry rows (TASK-019 schema; `outcome` is the
208
- * runner's taxonomy, `hook` names the emitter).
209
- * `hookActive` — `{hook, activeMs}` when a hook held the hot path. Presence alone
210
- * removes the upstream lane.
211
- * `processResult` — `{failureKind, signal, code, elapsedMs, survivors}` from the
212
- * process-tree runner. `survivors` is the escalation probe.
213
- * `indexError` — the thrown error (or its shape) from index discovery.
214
- * `lockOutcome` — the typed `{ok:false, reason:'busy'|'aborted', waitedMs}` envelope.
215
- * `context` — `{capTokens, estimatedTokens, ...}` from capacity negotiation.
216
- * `stream` — `{idleMs, idleTimeoutMs, ...}` from stream timing.
217
- * @returns {{ class: string, confidence: 'high'|'none', evidenceIds: string[],
218
- * recommendedNextCheck: string }} exactly four fields; `class` is either a
219
- * member of HANG_CLASSES or UNKNOWN_CLASS.
220
- */
221
- export function classifyHang(bundle = {}) {
222
- if (!isObject(bundle)) return unknown();
223
-
224
- for (const [lane, detect] of LANE_PRECEDENCE) {
225
- const evidence = detect(bundle);
226
- if (evidence) return resultFor(lane, evidence.confidence, evidence.evidenceIds, NEXT_CHECK[lane]);
227
- }
228
-
229
- return unknown(inconclusiveEvidenceIds(bundle));
230
- }
231
-
232
- /**
233
- * C19 finding → lane map. Every finding this cycle addressed has a lane whose evidence a
234
- * scenario in `tests/liveness/hangScenarios.test.js` produces, so no finding is left
235
- * without a classifier answer. Exposed as data (not prose) so the liveness suite can fail
236
- * when coverage regresses.
237
- */
238
- export const C19_LANE_MAP = Object.freeze([
239
- Object.freeze({ findings: Object.freeze(['H01', 'H02', 'H05', 'H08', 'H21']), lane: 'hook-overrun' }),
240
- Object.freeze({ findings: Object.freeze(['H03']), lane: 'process-tree-leak' }),
241
- Object.freeze({ findings: Object.freeze(['H09', 'H10', 'H11', 'H12', 'H13', 'H14', 'H15']), lane: 'index-deadline' }),
242
- Object.freeze({ findings: Object.freeze(['H16', 'H17', 'H18', 'H19', 'H20']), lane: 'lock-contention' }),
243
- Object.freeze({ findings: Object.freeze(['H04', 'H22']), lane: 'context-capacity' }),
244
- Object.freeze({ findings: Object.freeze(['H23', 'H24']), lane: 'hook-overrun' }),
245
- Object.freeze({ findings: Object.freeze(['H25']), lane: 'gateway-stream-idle' }),
246
- ]);