cyc-stack 0.7.1 → 0.9.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/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.cursor-plugin/plugin.json +1 -1
- package/README.md +25 -254
- package/bin/cyc.mjs +61 -23
- package/docs/assets/cyc-method-library.svg +1 -39
- package/docs/assets/cyc-overview.svg +1 -44
- package/docs/assets/cyc-workflow-diagram.svg +1 -415
- package/docs/context.md +13 -23
- package/docs/cyc-workflow.md +31 -84
- package/docs/installation.md +66 -124
- package/docs/onboarding-recovery.md +31 -37
- package/docs/project-tools.md +16 -10
- package/docs/response-standard.md +16 -32
- package/docs/runtime.md +22 -224
- package/docs/skill-contract.md +13 -56
- package/docs/task-context.md +56 -0
- package/docs/validation.md +2 -0
- package/docs/work-assessments.md +25 -92
- package/methods/cyc-build/SKILL.md +8 -53
- package/methods/cyc-challenge/SKILL.md +4 -0
- package/methods/cyc-context/SKILL.md +20 -53
- package/methods/cyc-context/references/evidence.md +1 -1
- package/methods/cyc-context/references/templates.md +4 -11
- package/methods/cyc-deliver/SKILL.md +6 -42
- package/methods/cyc-remember/SKILL.md +1 -1
- package/methods/cyc-scout/SKILL.md +17 -51
- package/methods/cyc-setup/SKILL.md +7 -19
- package/methods/cyc-verify/SKILL.md +15 -66
- package/methods/cyc-verify/references/recipe.md +2 -0
- package/package.json +9 -1
- package/plugin.json +1 -1
- package/rules/cyc-delivery.mdc +33 -33
- package/scripts/browser-audit.mjs +53 -0
- package/scripts/catalog.mjs +9 -2
- package/scripts/codex-host.mjs +178 -0
- package/scripts/context-review.mjs +212 -29
- package/scripts/delegation.mjs +156 -0
- package/scripts/execution.mjs +51 -0
- package/scripts/onboarding.mjs +14 -1
- package/scripts/packet.mjs +21 -6
- package/scripts/project-tools.mjs +43 -20
- package/scripts/recovery.mjs +20 -1
- package/scripts/response-mode.mjs +8 -0
- package/scripts/run-worker.mjs +4 -0
- package/scripts/runtime.mjs +648 -68
- package/scripts/swarm.mjs +154 -0
- package/scripts/task-context.mjs +164 -0
- package/scripts/work-review.mjs +32 -10
- package/skills/cyc/SKILL.md +29 -70
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
|
|
1
|
+
import { existsSync, lstatSync, statSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
2
2
|
import { dirname, join, relative, resolve } from 'node:path';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
4
|
import { spawnSync } from 'node:child_process';
|
|
5
|
-
import {
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { readRun, contextUpdate } from './runtime.mjs';
|
|
6
7
|
import { contextLinks } from './project-tools.mjs';
|
|
7
8
|
|
|
8
9
|
// Component context docs under docs/context/ and their quality check. A doc is for one component,
|
|
@@ -56,11 +57,20 @@ const oneLine = (value, max = 160) => {
|
|
|
56
57
|
const shortRun = id => String(id).slice(0, 8);
|
|
57
58
|
const day = iso => String(iso ?? '').slice(0, 10);
|
|
58
59
|
const fileName = path => path.split('/').at(-1);
|
|
59
|
-
const isComponentDoc = path => !!path && dirname(path) ===
|
|
60
|
+
export const isComponentDoc = (path, folder = contextFolder) => !!path && dirname(path) === folder && docFileName.test(fileName(path)) && !reservedDocs.has(fileName(path));
|
|
61
|
+
|
|
62
|
+
export function contextLocation(root) {
|
|
63
|
+
const config = existsSync(join(root, '.cyc/config.json')) ? JSON.parse(readFileSync(join(root, '.cyc/config.json'), 'utf8').replace(/^\uFEFF/, '')) : {};
|
|
64
|
+
const folder = canonicalPattern(config.context?.directory ?? contextFolder, { patterns: false });
|
|
65
|
+
if (folder === '.cyc' || folder.startsWith('.cyc/')) throw Error('Target context must not use engine or runtime storage.');
|
|
66
|
+
const path = local(root, folder);
|
|
67
|
+
if (existsSync(path) && !statSync(path).isDirectory()) throw Error(`Target context directory is a file: ${folder}. Choose a project-owned directory before start.`);
|
|
68
|
+
return { folder, index: `${folder}/INDEX.md` };
|
|
69
|
+
}
|
|
60
70
|
|
|
61
71
|
export function canonicalPattern(pattern, { patterns = true } = {}) {
|
|
62
72
|
const value = String(pattern ?? '').trim().replaceAll('`', '');
|
|
63
|
-
if (!value || /[\\:\0]/.test(value) || (!patterns && /[*?]/.test(value)) || /[
|
|
73
|
+
if (!value || /[\\:\0]/.test(value) || (!patterns && /[*?]/.test(value)) || /[{}]/.test(value) || value.split('/').some(p => !p || p === '.' || p === '..')) throw Error(`Use canonical project-relative ${patterns ? 'patterns' : 'paths'}: ${value || pattern}`);
|
|
64
74
|
return value;
|
|
65
75
|
}
|
|
66
76
|
|
|
@@ -80,6 +90,14 @@ export function matches(pattern, path) {
|
|
|
80
90
|
return new RegExp(`^${regex}$`).test(path) || (prefix && (prefix === path || prefix.startsWith(path + '/'))) || (!/[?*]/.test(pattern) && path.startsWith(pattern + '/'));
|
|
81
91
|
}
|
|
82
92
|
const covered = (covers, path) => covers.some(pattern => { try { return matches(pattern, path); } catch { return false; } });
|
|
93
|
+
const sha = value => createHash('sha256').update(value).digest('hex');
|
|
94
|
+
const catchAll = pattern => {
|
|
95
|
+
const parts = pattern.split('/');
|
|
96
|
+
if (parts[0] === 'src') parts.shift();
|
|
97
|
+
return pattern === 'all' || parts.every(part => !part.replace(/[*.?]/g, ''));
|
|
98
|
+
};
|
|
99
|
+
const testPath = path => /(^|\/)(tests?|test-support|__tests__)\/|[._-](test|spec)\./.test(path);
|
|
100
|
+
const sourceEntrypoint = path => !testPath(path) && (/\.(?:[cm]?[jt]sx?|py|go|rs|rb|php|java|cs|swift|vue|svelte|sql|json|ya?ml|toml|sh|ps1)$/.test(path) || /(?:^|\/)SKILL\.md$/.test(path));
|
|
83
101
|
|
|
84
102
|
function local(root, path) {
|
|
85
103
|
canonicalPattern(path, { patterns: false });
|
|
@@ -92,10 +110,11 @@ function local(root, path) {
|
|
|
92
110
|
return current;
|
|
93
111
|
}
|
|
94
112
|
const read = (root, path) => readFileSync(local(root, path), 'utf8').replace(/^/, '').replaceAll('\r\n', '\n');
|
|
95
|
-
function atomicWrite(path, content) {
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
renameSync(temporary, path);
|
|
113
|
+
function atomicWrite(path, content, staging) {
|
|
114
|
+
if (staging) mkdirSync(staging, { recursive: true });
|
|
115
|
+
const temporary = staging ? join(staging, `${randomUUID()}.context`) : `${path}.${randomUUID()}.tmp`;
|
|
116
|
+
try { writeFileSync(temporary, content, { flag: 'wx' }); renameSync(temporary, path); }
|
|
117
|
+
finally { try { if (existsSync(temporary)) unlinkSync(temporary); } catch { /* retained staging is not source or successful evidence */ } }
|
|
99
118
|
}
|
|
100
119
|
|
|
101
120
|
// ---------------------------------------------------------------- component docs
|
|
@@ -138,7 +157,7 @@ export function parseDoc(source, name = 'doc.md') {
|
|
|
138
157
|
const view = section('Current view');
|
|
139
158
|
if (view) {
|
|
140
159
|
if (!view.lines.some(line => line.trim())) issue('current-view', 'Current view is empty.', view.start);
|
|
141
|
-
const placeholder = view.lines.findIndex(line =>
|
|
160
|
+
const placeholder = view.lines.findIndex(line => /<(?:write|describe|fill|replace|actual|placeholder|todo|what|feature details)\b[^>]*>/i.test(line));
|
|
142
161
|
if (placeholder !== -1) issue('current-view', 'Current view still has a template placeholder.', view.start + placeholder);
|
|
143
162
|
}
|
|
144
163
|
const lessons = [];
|
|
@@ -177,13 +196,14 @@ export function parseDoc(source, name = 'doc.md') {
|
|
|
177
196
|
if (history.length && lastChange !== null) {
|
|
178
197
|
const newest = history[0];
|
|
179
198
|
if (lastChange === 'none recorded' || lastChange.run !== newest.run || lastChange.date !== newest.date) issue('last-change-current', `Newest entry is ${newest.date} · run ${newest.run}.`, lastIndex);
|
|
180
|
-
}
|
|
199
|
+
} else if (lastChange && lastChange !== 'none recorded') issue('last-change-current', 'Last changed names a run with no History entry.', lastIndex);
|
|
181
200
|
}
|
|
182
201
|
if (lines.length > maxDocLines) issue('size', `${lines.length} lines.`);
|
|
183
|
-
return { name, title, covers, lastChange, lessons, history, lines: lines.length, issues };
|
|
202
|
+
return { name, title, covers, lastChange, lessons, history, currentView: view?.lines.join('\n').trim() ?? '', lines: lines.length, issues };
|
|
184
203
|
}
|
|
185
204
|
|
|
186
205
|
export function listDocs(root) {
|
|
206
|
+
const { folder: contextFolder } = contextLocation(root);
|
|
187
207
|
const folder = local(root, contextFolder);
|
|
188
208
|
if (!existsSync(folder)) return [];
|
|
189
209
|
return readdirSync(folder).filter(name => name.endsWith('.md') && !reservedDocs.has(name) && lstatSync(join(folder, name)).isFile()).sort();
|
|
@@ -202,7 +222,7 @@ export function parseIndex(source) {
|
|
|
202
222
|
const lines = source.replace(/^/, '').replaceAll('\r\n', '\n').split('\n');
|
|
203
223
|
const table = { header: null, headerLine: -1, separatorLine: -1, columns: {}, rows: [], lines };
|
|
204
224
|
for (const [index, line] of lines.entries()) {
|
|
205
|
-
if (!/^\s*\|/.test(line)) { if (table.header && table.rows.length) break; table.header = null; continue; }
|
|
225
|
+
if (!/^\s*\|/.test(line)) { if (table.header && (table.rows.length || table.separatorLine >= 0)) break; table.header = null; continue; }
|
|
206
226
|
const cells = line.trim().replace(/^\||\|$/g, '').split(/(?<!\\)\|/).map(c => c.trim().replaceAll('\\|', '|'));
|
|
207
227
|
if (!table.header) {
|
|
208
228
|
if (!cells.some(c => c.toLowerCase() === 'covers')) continue;
|
|
@@ -221,6 +241,7 @@ export function parseIndex(source) {
|
|
|
221
241
|
}
|
|
222
242
|
|
|
223
243
|
function resolveLink(root, link) {
|
|
244
|
+
const { index: indexName } = contextLocation(root);
|
|
224
245
|
if (!link || /^[a-z]+:/i.test(link)) return null;
|
|
225
246
|
return relative(root, resolve(dirname(local(root, indexName)), link)).replaceAll('\\', '/');
|
|
226
247
|
}
|
|
@@ -255,7 +276,8 @@ export function docFreshness(root, docPath, covers) {
|
|
|
255
276
|
return { status: dirtyPaths.length ? 'dirty' : 'fresh', docCommit: doc, coveredCommit, dirtyPaths };
|
|
256
277
|
}
|
|
257
278
|
|
|
258
|
-
export function lintIndex(root, { git: checkGit = true } = {}) {
|
|
279
|
+
export function lintIndex(root, { git: checkGit = true, docs: selectedDocs } = {}) {
|
|
280
|
+
const { folder: contextFolder, index: indexName } = contextLocation(root);
|
|
259
281
|
const issues = [];
|
|
260
282
|
const issue = (rule, message, line) => issues.push({ rule, message, ...(line !== undefined ? { line: line + 1 } : {}) });
|
|
261
283
|
const exists = existsSync(local(root, indexName));
|
|
@@ -277,10 +299,11 @@ export function lintIndex(root, { git: checkGit = true } = {}) {
|
|
|
277
299
|
rows.push(entry);
|
|
278
300
|
if (!docPath) { if (row.docText && !row.link) issue('toc-link', `No link in the Doc cell: ${oneLine(row.docText, 60)}`, row.line); continue; }
|
|
279
301
|
if (!existsSync(local(root, docPath))) { issue('toc-link', `${docPath} does not exist.`, row.line); continue; }
|
|
280
|
-
if (!isComponentDoc(docPath)) continue;
|
|
302
|
+
if (!isComponentDoc(docPath, contextFolder)) continue;
|
|
281
303
|
entry.componentDoc = true;
|
|
282
304
|
if (seen.has(docPath)) issue('toc-unindexed', `${docPath} has more than one row (first at line ${seen.get(docPath) + 1}).`, row.line);
|
|
283
305
|
seen.set(docPath, row.line);
|
|
306
|
+
if (selectedDocs && !selectedDocs.includes(docPath)) continue;
|
|
284
307
|
const parsed = lintDoc(root, docPath);
|
|
285
308
|
entry.docIssues = parsed.issues.length;
|
|
286
309
|
if ([...parsed.covers].sort().join(',') !== [...row.covers].sort().join(',')) issue('toc-covers', `Row covers [${row.covers.join(', ')}] but ${docPath} covers [${parsed.covers.join(', ')}].`, row.line);
|
|
@@ -302,6 +325,7 @@ const docSummary = result => ({ path: result.path, ok: result.ok, issues: result
|
|
|
302
325
|
|
|
303
326
|
export function lintContext(root, { doc, git: checkGit = true } = {}) {
|
|
304
327
|
root = realpathSync(root);
|
|
328
|
+
const { folder: contextFolder } = contextLocation(root);
|
|
305
329
|
if (doc) {
|
|
306
330
|
const result = lintDoc(root, doc.replaceAll('\\', '/'));
|
|
307
331
|
return { ok: result.ok, docs: [docSummary(result)], rules, note: 'Structure rules only: a passing doc can still be wrong about its component.' };
|
|
@@ -311,6 +335,147 @@ export function lintContext(root, { doc, git: checkGit = true } = {}) {
|
|
|
311
335
|
return { ok: docs.every(d => d.ok) && index.ok, index: { path: index.path, exists: index.exists, ok: index.ok, issues: index.issues, freshness: index.freshness }, docs, rules, note: 'Structure and freshness rules only: a passing doc can still be wrong about its component, and a fresh doc is one whose covered paths have no later commit, not one that is correct.' };
|
|
312
336
|
}
|
|
313
337
|
|
|
338
|
+
// A current start plans records before scope freezes. Old stored runs without this
|
|
339
|
+
// contract remain legacy; spelling an old start envelope does not disable the default.
|
|
340
|
+
export function planRetention(root, { goal, build, allowedPaths = [], explicit } = {}) {
|
|
341
|
+
if (explicit?.version !== undefined && explicit.version !== 1) throw Error('Unsupported feature-retention version; use version 1.');
|
|
342
|
+
const { folder, index } = contextLocation(root);
|
|
343
|
+
const disposition = explicit?.disposition ?? (build ? 'required' : 'unnecessary');
|
|
344
|
+
if (!['required', 'unnecessary', 'restricted'].includes(disposition)) throw Error('context.retention.disposition must be required, unnecessary or restricted.');
|
|
345
|
+
if (disposition !== 'required' && !text(explicit?.reason) && (build || disposition === 'restricted')) throw Error('A nonrequired retention disposition needs its actual reason.');
|
|
346
|
+
let features = explicit?.features;
|
|
347
|
+
if (features === undefined && disposition === 'required') {
|
|
348
|
+
const existing = componentsOf(root).components.filter(c => c.inFolder && !c.covers.some(catchAll) && allowedPaths.some(p => covered(c.covers, p)));
|
|
349
|
+
features = [...new Map(existing.map(c => [c.doc, { id: fileName(c.doc).slice(0, -3), doc: c.doc, paths: allowedPaths.filter(p => covered(c.covers, p)) }])).values()];
|
|
350
|
+
if (!features.length) {
|
|
351
|
+
const id = String(goal).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64) || 'feature';
|
|
352
|
+
features = [{ id, doc: `${folder}/${id}.md`, paths: allowedPaths.filter(p => !p.startsWith('docs/') && !p.startsWith('.cyc/')) }];
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
features ??= [];
|
|
356
|
+
if (!Array.isArray(features) || features.length > 32 || new Set(features.map(f => f?.id)).size !== features.length || new Set(features.map(f => f?.doc)).size !== features.length || disposition === 'required' && !features.length) throw Error('Retention needs unique feature ids and canonical records (at most 32).');
|
|
357
|
+
features = structuredClone(features);
|
|
358
|
+
for (const f of features) {
|
|
359
|
+
if (!/^[a-z][a-z0-9-]{0,79}$/.test(f?.id ?? '') || !isComponentDoc(f.doc, folder) || !Array.isArray(f.paths)) throw Error('Each retention feature needs {id, doc: canonical feature path, paths: representative entrypoints}.');
|
|
360
|
+
local(root, f.doc);
|
|
361
|
+
for (const path of f.paths) { canonicalPattern(path, { patterns: false }); if (path.startsWith('.cyc/')) throw Error('Engine/runtime evidence is not a feature entrypoint.'); }
|
|
362
|
+
if (existsSync(local(root, f.doc))) f.baselineViewHash = sha(parseDoc(read(root, f.doc), fileName(f.doc)).currentView);
|
|
363
|
+
}
|
|
364
|
+
return { version: 1, disposition, routine: explicit?.routine === true, reason: explicit?.reason ?? (build ? 'Feature knowledge is required.' : 'Read-only/nonfeature route; implementation changes still require retention.'), folder, index, features: structuredClone(features) };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export const retentionOf = state => state.contextRetention ?? state.handoffs?.find(h => h.stage === 'scout' && h.status === 'passed')?.assessment?.context?.retention;
|
|
368
|
+
const support = (path, folder) => path.startsWith('.cyc/') || path === `${folder}/INDEX.md` || path.startsWith(`${folder}/`) || /(?:^|\/)(?:error-ledger\.md|verify-recipe\.md)$/.test(path);
|
|
369
|
+
function featureFiles(root, state, feature, files) {
|
|
370
|
+
const folder = retentionOf(state).folder;
|
|
371
|
+
const changed = Object.keys(files).filter(p => files[p] !== state.initialSource.files[p] && !support(p, folder));
|
|
372
|
+
const recordCovers = existsSync(local(root, feature.doc)) ? parseDoc(read(root, feature.doc), fileName(feature.doc)).covers : [];
|
|
373
|
+
// Context-only upkeep still describes an implementation. Reuse its focused
|
|
374
|
+
// owner, never the record/index itself or an unrelated workspace sample.
|
|
375
|
+
const maintenance = !changed.length && feature.paths.every(p => support(p, folder));
|
|
376
|
+
const anchors = maintenance ? recordCovers.filter(p => !support(p, folder) && !catchAll(p)) : [];
|
|
377
|
+
const paths = feature.paths.length ? feature.paths : maintenance ? anchors : changed;
|
|
378
|
+
const selected = changed.filter(p => covered([...paths, ...recordCovers], p));
|
|
379
|
+
for (const path of [...paths, ...anchors]) {
|
|
380
|
+
const sample = files[path] && !support(path, folder) ? path : selected.find(p => covered([path], p)) ?? Object.keys(files).find(p => covered([path], p) && !support(p, folder));
|
|
381
|
+
if (sample && !selected.includes(sample)) selected.push(sample);
|
|
382
|
+
}
|
|
383
|
+
return { paths, files: selected.slice(0, 32).map(path => ({ path, sha256: files[path] })) };
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export function checkRetention(root, state, files) {
|
|
387
|
+
const plan = retentionOf(state);
|
|
388
|
+
if (!plan) return { ok: true, status: 'legacy', docs: [], issues: [], note: 'Historical run has no feature-retention contract.' };
|
|
389
|
+
const issues = [], docs = [], ownership = [];
|
|
390
|
+
const issue = (rule, message, doc) => issues.push({ rule, message, ...(doc ? { doc } : {}) });
|
|
391
|
+
const edits = [...new Set([...Object.keys(state.initialSource.files), ...Object.keys(files)])].filter(p => files[p] !== state.initialSource.files[p] && !p.startsWith('.cyc/'));
|
|
392
|
+
const changed = edits.filter(p => !support(p, plan.folder));
|
|
393
|
+
if (plan.disposition === 'restricted') return { ok: false, status: 'pending', docs, issues: [{ rule: 'scope-restriction', message: plan.reason }], note: 'Required context remains incomplete; no documentation permission is inferred.' };
|
|
394
|
+
if (plan.disposition === 'unnecessary') {
|
|
395
|
+
if (state.playbook === 'feature' || edits.length && (!plan.routine || edits.some(p => !state.initialSource.files[p] || !files[p]))) issue('feature-plan', 'Source changes require planned context or an explicit routine disposition; routine work cannot add/delete files or claim feature retention.');
|
|
396
|
+
return { ok: !issues.length, status: issues.length ? 'pending' : 'unnecessary', docs, issues };
|
|
397
|
+
}
|
|
398
|
+
const index = lintIndex(root, { git: false, docs: plan.features.map(f => f.doc) });
|
|
399
|
+
if (!index.exists) issue('toc-link', `Missing target index ${plan.index}.`);
|
|
400
|
+
issues.push(...index.issues);
|
|
401
|
+
for (const feature of plan.features) {
|
|
402
|
+
const doc = feature.doc;
|
|
403
|
+
if (!existsSync(local(root, doc))) { issue('feature-doc', `Missing canonical record for ${feature.id}.`, doc); continue; }
|
|
404
|
+
const parsed = lintDoc(root, doc), selected = featureFiles(root, state, feature, files);
|
|
405
|
+
ownership.push(...parsed.covers);
|
|
406
|
+
issues.push(...parsed.issues.map(i => ({ ...i, doc })));
|
|
407
|
+
if (!parsed.currentView.split('\n').some(line => !/^\s*(?:#|-|\||`)/.test(line) && line.trim().length >= 80)) issue('feature-knowledge', 'Supply proportionate capability, contracts, decisions, checks and limitations as prose; headings/filenames alone are insufficient.', doc);
|
|
408
|
+
if (parsed.covers.some(catchAll)) issue('feature-coverage', 'A catch-all is not focused feature ownership.', doc);
|
|
409
|
+
if (!selected.paths.length || selected.paths.some(path => !covered(parsed.covers, path))) issue('feature-coverage', `Covers must resolve representative feature paths: ${selected.paths.join(', ') || 'none planned'}.`, doc);
|
|
410
|
+
const rows = index.rows.filter(row => row.componentDoc && row.doc === doc);
|
|
411
|
+
if (rows.length !== 1 || selected.paths.some(path => !covered(rows[0]?.covers ?? [], path))) issue('feature-index', 'A canonical resolving index row must map the feature entrypoints.', doc);
|
|
412
|
+
const latest = parsed.history[0];
|
|
413
|
+
if (parsed.history.filter(h => h.run === state.id).length !== 1) issue('feature-history', 'Keep exactly one entry for the current run.', doc);
|
|
414
|
+
if (latest?.run !== state.id) issue('feature-history', 'Current feature work needs its own dated History entry before verification.', doc);
|
|
415
|
+
if (!selected.files.length || !latest?.files.length) issue('feature-evidence', 'Current History needs actual selected source evidence.', doc);
|
|
416
|
+
for (const item of latest?.files ?? []) {
|
|
417
|
+
try {
|
|
418
|
+
const path = canonicalPattern(item.path, { patterns: false });
|
|
419
|
+
if (support(path, plan.folder) || !files[path] || !files[path].startsWith(item.hash.replace(/^sha256:/, ''))) issue('feature-evidence', `Missing/stale current source evidence: ${path}.`, doc);
|
|
420
|
+
} catch (error) { issue('feature-evidence', error.message, doc); }
|
|
421
|
+
}
|
|
422
|
+
for (const item of selected.files) if (!latest?.files.some(f => f.path === item.path)) issue('feature-evidence', `No current source evidence for ${item.path}.`, doc);
|
|
423
|
+
const authored = state.contextPreparation?.authored?.[feature.id];
|
|
424
|
+
if (!authored || authored.viewHash !== sha(parsed.currentView) || authored.sourcesHash !== sha(JSON.stringify(selected.files))) issue('feature-authoring', 'Author or revalidate the focused Current view against this source; generated History alone is not retained feature knowledge.', doc);
|
|
425
|
+
if (!files[doc] || !files[plan.index]) issue('feature-source', 'Canonical context/index must be included in verified source, not ignored runtime data.', doc);
|
|
426
|
+
docs.push(doc);
|
|
427
|
+
}
|
|
428
|
+
for (const path of changed) {
|
|
429
|
+
if ((sourceEntrypoint(path) || !state.initialSource.files[path] && !testPath(path)) && !covered(ownership, path)) issue('feature-entrypoint', `Changed implementation path has no planned canonical feature owner: ${path}.`);
|
|
430
|
+
for (const row of index.rows.filter(row => row.componentDoc && covered(row.covers, path))) if (!plan.features.some(f => f.doc === row.doc)) issue('feature-owner', `Plan the affected canonical owner ${row.doc} for ${path} before Build; retention remains pending without broadening this run.`);
|
|
431
|
+
}
|
|
432
|
+
return { ok: !issues.length, status: issues.length ? 'pending' : 'retained', docs, issues, note: 'Layout, mapping, provenance and source checks only; authored semantic truth and user acceptance are not certified.' };
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// Only the caller's active, scoped runtime transaction may invoke this writer.
|
|
436
|
+
// It uses observations available now; final receipts stay outside covered source.
|
|
437
|
+
export function prepareRetention(root, state, { records = [], summary = '', reason = '' } = {}, files, permit) {
|
|
438
|
+
const plan = retentionOf(state);
|
|
439
|
+
if (!plan || plan.disposition !== 'required') return { paths: [], authored: {} };
|
|
440
|
+
if (!Array.isArray(records) || new Set(records.map(r => r?.id)).size !== records.length || records.some(r => !plan.features.some(f => f.id === r?.id) || !text(r.currentView) || /<(?:write|describe|fill|actual|placeholder|todo)\b/i.test(r.currentView))) throw Error('learning.context needs unique planned ids and actual nonplaceholder currentView text.');
|
|
441
|
+
const writes = [], authored = {};
|
|
442
|
+
const date = state.contextPreparation?.date ?? new Date().toISOString().slice(0, 10);
|
|
443
|
+
for (const feature of plan.features) {
|
|
444
|
+
const exists = existsSync(local(root, feature.doc)), selected = featureFiles(root, state, feature, files);
|
|
445
|
+
let source = exists ? read(root, feature.doc) : newDocSource(feature.id.replaceAll('-', ' '), selected.files.length ? selected.files.map(f => f.path) : selected.paths);
|
|
446
|
+
let parsed = parseDoc(source, fileName(feature.doc));
|
|
447
|
+
if (parsed.issues.some(i => ['sections', 'title', 'last-change'].includes(i.rule)) || parsed.issues.some(i => i.rule === 'last-change-current') && parsed.lastChange?.run !== state.id) throw Error(`Repair existing context metadata/history first: ${feature.doc}. Do not invent an older run entry.`);
|
|
448
|
+
const record = records.find(r => r.id === feature.id);
|
|
449
|
+
if (record) source = source.replace(/(## Current view\n)[\s\S]*?(?=\n## Lessons)/, (_, heading) => `${heading}\n${record.currentView.trim()}\n`);
|
|
450
|
+
parsed = parseDoc(source, fileName(feature.doc));
|
|
451
|
+
const viewHash = sha(parsed.currentView), sourcesHash = sha(JSON.stringify(selected.files));
|
|
452
|
+
const prior = state.contextPreparation?.authored?.[feature.id];
|
|
453
|
+
if (record || viewHash !== (state.contextPreparation?.views?.[feature.id] ?? feature.baselineViewHash) || prior?.viewHash === viewHash && prior.sourcesHash === sourcesHash) authored[feature.id] = { viewHash, sourcesHash };
|
|
454
|
+
// Keep a repairable scaffold when no implementation anchor exists. Empty
|
|
455
|
+
// evidence must not overwrite valid metadata with an unreadable History.
|
|
456
|
+
if (!selected.files.length) {
|
|
457
|
+
if (!exists || read(root, feature.doc) !== source) writes.push({ path: feature.doc, source });
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
// Replace only this still-active run's preparation, preserving completed history.
|
|
461
|
+
const lines = source.split('\n');
|
|
462
|
+
for (const own of parsed.history.filter(h => h.run === state.id).reverse()) {
|
|
463
|
+
const next = parsed.history.find(h => h.line > own.line);
|
|
464
|
+
lines.splice(own.line - 1, (next ? next.line - 1 : source.split('\n').length) - (own.line - 1));
|
|
465
|
+
}
|
|
466
|
+
source = lines.join('\n');
|
|
467
|
+
const entry = [`### ${date} · run ${state.id} · ${oneLine(state.goal, 100)}`, `**Changed:** ${oneLine(summary || state.goal, 400)}`, `**Learned:** ${oneLine(reason || 'See the authored Current view; no user acceptance is inferred.', 400)}`, `**Decisive check:** Planned commands: ${state.commands.map(c => [c.command, ...c.args].join(' ')).join('; ') || 'none'}. Final outcomes are not yet claimed; inspect run ${state.id} command receipts separately. Local receipts may not travel with source.`, `**Files:** ${selected.files.map(f => `${f.path}@sha256:${f.sha256}`).join(', ')}`].join('\n');
|
|
468
|
+
source = applyEntry(source, { entry, lessons: [], lastChange: `Last changed by AI: ${date} · run ${state.id} · files: ${selected.files.map(f => f.path).join(', ')}` });
|
|
469
|
+
if (!exists || read(root, feature.doc) !== source) writes.push({ path: feature.doc, source });
|
|
470
|
+
}
|
|
471
|
+
for (const path of [...writes.map(w => w.path), plan.index]) { local(root, path); permit(path); }
|
|
472
|
+
const staging = local(root, `.cyc/runs/${state.id}/context-staging`);
|
|
473
|
+
for (const w of writes) { mkdirSync(dirname(local(root, w.path)), { recursive: true }); atomicWrite(local(root, w.path), w.source, staging); }
|
|
474
|
+
if (!existsSync(local(root, plan.index))) { mkdirSync(dirname(local(root, plan.index)), { recursive: true }); atomicWrite(local(root, plan.index), '# Feature context\n\n| Component | Covers | Doc | Last AI change | Lessons |\n| --- | --- | --- | --- | --- |\n', staging); }
|
|
475
|
+
refreshIndex(root, { staging, docs: plan.features.map(f => f.doc) });
|
|
476
|
+
return { paths: writes.map(w => w.path), date, authored, views: Object.fromEntries(plan.features.map(f => [f.id, sha(parseDoc(read(root, f.doc), fileName(f.doc)).currentView)])) };
|
|
477
|
+
}
|
|
478
|
+
|
|
314
479
|
// ---------------------------------------------------------------- run records
|
|
315
480
|
|
|
316
481
|
export function completedRuns(root) {
|
|
@@ -340,6 +505,7 @@ function ledgerEntriesFor(root, state) {
|
|
|
340
505
|
// What a component doc entry needs, read from the run's own record: nothing here is invented, and
|
|
341
506
|
// a field the run did not record is said to be missing.
|
|
342
507
|
export function runRecord(root, state) {
|
|
508
|
+
const { folder: contextFolder } = contextLocation(root);
|
|
343
509
|
const passed = stage => state.handoffs.findLast(h => h.stage === stage && h.status === 'passed');
|
|
344
510
|
const build = state.handoffs.filter(h => h.stage === 'build' && h.status === 'passed');
|
|
345
511
|
const deliver = passed('deliver'), verify = passed('verify');
|
|
@@ -364,7 +530,7 @@ export function runRecord(root, state) {
|
|
|
364
530
|
if (errors?.status === 'recorded' && text(errors.reason)) lessons.push(oneLine(errors.reason, 400));
|
|
365
531
|
for (const reason of retries) lessons.push(`Retry: ${oneLine(reason, 400)}`);
|
|
366
532
|
for (const entry of ledger) lessons.push(`Ledger ${entry.id}: ${entry.title}`);
|
|
367
|
-
const contextDocs = deliver?.contextDocs ?? files.map(f => f.path).filter(p => p
|
|
533
|
+
const contextDocs = (deliver?.contextDocs ?? files.map(f => f.path)).filter(p => isComponentDoc(p, contextFolder));
|
|
368
534
|
return { runId: state.id, date, completedAt, goal: state.goal, playbook: state.playbook, status: state.status, session: state.session ?? null, files,
|
|
369
535
|
changed: build.map(h => oneLine(h.summary.replace(/^Built: /, ''), 400)),
|
|
370
536
|
learning: learning ? { status: learning.status, reason: oneLine(learning.reason, 400), artifacts: learning.artifacts ?? [] } : null,
|
|
@@ -387,16 +553,18 @@ const lessonBullets = record => record.lessons.map(lesson => `- ${record.date}
|
|
|
387
553
|
// ---------------------------------------------------------------- review: propose and write
|
|
388
554
|
|
|
389
555
|
function componentsOf(root) {
|
|
556
|
+
const { folder: contextFolder, index: indexName } = contextLocation(root);
|
|
390
557
|
const exists = existsSync(local(root, indexName));
|
|
391
558
|
const table = exists ? parseIndex(read(root, indexName)) : { rows: [] };
|
|
392
559
|
const components = table.rows.filter(row => !row.malformed).flatMap(row => (row.links.length ? row.links : [null]).map(link => {
|
|
393
560
|
const doc = resolveLink(root, link);
|
|
394
|
-
return { component: row.component, covers: row.covers, doc, inFolder: isComponentDoc(doc) };
|
|
561
|
+
return { component: row.component, covers: row.covers, doc, inFolder: isComponentDoc(doc, contextFolder) };
|
|
395
562
|
}));
|
|
396
563
|
return { exists, components };
|
|
397
564
|
}
|
|
398
565
|
|
|
399
566
|
function recordedRuns(root, docs) {
|
|
567
|
+
const { folder: contextFolder } = contextLocation(root);
|
|
400
568
|
const runs = new Map();
|
|
401
569
|
for (const name of docs) {
|
|
402
570
|
const parsed = parseDoc(read(root, `${contextFolder}/${name}`), name);
|
|
@@ -438,7 +606,8 @@ function indexCells(root, docPath) {
|
|
|
438
606
|
return { parsed, last, lessons };
|
|
439
607
|
}
|
|
440
608
|
|
|
441
|
-
function refreshIndex(root) {
|
|
609
|
+
export function refreshIndex(root, { staging, docs } = {}) {
|
|
610
|
+
const { folder: contextFolder, index: indexName } = contextLocation(root);
|
|
442
611
|
const table = parseIndex(read(root, indexName));
|
|
443
612
|
if (!table.header) throw Error(`${indexName} has no table with a Covers column.`);
|
|
444
613
|
const lines = table.lines;
|
|
@@ -456,11 +625,13 @@ function refreshIndex(root) {
|
|
|
456
625
|
if (row.malformed) continue;
|
|
457
626
|
const docPath = resolveLink(root, row.link);
|
|
458
627
|
const cells = [...row.cells, ...added.map(() => '')];
|
|
459
|
-
if (isComponentDoc(docPath) && existsSync(local(root, docPath))) {
|
|
628
|
+
if (isComponentDoc(docPath, contextFolder) && existsSync(local(root, docPath))) {
|
|
460
629
|
seen.add(docPath);
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
630
|
+
if (!docs || docs.includes(docPath)) {
|
|
631
|
+
const { parsed, last, lessons } = indexCells(root, docPath);
|
|
632
|
+
if (parsed.covers.length) cells[columns.covers] = parsed.covers.join(', ');
|
|
633
|
+
cells[columns.lastChange] = last; cells[columns.lessons] = lessons;
|
|
634
|
+
}
|
|
464
635
|
}
|
|
465
636
|
lines[row.line] = render(cells);
|
|
466
637
|
}
|
|
@@ -468,7 +639,7 @@ function refreshIndex(root) {
|
|
|
468
639
|
const appended = [];
|
|
469
640
|
for (const name of listDocs(root)) {
|
|
470
641
|
const docPath = `${contextFolder}/${name}`;
|
|
471
|
-
if (seen.has(docPath)) continue;
|
|
642
|
+
if (seen.has(docPath) || docs && !docs.includes(docPath)) continue;
|
|
472
643
|
const { parsed, last, lessons } = indexCells(root, docPath);
|
|
473
644
|
const cells = [...Array(width + added.length)].map(() => '');
|
|
474
645
|
if (columns.component >= 0) cells[columns.component] = parsed.title ?? name;
|
|
@@ -478,12 +649,14 @@ function refreshIndex(root) {
|
|
|
478
649
|
appended.push(render(cells));
|
|
479
650
|
}
|
|
480
651
|
lines.splice(lastRow + 1, 0, ...appended);
|
|
481
|
-
|
|
652
|
+
const content = `${lines.join('\n').replace(/\n*$/, '')}\n`;
|
|
653
|
+
if (read(root, indexName) !== content) atomicWrite(local(root, indexName), content, staging);
|
|
482
654
|
return { addedColumns: added, addedRows: appended.length };
|
|
483
655
|
}
|
|
484
656
|
|
|
485
|
-
export function reviewContext(root, { run, since, all = false, write = false, newDoc } = {}) {
|
|
657
|
+
export function reviewContext(root, { run, since, all = false, write = false, newDoc, updateRun } = {}) {
|
|
486
658
|
root = realpathSync(root);
|
|
659
|
+
const { folder: contextFolder, index: indexName } = contextLocation(root);
|
|
487
660
|
if (newDoc !== undefined && (!docFileName.test(`${newDoc}.md`) || reservedDocs.has(`${newDoc}.md`))) throw Error(`--new needs a kebab-case component name (${docFileName.source} without .md).`);
|
|
488
661
|
if (since !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(since)) throw Error('--since needs YYYY-MM-DD.');
|
|
489
662
|
const { exists, components } = componentsOf(root);
|
|
@@ -503,6 +676,7 @@ export function reviewContext(root, { run, since, all = false, write = false, ne
|
|
|
503
676
|
const unmapped = [];
|
|
504
677
|
const retained = new Set([...record.contextDocs, ...(record.learning?.artifacts ?? []), ...(record.errorHistory?.artifacts ?? [])]);
|
|
505
678
|
for (const file of record.files) {
|
|
679
|
+
if (file.path.startsWith('.cyc/') || [indexName, `${contextFolder}/error-ledger.md`, `${contextFolder}/verify-recipe.md`, `${contextFolder}/recipes.json`].includes(file.path)) continue;
|
|
506
680
|
let mapped = false;
|
|
507
681
|
for (const component of components) {
|
|
508
682
|
if (!covered(component.covers, file.path)) continue;
|
|
@@ -511,7 +685,7 @@ export function reviewContext(root, { run, since, all = false, write = false, ne
|
|
|
511
685
|
if (!perComponent.has(key)) perComponent.set(key, { ...component, files: [] });
|
|
512
686
|
perComponent.get(key).files.push(file);
|
|
513
687
|
}
|
|
514
|
-
if (!mapped && !retained.has(file.path)) unmapped.push(file);
|
|
688
|
+
if (!mapped && !retained.has(file.path) && !file.path.startsWith('.cyc/')) unmapped.push(file);
|
|
515
689
|
}
|
|
516
690
|
const proposal = { runId: record.runId, date: record.date, goal: record.goal, playbook: record.playbook, contextDocsTouched: record.contextDocs,
|
|
517
691
|
components: [...perComponent.values()].map(component => {
|
|
@@ -533,6 +707,12 @@ export function reviewContext(root, { run, since, all = false, write = false, ne
|
|
|
533
707
|
const result = { ok: true, index: { path: indexName, exists, components: components.length, componentDocs: docs.length }, runs: proposals, unmappedFiles: [...unmappedAll].map(([path, runs]) => ({ path, runs })), written: null,
|
|
534
708
|
note: write ? 'Entries were appended from the runs\' own records; the Current view of each doc is yours to update. Review the diff before committing.' : 'Read-only proposal from completed run records: nothing was written. Add --write to append these entries and refresh the index; --new NAME creates a doc for unmapped files.' };
|
|
535
709
|
if (!write) return result;
|
|
710
|
+
if (!updateRun) throw Error('Completed-run catch-up needs a new active scoped update: context review --run SOURCE_ID --write --update-run UPDATE_ID. Use context prepare for current work; a reply packet cannot verify changed context.');
|
|
711
|
+
const writePaths = [...new Set([indexName, ...proposals.flatMap(p => [...p.components.filter(c => c.writable && !c.alreadyRecorded).map(c => c.doc), ...(p.newDoc ? [p.newDoc.path] : [])])])];
|
|
712
|
+
return contextUpdate(root, updateRun, writePaths, state => {
|
|
713
|
+
const retention = retentionOf(state);
|
|
714
|
+
if (!state.requiresChecks || !state.commands.length || retention?.disposition !== 'required' || writePaths.some(path => path !== indexName && !retention.features.some(f => f.doc === path))) throw Error('Catch-up needs a required feature-context plan covering these records and executable final verification. Start an implementation update with those canonical docs before Build; advisory catch-up cannot complete the repair.');
|
|
715
|
+
const staging = local(root, `.cyc/runs/${updateRun}/context-staging`);
|
|
536
716
|
const written = [];
|
|
537
717
|
for (const proposal of proposals) {
|
|
538
718
|
for (const component of proposal.components) {
|
|
@@ -542,7 +722,7 @@ export function reviewContext(root, { run, since, all = false, write = false, ne
|
|
|
542
722
|
const blocking = parsed.issues.filter(i => ['sections', 'last-change', 'title'].includes(i.rule));
|
|
543
723
|
if (blocking.length) { written.push({ doc: component.doc, runId: proposal.runId, written: false, reason: `Fix first: ${blocking.map(i => `${i.rule} (${i.message})`).join('; ')}` }); continue; }
|
|
544
724
|
const lastChange = `Last changed by AI: ${proposal.date} · run ${proposal.runId} · files: ${component.files.map(f => f.path).join(', ')}`;
|
|
545
|
-
atomicWrite(local(root, component.doc), applyEntry(source, { entry: component.entry, lessons: component.lessons, lastChange }));
|
|
725
|
+
atomicWrite(local(root, component.doc), applyEntry(source, { entry: component.entry, lessons: component.lessons, lastChange }), staging);
|
|
546
726
|
recorded.set(proposal.runId, [...(recorded.get(proposal.runId) ?? []), component.doc]);
|
|
547
727
|
written.push({ doc: component.doc, runId: proposal.runId, written: true });
|
|
548
728
|
}
|
|
@@ -551,17 +731,19 @@ export function reviewContext(root, { run, since, all = false, write = false, ne
|
|
|
551
731
|
const title = newDoc.split('-').map((w, i) => i ? w : w[0].toUpperCase() + w.slice(1)).join(' ');
|
|
552
732
|
const source = existsSync(local(root, path)) ? read(root, path) : newDocSource(title, covers);
|
|
553
733
|
if (parseDoc(source, `${newDoc}.md`).history.some(e => e.run === proposal.runId)) continue;
|
|
554
|
-
|
|
734
|
+
mkdirSync(dirname(local(root, path)), { recursive: true });
|
|
735
|
+
atomicWrite(local(root, path), applyEntry(source, { entry, lessons, lastChange: `Last changed by AI: ${proposal.date} · run ${proposal.runId} · files: ${covers.join(', ')}` }), staging);
|
|
555
736
|
written.push({ doc: path, runId: proposal.runId, written: true, created: !proposal.newDoc.exists });
|
|
556
737
|
}
|
|
557
738
|
}
|
|
558
739
|
let index = null;
|
|
559
740
|
if (written.some(w => w.written)) {
|
|
560
|
-
if (!existsSync(local(root, indexName))) atomicWrite(local(root, indexName), '# Context index\n\nRead the index, then the docs whose Covers match the paths you are about to change.\n\n| Component | Covers | Doc | Last AI change | Lessons |\n| --- | --- | --- | --- | --- |\n');
|
|
561
|
-
index = refreshIndex(root);
|
|
741
|
+
if (!existsSync(local(root, indexName))) { mkdirSync(dirname(local(root, indexName)), { recursive: true }); atomicWrite(local(root, indexName), '# Context index\n\nRead the index, then the docs whose Covers match the paths you are about to change.\n\n| Component | Covers | Doc | Last AI change | Lessons |\n| --- | --- | --- | --- | --- |\n', staging); }
|
|
742
|
+
index = refreshIndex(root, { staging });
|
|
562
743
|
}
|
|
563
744
|
const lint = lintContext(root, { git: false });
|
|
564
745
|
return { ...result, written, indexRefreshed: index, lint: { ok: lint.ok, index: lint.index.issues, docs: lint.docs.filter(d => !d.ok).map(d => ({ path: d.path, issues: d.issues })) } };
|
|
746
|
+
});
|
|
565
747
|
}
|
|
566
748
|
|
|
567
749
|
// ---------------------------------------------------------------- measure: what the index path costs
|
|
@@ -571,6 +753,7 @@ const tokensEstimate = chars => Math.round(chars / 4);
|
|
|
571
753
|
|
|
572
754
|
export function measureContext(root, { paths = [], run } = {}) {
|
|
573
755
|
root = realpathSync(root);
|
|
756
|
+
const { folder: contextFolder, index: indexName } = contextLocation(root);
|
|
574
757
|
if (!Array.isArray(paths)) throw Error('Paths must be an array.');
|
|
575
758
|
const { exists, components } = componentsOf(root);
|
|
576
759
|
if (!exists) throw Error(`${indexName} does not exist; nothing to measure.`);
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { digest } from './response-gate.mjs';
|
|
2
|
+
import { strictObject, text, identifier, strings, contextHash, renderContext, requireContextReady, touchContext, validateEvidence } from './task-context.mjs';
|
|
3
|
+
|
|
4
|
+
const finite = n => Number.isFinite(n) && n >= 0;
|
|
5
|
+
const positive = n => Number.isSafeInteger(n) && n > 0;
|
|
6
|
+
const within = (path, prefix) => path === prefix || path.startsWith(prefix + '/');
|
|
7
|
+
const sourceBasis = (source, paths) => Object.fromEntries(Object.entries(source).filter(([path]) => paths.some(prefix => within(path,prefix))).sort(([a],[b]) => a.localeCompare(b)));
|
|
8
|
+
const sourceDrift = (assignment, source) => digest(JSON.stringify(sourceBasis(source,assignment.paths))) !== assignment.basisHash;
|
|
9
|
+
export function delegationPolicy(input) {
|
|
10
|
+
strictObject(input, ['version','mode','maxWorkers','maxAssignments','budgetTokens','reserveTokens','maxResultBytes'], 'delegation');
|
|
11
|
+
if (input.version !== 1 || !['off','recommend','auto'].includes(input.mode ?? 'recommend')) throw Error('Delegation needs version 1 and off, recommend or auto mode.');
|
|
12
|
+
for (const key of ['budgetTokens','reserveTokens']) if (input[key] !== undefined && !positive(input[key])) throw Error('Invalid legacy token metadata.');
|
|
13
|
+
const { budgetTokens, reserveTokens, ...settings } = input;
|
|
14
|
+
const p = { version: 1, mode: 'recommend', maxWorkers: input.mode === 'auto' ? 2 : 1, maxAssignments: 4, maxResultBytes: 32768, ...settings };
|
|
15
|
+
if (!positive(p.maxWorkers) || p.maxWorkers > 8 || !positive(p.maxAssignments) || p.maxAssignments > 100 || !positive(p.maxResultBytes) || p.maxResultBytes > 262144) throw Error('Invalid delegation worker/result limits.');
|
|
16
|
+
return p;
|
|
17
|
+
}
|
|
18
|
+
export function initializeDelegation(policy) {
|
|
19
|
+
return { version: 1, policy, decision: null, assignments: [], accountedTokens: 0, usageReceipts: [], observedTokens: 0, usageUnknown: false };
|
|
20
|
+
}
|
|
21
|
+
function ledger(state) {
|
|
22
|
+
if (!state.delegation) throw Error('Delegation policy must be frozen at run start.');
|
|
23
|
+
return state.delegation;
|
|
24
|
+
}
|
|
25
|
+
export function decideDelegation(state, input) {
|
|
26
|
+
strictObject(input, ['version','objective','facts','capabilities','estimates'], 'delegation decision');
|
|
27
|
+
strictObject(input.facts, ['independent','sharedState','evidence'], 'task facts');
|
|
28
|
+
strictObject(input.capabilities, ['dispatch','evidence'], 'capabilities');
|
|
29
|
+
if (input.version !== 1 || !['tokens','spend','time'].includes(input.objective) || typeof input.facts.independent !== 'boolean' || typeof input.facts.sharedState !== 'boolean' || !text(input.facts.evidence) || typeof input.capabilities.dispatch !== 'boolean' || !text(input.capabilities.evidence)) throw Error('Decision needs explicit objective, dependency facts and capability evidence.');
|
|
30
|
+
if (input.estimates !== undefined) {
|
|
31
|
+
strictObject(input.estimates, ['solo','delegated','evidence'], 'estimates');
|
|
32
|
+
for (const k of ['solo','delegated']) {
|
|
33
|
+
strictObject(input.estimates[k], ['min','max'], 'estimate range');
|
|
34
|
+
if (!finite(input.estimates[k].min) || !finite(input.estimates[k].max) || input.estimates[k].max < input.estimates[k].min) throw Error('Invalid estimate range.');
|
|
35
|
+
}
|
|
36
|
+
if (!text(input.estimates.evidence)) throw Error('Estimate provenance is required.');
|
|
37
|
+
}
|
|
38
|
+
const d = ledger(state);
|
|
39
|
+
let route = 'solo', reason = 'Economic advantage is unknown or estimate ranges overlap.';
|
|
40
|
+
if (d.policy.mode === 'off') reason = 'Optional delegation is disabled; required review is unaffected.';
|
|
41
|
+
else if (!input.capabilities.dispatch) reason = 'Host dispatch is unavailable or not observed.';
|
|
42
|
+
else if (!input.facts.independent || input.facts.sharedState) reason = 'Shared or dependent decisions favor one owner.';
|
|
43
|
+
else if (input.objective === 'time') { route = 'delegate'; reason = 'Independent work can be delegated for time; token savings are not established.'; }
|
|
44
|
+
else if (input.estimates && input.estimates.delegated.max < input.estimates.solo.min) { route = 'delegate'; reason = 'Agent-reported full-route estimate ranges favor bounded delegation.'; }
|
|
45
|
+
d.decision = { version: 1, route, reason, ...structuredClone(input), origin: 'agent-reported; not host capability attestation or measured savings' };
|
|
46
|
+
return { route, reason, policy: d.policy, estimates: input.estimates ?? null, origin: d.decision.origin };
|
|
47
|
+
}
|
|
48
|
+
export function assignWorker(state, input, io) {
|
|
49
|
+
strictObject(input, ['version','id','objective','criteria','paths','writePaths','dependencies','contextRevision','contextHash','tokenBudget','stoppingRule','hostReference'], 'assignment');
|
|
50
|
+
const d = ledger(state); requireContextReady(state, io, { allowPending: true });
|
|
51
|
+
if (d.policy.mode === 'off' || d.decision?.route !== 'delegate') throw Error('A current bounded delegation decision is required.');
|
|
52
|
+
if (input.version !== 1 || !identifier(input.id) || !text(input.objective) || !text(input.stoppingRule) || input.tokenBudget !== undefined && !positive(input.tokenBudget)) throw Error('Invalid assignment identity/objective/stopping rule or legacy token metadata.');
|
|
53
|
+
for (const k of ['criteria','paths','writePaths','dependencies']) strings(input[k], k);
|
|
54
|
+
if (input.writePaths.length) throw Error('Initial delegation is read-only; worker writePaths must be empty.');
|
|
55
|
+
if (!input.paths.length || !input.criteria.length || input.criteria.some(id => !state.criteria.some(c => c.id === id))) throw Error('Assignment must cover declared criteria and a bounded source scope.');
|
|
56
|
+
if (input.contextRevision !== state.taskContext.revision || input.contextHash !== contextHash(state)) throw Error('Assignment needs the current acknowledged context revision/hash.');
|
|
57
|
+
if (input.hostReference !== undefined && !text(input.hostReference)) throw Error('Host reference must be observed nonempty text.');
|
|
58
|
+
if (d.assignments.some(a => a.id === input.id)) throw Error('Assignment IDs cannot be reused.');
|
|
59
|
+
if (d.assignments.length >= d.policy.maxAssignments) throw Error('Total assignment budget exhausted.');
|
|
60
|
+
const active = d.assignments.filter(a => ['active','cancelling'].includes(a.status));
|
|
61
|
+
if (active.length >= d.policy.maxWorkers) throw Error('Active worker limit reached; cancellation needs host acknowledgment.');
|
|
62
|
+
if (input.dependencies.some(id => id === input.id || !d.assignments.some(a => a.id === id && a.disposition === 'accepted'))) throw Error('Dependencies must be existing accepted assignments; cyclic/unknown dependencies are rejected.');
|
|
63
|
+
const paths = io.normalize(input.paths);
|
|
64
|
+
if (paths.some(path => state.allowedPaths.length && !state.allowedPaths.some(prefix => within(path, prefix)))) throw Error('Assignment scope exceeds parent authority.');
|
|
65
|
+
for (const path of paths) io.file(path);
|
|
66
|
+
const snapshot = io.source();
|
|
67
|
+
const basis = sourceBasis(snapshot,paths);
|
|
68
|
+
if (!Object.keys(basis).length || paths.some(p => !Object.keys(basis).some(file => within(file,p)))) throw Error('Each read scope needs current regular source files.');
|
|
69
|
+
const hash = contextHash(state);
|
|
70
|
+
const { tokenBudget, ...details } = input;
|
|
71
|
+
const assignment = { ...structuredClone(details), paths, basis, basisHash: digest(JSON.stringify(basis)), ...(d.policy.mode==='auto'?{contextDocument:renderContext(state)}:{}), status: 'active', stage: state.stages[state.stageIndex], attempt: state.attempt };
|
|
72
|
+
d.assignments.push(assignment); touchContext(state, hash);
|
|
73
|
+
return { runId: state.id, assignment: structuredClone(assignment), enforcement: 'Worker concurrency/scope limits; token usage is reporting only.' };
|
|
74
|
+
}
|
|
75
|
+
export function recordWorker(state, input, io) {
|
|
76
|
+
strictObject(input, ['version','assignmentId','resultId','status','contextRevision','contextHash','basisHash','summary','findings','failedApproaches','questions','checks','usage','hostStopped'], 'worker result');
|
|
77
|
+
const d = ledger(state), a = d.assignments.find(a => a.id === input.assignmentId);
|
|
78
|
+
if (!a) throw Error('Unknown assignment.');
|
|
79
|
+
if (Buffer.byteLength(JSON.stringify(input)) > d.policy.maxResultBytes) throw Error('Worker result exceeds maxResultBytes.');
|
|
80
|
+
const resultHash = digest(JSON.stringify(input));
|
|
81
|
+
if (a.result) {
|
|
82
|
+
if (a.resultHash === resultHash) return { runId: state.id, assignmentId: a.id, duplicate: true };
|
|
83
|
+
throw Error('Worker result replay differs from the recorded result.');
|
|
84
|
+
}
|
|
85
|
+
if (d.assignments.some(other => other.id !== a.id && other.result?.resultId === input.resultId)) throw Error('Result ID is already bound to another assignment.');
|
|
86
|
+
if (input.version !== 1 || !identifier(input.resultId) || !['passed','failed','cancelled'].includes(input.status) || input.hostStopped !== true || !text(input.summary)) throw Error('Result needs a terminal host acknowledgment, valid status and summary.');
|
|
87
|
+
if (input.contextRevision !== a.contextRevision || input.contextHash !== a.contextHash || input.basisHash !== a.basisHash) throw Error('Worker result has a foreign/stale assignment basis.');
|
|
88
|
+
if (!Array.isArray(input.findings) || new Set(input.findings.map(f=>f?.id)).size !== input.findings.length) throw Error('Worker findings need unique IDs.');
|
|
89
|
+
strings(input.failedApproaches, 'failedApproaches'); strings(input.questions, 'questions');
|
|
90
|
+
for (const f of input.findings) {
|
|
91
|
+
strictObject(f, ['id','text','evidence'], 'worker finding');
|
|
92
|
+
if (!identifier(f.id) || !text(f.text)) throw Error('Invalid worker finding.');
|
|
93
|
+
validateEvidence(state,f.evidence,io,{current:false});
|
|
94
|
+
if (f.evidence.some(e => { const path=io.normalize([e.path])[0]; return !a.paths.some(p => within(path,p)); })) throw Error('Worker evidence exceeds assignment scope.');
|
|
95
|
+
}
|
|
96
|
+
if (input.checks !== undefined) {
|
|
97
|
+
if (!Array.isArray(input.checks)) throw Error('checks needs an array.');
|
|
98
|
+
for (const c of input.checks) { strictObject(c,['command','result','evidence'],'reported check'); if (!text(c.command)||!['passed','failed','unverified'].includes(c.result)||!text(c.evidence)) throw Error('Invalid agent-reported check.'); }
|
|
99
|
+
}
|
|
100
|
+
const hash = contextHash(state);
|
|
101
|
+
recordUsage(d,input.usage);
|
|
102
|
+
const now = io.source();
|
|
103
|
+
a.result = structuredClone(input); a.resultHash = resultHash; a.status = 'returned';
|
|
104
|
+
a.stale = sourceDrift(a,now);
|
|
105
|
+
touchContext(state,hash);
|
|
106
|
+
return { runId: state.id, assignmentId: a.id, status: 'needs-reconciliation', stale: a.stale, accountedTokens: d.accountedTokens };
|
|
107
|
+
}
|
|
108
|
+
export function recordUsage(d,usage) {
|
|
109
|
+
let charge = 0;
|
|
110
|
+
if (usage !== undefined) {
|
|
111
|
+
strictObject(usage, ['receiptId','inputTokens','outputTokens','cachedInputTokens','model','origin'], 'usage');
|
|
112
|
+
const u = usage;
|
|
113
|
+
if (!identifier(u.receiptId) || !['host-reported','agent-estimated'].includes(u.origin) || !text(u.model) || !Number.isSafeInteger(u.inputTokens) || u.inputTokens < 0 || !Number.isSafeInteger(u.outputTokens) || u.outputTokens < 0 || u.cachedInputTokens !== undefined && (!Number.isSafeInteger(u.cachedInputTokens)||u.cachedInputTokens<0||u.cachedInputTokens>u.inputTokens)) throw Error('Invalid usage observation.');
|
|
114
|
+
if (d.usageReceipts.includes(u.receiptId)) throw Error('Usage receipt was already accounted.');
|
|
115
|
+
charge = u.inputTokens + u.outputTokens;
|
|
116
|
+
if (!Number.isSafeInteger(charge) || !Number.isSafeInteger(d.accountedTokens + charge)) throw Error('Usage exceeds safe integer accounting.');
|
|
117
|
+
if (u.origin === 'host-reported') d.observedTokens += charge;
|
|
118
|
+
else d.usageUnknown = true;
|
|
119
|
+
d.usageReceipts.push(u.receiptId);
|
|
120
|
+
} else d.usageUnknown = true;
|
|
121
|
+
d.accountedTokens += charge;
|
|
122
|
+
}
|
|
123
|
+
export function assignBatch(state,tasks,io) {
|
|
124
|
+
if (!Array.isArray(tasks)||!tasks.length||new Set(tasks.map(t=>t.id)).size!==tasks.length) throw Error('Batch needs unique assignments.');
|
|
125
|
+
const d=ledger(state), active=d.assignments.filter(a=>['active','cancelling'].includes(a.status)).length;
|
|
126
|
+
if(active+tasks.length>d.policy.maxWorkers||d.assignments.length+tasks.length>d.policy.maxAssignments)throw Error('Batch exceeds frozen worker/assignment limits.');
|
|
127
|
+
const source=JSON.stringify(io.source()),hash=contextHash(state);
|
|
128
|
+
const assignments=tasks.map(t=>assignWorker(structuredClone(state),t,io).assignment);
|
|
129
|
+
if(JSON.stringify(io.source())!==source)throw Error('Batch source changed during validation.');
|
|
130
|
+
d.assignments.push(...assignments);touchContext(state,hash);
|
|
131
|
+
return {assignments:structuredClone(assignments)};
|
|
132
|
+
}
|
|
133
|
+
export function cancelWorker(state, input) {
|
|
134
|
+
strictObject(input,['version','assignmentId','reason'],'cancellation');
|
|
135
|
+
const a = ledger(state).assignments.find(a=>a.id===input.assignmentId);
|
|
136
|
+
if (input.version!==1 || !a || a.status!=='active' || !text(input.reason)) throw Error('Cancellation needs an active assignment and reason.');
|
|
137
|
+
const hash=contextHash(state); a.status='cancelling'; a.cancelReason=input.reason; touchContext(state,hash);
|
|
138
|
+
return { runId:state.id,assignmentId:a.id,status:'cancelling',nextAction:'Cancel in the host, then record its terminal acknowledgment; capacity remains reserved.' };
|
|
139
|
+
}
|
|
140
|
+
export function reconcileWorkers(state, input, io) {
|
|
141
|
+
if (!Array.isArray(input.dispositions)) throw Error('Reconciliation needs contribution dispositions.');
|
|
142
|
+
const d=state.delegation;
|
|
143
|
+
if (!d && input.dispositions.length) throw Error('No worker contributions exist.');
|
|
144
|
+
const seen=new Set();
|
|
145
|
+
for (const item of input.dispositions) {
|
|
146
|
+
strictObject(item,['assignmentId','status','reason','findingIds','revalidation'],'worker disposition');
|
|
147
|
+
const a=d?.assignments.find(a=>a.id===item.assignmentId);
|
|
148
|
+
if (!a?.result || a.disposition || seen.has(a.id) || !['accepted','rejected'].includes(item.status) || !text(item.reason)) throw Error('Disposition needs an undisposed terminal result and evidence/reason.');
|
|
149
|
+
a.stale ||= sourceDrift(a,io.source());
|
|
150
|
+
strings(item.findingIds,'disposition findingIds');
|
|
151
|
+
if (item.status==='accepted' && (!item.findingIds.length || a.stale&&!text(item.revalidation) || item.findingIds.some(id=>!input.findings?.some(f=>f.id===id && f.origins?.includes(a.id) && !['stale','superseded'].includes(f.status))))) throw Error('Accepted results need retained findings with origin and explicit stale-source revalidation.');
|
|
152
|
+
for (const failure of a.result.failedApproaches) if (!input.failedApproaches?.includes(failure)) throw Error('Retain worker failed approaches as negative evidence.');
|
|
153
|
+
if (a.result.questions.length && !text(item.revalidation) && !input.conflicts?.length) throw Error('Resolve worker questions explicitly or retain an unresolved conflict.');
|
|
154
|
+
a.disposition=item.status; a.dispositionReason=item.reason; seen.add(a.id);
|
|
155
|
+
}
|
|
156
|
+
}
|