@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,507 +0,0 @@
1
- /**
2
- * dynamicWorkflow.js (TASK-012 / M06.2)
3
- *
4
- * Bounded dynamic-workflow experiment — compose a workflow only from a frozen
5
- * known-block catalog, validate the graph before execution, and run a
6
- * dependency-graph program with per-task route/completion and finite breakers
7
- * (`maxAttemptsPerFailure`, global `noProgressCap`, genuine-blocker
8
- * classification). Behind `experiments.dynamicWorkflow.enabled` (default
9
- * false). Not wired into route-task; evaluated by fixtures (SPEC §5 FR-022;
10
- * §10 "no-progress loop").
11
- *
12
- * Disabled posture: `composeWorkflow` returns `{status:'disabled'}` and
13
- * `runProgram` returns `{status:'disabled'}` BEFORE any runner call — zero
14
- * calls, zero prompt content.
15
- *
16
- * Program state reuses the C10 CompactResumable record *shape* (derived from
17
- * CONTRACTS.md §C10 — schemaVersion/taskId/route/budget/workflow/decisions/
18
- * escalationHistory/unresolvedFailures/nextAction, bounded arrays). No new
19
- * state DB, no persistence, no auto-promotion: a mid-run failure degrades to
20
- * the caller-supplied stable `fallback` workflow and the composition is never
21
- * promoted (`promoted:false` always).
22
- *
23
- * Runner contract: `runner({task, attempt, strategy, state}) → result` where
24
- * `result.status === 'ok'` (or the task's own `completion(result)` predicate)
25
- * completes the task; any other result is a failure whose signature is
26
- * `result.failure ?? result.status`. An identical repeated failure signature
27
- * is not progress and is capped by `maxAttemptsPerFailure`; consecutive
28
- * non-completing attempts are capped globally by `noProgressCap`. The runner
29
- * is also the fault-injection hook — tests inject failures through it.
30
- */
31
-
32
- const DEFAULT_MAX_ATTEMPTS_PER_FAILURE = 2;
33
- const DEFAULT_NO_PROGRESS_CAP = 3;
34
-
35
- // C10 bounds (CONTRACTS.md §C10): hypotheses ≤8, decisions ≤12,
36
- // evidenceRefs ≤24, escalationHistory ≤8.
37
- const MAX_DECISIONS = 12;
38
- const MAX_ESCALATIONS = 8;
39
-
40
- /**
41
- * Frozen known-block catalog — the only blocks a composition may use.
42
- * `permissions` are required grants; `owns` are exclusively-owned resources
43
- * (two blocks owning the same resource is an ownership conflict); `cost` is
44
- * charged against `constraints.budgetLimit`.
45
- */
46
- export const KNOWN_BLOCKS = Object.freeze({
47
- 'scan-context': Object.freeze({ permissions: ['read'], owns: [], cost: 1 }),
48
- plan: Object.freeze({ permissions: ['read'], owns: [], cost: 1 }),
49
- edit: Object.freeze({ permissions: ['read', 'write'], owns: ['worktree'], cost: 2 }),
50
- 'apply-patch': Object.freeze({ permissions: ['read', 'write'], owns: ['worktree'], cost: 2 }),
51
- verify: Object.freeze({ permissions: ['read', 'execute'], owns: [], cost: 1 }),
52
- report: Object.freeze({ permissions: ['read'], owns: [], cost: 1 }),
53
- });
54
-
55
- function dynamicWorkflowEnabled(config) {
56
- return config?.experiments?.dynamicWorkflow?.enabled === true;
57
- }
58
-
59
- function breakersOf(config) {
60
- const cfg = config?.experiments?.dynamicWorkflow ?? {};
61
- return {
62
- maxAttemptsPerFailure:
63
- typeof cfg.maxAttemptsPerFailure === 'number' && cfg.maxAttemptsPerFailure > 0
64
- ? cfg.maxAttemptsPerFailure
65
- : DEFAULT_MAX_ATTEMPTS_PER_FAILURE,
66
- noProgressCap:
67
- typeof cfg.noProgressCap === 'number' && cfg.noProgressCap > 0
68
- ? cfg.noProgressCap
69
- : DEFAULT_NO_PROGRESS_CAP,
70
- };
71
- }
72
-
73
- function isPlainObject(value) {
74
- return value !== null && typeof value === 'object' && !Array.isArray(value);
75
- }
76
-
77
- function boundedPush(list, item, cap) {
78
- if (list.length < cap) {
79
- list.push(item);
80
- }
81
- }
82
-
83
- /**
84
- * Compose a workflow graph from the frozen known-block catalog.
85
- * Unknown block ids pass through unresolved so `validateComposition` can
86
- * reject them with a named reason — a composed graph is only executable
87
- * after `validateComposition` returns `{valid:true}`.
88
- *
89
- * @param {{blocks: Array<string|{id:string, needs?:string[]}>,
90
- * constraints?: {allowedPermissions?: string[], budgetLimit?: number},
91
- * config?: object}} input
92
- * @returns {{version:1, nodes: Array, edges: Array, constraints: object} |
93
- * {status:'disabled', reasons:string[]}}
94
- */
95
- export function composeWorkflow({ blocks = [], constraints = {}, config = null } = {}) {
96
- if (!dynamicWorkflowEnabled(config)) {
97
- return { status: 'disabled', reasons: ['experiment-disabled'] };
98
- }
99
- const list = Array.isArray(blocks) ? blocks : [];
100
- const nodes = list.map((entry) => {
101
- const id = typeof entry === 'string' ? entry : entry?.id;
102
- const requestedNeeds = typeof entry === 'string' ? [] : entry?.needs;
103
- const known = KNOWN_BLOCKS[id] ?? null;
104
- return {
105
- id,
106
- needs: Array.isArray(requestedNeeds) ? [...requestedNeeds] : [],
107
- known,
108
- permissions: known ? [...known.permissions] : [],
109
- owns: known ? [...known.owns] : [],
110
- cost: known ? known.cost : 0,
111
- };
112
- });
113
- const edges = [];
114
- for (const node of nodes) {
115
- for (const dep of node.needs) {
116
- edges.push({ from: dep, to: node.id });
117
- }
118
- }
119
- return {
120
- version: 1,
121
- nodes,
122
- edges,
123
- constraints: isPlainObject(constraints) ? { ...constraints } : {},
124
- };
125
- }
126
-
127
- /**
128
- * Validate a composed graph before execution. Rejects malformed graphs,
129
- * duplicate/unknown blocks, missing dependency targets, cycles, permission
130
- * violations (block requires a grant absent from
131
- * `constraints.allowedPermissions`), ownership conflicts (two blocks owning
132
- * the same resource), and budget overruns (Σ block cost >
133
- * `constraints.budgetLimit`).
134
- *
135
- * @param {object} graph — output of `composeWorkflow`
136
- * @returns {{valid: boolean, errors: string[]}}
137
- */
138
- export function validateComposition(graph) {
139
- const errors = [];
140
- if (!isPlainObject(graph) || !Array.isArray(graph.nodes)) {
141
- return { valid: false, errors: ['malformed-graph'] };
142
- }
143
- const nodes = graph.nodes;
144
- const constraints = isPlainObject(graph.constraints) ? graph.constraints : {};
145
-
146
- const seen = new Set();
147
- const ids = new Set();
148
- for (const node of nodes) {
149
- if (typeof node?.id !== 'string' || !node.id) {
150
- errors.push('malformed-node');
151
- continue;
152
- }
153
- if (seen.has(node.id)) {
154
- errors.push(`duplicate-block:${node.id}`);
155
- continue;
156
- }
157
- seen.add(node.id);
158
- ids.add(node.id);
159
- if (!KNOWN_BLOCKS[node.id]) {
160
- errors.push(`unknown-block:${node.id}`);
161
- }
162
- }
163
-
164
- const needs = new Map();
165
- for (const node of nodes) {
166
- if (typeof node?.id !== 'string' || !node.id) continue;
167
- const list = Array.isArray(node.needs) ? node.needs : [];
168
- needs.set(node.id, list);
169
- for (const dep of list) {
170
- if (!ids.has(dep)) {
171
- errors.push(`missing-dependency:${dep}`);
172
- }
173
- }
174
- }
175
-
176
- // Cycle detection — iterative DFS, three-color.
177
- const color = new Map(); // 0=unvisited implicit, 1=in-stack, 2=done
178
- for (const start of ids) {
179
- if (color.get(start) === 2) continue;
180
- const stack = [[start, 0]];
181
- color.set(start, 1);
182
- while (stack.length > 0) {
183
- const frame = stack[stack.length - 1];
184
- const [id, idx] = frame;
185
- const deps = (needs.get(id) ?? []).filter((d) => ids.has(d));
186
- if (idx >= deps.length) {
187
- color.set(id, 2);
188
- stack.pop();
189
- continue;
190
- }
191
- frame[1] = idx + 1;
192
- const dep = deps[idx];
193
- const depColor = color.get(dep) ?? 0;
194
- if (depColor === 1) {
195
- errors.push(`cycle:${dep}->${id}`);
196
- } else if (depColor === 0) {
197
- color.set(dep, 1);
198
- stack.push([dep, 0]);
199
- }
200
- }
201
- }
202
-
203
- // Permission violations.
204
- if (constraints.allowedPermissions !== undefined) {
205
- const allowed = new Set(
206
- Array.isArray(constraints.allowedPermissions) ? constraints.allowedPermissions : [],
207
- );
208
- for (const node of nodes) {
209
- if (typeof node?.id !== 'string' || !KNOWN_BLOCKS[node.id]) continue;
210
- const required = KNOWN_BLOCKS[node.id].permissions;
211
- const missing = required.filter((p) => !allowed.has(p));
212
- if (missing.length > 0) {
213
- errors.push(`permission-denied:${node.id}:${missing.join(',')}`);
214
- }
215
- }
216
- }
217
-
218
- // Ownership conflicts — two blocks claiming the same exclusive resource.
219
- const owners = new Map();
220
- for (const node of nodes) {
221
- if (typeof node?.id !== 'string' || !KNOWN_BLOCKS[node.id]) continue;
222
- for (const resource of KNOWN_BLOCKS[node.id].owns) {
223
- if (owners.has(resource)) {
224
- errors.push(`ownership-conflict:${resource}`);
225
- } else {
226
- owners.set(resource, node.id);
227
- }
228
- }
229
- }
230
-
231
- // Budget overrun.
232
- if (typeof constraints.budgetLimit === 'number') {
233
- const total = nodes.reduce(
234
- (sum, node) => sum + (KNOWN_BLOCKS[node?.id]?.cost ?? 0),
235
- 0,
236
- );
237
- if (total > constraints.budgetLimit) {
238
- errors.push('budget-exceeded');
239
- }
240
- }
241
-
242
- return { valid: errors.length === 0, errors };
243
- }
244
-
245
- function defaultCompletion(result) {
246
- return result?.status === 'ok' || result?.ok === true;
247
- }
248
-
249
- function failureSignature(result) {
250
- if (typeof result?.failure === 'string' && result.failure) {
251
- return result.failure;
252
- }
253
- return String(result?.status ?? 'unknown');
254
- }
255
-
256
- function newProgramState({ programId, tasks }) {
257
- // C10 CompactResumableRun shape (CONTRACTS.md §C10) — in-memory only,
258
- // bounded and redacted; no new state DB.
259
- return {
260
- schemaVersion: 1,
261
- taskId: programId,
262
- taskBoundary: 'experiment-program',
263
- route: { routeVersion: 1, mode: 'dynamic-workflow', rigor: 'bounded', contractVersion: 1 },
264
- budget: { policyVersion: 1, consumed: 0, remaining: tasks.length },
265
- workflow: {
266
- workflowId: programId,
267
- workflowVersion: 1,
268
- phase: 'execute',
269
- completedBlocks: [],
270
- },
271
- invariants: [],
272
- hypotheses: [],
273
- decisions: [],
274
- evidenceRefs: [],
275
- escalationHistory: [],
276
- unresolvedFailures: [],
277
- nextAction: null,
278
- sourceSnapshot: null,
279
- };
280
- }
281
-
282
- /**
283
- * Run a dependency-graph program of bounded tasks. Each task carries its own
284
- * `route` and `completion(result)` predicate; tasks execute in dependency
285
- * order and dependents of a blocked task are skipped. Finite breakers:
286
- * `maxAttemptsPerFailure` caps retries of an identical failure signature
287
- * (identical retry ≠ progress), `noProgressCap` caps consecutive
288
- * non-completing attempts program-wide. A tripped breaker is a genuine
289
- * blocker — the run degrades to the caller-supplied stable `fallback`
290
- * workflow when present, else returns `status:'blocked'`. Never infinite,
291
- * never auto-promoted.
292
- *
293
- * @param {{tasks: Array<{id:string, needs?:string[], route?:object,
294
- * completion?:Function, strategies?:string[]}>, runner: Function,
295
- * fallback?: Function, programId?: string, config?: object}} input
296
- * @returns {object} `{status:'ok'|'blocked'|'degraded'|'disabled'|'invalid',
297
- * order, completed, skipped, blockers, attempts, state, promoted:false}`
298
- */
299
- export function runProgram({
300
- tasks = [],
301
- runner = null,
302
- fallback = null,
303
- programId = 'dynamic-workflow-program',
304
- config = null,
305
- } = {}) {
306
- if (!dynamicWorkflowEnabled(config)) {
307
- return { status: 'disabled', reasons: ['experiment-disabled'], promoted: false };
308
- }
309
- if (typeof runner !== 'function') {
310
- throw new TypeError('runProgram runner must be a function.');
311
- }
312
- const list = Array.isArray(tasks) ? tasks : [];
313
- const { maxAttemptsPerFailure, noProgressCap } = breakersOf(config);
314
-
315
- // Structural validation — same named reasons as validateComposition.
316
- const errors = [];
317
- const ids = new Set();
318
- const needs = new Map();
319
- for (const task of list) {
320
- if (typeof task?.id !== 'string' || !task.id) {
321
- errors.push('malformed-task');
322
- continue;
323
- }
324
- if (ids.has(task.id)) {
325
- errors.push(`duplicate-task:${task.id}`);
326
- continue;
327
- }
328
- ids.add(task.id);
329
- }
330
- for (const task of list) {
331
- if (typeof task?.id !== 'string' || !task.id) continue;
332
- const deps = Array.isArray(task.needs) ? task.needs : [];
333
- needs.set(task.id, deps);
334
- for (const dep of deps) {
335
- if (!ids.has(dep)) {
336
- errors.push(`missing-dependency:${dep}`);
337
- }
338
- }
339
- }
340
- // Topological order (Kahn) — deterministic input-order tie-break; leftover
341
- // in-degree means a cycle.
342
- const indegree = new Map([...ids].map((id) => [id, 0]));
343
- for (const task of list) {
344
- if (typeof task?.id !== 'string' || !task.id || !needs.has(task.id)) continue;
345
- for (const dep of needs.get(task.id)) {
346
- if (ids.has(dep)) {
347
- indegree.set(task.id, indegree.get(task.id) + 1);
348
- }
349
- }
350
- }
351
- const order = [];
352
- const ready = list
353
- .filter((t) => typeof t?.id === 'string' && indegree.get(t.id) === 0)
354
- .map((t) => t.id);
355
- const dependents = new Map([...ids].map((id) => [id, []]));
356
- for (const task of list) {
357
- if (typeof task?.id !== 'string' || !task.id || !needs.has(task.id)) continue;
358
- for (const dep of needs.get(task.id)) {
359
- if (ids.has(dep)) {
360
- dependents.get(dep).push(task.id);
361
- }
362
- }
363
- }
364
- while (ready.length > 0) {
365
- const id = ready.shift();
366
- order.push(id);
367
- for (const next of dependents.get(id)) {
368
- indegree.set(next, indegree.get(next) - 1);
369
- if (indegree.get(next) === 0) {
370
- ready.push(next);
371
- }
372
- }
373
- }
374
- if (order.length < ids.size) {
375
- const stuck = [...ids].filter((id) => !order.includes(id));
376
- errors.push(`cycle:${stuck.join(',')}`);
377
- }
378
- if (errors.length > 0) {
379
- return { status: 'invalid', errors, promoted: false };
380
- }
381
-
382
- const state = newProgramState({ programId, tasks: list });
383
- const taskById = new Map(list.map((t) => [t.id, t]));
384
- const completed = [];
385
- const completedSet = new Set();
386
- const skipped = [];
387
- const blockers = [];
388
- const attempts = {};
389
- let noProgress = 0;
390
- let programBlocked = false;
391
-
392
- for (const id of order) {
393
- if (programBlocked) {
394
- skipped.push(id);
395
- continue;
396
- }
397
- const task = taskById.get(id);
398
- const deps = needs.get(id) ?? [];
399
- if (deps.some((dep) => !completedSet.has(dep))) {
400
- skipped.push(id);
401
- continue;
402
- }
403
-
404
- const strategies = Array.isArray(task.strategies) ? task.strategies : [];
405
- const completion = typeof task.completion === 'function' ? task.completion : defaultCompletion;
406
- const signatureCounts = new Map();
407
- let done = false;
408
- let blockedReason = null;
409
- let blockedSignature = null;
410
- let attempt = 0;
411
-
412
- while (!done && blockedReason === null) {
413
- attempt += 1;
414
- const strategy = strategies.length > 0 ? strategies[attempt - 1] : undefined;
415
- // A throwing runner degrades to a failure result — it must never escape
416
- // runProgram as an exception (degrade contract, SPEC §FR-008).
417
- let result;
418
- try {
419
- result = runner({ task, attempt, strategy, state }) ?? {};
420
- } catch (err) {
421
- result = { status: 'runner-threw', failure: String(err?.message ?? err) };
422
- }
423
- state.budget.consumed += 1;
424
- if (completion(result)) {
425
- done = true;
426
- break;
427
- }
428
- noProgress += 1;
429
- const signature = failureSignature(result);
430
- const count = (signatureCounts.get(signature) ?? 0) + 1;
431
- signatureCounts.set(signature, count);
432
- if (count >= maxAttemptsPerFailure) {
433
- blockedReason = 'repeated-identical-failure';
434
- blockedSignature = signature;
435
- } else if (noProgress >= noProgressCap) {
436
- blockedReason = 'no-progress-cap';
437
- blockedSignature = signature;
438
- } else if (strategies.length > 0 && attempt >= strategies.length) {
439
- blockedReason = 'strategies-exhausted';
440
- blockedSignature = signature;
441
- }
442
- }
443
-
444
- attempts[id] = attempt;
445
- if (done) {
446
- completed.push(id);
447
- completedSet.add(id);
448
- state.workflow.completedBlocks.push(id);
449
- boundedPush(
450
- state.decisions,
451
- { taskId: id, route: task.route ?? null, attempts: attempt },
452
- MAX_DECISIONS,
453
- );
454
- continue;
455
- }
456
-
457
- // Genuine blocker — finite, classified, recorded.
458
- programBlocked = true;
459
- const blocker = { taskId: id, reason: blockedReason, signature: blockedSignature, attempts: attempt };
460
- blockers.push(blocker);
461
- boundedPush(state.unresolvedFailures, blocker, MAX_ESCALATIONS);
462
- boundedPush(
463
- state.escalationHistory,
464
- { taskId: id, reason: blockedReason, at: 'program' },
465
- MAX_ESCALATIONS,
466
- );
467
- state.nextAction = `blocked:${id}:${blockedReason}`;
468
- }
469
-
470
- // `remaining` counts unfinished tasks (blocked/skipped stay unfinished) —
471
- // decrementing per attempt would corrupt it on retries.
472
- state.budget.remaining = Math.max(0, ids.size - completedSet.size);
473
-
474
- const result = {
475
- order,
476
- completed,
477
- skipped,
478
- blockers,
479
- attempts,
480
- state,
481
- promoted: false, // no auto-promotion — ever
482
- };
483
-
484
- if (blockers.length === 0) {
485
- state.workflow.phase = 'complete';
486
- state.nextAction = null;
487
- return { status: 'ok', ...result };
488
- }
489
-
490
- state.workflow.phase = 'blocked';
491
- if (typeof fallback === 'function') {
492
- // A throwing fallback is still a degrade contract — record the throw as a
493
- // blocker and report 'blocked', never let the exception escape (FR-008).
494
- let fallbackResult = null;
495
- try {
496
- fallbackResult = fallback({ state, blockers }) ?? {};
497
- } catch {
498
- blockers.push({ taskId: null, reason: 'fallback-threw' });
499
- return { status: 'blocked', ...result, blockers };
500
- }
501
- if (fallbackResult.status === 'ok') {
502
- return { status: 'degraded', fallback: fallbackResult, ...result };
503
- }
504
- blockers.push({ taskId: null, reason: 'fallback-failed' });
505
- }
506
- return { status: 'blocked', ...result, blockers };
507
- }
@@ -1,154 +0,0 @@
1
- // handoffDocValidator.js — TASK-004 / Cycle C50 (mechanic #10, FR-007)
2
- //
3
- // Mechanical structure gate for handoff docs. Unlike taskBudgetValidator (advisory,
4
- // exit 0), this validator is a REAL gate: the CLI twin exits 1 on any violation.
5
- // Keep that difference explicit — do not "fix" the exit code.
6
- //
7
- // Exports:
8
- // validateHandoffDoc(markdown, kind) → { ok: boolean, failures: string[] }
9
- // kind ∈ 'plan' | 'task' | 'executor-report'
10
- //
11
- // Rules (SPEC §5 FR-007):
12
- // plan — `## §1`..`## §6` headings present and in ascending order
13
- // (extra trailing sections allowed), `## Planner Report`
14
- // section containing `PLANNER_MODEL:`.
15
- // task — required `## ` sections: Goal, Target Files, Test Cases,
16
- // Test Files, Verification Commands, Acceptance Criteria,
17
- // Dependencies, Interfaces; plus a `- Status:` field.
18
- // When the doc also carries `## Executor Report`, the report
19
- // header fields are validated too.
20
- // executor-report — required fields: EXECUTOR_TOOL, EXECUTOR_MODEL,
21
- // EXECUTOR_SUBAGENT, RED_OUTPUT.
22
- //
23
- // Parsing is deliberately markdown-light and dependency-free so the logic can be
24
- // duplicated byte-for-byte into the shipped CLI twin
25
- // (template_project/.claude/ukit/index/handoff-doc-validator.mjs) without
26
- // dragging `src/` into user installs — same pattern as taskBudgetValidator (C12).
27
-
28
- const PLAN_SECTIONS = ['§1', '§2', '§3', '§4', '§5', '§6'];
29
-
30
- const TASK_SECTIONS = [
31
- 'Goal',
32
- 'Target Files',
33
- 'Test Cases',
34
- 'Test Files',
35
- 'Verification Commands',
36
- 'Acceptance Criteria',
37
- 'Dependencies',
38
- 'Interfaces',
39
- ];
40
-
41
- const REPORT_FIELDS = ['EXECUTOR_TOOL', 'EXECUTOR_MODEL', 'EXECUTOR_SUBAGENT', 'RED_OUTPUT'];
42
-
43
- // Section helpers. Any line starting with `## ` opens a section; the body runs
44
- // until the next `## ` line or EOF. Returns [{ name, body, pos }] in file order.
45
- function splitSections(markdown) {
46
- const sections = [];
47
- const lines = String(markdown).split('\n');
48
- let current = null;
49
- lines.forEach((line, idx) => {
50
- const m = line.match(/^##\s+(.+?)\s*$/);
51
- if (m) {
52
- current = { name: m[1], body: '', pos: idx };
53
- sections.push(current);
54
- } else if (current) {
55
- current.body += line + '\n';
56
- }
57
- });
58
- return sections;
59
- }
60
-
61
- // Positions of `## §<n>` headings, keyed by the literal token ('§1'..'§6').
62
- // A heading matches when its name starts with the token (`## §1 Intent`).
63
- function planSectionPositions(sections) {
64
- const positions = new Map();
65
- for (const s of sections) {
66
- for (const token of PLAN_SECTIONS) {
67
- // `## §10`/`## §12` must not satisfy `§1` — the token only matches when it
68
- // is the whole heading or is followed by a non-digit boundary (space, colon…).
69
- if (!positions.has(token) && new RegExp(`^${token}(?!\\d)`).test(s.name)) positions.set(token, s.pos);
70
- }
71
- }
72
- return positions;
73
- }
74
-
75
- function hasSection(sections, name) {
76
- return sections.some((s) => s.name === name || s.name.startsWith(`${name} `) || s.name.startsWith(`${name}(`));
77
- }
78
-
79
- function getSection(sections, name) {
80
- return sections.find((s) => s.name === name || s.name.startsWith(`${name} `) || s.name.startsWith(`${name}(`));
81
- }
82
-
83
- function validatePlan(markdown) {
84
- const failures = [];
85
- const sections = splitSections(markdown);
86
- const positions = planSectionPositions(sections);
87
-
88
- for (const token of PLAN_SECTIONS) {
89
- if (!positions.has(token)) failures.push(`missing required section heading "## ${token}"`);
90
- }
91
-
92
- // Order check over the sections that exist: each must appear after the
93
- // highest position seen so far.
94
- let maxPos = -1;
95
- for (const token of PLAN_SECTIONS) {
96
- const pos = positions.get(token);
97
- if (pos === undefined) continue;
98
- if (pos < maxPos) {
99
- failures.push(`section order violation: "## ${token}" appears after a later section`);
100
- } else {
101
- maxPos = pos;
102
- }
103
- }
104
-
105
- const report = getSection(sections, 'Planner Report');
106
- if (!report) {
107
- failures.push('missing required section "## Planner Report"');
108
- } else if (!/^PLANNER_MODEL\s*:/m.test(report.body)) {
109
- failures.push('missing required field "PLANNER_MODEL:" inside "## Planner Report"');
110
- }
111
-
112
- return failures;
113
- }
114
-
115
- function validateExecutorReportFields(markdown, prefix) {
116
- const failures = [];
117
- for (const field of REPORT_FIELDS) {
118
- if (!new RegExp(`^${field}\\s*:`, 'm').test(markdown)) {
119
- failures.push(`${prefix}missing required field "${field}:"`);
120
- }
121
- }
122
- return failures;
123
- }
124
-
125
- function validateTask(markdown) {
126
- const failures = [];
127
- const sections = splitSections(markdown);
128
-
129
- for (const name of TASK_SECTIONS) {
130
- if (!hasSection(sections, name)) failures.push(`missing required section "## ${name}"`);
131
- }
132
- if (!/^\s*-?\s*Status\s*:/m.test(markdown)) {
133
- failures.push('missing required field "Status:"');
134
- }
135
-
136
- // A task file that already carries an Executor Report must satisfy the
137
- // report header contract too (FR-007).
138
- const report = getSection(sections, 'Executor Report');
139
- if (report) {
140
- failures.push(...validateExecutorReportFields(report.body, 'executor-report: '));
141
- }
142
-
143
- return failures;
144
- }
145
-
146
- export function validateHandoffDoc(markdown, kind) {
147
- const text = String(markdown ?? '');
148
- let failures;
149
- if (kind === 'plan') failures = validatePlan(text);
150
- else if (kind === 'task') failures = validateTask(text);
151
- else if (kind === 'executor-report') failures = validateExecutorReportFields(text, '');
152
- else failures = [`unknown kind "${kind}" (expected plan|task|executor-report)`];
153
- return { ok: failures.length === 0, failures };
154
- }