@ngockhoale/ukit 3.5.15 → 3.5.18

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 (77) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/manifests/platform.full.yaml +48 -0
  3. package/package.json +2 -1
  4. package/scripts/release/heavy-first.mjs +12 -0
  5. package/scripts/release/release-steps.mjs +7 -4
  6. package/scripts/release/run-core-batch.mjs +50 -0
  7. package/src/cli/commands/mission.js +102 -0
  8. package/src/cli/commands/rescue.js +83 -0
  9. package/src/cli/index.js +14 -0
  10. package/src/core/compact/contextBudget.js +62 -41
  11. package/src/core/compact/threshold.js +14 -32
  12. package/src/core/observability/schema/registry.js +91 -0
  13. package/src/core/runtimeConfig.js +53 -2
  14. package/src/diagnostics/routeOutcomes.js +5 -1
  15. package/src/diagnostics/skillAccuracy.js +5 -2
  16. package/src/render/buildVariables.js +2 -5
  17. package/template_project/.claude/commands/ukit/handoff-implement.md +3 -3
  18. package/template_project/.claude/commands/ukit/handoff-review.md +3 -3
  19. package/template_project/.claude/hooks/context-hardcap-gate.sh +47 -20
  20. package/template_project/.claude/hooks/context-window-guard.sh +82 -27
  21. package/template_project/.claude/hooks/delegation-gate.mjs +1 -1
  22. package/template_project/.claude/hooks/handoff-resume.sh +11 -2
  23. package/template_project/.claude/hooks/mission-capture.mjs +37 -0
  24. package/template_project/.claude/hooks/post-compact-observe.mjs +34 -0
  25. package/template_project/.claude/hooks/shell-watch.mjs +34 -0
  26. package/template_project/.claude/hooks/skill-router.sh +13 -0
  27. package/template_project/.claude/hooks/stop-failure-rescue.mjs +109 -0
  28. package/template_project/.claude/settings.json +36 -4
  29. package/template_project/.claude/skills/backend-api/SKILL.md +1 -1
  30. package/template_project/.claude/skills/delivery/SKILL.md +1 -1
  31. package/template_project/.claude/skills/docs-manager/SKILL.md +1 -1
  32. package/template_project/.claude/skills/duraone/SKILL.md +2 -1
  33. package/template_project/.claude/skills/file-organizer/SKILL.md +1 -1
  34. package/template_project/.claude/skills/frontend/SKILL.md +1 -1
  35. package/template_project/.claude/skills/frontend-vue/SKILL.md +1 -1
  36. package/template_project/.claude/skills/pdf-processing/SKILL.md +1 -1
  37. package/template_project/.claude/skills/postgres/SKILL.md +1 -1
  38. package/template_project/.claude/skills/testing-quality/SKILL.md +2 -0
  39. package/template_project/.claude/skills/webapp-testing/SKILL.md +1 -1
  40. package/template_project/.claude/ukit/index/route-task.mjs +3 -1
  41. package/template_project/.claude/ukit/index/tier-lane.mjs +1 -1
  42. package/template_project/.claude/ukit/runtime/compact-threshold.mjs +15 -29
  43. package/template_project/.claude/ukit/runtime/context-capacity.mjs +64 -1
  44. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +107 -4
  45. package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +20 -1
  46. package/template_project/.claude/ukit/runtime/mission/checkpoint.mjs +85 -0
  47. package/template_project/.claude/ukit/runtime/mission/classify.mjs +182 -0
  48. package/template_project/.claude/ukit/runtime/mission/drift.mjs +58 -0
  49. package/template_project/.claude/ukit/runtime/mission/graph.mjs +381 -0
  50. package/template_project/.claude/ukit/runtime/mission/hooks.mjs +199 -0
  51. package/template_project/.claude/ukit/runtime/mission/journal.mjs +68 -0
  52. package/template_project/.claude/ukit/runtime/mission/metrics.mjs +64 -0
  53. package/template_project/.claude/ukit/runtime/mission/recall.mjs +132 -0
  54. package/template_project/.claude/ukit/runtime/mission/redact.mjs +25 -0
  55. package/template_project/.claude/ukit/runtime/mission/restore.mjs +107 -0
  56. package/template_project/.claude/ukit/runtime/mission/store.mjs +231 -0
  57. package/template_project/.claude/ukit/runtime/mission/working.mjs +88 -0
  58. package/template_project/.claude/ukit/runtime/prompt-injection-cap.mjs +33 -0
  59. package/template_project/.claude/ukit/runtime/reinject-context.mjs +87 -6
  60. package/template_project/.claude/ukit/runtime/rescue/bundle.mjs +122 -0
  61. package/template_project/.claude/ukit/runtime/rescue/classify-failure.mjs +136 -0
  62. package/template_project/.claude/ukit/runtime/rescue/lease.mjs +65 -0
  63. package/template_project/.claude/ukit/runtime/rescue/reconstruct.mjs +273 -0
  64. package/template_project/.claude/ukit/runtime/rescue/recovery-state.mjs +120 -0
  65. package/template_project/.claude/ukit/runtime/rescue/rollover.mjs +151 -0
  66. package/template_project/.claude/ukit/runtime/sensitive-value-scanner.mjs +1 -1
  67. package/template_project/.claude/ukit/runtime/shell-watch.mjs +278 -0
  68. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +154 -0
  69. package/template_project/.omp/RULES.md +1 -1
  70. package/template_project/.omp/config.yml +2 -2
  71. package/template_project/.omp/hooks/pre/ukit-bridge.js +69 -2
  72. package/template_project/AGENTS.md +5 -1
  73. package/template_project/CLAUDE.md +5 -1
  74. package/template_project/docs/AI_HANDOFF/RULES.md +4 -4
  75. package/template_project/instructions/core.md +5 -1
  76. package/template_project/instructions/overlays/omp-rules.md +1 -1
  77. package/template_project/ukit/storage/config.json +32 -10
