@haaaiawd/skeinn 0.0.0-stage → 2.5.0

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.
@@ -0,0 +1,1992 @@
1
+ import {
2
+ appendFileSync,
3
+ existsSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ readdirSync,
7
+ renameSync,
8
+ statSync,
9
+ writeFileSync,
10
+ } from 'node:fs';
11
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
12
+ import { createHash } from 'node:crypto';
13
+ import {
14
+ agentProtocol,
15
+ AGENT_ANCHOR,
16
+ EXECUTION_PROTOCOL,
17
+ CAPABILITY_MODES,
18
+ CAPABILITY_TEMPLATE,
19
+ CORE_DESIGN_KINDS,
20
+ DESIGN_KINDS,
21
+ PROJECT_TEMPLATE,
22
+ RESEARCH_GUIDE,
23
+ STRUCTURE_TEMPLATE,
24
+ designTemplate,
25
+ evalConditionPrompt,
26
+ evalJudgePrompt,
27
+ evalProbeChecklist,
28
+ checkpointProtocol,
29
+ evalRelayBatonPrompt,
30
+ keeperProtocol,
31
+ shapingContext,
32
+ } from './protocol.js';
33
+
34
+ const SCHEMA_VERSION = 2;
35
+ const VALID_PROJECT_STATUS = new Set(['shaping', 'ready_for_keeper', 'build_ready', 'building', 'complete']);
36
+ const VALID_TASK_STATUS = new Set(['open', 'active', 'blocked', 'done']);
37
+ let runtimePaths = null;
38
+
39
+ function now() {
40
+ return new Date().toISOString();
41
+ }
42
+
43
+ function readJson(path, label = basename(path)) {
44
+ try {
45
+ return JSON.parse(readFileSync(path, 'utf8'));
46
+ } catch (error) {
47
+ throw new Error(`${label} cannot be read: ${error.message}`);
48
+ }
49
+ }
50
+
51
+ function atomicJson(path, value) {
52
+ const temp = `${path}.tmp-${process.pid}`;
53
+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
54
+ renameSync(temp, path);
55
+ }
56
+
57
+ function nextId(items, prefix) {
58
+ const max = items.reduce((highest, item) => {
59
+ const match = new RegExp(`^${prefix}-(\\d+)$`).exec(item.id || '');
60
+ return match ? Math.max(highest, Number(match[1])) : highest;
61
+ }, 0);
62
+ return `${prefix}-${String(max + 1).padStart(3, '0')}`;
63
+ }
64
+
65
+ function asObjects(values, key) {
66
+ if (!values) return [];
67
+ if (!Array.isArray(values)) throw new Error(`${key} must be an array`);
68
+ return values.map((value) => typeof value === 'string' ? { [key]: value } : value);
69
+ }
70
+
71
+ export function findRoot(from = process.cwd()) {
72
+ if (runtimePaths && existsSync(runtimePaths.state)) return runtimePaths.root;
73
+ let cursor = resolve(from);
74
+ while (true) {
75
+ if (existsSync(join(cursor, '.skeinn', 'state.json'))) return cursor;
76
+ if (existsSync(join(cursor, '.loom', 'state.json'))) {
77
+ throw new Error('Found a legacy .loom/ project. Rename .loom/ to .skeinn/, update any .loom/ paths in tasks.json and AGENTS.md, then run skeinn check.');
78
+ }
79
+ const parent = dirname(cursor);
80
+ if (parent === cursor) break;
81
+ cursor = parent;
82
+ }
83
+ throw new Error('Skeinn is not initialized. Run skeinn init in the project root.');
84
+ }
85
+
86
+ export function skeinnPaths(root = findRoot()) {
87
+ const absolute = resolve(root);
88
+ const skeinn = runtimePaths?.root === absolute ? runtimePaths.skeinn : join(absolute, '.skeinn');
89
+ return skeinnPathsShape(absolute, skeinn);
90
+ }
91
+
92
+ export function configureRuntime({ stateDir } = {}) {
93
+ if (!stateDir) {
94
+ runtimePaths = null;
95
+ return null;
96
+ }
97
+ const root = resolve(process.cwd());
98
+ const skeinn = resolve(stateDir);
99
+ const fromWorkspace = relative(root, skeinn);
100
+ if (!fromWorkspace || (!fromWorkspace.startsWith('..') && !isAbsolute(fromWorkspace))) {
101
+ throw new Error('--state-dir must be outside the scored workspace');
102
+ }
103
+ runtimePaths = skeinnPathsShape(root, skeinn);
104
+ return { workspace: root, state_dir: skeinn };
105
+ }
106
+
107
+ export function initProject(root = process.cwd()) {
108
+ const paths = skeinnPathsForInit(root);
109
+ if (existsSync(paths.state)) return { initialized: false, root: paths.root, reason: 'already_initialized' };
110
+ if (paths.skeinn === join(paths.root, '.skeinn') && existsSync(join(paths.root, '.loom', 'state.json'))) {
111
+ throw new Error('Found a legacy .loom/ project. Rename .loom/ to .skeinn/, update any .loom/ paths in tasks.json and AGENTS.md, then run skeinn check.');
112
+ }
113
+ if (existsSync(join(paths.skeinn, 'current')) || existsSync(join(paths.skeinn, 'v1'))) {
114
+ throw new Error('A legacy Skeinn project was found. Back it up and migrate deliberately; v2 will not overwrite it.');
115
+ }
116
+ mkdirSync(paths.design, { recursive: true });
117
+ mkdirSync(paths.capabilities, { recursive: true });
118
+ mkdirSync(paths.eval, { recursive: true });
119
+ const state = {
120
+ schema_version: SCHEMA_VERSION,
121
+ project: { name: basename(paths.root), status: 'shaping', created_at: now(), updated_at: now() },
122
+ understanding: { confirmed: [], assumptions: [], unresolved: [] },
123
+ keeper: { status: 'not_run', attempts: [] },
124
+ };
125
+ atomicJson(paths.state, state);
126
+ atomicJson(paths.tasks, { schema_version: SCHEMA_VERSION, tasks: [] });
127
+ atomicJson(paths.deliverables, { schema_version: SCHEMA_VERSION, deliverables: [] });
128
+ writeFileSync(paths.project, PROJECT_TEMPLATE, 'utf8');
129
+ writeFileSync(paths.structure, STRUCTURE_TEMPLATE, 'utf8');
130
+ writeFileSync(paths.decisions, '# Decision History\n\nCurrent truth belongs in PROJECT.md and linked design documents. This file preserves consequential superseding decisions.\n', 'utf8');
131
+ const anchored = paths.skeinn === join(paths.root, '.skeinn');
132
+ if (anchored) installAgentAnchor(paths.root);
133
+ return {
134
+ initialized: true,
135
+ root: paths.root,
136
+ files: ['.skeinn/PROJECT.md', '.skeinn/STRUCTURE.md', '.skeinn/DECISIONS.md', '.skeinn/state.json', '.skeinn/tasks.json', '.skeinn/deliverables.json', '.skeinn/design/', '.skeinn/capabilities/', ...(anchored ? ['AGENTS.md'] : [])],
137
+ next: 'Replace the template text in .skeinn/PROJECT.md and .skeinn/STRUCTURE.md with this project\u2019s truth, then shape the whole: skeinn record \u2192 iterate core Design surfaces (skeinn design add) and 1\u20133 bottleneck Capabilities (skeinn capability add, or skeinn capability exempt --reason) \u2192 skeinn deliverable add \u2192 skeinn task plan. Run `skeinn help shaping` for what each layer buys you.',
138
+ };
139
+ }
140
+
141
+ function skeinnPathsForInit(root) {
142
+ const absolute = resolve(root);
143
+ const skeinn = runtimePaths?.root === absolute ? runtimePaths.skeinn : join(absolute, '.skeinn');
144
+ return skeinnPathsShape(absolute, skeinn);
145
+ }
146
+
147
+ function skeinnPathsShape(root, skeinn) {
148
+ return {
149
+ root,
150
+ skeinn,
151
+ state: join(skeinn, 'state.json'),
152
+ tasks: join(skeinn, 'tasks.json'),
153
+ deliverables: join(skeinn, 'deliverables.json'),
154
+ project: join(skeinn, 'PROJECT.md'),
155
+ structure: join(skeinn, 'STRUCTURE.md'),
156
+ decisions: join(skeinn, 'DECISIONS.md'),
157
+ design: join(skeinn, 'design'),
158
+ capabilities: join(skeinn, 'capabilities'),
159
+ eval: join(skeinn, 'eval'),
160
+ };
161
+ }
162
+
163
+ function installAgentAnchor(root) {
164
+ const path = join(root, 'AGENTS.md');
165
+ const marker = '<!-- skeinn:v2 -->';
166
+ if (!existsSync(path)) writeFileSync(path, `${AGENT_ANCHOR}\n`, 'utf8');
167
+ else if (!readFileSync(path, 'utf8').includes(marker)) appendFileSync(path, `\n${AGENT_ANCHOR}\n`, 'utf8');
168
+ }
169
+
170
+ export function loadProject(root = findRoot()) {
171
+ const paths = skeinnPaths(root);
172
+ mkdirSync(paths.design, { recursive: true });
173
+ mkdirSync(paths.capabilities, { recursive: true });
174
+ mkdirSync(paths.eval, { recursive: true });
175
+ const state = readJson(paths.state, 'state.json');
176
+ const taskStore = readJson(paths.tasks, 'tasks.json');
177
+ const deliverableStore = existsSync(paths.deliverables) ? readJson(paths.deliverables, 'deliverables.json') : { schema_version: SCHEMA_VERSION, deliverables: [] };
178
+ validateState(state);
179
+ validateTasks(taskStore.tasks);
180
+ ensureClarify(state);
181
+ ensureKeeperState(state);
182
+ return { paths, state, taskStore, deliverableStore };
183
+ }
184
+
185
+
186
+ function ensureKeeperState(state) {
187
+ if (!state.keeper || typeof state.keeper !== 'object') state.keeper = { status: 'not_run', attempts: [] };
188
+ if (!Array.isArray(state.keeper.attempts)) state.keeper.attempts = [];
189
+ if (!Array.isArray(state.keeper.findings)) state.keeper.findings = [];
190
+ if (!Array.isArray(state.keeper.checkpoints)) state.keeper.checkpoints = [];
191
+ if (!state.keeper.reviewed_digests || typeof state.keeper.reviewed_digests !== 'object') state.keeper.reviewed_digests = {};
192
+ if (typeof state.keeper.launch_completed !== 'boolean') state.keeper.launch_completed = ['passed', 'passed_with_advisories', 'skipped'].includes(state.keeper.status);
193
+ return state.keeper;
194
+ }
195
+
196
+ function sha256Text(text) {
197
+ return createHash('sha256').update(text).digest('hex');
198
+ }
199
+
200
+ export function artifactDigests(paths, tasks, state = null) {
201
+ const map = {};
202
+ map['.skeinn/PROJECT.md'] = sha256Text(readFileSync(paths.project, 'utf8'));
203
+ if (existsSync(paths.structure)) map['.skeinn/STRUCTURE.md'] = sha256Text(readFileSync(paths.structure, 'utf8'));
204
+ map['.skeinn/DECISIONS.md'] = sha256Text(readFileSync(paths.decisions, 'utf8'));
205
+ if (state?.capability_exemption) map['state:capability_exemption'] = sha256Text(JSON.stringify(state.capability_exemption));
206
+ for (const name of readdirSync(paths.design).filter((file) => file.endsWith('.md')).sort()) {
207
+ map[`.skeinn/design/${name}`] = sha256Text(readFileSync(join(paths.design, name), 'utf8'));
208
+ }
209
+ for (const name of listCapabilities(paths.root)) {
210
+ const capFile = capabilityPath(paths, name);
211
+ const ref = normalizeRef(paths, capFile);
212
+ const statusPath = join(paths.capabilities, name, 'status.json');
213
+ const combined = readFileSync(capFile, 'utf8') + (existsSync(statusPath) ? readFileSync(statusPath, 'utf8') : '');
214
+ map[ref] = sha256Text(combined);
215
+ }
216
+ for (const task of tasks) {
217
+ const { progress, evidence, status, updated_at, completed_at, reopened_at, block, ...definition } = task;
218
+ map[`task:${task.id}`] = sha256Text(JSON.stringify(definition));
219
+ }
220
+ return map;
221
+ }
222
+
223
+ function overallDigest(digestMap) {
224
+ const hash = createHash('sha256');
225
+ for (const key of Object.keys(digestMap).sort()) hash.update(`${key}:${digestMap[key]}
226
+ `);
227
+ return hash.digest('hex');
228
+ }
229
+
230
+ export function activeHorizon(tasks, paths, depth = 2) {
231
+ const done = new Set(tasks.filter((t) => t.status === 'done').map((t) => t.id));
232
+ const byId = new Map(tasks.map((t) => [t.id, t]));
233
+ const selected = new Set();
234
+ let frontier = tasks
235
+ .filter((t) => t.status === 'active' || (t.status === 'open' && t.depends_on.every((d) => done.has(d))))
236
+ .map((t) => t.id);
237
+ for (const id of frontier) selected.add(id);
238
+ for (let hop = 0; hop < depth; hop += 1) {
239
+ const nextLayer = [];
240
+ for (const t of tasks) {
241
+ if (selected.has(t.id) || t.status !== 'open') continue;
242
+ if (t.depends_on.some((d) => selected.has(d)) && t.depends_on.every((d) => done.has(d) || selected.has(d))) {
243
+ nextLayer.push(t.id);
244
+ }
245
+ }
246
+ if (!nextLayer.length) break;
247
+ for (const id of nextLayer) selected.add(id);
248
+ }
249
+ const artifacts = new Set(['.skeinn/PROJECT.md', '.skeinn/DECISIONS.md']);
250
+ if (existsSync(paths.structure)) artifacts.add('.skeinn/STRUCTURE.md');
251
+ let sawCapability = false;
252
+ for (const id of selected) {
253
+ const t = byId.get(id);
254
+ if (!t) continue;
255
+ artifacts.add(`task:${t.id}`);
256
+ for (const ref of t.reads || []) {
257
+ const norm = ref.replaceAll('\\', '/');
258
+ if (norm.startsWith('.skeinn/')) artifacts.add(norm);
259
+ if (norm.startsWith('.skeinn/capabilities/')) sawCapability = true;
260
+ }
261
+ if (t.implements?.trim()) {
262
+ const ref = t.implements.trim().split('#')[0].replaceAll('\\', '/');
263
+ if (ref.startsWith('.skeinn/')) artifacts.add(ref);
264
+ }
265
+ }
266
+ // Ensure capability files (or exemption) are always audited in the horizon
267
+ if (!sawCapability) {
268
+ for (const name of listCapabilities(paths.root)) artifacts.add(normalizeRef(paths, capabilityPath(paths, name)));
269
+ }
270
+ return { taskIds: [...selected], artifacts: [...artifacts].sort() };
271
+ }
272
+
273
+ function computeDirtyArtifacts(currentMap, baselineMap, scopeKeys = null) {
274
+ const keys = scopeKeys ? scopeKeys.filter((k) => k in currentMap) : Object.keys(currentMap);
275
+ return keys.filter((k) => currentMap[k] !== baselineMap?.[k]).sort();
276
+ }
277
+
278
+ const SILENT_DRIFT_TASK_THRESHOLD = 5;
279
+
280
+ // The clean-review watermark only advances on a 'clean' checkpoint or a passed Launch.
281
+ // drift_detected/blocked verdicts deliberately do NOT refresh it — a failed audit cannot silence the bell.
282
+ function cleanReviewBaselineAt(state) {
283
+ const cleanCheckpoints = (state.keeper.checkpoints || []).filter((c) => c.verdict === 'clean');
284
+ if (cleanCheckpoints.length) return cleanCheckpoints.at(-1).at || '';
285
+ const passes = (state.keeper.attempts || []).filter((a) => ['passed', 'passed_with_advisories'].includes(a.verdict));
286
+ if (passes.length) return passes.at(-1).at || '';
287
+ return state.project?.created_at || '';
288
+ }
289
+
290
+ // Delivery Tasks finished since the last clean independent review — the silent-drift bell.
291
+ // Pure derivation: no new state field; resets automatically when a clean checkpoint records.
292
+ function deliveryTasksDoneSinceCleanReview(state, tasks) {
293
+ const baselineAt = cleanReviewBaselineAt(state);
294
+ return tasks.filter((t) => t.status === 'done' && (t.kind || 'delivery') !== 'spike' && (t.completed_at || t.updated_at || '') > baselineAt);
295
+ }
296
+
297
+ function silentDriftAlert(state, tasks) {
298
+ if (!state.keeper.launch_completed) return [];
299
+ return deliveryTasksDoneSinceCleanReview(state, tasks);
300
+ }
301
+
302
+ function normalizeFindingKey(scope, text) {
303
+ return `${(scope || 'project').trim().toLowerCase()}::${String(text || '').trim().toLowerCase()}`;
304
+ }
305
+
306
+ function upsertFindings(state, rawItems, { sourceRunId, defaultSeverity = 'blocking' } = {}) {
307
+ const keeper = ensureKeeperState(state);
308
+ const touched = [];
309
+ for (const raw of rawItems || []) {
310
+ const text = typeof raw === 'string' ? raw.trim() : (raw?.gap || raw?.text || '').trim();
311
+ if (!text) continue;
312
+ const scope = (typeof raw === 'object' && raw?.scope ? String(raw.scope).trim() : '') || 'project';
313
+ const severity = (typeof raw === 'object' && ['blocking', 'minor'].includes(raw?.severity)) ? raw.severity : defaultSeverity;
314
+ const key = normalizeFindingKey(scope, text);
315
+ const existing = keeper.findings.find((f) => f.status === 'open' && normalizeFindingKey(f.scope, f.text) === key);
316
+ if (existing) {
317
+ if (severity === 'blocking') existing.severity = 'blocking';
318
+ existing.updated_at = now();
319
+ touched.push(existing);
320
+ } else {
321
+ const entry = {
322
+ id: nextId(keeper.findings, 'FND'),
323
+ scope,
324
+ text,
325
+ severity,
326
+ status: 'open',
327
+ source_run_id: sourceRunId || '',
328
+ closure_evidence: '',
329
+ at: now(),
330
+ };
331
+ keeper.findings.push(entry);
332
+ touched.push(entry);
333
+ }
334
+ }
335
+ return touched;
336
+ }
337
+
338
+ function findingsForTask(state, task) {
339
+ const keeper = ensureKeeperState(state);
340
+ const scopes = new Set([task.id]);
341
+ for (const ref of task.reads || []) scopes.add(ref.replaceAll('\\', '/'));
342
+ if (task.implements?.trim()) scopes.add(task.implements.trim().split('#')[0].replaceAll('\\', '/'));
343
+ return keeper.findings.filter((f) => f.status === 'open' && scopes.has(f.scope));
344
+ }
345
+
346
+ function ensureClarify(state) {
347
+ if (!state.clarify || typeof state.clarify !== 'object') state.clarify = { active: false, reason: '', started_at: '', closed_at: '', rounds: [] };
348
+ if (!Array.isArray(state.clarify.rounds)) state.clarify.rounds = [];
349
+ return state.clarify;
350
+ }
351
+
352
+ function validateState(state) {
353
+ if (state.schema_version !== SCHEMA_VERSION) throw new Error(`Unsupported schema_version ${state.schema_version}`);
354
+ if (!VALID_PROJECT_STATUS.has(state.project?.status)) throw new Error('Invalid project status');
355
+ for (const key of ['confirmed', 'assumptions', 'unresolved']) {
356
+ if (!Array.isArray(state.understanding?.[key])) throw new Error(`understanding.${key} must be an array`);
357
+ }
358
+ }
359
+
360
+ function validateTasks(tasks) {
361
+ if (!Array.isArray(tasks)) throw new Error('tasks.json tasks must be an array');
362
+ const ids = new Set();
363
+ let active = 0;
364
+ for (const task of tasks) {
365
+ if (!task.id || ids.has(task.id)) throw new Error(`Task id is missing or duplicated: ${task.id || '<missing>'}`);
366
+ ids.add(task.id);
367
+ if (!task.title || !task.outcome) throw new Error(`${task.id} requires title and outcome`);
368
+ if (task.outcome.length < 20) throw new Error(`${task.id} outcome must be at least 20 characters describing the observable difference`);
369
+ if (!VALID_TASK_STATUS.has(task.status)) throw new Error(`${task.id} has invalid status ${task.status}`);
370
+ if (!Array.isArray(task.depends_on) || !Array.isArray(task.reads)) throw new Error(`${task.id} dependencies and reads must be arrays`);
371
+ if (!task.reads.length) throw new Error(`${task.id} reads must list at least one specific file or artifact`);
372
+ if (!Array.isArray(task.touches) || !task.touches.length) throw new Error(`${task.id} touches must list at least one specific file or artifact`);
373
+ if (!Array.isArray(task.boundaries) || !task.boundaries.length) throw new Error(`${task.id} boundaries must list at least one thing this Task does NOT do`);
374
+ const hasAcceptance = Array.isArray(task.acceptance) && task.acceptance.length > 0;
375
+ const hasDoneWhen = Array.isArray(task.done_when) && task.done_when.length > 0;
376
+ if (!hasAcceptance && !hasDoneWhen) throw new Error(`${task.id} requires acceptance[] (preferred) or done_when[]`);
377
+ if (hasAcceptance) {
378
+ for (const acc of task.acceptance) {
379
+ if (!acc || typeof acc !== 'object') throw new Error(`${task.id} acceptance entries must be objects`);
380
+ if (!acc.criterion || typeof acc.criterion !== 'string') throw new Error(`${task.id} acceptance entry missing criterion (what must be true for this condition to pass)`);
381
+ if (!acc.verify_by || typeof acc.verify_by !== 'string') throw new Error(`${task.id} acceptance entry missing verify_by (how to check)`);
382
+ if (acc.evidence !== undefined && typeof acc.evidence !== 'string') throw new Error(`${task.id} acceptance evidence must be a string`);
383
+ }
384
+ }
385
+ if (task.implements !== undefined && typeof task.implements !== 'string') throw new Error(`${task.id} implements must be a string referencing a design decision`);
386
+ if (task.design_exemption !== undefined && (typeof task.design_exemption !== 'string' || (task.design_exemption && task.design_exemption.length < 10))) throw new Error(`${task.id} design_exemption must be a concrete reason`);
387
+ if (task.capability_exemption !== undefined && (typeof task.capability_exemption !== 'string' || (task.capability_exemption && task.capability_exemption.length < 10))) throw new Error(`${task.id} capability_exemption must be a concrete reason`);
388
+ if (task.kind !== undefined && !['delivery', 'spike'].includes(task.kind)) throw new Error(`${task.id} kind must be delivery or spike`);
389
+ if (task.guardrails !== undefined) {
390
+ if (!Array.isArray(task.guardrails)) throw new Error(`${task.id} guardrails must be an array of strings`);
391
+ for (const rule of task.guardrails) if (typeof rule !== 'string' || !rule.trim()) throw new Error(`${task.id} guardrails entries must be non-empty strings`);
392
+ }
393
+ if (task.integrity_version !== undefined && task.integrity_version !== 1) throw new Error(`${task.id} integrity_version is unsupported`);
394
+ if (task.capability_hooks !== undefined) {
395
+ if (!Array.isArray(task.capability_hooks)) throw new Error(`${task.id} capability_hooks must be an array`);
396
+ for (const hook of task.capability_hooks) {
397
+ if (!hook || typeof hook !== 'object' || typeof hook.node !== 'string' || !hook.node.includes('#')) throw new Error(`${task.id} capability_hooks entry must have a node field like "capability-slug#C1"`);
398
+ if (hook.at !== undefined && typeof hook.at !== 'string') throw new Error(`${task.id} capability_hooks at must be a string`);
399
+ if (hook.must_produce !== undefined && typeof hook.must_produce !== 'string') throw new Error(`${task.id} capability_hooks must_produce must be a string`);
400
+ }
401
+ }
402
+ if (task.covers !== undefined) {
403
+ if (!Array.isArray(task.covers)) throw new Error(`${task.id} covers must be an array of deliverable IDs`);
404
+ for (const dlvId of task.covers) if (typeof dlvId !== 'string') throw new Error(`${task.id} covers entries must be deliverable ID strings`);
405
+ }
406
+ if (task.status === 'active') active += 1;
407
+ }
408
+ if (active > 1) throw new Error('Only one Task may be active');
409
+ const taskById = new Map(tasks.map((task) => [task.id, task]));
410
+ for (const task of tasks) {
411
+ for (const dep of task.depends_on) if (!ids.has(dep)) throw new Error(`${task.id} depends on missing Task ${dep}`);
412
+ }
413
+ // A spike produces empirical findings, not deliverables: delivery Tasks must never wire one into the DAG.
414
+ // Checked here (not at import) so `task update` cannot retro-fit a depended-on Task into a spike either.
415
+ for (const task of tasks) {
416
+ if ((task.kind || 'delivery') === 'spike') continue;
417
+ for (const dep of task.depends_on) {
418
+ if (taskById.get(dep)?.kind === 'spike') throw new Error(`${task.id} cannot depend on spike Task ${dep}; distill spike findings into Design/Capability or skeinn record instead of wiring a spike into the delivery DAG.`);
419
+ }
420
+ }
421
+ detectCycles(tasks);
422
+ }
423
+
424
+ function detectCycles(tasks) {
425
+ const map = new Map(tasks.map((task) => [task.id, task.depends_on]));
426
+ const visiting = new Set();
427
+ const visited = new Set();
428
+ function visit(id) {
429
+ if (visiting.has(id)) throw new Error(`Task dependency cycle includes ${id}`);
430
+ if (visited.has(id)) return;
431
+ visiting.add(id);
432
+ for (const dep of map.get(id) || []) visit(dep);
433
+ visiting.delete(id);
434
+ visited.add(id);
435
+ }
436
+ for (const id of map.keys()) visit(id);
437
+ }
438
+
439
+ export function recordUnderstanding(payload, root = findRoot()) {
440
+ const { paths, state } = loadProject(root);
441
+ for (const item of asObjects(payload.confirmed, 'text')) {
442
+ if (!item.text) throw new Error('Confirmed fact requires text');
443
+ state.understanding.confirmed.push({ id: nextId(state.understanding.confirmed, 'F'), text: item.text, source: item.source || 'conversation', at: now() });
444
+ }
445
+ for (const item of asObjects(payload.assumptions, 'text')) {
446
+ if (!item.text) throw new Error('Assumption requires text');
447
+ state.understanding.assumptions.push({ id: nextId(state.understanding.assumptions, 'A'), text: item.text, status: 'active', source: item.source || 'agent', at: now() });
448
+ }
449
+ for (const item of asObjects(payload.unresolved, 'question')) {
450
+ if (!item.question) throw new Error('Unresolved item requires question');
451
+ state.understanding.unresolved.push({ id: nextId(state.understanding.unresolved, 'Q'), question: item.question, impact: item.impact || 'medium', status: 'open', at: now() });
452
+ }
453
+ for (const item of payload.resolved || []) {
454
+ const target = state.understanding.unresolved.find((candidate) => candidate.id === item.id);
455
+ if (!target) throw new Error(`Unknown unresolved id ${item.id}`);
456
+ target.status = item.status === 'skipped' ? 'skipped' : 'resolved';
457
+ target.resolution = item.resolution || '';
458
+ target.resolved_at = now();
459
+ }
460
+ for (const id of payload.retire_assumptions || []) {
461
+ const target = state.understanding.assumptions.find((candidate) => candidate.id === id);
462
+ if (!target) throw new Error(`Unknown assumption id ${id}`);
463
+ target.status = 'retired';
464
+ }
465
+ if (payload.project_status) throw new Error('Project status is controlled by ready, Keeper, and Task commands');
466
+ for (const decision of payload.decisions || []) appendDecision(paths.decisions, decision, state);
467
+ state.project.updated_at = now();
468
+ atomicJson(paths.state, state);
469
+ return { ...state.understanding, next: 'Keep shaping: iterate core Design surfaces (skeinn design add) and 1–3 bottleneck Capabilities (skeinn capability add <slug> --title <field>, or skeinn capability exempt --reason), then skeinn deliverable add and skeinn task plan. skeinn context names the current frontier.' };
470
+ }
471
+
472
+ function appendDecision(path, decision, state) {
473
+ if (!decision.title || !decision.decision || !decision.rationale) throw new Error('Decision requires title, decision, and rationale');
474
+ const prior = state.decision_ids || [];
475
+ const id = nextId(prior.map((value) => ({ id: value })), 'D');
476
+ state.decision_ids = [...prior, id];
477
+ const supersedes = decision.supersedes?.length ? decision.supersedes.join(', ') : 'none';
478
+ appendFileSync(path, `\n## ${id}: ${decision.title}\n\n- Current decision: ${decision.decision}\n- Rationale: ${decision.rationale}\n- Source: ${decision.source || 'conversation'}\n- Supersedes: ${supersedes}\n- Affects: ${(decision.affects || []).join(', ') || 'project-wide or not yet classified'}\n- Recorded: ${now()}\n`, 'utf8');
479
+ }
480
+
481
+ export function createDesign(slug, options = {}, root = findRoot()) {
482
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) throw new Error('Design slug must use lowercase letters, numbers, and hyphens');
483
+ if (!options.title) throw new Error('Design document requires --title');
484
+ if (!DESIGN_KINDS.includes(options.kind)) throw new Error(`Design kind must be one of: ${DESIGN_KINDS.join(', ')}`);
485
+ const { paths } = loadProject(root);
486
+ const path = join(paths.design, `${slug}.md`);
487
+ if (existsSync(path)) throw new Error(`Design document already exists: ${slug}`);
488
+ writeFileSync(path, designTemplate({ title: options.title, kind: options.kind }), 'utf8');
489
+ return {
490
+ slug,
491
+ kind: options.kind,
492
+ path: relative(paths.root, path).replaceAll('\\', '/'),
493
+ next: `Fill every section of .skeinn/design/${slug}.md with project-specific decisions — template text fails skeinn project ready. Compare at least two genuinely viable alternatives and compile applied capability rules into concrete mechanisms, then skeinn deliverable add → skeinn task plan.`,
494
+ };
495
+ }
496
+
497
+ export function listDesigns(root = findRoot()) {
498
+ const { paths } = loadProject(root);
499
+ return readdirSync(paths.design).filter((name) => name.endsWith('.md')).sort();
500
+ }
501
+
502
+ export function getDesign(slug, root = findRoot()) {
503
+ const { paths } = loadProject(root);
504
+ const name = slug.endsWith('.md') ? slug : `${slug}.md`;
505
+ if (basename(name) !== name) throw new Error('Invalid design document name');
506
+ const path = join(paths.design, name);
507
+ if (!existsSync(path)) throw new Error(`Design document not found: ${slug}`);
508
+ return readFileSync(path, 'utf8');
509
+ }
510
+
511
+ function capabilitySlug(name) {
512
+ return name.endsWith('.md') ? name.slice(0, -3) : name;
513
+ }
514
+
515
+ function isLegacyDirectoryCapability(paths, name) {
516
+ const slug = capabilitySlug(name);
517
+ return existsSync(join(paths.capabilities, slug, 'capability.md'));
518
+ }
519
+
520
+ function parseSingleFileCapabilityMeta(content) {
521
+ const modeMatch = content.match(/^-\s*Mode:\s*([^\n]+)/m);
522
+ const authorityMatch = content.match(/^-\s*Authority:\s*([^\n]+)/m);
523
+ const scenarioMatch = content.match(/^-\s*Scenario:\s*([^\n]+)/m);
524
+ return {
525
+ mode: modeMatch ? modeMatch[1].trim() : 'external_researched',
526
+ authority: authorityMatch ? authorityMatch[1].trim() : 'agent_provisional',
527
+ scenario: scenarioMatch ? scenarioMatch[1].trim() : '',
528
+ };
529
+ }
530
+
531
+ export function createCapability(slug, options = {}, root = findRoot()) {
532
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) throw new Error('Capability slug must use lowercase letters, numbers, and hyphens');
533
+ if (!options.title) throw new Error('Capability requires --title');
534
+ const mode = options.mode || 'external_researched';
535
+ if (!CAPABILITY_MODES.includes(mode)) throw new Error(`Capability --mode must be one of: ${CAPABILITY_MODES.join(', ')}`);
536
+ const { paths, state } = loadProject(root);
537
+ const filePath = join(paths.capabilities, `${slug}.md`);
538
+ const legacyDirPath = join(paths.capabilities, slug);
539
+ if (existsSync(filePath) || existsSync(legacyDirPath)) throw new Error(`Capability already exists: ${slug}`);
540
+ writeFileSync(filePath, CAPABILITY_TEMPLATE({ title: options.title, mode }), 'utf8');
541
+ if (state.capability_exemption) {
542
+ delete state.capability_exemption;
543
+ state.project.updated_at = now();
544
+ atomicJson(paths.state, state);
545
+ }
546
+ return {
547
+ slug,
548
+ mode,
549
+ path: relative(paths.root, filePath).replaceAll('\\', '/'),
550
+ next: `Research how real practitioners operate in this field, reflect on this project's constraints, and fill .skeinn/capabilities/${slug}.md (including concrete operational rules and Before -> After Design delta). If external search is unavailable, set Mode: offline_reflection honestly rather than citing agent-authored sources. Run skeinn help capability for the quality bar.`,
551
+ };
552
+ }
553
+
554
+ export function exemptCapabilities(reason, root = findRoot()) {
555
+ if (!reason || reason.trim().length < 15) throw new Error('Capability exemption requires a concrete --reason (at least 15 characters explaining why standard engineering suffices without specialist domain research)');
556
+ const { paths, state } = loadProject(root);
557
+ const existing = listCapabilities(root);
558
+ if (existing.length) throw new Error(`Cannot exempt capabilities while capability files already exist: ${existing.join(', ')}`);
559
+ state.capability_exemption = { reason: reason.trim(), at: now() };
560
+ state.project.updated_at = now();
561
+ atomicJson(paths.state, state);
562
+ return {
563
+ exempted: true,
564
+ reason: state.capability_exemption.reason,
565
+ next: 'Exemption recorded. Keeper will audit whether standard engineering genuinely suffices for this project. Continue shaping Design and Tasks, then run skeinn project ready.',
566
+ };
567
+ }
568
+
569
+ export function listCapabilities(root = findRoot()) {
570
+ const { paths } = loadProject(root);
571
+ const entries = readdirSync(paths.capabilities, { withFileTypes: true });
572
+ const names = entries
573
+ .filter((entry) => (entry.isDirectory() && existsSync(join(paths.capabilities, entry.name, 'capability.md'))) || (entry.isFile() && entry.name.endsWith('.md')))
574
+ .map((entry) => (entry.isDirectory() ? entry.name : entry.name.slice(0, -3)))
575
+ .sort();
576
+ return names;
577
+ }
578
+
579
+ export function getCapability(slug, root = findRoot()) {
580
+ const { paths } = loadProject(root);
581
+ const cleanSlug = capabilitySlug(slug);
582
+ if (basename(cleanSlug) !== cleanSlug) throw new Error('Invalid capability name');
583
+ const filePath = join(paths.capabilities, `${cleanSlug}.md`);
584
+ if (existsSync(filePath)) return readFileSync(filePath, 'utf8');
585
+ const dirCapability = join(paths.capabilities, cleanSlug, 'capability.md');
586
+ if (existsSync(dirCapability)) return readFileSync(dirCapability, 'utf8');
587
+ throw new Error(`Capability not found: ${slug}`);
588
+ }
589
+
590
+ export function researchCapability(slug, options = {}, root = findRoot()) {
591
+ const { paths } = loadProject(root);
592
+ const cleanSlug = capabilitySlug(slug);
593
+ const singleFile = join(paths.capabilities, `${cleanSlug}.md`);
594
+ if (existsSync(singleFile)) {
595
+ return {
596
+ slug: cleanSlug,
597
+ mode: parseSingleFileCapabilityMeta(readFileSync(singleFile, 'utf8')).mode,
598
+ path: relative(paths.root, singleFile).replaceAll('\\', '/'),
599
+ next: `Skeinn 2.4+ uses single-file capabilities. Write real practitioner findings and verifiable sources directly into .skeinn/capabilities/${cleanSlug}.md under "## How real practitioners operate".`,
600
+ };
601
+ }
602
+ if (!options.field) throw new Error('Research requires --field <professional-field>');
603
+ const dir = join(paths.capabilities, cleanSlug);
604
+ if (!existsSync(dir)) throw new Error(`Capability not found: ${slug}. Run skeinn capability add ${cleanSlug} --title <text> first.`);
605
+ const statusPath = join(dir, 'status.json');
606
+ if (!existsSync(statusPath)) throw new Error(`Capability ${slug} is not a research-directory dossier`);
607
+ const status = readJson(statusPath, 'status.json');
608
+ if (status.status === 'confirmed') {
609
+ status.reopened_at = now();
610
+ status.reopen_reason = options.reopen_reason || 'new evidence requires updating the capability';
611
+ }
612
+ status.field = options.field;
613
+ status.status = 'researching';
614
+ status.updated_at = now();
615
+ atomicJson(statusPath, status);
616
+ const researchDir = join(dir, 'research');
617
+ mkdirSync(researchDir, { recursive: true });
618
+ const guidePath = join(researchDir, '_guide.md');
619
+ if (!existsSync(guidePath)) writeFileSync(guidePath, RESEARCH_GUIDE, 'utf8');
620
+ return {
621
+ slug: cleanSlug,
622
+ field: options.field,
623
+ research_dir: relative(paths.root, researchDir).replaceAll('\\', '/'),
624
+ status: 'researching',
625
+ next: `Add .md files to research/ then run skeinn capability synthesize ${cleanSlug}.`,
626
+ };
627
+ }
628
+
629
+ export function synthesizeCapability(slug, root = findRoot()) {
630
+ const { paths } = loadProject(root);
631
+ const cleanSlug = capabilitySlug(slug);
632
+ const singleFile = join(paths.capabilities, `${cleanSlug}.md`);
633
+ if (existsSync(singleFile)) {
634
+ const content = readFileSync(singleFile, 'utf8');
635
+ const issues = validateSingleFileCapability(cleanSlug, content);
636
+ if (issues.length) throw new Error(`Capability ${cleanSlug} is not ready:\n- ${issues.join('\n- ')}`);
637
+ const meta = parseSingleFileCapabilityMeta(content);
638
+ return { slug: cleanSlug, mode: meta.mode, authority: meta.authority, valid: true, next: `Apply ${cleanSlug}'s operational rules and Design delta into your Design documents, or upgrade authority with skeinn capability confirm ${cleanSlug} --scenario "<text>" --source human.` };
639
+ }
640
+ const dir = join(paths.capabilities, cleanSlug);
641
+ if (!existsSync(dir)) throw new Error(`Capability not found: ${slug}`);
642
+ const statusPath = join(dir, 'status.json');
643
+ if (!existsSync(statusPath)) throw new Error(`Capability ${slug} is not a research-directory dossier`);
644
+ const status = readJson(statusPath, 'status.json');
645
+ if (status.status === 'confirmed') throw new Error(`Capability ${slug} is confirmed; run skeinn capability research ${slug} --field <text> to reopen it with new evidence`);
646
+ const researchDir = join(dir, 'research');
647
+ const materials = readdirSync(researchDir).filter((f) => f.endsWith('.md') && f !== '_guide.md').sort();
648
+ if (!materials.length) throw new Error(`No research materials found in ${slug}/research/.`);
649
+ const capPath = join(dir, 'capability.md');
650
+ const content = readFileSync(capPath, 'utf8');
651
+ const nodePattern = /### (C\d+):/g;
652
+ const nodes = [...content.matchAll(nodePattern)].map((m) => m[1]);
653
+ if (!nodes.length) throw new Error('Capability has no decision tree nodes (### C1, C2, ...). Add nodes before synthesizing.');
654
+ const missingSources = [];
655
+ const missingCounterexamples = [];
656
+ const danglingSources = [];
657
+ const materialNames = materials.flatMap((f) => [f, f.slice(0, -3)]);
658
+ for (const node of nodes) {
659
+ const nodeSection = content.split(`### ${node}:`)[1]?.split('### ')[0] || '';
660
+ if (!nodeSection.includes('source:')) missingSources.push(node);
661
+ else {
662
+ const sourceMatch = nodeSection.match(/source:\s*(.+)(?:\n|$)/);
663
+ const cited = sourceMatch ? sourceMatch[1].trim() : '';
664
+ if (cited && !materialNames.some((name) => cited.includes(name))) danglingSources.push(node);
665
+ }
666
+ if (!nodeSection.includes('counterexample:')) missingCounterexamples.push(node);
667
+ }
668
+ if (missingSources.length) throw new Error(`Decision tree nodes missing source citations: ${missingSources.join(', ')}. Every node must reference a research material.`);
669
+ if (danglingSources.length) throw new Error(`Decision tree nodes cite sources not found in research/: ${danglingSources.join(', ')}. The source field should reference one of the research files.`);
670
+ if (missingCounterexamples.length) throw new Error(`Decision tree nodes missing counterexamples: ${missingCounterexamples.join(', ')}. Every node must have a counterexample (a situation where an expert would NOT walk this path).`);
671
+ status.status = 'synthesized';
672
+ status.updated_at = now();
673
+ atomicJson(statusPath, status);
674
+ return { slug: cleanSlug, status: 'synthesized', nodes: nodes.length, materials: materials.length, next: `Run skeinn capability confirm ${cleanSlug} --scenario <text> --source human|agent.` };
675
+ }
676
+
677
+ export function confirmCapability(slug, options = {}, root = findRoot()) {
678
+ if (!options.scenario || options.scenario.length < 20) throw new Error('Confirm requires --scenario <text> (at least 20 characters describing the project situation this expertise applies to)');
679
+ if (!['human', 'agent'].includes(options.source)) throw new Error('Capability confirmation requires explicit provenance: --source human|agent');
680
+ const { paths } = loadProject(root);
681
+ const cleanSlug = capabilitySlug(slug);
682
+ const singleFile = join(paths.capabilities, `${cleanSlug}.md`);
683
+ if (existsSync(singleFile)) {
684
+ let content = readFileSync(singleFile, 'utf8');
685
+ const authority = options.source === 'human' ? 'human_confirmed' : 'agent_provisional';
686
+ if (/^-\s*Authority:.*$/m.test(content)) content = content.replace(/^-\s*Authority:.*$/m, `- Authority: ${authority}`);
687
+ else content = content.replace(/^(# .+\n)/, `$1\n- Authority: ${authority}\n`);
688
+ if (/^-\s*Scenario:.*$/m.test(content)) content = content.replace(/^-\s*Scenario:.*$/m, `- Scenario: ${options.scenario}`);
689
+ else content = content.replace(/^(-\s*Authority:.*\n)/m, `$1- Scenario: ${options.scenario}\n`);
690
+ writeFileSync(singleFile, content, 'utf8');
691
+ const meta = parseSingleFileCapabilityMeta(content);
692
+ return {
693
+ slug: cleanSlug,
694
+ mode: meta.mode,
695
+ authority,
696
+ status: options.source === 'human' ? 'confirmed' : 'provisional',
697
+ scenario: options.scenario,
698
+ source: options.source,
699
+ next: `Compile ${cleanSlug}'s operational rules and Design delta into your Design documents (skeinn design add), then carry key red lines into Task guardrails and acceptance criteria.${options.source === 'agent' ? ' Authority stays agent_provisional until a human confirms.' : ''}`,
700
+ };
701
+ }
702
+ const dir = join(paths.capabilities, cleanSlug);
703
+ if (!existsSync(dir)) throw new Error(`Capability not found: ${slug}`);
704
+ const statusPath = join(dir, 'status.json');
705
+ if (!existsSync(statusPath)) throw new Error(`Capability ${slug} is not a research-directory dossier`);
706
+ const status = readJson(statusPath, 'status.json');
707
+ if (!['synthesized', 'provisional'].includes(status.status)) throw new Error(`Capability ${slug} must be synthesized before confirmation. Run skeinn capability synthesize ${slug} first.`);
708
+ status.scenario = options.scenario;
709
+ status.source = options.source;
710
+ status.status = options.source === 'human' ? 'confirmed' : 'provisional';
711
+ status.selected_at = now();
712
+ status.confirmed_at = options.source === 'human' ? now() : '';
713
+ status.updated_at = now();
714
+ atomicJson(statusPath, status);
715
+ const capPath = join(dir, 'capability.md');
716
+ const content = readFileSync(capPath, 'utf8');
717
+ const scenarioMatch = content.match(/(## Project scenario\n)([\s\S]*?)(\n## )/);
718
+ if (scenarioMatch) {
719
+ const prefix = scenarioMatch[1];
720
+ const suffix = scenarioMatch[3];
721
+ const blockquote = scenarioMatch[2].match(/(> [^\n]+\n)+/);
722
+ const blockquoteText = blockquote ? blockquote[0] : '';
723
+ const updated = content.replace(/## Project scenario\n[\s\S]*?\n## /, `${prefix}${blockquoteText}\n${options.scenario}\n${suffix}`);
724
+ writeFileSync(capPath, updated, 'utf8');
725
+ }
726
+ return {
727
+ slug: cleanSlug,
728
+ status: status.status,
729
+ scenario: options.scenario,
730
+ source: options.source,
731
+ next: `Write design documents informed by this capability, then carry key red lines into Tasks.${status.status === 'provisional' ? ' Status stays provisional until a human confirms.' : ''}`,
732
+ };
733
+ }
734
+
735
+ export function getCapabilityStatus(slug, root = findRoot()) {
736
+ const { paths } = loadProject(root);
737
+ const cleanSlug = capabilitySlug(slug);
738
+ const singleFile = join(paths.capabilities, `${cleanSlug}.md`);
739
+ if (existsSync(singleFile)) {
740
+ const content = readFileSync(singleFile, 'utf8');
741
+ const meta = parseSingleFileCapabilityMeta(content);
742
+ const issues = validateSingleFileCapability(cleanSlug, content);
743
+ return {
744
+ slug: cleanSlug,
745
+ format: 'single-file',
746
+ mode: meta.mode,
747
+ authority: meta.authority,
748
+ scenario: meta.scenario,
749
+ ready: issues.length === 0,
750
+ issues,
751
+ };
752
+ }
753
+ const dir = join(paths.capabilities, cleanSlug);
754
+ const statusPath = join(dir, 'status.json');
755
+ if (!existsSync(statusPath)) throw new Error(`Capability not found: ${slug}`);
756
+ return { ...readJson(statusPath, 'status.json'), slug: cleanSlug, format: 'legacy-directory' };
757
+ }
758
+
759
+ export function addDeliverable(slug, options = {}, root = findRoot()) {
760
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) throw new Error('Deliverable slug must use lowercase letters, numbers, and hyphens');
761
+ if (!options.title) throw new Error('Deliverable requires --title');
762
+ if (!options.kind) throw new Error('Deliverable requires --kind (module, feature, behavior, interface, artifact, operational, verification, or other)');
763
+ const { paths, deliverableStore } = loadProject(root);
764
+ if (deliverableStore.deliverables.some((item) => item.slug === slug)) throw new Error(`Deliverable already exists: ${slug}`);
765
+ const id = nextId(deliverableStore.deliverables, 'DLV');
766
+ deliverableStore.deliverables.push({ id, slug, title: options.title, kind: options.kind, notes: options.notes || '', covered_by: [], created_at: now() });
767
+ atomicJson(paths.deliverables, deliverableStore);
768
+ return { id, slug, title: options.title, kind: options.kind };
769
+ }
770
+
771
+ export function listDeliverables(root = findRoot()) {
772
+ const { deliverableStore } = loadProject(root);
773
+ return deliverableStore.deliverables.map((item) => ({ id: item.id, slug: item.slug, title: item.title, kind: item.kind, covered: item.covered_by.length > 0 }));
774
+ }
775
+
776
+ export function checkDeliverableCoverage(root = findRoot()) {
777
+ const { paths, taskStore, deliverableStore } = loadProject(root);
778
+ const taskCovers = new Map();
779
+ for (const task of taskStore.tasks) {
780
+ for (const dlvId of task.covers || []) {
781
+ if (!taskCovers.has(dlvId)) taskCovers.set(dlvId, []);
782
+ taskCovers.get(dlvId).push(task.id);
783
+ }
784
+ }
785
+ const uncovered = [];
786
+ const covered = [];
787
+ for (const dlv of deliverableStore.deliverables) {
788
+ const tasks = taskCovers.get(dlv.id) || [];
789
+ if (tasks.length === 0) uncovered.push({ id: dlv.id, slug: dlv.slug, title: dlv.title });
790
+ else covered.push({ id: dlv.id, slug: dlv.slug, tasks });
791
+ }
792
+ let changed = false;
793
+ for (const dlv of deliverableStore.deliverables) {
794
+ const tasks = taskCovers.get(dlv.id) || [];
795
+ const sorted = [...tasks].sort();
796
+ const current = JSON.stringify(dlv.covered_by);
797
+ const newVal = JSON.stringify(sorted);
798
+ if (current !== newVal) { dlv.covered_by = sorted; changed = true; }
799
+ }
800
+ if (changed) atomicJson(paths.deliverables, deliverableStore);
801
+ const taskById = new Map(taskStore.tasks.map((task) => [task.id, task]));
802
+ const delivered = covered.filter((item) => item.tasks.some((id) => taskById.get(id)?.status === 'done'));
803
+ return { total: deliverableStore.deliverables.length, covered: covered.length, delivered: delivered.length, uncovered: uncovered.length, uncovered_items: uncovered, covered_items: covered };
804
+ }
805
+
806
+ function capabilityPath(paths, name) {
807
+ const slug = capabilitySlug(name);
808
+ const singleFile = join(paths.capabilities, `${slug}.md`);
809
+ if (existsSync(singleFile)) return singleFile;
810
+ const dirCapability = join(paths.capabilities, slug, 'capability.md');
811
+ if (existsSync(dirCapability)) return dirCapability;
812
+ return singleFile;
813
+ }
814
+
815
+ function capabilityTemplateResidue(content) {
816
+ return content.includes('Name the established field, what expertise it contributes')
817
+ || content.includes('Name the established field, what judgment it contributes')
818
+ || content.includes('<node name>')
819
+ || content.includes('<which research material or expert narrative supports this node>')
820
+ || content.includes('<what a top practitioner actually does')
821
+ || content.includes('<what concrete Design decision changed because of this research and reflection>');
822
+ }
823
+
824
+ function designTemplateResidue(content) {
825
+ return content.includes('Describe the project-specific decision, mechanism, boundary, or evidence owned by this section.')
826
+ || content.includes('Compare at least two genuinely viable alternatives (no strawmen).')
827
+ || content.includes('List the specific capability rules, anti-patterns, or verification probes from `.skeinn/capabilities/`')
828
+ || content.includes('Name the concrete false-positive outcomes where the build appears complete');
829
+ }
830
+
831
+ function extractSection(content, heading) {
832
+ const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
833
+ const match = content.match(new RegExp(`^##\\s+${escaped}\\s*\\n([\\s\\S]*?)(?=^##\\s+|$(?!\\n))`, 'mi'));
834
+ return match ? match[1].trim() : '';
835
+ }
836
+
837
+ const FAKE_SOURCE_PATTERNS = [
838
+ /\bagent-authored\b/i,
839
+ /\bself-authored\b/i,
840
+ /\binternal agent analysis\b/i,
841
+ /\bwritten by agent\b/i,
842
+ ];
843
+
844
+ function hasVerifiableSource(sectionText) {
845
+ return /(https?:\/\/\S+|github\.com\/\S+|\[[^\]]+\]\([^)]+\)|Source:\s*\S{4,}|RFC\s*\d+|doi:|ISBN|postmortem|case study|benchmark|repo:)/i.test(sectionText);
846
+ }
847
+
848
+ function validateSingleFileCapability(slug, content) {
849
+ const issues = [];
850
+ if (capabilityTemplateResidue(content)) {
851
+ issues.push(`Capability ${slug} still contains template instructions`);
852
+ return issues;
853
+ }
854
+ const meta = parseSingleFileCapabilityMeta(content);
855
+ if (!CAPABILITY_MODES.includes(meta.mode)) {
856
+ issues.push(`Capability ${slug} has invalid Mode "${meta.mode}" (must be ${CAPABILITY_MODES.join(', ')})`);
857
+ }
858
+ const practices = extractSection(content, 'How real practitioners operate');
859
+ const reflection = extractSection(content, 'Reflection for this project');
860
+ const rules = extractSection(content, 'Operational rules and Design delta');
861
+ if (!practices) issues.push(`Capability ${slug} is missing "## How real practitioners operate"`);
862
+ if (!reflection) issues.push(`Capability ${slug} is missing "## Reflection for this project"`);
863
+ if (!rules) issues.push(`Capability ${slug} is missing "## Operational rules and Design delta"`);
864
+ if (meta.mode === 'external_researched') {
865
+ if (FAKE_SOURCE_PATTERNS.some((pattern) => pattern.test(practices))) {
866
+ issues.push(`Capability ${slug} cites agent-authored/self-authored notes under Mode: external_researched — cite real external practitioner sources or switch honestly to Mode: offline_reflection`);
867
+ } else if (practices && !hasVerifiableSource(practices)) {
868
+ issues.push(`Capability ${slug} declares Mode: external_researched but "## How real practitioners operate" has no verifiable external source (URL, repo, article/book, or Source: reference)`);
869
+ }
870
+ }
871
+ if (rules && !/design delta/i.test(rules)) {
872
+ issues.push(`Capability ${slug} must record a concrete "Design delta" (what Design decision changed because of this research and reflection)`);
873
+ }
874
+ return issues;
875
+ }
876
+
877
+ function extractCapabilityNode(paths, nodeRef) {
878
+ const parts = nodeRef.split('#');
879
+ if (parts.length !== 2) return null;
880
+ const [slug, nodeId] = parts;
881
+ const capPath = capabilityPath(paths, slug);
882
+ if (!existsSync(capPath)) return null;
883
+ const content = readFileSync(capPath, 'utf8');
884
+ const header = `### ${nodeId}:`;
885
+ const headerIndex = content.indexOf(header);
886
+ if (headerIndex === -1) return null;
887
+ const afterHeader = content.slice(headerIndex + header.length);
888
+ const nextNode = afterHeader.search(/### C\d+:/);
889
+ const nextSection = afterHeader.search(/\n## /);
890
+ let endIdx = afterHeader.length;
891
+ if (nextNode !== -1) endIdx = Math.min(endIdx, nextNode);
892
+ if (nextSection !== -1) endIdx = Math.min(endIdx, nextSection);
893
+ return `${header}${afterHeader.slice(0, endIdx)}`;
894
+ }
895
+
896
+ export function importTasks(payload, root = findRoot()) {
897
+ const { paths, taskStore } = loadProject(root);
898
+ const incoming = Array.isArray(payload) ? payload : payload.tasks;
899
+ if (!Array.isArray(incoming) || !incoming.length) throw new Error('Task plan requires a non-empty tasks array');
900
+ for (const raw of incoming) {
901
+ if (raw.status && raw.status !== 'open') throw new Error('New Work Map Tasks must start open; completion requires Task evidence');
902
+ const id = raw.id || nextId(taskStore.tasks, 'TASK');
903
+ if (taskStore.tasks.some((task) => task.id === id)) throw new Error(`Task already exists: ${id}`);
904
+ taskStore.tasks.push({
905
+ id,
906
+ title: raw.title,
907
+ outcome: raw.outcome,
908
+ acceptance: raw.acceptance || [],
909
+ done_when: raw.done_when || [],
910
+ kind: raw.kind || 'delivery',
911
+ boundaries: raw.boundaries || [],
912
+ guardrails: raw.guardrails || [],
913
+ depends_on: raw.depends_on || [],
914
+ reads: raw.reads || ['.skeinn/PROJECT.md'],
915
+ touches: raw.touches || [],
916
+ implements: raw.implements || '',
917
+ design_exemption: raw.design_exemption || '',
918
+ capability_hooks: raw.capability_hooks || [],
919
+ capability_exemption: raw.capability_exemption || '',
920
+ integrity_version: 1,
921
+ covers: raw.covers || [],
922
+ status: 'open',
923
+ progress: raw.progress || { completed: [], current: '', next: '' },
924
+ evidence: raw.evidence || [],
925
+ created_at: now(),
926
+ updated_at: now(),
927
+ });
928
+ }
929
+ validateTasks(taskStore.tasks);
930
+ atomicJson(paths.tasks, taskStore);
931
+ const { state } = loadProject(root);
932
+ if (state.project.status === 'complete') {
933
+ state.project.status = 'building';
934
+ state.project.updated_at = now();
935
+ atomicJson(paths.state, state);
936
+ }
937
+ return { ...taskSummary(taskStore.tasks), next: 'When PROJECT.md, design documents, capability files (or exemption), and the Work Map are stable, run skeinn project ready to freeze a digest for the one-time Keeper handoff. skeinn context names anything still unfinished.' };
938
+ }
939
+
940
+ export function taskSummary(tasks) {
941
+ return {
942
+ total: tasks.length,
943
+ open: tasks.filter((task) => task.status === 'open').length,
944
+ active: tasks.find((task) => task.status === 'active')?.id || null,
945
+ blocked: tasks.filter((task) => task.status === 'blocked').length,
946
+ done: tasks.filter((task) => task.status === 'done').length,
947
+ };
948
+ }
949
+
950
+ export function getTask(id, root = findRoot()) {
951
+ const { taskStore } = loadProject(root);
952
+ const task = id ? taskStore.tasks.find((item) => item.id === id) : nextTask(taskStore.tasks);
953
+ if (!task) throw new Error(id ? `Task not found: ${id}` : 'No executable Task is available');
954
+ return task;
955
+ }
956
+
957
+ function nextTask(tasks) {
958
+ const active = tasks.find((task) => task.status === 'active');
959
+ if (active) return active;
960
+ const done = new Set(tasks.filter((task) => task.status === 'done').map((task) => task.id));
961
+ return tasks.find((task) => task.status === 'open' && task.depends_on.every((id) => done.has(id))) || null;
962
+ }
963
+
964
+ function sectionHeadingExists(content, anchor) {
965
+ const needle = anchor.toLowerCase();
966
+ return content.split(/\r?\n/).some((line) => /^#{1,6}\s/.test(line) && line.replace(/^#{1,6}\s*/, '').toLowerCase().includes(needle));
967
+ }
968
+
969
+ function taskIntegrityFindings(task, designs, capabilities, paths) {
970
+ if (task.integrity_version !== 1) return [];
971
+ const findings = [];
972
+ if (task.kind !== 'spike' && designs.length && !task.implements?.trim() && !task.design_exemption?.trim()) findings.push('is missing implements or design_exemption');
973
+ if (!paths) return findings;
974
+ if (task.implements?.trim()) {
975
+ const raw = task.implements.trim();
976
+ const [ref, anchor] = raw.split('#');
977
+ let target = null;
978
+ try {
979
+ target = declaredArtifactPath(paths, ref);
980
+ } catch {
981
+ findings.push(`implements uses an unsafe path: ${raw}`);
982
+ }
983
+ if (target && existsSync(target)) {
984
+ if (anchor?.trim() && !sectionHeadingExists(readFileSync(target, 'utf8'), anchor.trim())) findings.push(`implements references a missing design section: ${anchor.trim()}`);
985
+ } else if (target && (ref.includes('/') || ref.includes('\\') || ref.includes('.'))) {
986
+ findings.push(`implements references a missing design document: ${ref}`);
987
+ } else if (target) {
988
+ const corpus = [paths.decisions, ...designs.map((name) => join(paths.design, name)), ...capabilities.map((name) => capabilityPath(paths, name))]
989
+ .filter((path) => existsSync(path))
990
+ .map((path) => readFileSync(path, 'utf8'))
991
+ .join('\n');
992
+ if (!corpus.includes(raw)) findings.push(`implements references a decision not found in project truth: ${raw}`);
993
+ }
994
+ }
995
+ for (const hook of task.capability_hooks || []) {
996
+ const [slug, node] = (hook.node || '').split('#');
997
+ if (!capabilities.includes(slug)) {
998
+ findings.push(`capability_hooks references a missing dossier: ${slug}`);
999
+ continue;
1000
+ }
1001
+ if (node && !sectionHeadingExists(readFileSync(capabilityPath(paths, slug), 'utf8'), node)) findings.push(`capability_hooks references a missing capability node: ${hook.node}`);
1002
+ }
1003
+ return findings;
1004
+ }
1005
+
1006
+ function assertTaskIntegrityClassification(task, root) {
1007
+ const { paths } = loadProject(root);
1008
+ const findings = taskIntegrityFindings(task, listDesigns(root), listCapabilities(root), paths);
1009
+ if (findings.length) throw new Error(`${task.id} has unresolved integrity classification:\n- ${findings.join('\n- ')}\nRepair the reference or add a concrete exemption before execution.`);
1010
+ }
1011
+
1012
+ function declaredArtifactPath(paths, ref) {
1013
+ const normalized = ref.replaceAll('\\', '/');
1014
+ if (isAbsolute(normalized) || normalized.startsWith('/') || normalized.includes('..')) throw new Error(`Unsafe declared artifact path: ${ref}`);
1015
+ const fromSkeinn = normalized === '.skeinn' || normalized.startsWith('.skeinn/');
1016
+ const base = fromSkeinn ? paths.skeinn : paths.root;
1017
+ const relativeRef = fromSkeinn ? normalized.slice('.skeinn'.length).replace(/^\//, '') : normalized;
1018
+ const absolute = resolve(base, relativeRef);
1019
+ const prefix = `${base}${process.platform === 'win32' ? '\\' : '/'}`;
1020
+ if (!absolute.startsWith(prefix) && absolute !== base) throw new Error(`Unsafe declared artifact path: ${ref}`);
1021
+ return absolute;
1022
+ }
1023
+
1024
+ function missingTaskOutputs(task, paths) {
1025
+ if (task.integrity_version !== 1) return [];
1026
+ return task.touches.filter((ref) => !existsSync(declaredArtifactPath(paths, ref)));
1027
+ }
1028
+
1029
+ export function updateTask(id, patch, root = findRoot()) {
1030
+ const { paths, taskStore } = loadProject(root);
1031
+ const task = taskStore.tasks.find((item) => item.id === id);
1032
+ if (!task) throw new Error(`Task not found: ${id}`);
1033
+ if (task.status === 'done') throw new Error(`${id} is done; reopen it first (skeinn task reopen ${id} --reason <why the completion is being revisited>) before changing its record`);
1034
+ const allowed = ['title', 'kind', 'outcome', 'acceptance', 'done_when', 'boundaries', 'guardrails', 'depends_on', 'reads', 'touches', 'implements', 'design_exemption', 'capability_hooks', 'capability_exemption', 'covers', 'progress', 'evidence'];
1035
+ for (const key of Object.keys(patch)) if (!allowed.includes(key)) throw new Error(`Task field cannot be updated: ${key}`);
1036
+ Object.assign(task, patch, { updated_at: now() });
1037
+ validateTasks(taskStore.tasks);
1038
+ atomicJson(paths.tasks, taskStore);
1039
+ return task;
1040
+ }
1041
+
1042
+ export function blockTask(id, payload, root = findRoot()) {
1043
+ const task = getTask(id, root);
1044
+ if (task.status !== 'active') throw new Error(`${id} is not active`);
1045
+ if (!payload.reason || payload.reason.length < 10) throw new Error('Blocking a Task requires a concrete reason');
1046
+ if (!Array.isArray(payload.recovery_conditions) || !payload.recovery_conditions.length) throw new Error('Blocking a Task requires recovery_conditions');
1047
+ const evidence = Array.isArray(payload.evidence) ? payload.evidence : [];
1048
+ const { paths, taskStore } = loadProject(root);
1049
+ const target = taskStore.tasks.find((item) => item.id === id);
1050
+ target.status = 'blocked';
1051
+ target.block = { reason: payload.reason, recovery_conditions: payload.recovery_conditions, at: now() };
1052
+ target.progress = { ...target.progress, current: `blocked: ${payload.reason}`, next: payload.recovery_conditions.join('; ') };
1053
+ target.evidence = [...target.evidence, ...evidence];
1054
+ target.updated_at = now();
1055
+ validateTasks(taskStore.tasks);
1056
+ atomicJson(paths.tasks, taskStore);
1057
+ return target;
1058
+ }
1059
+
1060
+ export function reopenTask(id, options = {}, root = findRoot()) {
1061
+ const { paths, taskStore } = loadProject(root);
1062
+ if (taskStore.tasks.some((task) => task.status === 'active')) throw new Error('Another Task is already active');
1063
+ const task = taskStore.tasks.find((item) => item.id === id);
1064
+ if (!task || !['blocked', 'done'].includes(task.status)) throw new Error(`${id} is neither blocked nor done`);
1065
+ if (!options.reason || options.reason.length < 10) throw new Error(`Reopening ${id} requires a concrete --reason — for blocked Tasks state how the recovery conditions were met, for done Tasks why the completion is disproved`);
1066
+ const priorStatus = task.status;
1067
+ task.status = 'open';
1068
+ if (priorStatus === 'done') {
1069
+ task.evidence.push({ type: 'completion_reopened', reason: options.reason, at: now() });
1070
+ task.progress = { ...task.progress, current: `completion reopened: ${options.reason}`, next: 'Re-run the Task and close every done condition with evidence.' };
1071
+ } else {
1072
+ task.evidence.push({ type: 'block_reopened', reason: options.reason, at: now() });
1073
+ task.progress = { ...task.progress, current: `block reopened: ${options.reason}`, next: 'Address the recorded recovery conditions and re-verify before completing.' };
1074
+ }
1075
+ task.reopened_at = now();
1076
+ task.updated_at = now();
1077
+ validateTasks(taskStore.tasks);
1078
+ atomicJson(paths.tasks, taskStore);
1079
+ const { state } = loadProject(root);
1080
+ if (state.project.status === 'complete') {
1081
+ state.project.status = 'building';
1082
+ state.project.updated_at = now();
1083
+ atomicJson(paths.state, state);
1084
+ }
1085
+ return task;
1086
+ }
1087
+
1088
+ export function startTask(id, root = findRoot()) {
1089
+ const { paths, state, taskStore } = loadProject(root);
1090
+ if (taskStore.tasks.some((task) => task.status === 'active')) throw new Error('Another Task is already active');
1091
+ const task = taskStore.tasks.find((item) => item.id === id);
1092
+ if (!task || task.status !== 'open') throw new Error(`${id} is not open`);
1093
+ const isSpike = task.kind === 'spike';
1094
+ if (!isSpike) {
1095
+ const latestKeeper = state.keeper.attempts.at(-1);
1096
+ const passedStatus = ['passed', 'passed_with_advisories'].includes(state.keeper.status);
1097
+ const attestedPass = passedStatus && latestKeeper?.review?.mode === 'independent';
1098
+ if (passedStatus && !attestedPass) throw new Error('The recorded Keeper pass has no independent review provenance. Obtain a fresh Keeper review (see skeinn review --help) or record an explicit skip: skeinn keeper skip --reason <limitation>.');
1099
+ if (!state.keeper.launch_completed && !['passed', 'passed_with_advisories', 'skipped'].includes(state.keeper.status)) {
1100
+ throw new Error('The one-time Keeper handoff has not passed. Run skeinn keeper prompt.');
1101
+ }
1102
+ }
1103
+ assertTaskIntegrityClassification(task, root);
1104
+ const pinned = findingsForTask(state, task);
1105
+ const blockingPinned = pinned.filter((f) => f.severity === 'blocking');
1106
+ if (blockingPinned.length) {
1107
+ throw new Error(`${id} has open blocking findings pinned to its scope:\n- ${blockingPinned.map((f) => `${f.id} [${f.scope}]: ${f.text}`).join('\n- ')}\nResolve each with skeinn keeper resolve <id> --evidence "<proof>" before starting.`);
1108
+ }
1109
+ const done = new Set(taskStore.tasks.filter((item) => item.status === 'done').map((item) => item.id));
1110
+ const missing = task.depends_on.filter((dep) => !done.has(dep));
1111
+ if (missing.length) throw new Error(`${id} has incomplete dependencies: ${missing.join(', ')}`);
1112
+ for (const ref of task.reads) readContextDocument(paths, ref);
1113
+ task.status = 'active';
1114
+ task.updated_at = now();
1115
+ validateTasks(taskStore.tasks);
1116
+ atomicJson(paths.tasks, taskStore);
1117
+ if (!isSpike || state.project.status !== 'shaping') state.project.status = 'building';
1118
+ state.project.updated_at = now();
1119
+ atomicJson(paths.state, state);
1120
+ const advisories = pinned.filter((f) => f.severity === 'minor').map((f) => `${f.id} [${f.scope}]: ${f.text}`);
1121
+ return {
1122
+ ...task,
1123
+ ...(advisories.length ? { pinned_advisories: advisories } : {}),
1124
+ next: advisories.length
1125
+ ? `This Task has ${advisories.length} pinned advisory item(s) — address them during implementation and close via skeinn keeper resolve <id> --evidence "<proof>". Run skeinn context before editing.`
1126
+ : 'Run skeinn context to load the execution protocol, guardrails, and every file in reads before editing.',
1127
+ };
1128
+ }
1129
+
1130
+ export function completeTask(id, payload, root = findRoot()) {
1131
+ const { paths, state, taskStore } = loadProject(root);
1132
+ const task = taskStore.tasks.find((item) => item.id === id);
1133
+ if (!task) throw new Error(`Task not found: ${id}`);
1134
+ if (task.status !== 'active') throw new Error(`${id} is not active`);
1135
+ if (!Array.isArray(payload.evidence) || !payload.evidence.length) throw new Error('Completing a Task requires concrete evidence');
1136
+ assertTaskIntegrityClassification(task, root);
1137
+ const missingOutputs = missingTaskOutputs(task, paths);
1138
+ if (missingOutputs.length) throw new Error(`${id} declared output does not exist:\n- ${missingOutputs.join('\n- ')}`);
1139
+ const hasAcceptance = Array.isArray(task.acceptance) && task.acceptance.length > 0;
1140
+ if (hasAcceptance) {
1141
+ if (!Array.isArray(payload.acceptance_results)) throw new Error('Completing a Task with acceptance[] requires acceptance_results[]');
1142
+ const criteria = new Set(task.acceptance.map((acc) => acc.criterion));
1143
+ const seen = new Set();
1144
+ for (const result of payload.acceptance_results) {
1145
+ if (!result || !criteria.has(result.criterion)) throw new Error('acceptance_results criterion must match an exact acceptance criterion');
1146
+ if (seen.has(result.criterion)) throw new Error(`Duplicate acceptance result: ${result.criterion}`);
1147
+ if (!result.evidence || typeof result.evidence !== 'string' || result.evidence.length < 5) throw new Error(`acceptance result requires concrete evidence: ${result.criterion}`);
1148
+ seen.add(result.criterion);
1149
+ }
1150
+ const missingResults = task.acceptance.filter((acc) => !seen.has(acc.criterion));
1151
+ if (missingResults.length) throw new Error(`Task completion is missing acceptance results:\n- ${missingResults.map((acc) => acc.criterion).join('\n- ')}`);
1152
+ for (const result of payload.acceptance_results) {
1153
+ const acc = task.acceptance.find((acc) => acc.criterion === result.criterion);
1154
+ acc.evidence = result.evidence;
1155
+ }
1156
+ task.status = 'done';
1157
+ task.evidence = [...task.evidence, ...payload.evidence, { type: 'acceptance_results', results: payload.acceptance_results, at: now() }];
1158
+ } else {
1159
+ if (!Array.isArray(payload.checks)) throw new Error('Completing a Task with done_when[] requires checks for every done_when criterion');
1160
+ const criteria = new Set(task.done_when);
1161
+ const seen = new Set();
1162
+ for (const check of payload.checks) {
1163
+ if (!check || !criteria.has(check.criterion)) throw new Error('Task completion check must quote an exact done_when criterion');
1164
+ if (seen.has(check.criterion)) throw new Error(`Duplicate Task completion check: ${check.criterion}`);
1165
+ if (!Array.isArray(check.evidence) || !check.evidence.length) throw new Error(`Task completion check requires evidence: ${check.criterion}`);
1166
+ seen.add(check.criterion);
1167
+ }
1168
+ const missingChecks = task.done_when.filter((criterion) => !seen.has(criterion));
1169
+ if (missingChecks.length) throw new Error(`Task completion is missing done_when checks:\n- ${missingChecks.join('\n- ')}`);
1170
+ task.status = 'done';
1171
+ task.evidence = [...task.evidence, ...payload.evidence, { type: 'done_when_checks', checks: payload.checks, at: now() }];
1172
+ }
1173
+ task.progress = { ...task.progress, current: 'complete', next: '' };
1174
+ task.completed_at = now();
1175
+ task.updated_at = now();
1176
+ validateTasks(taskStore.tasks);
1177
+ atomicJson(paths.tasks, taskStore);
1178
+ if (taskStore.tasks.length && taskStore.tasks.every((item) => item.status === 'done')) {
1179
+ state.project.status = 'complete';
1180
+ state.project.updated_at = now();
1181
+ atomicJson(paths.state, state);
1182
+ }
1183
+ return task;
1184
+ }
1185
+
1186
+ export function markReady(root = findRoot(), options = {}) {
1187
+ const { paths, state, taskStore } = loadProject(root);
1188
+ const project = readFileSync(paths.project, 'utf8');
1189
+ const designs = listDesigns(root);
1190
+ const capabilities = listCapabilities(root);
1191
+ const highOpen = state.understanding.unresolved.filter((item) => item.status === 'open' && item.impact === 'high');
1192
+ const errors = [];
1193
+ if (project.includes('> This is the concise entry point') || project.length < 400) errors.push('PROJECT.md still looks like a template');
1194
+ if (!designs.length) errors.push('No design document exists; PROJECT.md is an index, not the entire project design');
1195
+ const unfinishedDesigns = designs.filter((name) => designTemplateResidue(readFileSync(join(paths.design, name), 'utf8')));
1196
+ if (unfinishedDesigns.length) errors.push(`Design documents still contain template instructions: ${unfinishedDesigns.join(', ')}`);
1197
+ if (!capabilities.length && !state.capability_exemption?.reason) {
1198
+ errors.push('No capability file exists and no capability exemption is recorded. Add 1–3 bottleneck capabilities with skeinn capability add <slug> --title <field>, or record skeinn capability exempt --reason <why standard engineering suffices>');
1199
+ }
1200
+ for (const name of capabilities) {
1201
+ const content = readFileSync(capabilityPath(paths, name), 'utf8');
1202
+ if (isLegacyDirectoryCapability(paths, name)) {
1203
+ if (capabilityTemplateResidue(content)) errors.push(`Capability dossier still contains template instructions: ${name}`);
1204
+ } else {
1205
+ errors.push(...validateSingleFileCapability(name, content));
1206
+ }
1207
+ }
1208
+ if (!taskStore.tasks.length) errors.push('The initial work map is empty');
1209
+ const integrityErrors = [];
1210
+ for (const task of taskStore.tasks) {
1211
+ for (const finding of taskIntegrityFindings(task, designs, capabilities, paths)) integrityErrors.push(`${task.id} ${finding}`);
1212
+ }
1213
+ if (integrityErrors.length) errors.push(`Task integrity classification is unresolved:\n - ${integrityErrors.join('\n - ')}`);
1214
+ if (highOpen.length) errors.push(`High-impact questions remain open: ${highOpen.map((item) => item.id).join(', ')}`);
1215
+ const currentDigests = artifactDigests(paths, taskStore.tasks, state);
1216
+ const digest = overallDigest(currentDigests);
1217
+ const latestKeeper = state.keeper.attempts.at(-1);
1218
+ if (['needs_revision', 'blocked'].includes(state.keeper.status) && latestKeeper?.prepared_digest === digest) {
1219
+ errors.push('Keeper requested revision, but project truth and Task definitions have not changed');
1220
+ }
1221
+ // Convergence guard: if last two failed attempts did not strictly reduce blocking count (>=), pause blind looping
1222
+ const failedAttempts = state.keeper.attempts.filter((a) => ['needs_revision', 'blocked'].includes(a.verdict));
1223
+ if (failedAttempts.length >= 2 && !options.forceRound) {
1224
+ const prev = failedAttempts.at(-2);
1225
+ const curr = failedAttempts.at(-1);
1226
+ const prevCount = typeof prev.blocking_count === 'number' ? prev.blocking_count : (prev.gaps || []).length;
1227
+ const currCount = typeof curr.blocking_count === 'number' ? curr.blocking_count : (curr.gaps || []).length;
1228
+ if (currCount > 0 && currCount >= prevCount) {
1229
+ errors.push(`Non-convergent Keeper loop detected: blocking findings did not decrease across the last two rounds (${prevCount} -> ${currCount}). Narrow the active horizon, record a bounded assumption (skeinn record), or pass --force-round --reason "<why another round will converge>"`);
1230
+ }
1231
+ }
1232
+ if (options.forceRound && (!options.reason || options.reason.trim().length < 10)) {
1233
+ errors.push('--force-round requires a concrete --reason (at least 10 characters)');
1234
+ }
1235
+ if (errors.length) throw new Error(`Project is not ready for Keeper:\n- ${errors.join('\n- ')}`);
1236
+ const horizon = activeHorizon(taskStore.tasks, paths, 2);
1237
+ const priorBaseline = latestKeeper?.artifact_digests || state.keeper.reviewed_digests || {};
1238
+ const dirty = computeDirtyArtifacts(currentDigests, priorBaseline, horizon.artifacts);
1239
+ delete state.keeper.auto_passed;
1240
+ state.project.status = 'ready_for_keeper';
1241
+ state.project.updated_at = now();
1242
+ state.keeper.prepared_digest = digest;
1243
+ state.keeper.prepared_artifact_digests = currentDigests;
1244
+ state.keeper.prepared_horizon_tasks = horizon.taskIds;
1245
+ state.keeper.prepared_horizon_artifacts = horizon.artifacts;
1246
+ state.keeper.prepared_dirty_artifacts = dirty;
1247
+ state.keeper.prepared_attempt = state.keeper.attempts.length + 1;
1248
+ atomicJson(paths.state, state);
1249
+ return {
1250
+ ready_for_keeper: true,
1251
+ digest: state.keeper.prepared_digest,
1252
+ attempt: state.keeper.prepared_attempt,
1253
+ delta_mode: state.keeper.prepared_attempt >= 2,
1254
+ horizon_tasks: horizon.taskIds,
1255
+ dirty_artifacts: dirty,
1256
+ next: 'Open a fresh Agent and run skeinn keeper prompt',
1257
+ };
1258
+ }
1259
+
1260
+ function projectDigest(paths, tasks, state = null) {
1261
+ return overallDigest(artifactDigests(paths, tasks, state));
1262
+ }
1263
+
1264
+ export function getKeeperPrompt(root = findRoot()) {
1265
+ const { state } = loadProject(root);
1266
+ if (state.project.status !== 'ready_for_keeper') throw new Error('Run skeinn project ready before Keeper handoff');
1267
+ const attempt = state.keeper.prepared_attempt || 1;
1268
+ return keeperProtocol({
1269
+ attemptNumber: attempt,
1270
+ preparedDigest: state.keeper.prepared_digest,
1271
+ deltaMode: attempt >= 2,
1272
+ dirtyArtifacts: state.keeper.prepared_dirty_artifacts || [],
1273
+ horizonTaskIds: state.keeper.prepared_horizon_tasks || [],
1274
+ });
1275
+ }
1276
+
1277
+ export function recordKeeper(payload, root = findRoot()) {
1278
+ const { paths, state, taskStore } = loadProject(root);
1279
+ if (state.project.status !== 'ready_for_keeper') throw new Error('Keeper result cannot be recorded before skeinn project ready');
1280
+ if (!['passed', 'passed_with_advisories', 'needs_revision', 'blocked'].includes(payload.verdict)) {
1281
+ throw new Error('Keeper verdict must be passed, passed_with_advisories, needs_revision, or blocked');
1282
+ }
1283
+ if (!payload.summary || !Array.isArray(payload.evidence) || !payload.evidence.length) throw new Error('Keeper result requires summary and evidence');
1284
+ const isPass = ['passed', 'passed_with_advisories'].includes(payload.verdict);
1285
+ if (payload.evidence.some((item) => typeof item !== 'string' || !item.trim())) throw new Error('Keeper evidence entries must be non-empty strings');
1286
+ if (payload.gaps !== undefined && !Array.isArray(payload.gaps)) throw new Error('Keeper gaps must be an array');
1287
+ if (payload.advisories !== undefined && !Array.isArray(payload.advisories)) throw new Error('Keeper advisories must be an array');
1288
+ for (const gap of payload.gaps || []) {
1289
+ if (typeof gap === 'string' && gap.trim()) continue;
1290
+ if (gap && typeof gap === 'object' && typeof gap.gap === 'string' && gap.gap.trim()) continue;
1291
+ throw new Error('Each Keeper gap must be a non-empty string or an object with a gap field');
1292
+ }
1293
+ if (isPass) {
1294
+ if (payload.verdict === 'passed' && payload.gaps?.length) throw new Error('Keeper pass cannot contain unresolved gaps; use passed_with_advisories for minor-only items');
1295
+ if (payload.verdict === 'passed_with_advisories') {
1296
+ const blockingInPass = (payload.gaps || []).filter((g) => typeof g === 'string' || g.severity !== 'minor');
1297
+ if (blockingInPass.length) throw new Error('passed_with_advisories cannot include blocking gaps; use needs_revision for blocking gaps');
1298
+ }
1299
+ if (!payload.review || payload.review.mode !== 'independent') throw new Error('Keeper pass requires an independent review; use review.mode="independent" from a fresh Agent, or skeinn keeper skip with a concrete reason');
1300
+ if (!payload.review.reviewer_id || payload.review.reviewer_id.length < 6 || !payload.review.evidence || payload.review.evidence.length < 10) throw new Error('Independent Keeper review requires reviewer_id and concrete review evidence');
1301
+ }
1302
+
1303
+ if (!payload.run_id || payload.run_id.length < 6) throw new Error('Keeper result requires a unique fresh-thread run_id');
1304
+ if (state.keeper.attempts.some((attempt) => attempt.run_id === payload.run_id)) throw new Error(`Keeper run_id was already used: ${payload.run_id}`);
1305
+ if (!payload.prepared_digest || payload.prepared_digest !== state.keeper.prepared_digest) throw new Error('Keeper result prepared_digest does not match the current ready state');
1306
+ const currentDigests = artifactDigests(paths, taskStore.tasks, state);
1307
+ const currentDigest = overallDigest(currentDigests);
1308
+ if (currentDigest !== state.keeper.prepared_digest) throw new Error('Project truth changed after skeinn project ready; prepare a new Keeper attempt');
1309
+ if (isPass) {
1310
+ const openFindings = new Map();
1311
+ for (const attempt of state.keeper.attempts) {
1312
+ for (const closure of attempt.closure_results || []) openFindings.delete(closure.gap);
1313
+ for (const finding of attempt.gaps || []) {
1314
+ const gap = typeof finding === 'string' ? finding : finding?.gap;
1315
+ if (gap) openFindings.set(gap, true);
1316
+ }
1317
+ }
1318
+ for (const gap of openFindings.keys()) {
1319
+ const closure = payload.closure_results?.find((item) => item.gap === gap);
1320
+ if (!closure || typeof closure.evidence !== 'string' || !closure.evidence.trim()) {
1321
+ throw new Error(`Keeper pass requires closure_results evidence for: ${gap}`);
1322
+ }
1323
+ }
1324
+ }
1325
+ const horizonSet = new Set([...(state.keeper.prepared_horizon_tasks || []), ...(state.keeper.prepared_horizon_artifacts || []), 'project']);
1326
+ const blockingCount = (payload.gaps || []).filter((g) => {
1327
+ if (typeof g === 'string') return true;
1328
+ const sev = g.severity || 'blocking';
1329
+ if (sev !== 'blocking') return false;
1330
+ // Out-of-horizon blocking observations auto-downgrade to minor advisory
1331
+ if (g.scope && !horizonSet.has(g.scope)) return false;
1332
+ return true;
1333
+ }).length;
1334
+ const attempt = {
1335
+ run_id: payload.run_id,
1336
+ prepared_digest: payload.prepared_digest,
1337
+ artifact_digests: currentDigests,
1338
+ verdict: payload.verdict,
1339
+ blocking_count: blockingCount,
1340
+ summary: payload.summary,
1341
+ evidence: payload.evidence,
1342
+ gaps: payload.gaps || [],
1343
+ advisories: payload.advisories || [],
1344
+ review: payload.review || { mode: 'unverified', reviewer_id: '', evidence: '' },
1345
+ can_auto_pass: false,
1346
+ closure_results: payload.closure_results || [],
1347
+ at: now(),
1348
+ };
1349
+ state.keeper.attempts.push(attempt);
1350
+ // Apply closures to unified findings ledger
1351
+ for (const closure of payload.closure_results || []) {
1352
+ for (const f of state.keeper.findings) {
1353
+ if (f.status === 'open' && (f.text === closure.gap || f.id === closure.id)) {
1354
+ f.status = 'closed';
1355
+ f.closure_evidence = closure.evidence;
1356
+ f.closed_at = now();
1357
+ }
1358
+ }
1359
+ }
1360
+ // Upsert findings/advisories into unified ledger (with horizon-relative severity)
1361
+ if (isPass) {
1362
+ const minorItems = [
1363
+ ...(payload.gaps || []).map((g) => (typeof g === 'string' ? { gap: g, severity: 'minor' } : { ...g, severity: 'minor' })),
1364
+ ...(payload.advisories || []).map((a) => (typeof a === 'string' ? { gap: a, severity: 'minor' } : { ...a, severity: 'minor' })),
1365
+ ];
1366
+ upsertFindings(state, minorItems, { sourceRunId: payload.run_id, defaultSeverity: 'minor' });
1367
+ // Commit reviewed horizon artifacts into reviewed_digests (birth certificate)
1368
+ const reviewedScope = state.keeper.prepared_horizon_artifacts?.length
1369
+ ? state.keeper.prepared_horizon_artifacts
1370
+ : Object.keys(currentDigests);
1371
+ for (const key of reviewedScope) {
1372
+ if (key in currentDigests) state.keeper.reviewed_digests[key] = currentDigests[key];
1373
+ }
1374
+ state.keeper.launch_completed = true;
1375
+ state.project.status = 'build_ready';
1376
+ } else {
1377
+ const normalizedGaps = (payload.gaps || []).map((g) => {
1378
+ if (typeof g === 'string') return { gap: g, scope: 'project', severity: 'blocking' };
1379
+ const scope = g.scope || 'project';
1380
+ const sev = g.severity === 'minor' || (scope !== 'project' && !horizonSet.has(scope)) ? 'minor' : 'blocking';
1381
+ return { ...g, scope, severity: sev };
1382
+ });
1383
+ upsertFindings(state, normalizedGaps, { sourceRunId: payload.run_id, defaultSeverity: 'blocking' });
1384
+ state.project.status = 'shaping';
1385
+ }
1386
+ state.keeper.status = payload.verdict;
1387
+ state.project.updated_at = now();
1388
+ atomicJson(paths.state, state);
1389
+ return state.keeper;
1390
+ }
1391
+
1392
+ export function resolveFinding(id, options = {}, root = findRoot()) {
1393
+ if (!options.evidence || options.evidence.trim().length < 10) {
1394
+ throw new Error('Resolving a finding requires concrete --evidence (at least 10 characters)');
1395
+ }
1396
+ const { paths, state } = loadProject(root);
1397
+ const finding = state.keeper.findings.find((f) => f.id === id);
1398
+ if (!finding) throw new Error(`Finding not found: ${id}`);
1399
+ if (finding.status === 'closed') return finding;
1400
+ finding.status = 'closed';
1401
+ finding.closure_evidence = options.evidence.trim();
1402
+ finding.closed_at = now();
1403
+ state.project.updated_at = now();
1404
+ atomicJson(paths.state, state);
1405
+ return finding;
1406
+ }
1407
+
1408
+ export function resetKeeper(reason, root = findRoot()) {
1409
+ if (!reason || reason.trim().length < 10) throw new Error('Resetting Keeper requires a concrete --reason (at least 10 characters)');
1410
+ const { paths, state } = loadProject(root);
1411
+ state.keeper.reviewed_digests = {};
1412
+ state.keeper.launch_completed = false;
1413
+ state.keeper.status = 'not_run';
1414
+ state.project.status = 'shaping';
1415
+ state.project.updated_at = now();
1416
+ atomicJson(paths.state, state);
1417
+ recordDecision({ summary: `Keeper relaunch reset: ${reason.trim()}`, changes: ['.skeinn/state.json'] }, root);
1418
+ return { reset: true, reason: reason.trim(), next: 'Shape the revised direction, then run skeinn project ready for a fresh Launch Keeper review.' };
1419
+ }
1420
+
1421
+ export function getCheckpointPrompt(options = {}, root = findRoot()) {
1422
+ const { paths, state, taskStore } = loadProject(root);
1423
+ const currentDigests = artifactDigests(paths, taskStore.tasks, state);
1424
+ const horizon = activeHorizon(taskStore.tasks, paths, 2);
1425
+ const dirty = computeDirtyArtifacts(currentDigests, state.keeper.reviewed_digests, horizon.artifacts);
1426
+ const openFindings = state.keeper.findings.filter((f) => f.status === 'open');
1427
+ // Even with dirty === 0 (pure code drift, no declaration churn) the reviewer needs the
1428
+ // recent delivery slice — its touches list is exactly what to diff against spec.
1429
+ const recentDone = deliveryTasksDoneSinceCleanReview(state, taskStore.tasks).map((t) => ({ id: t.id, title: t.title, implements: t.implements || '', touches: t.touches || [] }));
1430
+ return checkpointProtocol({
1431
+ milestone: options.milestone || 'in-flight',
1432
+ dirtyArtifacts: dirty,
1433
+ openFindings,
1434
+ recentDoneTasks: recentDone,
1435
+ preparedDigest: overallDigest(currentDigests),
1436
+ });
1437
+ }
1438
+
1439
+ export function recordCheckpoint(payload, root = findRoot()) {
1440
+ const { paths, state, taskStore } = loadProject(root);
1441
+ if (!['clean', 'drift_detected', 'blocked'].includes(payload.verdict)) {
1442
+ throw new Error('Checkpoint verdict must be clean, drift_detected, or blocked');
1443
+ }
1444
+ if (!payload.run_id || payload.run_id.length < 6) throw new Error('Checkpoint requires a unique run_id');
1445
+ if (state.keeper.checkpoints.some((c) => c.run_id === payload.run_id)) throw new Error(`Checkpoint run_id already used: ${payload.run_id}`);
1446
+ if (!payload.summary || !Array.isArray(payload.evidence) || !payload.evidence.length) throw new Error('Checkpoint requires summary and evidence');
1447
+ if (!payload.review || payload.review.mode !== 'independent' || !payload.review.reviewer_id || payload.review.reviewer_id.length < 6) {
1448
+ throw new Error('Checkpoint requires independent review provenance (review.mode="independent" and reviewer_id)');
1449
+ }
1450
+ const currentDigests = artifactDigests(paths, taskStore.tasks, state);
1451
+ const horizon = activeHorizon(taskStore.tasks, paths, 2);
1452
+ const dirty = computeDirtyArtifacts(currentDigests, state.keeper.reviewed_digests, horizon.artifacts);
1453
+ for (const closure of payload.closure_results || []) {
1454
+ if (!closure.evidence || closure.evidence.trim().length < 5) throw new Error(`Closure for ${closure.id || closure.gap} requires concrete evidence`);
1455
+ for (const f of state.keeper.findings) {
1456
+ if (f.status === 'open' && (f.id === closure.id || f.text === closure.gap)) {
1457
+ f.status = 'closed';
1458
+ f.closure_evidence = closure.evidence.trim();
1459
+ f.closed_at = now();
1460
+ }
1461
+ }
1462
+ }
1463
+ if (payload.findings?.length) {
1464
+ upsertFindings(state, payload.findings, { sourceRunId: payload.run_id, defaultSeverity: payload.verdict === 'clean' ? 'minor' : 'blocking' });
1465
+ }
1466
+ if (payload.verdict === 'clean') {
1467
+ for (const key of horizon.artifacts) {
1468
+ if (key in currentDigests) state.keeper.reviewed_digests[key] = currentDigests[key];
1469
+ }
1470
+ }
1471
+ const record = {
1472
+ id: nextId(state.keeper.checkpoints, 'CHK'),
1473
+ run_id: payload.run_id,
1474
+ milestone: payload.milestone || 'in-flight',
1475
+ verdict: payload.verdict,
1476
+ summary: payload.summary,
1477
+ dirty_artifacts: dirty,
1478
+ findings_added: (payload.findings || []).length,
1479
+ closures: (payload.closure_results || []).length,
1480
+ review: payload.review,
1481
+ evidence: payload.evidence,
1482
+ snapshot_digest: overallDigest(currentDigests),
1483
+ at: now(),
1484
+ };
1485
+ state.keeper.checkpoints.push(record);
1486
+ state.project.updated_at = now();
1487
+ atomicJson(paths.state, state);
1488
+ return record;
1489
+ }
1490
+
1491
+ export function skipKeeper(reason, root = findRoot()) {
1492
+ if (!reason || reason.length < 10) throw new Error('Skipping Keeper requires a concrete reason');
1493
+ const { paths, state } = loadProject(root);
1494
+ if (state.project.status !== 'ready_for_keeper') throw new Error('Keeper can only be skipped after skeinn project ready');
1495
+ state.keeper.status = 'skipped';
1496
+ state.keeper.launch_completed = true;
1497
+ state.keeper.skip_reason = reason;
1498
+ state.project.status = 'build_ready';
1499
+ state.project.updated_at = now();
1500
+ atomicJson(paths.state, state);
1501
+ return state.keeper;
1502
+ }
1503
+
1504
+ export function startClarify(options = {}, root = findRoot()) {
1505
+ if (!options.reason || options.reason.length < 10) throw new Error('Opening a clarification round requires a concrete --reason (what changed or what is now unclear)');
1506
+ const { paths, state } = loadProject(root);
1507
+ const clarify = ensureClarify(state);
1508
+ if (clarify.active) throw new Error(`A clarification round is already open: ${clarify.reason}`);
1509
+ clarify.active = true;
1510
+ clarify.reason = options.reason;
1511
+ clarify.started_at = now();
1512
+ clarify.closed_at = '';
1513
+ clarify.rounds = [];
1514
+ state.project.updated_at = now();
1515
+ atomicJson(paths.state, state);
1516
+ return { active: true, reason: clarify.reason, next: 'Pause material work and ask the human ONE batch of only material questions — answers that could change the result, boundary, design, or proof (typically two to seven). Then record the batch with skeinn clarify resolve --json-file <round.json>.' };
1517
+ }
1518
+
1519
+ export function resolveClarify(payload, root = findRoot()) {
1520
+ const { paths, state } = loadProject(root);
1521
+ const clarify = ensureClarify(state);
1522
+ if (!clarify.active) throw new Error('No clarification round is open. Start one with skeinn clarify start --reason <what changed>.');
1523
+ const answered = [];
1524
+ for (const item of payload.answers || []) {
1525
+ if (item.id) {
1526
+ const target = state.understanding.unresolved.find((q) => q.id === item.id);
1527
+ if (!target) throw new Error(`Unknown unresolved id ${item.id}`);
1528
+ if (!item.resolution && item.status !== 'skipped') throw new Error(`Answer for ${item.id} requires a resolution or skipped status`);
1529
+ target.status = item.status === 'skipped' ? 'skipped' : 'resolved';
1530
+ target.resolution = item.resolution || '';
1531
+ target.resolved_at = now();
1532
+ answered.push(item.id);
1533
+ } else if (item.question && item.resolution) {
1534
+ state.understanding.confirmed.push({ id: nextId(state.understanding.confirmed, 'F'), text: `${item.question} → ${item.resolution}`, source: 'clarification', at: now() });
1535
+ answered.push(item.question);
1536
+ } else {
1537
+ throw new Error('Each answer needs {id, resolution|skipped} for a recorded question or {question, resolution} to record the answer as a fact');
1538
+ }
1539
+ }
1540
+ for (const item of asObjects(payload.confirmed, 'text')) {
1541
+ if (!item.text) throw new Error('Confirmed fact requires text');
1542
+ state.understanding.confirmed.push({ id: nextId(state.understanding.confirmed, 'F'), text: item.text, source: item.source || 'clarification', at: now() });
1543
+ }
1544
+ for (const id of payload.retire_assumptions || []) {
1545
+ const target = state.understanding.assumptions.find((a) => a.id === id);
1546
+ if (!target) throw new Error(`Unknown assumption id ${id}`);
1547
+ target.status = 'retired';
1548
+ }
1549
+ for (const decision of payload.decisions || []) appendDecision(paths.decisions, decision, state);
1550
+ const roundNo = clarify.rounds.length + 1;
1551
+ const newOpenIds = [];
1552
+ for (const item of asObjects(payload.new_questions, 'question')) {
1553
+ if (!item.question) throw new Error('New question requires question text');
1554
+ const id = nextId(state.understanding.unresolved, 'Q');
1555
+ state.understanding.unresolved.push({ id, question: item.question, recommendation: item.recommendation || '', impact: item.impact || 'medium', status: 'open', at: now(), clarify_round: roundNo });
1556
+ newOpenIds.push(id);
1557
+ }
1558
+ clarify.rounds.push({ round: roundNo, answered, confirmed: (payload.confirmed || []).length, decisions: (payload.decisions || []).length, new_open: newOpenIds, at: now() });
1559
+ state.project.updated_at = now();
1560
+ atomicJson(paths.state, state);
1561
+ const openRoundQs = state.understanding.unresolved.filter((q) => q.status === 'open' && q.clarify_round);
1562
+ return {
1563
+ round: roundNo,
1564
+ rounds_recorded: clarify.rounds.length,
1565
+ open_round_questions: openRoundQs.map((q) => `${q.id}: ${q.question}`),
1566
+ next: openRoundQs.length
1567
+ ? 'Material questions remain open — ask them in the next batch, then skeinn clarify resolve again.'
1568
+ : 'Round recorded. If the direction materially changed, run skeinn decision for consequential changes, update the affected design documents and Tasks, then skeinn clarify close.',
1569
+ };
1570
+ }
1571
+
1572
+ export function closeClarify(root = findRoot()) {
1573
+ const { paths, state } = loadProject(root);
1574
+ const clarify = ensureClarify(state);
1575
+ if (!clarify.active) throw new Error('No clarification round is open.');
1576
+ if (!clarify.rounds.length) throw new Error('Closing requires at least one recorded round — run skeinn clarify resolve with real answers. Closing empty would silently drop the trigger.');
1577
+ const openQs = state.understanding.unresolved.filter((q) => q.status === 'open' && q.clarify_round);
1578
+ if (openQs.length) throw new Error(`Round questions still open: ${openQs.map((q) => `${q.id}: ${q.question}`).join(' | ')}. Resolve them or explicitly mark them skipped via skeinn clarify resolve.`);
1579
+ clarify.active = false;
1580
+ clarify.closed_at = now();
1581
+ state.project.updated_at = now();
1582
+ atomicJson(paths.state, state);
1583
+ return { closed: true, rounds: clarify.rounds.length, next: 'Cascade the answers downward: update PROJECT.md, design documents, and Tasks to match the clarified direction; record skeinn decision for consequential changes (skeinn check flags affected done Tasks); then resume from skeinn context.' };
1584
+ }
1585
+
1586
+ export function clarifyStatus(root = findRoot()) {
1587
+ const { state } = loadProject(root);
1588
+ const clarify = ensureClarify(state);
1589
+ return { ...clarify, open_round_questions: state.understanding.unresolved.filter((q) => q.status === 'open' && q.clarify_round).map((q) => ({ id: q.id, question: q.question, recommendation: q.recommendation || '', impact: q.impact })) };
1590
+ }
1591
+
1592
+ export function recordDecision(payload, root = findRoot()) {
1593
+ if (!payload || !payload.summary || payload.summary.length < 10) throw new Error('Decision requires --summary (what changed and why)');
1594
+ if (!payload.changes || !Array.isArray(payload.changes) || !payload.changes.length) throw new Error('Decision requires --changes (array of affected files or decisions)');
1595
+ const { paths } = loadProject(root);
1596
+ const id = `D-${new Date().toISOString().slice(0, 10)}-${Date.now().toString(36).slice(-4)}`;
1597
+ const entry = `## ${id}: ${payload.summary}\n\n- Changed: ${payload.changes.join(', ')}\n${payload.affected_tasks ? `- Affected tasks: ${payload.affected_tasks.join(', ')}\n` : ''}- At: ${now()}\n`;
1598
+ const existing = readFileSync(paths.decisions, 'utf8');
1599
+ const separator = existing.endsWith('\n') ? '\n' : '\n\n';
1600
+ writeFileSync(paths.decisions, existing + separator + entry, 'utf8');
1601
+ return { id, summary: payload.summary, changes: payload.changes, affected_tasks: payload.affected_tasks || [] };
1602
+ }
1603
+
1604
+ function describeCapabilityState(paths, name) {
1605
+ if (isLegacyDirectoryCapability(paths, name)) {
1606
+ const statusPath = join(paths.capabilities, name, 'status.json');
1607
+ return existsSync(statusPath) ? `${name} (${readJson(statusPath, 'status.json').status || 'legacy'})` : `${name} (legacy)`;
1608
+ }
1609
+ const content = readFileSync(capabilityPath(paths, name), 'utf8');
1610
+ const meta = parseSingleFileCapabilityMeta(content);
1611
+ const flag = meta.mode === 'offline_reflection' ? 'offline_reflection — unverified externally' : meta.mode;
1612
+ return `${name} (${flag}, ${meta.authority})`;
1613
+ }
1614
+
1615
+ export function compileContext(options = {}, root = findRoot()) {
1616
+ const { paths, state, taskStore } = loadProject(root);
1617
+ const designs = listDesigns(root);
1618
+ const capabilities = listCapabilities(root);
1619
+ const summary = taskSummary(taskStore.tasks);
1620
+ const task = options.taskId ? getTask(options.taskId, root) : taskStore.tasks.find((item) => item.status === 'active');
1621
+ const next = nextTask(taskStore.tasks);
1622
+ const blockedTasks = taskStore.tasks.filter((item) => item.status === 'blocked');
1623
+ const blockedLine = blockedTasks.length
1624
+ ? `- Blocked: ${blockedTasks.map((item) => `${item.id} — ${item.block?.reason || 'no reason recorded'} (recover: ${(item.block?.recovery_conditions || []).join('; ') || 'not recorded'})`).join(' | ')}\n`
1625
+ : '';
1626
+ const clarify = state.clarify || { active: false };
1627
+ const openRoundQs = state.understanding.unresolved.filter((q) => q.status === 'open' && q.clarify_round);
1628
+ const frontierBlock = openRoundQs.length
1629
+ ? `\n - Current frontier (ask now, each with your recommended answer):\n${openRoundQs.map((q) => ` - ${q.id}: ${q.question}${q.recommendation ? ` — recommended: ${q.recommendation}` : ''}`).join('\n')}`
1630
+ : '';
1631
+ const recommendation = clarify.active
1632
+ ? `Clarification round OPEN: ${clarify.reason} (rounds recorded: ${clarify.rounds.length}). Pause material work — do not edit code or Tasks until the round closes. Look up every fact discoverable from the workspace yourself; ask the human only the decision questions in the current frontier, each carrying your recommended answer. Record the batch with \`skeinn clarify resolve --json-file\`, then \`skeinn clarify close\`.${frontierBlock}`
1633
+ : state.project.status === 'ready_for_keeper'
1634
+ ? 'Keeper handoff pending. The host must open a fresh Agent without inherited conversation, provide the workspace and CLI paths, and ask it to run `skeinn keeper prompt`. Wait for `skeinn keeper record`, then resume `skeinn context`. See `skeinn review --help` for the complete handoff.'
1635
+ : ['needs_revision', 'blocked'].includes(state.keeper.status)
1636
+ ? 'Resolve the Keeper findings in the source documents and Tasks, run `skeinn project ready`, and obtain a fresh independent review. A changed digest does not prove findings are closed. See `skeinn review --help`.'
1637
+ : task
1638
+ ? `You have an active Task: ${task.id}. Read the Active Task, its guardrails, and its reads below. Then take the smallest action that advances the outcome inside the boundaries. Update progress or mark done only with concrete evidence.`
1639
+ : next
1640
+ ? `No active Task. The next executable Task is ${next.id}. Start it with \`skeinn task start ${next.id}\` if the project is build_ready, or run \`skeinn project ready\` if not. If the next Task is wrong, repair the Work Map first.`
1641
+ : state.project.status === 'complete'
1642
+ ? 'All Tasks are done. Run \`skeinn check\` to verify health. If new work arises, record the decision and update the Work Map.'
1643
+ : state.project.status === 'shaping'
1644
+ ? shapingFrontier({ paths, state, taskStore, designs, capabilities })
1645
+ : blockedTasks.length
1646
+ ? 'No executable Task. Review the blocked Tasks listed above; reopen one when its recovery conditions are met with `skeinn task reopen <id> --reason <how they were met>`, or extend the Work Map.'
1647
+ : 'No executable Task. Create or update Tasks so the Work Map matches the project goal.';
1648
+ const capabilityStates = capabilities.map((name) => describeCapabilityState(paths, name));
1649
+ const capStatusLine = capabilityStates.length
1650
+ ? capabilityStates.join(', ')
1651
+ : state.capability_exemption?.reason
1652
+ ? `exempted (${state.capability_exemption.reason})`
1653
+ : 'none';
1654
+ const recentDoneTasks = silentDriftAlert(state, taskStore.tasks);
1655
+ const silentDriftLine = recentDoneTasks.length >= SILENT_DRIFT_TASK_THRESHOLD
1656
+ ? `- Silent-drift watch: ${recentDoneTasks.length} delivery tasks since the last clean Keeper review — consider \`skeinn keeper checkpoint prompt\`\n`
1657
+ : '';
1658
+ const statusBlock = `## Current Skeinn state and recommended action\n\n- Project status: ${state.project.status}\n- Active task: ${summary.active || 'none'}\n- Work map: ${summary.total} total, ${summary.open} open, ${summary.done} done, ${summary.blocked} blocked\n${blockedLine}- Design documents: ${designs.length}\n- Capability files: ${capStatusLine}\n- Keeper status: ${state.keeper.status}\n${silentDriftLine}- Clarification round: ${clarify.active ? `OPEN — ${clarify.reason} (${clarify.rounds.length} recorded)` : 'none'}\n\n**Recommended next action:** ${recommendation}\n\nThis is a recommendation, not a script. Use your judgment; if you choose differently, record the reason in \`.skeinn/DECISIONS.md\` or the active Task evidence.${options.keeper || options.full ? '' : '\n\nNeed the full runtime protocol (first entry or after a context reset)? Run skeinn context --full.'}`;
1659
+ const blocks = [statusBlock];
1660
+ if (options.full || options.keeper) blocks.push(agentProtocol({ humanChannel: options.humanChannel || 'available' }));
1661
+ blocks.push(shapingContext({ state, taskSummary: summary, capabilityNames: capabilityStates, designNames: designs, forKeeper: Boolean(options.keeper) }));
1662
+ if (['passed', 'passed_with_advisories'].includes(state.keeper.status) && state.keeper.attempts.at(-1)?.review?.mode !== 'independent') {
1663
+ blocks.splice(1, 0, 'WARNING: The recorded Keeper pass has no independent review provenance. It is a legacy/unverified pass, not verified readiness. Prepare a fresh handoff before relying on it; see `skeinn review --help`.');
1664
+ }
1665
+ blocks.push(`## Project whole (${normalizeRef(paths, paths.project)})\n\n${readFileSync(paths.project, 'utf8')}`);
1666
+ if (existsSync(paths.structure)) blocks.push(`## Project structure (${normalizeRef(paths, paths.structure)})\n\n${readFileSync(paths.structure, 'utf8')}`);
1667
+ if (options.checkpoint) {
1668
+ const currentDigests = artifactDigests(paths, taskStore.tasks, state);
1669
+ const horizon = activeHorizon(taskStore.tasks, paths, 2);
1670
+ const dirty = computeDirtyArtifacts(currentDigests, state.keeper.reviewed_digests, horizon.artifacts);
1671
+ const openFindings = state.keeper.findings.filter((f) => f.status === 'open');
1672
+ const recentDone = deliveryTasksDoneSinceCleanReview(state, taskStore.tasks);
1673
+ blocks.unshift(checkpointProtocol({ milestone: 'in-flight', dirtyArtifacts: dirty, openFindings, recentDoneTasks: recentDone.map((t) => ({ id: t.id, title: t.title, implements: t.implements || '', touches: t.touches || [] })), preparedDigest: overallDigest(currentDigests) }));
1674
+ blocks.push(`## Decision history (${normalizeRef(paths, paths.decisions)})\n\n${readFileSync(paths.decisions, 'utf8')}`);
1675
+ blocks.push(`## Dirty / newly-entering horizon artifacts (${dirty.length})\n\n${dirty.length ? dirty.map((k) => `- ${k}`).join('\n') : '- none'}`);
1676
+ blocks.push(`## Delivery Tasks completed since last clean review (${recentDone.length})\n\n${recentDone.length ? recentDone.map((t) => `- ${t.id} — ${t.title}\n implements: ${t.implements || 'n/a'}\n touches: ${(t.touches || []).join(', ')}`).join('\n') : '- none'}`);
1677
+ for (const key of dirty) {
1678
+ if (key.startsWith('.skeinn/design/')) blocks.push(`## Design document (dirty): ${basename(key)}\n\n${getDesign(basename(key), root)}`);
1679
+ else if (key.startsWith('.skeinn/capabilities/')) blocks.push(`## Capability file (dirty): ${basename(key)}\n\n${getCapability(basename(key), root)}`);
1680
+ else if (key.startsWith('task:')) {
1681
+ const t = taskStore.tasks.find((item) => item.id === key.slice(5));
1682
+ if (t) blocks.push(`## Horizon Task (dirty): ${t.id}\n\n${JSON.stringify(t, null, 2)}`);
1683
+ }
1684
+ }
1685
+ } else if (options.keeper) {
1686
+ const attempt = state.keeper.prepared_attempt || 1;
1687
+ const isDelta = attempt >= 2 && !options.full;
1688
+ const dirty = state.keeper.prepared_dirty_artifacts || [];
1689
+ const dirtySet = new Set(dirty);
1690
+ blocks.unshift(keeperProtocol({
1691
+ attemptNumber: attempt,
1692
+ preparedDigest: state.keeper.prepared_digest,
1693
+ deltaMode: attempt >= 2,
1694
+ dirtyArtifacts: dirty,
1695
+ horizonTaskIds: state.keeper.prepared_horizon_tasks || [],
1696
+ }));
1697
+ blocks.push(`## Decision history (${normalizeRef(paths, paths.decisions)})\n\n${readFileSync(paths.decisions, 'utf8')}`);
1698
+ blocks.push(`## Work map summary\n\n${JSON.stringify(summary, null, 2)}\n\nActive horizon Tasks: ${(state.keeper.prepared_horizon_tasks || []).join(', ') || 'none'}\n\nFirst executable Task:\n\n${JSON.stringify(nextTask(taskStore.tasks), null, 2)}`);
1699
+ for (const name of designs) {
1700
+ const ref = `.skeinn/design/${name}`;
1701
+ if (!isDelta || dirtySet.has(ref)) blocks.push(`## Design document: ${name}\n\n${getDesign(name, root)}`);
1702
+ }
1703
+ if (capabilities.length) {
1704
+ for (const name of capabilities) {
1705
+ const ref = normalizeRef(paths, capabilityPath(paths, name));
1706
+ if (!isDelta || dirtySet.has(ref)) blocks.push(`## Capability file: ${name}\n\n${getCapability(name, root)}`);
1707
+ }
1708
+ } else if (state.capability_exemption?.reason) {
1709
+ blocks.push(`## Capability exemption (audit whether standard engineering genuinely suffices)\n\n- Reason: ${state.capability_exemption.reason}\n- Recorded at: ${state.capability_exemption.at}`);
1710
+ }
1711
+ } else if (task) {
1712
+ if (options.full) blocks.push(EXECUTION_PROTOCOL);
1713
+ blocks.push(`## Active Task\n\n${JSON.stringify(task, null, 2)}`);
1714
+ if (task.guardrails && task.guardrails.length) {
1715
+ blocks.push(`## Task guardrails (specialist red lines)\n\n${task.guardrails.map((rule) => `- ${rule}`).join('\n')}`);
1716
+ }
1717
+ const taskFindings = findingsForTask(state, task);
1718
+ if (taskFindings.length) {
1719
+ blocks.push(`## Pinned Keeper findings for ${task.id}\n\n${taskFindings.map((f) => `- ${f.id} [${f.severity}, scope: ${f.scope}]: ${f.text}`).join('\n')}\n\nClose each with \`skeinn keeper resolve <id> --evidence "<proof>"\`.`);
1720
+ }
1721
+ for (const ref of task.reads) {
1722
+ const content = readContextDocument(paths, ref);
1723
+ if (content && ref.replaceAll('\\', '/') !== normalizeRef(paths, paths.project)) blocks.push(`## Task context: ${ref}\n\n${content}`);
1724
+ }
1725
+ if (task.capability_hooks && task.capability_hooks.length) {
1726
+ const hookBlocks = [];
1727
+ for (const hook of task.capability_hooks) {
1728
+ const nodeContent = extractCapabilityNode(paths, hook.node);
1729
+ if (nodeContent) {
1730
+ const atLine = hook.at ? `\n\n**Activate at:** ${hook.at}` : '';
1731
+ const produceLine = hook.must_produce ? `\n\n**Must produce:** ${hook.must_produce}` : '';
1732
+ hookBlocks.push(`### Capability hook: ${hook.node}${atLine}${produceLine}\n\n${nodeContent}`);
1733
+ }
1734
+ }
1735
+ if (hookBlocks.length) blocks.push(`## Capability decision points\n\n${hookBlocks.join('\n\n')}`);
1736
+ }
1737
+ } else {
1738
+ blocks.push(`## On-demand project context\n\n- Decision history: .skeinn/DECISIONS.md (read when correction or lineage matters)\n${capabilities.length ? capabilities.map((name) => `- Professional capability: ${normalizeRef(paths, capabilityPath(paths, name))}`).join('\n') : state.capability_exemption?.reason ? `- Capability exemption: ${state.capability_exemption.reason}` : '- No capability files yet; add 1–3 bottleneck domains with skeinn capability add <slug> --title <field>, or record skeinn capability exempt --reason.'}\n${designs.length ? designs.map((name) => `- Design: .skeinn/design/${name}`).join('\n') : '- No design documents yet; split the whole according to consequential systems and decisions.'}
1739
+ - Guidance: skeinn help shaping | design | capability | task`);
1740
+ }
1741
+ return blocks.filter(Boolean).join('\n\n---\n\n');
1742
+ }
1743
+
1744
+ function shapingFrontier({ paths, state, taskStore, designs, capabilities }) {
1745
+ const gaps = [];
1746
+ const project = readFileSync(paths.project, 'utf8');
1747
+ if (project.includes('> This is the concise entry point') || project.length < 400) gaps.push('PROJECT.md is still a template — write the real intended result, boundaries, and document map');
1748
+ if (!designs.length) gaps.push('no design documents — split the consequential decision surfaces with skeinn design add (skeinn help design explains what one owns)');
1749
+ const unfinishedDesigns = designs.filter((name) => designTemplateResidue(readFileSync(join(paths.design, name), 'utf8')));
1750
+ if (unfinishedDesigns.length) gaps.push(`design documents still contain template text: ${unfinishedDesigns.join(', ')}`);
1751
+ if (!capabilities.length && !state.capability_exemption?.reason) {
1752
+ gaps.push('no capability files or exemption — research 1–3 bottleneck domains with skeinn capability add <slug> --title <field>, or explicitly record skeinn capability exempt --reason <why standard engineering suffices>');
1753
+ } else {
1754
+ const capIssues = [];
1755
+ for (const name of capabilities) {
1756
+ const content = readFileSync(capabilityPath(paths, name), 'utf8');
1757
+ if (isLegacyDirectoryCapability(paths, name)) {
1758
+ const statusPath = join(paths.capabilities, name, 'status.json');
1759
+ const st = existsSync(statusPath) ? readJson(statusPath, 'status.json').status : 'legacy';
1760
+ if (st !== 'confirmed') capIssues.push(`${name} (${st})`);
1761
+ } else {
1762
+ const issues = validateSingleFileCapability(name, content);
1763
+ if (issues.length) capIssues.push(`${name} (${issues[0]})`);
1764
+ }
1765
+ }
1766
+ if (capIssues.length) gaps.push(`capability files incomplete — finish practitioner research, reflection, and Design delta for: ${capIssues.join('; ')}`);
1767
+ }
1768
+ const highOpen = state.understanding.unresolved.filter((item) => item.status === 'open' && item.impact === 'high');
1769
+ if (highOpen.length) gaps.push(`high-impact questions still open: ${highOpen.map((item) => item.id).join(', ')}`);
1770
+ if (!taskStore.tasks.length) gaps.push('the Work Map is empty — decompose the delivery surface (skeinn deliverable add) and plan Tasks (skeinn task plan --help)');
1771
+ if (!gaps.length) return 'Shaping layers are present. If material uncertainty remains, keep clarifying; otherwise run skeinn project ready to freeze a digest for the one-time Keeper handoff.';
1772
+ return `Project is still shaping. Unfinished frontier:\n${gaps.map((gap) => ` - ${gap}`).join('\n')}\nIterate Design and bottleneck Capabilities together, then run skeinn project ready.`;
1773
+ }
1774
+
1775
+ function normalizeRef(paths, absolute) {
1776
+ const skeinnPrefix = `${paths.skeinn}${process.platform === 'win32' ? '\\' : '/'}`;
1777
+ if (absolute === paths.skeinn || absolute.startsWith(skeinnPrefix)) return `.skeinn/${relative(paths.skeinn, absolute).replaceAll('\\', '/')}`.replace(/\/$/, '');
1778
+ return relative(paths.root, absolute).replaceAll('\\', '/');
1779
+ }
1780
+
1781
+ function readContextDocument(paths, ref) {
1782
+ const normalized = ref.replaceAll('\\', '/');
1783
+ if (isAbsolute(normalized) || normalized.startsWith('/') || normalized.includes('..')) throw new Error(`Unsafe context reference: ${ref}`);
1784
+ const fromSkeinn = normalized === '.skeinn' || normalized.startsWith('.skeinn/');
1785
+ const base = fromSkeinn ? paths.skeinn : paths.root;
1786
+ const relativeRef = fromSkeinn ? normalized.slice('.skeinn'.length).replace(/^\//, '') : normalized;
1787
+ const absolute = resolve(base, relativeRef);
1788
+ const prefix = `${base}${process.platform === 'win32' ? '\\' : '/'}`;
1789
+ if (!absolute.startsWith(prefix) && absolute !== base) throw new Error(`Unsafe context reference: ${ref}`);
1790
+ if (!existsSync(absolute)) throw new Error(`Task context file does not exist: ${ref}`);
1791
+ if (!statSync(absolute).isFile()) throw new Error(`Task context must name a file, not a directory: ${ref}`);
1792
+ return readFileSync(absolute, 'utf8');
1793
+ }
1794
+
1795
+ export function checkProject(root = findRoot()) {
1796
+ const { paths, state, taskStore } = loadProject(root);
1797
+ const designs = listDesigns(root);
1798
+ const capabilities = listCapabilities(root);
1799
+ const errors = [];
1800
+ const warnings = [];
1801
+ const taskById = new Map(taskStore.tasks.map((task) => [task.id, task]));
1802
+ for (const task of taskStore.tasks) {
1803
+ for (const ref of task.reads) {
1804
+ try { readContextDocument(paths, ref); } catch (error) { errors.push(`${task.id}: ${error.message}`); }
1805
+ }
1806
+ if (task.capability_hooks) {
1807
+ for (const hook of task.capability_hooks) {
1808
+ const nodeContent = extractCapabilityNode(paths, hook.node);
1809
+ if (nodeContent === null) warnings.push(`${task.id} references missing capability node: ${hook.node}`);
1810
+ }
1811
+ }
1812
+ if (task.integrity_version === 1) {
1813
+ const classificationFindings = taskIntegrityFindings(task, designs, capabilities, paths);
1814
+ const target = ['active', 'done'].includes(task.status) ? errors : warnings;
1815
+ target.push(...classificationFindings.map((finding) => `${task.id} ${finding}`));
1816
+ if (task.status === 'done') {
1817
+ const missingOutputs = missingTaskOutputs(task, paths);
1818
+ errors.push(...missingOutputs.map((output) => `${task.id} declared output does not exist: ${output}`));
1819
+ const staleDeps = task.depends_on.filter((depId) => taskById.get(depId)?.status !== 'done');
1820
+ if (staleDeps.length) {
1821
+ warnings.push(`${task.id} is done but upstream dependency (${staleDeps.join(', ')}) is no longer done — needs_recheck (reopen if prior evidence is invalidated)`);
1822
+ }
1823
+ }
1824
+ }
1825
+ const hasAcceptance = Array.isArray(task.acceptance) && task.acceptance.length > 0;
1826
+ const hasDoneWhen = Array.isArray(task.done_when) && task.done_when.length > 0;
1827
+ if (!hasAcceptance && hasDoneWhen) warnings.push(`${task.id} uses done_when[] without acceptance[] — consider migrating to structured acceptance for clearer verification`);
1828
+ }
1829
+ if (state.project.status === 'build_ready' && !['passed', 'passed_with_advisories', 'skipped'].includes(state.keeper.status)) errors.push('Project is build_ready without Keeper pass or explicit skip');
1830
+ if (state.understanding.unresolved.some((item) => item.status === 'open' && item.impact === 'high')) warnings.push('High-impact uncertainty remains open');
1831
+ const decisionsContent = readFileSync(paths.decisions, 'utf8');
1832
+ for (const block of decisionsContent.split(/\n(?=## )/)) {
1833
+ const affectedMatch = block.match(/- Affected tasks: (.+)/);
1834
+ if (!affectedMatch) continue;
1835
+ const decisionAt = block.match(/- At: (\S+)/)?.[1] || '';
1836
+ for (const taskId of affectedMatch[1].split(',').map((s) => s.trim()).filter(Boolean)) {
1837
+ const task = taskStore.tasks.find((item) => item.id === taskId);
1838
+ if (!task || task.status !== 'done') continue;
1839
+ const completedAt = task.completed_at || task.updated_at || '';
1840
+ if (decisionAt && completedAt && completedAt > decisionAt) continue;
1841
+ warnings.push(`${taskId} is done but was marked affected by a decision; reopen and re-complete it to close this warning (skeinn task reopen ${taskId} --reason <how the decision was reviewed>)`);
1842
+ }
1843
+ }
1844
+ if (!capabilities.length && !state.capability_exemption?.reason) warnings.push('No capability file exists and no capability exemption is recorded; add 1–3 bottleneck capabilities or run skeinn capability exempt --reason');
1845
+ if (!designs.length) warnings.push('No design document exists; PROJECT.md should remain a concise map of the whole');
1846
+ if (!existsSync(paths.structure)) warnings.push('No STRUCTURE.md exists; declare where files go so the Agent does not guess');
1847
+ else if (readFileSync(paths.structure, 'utf8').includes('Where implementation files go. Example:')) warnings.push('STRUCTURE.md still contains template instructions; customize it for this project');
1848
+ for (const name of designs) {
1849
+ const content = readFileSync(join(paths.design, name), 'utf8');
1850
+ if (designTemplateResidue(content)) warnings.push(`Design document still contains template instructions: ${name}`);
1851
+ const kindMatch = content.match(/^-\s*Kind:\s*([^\n]+)/m);
1852
+ const kind = kindMatch ? kindMatch[1].trim() : '';
1853
+ if (CORE_DESIGN_KINDS.includes(kind) && !extractSection(content, 'Alternatives considered')) {
1854
+ warnings.push(`Core design document ${name} (${kind}) has no "## Alternatives considered" section — compare at least two viable options to avoid first-draft convergence`);
1855
+ }
1856
+ }
1857
+ for (const name of capabilities) {
1858
+ const content = readFileSync(capabilityPath(paths, name), 'utf8');
1859
+ if (isLegacyDirectoryCapability(paths, name)) {
1860
+ if (capabilityTemplateResidue(content)) warnings.push(`Capability dossier still contains template instructions: ${name}`);
1861
+ if (content.includes('### C') && !content.includes('source:')) warnings.push(`Capability dossier has decision tree nodes without source citations: ${name}`);
1862
+ const statusPath = join(paths.capabilities, name, 'status.json');
1863
+ if (existsSync(statusPath)) {
1864
+ const capStatus = readJson(statusPath, 'status.json');
1865
+ if (capStatus.status && capStatus.status !== 'confirmed') warnings.push(`Capability ${name} is ${capStatus.status}, not confirmed; tasks referencing it proceed provisionally`);
1866
+ }
1867
+ } else {
1868
+ const issues = validateSingleFileCapability(name, content);
1869
+ warnings.push(...issues);
1870
+ const meta = parseSingleFileCapabilityMeta(content);
1871
+ if (meta.mode === 'offline_reflection') warnings.push(`Capability ${name} is offline_reflection (unverified externally)`);
1872
+ }
1873
+ }
1874
+ const latestKeeper = state.keeper.attempts.at(-1);
1875
+ if (['passed', 'passed_with_advisories'].includes(state.keeper.status) && latestKeeper && latestKeeper.review?.mode !== 'independent') errors.push('Keeper pass has no independently attested review provenance; obtain a fresh review (skeinn review --help) or record skeinn keeper skip --reason <limitation>');
1876
+ const latestCheckpoint = state.keeper.checkpoints.at(-1);
1877
+ if (latestCheckpoint && latestCheckpoint.verdict === 'drift_detected') {
1878
+ warnings.push(`Latest in-flight checkpoint (${latestCheckpoint.id}) detected drift: ${latestCheckpoint.summary}`);
1879
+ }
1880
+ if (state.keeper.launch_completed && state.project.status === 'building') {
1881
+ const currentDigests = artifactDigests(paths, taskStore.tasks, state);
1882
+ const horizon = activeHorizon(taskStore.tasks, paths, 2);
1883
+ const dirty = computeDirtyArtifacts(currentDigests, state.keeper.reviewed_digests, horizon.artifacts);
1884
+ if (dirty.length) warnings.push(`In-flight horizon has ${dirty.length} unreviewed/changed artifact(s): ${dirty.join(', ')} — consider skeinn keeper checkpoint prompt`);
1885
+ }
1886
+ const recentDone = silentDriftAlert(state, taskStore.tasks);
1887
+ if (recentDone.length >= SILENT_DRIFT_TASK_THRESHOLD) {
1888
+ warnings.push(`${recentDone.length} delivery task(s) completed since the last clean Keeper review/checkpoint (${recentDone.map((t) => t.id).join(', ')}) — run skeinn keeper checkpoint prompt to guard against silent spec-to-code drift.`);
1889
+ }
1890
+ const coverage = checkDeliverableCoverage(root);
1891
+ if (coverage.uncovered > 0) warnings.push(`Uncovered deliverables: ${coverage.uncovered_items.map((item) => item.slug).join(', ')}`);
1892
+ if (coverage.covered > coverage.delivered) warnings.push(`${coverage.covered - coverage.delivered} deliverable(s) are covered only by Tasks not yet done`);
1893
+ return { healthy: errors.length === 0, errors, warnings, summary: taskSummary(taskStore.tasks), deliverable_coverage: { total: coverage.total, planned: coverage.covered, delivered: coverage.delivered, uncovered: coverage.uncovered } };
1894
+ }
1895
+
1896
+ export function scaffoldEval(payload, root = findRoot()) {
1897
+ if (!payload.id || !payload.title || !payload.brief) throw new Error('Eval scenario requires id, title, and brief');
1898
+ const { paths } = loadProject(root);
1899
+ const slug = payload.id.toLowerCase().replace(/[^a-z0-9-]+/g, '-');
1900
+ const dir = join(paths.eval, slug);
1901
+ if (existsSync(dir)) throw new Error(`Eval scenario already exists: ${payload.id}`);
1902
+ mkdirSync(dir, { recursive: true });
1903
+ const humanChannel = payload.human_channel || 'available';
1904
+ if (!['available', 'unavailable'].includes(humanChannel)) throw new Error('human_channel must be available or unavailable');
1905
+ const mode = payload.mode || 'relay';
1906
+ if (!['probe', 'relay', 'full'].includes(mode)) throw new Error('Eval mode must be probe, relay, or full');
1907
+ const budgetCny = typeof payload.budget_cny === 'number' ? payload.budget_cny : (mode === 'probe' ? 5 : mode === 'relay' ? 20 : 60);
1908
+ const defaultReps = mode === 'full' ? 3 : 1;
1909
+ const manifest = {
1910
+ schema_version: 2,
1911
+ id: payload.id,
1912
+ title: payload.title,
1913
+ mode,
1914
+ budget_cny: budgetCny,
1915
+ brief: payload.brief,
1916
+ pivot: payload.pivot || '',
1917
+ primary_comparison: 'same capable Agent without Skeinn vs with Skeinn',
1918
+ hidden_user_facts: payload.hidden_user_facts || [],
1919
+ hidden_checks: payload.hidden_checks || [],
1920
+ success_criteria: payload.success_criteria || [],
1921
+ scoring_mode: 'pairwise_forced_choice + hidden_oracle + real_telemetry',
1922
+ conditions: [
1923
+ { id: 'baseline', framework: 'none', instruction: 'Work normally with all ordinary Agent capabilities and tools.' },
1924
+ { id: 'skeinn', framework: 'skeinn-v2', instruction: 'Use Skeinn as invisible Agent continuity infrastructure.' },
1925
+ ],
1926
+ controls: {
1927
+ same_model_tools_workspace_and_budget: true,
1928
+ human_channel: humanChannel,
1929
+ minimum_repetitions_per_condition: payload.repetitions || defaultReps,
1930
+ scripted_user_answers: true,
1931
+ context_reset_points: payload.context_reset_points || (mode === 'relay' ? ['after-baton-1', 'after-baton-2'] : ['after-shaping', 'mid-task']),
1932
+ blind_pairwise_order_swap: true,
1933
+ anonymization_preserves_relative_layout: true,
1934
+ judge_packet_preflight_required: true,
1935
+ condition_output_digest_manifest: true,
1936
+ telemetry_required: true,
1937
+ },
1938
+ measures: ['intent_fidelity_and_pivot_survival', 'specialist_craft_depth', 'cold_handoff_continuity', 'hidden_oracle_credibility', 'user_burden_and_ceremony', 'net_value_per_rmb'],
1939
+ };
1940
+ atomicJson(join(dir, 'manifest.json'), manifest);
1941
+ atomicJson(join(dir, 'telemetry-template.json'), {
1942
+ scenario_id: payload.id,
1943
+ mode,
1944
+ model: '<e.g. deepseek-v4.1-flash>',
1945
+ budget_cny_cap: budgetCny,
1946
+ arms: {
1947
+ baseline: { input_tokens: 0, output_tokens: 0, cost_cny: 0, wall_seconds: 0, tool_calls: 0, batons_completed: 0, hidden_oracle_passed: 0, hidden_oracle_total: 0 },
1948
+ skeinn: { input_tokens: 0, output_tokens: 0, cost_cny: 0, wall_seconds: 0, tool_calls: 0, cli_retries: 0, batons_completed: 0, hidden_oracle_passed: 0, hidden_oracle_total: 0 },
1949
+ },
1950
+ });
1951
+ const oracleScript = `#!/usr/bin/env node
1952
+ // Hidden Oracle assertions for ${payload.id} — NEVER show this file to the tested Agents.
1953
+ // Run against each anonymized arm directory: node hidden-oracle.mjs <arm-workspace-dir>
1954
+ import { existsSync, readFileSync } from 'node:fs';
1955
+ import { resolve } from 'node:path';
1956
+
1957
+ const target = resolve(process.argv[2] || '.');
1958
+ const checks = [
1959
+ // Add objective Pass/Fail checks here (files, contracts, static scans, smoke runs):
1960
+ { name: 'workspace exists', fn: () => existsSync(target) },
1961
+ ];
1962
+
1963
+ let passed = 0;
1964
+ for (const check of checks) {
1965
+ try {
1966
+ if (!check.fn()) throw new Error('returned false');
1967
+ passed += 1;
1968
+ console.log(\`PASS: \${check.name}\`);
1969
+ } catch (err) {
1970
+ console.error(\`FAIL: \${check.name} — \${err.message}\`);
1971
+ process.exitCode = 1;
1972
+ }
1973
+ }
1974
+ console.log(JSON.stringify({ target, passed, total: checks.length }, null, 2));
1975
+ `;
1976
+ writeFileSync(join(dir, 'hidden-oracle.mjs'), oracleScript, 'utf8');
1977
+ writeFileSync(join(dir, 'baseline-prompt.md'), `${evalConditionPrompt({ brief: payload.brief, skeinn: false, humanChannel })}\n`, 'utf8');
1978
+ writeFileSync(join(dir, 'skeinn-prompt.md'), `${evalConditionPrompt({ brief: payload.brief, skeinn: true, humanChannel })}\n`, 'utf8');
1979
+ writeFileSync(join(dir, 'judge-prompt.md'), `${evalJudgePrompt()}\n`, 'utf8');
1980
+ if (mode === 'relay') {
1981
+ const batonsDir = join(dir, 'batons');
1982
+ mkdirSync(batonsDir, { recursive: true });
1983
+ for (const baton of [1, 2, 3]) {
1984
+ writeFileSync(join(batonsDir, `baseline-baton-${baton}.md`), `${evalRelayBatonPrompt({ brief: payload.brief, pivot: payload.pivot, batonNumber: baton, skeinn: false, humanChannel })}\n`, 'utf8');
1985
+ writeFileSync(join(batonsDir, `skeinn-baton-${baton}.md`), `${evalRelayBatonPrompt({ brief: payload.brief, pivot: payload.pivot, batonNumber: baton, skeinn: true, humanChannel })}\n`, 'utf8');
1986
+ }
1987
+ }
1988
+ if (mode === 'probe') {
1989
+ writeFileSync(join(dir, 'probe-checklist.md'), evalProbeChecklist({ id: payload.id, title: payload.title }), 'utf8');
1990
+ }
1991
+ return { scenario: payload.id, mode, budget_cny: budgetCny, path: normalizeRef(paths, dir), controls: manifest.controls };
1992
+ }