@haaaiawd/skeinn 0.0.0-stage → 2.4.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.
- package/CHANGELOG.md +90 -0
- package/CONTRIBUTING.md +37 -0
- package/EVIL_EVAL.md +84 -0
- package/LICENSE +21 -0
- package/README.md +164 -2
- package/README.zh-CN.md +229 -0
- package/SECURITY.md +11 -0
- package/cli/bin/skeinn.js +497 -0
- package/cli/src/protocol.js +797 -0
- package/cli/src/store.js +1554 -0
- package/design.md +230 -0
- package/docs/PROMPT_CATALOG.md +139 -0
- package/docs/RELEASE_CHECKLIST.md +53 -0
- package/docs/UX_FLOW.md +188 -0
- package/docs/ai-development-landscape-2026-10.md +163 -0
- package/docs/brand/skeinn-mark-dark.svg +14 -0
- package/docs/brand/skeinn-mark.svg +14 -0
- package/docs/brand/skeinn-wordmark-dark.svg +11 -0
- package/docs/brand/skeinn-wordmark-light.svg +11 -0
- package/docs/loom-eval-loop.drawio +21 -0
- package/docs/loom-eval-loop.svg +56 -0
- package/docs/loom-journey-audit.md +107 -0
- package/docs/loom-production-loop.drawio +41 -0
- package/docs/loom-production-loop.svg +92 -0
- package/package.json +54 -4
package/cli/src/store.js
ADDED
|
@@ -0,0 +1,1554 @@
|
|
|
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
|
+
evalRelayBatonPrompt,
|
|
29
|
+
keeperProtocol,
|
|
30
|
+
shapingContext,
|
|
31
|
+
} from './protocol.js';
|
|
32
|
+
|
|
33
|
+
const SCHEMA_VERSION = 2;
|
|
34
|
+
const VALID_PROJECT_STATUS = new Set(['shaping', 'ready_for_keeper', 'build_ready', 'building', 'complete']);
|
|
35
|
+
const VALID_TASK_STATUS = new Set(['open', 'active', 'blocked', 'done']);
|
|
36
|
+
let runtimePaths = null;
|
|
37
|
+
|
|
38
|
+
function now() {
|
|
39
|
+
return new Date().toISOString();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function readJson(path, label = basename(path)) {
|
|
43
|
+
try {
|
|
44
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
45
|
+
} catch (error) {
|
|
46
|
+
throw new Error(`${label} cannot be read: ${error.message}`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function atomicJson(path, value) {
|
|
51
|
+
const temp = `${path}.tmp-${process.pid}`;
|
|
52
|
+
writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
53
|
+
renameSync(temp, path);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function nextId(items, prefix) {
|
|
57
|
+
const max = items.reduce((highest, item) => {
|
|
58
|
+
const match = new RegExp(`^${prefix}-(\\d+)$`).exec(item.id || '');
|
|
59
|
+
return match ? Math.max(highest, Number(match[1])) : highest;
|
|
60
|
+
}, 0);
|
|
61
|
+
return `${prefix}-${String(max + 1).padStart(3, '0')}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function asObjects(values, key) {
|
|
65
|
+
if (!values) return [];
|
|
66
|
+
if (!Array.isArray(values)) throw new Error(`${key} must be an array`);
|
|
67
|
+
return values.map((value) => typeof value === 'string' ? { [key]: value } : value);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function findRoot(from = process.cwd()) {
|
|
71
|
+
if (runtimePaths && existsSync(runtimePaths.state)) return runtimePaths.root;
|
|
72
|
+
let cursor = resolve(from);
|
|
73
|
+
while (true) {
|
|
74
|
+
if (existsSync(join(cursor, '.skeinn', 'state.json'))) return cursor;
|
|
75
|
+
if (existsSync(join(cursor, '.loom', 'state.json'))) {
|
|
76
|
+
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.');
|
|
77
|
+
}
|
|
78
|
+
const parent = dirname(cursor);
|
|
79
|
+
if (parent === cursor) break;
|
|
80
|
+
cursor = parent;
|
|
81
|
+
}
|
|
82
|
+
throw new Error('Skeinn is not initialized. Run skeinn init in the project root.');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function skeinnPaths(root = findRoot()) {
|
|
86
|
+
const absolute = resolve(root);
|
|
87
|
+
const skeinn = runtimePaths?.root === absolute ? runtimePaths.skeinn : join(absolute, '.skeinn');
|
|
88
|
+
return skeinnPathsShape(absolute, skeinn);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function configureRuntime({ stateDir } = {}) {
|
|
92
|
+
if (!stateDir) {
|
|
93
|
+
runtimePaths = null;
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const root = resolve(process.cwd());
|
|
97
|
+
const skeinn = resolve(stateDir);
|
|
98
|
+
const fromWorkspace = relative(root, skeinn);
|
|
99
|
+
if (!fromWorkspace || (!fromWorkspace.startsWith('..') && !isAbsolute(fromWorkspace))) {
|
|
100
|
+
throw new Error('--state-dir must be outside the scored workspace');
|
|
101
|
+
}
|
|
102
|
+
runtimePaths = skeinnPathsShape(root, skeinn);
|
|
103
|
+
return { workspace: root, state_dir: skeinn };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function initProject(root = process.cwd()) {
|
|
107
|
+
const paths = skeinnPathsForInit(root);
|
|
108
|
+
if (existsSync(paths.state)) return { initialized: false, root: paths.root, reason: 'already_initialized' };
|
|
109
|
+
if (paths.skeinn === join(paths.root, '.skeinn') && existsSync(join(paths.root, '.loom', 'state.json'))) {
|
|
110
|
+
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.');
|
|
111
|
+
}
|
|
112
|
+
if (existsSync(join(paths.skeinn, 'current')) || existsSync(join(paths.skeinn, 'v1'))) {
|
|
113
|
+
throw new Error('A legacy Skeinn project was found. Back it up and migrate deliberately; v2 will not overwrite it.');
|
|
114
|
+
}
|
|
115
|
+
mkdirSync(paths.design, { recursive: true });
|
|
116
|
+
mkdirSync(paths.capabilities, { recursive: true });
|
|
117
|
+
mkdirSync(paths.eval, { recursive: true });
|
|
118
|
+
const state = {
|
|
119
|
+
schema_version: SCHEMA_VERSION,
|
|
120
|
+
project: { name: basename(paths.root), status: 'shaping', created_at: now(), updated_at: now() },
|
|
121
|
+
understanding: { confirmed: [], assumptions: [], unresolved: [] },
|
|
122
|
+
keeper: { status: 'not_run', attempts: [] },
|
|
123
|
+
};
|
|
124
|
+
atomicJson(paths.state, state);
|
|
125
|
+
atomicJson(paths.tasks, { schema_version: SCHEMA_VERSION, tasks: [] });
|
|
126
|
+
atomicJson(paths.deliverables, { schema_version: SCHEMA_VERSION, deliverables: [] });
|
|
127
|
+
writeFileSync(paths.project, PROJECT_TEMPLATE, 'utf8');
|
|
128
|
+
writeFileSync(paths.structure, STRUCTURE_TEMPLATE, 'utf8');
|
|
129
|
+
writeFileSync(paths.decisions, '# Decision History\n\nCurrent truth belongs in PROJECT.md and linked design documents. This file preserves consequential superseding decisions.\n', 'utf8');
|
|
130
|
+
const anchored = paths.skeinn === join(paths.root, '.skeinn');
|
|
131
|
+
if (anchored) installAgentAnchor(paths.root);
|
|
132
|
+
return {
|
|
133
|
+
initialized: true,
|
|
134
|
+
root: paths.root,
|
|
135
|
+
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'] : [])],
|
|
136
|
+
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.',
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function skeinnPathsForInit(root) {
|
|
141
|
+
const absolute = resolve(root);
|
|
142
|
+
const skeinn = runtimePaths?.root === absolute ? runtimePaths.skeinn : join(absolute, '.skeinn');
|
|
143
|
+
return skeinnPathsShape(absolute, skeinn);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function skeinnPathsShape(root, skeinn) {
|
|
147
|
+
return {
|
|
148
|
+
root,
|
|
149
|
+
skeinn,
|
|
150
|
+
state: join(skeinn, 'state.json'),
|
|
151
|
+
tasks: join(skeinn, 'tasks.json'),
|
|
152
|
+
deliverables: join(skeinn, 'deliverables.json'),
|
|
153
|
+
project: join(skeinn, 'PROJECT.md'),
|
|
154
|
+
structure: join(skeinn, 'STRUCTURE.md'),
|
|
155
|
+
decisions: join(skeinn, 'DECISIONS.md'),
|
|
156
|
+
design: join(skeinn, 'design'),
|
|
157
|
+
capabilities: join(skeinn, 'capabilities'),
|
|
158
|
+
eval: join(skeinn, 'eval'),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function installAgentAnchor(root) {
|
|
163
|
+
const path = join(root, 'AGENTS.md');
|
|
164
|
+
const marker = '<!-- skeinn:v2 -->';
|
|
165
|
+
if (!existsSync(path)) writeFileSync(path, `${AGENT_ANCHOR}\n`, 'utf8');
|
|
166
|
+
else if (!readFileSync(path, 'utf8').includes(marker)) appendFileSync(path, `\n${AGENT_ANCHOR}\n`, 'utf8');
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function loadProject(root = findRoot()) {
|
|
170
|
+
const paths = skeinnPaths(root);
|
|
171
|
+
mkdirSync(paths.design, { recursive: true });
|
|
172
|
+
mkdirSync(paths.capabilities, { recursive: true });
|
|
173
|
+
mkdirSync(paths.eval, { recursive: true });
|
|
174
|
+
const state = readJson(paths.state, 'state.json');
|
|
175
|
+
const taskStore = readJson(paths.tasks, 'tasks.json');
|
|
176
|
+
const deliverableStore = existsSync(paths.deliverables) ? readJson(paths.deliverables, 'deliverables.json') : { schema_version: SCHEMA_VERSION, deliverables: [] };
|
|
177
|
+
validateState(state);
|
|
178
|
+
validateTasks(taskStore.tasks);
|
|
179
|
+
ensureClarify(state);
|
|
180
|
+
return { paths, state, taskStore, deliverableStore };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function ensureClarify(state) {
|
|
184
|
+
if (!state.clarify || typeof state.clarify !== 'object') state.clarify = { active: false, reason: '', started_at: '', closed_at: '', rounds: [] };
|
|
185
|
+
if (!Array.isArray(state.clarify.rounds)) state.clarify.rounds = [];
|
|
186
|
+
return state.clarify;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function validateState(state) {
|
|
190
|
+
if (state.schema_version !== SCHEMA_VERSION) throw new Error(`Unsupported schema_version ${state.schema_version}`);
|
|
191
|
+
if (!VALID_PROJECT_STATUS.has(state.project?.status)) throw new Error('Invalid project status');
|
|
192
|
+
for (const key of ['confirmed', 'assumptions', 'unresolved']) {
|
|
193
|
+
if (!Array.isArray(state.understanding?.[key])) throw new Error(`understanding.${key} must be an array`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function validateTasks(tasks) {
|
|
198
|
+
if (!Array.isArray(tasks)) throw new Error('tasks.json tasks must be an array');
|
|
199
|
+
const ids = new Set();
|
|
200
|
+
let active = 0;
|
|
201
|
+
for (const task of tasks) {
|
|
202
|
+
if (!task.id || ids.has(task.id)) throw new Error(`Task id is missing or duplicated: ${task.id || '<missing>'}`);
|
|
203
|
+
ids.add(task.id);
|
|
204
|
+
if (!task.title || !task.outcome) throw new Error(`${task.id} requires title and outcome`);
|
|
205
|
+
if (task.outcome.length < 20) throw new Error(`${task.id} outcome must be at least 20 characters describing the observable difference`);
|
|
206
|
+
if (!VALID_TASK_STATUS.has(task.status)) throw new Error(`${task.id} has invalid status ${task.status}`);
|
|
207
|
+
if (!Array.isArray(task.depends_on) || !Array.isArray(task.reads)) throw new Error(`${task.id} dependencies and reads must be arrays`);
|
|
208
|
+
if (!task.reads.length) throw new Error(`${task.id} reads must list at least one specific file or artifact`);
|
|
209
|
+
if (!Array.isArray(task.touches) || !task.touches.length) throw new Error(`${task.id} touches must list at least one specific file or artifact`);
|
|
210
|
+
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`);
|
|
211
|
+
const hasAcceptance = Array.isArray(task.acceptance) && task.acceptance.length > 0;
|
|
212
|
+
const hasDoneWhen = Array.isArray(task.done_when) && task.done_when.length > 0;
|
|
213
|
+
if (!hasAcceptance && !hasDoneWhen) throw new Error(`${task.id} requires acceptance[] (preferred) or done_when[]`);
|
|
214
|
+
if (hasAcceptance) {
|
|
215
|
+
for (const acc of task.acceptance) {
|
|
216
|
+
if (!acc || typeof acc !== 'object') throw new Error(`${task.id} acceptance entries must be objects`);
|
|
217
|
+
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)`);
|
|
218
|
+
if (!acc.verify_by || typeof acc.verify_by !== 'string') throw new Error(`${task.id} acceptance entry missing verify_by (how to check)`);
|
|
219
|
+
if (acc.evidence !== undefined && typeof acc.evidence !== 'string') throw new Error(`${task.id} acceptance evidence must be a string`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (task.implements !== undefined && typeof task.implements !== 'string') throw new Error(`${task.id} implements must be a string referencing a design decision`);
|
|
223
|
+
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`);
|
|
224
|
+
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`);
|
|
225
|
+
if (task.guardrails !== undefined) {
|
|
226
|
+
if (!Array.isArray(task.guardrails)) throw new Error(`${task.id} guardrails must be an array of strings`);
|
|
227
|
+
for (const rule of task.guardrails) if (typeof rule !== 'string' || !rule.trim()) throw new Error(`${task.id} guardrails entries must be non-empty strings`);
|
|
228
|
+
}
|
|
229
|
+
if (task.integrity_version !== undefined && task.integrity_version !== 1) throw new Error(`${task.id} integrity_version is unsupported`);
|
|
230
|
+
if (task.capability_hooks !== undefined) {
|
|
231
|
+
if (!Array.isArray(task.capability_hooks)) throw new Error(`${task.id} capability_hooks must be an array`);
|
|
232
|
+
for (const hook of task.capability_hooks) {
|
|
233
|
+
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"`);
|
|
234
|
+
if (hook.at !== undefined && typeof hook.at !== 'string') throw new Error(`${task.id} capability_hooks at must be a string`);
|
|
235
|
+
if (hook.must_produce !== undefined && typeof hook.must_produce !== 'string') throw new Error(`${task.id} capability_hooks must_produce must be a string`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (task.covers !== undefined) {
|
|
239
|
+
if (!Array.isArray(task.covers)) throw new Error(`${task.id} covers must be an array of deliverable IDs`);
|
|
240
|
+
for (const dlvId of task.covers) if (typeof dlvId !== 'string') throw new Error(`${task.id} covers entries must be deliverable ID strings`);
|
|
241
|
+
}
|
|
242
|
+
if (task.status === 'active') active += 1;
|
|
243
|
+
}
|
|
244
|
+
if (active > 1) throw new Error('Only one Task may be active');
|
|
245
|
+
for (const task of tasks) {
|
|
246
|
+
for (const dep of task.depends_on) if (!ids.has(dep)) throw new Error(`${task.id} depends on missing Task ${dep}`);
|
|
247
|
+
}
|
|
248
|
+
detectCycles(tasks);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function detectCycles(tasks) {
|
|
252
|
+
const map = new Map(tasks.map((task) => [task.id, task.depends_on]));
|
|
253
|
+
const visiting = new Set();
|
|
254
|
+
const visited = new Set();
|
|
255
|
+
function visit(id) {
|
|
256
|
+
if (visiting.has(id)) throw new Error(`Task dependency cycle includes ${id}`);
|
|
257
|
+
if (visited.has(id)) return;
|
|
258
|
+
visiting.add(id);
|
|
259
|
+
for (const dep of map.get(id) || []) visit(dep);
|
|
260
|
+
visiting.delete(id);
|
|
261
|
+
visited.add(id);
|
|
262
|
+
}
|
|
263
|
+
for (const id of map.keys()) visit(id);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function recordUnderstanding(payload, root = findRoot()) {
|
|
267
|
+
const { paths, state } = loadProject(root);
|
|
268
|
+
for (const item of asObjects(payload.confirmed, 'text')) {
|
|
269
|
+
if (!item.text) throw new Error('Confirmed fact requires text');
|
|
270
|
+
state.understanding.confirmed.push({ id: nextId(state.understanding.confirmed, 'F'), text: item.text, source: item.source || 'conversation', at: now() });
|
|
271
|
+
}
|
|
272
|
+
for (const item of asObjects(payload.assumptions, 'text')) {
|
|
273
|
+
if (!item.text) throw new Error('Assumption requires text');
|
|
274
|
+
state.understanding.assumptions.push({ id: nextId(state.understanding.assumptions, 'A'), text: item.text, status: 'active', source: item.source || 'agent', at: now() });
|
|
275
|
+
}
|
|
276
|
+
for (const item of asObjects(payload.unresolved, 'question')) {
|
|
277
|
+
if (!item.question) throw new Error('Unresolved item requires question');
|
|
278
|
+
state.understanding.unresolved.push({ id: nextId(state.understanding.unresolved, 'Q'), question: item.question, impact: item.impact || 'medium', status: 'open', at: now() });
|
|
279
|
+
}
|
|
280
|
+
for (const item of payload.resolved || []) {
|
|
281
|
+
const target = state.understanding.unresolved.find((candidate) => candidate.id === item.id);
|
|
282
|
+
if (!target) throw new Error(`Unknown unresolved id ${item.id}`);
|
|
283
|
+
target.status = item.status === 'skipped' ? 'skipped' : 'resolved';
|
|
284
|
+
target.resolution = item.resolution || '';
|
|
285
|
+
target.resolved_at = now();
|
|
286
|
+
}
|
|
287
|
+
for (const id of payload.retire_assumptions || []) {
|
|
288
|
+
const target = state.understanding.assumptions.find((candidate) => candidate.id === id);
|
|
289
|
+
if (!target) throw new Error(`Unknown assumption id ${id}`);
|
|
290
|
+
target.status = 'retired';
|
|
291
|
+
}
|
|
292
|
+
if (payload.project_status) throw new Error('Project status is controlled by ready, Keeper, and Task commands');
|
|
293
|
+
for (const decision of payload.decisions || []) appendDecision(paths.decisions, decision, state);
|
|
294
|
+
state.project.updated_at = now();
|
|
295
|
+
atomicJson(paths.state, state);
|
|
296
|
+
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.' };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function appendDecision(path, decision, state) {
|
|
300
|
+
if (!decision.title || !decision.decision || !decision.rationale) throw new Error('Decision requires title, decision, and rationale');
|
|
301
|
+
const prior = state.decision_ids || [];
|
|
302
|
+
const id = nextId(prior.map((value) => ({ id: value })), 'D');
|
|
303
|
+
state.decision_ids = [...prior, id];
|
|
304
|
+
const supersedes = decision.supersedes?.length ? decision.supersedes.join(', ') : 'none';
|
|
305
|
+
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');
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export function createDesign(slug, options = {}, root = findRoot()) {
|
|
309
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) throw new Error('Design slug must use lowercase letters, numbers, and hyphens');
|
|
310
|
+
if (!options.title) throw new Error('Design document requires --title');
|
|
311
|
+
if (!DESIGN_KINDS.includes(options.kind)) throw new Error(`Design kind must be one of: ${DESIGN_KINDS.join(', ')}`);
|
|
312
|
+
const { paths } = loadProject(root);
|
|
313
|
+
const path = join(paths.design, `${slug}.md`);
|
|
314
|
+
if (existsSync(path)) throw new Error(`Design document already exists: ${slug}`);
|
|
315
|
+
writeFileSync(path, designTemplate({ title: options.title, kind: options.kind }), 'utf8');
|
|
316
|
+
return {
|
|
317
|
+
slug,
|
|
318
|
+
kind: options.kind,
|
|
319
|
+
path: relative(paths.root, path).replaceAll('\\', '/'),
|
|
320
|
+
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.`,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export function listDesigns(root = findRoot()) {
|
|
325
|
+
const { paths } = loadProject(root);
|
|
326
|
+
return readdirSync(paths.design).filter((name) => name.endsWith('.md')).sort();
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
export function getDesign(slug, root = findRoot()) {
|
|
330
|
+
const { paths } = loadProject(root);
|
|
331
|
+
const name = slug.endsWith('.md') ? slug : `${slug}.md`;
|
|
332
|
+
if (basename(name) !== name) throw new Error('Invalid design document name');
|
|
333
|
+
const path = join(paths.design, name);
|
|
334
|
+
if (!existsSync(path)) throw new Error(`Design document not found: ${slug}`);
|
|
335
|
+
return readFileSync(path, 'utf8');
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function capabilitySlug(name) {
|
|
339
|
+
return name.endsWith('.md') ? name.slice(0, -3) : name;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function isLegacyDirectoryCapability(paths, name) {
|
|
343
|
+
const slug = capabilitySlug(name);
|
|
344
|
+
return existsSync(join(paths.capabilities, slug, 'capability.md'));
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function parseSingleFileCapabilityMeta(content) {
|
|
348
|
+
const modeMatch = content.match(/^-\s*Mode:\s*([^\n]+)/m);
|
|
349
|
+
const authorityMatch = content.match(/^-\s*Authority:\s*([^\n]+)/m);
|
|
350
|
+
const scenarioMatch = content.match(/^-\s*Scenario:\s*([^\n]+)/m);
|
|
351
|
+
return {
|
|
352
|
+
mode: modeMatch ? modeMatch[1].trim() : 'external_researched',
|
|
353
|
+
authority: authorityMatch ? authorityMatch[1].trim() : 'agent_provisional',
|
|
354
|
+
scenario: scenarioMatch ? scenarioMatch[1].trim() : '',
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
export function createCapability(slug, options = {}, root = findRoot()) {
|
|
359
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) throw new Error('Capability slug must use lowercase letters, numbers, and hyphens');
|
|
360
|
+
if (!options.title) throw new Error('Capability requires --title');
|
|
361
|
+
const mode = options.mode || 'external_researched';
|
|
362
|
+
if (!CAPABILITY_MODES.includes(mode)) throw new Error(`Capability --mode must be one of: ${CAPABILITY_MODES.join(', ')}`);
|
|
363
|
+
const { paths, state } = loadProject(root);
|
|
364
|
+
const filePath = join(paths.capabilities, `${slug}.md`);
|
|
365
|
+
const legacyDirPath = join(paths.capabilities, slug);
|
|
366
|
+
if (existsSync(filePath) || existsSync(legacyDirPath)) throw new Error(`Capability already exists: ${slug}`);
|
|
367
|
+
writeFileSync(filePath, CAPABILITY_TEMPLATE({ title: options.title, mode }), 'utf8');
|
|
368
|
+
if (state.capability_exemption) {
|
|
369
|
+
delete state.capability_exemption;
|
|
370
|
+
state.project.updated_at = now();
|
|
371
|
+
atomicJson(paths.state, state);
|
|
372
|
+
}
|
|
373
|
+
return {
|
|
374
|
+
slug,
|
|
375
|
+
mode,
|
|
376
|
+
path: relative(paths.root, filePath).replaceAll('\\', '/'),
|
|
377
|
+
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.`,
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export function exemptCapabilities(reason, root = findRoot()) {
|
|
382
|
+
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)');
|
|
383
|
+
const { paths, state } = loadProject(root);
|
|
384
|
+
const existing = listCapabilities(root);
|
|
385
|
+
if (existing.length) throw new Error(`Cannot exempt capabilities while capability files already exist: ${existing.join(', ')}`);
|
|
386
|
+
state.capability_exemption = { reason: reason.trim(), at: now() };
|
|
387
|
+
state.project.updated_at = now();
|
|
388
|
+
atomicJson(paths.state, state);
|
|
389
|
+
return {
|
|
390
|
+
exempted: true,
|
|
391
|
+
reason: state.capability_exemption.reason,
|
|
392
|
+
next: 'Exemption recorded. Keeper will audit whether standard engineering genuinely suffices for this project. Continue shaping Design and Tasks, then run skeinn project ready.',
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
export function listCapabilities(root = findRoot()) {
|
|
397
|
+
const { paths } = loadProject(root);
|
|
398
|
+
const entries = readdirSync(paths.capabilities, { withFileTypes: true });
|
|
399
|
+
const names = entries
|
|
400
|
+
.filter((entry) => (entry.isDirectory() && existsSync(join(paths.capabilities, entry.name, 'capability.md'))) || (entry.isFile() && entry.name.endsWith('.md')))
|
|
401
|
+
.map((entry) => (entry.isDirectory() ? entry.name : entry.name.slice(0, -3)))
|
|
402
|
+
.sort();
|
|
403
|
+
return names;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export function getCapability(slug, root = findRoot()) {
|
|
407
|
+
const { paths } = loadProject(root);
|
|
408
|
+
const cleanSlug = capabilitySlug(slug);
|
|
409
|
+
if (basename(cleanSlug) !== cleanSlug) throw new Error('Invalid capability name');
|
|
410
|
+
const filePath = join(paths.capabilities, `${cleanSlug}.md`);
|
|
411
|
+
if (existsSync(filePath)) return readFileSync(filePath, 'utf8');
|
|
412
|
+
const dirCapability = join(paths.capabilities, cleanSlug, 'capability.md');
|
|
413
|
+
if (existsSync(dirCapability)) return readFileSync(dirCapability, 'utf8');
|
|
414
|
+
throw new Error(`Capability not found: ${slug}`);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export function researchCapability(slug, options = {}, root = findRoot()) {
|
|
418
|
+
const { paths } = loadProject(root);
|
|
419
|
+
const cleanSlug = capabilitySlug(slug);
|
|
420
|
+
const singleFile = join(paths.capabilities, `${cleanSlug}.md`);
|
|
421
|
+
if (existsSync(singleFile)) {
|
|
422
|
+
return {
|
|
423
|
+
slug: cleanSlug,
|
|
424
|
+
mode: parseSingleFileCapabilityMeta(readFileSync(singleFile, 'utf8')).mode,
|
|
425
|
+
path: relative(paths.root, singleFile).replaceAll('\\', '/'),
|
|
426
|
+
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".`,
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
if (!options.field) throw new Error('Research requires --field <professional-field>');
|
|
430
|
+
const dir = join(paths.capabilities, cleanSlug);
|
|
431
|
+
if (!existsSync(dir)) throw new Error(`Capability not found: ${slug}. Run skeinn capability add ${cleanSlug} --title <text> first.`);
|
|
432
|
+
const statusPath = join(dir, 'status.json');
|
|
433
|
+
if (!existsSync(statusPath)) throw new Error(`Capability ${slug} is not a research-directory dossier`);
|
|
434
|
+
const status = readJson(statusPath, 'status.json');
|
|
435
|
+
if (status.status === 'confirmed') {
|
|
436
|
+
status.reopened_at = now();
|
|
437
|
+
status.reopen_reason = options.reopen_reason || 'new evidence requires updating the capability';
|
|
438
|
+
}
|
|
439
|
+
status.field = options.field;
|
|
440
|
+
status.status = 'researching';
|
|
441
|
+
status.updated_at = now();
|
|
442
|
+
atomicJson(statusPath, status);
|
|
443
|
+
const researchDir = join(dir, 'research');
|
|
444
|
+
mkdirSync(researchDir, { recursive: true });
|
|
445
|
+
const guidePath = join(researchDir, '_guide.md');
|
|
446
|
+
if (!existsSync(guidePath)) writeFileSync(guidePath, RESEARCH_GUIDE, 'utf8');
|
|
447
|
+
return {
|
|
448
|
+
slug: cleanSlug,
|
|
449
|
+
field: options.field,
|
|
450
|
+
research_dir: relative(paths.root, researchDir).replaceAll('\\', '/'),
|
|
451
|
+
status: 'researching',
|
|
452
|
+
next: `Add .md files to research/ then run skeinn capability synthesize ${cleanSlug}.`,
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
export function synthesizeCapability(slug, root = findRoot()) {
|
|
457
|
+
const { paths } = loadProject(root);
|
|
458
|
+
const cleanSlug = capabilitySlug(slug);
|
|
459
|
+
const singleFile = join(paths.capabilities, `${cleanSlug}.md`);
|
|
460
|
+
if (existsSync(singleFile)) {
|
|
461
|
+
const content = readFileSync(singleFile, 'utf8');
|
|
462
|
+
const issues = validateSingleFileCapability(cleanSlug, content);
|
|
463
|
+
if (issues.length) throw new Error(`Capability ${cleanSlug} is not ready:\n- ${issues.join('\n- ')}`);
|
|
464
|
+
const meta = parseSingleFileCapabilityMeta(content);
|
|
465
|
+
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.` };
|
|
466
|
+
}
|
|
467
|
+
const dir = join(paths.capabilities, cleanSlug);
|
|
468
|
+
if (!existsSync(dir)) throw new Error(`Capability not found: ${slug}`);
|
|
469
|
+
const statusPath = join(dir, 'status.json');
|
|
470
|
+
if (!existsSync(statusPath)) throw new Error(`Capability ${slug} is not a research-directory dossier`);
|
|
471
|
+
const status = readJson(statusPath, 'status.json');
|
|
472
|
+
if (status.status === 'confirmed') throw new Error(`Capability ${slug} is confirmed; run skeinn capability research ${slug} --field <text> to reopen it with new evidence`);
|
|
473
|
+
const researchDir = join(dir, 'research');
|
|
474
|
+
const materials = readdirSync(researchDir).filter((f) => f.endsWith('.md') && f !== '_guide.md').sort();
|
|
475
|
+
if (!materials.length) throw new Error(`No research materials found in ${slug}/research/.`);
|
|
476
|
+
const capPath = join(dir, 'capability.md');
|
|
477
|
+
const content = readFileSync(capPath, 'utf8');
|
|
478
|
+
const nodePattern = /### (C\d+):/g;
|
|
479
|
+
const nodes = [...content.matchAll(nodePattern)].map((m) => m[1]);
|
|
480
|
+
if (!nodes.length) throw new Error('Capability has no decision tree nodes (### C1, C2, ...). Add nodes before synthesizing.');
|
|
481
|
+
const missingSources = [];
|
|
482
|
+
const missingCounterexamples = [];
|
|
483
|
+
const danglingSources = [];
|
|
484
|
+
const materialNames = materials.flatMap((f) => [f, f.slice(0, -3)]);
|
|
485
|
+
for (const node of nodes) {
|
|
486
|
+
const nodeSection = content.split(`### ${node}:`)[1]?.split('### ')[0] || '';
|
|
487
|
+
if (!nodeSection.includes('source:')) missingSources.push(node);
|
|
488
|
+
else {
|
|
489
|
+
const sourceMatch = nodeSection.match(/source:\s*(.+)(?:\n|$)/);
|
|
490
|
+
const cited = sourceMatch ? sourceMatch[1].trim() : '';
|
|
491
|
+
if (cited && !materialNames.some((name) => cited.includes(name))) danglingSources.push(node);
|
|
492
|
+
}
|
|
493
|
+
if (!nodeSection.includes('counterexample:')) missingCounterexamples.push(node);
|
|
494
|
+
}
|
|
495
|
+
if (missingSources.length) throw new Error(`Decision tree nodes missing source citations: ${missingSources.join(', ')}. Every node must reference a research material.`);
|
|
496
|
+
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.`);
|
|
497
|
+
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).`);
|
|
498
|
+
status.status = 'synthesized';
|
|
499
|
+
status.updated_at = now();
|
|
500
|
+
atomicJson(statusPath, status);
|
|
501
|
+
return { slug: cleanSlug, status: 'synthesized', nodes: nodes.length, materials: materials.length, next: `Run skeinn capability confirm ${cleanSlug} --scenario <text> --source human|agent.` };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
export function confirmCapability(slug, options = {}, root = findRoot()) {
|
|
505
|
+
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)');
|
|
506
|
+
if (!['human', 'agent'].includes(options.source)) throw new Error('Capability confirmation requires explicit provenance: --source human|agent');
|
|
507
|
+
const { paths } = loadProject(root);
|
|
508
|
+
const cleanSlug = capabilitySlug(slug);
|
|
509
|
+
const singleFile = join(paths.capabilities, `${cleanSlug}.md`);
|
|
510
|
+
if (existsSync(singleFile)) {
|
|
511
|
+
let content = readFileSync(singleFile, 'utf8');
|
|
512
|
+
const authority = options.source === 'human' ? 'human_confirmed' : 'agent_provisional';
|
|
513
|
+
if (/^-\s*Authority:.*$/m.test(content)) content = content.replace(/^-\s*Authority:.*$/m, `- Authority: ${authority}`);
|
|
514
|
+
else content = content.replace(/^(# .+\n)/, `$1\n- Authority: ${authority}\n`);
|
|
515
|
+
if (/^-\s*Scenario:.*$/m.test(content)) content = content.replace(/^-\s*Scenario:.*$/m, `- Scenario: ${options.scenario}`);
|
|
516
|
+
else content = content.replace(/^(-\s*Authority:.*\n)/m, `$1- Scenario: ${options.scenario}\n`);
|
|
517
|
+
writeFileSync(singleFile, content, 'utf8');
|
|
518
|
+
const meta = parseSingleFileCapabilityMeta(content);
|
|
519
|
+
return {
|
|
520
|
+
slug: cleanSlug,
|
|
521
|
+
mode: meta.mode,
|
|
522
|
+
authority,
|
|
523
|
+
status: options.source === 'human' ? 'confirmed' : 'provisional',
|
|
524
|
+
scenario: options.scenario,
|
|
525
|
+
source: options.source,
|
|
526
|
+
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.' : ''}`,
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
const dir = join(paths.capabilities, cleanSlug);
|
|
530
|
+
if (!existsSync(dir)) throw new Error(`Capability not found: ${slug}`);
|
|
531
|
+
const statusPath = join(dir, 'status.json');
|
|
532
|
+
if (!existsSync(statusPath)) throw new Error(`Capability ${slug} is not a research-directory dossier`);
|
|
533
|
+
const status = readJson(statusPath, 'status.json');
|
|
534
|
+
if (!['synthesized', 'provisional'].includes(status.status)) throw new Error(`Capability ${slug} must be synthesized before confirmation. Run skeinn capability synthesize ${slug} first.`);
|
|
535
|
+
status.scenario = options.scenario;
|
|
536
|
+
status.source = options.source;
|
|
537
|
+
status.status = options.source === 'human' ? 'confirmed' : 'provisional';
|
|
538
|
+
status.selected_at = now();
|
|
539
|
+
status.confirmed_at = options.source === 'human' ? now() : '';
|
|
540
|
+
status.updated_at = now();
|
|
541
|
+
atomicJson(statusPath, status);
|
|
542
|
+
const capPath = join(dir, 'capability.md');
|
|
543
|
+
const content = readFileSync(capPath, 'utf8');
|
|
544
|
+
const scenarioMatch = content.match(/(## Project scenario\n)([\s\S]*?)(\n## )/);
|
|
545
|
+
if (scenarioMatch) {
|
|
546
|
+
const prefix = scenarioMatch[1];
|
|
547
|
+
const suffix = scenarioMatch[3];
|
|
548
|
+
const blockquote = scenarioMatch[2].match(/(> [^\n]+\n)+/);
|
|
549
|
+
const blockquoteText = blockquote ? blockquote[0] : '';
|
|
550
|
+
const updated = content.replace(/## Project scenario\n[\s\S]*?\n## /, `${prefix}${blockquoteText}\n${options.scenario}\n${suffix}`);
|
|
551
|
+
writeFileSync(capPath, updated, 'utf8');
|
|
552
|
+
}
|
|
553
|
+
return {
|
|
554
|
+
slug: cleanSlug,
|
|
555
|
+
status: status.status,
|
|
556
|
+
scenario: options.scenario,
|
|
557
|
+
source: options.source,
|
|
558
|
+
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.' : ''}`,
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
export function getCapabilityStatus(slug, root = findRoot()) {
|
|
563
|
+
const { paths } = loadProject(root);
|
|
564
|
+
const cleanSlug = capabilitySlug(slug);
|
|
565
|
+
const singleFile = join(paths.capabilities, `${cleanSlug}.md`);
|
|
566
|
+
if (existsSync(singleFile)) {
|
|
567
|
+
const content = readFileSync(singleFile, 'utf8');
|
|
568
|
+
const meta = parseSingleFileCapabilityMeta(content);
|
|
569
|
+
const issues = validateSingleFileCapability(cleanSlug, content);
|
|
570
|
+
return {
|
|
571
|
+
slug: cleanSlug,
|
|
572
|
+
format: 'single-file',
|
|
573
|
+
mode: meta.mode,
|
|
574
|
+
authority: meta.authority,
|
|
575
|
+
scenario: meta.scenario,
|
|
576
|
+
ready: issues.length === 0,
|
|
577
|
+
issues,
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
const dir = join(paths.capabilities, cleanSlug);
|
|
581
|
+
const statusPath = join(dir, 'status.json');
|
|
582
|
+
if (!existsSync(statusPath)) throw new Error(`Capability not found: ${slug}`);
|
|
583
|
+
return { ...readJson(statusPath, 'status.json'), slug: cleanSlug, format: 'legacy-directory' };
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
export function addDeliverable(slug, options = {}, root = findRoot()) {
|
|
587
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) throw new Error('Deliverable slug must use lowercase letters, numbers, and hyphens');
|
|
588
|
+
if (!options.title) throw new Error('Deliverable requires --title');
|
|
589
|
+
if (!options.kind) throw new Error('Deliverable requires --kind (module, feature, behavior, interface, artifact, operational, verification, or other)');
|
|
590
|
+
const { paths, deliverableStore } = loadProject(root);
|
|
591
|
+
if (deliverableStore.deliverables.some((item) => item.slug === slug)) throw new Error(`Deliverable already exists: ${slug}`);
|
|
592
|
+
const id = nextId(deliverableStore.deliverables, 'DLV');
|
|
593
|
+
deliverableStore.deliverables.push({ id, slug, title: options.title, kind: options.kind, notes: options.notes || '', covered_by: [], created_at: now() });
|
|
594
|
+
atomicJson(paths.deliverables, deliverableStore);
|
|
595
|
+
return { id, slug, title: options.title, kind: options.kind };
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
export function listDeliverables(root = findRoot()) {
|
|
599
|
+
const { deliverableStore } = loadProject(root);
|
|
600
|
+
return deliverableStore.deliverables.map((item) => ({ id: item.id, slug: item.slug, title: item.title, kind: item.kind, covered: item.covered_by.length > 0 }));
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
export function checkDeliverableCoverage(root = findRoot()) {
|
|
604
|
+
const { paths, taskStore, deliverableStore } = loadProject(root);
|
|
605
|
+
const taskCovers = new Map();
|
|
606
|
+
for (const task of taskStore.tasks) {
|
|
607
|
+
for (const dlvId of task.covers || []) {
|
|
608
|
+
if (!taskCovers.has(dlvId)) taskCovers.set(dlvId, []);
|
|
609
|
+
taskCovers.get(dlvId).push(task.id);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
const uncovered = [];
|
|
613
|
+
const covered = [];
|
|
614
|
+
for (const dlv of deliverableStore.deliverables) {
|
|
615
|
+
const tasks = taskCovers.get(dlv.id) || [];
|
|
616
|
+
if (tasks.length === 0) uncovered.push({ id: dlv.id, slug: dlv.slug, title: dlv.title });
|
|
617
|
+
else covered.push({ id: dlv.id, slug: dlv.slug, tasks });
|
|
618
|
+
}
|
|
619
|
+
let changed = false;
|
|
620
|
+
for (const dlv of deliverableStore.deliverables) {
|
|
621
|
+
const tasks = taskCovers.get(dlv.id) || [];
|
|
622
|
+
const sorted = [...tasks].sort();
|
|
623
|
+
const current = JSON.stringify(dlv.covered_by);
|
|
624
|
+
const newVal = JSON.stringify(sorted);
|
|
625
|
+
if (current !== newVal) { dlv.covered_by = sorted; changed = true; }
|
|
626
|
+
}
|
|
627
|
+
if (changed) atomicJson(paths.deliverables, deliverableStore);
|
|
628
|
+
const taskById = new Map(taskStore.tasks.map((task) => [task.id, task]));
|
|
629
|
+
const delivered = covered.filter((item) => item.tasks.some((id) => taskById.get(id)?.status === 'done'));
|
|
630
|
+
return { total: deliverableStore.deliverables.length, covered: covered.length, delivered: delivered.length, uncovered: uncovered.length, uncovered_items: uncovered, covered_items: covered };
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
function capabilityPath(paths, name) {
|
|
634
|
+
const slug = capabilitySlug(name);
|
|
635
|
+
const singleFile = join(paths.capabilities, `${slug}.md`);
|
|
636
|
+
if (existsSync(singleFile)) return singleFile;
|
|
637
|
+
const dirCapability = join(paths.capabilities, slug, 'capability.md');
|
|
638
|
+
if (existsSync(dirCapability)) return dirCapability;
|
|
639
|
+
return singleFile;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
function capabilityTemplateResidue(content) {
|
|
643
|
+
return content.includes('Name the established field, what expertise it contributes')
|
|
644
|
+
|| content.includes('Name the established field, what judgment it contributes')
|
|
645
|
+
|| content.includes('<node name>')
|
|
646
|
+
|| content.includes('<which research material or expert narrative supports this node>')
|
|
647
|
+
|| content.includes('<what a top practitioner actually does')
|
|
648
|
+
|| content.includes('<what concrete Design decision changed because of this research and reflection>');
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
function designTemplateResidue(content) {
|
|
652
|
+
return content.includes('Describe the project-specific decision, mechanism, boundary, or evidence owned by this section.')
|
|
653
|
+
|| content.includes('Compare at least two genuinely viable alternatives (no strawmen).')
|
|
654
|
+
|| content.includes('List the specific capability rules, anti-patterns, or verification probes from `.skeinn/capabilities/`')
|
|
655
|
+
|| content.includes('Name the concrete false-positive outcomes where the build appears complete');
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function extractSection(content, heading) {
|
|
659
|
+
const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
660
|
+
const match = content.match(new RegExp(`^##\\s+${escaped}\\s*\\n([\\s\\S]*?)(?=^##\\s+|$(?!\\n))`, 'mi'));
|
|
661
|
+
return match ? match[1].trim() : '';
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const FAKE_SOURCE_PATTERNS = [
|
|
665
|
+
/\bagent-authored\b/i,
|
|
666
|
+
/\bself-authored\b/i,
|
|
667
|
+
/\binternal agent analysis\b/i,
|
|
668
|
+
/\bwritten by agent\b/i,
|
|
669
|
+
];
|
|
670
|
+
|
|
671
|
+
function hasVerifiableSource(sectionText) {
|
|
672
|
+
return /(https?:\/\/\S+|github\.com\/\S+|\[[^\]]+\]\([^)]+\)|Source:\s*\S{4,}|RFC\s*\d+|doi:|ISBN|postmortem|case study|benchmark|repo:)/i.test(sectionText);
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
function validateSingleFileCapability(slug, content) {
|
|
676
|
+
const issues = [];
|
|
677
|
+
if (capabilityTemplateResidue(content)) {
|
|
678
|
+
issues.push(`Capability ${slug} still contains template instructions`);
|
|
679
|
+
return issues;
|
|
680
|
+
}
|
|
681
|
+
const meta = parseSingleFileCapabilityMeta(content);
|
|
682
|
+
if (!CAPABILITY_MODES.includes(meta.mode)) {
|
|
683
|
+
issues.push(`Capability ${slug} has invalid Mode "${meta.mode}" (must be ${CAPABILITY_MODES.join(', ')})`);
|
|
684
|
+
}
|
|
685
|
+
const practices = extractSection(content, 'How real practitioners operate');
|
|
686
|
+
const reflection = extractSection(content, 'Reflection for this project');
|
|
687
|
+
const rules = extractSection(content, 'Operational rules and Design delta');
|
|
688
|
+
if (!practices) issues.push(`Capability ${slug} is missing "## How real practitioners operate"`);
|
|
689
|
+
if (!reflection) issues.push(`Capability ${slug} is missing "## Reflection for this project"`);
|
|
690
|
+
if (!rules) issues.push(`Capability ${slug} is missing "## Operational rules and Design delta"`);
|
|
691
|
+
if (meta.mode === 'external_researched') {
|
|
692
|
+
if (FAKE_SOURCE_PATTERNS.some((pattern) => pattern.test(practices))) {
|
|
693
|
+
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`);
|
|
694
|
+
} else if (practices && !hasVerifiableSource(practices)) {
|
|
695
|
+
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)`);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
if (rules && !/design delta/i.test(rules)) {
|
|
699
|
+
issues.push(`Capability ${slug} must record a concrete "Design delta" (what Design decision changed because of this research and reflection)`);
|
|
700
|
+
}
|
|
701
|
+
return issues;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
function extractCapabilityNode(paths, nodeRef) {
|
|
705
|
+
const parts = nodeRef.split('#');
|
|
706
|
+
if (parts.length !== 2) return null;
|
|
707
|
+
const [slug, nodeId] = parts;
|
|
708
|
+
const capPath = capabilityPath(paths, slug);
|
|
709
|
+
if (!existsSync(capPath)) return null;
|
|
710
|
+
const content = readFileSync(capPath, 'utf8');
|
|
711
|
+
const header = `### ${nodeId}:`;
|
|
712
|
+
const headerIndex = content.indexOf(header);
|
|
713
|
+
if (headerIndex === -1) return null;
|
|
714
|
+
const afterHeader = content.slice(headerIndex + header.length);
|
|
715
|
+
const nextNode = afterHeader.search(/### C\d+:/);
|
|
716
|
+
const nextSection = afterHeader.search(/\n## /);
|
|
717
|
+
let endIdx = afterHeader.length;
|
|
718
|
+
if (nextNode !== -1) endIdx = Math.min(endIdx, nextNode);
|
|
719
|
+
if (nextSection !== -1) endIdx = Math.min(endIdx, nextSection);
|
|
720
|
+
return `${header}${afterHeader.slice(0, endIdx)}`;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
export function importTasks(payload, root = findRoot()) {
|
|
724
|
+
const { paths, taskStore } = loadProject(root);
|
|
725
|
+
const incoming = Array.isArray(payload) ? payload : payload.tasks;
|
|
726
|
+
if (!Array.isArray(incoming) || !incoming.length) throw new Error('Task plan requires a non-empty tasks array');
|
|
727
|
+
for (const raw of incoming) {
|
|
728
|
+
if (raw.status && raw.status !== 'open') throw new Error('New Work Map Tasks must start open; completion requires Task evidence');
|
|
729
|
+
const id = raw.id || nextId(taskStore.tasks, 'TASK');
|
|
730
|
+
if (taskStore.tasks.some((task) => task.id === id)) throw new Error(`Task already exists: ${id}`);
|
|
731
|
+
taskStore.tasks.push({
|
|
732
|
+
id,
|
|
733
|
+
title: raw.title,
|
|
734
|
+
outcome: raw.outcome,
|
|
735
|
+
acceptance: raw.acceptance || [],
|
|
736
|
+
done_when: raw.done_when || [],
|
|
737
|
+
boundaries: raw.boundaries || [],
|
|
738
|
+
guardrails: raw.guardrails || [],
|
|
739
|
+
depends_on: raw.depends_on || [],
|
|
740
|
+
reads: raw.reads || ['.skeinn/PROJECT.md'],
|
|
741
|
+
touches: raw.touches || [],
|
|
742
|
+
implements: raw.implements || '',
|
|
743
|
+
design_exemption: raw.design_exemption || '',
|
|
744
|
+
capability_hooks: raw.capability_hooks || [],
|
|
745
|
+
capability_exemption: raw.capability_exemption || '',
|
|
746
|
+
integrity_version: 1,
|
|
747
|
+
covers: raw.covers || [],
|
|
748
|
+
status: 'open',
|
|
749
|
+
progress: raw.progress || { completed: [], current: '', next: '' },
|
|
750
|
+
evidence: raw.evidence || [],
|
|
751
|
+
created_at: now(),
|
|
752
|
+
updated_at: now(),
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
validateTasks(taskStore.tasks);
|
|
756
|
+
atomicJson(paths.tasks, taskStore);
|
|
757
|
+
const { state } = loadProject(root);
|
|
758
|
+
if (state.project.status === 'complete') {
|
|
759
|
+
state.project.status = 'building';
|
|
760
|
+
state.project.updated_at = now();
|
|
761
|
+
atomicJson(paths.state, state);
|
|
762
|
+
}
|
|
763
|
+
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.' };
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
export function taskSummary(tasks) {
|
|
767
|
+
return {
|
|
768
|
+
total: tasks.length,
|
|
769
|
+
open: tasks.filter((task) => task.status === 'open').length,
|
|
770
|
+
active: tasks.find((task) => task.status === 'active')?.id || null,
|
|
771
|
+
blocked: tasks.filter((task) => task.status === 'blocked').length,
|
|
772
|
+
done: tasks.filter((task) => task.status === 'done').length,
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
export function getTask(id, root = findRoot()) {
|
|
777
|
+
const { taskStore } = loadProject(root);
|
|
778
|
+
const task = id ? taskStore.tasks.find((item) => item.id === id) : nextTask(taskStore.tasks);
|
|
779
|
+
if (!task) throw new Error(id ? `Task not found: ${id}` : 'No executable Task is available');
|
|
780
|
+
return task;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
function nextTask(tasks) {
|
|
784
|
+
const active = tasks.find((task) => task.status === 'active');
|
|
785
|
+
if (active) return active;
|
|
786
|
+
const done = new Set(tasks.filter((task) => task.status === 'done').map((task) => task.id));
|
|
787
|
+
return tasks.find((task) => task.status === 'open' && task.depends_on.every((id) => done.has(id))) || null;
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
function sectionHeadingExists(content, anchor) {
|
|
791
|
+
const needle = anchor.toLowerCase();
|
|
792
|
+
return content.split(/\r?\n/).some((line) => /^#{1,6}\s/.test(line) && line.replace(/^#{1,6}\s*/, '').toLowerCase().includes(needle));
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
function taskIntegrityFindings(task, designs, capabilities, paths) {
|
|
796
|
+
if (task.integrity_version !== 1) return [];
|
|
797
|
+
const findings = [];
|
|
798
|
+
if (designs.length && !task.implements?.trim() && !task.design_exemption?.trim()) findings.push('is missing implements or design_exemption');
|
|
799
|
+
if (!paths) return findings;
|
|
800
|
+
if (task.implements?.trim()) {
|
|
801
|
+
const raw = task.implements.trim();
|
|
802
|
+
const [ref, anchor] = raw.split('#');
|
|
803
|
+
let target = null;
|
|
804
|
+
try {
|
|
805
|
+
target = declaredArtifactPath(paths, ref);
|
|
806
|
+
} catch {
|
|
807
|
+
findings.push(`implements uses an unsafe path: ${raw}`);
|
|
808
|
+
}
|
|
809
|
+
if (target && existsSync(target)) {
|
|
810
|
+
if (anchor?.trim() && !sectionHeadingExists(readFileSync(target, 'utf8'), anchor.trim())) findings.push(`implements references a missing design section: ${anchor.trim()}`);
|
|
811
|
+
} else if (target && (ref.includes('/') || ref.includes('\\') || ref.includes('.'))) {
|
|
812
|
+
findings.push(`implements references a missing design document: ${ref}`);
|
|
813
|
+
} else if (target) {
|
|
814
|
+
const corpus = [paths.decisions, ...designs.map((name) => join(paths.design, name)), ...capabilities.map((name) => capabilityPath(paths, name))]
|
|
815
|
+
.filter((path) => existsSync(path))
|
|
816
|
+
.map((path) => readFileSync(path, 'utf8'))
|
|
817
|
+
.join('\n');
|
|
818
|
+
if (!corpus.includes(raw)) findings.push(`implements references a decision not found in project truth: ${raw}`);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
for (const hook of task.capability_hooks || []) {
|
|
822
|
+
const [slug, node] = (hook.node || '').split('#');
|
|
823
|
+
if (!capabilities.includes(slug)) {
|
|
824
|
+
findings.push(`capability_hooks references a missing dossier: ${slug}`);
|
|
825
|
+
continue;
|
|
826
|
+
}
|
|
827
|
+
if (node && !sectionHeadingExists(readFileSync(capabilityPath(paths, slug), 'utf8'), node)) findings.push(`capability_hooks references a missing capability node: ${hook.node}`);
|
|
828
|
+
}
|
|
829
|
+
return findings;
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
function assertTaskIntegrityClassification(task, root) {
|
|
833
|
+
const { paths } = loadProject(root);
|
|
834
|
+
const findings = taskIntegrityFindings(task, listDesigns(root), listCapabilities(root), paths);
|
|
835
|
+
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.`);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
function declaredArtifactPath(paths, ref) {
|
|
839
|
+
const normalized = ref.replaceAll('\\', '/');
|
|
840
|
+
if (isAbsolute(normalized) || normalized.startsWith('/') || normalized.includes('..')) throw new Error(`Unsafe declared artifact path: ${ref}`);
|
|
841
|
+
const fromSkeinn = normalized === '.skeinn' || normalized.startsWith('.skeinn/');
|
|
842
|
+
const base = fromSkeinn ? paths.skeinn : paths.root;
|
|
843
|
+
const relativeRef = fromSkeinn ? normalized.slice('.skeinn'.length).replace(/^\//, '') : normalized;
|
|
844
|
+
const absolute = resolve(base, relativeRef);
|
|
845
|
+
const prefix = `${base}${process.platform === 'win32' ? '\\' : '/'}`;
|
|
846
|
+
if (!absolute.startsWith(prefix) && absolute !== base) throw new Error(`Unsafe declared artifact path: ${ref}`);
|
|
847
|
+
return absolute;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
function missingTaskOutputs(task, paths) {
|
|
851
|
+
if (task.integrity_version !== 1) return [];
|
|
852
|
+
return task.touches.filter((ref) => !existsSync(declaredArtifactPath(paths, ref)));
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
export function updateTask(id, patch, root = findRoot()) {
|
|
856
|
+
const { paths, taskStore } = loadProject(root);
|
|
857
|
+
const task = taskStore.tasks.find((item) => item.id === id);
|
|
858
|
+
if (!task) throw new Error(`Task not found: ${id}`);
|
|
859
|
+
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`);
|
|
860
|
+
const allowed = ['title', 'outcome', 'acceptance', 'done_when', 'boundaries', 'guardrails', 'depends_on', 'reads', 'touches', 'implements', 'design_exemption', 'capability_hooks', 'capability_exemption', 'covers', 'progress', 'evidence'];
|
|
861
|
+
for (const key of Object.keys(patch)) if (!allowed.includes(key)) throw new Error(`Task field cannot be updated: ${key}`);
|
|
862
|
+
Object.assign(task, patch, { updated_at: now() });
|
|
863
|
+
validateTasks(taskStore.tasks);
|
|
864
|
+
atomicJson(paths.tasks, taskStore);
|
|
865
|
+
return task;
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
export function blockTask(id, payload, root = findRoot()) {
|
|
869
|
+
const task = getTask(id, root);
|
|
870
|
+
if (task.status !== 'active') throw new Error(`${id} is not active`);
|
|
871
|
+
if (!payload.reason || payload.reason.length < 10) throw new Error('Blocking a Task requires a concrete reason');
|
|
872
|
+
if (!Array.isArray(payload.recovery_conditions) || !payload.recovery_conditions.length) throw new Error('Blocking a Task requires recovery_conditions');
|
|
873
|
+
const evidence = Array.isArray(payload.evidence) ? payload.evidence : [];
|
|
874
|
+
const { paths, taskStore } = loadProject(root);
|
|
875
|
+
const target = taskStore.tasks.find((item) => item.id === id);
|
|
876
|
+
target.status = 'blocked';
|
|
877
|
+
target.block = { reason: payload.reason, recovery_conditions: payload.recovery_conditions, at: now() };
|
|
878
|
+
target.progress = { ...target.progress, current: `blocked: ${payload.reason}`, next: payload.recovery_conditions.join('; ') };
|
|
879
|
+
target.evidence = [...target.evidence, ...evidence];
|
|
880
|
+
target.updated_at = now();
|
|
881
|
+
validateTasks(taskStore.tasks);
|
|
882
|
+
atomicJson(paths.tasks, taskStore);
|
|
883
|
+
return target;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
export function reopenTask(id, options = {}, root = findRoot()) {
|
|
887
|
+
const { paths, taskStore } = loadProject(root);
|
|
888
|
+
if (taskStore.tasks.some((task) => task.status === 'active')) throw new Error('Another Task is already active');
|
|
889
|
+
const task = taskStore.tasks.find((item) => item.id === id);
|
|
890
|
+
if (!task || !['blocked', 'done'].includes(task.status)) throw new Error(`${id} is neither blocked nor done`);
|
|
891
|
+
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`);
|
|
892
|
+
const priorStatus = task.status;
|
|
893
|
+
task.status = 'open';
|
|
894
|
+
if (priorStatus === 'done') {
|
|
895
|
+
task.evidence.push({ type: 'completion_reopened', reason: options.reason, at: now() });
|
|
896
|
+
task.progress = { ...task.progress, current: `completion reopened: ${options.reason}`, next: 'Re-run the Task and close every done condition with evidence.' };
|
|
897
|
+
} else {
|
|
898
|
+
task.evidence.push({ type: 'block_reopened', reason: options.reason, at: now() });
|
|
899
|
+
task.progress = { ...task.progress, current: `block reopened: ${options.reason}`, next: 'Address the recorded recovery conditions and re-verify before completing.' };
|
|
900
|
+
}
|
|
901
|
+
task.reopened_at = now();
|
|
902
|
+
task.updated_at = now();
|
|
903
|
+
validateTasks(taskStore.tasks);
|
|
904
|
+
atomicJson(paths.tasks, taskStore);
|
|
905
|
+
const { state } = loadProject(root);
|
|
906
|
+
if (state.project.status === 'complete') {
|
|
907
|
+
state.project.status = 'building';
|
|
908
|
+
state.project.updated_at = now();
|
|
909
|
+
atomicJson(paths.state, state);
|
|
910
|
+
}
|
|
911
|
+
return task;
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
export function startTask(id, root = findRoot()) {
|
|
915
|
+
const { paths, state, taskStore } = loadProject(root);
|
|
916
|
+
const latestKeeper = state.keeper.attempts.at(-1);
|
|
917
|
+
const attestedPass = state.keeper.status === 'passed' && latestKeeper?.review?.mode === 'independent';
|
|
918
|
+
if (state.keeper.status === 'passed' && !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>.');
|
|
919
|
+
if (!['passed', 'skipped'].includes(state.keeper.status)) throw new Error('The one-time Keeper handoff has not passed. Run skeinn keeper prompt.');
|
|
920
|
+
if (taskStore.tasks.some((task) => task.status === 'active')) throw new Error('Another Task is already active');
|
|
921
|
+
const task = taskStore.tasks.find((item) => item.id === id);
|
|
922
|
+
if (!task || task.status !== 'open') throw new Error(`${id} is not open`);
|
|
923
|
+
assertTaskIntegrityClassification(task, root);
|
|
924
|
+
const done = new Set(taskStore.tasks.filter((item) => item.status === 'done').map((item) => item.id));
|
|
925
|
+
const missing = task.depends_on.filter((dep) => !done.has(dep));
|
|
926
|
+
if (missing.length) throw new Error(`${id} has incomplete dependencies: ${missing.join(', ')}`);
|
|
927
|
+
for (const ref of task.reads) readContextDocument(paths, ref);
|
|
928
|
+
task.status = 'active';
|
|
929
|
+
task.updated_at = now();
|
|
930
|
+
validateTasks(taskStore.tasks);
|
|
931
|
+
atomicJson(paths.tasks, taskStore);
|
|
932
|
+
state.project.status = 'building';
|
|
933
|
+
state.project.updated_at = now();
|
|
934
|
+
atomicJson(paths.state, state);
|
|
935
|
+
return { ...task, next: 'Run skeinn context to load the execution protocol, guardrails, and every file in reads before editing.' };
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
export function completeTask(id, payload, root = findRoot()) {
|
|
939
|
+
const { paths, state, taskStore } = loadProject(root);
|
|
940
|
+
const task = taskStore.tasks.find((item) => item.id === id);
|
|
941
|
+
if (!task) throw new Error(`Task not found: ${id}`);
|
|
942
|
+
if (task.status !== 'active') throw new Error(`${id} is not active`);
|
|
943
|
+
if (!Array.isArray(payload.evidence) || !payload.evidence.length) throw new Error('Completing a Task requires concrete evidence');
|
|
944
|
+
assertTaskIntegrityClassification(task, root);
|
|
945
|
+
const missingOutputs = missingTaskOutputs(task, paths);
|
|
946
|
+
if (missingOutputs.length) throw new Error(`${id} declared output does not exist:\n- ${missingOutputs.join('\n- ')}`);
|
|
947
|
+
const hasAcceptance = Array.isArray(task.acceptance) && task.acceptance.length > 0;
|
|
948
|
+
if (hasAcceptance) {
|
|
949
|
+
if (!Array.isArray(payload.acceptance_results)) throw new Error('Completing a Task with acceptance[] requires acceptance_results[]');
|
|
950
|
+
const criteria = new Set(task.acceptance.map((acc) => acc.criterion));
|
|
951
|
+
const seen = new Set();
|
|
952
|
+
for (const result of payload.acceptance_results) {
|
|
953
|
+
if (!result || !criteria.has(result.criterion)) throw new Error('acceptance_results criterion must match an exact acceptance criterion');
|
|
954
|
+
if (seen.has(result.criterion)) throw new Error(`Duplicate acceptance result: ${result.criterion}`);
|
|
955
|
+
if (!result.evidence || typeof result.evidence !== 'string' || result.evidence.length < 5) throw new Error(`acceptance result requires concrete evidence: ${result.criterion}`);
|
|
956
|
+
seen.add(result.criterion);
|
|
957
|
+
}
|
|
958
|
+
const missingResults = task.acceptance.filter((acc) => !seen.has(acc.criterion));
|
|
959
|
+
if (missingResults.length) throw new Error(`Task completion is missing acceptance results:\n- ${missingResults.map((acc) => acc.criterion).join('\n- ')}`);
|
|
960
|
+
for (const result of payload.acceptance_results) {
|
|
961
|
+
const acc = task.acceptance.find((acc) => acc.criterion === result.criterion);
|
|
962
|
+
acc.evidence = result.evidence;
|
|
963
|
+
}
|
|
964
|
+
task.status = 'done';
|
|
965
|
+
task.evidence = [...task.evidence, ...payload.evidence, { type: 'acceptance_results', results: payload.acceptance_results, at: now() }];
|
|
966
|
+
} else {
|
|
967
|
+
if (!Array.isArray(payload.checks)) throw new Error('Completing a Task with done_when[] requires checks for every done_when criterion');
|
|
968
|
+
const criteria = new Set(task.done_when);
|
|
969
|
+
const seen = new Set();
|
|
970
|
+
for (const check of payload.checks) {
|
|
971
|
+
if (!check || !criteria.has(check.criterion)) throw new Error('Task completion check must quote an exact done_when criterion');
|
|
972
|
+
if (seen.has(check.criterion)) throw new Error(`Duplicate Task completion check: ${check.criterion}`);
|
|
973
|
+
if (!Array.isArray(check.evidence) || !check.evidence.length) throw new Error(`Task completion check requires evidence: ${check.criterion}`);
|
|
974
|
+
seen.add(check.criterion);
|
|
975
|
+
}
|
|
976
|
+
const missingChecks = task.done_when.filter((criterion) => !seen.has(criterion));
|
|
977
|
+
if (missingChecks.length) throw new Error(`Task completion is missing done_when checks:\n- ${missingChecks.join('\n- ')}`);
|
|
978
|
+
task.status = 'done';
|
|
979
|
+
task.evidence = [...task.evidence, ...payload.evidence, { type: 'done_when_checks', checks: payload.checks, at: now() }];
|
|
980
|
+
}
|
|
981
|
+
task.progress = { ...task.progress, current: 'complete', next: '' };
|
|
982
|
+
task.completed_at = now();
|
|
983
|
+
task.updated_at = now();
|
|
984
|
+
validateTasks(taskStore.tasks);
|
|
985
|
+
atomicJson(paths.tasks, taskStore);
|
|
986
|
+
if (taskStore.tasks.length && taskStore.tasks.every((item) => item.status === 'done')) {
|
|
987
|
+
state.project.status = 'complete';
|
|
988
|
+
state.project.updated_at = now();
|
|
989
|
+
atomicJson(paths.state, state);
|
|
990
|
+
}
|
|
991
|
+
return task;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
export function markReady(root = findRoot()) {
|
|
995
|
+
const { paths, state, taskStore } = loadProject(root);
|
|
996
|
+
const project = readFileSync(paths.project, 'utf8');
|
|
997
|
+
const designs = listDesigns(root);
|
|
998
|
+
const capabilities = listCapabilities(root);
|
|
999
|
+
const highOpen = state.understanding.unresolved.filter((item) => item.status === 'open' && item.impact === 'high');
|
|
1000
|
+
const errors = [];
|
|
1001
|
+
if (project.includes('> This is the concise entry point') || project.length < 400) errors.push('PROJECT.md still looks like a template');
|
|
1002
|
+
if (!designs.length) errors.push('No design document exists; PROJECT.md is an index, not the entire project design');
|
|
1003
|
+
const unfinishedDesigns = designs.filter((name) => designTemplateResidue(readFileSync(join(paths.design, name), 'utf8')));
|
|
1004
|
+
if (unfinishedDesigns.length) errors.push(`Design documents still contain template instructions: ${unfinishedDesigns.join(', ')}`);
|
|
1005
|
+
if (!capabilities.length && !state.capability_exemption?.reason) {
|
|
1006
|
+
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>');
|
|
1007
|
+
}
|
|
1008
|
+
for (const name of capabilities) {
|
|
1009
|
+
const content = readFileSync(capabilityPath(paths, name), 'utf8');
|
|
1010
|
+
if (isLegacyDirectoryCapability(paths, name)) {
|
|
1011
|
+
if (capabilityTemplateResidue(content)) errors.push(`Capability dossier still contains template instructions: ${name}`);
|
|
1012
|
+
} else {
|
|
1013
|
+
errors.push(...validateSingleFileCapability(name, content));
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
if (!taskStore.tasks.length) errors.push('The initial work map is empty');
|
|
1017
|
+
const integrityErrors = [];
|
|
1018
|
+
for (const task of taskStore.tasks) {
|
|
1019
|
+
for (const finding of taskIntegrityFindings(task, designs, capabilities, paths)) integrityErrors.push(`${task.id} ${finding}`);
|
|
1020
|
+
}
|
|
1021
|
+
if (integrityErrors.length) errors.push(`Task integrity classification is unresolved:\n - ${integrityErrors.join('\n - ')}`);
|
|
1022
|
+
if (highOpen.length) errors.push(`High-impact questions remain open: ${highOpen.map((item) => item.id).join(', ')}`);
|
|
1023
|
+
const digest = projectDigest(paths, taskStore.tasks, state);
|
|
1024
|
+
const latestKeeper = state.keeper.attempts.at(-1);
|
|
1025
|
+
if (['needs_revision', 'blocked'].includes(state.keeper.status) && latestKeeper?.prepared_digest === digest) {
|
|
1026
|
+
errors.push('Keeper requested revision, but project truth and Task definitions have not changed');
|
|
1027
|
+
}
|
|
1028
|
+
if (errors.length) throw new Error(`Project is not ready for Keeper:\n- ${errors.join('\n- ')}`);
|
|
1029
|
+
delete state.keeper.auto_passed;
|
|
1030
|
+
state.project.status = 'ready_for_keeper';
|
|
1031
|
+
state.project.updated_at = now();
|
|
1032
|
+
state.keeper.prepared_digest = digest;
|
|
1033
|
+
state.keeper.prepared_attempt = state.keeper.attempts.length + 1;
|
|
1034
|
+
atomicJson(paths.state, state);
|
|
1035
|
+
return { ready_for_keeper: true, digest: state.keeper.prepared_digest, next: 'Open a fresh Agent and run skeinn keeper prompt' };
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
function projectDigest(paths, tasks, state = null) {
|
|
1039
|
+
const hash = createHash('sha256');
|
|
1040
|
+
hash.update(readFileSync(paths.project));
|
|
1041
|
+
if (existsSync(paths.structure)) hash.update(readFileSync(paths.structure));
|
|
1042
|
+
hash.update(readFileSync(paths.decisions));
|
|
1043
|
+
if (state?.capability_exemption) hash.update(JSON.stringify(state.capability_exemption));
|
|
1044
|
+
for (const name of readdirSync(paths.design).filter((file) => file.endsWith('.md')).sort()) hash.update(readFileSync(join(paths.design, name)));
|
|
1045
|
+
for (const name of listCapabilities()) {
|
|
1046
|
+
hash.update(readFileSync(capabilityPath(paths, name), 'utf8'));
|
|
1047
|
+
const statusPath = join(paths.capabilities, name, 'status.json');
|
|
1048
|
+
if (existsSync(statusPath)) hash.update(readFileSync(statusPath, 'utf8'));
|
|
1049
|
+
}
|
|
1050
|
+
hash.update(JSON.stringify(tasks.map(({ progress, evidence, status, updated_at, ...definition }) => definition)));
|
|
1051
|
+
return hash.digest('hex');
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
export function getKeeperPrompt(root = findRoot()) {
|
|
1055
|
+
const { state } = loadProject(root);
|
|
1056
|
+
if (state.project.status !== 'ready_for_keeper') throw new Error('Run skeinn project ready before Keeper handoff');
|
|
1057
|
+
return keeperProtocol({ attemptNumber: state.keeper.prepared_attempt, preparedDigest: state.keeper.prepared_digest });
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
export function recordKeeper(payload, root = findRoot()) {
|
|
1061
|
+
const { paths, state, taskStore } = loadProject(root);
|
|
1062
|
+
if (state.project.status !== 'ready_for_keeper') throw new Error('Keeper result cannot be recorded before skeinn project ready');
|
|
1063
|
+
if (!['passed', 'needs_revision', 'blocked'].includes(payload.verdict)) throw new Error('Keeper verdict must be passed, needs_revision, or blocked');
|
|
1064
|
+
if (!payload.summary || !Array.isArray(payload.evidence) || !payload.evidence.length) throw new Error('Keeper result requires summary and evidence');
|
|
1065
|
+
if (payload.verdict === 'passed') {
|
|
1066
|
+
if (payload.gaps?.length) throw new Error('Keeper pass cannot contain unresolved gaps');
|
|
1067
|
+
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');
|
|
1068
|
+
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');
|
|
1069
|
+
}
|
|
1070
|
+
if (payload.evidence.some((item) => typeof item !== 'string' || !item.trim())) throw new Error('Keeper evidence entries must be non-empty strings');
|
|
1071
|
+
if (payload.gaps !== undefined && !Array.isArray(payload.gaps)) throw new Error('Keeper gaps must be an array');
|
|
1072
|
+
for (const gap of payload.gaps || []) {
|
|
1073
|
+
if (typeof gap === 'string' && gap.trim()) continue;
|
|
1074
|
+
if (gap && typeof gap === 'object' && typeof gap.gap === 'string' && gap.gap.trim()) continue;
|
|
1075
|
+
throw new Error('Each Keeper gap must be a non-empty string or an object with a gap field');
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
if (!payload.run_id || payload.run_id.length < 6) throw new Error('Keeper result requires a unique fresh-thread run_id');
|
|
1079
|
+
if (state.keeper.attempts.some((attempt) => attempt.run_id === payload.run_id)) throw new Error(`Keeper run_id was already used: ${payload.run_id}`);
|
|
1080
|
+
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');
|
|
1081
|
+
const currentDigest = projectDigest(paths, taskStore.tasks, state);
|
|
1082
|
+
if (currentDigest !== state.keeper.prepared_digest) throw new Error('Project truth changed after skeinn project ready; prepare a new Keeper attempt');
|
|
1083
|
+
if (payload.verdict === 'passed') {
|
|
1084
|
+
const openFindings = new Map();
|
|
1085
|
+
for (const attempt of state.keeper.attempts) {
|
|
1086
|
+
for (const closure of attempt.closure_results || []) openFindings.delete(closure.gap);
|
|
1087
|
+
for (const finding of attempt.gaps || []) {
|
|
1088
|
+
const gap = typeof finding === 'string' ? finding : finding?.gap;
|
|
1089
|
+
if (gap) openFindings.set(gap, true);
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
for (const gap of openFindings.keys()) {
|
|
1093
|
+
const closure = payload.closure_results?.find((item) => item.gap === gap);
|
|
1094
|
+
if (!closure || typeof closure.evidence !== 'string' || !closure.evidence.trim()) {
|
|
1095
|
+
throw new Error(`Keeper pass requires closure_results evidence for: ${gap}`);
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
const attempt = { run_id: payload.run_id, prepared_digest: payload.prepared_digest, verdict: payload.verdict, summary: payload.summary, evidence: payload.evidence, gaps: payload.gaps || [], review: payload.review || { mode: 'unverified', reviewer_id: '', evidence: '' }, can_auto_pass: false, at: now() };
|
|
1100
|
+
state.keeper.attempts.push(attempt);
|
|
1101
|
+
attempt.closure_results = payload.closure_results || [];
|
|
1102
|
+
state.keeper.status = payload.verdict;
|
|
1103
|
+
if (payload.verdict === 'passed') state.project.status = 'build_ready';
|
|
1104
|
+
else state.project.status = 'shaping';
|
|
1105
|
+
state.project.updated_at = now();
|
|
1106
|
+
atomicJson(paths.state, state);
|
|
1107
|
+
return state.keeper;
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
export function skipKeeper(reason, root = findRoot()) {
|
|
1111
|
+
if (!reason || reason.length < 10) throw new Error('Skipping Keeper requires a concrete reason');
|
|
1112
|
+
const { paths, state } = loadProject(root);
|
|
1113
|
+
if (state.project.status !== 'ready_for_keeper') throw new Error('Keeper can only be skipped after skeinn project ready');
|
|
1114
|
+
state.keeper.status = 'skipped';
|
|
1115
|
+
state.keeper.skip_reason = reason;
|
|
1116
|
+
state.project.status = 'build_ready';
|
|
1117
|
+
state.project.updated_at = now();
|
|
1118
|
+
atomicJson(paths.state, state);
|
|
1119
|
+
return state.keeper;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
export function startClarify(options = {}, root = findRoot()) {
|
|
1123
|
+
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)');
|
|
1124
|
+
const { paths, state } = loadProject(root);
|
|
1125
|
+
const clarify = ensureClarify(state);
|
|
1126
|
+
if (clarify.active) throw new Error(`A clarification round is already open: ${clarify.reason}`);
|
|
1127
|
+
clarify.active = true;
|
|
1128
|
+
clarify.reason = options.reason;
|
|
1129
|
+
clarify.started_at = now();
|
|
1130
|
+
clarify.closed_at = '';
|
|
1131
|
+
clarify.rounds = [];
|
|
1132
|
+
state.project.updated_at = now();
|
|
1133
|
+
atomicJson(paths.state, state);
|
|
1134
|
+
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>.' };
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
export function resolveClarify(payload, root = findRoot()) {
|
|
1138
|
+
const { paths, state } = loadProject(root);
|
|
1139
|
+
const clarify = ensureClarify(state);
|
|
1140
|
+
if (!clarify.active) throw new Error('No clarification round is open. Start one with skeinn clarify start --reason <what changed>.');
|
|
1141
|
+
const answered = [];
|
|
1142
|
+
for (const item of payload.answers || []) {
|
|
1143
|
+
if (item.id) {
|
|
1144
|
+
const target = state.understanding.unresolved.find((q) => q.id === item.id);
|
|
1145
|
+
if (!target) throw new Error(`Unknown unresolved id ${item.id}`);
|
|
1146
|
+
if (!item.resolution && item.status !== 'skipped') throw new Error(`Answer for ${item.id} requires a resolution or skipped status`);
|
|
1147
|
+
target.status = item.status === 'skipped' ? 'skipped' : 'resolved';
|
|
1148
|
+
target.resolution = item.resolution || '';
|
|
1149
|
+
target.resolved_at = now();
|
|
1150
|
+
answered.push(item.id);
|
|
1151
|
+
} else if (item.question && item.resolution) {
|
|
1152
|
+
state.understanding.confirmed.push({ id: nextId(state.understanding.confirmed, 'F'), text: `${item.question} → ${item.resolution}`, source: 'clarification', at: now() });
|
|
1153
|
+
answered.push(item.question);
|
|
1154
|
+
} else {
|
|
1155
|
+
throw new Error('Each answer needs {id, resolution|skipped} for a recorded question or {question, resolution} to record the answer as a fact');
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
for (const item of asObjects(payload.confirmed, 'text')) {
|
|
1159
|
+
if (!item.text) throw new Error('Confirmed fact requires text');
|
|
1160
|
+
state.understanding.confirmed.push({ id: nextId(state.understanding.confirmed, 'F'), text: item.text, source: item.source || 'clarification', at: now() });
|
|
1161
|
+
}
|
|
1162
|
+
for (const id of payload.retire_assumptions || []) {
|
|
1163
|
+
const target = state.understanding.assumptions.find((a) => a.id === id);
|
|
1164
|
+
if (!target) throw new Error(`Unknown assumption id ${id}`);
|
|
1165
|
+
target.status = 'retired';
|
|
1166
|
+
}
|
|
1167
|
+
for (const decision of payload.decisions || []) appendDecision(paths.decisions, decision, state);
|
|
1168
|
+
const roundNo = clarify.rounds.length + 1;
|
|
1169
|
+
const newOpenIds = [];
|
|
1170
|
+
for (const item of asObjects(payload.new_questions, 'question')) {
|
|
1171
|
+
if (!item.question) throw new Error('New question requires question text');
|
|
1172
|
+
const id = nextId(state.understanding.unresolved, 'Q');
|
|
1173
|
+
state.understanding.unresolved.push({ id, question: item.question, recommendation: item.recommendation || '', impact: item.impact || 'medium', status: 'open', at: now(), clarify_round: roundNo });
|
|
1174
|
+
newOpenIds.push(id);
|
|
1175
|
+
}
|
|
1176
|
+
clarify.rounds.push({ round: roundNo, answered, confirmed: (payload.confirmed || []).length, decisions: (payload.decisions || []).length, new_open: newOpenIds, at: now() });
|
|
1177
|
+
state.project.updated_at = now();
|
|
1178
|
+
atomicJson(paths.state, state);
|
|
1179
|
+
const openRoundQs = state.understanding.unresolved.filter((q) => q.status === 'open' && q.clarify_round);
|
|
1180
|
+
return {
|
|
1181
|
+
round: roundNo,
|
|
1182
|
+
rounds_recorded: clarify.rounds.length,
|
|
1183
|
+
open_round_questions: openRoundQs.map((q) => `${q.id}: ${q.question}`),
|
|
1184
|
+
next: openRoundQs.length
|
|
1185
|
+
? 'Material questions remain open — ask them in the next batch, then skeinn clarify resolve again.'
|
|
1186
|
+
: 'Round recorded. If the direction materially changed, run skeinn decision for consequential changes, update the affected design documents and Tasks, then skeinn clarify close.',
|
|
1187
|
+
};
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
export function closeClarify(root = findRoot()) {
|
|
1191
|
+
const { paths, state } = loadProject(root);
|
|
1192
|
+
const clarify = ensureClarify(state);
|
|
1193
|
+
if (!clarify.active) throw new Error('No clarification round is open.');
|
|
1194
|
+
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.');
|
|
1195
|
+
const openQs = state.understanding.unresolved.filter((q) => q.status === 'open' && q.clarify_round);
|
|
1196
|
+
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.`);
|
|
1197
|
+
clarify.active = false;
|
|
1198
|
+
clarify.closed_at = now();
|
|
1199
|
+
state.project.updated_at = now();
|
|
1200
|
+
atomicJson(paths.state, state);
|
|
1201
|
+
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.' };
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
export function clarifyStatus(root = findRoot()) {
|
|
1205
|
+
const { state } = loadProject(root);
|
|
1206
|
+
const clarify = ensureClarify(state);
|
|
1207
|
+
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 })) };
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
export function recordDecision(payload, root = findRoot()) {
|
|
1211
|
+
if (!payload || !payload.summary || payload.summary.length < 10) throw new Error('Decision requires --summary (what changed and why)');
|
|
1212
|
+
if (!payload.changes || !Array.isArray(payload.changes) || !payload.changes.length) throw new Error('Decision requires --changes (array of affected files or decisions)');
|
|
1213
|
+
const { paths } = loadProject(root);
|
|
1214
|
+
const id = `D-${new Date().toISOString().slice(0, 10)}-${Date.now().toString(36).slice(-4)}`;
|
|
1215
|
+
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`;
|
|
1216
|
+
const existing = readFileSync(paths.decisions, 'utf8');
|
|
1217
|
+
const separator = existing.endsWith('\n') ? '\n' : '\n\n';
|
|
1218
|
+
writeFileSync(paths.decisions, existing + separator + entry, 'utf8');
|
|
1219
|
+
return { id, summary: payload.summary, changes: payload.changes, affected_tasks: payload.affected_tasks || [] };
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
function describeCapabilityState(paths, name) {
|
|
1223
|
+
if (isLegacyDirectoryCapability(paths, name)) {
|
|
1224
|
+
const statusPath = join(paths.capabilities, name, 'status.json');
|
|
1225
|
+
return existsSync(statusPath) ? `${name} (${readJson(statusPath, 'status.json').status || 'legacy'})` : `${name} (legacy)`;
|
|
1226
|
+
}
|
|
1227
|
+
const content = readFileSync(capabilityPath(paths, name), 'utf8');
|
|
1228
|
+
const meta = parseSingleFileCapabilityMeta(content);
|
|
1229
|
+
const flag = meta.mode === 'offline_reflection' ? 'offline_reflection — unverified externally' : meta.mode;
|
|
1230
|
+
return `${name} (${flag}, ${meta.authority})`;
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
export function compileContext(options = {}, root = findRoot()) {
|
|
1234
|
+
const { paths, state, taskStore } = loadProject(root);
|
|
1235
|
+
const designs = listDesigns(root);
|
|
1236
|
+
const capabilities = listCapabilities(root);
|
|
1237
|
+
const summary = taskSummary(taskStore.tasks);
|
|
1238
|
+
const task = options.taskId ? getTask(options.taskId, root) : taskStore.tasks.find((item) => item.status === 'active');
|
|
1239
|
+
const next = nextTask(taskStore.tasks);
|
|
1240
|
+
const blockedTasks = taskStore.tasks.filter((item) => item.status === 'blocked');
|
|
1241
|
+
const blockedLine = blockedTasks.length
|
|
1242
|
+
? `- Blocked: ${blockedTasks.map((item) => `${item.id} — ${item.block?.reason || 'no reason recorded'} (recover: ${(item.block?.recovery_conditions || []).join('; ') || 'not recorded'})`).join(' | ')}\n`
|
|
1243
|
+
: '';
|
|
1244
|
+
const clarify = state.clarify || { active: false };
|
|
1245
|
+
const openRoundQs = state.understanding.unresolved.filter((q) => q.status === 'open' && q.clarify_round);
|
|
1246
|
+
const frontierBlock = openRoundQs.length
|
|
1247
|
+
? `\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')}`
|
|
1248
|
+
: '';
|
|
1249
|
+
const recommendation = clarify.active
|
|
1250
|
+
? `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}`
|
|
1251
|
+
: state.project.status === 'ready_for_keeper'
|
|
1252
|
+
? '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.'
|
|
1253
|
+
: ['needs_revision', 'blocked'].includes(state.keeper.status)
|
|
1254
|
+
? '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`.'
|
|
1255
|
+
: task
|
|
1256
|
+
? `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.`
|
|
1257
|
+
: next
|
|
1258
|
+
? `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.`
|
|
1259
|
+
: state.project.status === 'complete'
|
|
1260
|
+
? 'All Tasks are done. Run \`skeinn check\` to verify health. If new work arises, record the decision and update the Work Map.'
|
|
1261
|
+
: state.project.status === 'shaping'
|
|
1262
|
+
? shapingFrontier({ paths, state, taskStore, designs, capabilities })
|
|
1263
|
+
: blockedTasks.length
|
|
1264
|
+
? '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.'
|
|
1265
|
+
: 'No executable Task. Create or update Tasks so the Work Map matches the project goal.';
|
|
1266
|
+
const capabilityStates = capabilities.map((name) => describeCapabilityState(paths, name));
|
|
1267
|
+
const capStatusLine = capabilityStates.length
|
|
1268
|
+
? capabilityStates.join(', ')
|
|
1269
|
+
: state.capability_exemption?.reason
|
|
1270
|
+
? `exempted (${state.capability_exemption.reason})`
|
|
1271
|
+
: 'none';
|
|
1272
|
+
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- 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.'}`;
|
|
1273
|
+
const blocks = [statusBlock];
|
|
1274
|
+
if (options.full || options.keeper) blocks.push(agentProtocol({ humanChannel: options.humanChannel || 'available' }));
|
|
1275
|
+
blocks.push(shapingContext({ state, taskSummary: summary, capabilityNames: capabilityStates, designNames: designs, forKeeper: Boolean(options.keeper) }));
|
|
1276
|
+
if (state.keeper.status === 'passed' && state.keeper.attempts.at(-1)?.review?.mode !== 'independent') {
|
|
1277
|
+
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`.');
|
|
1278
|
+
}
|
|
1279
|
+
blocks.push(`## Project whole (${normalizeRef(paths, paths.project)})\n\n${readFileSync(paths.project, 'utf8')}`);
|
|
1280
|
+
if (existsSync(paths.structure)) blocks.push(`## Project structure (${normalizeRef(paths, paths.structure)})\n\n${readFileSync(paths.structure, 'utf8')}`);
|
|
1281
|
+
if (options.keeper) {
|
|
1282
|
+
blocks.unshift(keeperProtocol({ attemptNumber: state.keeper.prepared_attempt, preparedDigest: state.keeper.prepared_digest }));
|
|
1283
|
+
blocks.push(`## Decision history (${normalizeRef(paths, paths.decisions)})\n\n${readFileSync(paths.decisions, 'utf8')}`);
|
|
1284
|
+
blocks.push(`## Work map summary\n\n${JSON.stringify(summary, null, 2)}\n\nFirst executable Task:\n\n${JSON.stringify(nextTask(taskStore.tasks), null, 2)}`);
|
|
1285
|
+
for (const name of designs) blocks.push(`## Design document: ${name}\n\n${getDesign(name, root)}`);
|
|
1286
|
+
if (capabilities.length) {
|
|
1287
|
+
for (const name of capabilities) blocks.push(`## Capability file: ${name}\n\n${getCapability(name, root)}`);
|
|
1288
|
+
} else if (state.capability_exemption?.reason) {
|
|
1289
|
+
blocks.push(`## Capability exemption (audit whether standard engineering genuinely suffices)\n\n- Reason: ${state.capability_exemption.reason}\n- Recorded at: ${state.capability_exemption.at}`);
|
|
1290
|
+
}
|
|
1291
|
+
} else if (task) {
|
|
1292
|
+
if (options.full) blocks.push(EXECUTION_PROTOCOL);
|
|
1293
|
+
blocks.push(`## Active Task\n\n${JSON.stringify(task, null, 2)}`);
|
|
1294
|
+
if (task.guardrails && task.guardrails.length) {
|
|
1295
|
+
blocks.push(`## Task guardrails (specialist red lines)\n\n${task.guardrails.map((rule) => `- ${rule}`).join('\n')}`);
|
|
1296
|
+
}
|
|
1297
|
+
for (const ref of task.reads) {
|
|
1298
|
+
const content = readContextDocument(paths, ref);
|
|
1299
|
+
if (content && ref.replaceAll('\\', '/') !== normalizeRef(paths, paths.project)) blocks.push(`## Task context: ${ref}\n\n${content}`);
|
|
1300
|
+
}
|
|
1301
|
+
if (task.capability_hooks && task.capability_hooks.length) {
|
|
1302
|
+
const hookBlocks = [];
|
|
1303
|
+
for (const hook of task.capability_hooks) {
|
|
1304
|
+
const nodeContent = extractCapabilityNode(paths, hook.node);
|
|
1305
|
+
if (nodeContent) {
|
|
1306
|
+
const atLine = hook.at ? `\n\n**Activate at:** ${hook.at}` : '';
|
|
1307
|
+
const produceLine = hook.must_produce ? `\n\n**Must produce:** ${hook.must_produce}` : '';
|
|
1308
|
+
hookBlocks.push(`### Capability hook: ${hook.node}${atLine}${produceLine}\n\n${nodeContent}`);
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
if (hookBlocks.length) blocks.push(`## Capability decision points\n\n${hookBlocks.join('\n\n')}`);
|
|
1312
|
+
}
|
|
1313
|
+
} else {
|
|
1314
|
+
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.'}
|
|
1315
|
+
- Guidance: skeinn help shaping | design | capability | task`);
|
|
1316
|
+
}
|
|
1317
|
+
return blocks.filter(Boolean).join('\n\n---\n\n');
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
function shapingFrontier({ paths, state, taskStore, designs, capabilities }) {
|
|
1321
|
+
const gaps = [];
|
|
1322
|
+
const project = readFileSync(paths.project, 'utf8');
|
|
1323
|
+
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');
|
|
1324
|
+
if (!designs.length) gaps.push('no design documents — split the consequential decision surfaces with skeinn design add (skeinn help design explains what one owns)');
|
|
1325
|
+
const unfinishedDesigns = designs.filter((name) => designTemplateResidue(readFileSync(join(paths.design, name), 'utf8')));
|
|
1326
|
+
if (unfinishedDesigns.length) gaps.push(`design documents still contain template text: ${unfinishedDesigns.join(', ')}`);
|
|
1327
|
+
if (!capabilities.length && !state.capability_exemption?.reason) {
|
|
1328
|
+
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>');
|
|
1329
|
+
} else {
|
|
1330
|
+
const capIssues = [];
|
|
1331
|
+
for (const name of capabilities) {
|
|
1332
|
+
const content = readFileSync(capabilityPath(paths, name), 'utf8');
|
|
1333
|
+
if (isLegacyDirectoryCapability(paths, name)) {
|
|
1334
|
+
const statusPath = join(paths.capabilities, name, 'status.json');
|
|
1335
|
+
const st = existsSync(statusPath) ? readJson(statusPath, 'status.json').status : 'legacy';
|
|
1336
|
+
if (st !== 'confirmed') capIssues.push(`${name} (${st})`);
|
|
1337
|
+
} else {
|
|
1338
|
+
const issues = validateSingleFileCapability(name, content);
|
|
1339
|
+
if (issues.length) capIssues.push(`${name} (${issues[0]})`);
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
if (capIssues.length) gaps.push(`capability files incomplete — finish practitioner research, reflection, and Design delta for: ${capIssues.join('; ')}`);
|
|
1343
|
+
}
|
|
1344
|
+
const highOpen = state.understanding.unresolved.filter((item) => item.status === 'open' && item.impact === 'high');
|
|
1345
|
+
if (highOpen.length) gaps.push(`high-impact questions still open: ${highOpen.map((item) => item.id).join(', ')}`);
|
|
1346
|
+
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)');
|
|
1347
|
+
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.';
|
|
1348
|
+
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.`;
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
function normalizeRef(paths, absolute) {
|
|
1352
|
+
const skeinnPrefix = `${paths.skeinn}${process.platform === 'win32' ? '\\' : '/'}`;
|
|
1353
|
+
if (absolute === paths.skeinn || absolute.startsWith(skeinnPrefix)) return `.skeinn/${relative(paths.skeinn, absolute).replaceAll('\\', '/')}`.replace(/\/$/, '');
|
|
1354
|
+
return relative(paths.root, absolute).replaceAll('\\', '/');
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
function readContextDocument(paths, ref) {
|
|
1358
|
+
const normalized = ref.replaceAll('\\', '/');
|
|
1359
|
+
if (isAbsolute(normalized) || normalized.startsWith('/') || normalized.includes('..')) throw new Error(`Unsafe context reference: ${ref}`);
|
|
1360
|
+
const fromSkeinn = normalized === '.skeinn' || normalized.startsWith('.skeinn/');
|
|
1361
|
+
const base = fromSkeinn ? paths.skeinn : paths.root;
|
|
1362
|
+
const relativeRef = fromSkeinn ? normalized.slice('.skeinn'.length).replace(/^\//, '') : normalized;
|
|
1363
|
+
const absolute = resolve(base, relativeRef);
|
|
1364
|
+
const prefix = `${base}${process.platform === 'win32' ? '\\' : '/'}`;
|
|
1365
|
+
if (!absolute.startsWith(prefix) && absolute !== base) throw new Error(`Unsafe context reference: ${ref}`);
|
|
1366
|
+
if (!existsSync(absolute)) throw new Error(`Task context file does not exist: ${ref}`);
|
|
1367
|
+
if (!statSync(absolute).isFile()) throw new Error(`Task context must name a file, not a directory: ${ref}`);
|
|
1368
|
+
return readFileSync(absolute, 'utf8');
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
export function checkProject(root = findRoot()) {
|
|
1372
|
+
const { paths, state, taskStore } = loadProject(root);
|
|
1373
|
+
const designs = listDesigns(root);
|
|
1374
|
+
const capabilities = listCapabilities(root);
|
|
1375
|
+
const errors = [];
|
|
1376
|
+
const warnings = [];
|
|
1377
|
+
const taskById = new Map(taskStore.tasks.map((task) => [task.id, task]));
|
|
1378
|
+
for (const task of taskStore.tasks) {
|
|
1379
|
+
for (const ref of task.reads) {
|
|
1380
|
+
try { readContextDocument(paths, ref); } catch (error) { errors.push(`${task.id}: ${error.message}`); }
|
|
1381
|
+
}
|
|
1382
|
+
if (task.capability_hooks) {
|
|
1383
|
+
for (const hook of task.capability_hooks) {
|
|
1384
|
+
const nodeContent = extractCapabilityNode(paths, hook.node);
|
|
1385
|
+
if (nodeContent === null) warnings.push(`${task.id} references missing capability node: ${hook.node}`);
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
if (task.integrity_version === 1) {
|
|
1389
|
+
const classificationFindings = taskIntegrityFindings(task, designs, capabilities, paths);
|
|
1390
|
+
const target = ['active', 'done'].includes(task.status) ? errors : warnings;
|
|
1391
|
+
target.push(...classificationFindings.map((finding) => `${task.id} ${finding}`));
|
|
1392
|
+
if (task.status === 'done') {
|
|
1393
|
+
const missingOutputs = missingTaskOutputs(task, paths);
|
|
1394
|
+
errors.push(...missingOutputs.map((output) => `${task.id} declared output does not exist: ${output}`));
|
|
1395
|
+
const staleDeps = task.depends_on.filter((depId) => taskById.get(depId)?.status !== 'done');
|
|
1396
|
+
if (staleDeps.length) {
|
|
1397
|
+
warnings.push(`${task.id} is done but upstream dependency (${staleDeps.join(', ')}) is no longer done — needs_recheck (reopen if prior evidence is invalidated)`);
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
const hasAcceptance = Array.isArray(task.acceptance) && task.acceptance.length > 0;
|
|
1402
|
+
const hasDoneWhen = Array.isArray(task.done_when) && task.done_when.length > 0;
|
|
1403
|
+
if (!hasAcceptance && hasDoneWhen) warnings.push(`${task.id} uses done_when[] without acceptance[] — consider migrating to structured acceptance for clearer verification`);
|
|
1404
|
+
}
|
|
1405
|
+
if (state.project.status === 'build_ready' && !['passed', 'skipped'].includes(state.keeper.status)) errors.push('Project is build_ready without Keeper pass or explicit skip');
|
|
1406
|
+
if (state.understanding.unresolved.some((item) => item.status === 'open' && item.impact === 'high')) warnings.push('High-impact uncertainty remains open');
|
|
1407
|
+
const decisionsContent = readFileSync(paths.decisions, 'utf8');
|
|
1408
|
+
for (const block of decisionsContent.split(/\n(?=## )/)) {
|
|
1409
|
+
const affectedMatch = block.match(/- Affected tasks: (.+)/);
|
|
1410
|
+
if (!affectedMatch) continue;
|
|
1411
|
+
const decisionAt = block.match(/- At: (\S+)/)?.[1] || '';
|
|
1412
|
+
for (const taskId of affectedMatch[1].split(',').map((s) => s.trim()).filter(Boolean)) {
|
|
1413
|
+
const task = taskStore.tasks.find((item) => item.id === taskId);
|
|
1414
|
+
if (!task || task.status !== 'done') continue;
|
|
1415
|
+
const completedAt = task.completed_at || task.updated_at || '';
|
|
1416
|
+
if (decisionAt && completedAt && completedAt > decisionAt) continue;
|
|
1417
|
+
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>)`);
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
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');
|
|
1421
|
+
if (!designs.length) warnings.push('No design document exists; PROJECT.md should remain a concise map of the whole');
|
|
1422
|
+
if (!existsSync(paths.structure)) warnings.push('No STRUCTURE.md exists; declare where files go so the Agent does not guess');
|
|
1423
|
+
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');
|
|
1424
|
+
for (const name of designs) {
|
|
1425
|
+
const content = readFileSync(join(paths.design, name), 'utf8');
|
|
1426
|
+
if (designTemplateResidue(content)) warnings.push(`Design document still contains template instructions: ${name}`);
|
|
1427
|
+
const kindMatch = content.match(/^-\s*Kind:\s*([^\n]+)/m);
|
|
1428
|
+
const kind = kindMatch ? kindMatch[1].trim() : '';
|
|
1429
|
+
if (CORE_DESIGN_KINDS.includes(kind) && !extractSection(content, 'Alternatives considered')) {
|
|
1430
|
+
warnings.push(`Core design document ${name} (${kind}) has no "## Alternatives considered" section — compare at least two viable options to avoid first-draft convergence`);
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
for (const name of capabilities) {
|
|
1434
|
+
const content = readFileSync(capabilityPath(paths, name), 'utf8');
|
|
1435
|
+
if (isLegacyDirectoryCapability(paths, name)) {
|
|
1436
|
+
if (capabilityTemplateResidue(content)) warnings.push(`Capability dossier still contains template instructions: ${name}`);
|
|
1437
|
+
if (content.includes('### C') && !content.includes('source:')) warnings.push(`Capability dossier has decision tree nodes without source citations: ${name}`);
|
|
1438
|
+
const statusPath = join(paths.capabilities, name, 'status.json');
|
|
1439
|
+
if (existsSync(statusPath)) {
|
|
1440
|
+
const capStatus = readJson(statusPath, 'status.json');
|
|
1441
|
+
if (capStatus.status && capStatus.status !== 'confirmed') warnings.push(`Capability ${name} is ${capStatus.status}, not confirmed; tasks referencing it proceed provisionally`);
|
|
1442
|
+
}
|
|
1443
|
+
} else {
|
|
1444
|
+
const issues = validateSingleFileCapability(name, content);
|
|
1445
|
+
warnings.push(...issues);
|
|
1446
|
+
const meta = parseSingleFileCapabilityMeta(content);
|
|
1447
|
+
if (meta.mode === 'offline_reflection') warnings.push(`Capability ${name} is offline_reflection (unverified externally)`);
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
const latestKeeper = state.keeper.attempts.at(-1);
|
|
1451
|
+
if (state.keeper.status === 'passed' && 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>');
|
|
1452
|
+
const coverage = checkDeliverableCoverage(root);
|
|
1453
|
+
if (coverage.uncovered > 0) warnings.push(`Uncovered deliverables: ${coverage.uncovered_items.map((item) => item.slug).join(', ')}`);
|
|
1454
|
+
if (coverage.covered > coverage.delivered) warnings.push(`${coverage.covered - coverage.delivered} deliverable(s) are covered only by Tasks not yet done`);
|
|
1455
|
+
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 } };
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
export function scaffoldEval(payload, root = findRoot()) {
|
|
1459
|
+
if (!payload.id || !payload.title || !payload.brief) throw new Error('Eval scenario requires id, title, and brief');
|
|
1460
|
+
const { paths } = loadProject(root);
|
|
1461
|
+
const slug = payload.id.toLowerCase().replace(/[^a-z0-9-]+/g, '-');
|
|
1462
|
+
const dir = join(paths.eval, slug);
|
|
1463
|
+
if (existsSync(dir)) throw new Error(`Eval scenario already exists: ${payload.id}`);
|
|
1464
|
+
mkdirSync(dir, { recursive: true });
|
|
1465
|
+
const humanChannel = payload.human_channel || 'available';
|
|
1466
|
+
if (!['available', 'unavailable'].includes(humanChannel)) throw new Error('human_channel must be available or unavailable');
|
|
1467
|
+
const mode = payload.mode || 'relay';
|
|
1468
|
+
if (!['probe', 'relay', 'full'].includes(mode)) throw new Error('Eval mode must be probe, relay, or full');
|
|
1469
|
+
const budgetCny = typeof payload.budget_cny === 'number' ? payload.budget_cny : (mode === 'probe' ? 5 : mode === 'relay' ? 20 : 60);
|
|
1470
|
+
const defaultReps = mode === 'full' ? 3 : 1;
|
|
1471
|
+
const manifest = {
|
|
1472
|
+
schema_version: 2,
|
|
1473
|
+
id: payload.id,
|
|
1474
|
+
title: payload.title,
|
|
1475
|
+
mode,
|
|
1476
|
+
budget_cny: budgetCny,
|
|
1477
|
+
brief: payload.brief,
|
|
1478
|
+
pivot: payload.pivot || '',
|
|
1479
|
+
primary_comparison: 'same capable Agent without Skeinn vs with Skeinn',
|
|
1480
|
+
hidden_user_facts: payload.hidden_user_facts || [],
|
|
1481
|
+
hidden_checks: payload.hidden_checks || [],
|
|
1482
|
+
success_criteria: payload.success_criteria || [],
|
|
1483
|
+
scoring_mode: 'pairwise_forced_choice + hidden_oracle + real_telemetry',
|
|
1484
|
+
conditions: [
|
|
1485
|
+
{ id: 'baseline', framework: 'none', instruction: 'Work normally with all ordinary Agent capabilities and tools.' },
|
|
1486
|
+
{ id: 'skeinn', framework: 'skeinn-v2', instruction: 'Use Skeinn as invisible Agent continuity infrastructure.' },
|
|
1487
|
+
],
|
|
1488
|
+
controls: {
|
|
1489
|
+
same_model_tools_workspace_and_budget: true,
|
|
1490
|
+
human_channel: humanChannel,
|
|
1491
|
+
minimum_repetitions_per_condition: payload.repetitions || defaultReps,
|
|
1492
|
+
scripted_user_answers: true,
|
|
1493
|
+
context_reset_points: payload.context_reset_points || (mode === 'relay' ? ['after-baton-1', 'after-baton-2'] : ['after-shaping', 'mid-task']),
|
|
1494
|
+
blind_pairwise_order_swap: true,
|
|
1495
|
+
anonymization_preserves_relative_layout: true,
|
|
1496
|
+
judge_packet_preflight_required: true,
|
|
1497
|
+
condition_output_digest_manifest: true,
|
|
1498
|
+
telemetry_required: true,
|
|
1499
|
+
},
|
|
1500
|
+
measures: ['intent_fidelity_and_pivot_survival', 'specialist_craft_depth', 'cold_handoff_continuity', 'hidden_oracle_credibility', 'user_burden_and_ceremony', 'net_value_per_rmb'],
|
|
1501
|
+
};
|
|
1502
|
+
atomicJson(join(dir, 'manifest.json'), manifest);
|
|
1503
|
+
atomicJson(join(dir, 'telemetry-template.json'), {
|
|
1504
|
+
scenario_id: payload.id,
|
|
1505
|
+
mode,
|
|
1506
|
+
model: '<e.g. deepseek-v4.1-flash>',
|
|
1507
|
+
budget_cny_cap: budgetCny,
|
|
1508
|
+
arms: {
|
|
1509
|
+
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 },
|
|
1510
|
+
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 },
|
|
1511
|
+
},
|
|
1512
|
+
});
|
|
1513
|
+
const oracleScript = `#!/usr/bin/env node
|
|
1514
|
+
// Hidden Oracle assertions for ${payload.id} — NEVER show this file to the tested Agents.
|
|
1515
|
+
// Run against each anonymized arm directory: node hidden-oracle.mjs <arm-workspace-dir>
|
|
1516
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
1517
|
+
import { resolve } from 'node:path';
|
|
1518
|
+
|
|
1519
|
+
const target = resolve(process.argv[2] || '.');
|
|
1520
|
+
const checks = [
|
|
1521
|
+
// Add objective Pass/Fail checks here (files, contracts, static scans, smoke runs):
|
|
1522
|
+
{ name: 'workspace exists', fn: () => existsSync(target) },
|
|
1523
|
+
];
|
|
1524
|
+
|
|
1525
|
+
let passed = 0;
|
|
1526
|
+
for (const check of checks) {
|
|
1527
|
+
try {
|
|
1528
|
+
if (!check.fn()) throw new Error('returned false');
|
|
1529
|
+
passed += 1;
|
|
1530
|
+
console.log(\`PASS: \${check.name}\`);
|
|
1531
|
+
} catch (err) {
|
|
1532
|
+
console.error(\`FAIL: \${check.name} — \${err.message}\`);
|
|
1533
|
+
process.exitCode = 1;
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
console.log(JSON.stringify({ target, passed, total: checks.length }, null, 2));
|
|
1537
|
+
`;
|
|
1538
|
+
writeFileSync(join(dir, 'hidden-oracle.mjs'), oracleScript, 'utf8');
|
|
1539
|
+
writeFileSync(join(dir, 'baseline-prompt.md'), `${evalConditionPrompt({ brief: payload.brief, skeinn: false, humanChannel })}\n`, 'utf8');
|
|
1540
|
+
writeFileSync(join(dir, 'skeinn-prompt.md'), `${evalConditionPrompt({ brief: payload.brief, skeinn: true, humanChannel })}\n`, 'utf8');
|
|
1541
|
+
writeFileSync(join(dir, 'judge-prompt.md'), `${evalJudgePrompt()}\n`, 'utf8');
|
|
1542
|
+
if (mode === 'relay') {
|
|
1543
|
+
const batonsDir = join(dir, 'batons');
|
|
1544
|
+
mkdirSync(batonsDir, { recursive: true });
|
|
1545
|
+
for (const baton of [1, 2, 3]) {
|
|
1546
|
+
writeFileSync(join(batonsDir, `baseline-baton-${baton}.md`), `${evalRelayBatonPrompt({ brief: payload.brief, pivot: payload.pivot, batonNumber: baton, skeinn: false, humanChannel })}\n`, 'utf8');
|
|
1547
|
+
writeFileSync(join(batonsDir, `skeinn-baton-${baton}.md`), `${evalRelayBatonPrompt({ brief: payload.brief, pivot: payload.pivot, batonNumber: baton, skeinn: true, humanChannel })}\n`, 'utf8');
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
if (mode === 'probe') {
|
|
1551
|
+
writeFileSync(join(dir, 'probe-checklist.md'), evalProbeChecklist({ id: payload.id, title: payload.title }), 'utf8');
|
|
1552
|
+
}
|
|
1553
|
+
return { scenario: payload.id, mode, budget_cny: budgetCny, path: normalizeRef(paths, dir), controls: manifest.controls };
|
|
1554
|
+
}
|