@@ -0,0 +1,182 @@
1
+ // Mission classifier (WP1). Pure, deterministic, no model calls, never throws. Contract:
2
+ // foldText(s) -> lowercase, diacritics stripped (Vietnamese d-stroke handled)
3
+ // extractRequirements(text) -> { requirements:[{text,kind,priority,files}], constraints[], prohibitions[],
4
+ // files[], features[], priority:'high'|'normal' }
5
+ // kind: feature|constraint|prohibition|test|ui|defect|question
6
+ // classifyPrompt({text, requirements=[{id,text,kind,status,workstream}], origin='user'})
7
+ // -> { relation:{type,targets[],score,method}, extracted }
8
+ // type: question|supersedes|defect|priority|extends|refines|independent|ambiguous
9
+ // origin 'system' -> { relation:null, extracted:null } (system text is never classified)
10
+ // independent prompts of kind ui/test list the active feature reqs as targets (graph links them RELATES_TO).
11
+ // ambiguous = keep both, graph marks status conflict, never blocks.
12
+ // registerReclassifier(fn) -> unregister(); fn({text, base, requirements}) may return a replacement
13
+ // {relation, extracted?} ; reclassifyPrompt(input) (async) applies them, off the hot path. Failures ignored.
14
+ // overlapScore(aText, bText) -> 0..1 stem-overlap used for target resolution.
15
+
16
+ export function foldText(s) {
17
+ return String(s ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/gi, 'd').toLowerCase();
18
+ }
19
+
20
+ const STOP = new Set(('a an the to of in on for and or with is are be it this that these those at by from as into our my your their ' +
21
+ 'please also include plus new all some any can could should would will do does did how what why when where which who ' +
22
+ 'fix bug add implement change update make create build thay vi doi them sua tao lam cho cua va la co khong duoc cac nhung mot ' +
23
+ 'loi hay can phai voi trong khi se da dang cung bao gom nua').split(/\s+/));
24
+
25
+ function stem(w) {
26
+ return w.replace(/(?:ations?|ation|ing|ed|es|s)$/, (m, off) => (off >= 3 ? '' : m));
27
+ }
28
+ function tokens(text) {
29
+ return [...new Set(foldText(text).replace(/[^a-z0-9_]+/g, ' ').split(' ').filter((w) => w.length > 1 && !STOP.has(w)).map(stem).filter((w) => w.length > 1))];
30
+ }
31
+
32
+ export function overlapScore(a, b) {
33
+ const ta = tokens(a);
34
+ const tb = new Set(tokens(b));
35
+ if (!ta.length || !tb.size) return 0;
36
+ let common = 0;
37
+ for (const t of ta) if (tb.has(t)) common += 1;
38
+ return common / Math.min(ta.length, tb.size);
39
+ }
40
+
41
+ const RE = {
42
+ question: /^(?:what|how|why|where|when|which|who|whom|is|are|was|were|does|do|did|can|could|should|would|will|la gi|tai sao|nhu the nao|o dau|bao nhieu|co phai|lam sao)\b|\?\s*$/,
43
+ imperative: /\b(?:implement|add|fix|create|make|build|change|update|remove|delete|write|refactor|include|replace|rename|move|thay|doi|them|sua|xoa|tao|lam|cap nhat|viet)\b/,
44
+ supersede: /\b(?:instead of|no longer|rather than|replace|replaced|switch from|change\b.+\bto|thay vi|khong con|doi\b.+\bsang|doi\b.+\bthanh|bo\b.+\bdung)\b/,
45
+ defect: /\b(?:fix|bug|bugs|broken|crash|crashes|regress\w*|fails?|failing|loi|hong|khong chay|sua loi)\b/,
46
+ extend: /\b(?:also|include|including|plus|additionally|as well|in addition|them|cung|bao gom|nua)\b/,
47
+ edit: /\b(?:update|modify|change|edit|refine|improve|adjust|sua|cap nhat|chinh)\b/,
48
+ priority: /\b(?:urgent|asap|critical|highest priority|high priority|top priority|priority|first|uu tien|gap|truoc tien)\b/,
49
+ prohibition: /\b(?:khong duoc|dung\b|cam|never|must not|mustn't|do not|don't|should not|shouldn't|cannot|can't|no\s+\w+\s+allowed)\b/,
50
+ constraint: /\b(?:must|always|only|should|required?|phai|chi|bat buoc|need to|needs to)\b/,
51
+ test: /\b(?:tests?|testing|coverage|spec|specs|e2e|kiem thu|unit)\b/,
52
+ ui: /\b(?:ui|ux|design|layout|css|style|styling|theme|giao dien|screen|page|component)\b/,
53
+ };
54
+
55
+ const FILE_RE = /(?:[\w@.-]+\/)+[\w@.-]+|\b[\w-]+\.(?:mjs|cjs|js|jsx|ts|tsx|json|md|css|scss|html|py|sh|yml|yaml|go|rs|java|sql)\b/g;
56
+
57
+ const cleanFiles = (a) => [...new Set((a || []).map((x) => x.replace(/[.,;:]+$/, '')))];
58
+ function kindOf(segment) {
59
+ const f = foldText(segment);
60
+ if (RE.question.test(f) && !RE.imperative.test(f)) return 'question';
61
+ if (RE.prohibition.test(f)) return 'prohibition';
62
+ if (RE.defect.test(f)) return 'defect';
63
+ if (RE.test.test(f)) return 'test';
64
+ if (RE.ui.test(f)) return 'ui';
65
+ if (RE.constraint.test(f)) return 'constraint';
66
+ return 'feature';
67
+ }
68
+
69
+ function splitSegments(text) {
70
+ const out = [];
71
+ for (const line of String(text ?? '').split(/\r?\n/)) {
72
+ const clean = line.replace(/^\s*(?:[-*+•]|\d+[.)])\s+/, '').trim();
73
+ if (!clean) continue;
74
+ for (const s of clean.split(/(?<=[.!?;])\s+/)) {
75
+ const t = s.trim().replace(/[.;]+$/, '').trim();
76
+ if (t.length >= 3) out.push(t);
77
+ }
78
+ }
79
+ return out;
80
+ }
81
+
82
+ export function extractRequirements(text) {
83
+ try {
84
+ const src = String(text ?? '');
85
+ const requirements = splitSegments(src).map((seg) => ({
86
+ text: seg, kind: kindOf(seg),
87
+ priority: RE.priority.test(foldText(seg)) ? 'high' : 'normal',
88
+ files: cleanFiles(seg.match(FILE_RE)),
89
+ }));
90
+ return {
91
+ requirements,
92
+ constraints: requirements.filter((r) => r.kind === 'constraint').map((r) => r.text),
93
+ prohibitions: requirements.filter((r) => r.kind === 'prohibition').map((r) => r.text),
94
+ files: cleanFiles(src.match(FILE_RE)),
95
+ features: tokens(src).slice(0, 12),
96
+ priority: RE.priority.test(foldText(src)) ? 'high' : 'normal',
97
+ };
98
+ } catch {
99
+ return { requirements: [], constraints: [], prohibitions: [], files: [], features: [], priority: 'normal' };
100
+ }
101
+ }
102
+
103
+ const SUPERSEDE_MIN = 0.4;
104
+ const AMBIGUOUS_MIN = 0.15;
105
+ const EXTEND_MIN = 0.25;
106
+ const REFINE_MIN = 0.5;
107
+
108
+ function rank(text, reqs) {
109
+ return reqs.map((r) => ({ id: r.id, score: overlapScore(text, r.text), r }))
110
+ .filter((x) => x.score > 0).sort((a, b) => b.score - a.score);
111
+ }
112
+
113
+ export function classifyPrompt({ text, requirements = [], origin = 'user' } = {}) {
114
+ try {
115
+ if (origin === 'system') return { relation: null, extracted: null };
116
+ const extracted = extractRequirements(text);
117
+ const f = foldText(text);
118
+ const live = (Array.isArray(requirements) ? requirements : []).filter((r) => r && (r.status === 'active' || r.status === 'conflict' || !r.status)
119
+ && r.kind !== 'question');
120
+ const ranked = rank(text, live);
121
+ const best = ranked[0];
122
+ const mk = (type, targets, score, method) => ({ relation: { type, targets, score: Math.round(score * 100) / 100, method }, extracted });
123
+ const kinds = extracted.requirements.map((r) => r.kind);
124
+ const allQuestions = kinds.length > 0 && kinds.every((k) => k === 'question');
125
+
126
+ if (allQuestions || (!kinds.length && RE.question.test(f))) return mk('question', [], 1, 'question-no-imperative');
127
+
128
+ if (RE.supersede.test(f) && best && best.score >= AMBIGUOUS_MIN) {
129
+ const second = ranked[1];
130
+ const tie = second && best.score - second.score < 0.05;
131
+ if (best.score >= SUPERSEDE_MIN && !tie) return mk('supersedes', [best.id], best.score, 'supersede-cue+overlap');
132
+ const targets = tie ? ranked.filter((x) => best.score - x.score < 0.05).map((x) => x.id) : [best.id];
133
+ return mk('ambiguous', targets, best.score, tie ? 'supersede-tie' : 'supersede-sub-threshold');
134
+ }
135
+
136
+ if (RE.defect.test(f)) {
137
+ return best && best.score >= AMBIGUOUS_MIN
138
+ ? mk('defect', [best.id], best.score, 'defect-cue+overlap')
139
+ : mk('defect', [], 0, 'defect-cue');
140
+ }
141
+
142
+ if (RE.priority.test(f) && best && best.score >= EXTEND_MIN && !RE.imperative.test(f.replace(RE.priority, ''))) {
143
+ return mk('priority', [best.id], best.score, 'priority-cue+overlap');
144
+ }
145
+
146
+ const cue = RE.extend.test(f);
147
+ if (best && best.score >= REFINE_MIN && RE.edit.test(f)) return mk('refines', [best.id], best.score, 'overlap+edit-verb');
148
+ if (best && best.score >= EXTEND_MIN && cue) return mk('extends', [best.id], best.score, 'extend-cue+overlap');
149
+ if (best && best.score >= REFINE_MIN) return mk('extends', [best.id], best.score, 'high-overlap');
150
+ if (cue) {
151
+ const recent = [...live].reverse().find((r) => r.kind === 'feature' || r.kind === 'defect') || live[live.length - 1];
152
+ if (recent) return mk('extends', [recent.id], 0.1, 'extend-cue-recent');
153
+ }
154
+
155
+ const primary = kinds.find((k) => k === 'ui' || k === 'test');
156
+ if (primary) {
157
+ const scope = live.filter((r) => r.kind === 'feature' || r.kind === 'defect').map((r) => r.id).slice(-12);
158
+ return mk('independent', scope, 0, `scope-${primary}`);
159
+ }
160
+ return mk('independent', [], 0, 'no-match');
161
+ } catch {
162
+ return { relation: { type: 'independent', targets: [], score: 0, method: 'error-fallback' }, extracted: extractRequirements('') };
163
+ }
164
+ }
165
+
166
+ const reclassifiers = new Set();
167
+ export function registerReclassifier(fn) {
168
+ if (typeof fn !== 'function') return () => {};
169
+ reclassifiers.add(fn);
170
+ return () => reclassifiers.delete(fn);
171
+ }
172
+
173
+ export async function reclassifyPrompt(input = {}) {
174
+ let result = classifyPrompt(input);
175
+ for (const fn of reclassifiers) {
176
+ try {
177
+ const r = await fn({ text: input.text, base: result, requirements: input.requirements || [] });
178
+ if (r && r.relation && typeof r.relation.type === 'string') result = { relation: r.relation, extracted: r.extracted || result.extracted };
179
+ } catch { /* hook failures never affect the deterministic result */ }
180
+ }
181
+ return result;
182
+ }
@@ -0,0 +1,58 @@
1
+ // Mission drift detectors (WP2), graph-only. Contract:
2
+ // detectDrift(graph, {checkpoint?, writtenPaths?, newPromptSinceVerify?, now?, staleMs?}) -> finding[]
3
+ // finding = {code, severity:'warn'|'info', ref, detail}; never throws (returns [] on error).
4
+ // codes: req-without-task, orphan-task, duplicate-task, stale-done-unverified, stale-ac,
5
+ // req-missing-from-checkpoint, write-to-verified-paths, priority-inversion
6
+ // checkpoint = {activeReqIds:[...]}; writtenPaths = paths written this turn (no new prompt => drift);
7
+ // graph is the object from graph.mjs createGraph/loadGraph.
8
+ import crypto from 'node:crypto';
9
+
10
+ export const STALE_DONE_MS = 30 * 60 * 1000;
11
+ const live = (r) => r && (r.status === 'active' || r.status === 'conflict') && r.kind !== 'question';
12
+ const overlap = (a, b) => { const x = String(a).replace(/\/+$/, ''); const y = String(b).replace(/\/+$/, ''); return x === y || x.startsWith(`${y}/`) || y.startsWith(`${x}/`); };
13
+
14
+ export function detectDrift(graph, { checkpoint, writtenPaths = [], newPromptSinceVerify = false, now = Date.now(), staleMs = STALE_DONE_MS } = {}) {
15
+ const out = [];
16
+ try {
17
+ const s = graph.state;
18
+ const add = (code, ref, detail, severity = 'warn') => out.push({ code, severity, ref, detail });
19
+ const tasks = Object.values(s.tasks);
20
+
21
+ for (const r of Object.values(s.reqs)) {
22
+ if (live(r) && !graph.tasksForReq(r.id).some((t) => t.status !== 'cancelled')) add('req-without-task', r.id, 'active requirement has no IMPLEMENTS task');
23
+ }
24
+ for (const t of tasks) {
25
+ if (t.status === 'cancelled') continue;
26
+ if (!(t.reqIds || []).some((id) => s.reqs[id])) add('orphan-task', t.id, 'task implements no known requirement');
27
+ if (t.status === 'done_unverified' && now - (t.ts || now) > staleMs) add('stale-done-unverified', t.id, 'done but unverified past threshold');
28
+ }
29
+ const seen = new Map();
30
+ for (const t of tasks) {
31
+ if (t.status === 'cancelled') continue;
32
+ const key = crypto.createHash('sha1').update(`${(t.reqIds || []).join(',')}|${String(t.title).toLowerCase().trim()}`).digest('hex');
33
+ if (seen.has(key)) add('duplicate-task', t.id, `duplicates ${seen.get(key)}`); else seen.set(key, t.id);
34
+ }
35
+ for (const a of Object.values(s.acs)) if (a.status === 'stale') add('stale-ac', a.id, 'acceptance criterion went stale; re-verify');
36
+
37
+ if (checkpoint && Array.isArray(checkpoint.activeReqIds)) {
38
+ const have = new Set(checkpoint.activeReqIds);
39
+ for (const r of Object.values(s.reqs)) if (live(r) && !have.has(r.id)) add('req-missing-from-checkpoint', r.id, 'active requirement absent from latest checkpoint', 'info');
40
+ }
41
+
42
+ if (!newPromptSinceVerify && writtenPaths.length) {
43
+ for (const t of tasks) {
44
+ if (t.status === 'verified' && (t.paths || []).some((p) => writtenPaths.some((w) => overlap(p, w)))) add('write-to-verified-paths', t.id, 'writes touch verified task paths without a new prompt');
45
+ }
46
+ }
47
+
48
+ const rank = (r) => (r?.priority === 'high' ? 1 : 0);
49
+ const ready = graph.readySet();
50
+ const ip = tasks.filter((t) => t.status === 'in_progress');
51
+ for (const cur of ip) {
52
+ const cr = rank(s.reqs[cur.reqIds?.[0]]);
53
+ const higher = ready.find((t) => rank(s.reqs[t.reqIds?.[0]]) > cr);
54
+ if (higher) add('priority-inversion', cur.id, `${higher.id} is higher priority and ready`);
55
+ }
56
+ } catch { return []; }
57
+ return out;
58
+ }
@@ -0,0 +1,381 @@
1
+ // Mission graph, Level B (WP2). Contract, for other workers. Pure in-memory model + event-sourced persistence.
2
+ // Nothing here throws to hook callers: mutators return null/false on bad input; load/persist return {ok:false}.
3
+ //
4
+ // createGraph(snapshot?) -> graph (graph.state is the plain serialisable state)
5
+ // loadGraph({projectRoot, missionId}) -> Promise<graph> (graph.json snapshot + replay of events with seq > lastSeq)
6
+ // persistGraph(graph, {projectRoot, missionId}) -> Promise<{ok, events, spooled}>
7
+ // appends the graph's pending events via store.appendEvent, then writes graph.json (open items only),
8
+ // bindings.json (LRU 2000) and appends newly-closed items to graph-archive.jsonl.
9
+ //
10
+ // graph methods (all mutations emit events through ONE reducer, so replay == live; ids are stable R-n/T-n/AC-n/W-n):
11
+ // applyPrompt(prompt, {classification?}) -> {relation, reqIds, taskIds, acIds, workstream} | null
12
+ // prompt = {promptId, text, origin?, relation?, extracted?}. origin 'system' -> null (never classified).
13
+ // extends/refines -> RELATES_TO (+MODIFIES for refines, which invalidates the refined target's verified work);
14
+ // supersedes -> old req status 'superseded' (record kept, revisions both kept), SUPERSEDES edge, old open tasks cancelled;
15
+ // defect -> REGRESSES to the target req AND its root feature, verified work of the target is invalidated;
16
+ // ambiguous -> both reqs status 'conflict'; independent ui/test prompts link RELATES_TO to feature reqs they scope.
17
+ // question -> req kind 'question' (no task, never blocks completion).
18
+ // addRequirement({promptId,text,kind,priority,workstream,parent,scope}) / addTask({reqIds,title,workstream,paths,parent,outcome})
19
+ // addAc({taskId,reqId,text}) / addEdge({from,to,type,promptId}) (edges: DEPENDS_ON BLOCKS IMPLEMENTS RELATES_TO MODIFIES SUPERSEDES REGRESSES VERIFIED_BY)
20
+ // setTaskStatus(taskId, status, {owner,paths}) -- 'verified' is REJECTED here; the only road to verified is recordEvidence.
21
+ // recordEvidence(acId, {kind:'receipt'|'test'|'commit', ref, gitRev?, ts?}) -> bool (kind+ref required)
22
+ // AC -> verified; task -> verified once all its ACs are verified.
23
+ // readySet() -> task[] topological: pending/ready/invalidated, all DEPENDS_ON deps verified, no BLOCKS from unverified tasks, no blocker.
24
+ // invalidateByPaths(paths) -> taskIds only verified/done_unverified tasks whose paths overlap are invalidated (their ACs go stale).
25
+ // isComplete() -> {complete, missing:[reqId]} every active (active|conflict, non-question) requirement has >=1 AC and all ACs verified.
26
+ // bindTaskInstance(taskInstanceId, taskId) / getBinding(id) ; setBlocker(taskId,{code,reason,deniedOps[]}) / clearBlocker(taskId)
27
+ // blockerForInstance(taskInstanceId) -> {taskId, blocker}|null (a new instance bound to a blocked task inherits it)
28
+ // edges() -> all edges incl. derived IMPLEMENTS (task->req, from task.reqIds) and VERIFIED_BY (task->ac)
29
+ // snapshot() -> {v,rev,lastSeq,counters,reqs,tasks,acs,edges,workstreams} open items only; closedItems() -> archive candidates
30
+ // drainEvents() -> pending events (used by persistGraph)
31
+ import { classifyPrompt } from './classify.mjs';
32
+ import {
33
+ appendEvent, appendJsonlSync, missionDir, readEvents, readSnapshot, writeSnapshot,
34
+ } from './store.mjs';
35
+ import fs from 'node:fs';
36
+ import path from 'node:path';
37
+
38
+ export const EDGE_TYPES = ['DEPENDS_ON', 'BLOCKS', 'IMPLEMENTS', 'RELATES_TO', 'MODIFIES', 'SUPERSEDES', 'REGRESSES', 'VERIFIED_BY'];
39
+ const SETTABLE = new Set(['pending', 'ready', 'in_progress', 'blocked', 'done_unverified', 'invalidated', 'cancelled']);
40
+ const READY_FROM = new Set(['pending', 'ready', 'invalidated']);
41
+ const EVIDENCE_KINDS = new Set(['receipt', 'test', 'commit']);
42
+ const BIND_LRU = 2000;
43
+ const num = (id) => Number(String(id).replace(/\D/g, '')) || 0;
44
+ const live = (r) => r && (r.status === 'active' || r.status === 'conflict') && r.kind !== 'question';
45
+
46
+ function pathsOverlap(a, b) {
47
+ const x = String(a).replace(/\/+$/, '');
48
+ const y = String(b).replace(/\/+$/, '');
49
+ return x === y || x.startsWith(`${y}/`) || y.startsWith(`${x}/`);
50
+ }
51
+
52
+ export function createGraph(snap) {
53
+ const s = {
54
+ v: 1, rev: 0, lastSeq: 0, counters: { R: 0, T: 0, AC: 0, W: 0, ev: 0 },
55
+ reqs: {}, tasks: {}, acs: {}, edges: [], workstreams: {}, blockers: {},
56
+ };
57
+ if (snap && typeof snap === 'object') {
58
+ Object.assign(s, { rev: snap.rev || 0, lastSeq: snap.lastSeq || 0 });
59
+ Object.assign(s.counters, snap.counters || {});
60
+ for (const k of ['reqs', 'tasks', 'acs', 'workstreams', 'blockers']) s[k] = { ...(snap[k] || {}) };
61
+ s.edges = Array.isArray(snap.edges) ? [...snap.edges] : [];
62
+ for (const a of Object.values(s.acs)) if (!a.reqId) a.reqId = s.tasks[a.taskId]?.reqIds?.[0];
63
+ }
64
+ const bindings = new Map();
65
+ const edgeKeys = new Set(s.edges.map((e) => `${e.from}|${e.to}|${e.type}`));
66
+ const reqTasks = new Map();
67
+ const pending = [];
68
+ const archived = new Set();
69
+
70
+ const indexTask = (t) => { for (const r of t.reqIds || []) { if (!reqTasks.has(r)) reqTasks.set(r, new Set()); reqTasks.get(r).add(t.id); } };
71
+ Object.values(s.tasks).forEach(indexTask);
72
+ const bump = (kind, id) => { const n = num(id); if (n > s.counters[kind]) s.counters[kind] = n; };
73
+
74
+ // single reducer: idempotent by id so duplicate/out-of-order replays converge
75
+ function reduce(kind, d) {
76
+ switch (kind) {
77
+ case 'req.add': if (!s.reqs[d.req.id]) { s.reqs[d.req.id] = d.req; bump('R', d.req.id); } break;
78
+ case 'req.update': if (s.reqs[d.id]) Object.assign(s.reqs[d.id], d.patch); break;
79
+ case 'task.add': if (!s.tasks[d.task.id]) { s.tasks[d.task.id] = d.task; bump('T', d.task.id); indexTask(d.task); } break;
80
+ case 'task.update': if (s.tasks[d.id]) Object.assign(s.tasks[d.id], d.patch); break;
81
+ case 'ac.add': if (!s.acs[d.ac.id]) {
82
+ s.acs[d.ac.id] = d.ac; bump('AC', d.ac.id);
83
+ const t = s.tasks[d.ac.taskId];
84
+ if (t && !(t.acIds || (t.acIds = [])).includes(d.ac.id)) t.acIds.push(d.ac.id);
85
+ } break;
86
+ case 'ac.update': if (s.acs[d.id]) {
87
+ const ac = s.acs[d.id];
88
+ if (d.evidence) { ac.evidence = [...(ac.evidence || []), d.evidence]; ac.status = 'verified'; } else Object.assign(ac, d.patch);
89
+ } break;
90
+ case 'edge.add': { const k = `${d.edge.from}|${d.edge.to}|${d.edge.type}`; if (!edgeKeys.has(k)) { edgeKeys.add(k); s.edges.push(d.edge); } } break;
91
+ case 'ws.add': if (!s.workstreams[d.ws.id]) { s.workstreams[d.ws.id] = d.ws; bump('W', d.ws.id); } break;
92
+ case 'bind': bindings.delete(d.iid); bindings.set(d.iid, { taskId: d.taskId, reqIds: d.reqIds || [] });
93
+ while (bindings.size > BIND_LRU) bindings.delete(bindings.keys().next().value); break;
94
+ case 'blocker.set': if (s.tasks[d.taskId]) s.blockers[d.taskId] = d.blocker; break;
95
+ case 'blocker.clear': delete s.blockers[d.taskId]; break;
96
+ default: return;
97
+ }
98
+ s.rev += 1;
99
+ }
100
+ const emit = (kind, data) => { reduce(kind, data); pending.push({ kind, data, dedupeKey: `${(s.counters.ev += 1)}:${kind}` }); };
101
+
102
+ const g = {
103
+ state: s,
104
+ apply: (kind, data) => { try { reduce(kind, data); } catch { /* ignore malformed replay event */ } },
105
+ drainEvents: () => pending.splice(0),
106
+
107
+ addWorkstream(title) { const id = `W-${s.counters.W + 1}`; emit('ws.add', { ws: { id, title: String(title).slice(0, 80) } }); return id; },
108
+ addRequirement({ promptId, text, kind = 'feature', priority = 'normal', workstream, parent, scope } = {}) {
109
+ try {
110
+ if (!text) return null;
111
+ const id = `R-${s.counters.R + 1}`;
112
+ const req = { id, promptId, text: String(text), kind, status: 'active', ws: workstream, priority, revisions: [{ promptId, text: String(text) }] };
113
+ if (parent) req.parent = parent;
114
+ if (scope) req.scope = scope;
115
+ if (priority === 'normal') delete req.priority;
116
+ emit('req.add', { req });
117
+ return s.reqs[id];
118
+ } catch { return null; }
119
+ },
120
+ addTask({ reqIds = [], title, workstream, paths, parent, outcome, ts } = {}) {
121
+ try {
122
+ if (!title) return null;
123
+ const id = `T-${s.counters.T + 1}`;
124
+ const task = { id, reqIds: [...reqIds], title: String(title), status: 'pending', ws: workstream, ts: ts ?? Date.now() };
125
+ if (paths?.length) task.paths = [...new Set(paths)];
126
+ if (parent) task.parent = parent;
127
+ if (outcome) task.outcome = outcome;
128
+ emit('task.add', { task });
129
+ return s.tasks[id];
130
+ } catch { return null; }
131
+ },
132
+ addAc({ taskId, reqId, text } = {}) {
133
+ try {
134
+ if (!s.tasks[taskId]) return null;
135
+ const id = `AC-${s.counters.AC + 1}`;
136
+ const ac = { id, taskId, reqId, status: 'unverified' };
137
+ if (text && text !== `Verified: ${s.tasks[taskId].title}`) ac.text = text;
138
+ emit('ac.add', { ac });
139
+ return s.acs[id];
140
+ } catch { return null; }
141
+ },
142
+ addEdge({ from, to, type, promptId } = {}) {
143
+ if (!from || !to || !EDGE_TYPES.includes(type)) return null;
144
+ const edge = { from, to, type };
145
+ if (promptId) edge.promptId = promptId;
146
+ if (edgeKeys.has(`${from}|${to}|${type}`)) return edge;
147
+ emit('edge.add', { edge });
148
+ return edge;
149
+ },
150
+ setReqStatus(id, status) { if (!s.reqs[id]) return false; emit('req.update', { id, patch: { status } }); return true; },
151
+ setTaskStatus(taskId, status, { owner, paths } = {}) {
152
+ try {
153
+ const t = s.tasks[taskId];
154
+ if (!t || !SETTABLE.has(status)) return false; // 'verified' only via recordEvidence
155
+ const patch = { status, ts: Date.now() };
156
+ if (owner !== undefined) patch.owner = owner;
157
+ if (paths?.length) patch.paths = [...new Set([...(t.paths || []), ...paths])];
158
+ emit('task.update', { id: taskId, patch });
159
+ return true;
160
+ } catch { return false; }
161
+ },
162
+ recordEvidence(acId, evidence = {}) {
163
+ try {
164
+ const ac = s.acs[acId];
165
+ if (!ac || !EVIDENCE_KINDS.has(evidence.kind) || !evidence.ref) return false;
166
+ emit('ac.update', { id: acId, evidence: { kind: evidence.kind, ref: String(evidence.ref), gitRev: evidence.gitRev || null, ts: evidence.ts || Date.now() } });
167
+ const t = s.tasks[ac.taskId];
168
+ if (t && (t.acIds || []).every((id) => s.acs[id]?.status === 'verified')) emit('task.update', { id: t.id, patch: { status: 'verified', ts: Date.now() } });
169
+ return true;
170
+ } catch { return false; }
171
+ },
172
+ invalidateByPaths(paths = []) {
173
+ const hit = [];
174
+ try {
175
+ const list = (Array.isArray(paths) ? paths : [paths]).filter(Boolean);
176
+ if (!list.length) return hit;
177
+ for (const t of Object.values(s.tasks)) {
178
+ if (t.status !== 'verified' && t.status !== 'done_unverified') continue;
179
+ if (!(t.paths || []).some((p) => list.some((q) => pathsOverlap(p, q)))) continue;
180
+ emit('task.update', { id: t.id, patch: { status: 'invalidated', ts: Date.now() } });
181
+ for (const id of t.acIds || []) if (s.acs[id]?.status === 'verified') emit('ac.update', { id, patch: { status: 'stale' } });
182
+ hit.push(t.id);
183
+ }
184
+ } catch { /* fail safe */ }
185
+ return hit;
186
+ },
187
+ readySet() {
188
+ try {
189
+ const blockedBy = new Map();
190
+ const deps = new Map();
191
+ for (const e of g.edges()) {
192
+ if (e.type === 'DEPENDS_ON') (deps.get(e.from) || deps.set(e.from, []).get(e.from)).push(e.to);
193
+ if (e.type === 'BLOCKS') (blockedBy.get(e.to) || blockedBy.set(e.to, []).get(e.to)).push(e.from);
194
+ }
195
+ const done = (id) => s.tasks[id]?.status === 'verified' || s.tasks[id]?.status === 'cancelled' || !s.tasks[id];
196
+ return Object.values(s.tasks).filter((t) => READY_FROM.has(t.status) && !s.blockers[t.id]
197
+ && (deps.get(t.id) || []).every(done) && (blockedBy.get(t.id) || []).every(done))
198
+ .sort((a, b) => num(a.id) - num(b.id));
199
+ } catch { return []; }
200
+ },
201
+ isComplete() {
202
+ const missing = [];
203
+ for (const r of Object.values(s.reqs)) {
204
+ if (!live(r)) continue;
205
+ const acs = [...(reqTasks.get(r.id) || [])].flatMap((tid) => (s.tasks[tid]?.status === 'cancelled' ? [] : s.tasks[tid]?.acIds || []));
206
+ if (!acs.length || !acs.every((id) => s.acs[id]?.status === 'verified')) missing.push(r.id);
207
+ }
208
+ return { complete: missing.length === 0, missing };
209
+ },
210
+ tasksForReq: (reqId) => [...(reqTasks.get(reqId) || [])].map((id) => s.tasks[id]).filter(Boolean),
211
+ acText: (ac) => ac.text || `Verified: ${s.tasks[ac.taskId]?.title ?? ''}`,
212
+ rootOf(reqId) { let r = s.reqs[reqId]; let n = 0; while (r?.parent && s.reqs[r.parent] && n++ < 50) r = s.reqs[r.parent]; return r?.id; },
213
+
214
+ bindTaskInstance(iid, taskId) {
215
+ if (!iid || !s.tasks[taskId]) return false;
216
+ emit('bind', { iid, taskId, reqIds: s.tasks[taskId].reqIds });
217
+ return true;
218
+ },
219
+ getBinding: (iid) => bindings.get(iid) || null,
220
+ exportBindings: () => Object.fromEntries(bindings),
221
+ setBlocker(taskId, { code, reason, deniedOps = [] } = {}) {
222
+ if (!s.tasks[taskId] || !code) return false;
223
+ emit('blocker.set', { taskId, blocker: { code, reason: reason || '', deniedOps: [...deniedOps] } });
224
+ return true;
225
+ },
226
+ clearBlocker(taskId) { if (!s.blockers[taskId]) return false; emit('blocker.clear', { taskId }); return true; },
227
+ blockerForInstance(iid) {
228
+ const b = bindings.get(iid);
229
+ return b && s.blockers[b.taskId] ? { taskId: b.taskId, blocker: s.blockers[b.taskId] } : null;
230
+ },
231
+
232
+ edges() {
233
+ const out = [...s.edges];
234
+ for (const t of Object.values(s.tasks)) {
235
+ for (const r of t.reqIds || []) out.push({ from: t.id, to: r, type: 'IMPLEMENTS' });
236
+ for (const a of t.acIds || []) out.push({ from: t.id, to: a, type: 'VERIFIED_BY' });
237
+ }
238
+ return out;
239
+ },
240
+
241
+ applyPrompt(prompt, { classification } = {}) {
242
+ try {
243
+ if (!prompt || prompt.origin === 'system' || !prompt.text) return null;
244
+ const reqsNow = Object.values(s.reqs);
245
+ const cls = classification || (prompt.relation ? { relation: prompt.relation, extracted: prompt.extracted } : null)
246
+ || classifyPrompt({ text: prompt.text, requirements: reqsNow });
247
+ const relation = cls.relation;
248
+ const extracted = cls.extracted || { requirements: [] };
249
+ const pid = prompt.promptId;
250
+ const targets = (relation.targets || []).filter((id) => s.reqs[id]);
251
+ const target = targets[0] ? s.reqs[targets[0]] : null;
252
+ const type = relation.type;
253
+ let ws;
254
+ if (target && ['extends', 'refines', 'defect', 'supersedes', 'priority'].includes(type)) ws = target.ws;
255
+ if (!ws) ws = g.addWorkstream((extracted.requirements[0]?.text || prompt.text).slice(0, 60));
256
+ const reqIds = []; const taskIds = []; const acIds = [];
257
+ const cands = extracted.requirements.length ? extracted.requirements : [{ text: prompt.text, kind: 'feature', priority: 'normal', files: [] }];
258
+ for (const c of cands) {
259
+ const kind = type === 'defect' && c.kind === 'feature' ? 'defect' : c.kind;
260
+ const parent = target && ['extends', 'refines', 'defect'].includes(type) ? target.id : undefined;
261
+ const req = g.addRequirement({ promptId: pid, text: c.text, kind, priority: c.priority, workstream: ws, parent });
262
+ if (!req) continue;
263
+ reqIds.push(req.id);
264
+ if (kind === 'question') { reduce('req.update', { id: req.id, patch: { status: 'active' } }); continue; }
265
+ const task = g.addTask({ reqIds: [req.id], title: c.text, workstream: ws, paths: c.files });
266
+ const ac = task && g.addAc({ taskId: task.id, reqId: req.id });
267
+ if (task) taskIds.push(task.id);
268
+ if (ac) acIds.push(ac.id);
269
+ for (const tid of targets) {
270
+ if (type === 'extends' || type === 'priority') g.addEdge({ from: req.id, to: tid, type: 'RELATES_TO', promptId: pid });
271
+ if (type === 'refines') {
272
+ g.addEdge({ from: req.id, to: tid, type: 'RELATES_TO', promptId: pid });
273
+ for (const old of g.tasksForReq(tid)) {
274
+ if (task) g.addEdge({ from: task.id, to: old.id, type: 'MODIFIES', promptId: pid });
275
+ if (old.status === 'verified' || old.status === 'done_unverified') g.invalidateTask(old.id);
276
+ }
277
+ }
278
+ if (type === 'defect') {
279
+ g.addEdge({ from: req.id, to: tid, type: 'REGRESSES', promptId: pid });
280
+ const root = g.rootOf(tid);
281
+ if (root && root !== tid) g.addEdge({ from: req.id, to: root, type: 'REGRESSES', promptId: pid });
282
+ for (const old of [...g.tasksForReq(tid), ...(root && root !== tid ? g.tasksForReq(root) : [])]) {
283
+ if (old.status === 'verified' || old.status === 'done_unverified') g.invalidateTask(old.id);
284
+ }
285
+ }
286
+ if (type === 'supersedes') {
287
+ g.addEdge({ from: req.id, to: tid, type: 'SUPERSEDES', promptId: pid });
288
+ emit('req.update', { id: tid, patch: { status: 'superseded', supersededBy: req.id } });
289
+ for (const old of g.tasksForReq(tid)) {
290
+ if (old.status === 'verified') g.invalidateTask(old.id);
291
+ else emit('task.update', { id: old.id, patch: { status: 'cancelled', ts: Date.now() } });
292
+ }
293
+ }
294
+ if (type === 'ambiguous') {
295
+ g.addEdge({ from: req.id, to: tid, type: 'RELATES_TO', promptId: pid });
296
+ emit('req.update', { id: tid, patch: { status: 'conflict' } });
297
+ emit('req.update', { id: req.id, patch: { status: 'conflict' } });
298
+ }
299
+ if (type === 'independent' && (kind === 'ui' || kind === 'test')) g.addEdge({ from: req.id, to: tid, type: 'RELATES_TO', promptId: pid });
300
+ }
301
+ if (type === 'independent' && task && (kind === 'ui' || kind === 'test')) {
302
+ for (const tid of targets) for (const old of g.tasksForReq(tid)) g.addEdge({ from: task.id, to: old.id, type: 'MODIFIES', promptId: pid });
303
+ }
304
+ }
305
+ return { relation, reqIds, taskIds, acIds, workstream: ws };
306
+ } catch { return null; }
307
+ },
308
+ invalidateTask(taskId) {
309
+ const t = s.tasks[taskId];
310
+ if (!t) return false;
311
+ emit('task.update', { id: taskId, patch: { status: 'invalidated', ts: Date.now() } });
312
+ for (const id of t.acIds || []) if (s.acs[id]?.status === 'verified') emit('ac.update', { id, patch: { status: 'stale' } });
313
+ return true;
314
+ },
315
+
316
+ closedItems() {
317
+ const reqs = Object.values(s.reqs).filter((r) => r.status === 'superseded' || r.status === 'answered');
318
+ const closedReq = new Set(reqs.map((r) => r.id));
319
+ const tasks = Object.values(s.tasks).filter((t) => t.status === 'cancelled' || (t.reqIds?.length && t.reqIds.every((r) => closedReq.has(r))));
320
+ const closedTask = new Set(tasks.map((t) => t.id));
321
+ const acs = Object.values(s.acs).filter((a) => closedTask.has(a.taskId));
322
+ return { reqs, tasks, acs };
323
+ },
324
+ snapshot() {
325
+ const c = g.closedItems();
326
+ const drop = (list) => new Set(list.map((x) => x.id));
327
+ const dr = drop(c.reqs); const dt = drop(c.tasks); const da = drop(c.acs);
328
+ const pick = (obj, skip) => Object.fromEntries(Object.entries(obj).filter(([k]) => !skip.has(k)));
329
+ return {
330
+ v: 1, rev: s.rev, lastSeq: s.lastSeq, counters: s.counters,
331
+ reqs: pick(s.reqs, dr), tasks: pick(s.tasks, dt),
332
+ // ac.reqId is derivable from its task (first reqId) and restored on load; keeps 1000-task snapshots small
333
+ acs: Object.fromEntries(Object.entries(s.acs).filter(([k]) => !da.has(k)).map(([k, a]) => {
334
+ const { reqId, ...rest } = a;
335
+ return [k, reqId && reqId !== s.tasks[a.taskId]?.reqIds?.[0] ? a : rest];
336
+ })),
337
+ edges: s.edges.filter((e) => !dr.has(e.from) && !dr.has(e.to) && !dt.has(e.from) && !dt.has(e.to)),
338
+ workstreams: s.workstreams, blockers: pick(s.blockers, dt),
339
+ };
340
+ },
341
+ _archived: archived,
342
+ };
343
+ return g;
344
+ }
345
+
346
+ export async function loadGraph({ projectRoot, missionId } = {}) {
347
+ try {
348
+ const snap = readSnapshot(projectRoot, missionId);
349
+ const g = createGraph(snap);
350
+ try {
351
+ const b = JSON.parse(fs.readFileSync(path.join(missionDir(projectRoot, missionId), 'bindings.json'), 'utf8'));
352
+ for (const [iid, v] of Object.entries(b)) g.apply('bind', { iid, taskId: v.taskId, reqIds: v.reqIds });
353
+ } catch { /* no bindings yet */ }
354
+ const events = readEvents(projectRoot, missionId, g.state.lastSeq);
355
+ for (const e of events) if (e.kind !== 'prompt' && e.data) { g.apply(e.kind, e.data); g.state.lastSeq = Math.max(g.state.lastSeq, e.seq); }
356
+ for (const e of events) g.state.lastSeq = Math.max(g.state.lastSeq, e.seq);
357
+ return g;
358
+ } catch { return createGraph(); }
359
+ }
360
+
361
+ export async function persistGraph(graph, { projectRoot, missionId } = {}) {
362
+ try {
363
+ let events = 0; let spooled = 0;
364
+ for (const ev of graph.drainEvents()) {
365
+ const r = await appendEvent(projectRoot, missionId, { kind: ev.kind, dedupeKey: ev.dedupeKey, data: ev.data });
366
+ if (r.ok && r.event) { events += 1; graph.state.lastSeq = Math.max(graph.state.lastSeq, r.event.seq); } else if (r.spooled) spooled += 1;
367
+ }
368
+ const closed = graph.closedItems();
369
+ const base = path.join(missionDir(projectRoot, missionId), 'graph-archive');
370
+ for (const kind of ['reqs', 'tasks', 'acs']) {
371
+ for (const item of closed[kind]) {
372
+ if (graph._archived.has(item.id)) continue;
373
+ graph._archived.add(item.id);
374
+ appendJsonlSync(base, { kind, item });
375
+ }
376
+ }
377
+ writeSnapshot(projectRoot, missionId, graph.snapshot());
378
+ fs.writeFileSync(path.join(missionDir(projectRoot, missionId), 'bindings.json'), JSON.stringify(graph.exportBindings()));
379
+ return { ok: true, events, spooled };
380
+ } catch (e) { return { ok: false, error: String(e?.message || e) }; }
381
+ }