cyc-stack 0.7.0 → 0.8.3
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/INSTALL.md +2 -0
- package/README.md +1 -1
- package/bin/cyc.mjs +81 -22
- package/docs/context.md +10 -26
- package/docs/installation.md +4 -0
- package/docs/project-tools.md +14 -10
- package/docs/response-standard.md +8 -32
- package/docs/runtime.md +58 -174
- package/docs/work-assessments.md +25 -92
- package/methods/cyc-build/SKILL.md +1 -1
- package/methods/cyc-challenge/SKILL.md +4 -0
- package/methods/cyc-context/SKILL.md +18 -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 +2 -2
- package/methods/cyc-remember/SKILL.md +1 -1
- package/methods/cyc-scout/SKILL.md +17 -51
- package/methods/cyc-verify/SKILL.md +15 -66
- package/methods/cyc-verify/references/recipe.md +2 -0
- package/package.json +4 -1
- package/plugin.json +1 -1
- package/rules/cyc-delivery.mdc +33 -33
- package/scripts/browser-audit.mjs +53 -0
- package/scripts/context-review.mjs +202 -29
- package/scripts/execution.mjs +51 -0
- package/scripts/packet.mjs +21 -6
- package/scripts/project-tools.mjs +18 -16
- package/scripts/run-worker.mjs +4 -0
- package/scripts/runtime.mjs +482 -65
- package/scripts/work-review.mjs +32 -10
- package/skills/cyc/SKILL.md +24 -71
|
@@ -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,137 @@ 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 paths = feature.paths.length ? feature.paths : changed;
|
|
373
|
+
const recordCovers = existsSync(local(root, feature.doc)) ? parseDoc(read(root, feature.doc), fileName(feature.doc)).covers : [];
|
|
374
|
+
const selected = changed.filter(p => covered([...paths, ...recordCovers], p));
|
|
375
|
+
for (const path of paths) {
|
|
376
|
+
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));
|
|
377
|
+
if (sample && !selected.includes(sample)) selected.push(sample);
|
|
378
|
+
}
|
|
379
|
+
return { paths, files: selected.slice(0, 32).map(path => ({ path, sha256: files[path] })) };
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
export function checkRetention(root, state, files) {
|
|
383
|
+
const plan = retentionOf(state);
|
|
384
|
+
if (!plan) return { ok: true, status: 'legacy', docs: [], issues: [], note: 'Historical run has no feature-retention contract.' };
|
|
385
|
+
const issues = [], docs = [], ownership = [];
|
|
386
|
+
const issue = (rule, message, doc) => issues.push({ rule, message, ...(doc ? { doc } : {}) });
|
|
387
|
+
const edits = [...new Set([...Object.keys(state.initialSource.files), ...Object.keys(files)])].filter(p => files[p] !== state.initialSource.files[p] && !p.startsWith('.cyc/'));
|
|
388
|
+
const changed = edits.filter(p => !support(p, plan.folder));
|
|
389
|
+
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.' };
|
|
390
|
+
if (plan.disposition === 'unnecessary') {
|
|
391
|
+
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.');
|
|
392
|
+
return { ok: !issues.length, status: issues.length ? 'pending' : 'unnecessary', docs, issues };
|
|
393
|
+
}
|
|
394
|
+
const index = lintIndex(root, { git: false, docs: plan.features.map(f => f.doc) });
|
|
395
|
+
if (!index.exists) issue('toc-link', `Missing target index ${plan.index}.`);
|
|
396
|
+
issues.push(...index.issues);
|
|
397
|
+
for (const feature of plan.features) {
|
|
398
|
+
const doc = feature.doc;
|
|
399
|
+
if (!existsSync(local(root, doc))) { issue('feature-doc', `Missing canonical record for ${feature.id}.`, doc); continue; }
|
|
400
|
+
const parsed = lintDoc(root, doc), selected = featureFiles(root, state, feature, files);
|
|
401
|
+
ownership.push(...parsed.covers);
|
|
402
|
+
issues.push(...parsed.issues.map(i => ({ ...i, doc })));
|
|
403
|
+
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);
|
|
404
|
+
if (parsed.covers.some(catchAll)) issue('feature-coverage', 'A catch-all is not focused feature ownership.', doc);
|
|
405
|
+
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);
|
|
406
|
+
const rows = index.rows.filter(row => row.componentDoc && row.doc === doc);
|
|
407
|
+
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);
|
|
408
|
+
const latest = parsed.history[0];
|
|
409
|
+
if (parsed.history.filter(h => h.run === state.id).length !== 1) issue('feature-history', 'Keep exactly one entry for the current run.', doc);
|
|
410
|
+
if (latest?.run !== state.id) issue('feature-history', 'Current feature work needs its own dated History entry before verification.', doc);
|
|
411
|
+
if (!latest?.files.length) issue('feature-evidence', 'Current History needs actual selected source evidence.', doc);
|
|
412
|
+
for (const item of latest?.files ?? []) {
|
|
413
|
+
try {
|
|
414
|
+
const path = canonicalPattern(item.path, { patterns: false });
|
|
415
|
+
if (support(path, plan.folder) || !files[path] || !files[path].startsWith(item.hash.replace(/^sha256:/, ''))) issue('feature-evidence', `Missing/stale current source evidence: ${path}.`, doc);
|
|
416
|
+
} catch (error) { issue('feature-evidence', error.message, doc); }
|
|
417
|
+
}
|
|
418
|
+
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);
|
|
419
|
+
const authored = state.contextPreparation?.authored?.[feature.id];
|
|
420
|
+
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);
|
|
421
|
+
if (!files[doc] || !files[plan.index]) issue('feature-source', 'Canonical context/index must be included in verified source, not ignored runtime data.', doc);
|
|
422
|
+
docs.push(doc);
|
|
423
|
+
}
|
|
424
|
+
for (const path of changed) {
|
|
425
|
+
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}.`);
|
|
426
|
+
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.`);
|
|
427
|
+
}
|
|
428
|
+
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.' };
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// Only the caller's active, scoped runtime transaction may invoke this writer.
|
|
432
|
+
// It uses observations available now; final receipts stay outside covered source.
|
|
433
|
+
export function prepareRetention(root, state, { records = [], summary = '', reason = '' } = {}, files, permit) {
|
|
434
|
+
const plan = retentionOf(state);
|
|
435
|
+
if (!plan || plan.disposition !== 'required') return { paths: [], authored: {} };
|
|
436
|
+
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.');
|
|
437
|
+
const writes = [], authored = {};
|
|
438
|
+
const date = state.contextPreparation?.date ?? new Date().toISOString().slice(0, 10);
|
|
439
|
+
for (const feature of plan.features) {
|
|
440
|
+
const exists = existsSync(local(root, feature.doc)), selected = featureFiles(root, state, feature, files);
|
|
441
|
+
let source = exists ? read(root, feature.doc) : newDocSource(feature.id.replaceAll('-', ' '), selected.files.length ? selected.files.map(f => f.path) : selected.paths);
|
|
442
|
+
let parsed = parseDoc(source, fileName(feature.doc));
|
|
443
|
+
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.`);
|
|
444
|
+
const record = records.find(r => r.id === feature.id);
|
|
445
|
+
if (record) source = source.replace(/(## Current view\n)[\s\S]*?(?=\n## Lessons)/, (_, heading) => `${heading}\n${record.currentView.trim()}\n`);
|
|
446
|
+
parsed = parseDoc(source, fileName(feature.doc));
|
|
447
|
+
const viewHash = sha(parsed.currentView), sourcesHash = sha(JSON.stringify(selected.files));
|
|
448
|
+
const prior = state.contextPreparation?.authored?.[feature.id];
|
|
449
|
+
if (record || viewHash !== (state.contextPreparation?.views?.[feature.id] ?? feature.baselineViewHash) || prior?.viewHash === viewHash && prior.sourcesHash === sourcesHash) authored[feature.id] = { viewHash, sourcesHash };
|
|
450
|
+
// Replace only this still-active run's preparation, preserving completed history.
|
|
451
|
+
const lines = source.split('\n');
|
|
452
|
+
for (const own of parsed.history.filter(h => h.run === state.id).reverse()) {
|
|
453
|
+
const next = parsed.history.find(h => h.line > own.line);
|
|
454
|
+
lines.splice(own.line - 1, (next ? next.line - 1 : source.split('\n').length) - (own.line - 1));
|
|
455
|
+
}
|
|
456
|
+
source = lines.join('\n');
|
|
457
|
+
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');
|
|
458
|
+
source = applyEntry(source, { entry, lessons: [], lastChange: `Last changed by AI: ${date} · run ${state.id} · files: ${selected.files.map(f => f.path).join(', ')}` });
|
|
459
|
+
if (!exists || read(root, feature.doc) !== source) writes.push({ path: feature.doc, source });
|
|
460
|
+
}
|
|
461
|
+
for (const path of [...writes.map(w => w.path), plan.index]) { local(root, path); permit(path); }
|
|
462
|
+
const staging = local(root, `.cyc/runs/${state.id}/context-staging`);
|
|
463
|
+
for (const w of writes) { mkdirSync(dirname(local(root, w.path)), { recursive: true }); atomicWrite(local(root, w.path), w.source, staging); }
|
|
464
|
+
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); }
|
|
465
|
+
refreshIndex(root, { staging, docs: plan.features.map(f => f.doc) });
|
|
466
|
+
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)])) };
|
|
467
|
+
}
|
|
468
|
+
|
|
314
469
|
// ---------------------------------------------------------------- run records
|
|
315
470
|
|
|
316
471
|
export function completedRuns(root) {
|
|
@@ -340,6 +495,7 @@ function ledgerEntriesFor(root, state) {
|
|
|
340
495
|
// What a component doc entry needs, read from the run's own record: nothing here is invented, and
|
|
341
496
|
// a field the run did not record is said to be missing.
|
|
342
497
|
export function runRecord(root, state) {
|
|
498
|
+
const { folder: contextFolder } = contextLocation(root);
|
|
343
499
|
const passed = stage => state.handoffs.findLast(h => h.stage === stage && h.status === 'passed');
|
|
344
500
|
const build = state.handoffs.filter(h => h.stage === 'build' && h.status === 'passed');
|
|
345
501
|
const deliver = passed('deliver'), verify = passed('verify');
|
|
@@ -364,7 +520,7 @@ export function runRecord(root, state) {
|
|
|
364
520
|
if (errors?.status === 'recorded' && text(errors.reason)) lessons.push(oneLine(errors.reason, 400));
|
|
365
521
|
for (const reason of retries) lessons.push(`Retry: ${oneLine(reason, 400)}`);
|
|
366
522
|
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
|
|
523
|
+
const contextDocs = (deliver?.contextDocs ?? files.map(f => f.path)).filter(p => isComponentDoc(p, contextFolder));
|
|
368
524
|
return { runId: state.id, date, completedAt, goal: state.goal, playbook: state.playbook, status: state.status, session: state.session ?? null, files,
|
|
369
525
|
changed: build.map(h => oneLine(h.summary.replace(/^Built: /, ''), 400)),
|
|
370
526
|
learning: learning ? { status: learning.status, reason: oneLine(learning.reason, 400), artifacts: learning.artifacts ?? [] } : null,
|
|
@@ -387,16 +543,18 @@ const lessonBullets = record => record.lessons.map(lesson => `- ${record.date}
|
|
|
387
543
|
// ---------------------------------------------------------------- review: propose and write
|
|
388
544
|
|
|
389
545
|
function componentsOf(root) {
|
|
546
|
+
const { folder: contextFolder, index: indexName } = contextLocation(root);
|
|
390
547
|
const exists = existsSync(local(root, indexName));
|
|
391
548
|
const table = exists ? parseIndex(read(root, indexName)) : { rows: [] };
|
|
392
549
|
const components = table.rows.filter(row => !row.malformed).flatMap(row => (row.links.length ? row.links : [null]).map(link => {
|
|
393
550
|
const doc = resolveLink(root, link);
|
|
394
|
-
return { component: row.component, covers: row.covers, doc, inFolder: isComponentDoc(doc) };
|
|
551
|
+
return { component: row.component, covers: row.covers, doc, inFolder: isComponentDoc(doc, contextFolder) };
|
|
395
552
|
}));
|
|
396
553
|
return { exists, components };
|
|
397
554
|
}
|
|
398
555
|
|
|
399
556
|
function recordedRuns(root, docs) {
|
|
557
|
+
const { folder: contextFolder } = contextLocation(root);
|
|
400
558
|
const runs = new Map();
|
|
401
559
|
for (const name of docs) {
|
|
402
560
|
const parsed = parseDoc(read(root, `${contextFolder}/${name}`), name);
|
|
@@ -438,7 +596,8 @@ function indexCells(root, docPath) {
|
|
|
438
596
|
return { parsed, last, lessons };
|
|
439
597
|
}
|
|
440
598
|
|
|
441
|
-
function refreshIndex(root) {
|
|
599
|
+
export function refreshIndex(root, { staging, docs } = {}) {
|
|
600
|
+
const { folder: contextFolder, index: indexName } = contextLocation(root);
|
|
442
601
|
const table = parseIndex(read(root, indexName));
|
|
443
602
|
if (!table.header) throw Error(`${indexName} has no table with a Covers column.`);
|
|
444
603
|
const lines = table.lines;
|
|
@@ -456,11 +615,13 @@ function refreshIndex(root) {
|
|
|
456
615
|
if (row.malformed) continue;
|
|
457
616
|
const docPath = resolveLink(root, row.link);
|
|
458
617
|
const cells = [...row.cells, ...added.map(() => '')];
|
|
459
|
-
if (isComponentDoc(docPath) && existsSync(local(root, docPath))) {
|
|
618
|
+
if (isComponentDoc(docPath, contextFolder) && existsSync(local(root, docPath))) {
|
|
460
619
|
seen.add(docPath);
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
620
|
+
if (!docs || docs.includes(docPath)) {
|
|
621
|
+
const { parsed, last, lessons } = indexCells(root, docPath);
|
|
622
|
+
if (parsed.covers.length) cells[columns.covers] = parsed.covers.join(', ');
|
|
623
|
+
cells[columns.lastChange] = last; cells[columns.lessons] = lessons;
|
|
624
|
+
}
|
|
464
625
|
}
|
|
465
626
|
lines[row.line] = render(cells);
|
|
466
627
|
}
|
|
@@ -468,7 +629,7 @@ function refreshIndex(root) {
|
|
|
468
629
|
const appended = [];
|
|
469
630
|
for (const name of listDocs(root)) {
|
|
470
631
|
const docPath = `${contextFolder}/${name}`;
|
|
471
|
-
if (seen.has(docPath)) continue;
|
|
632
|
+
if (seen.has(docPath) || docs && !docs.includes(docPath)) continue;
|
|
472
633
|
const { parsed, last, lessons } = indexCells(root, docPath);
|
|
473
634
|
const cells = [...Array(width + added.length)].map(() => '');
|
|
474
635
|
if (columns.component >= 0) cells[columns.component] = parsed.title ?? name;
|
|
@@ -478,12 +639,14 @@ function refreshIndex(root) {
|
|
|
478
639
|
appended.push(render(cells));
|
|
479
640
|
}
|
|
480
641
|
lines.splice(lastRow + 1, 0, ...appended);
|
|
481
|
-
|
|
642
|
+
const content = `${lines.join('\n').replace(/\n*$/, '')}\n`;
|
|
643
|
+
if (read(root, indexName) !== content) atomicWrite(local(root, indexName), content, staging);
|
|
482
644
|
return { addedColumns: added, addedRows: appended.length };
|
|
483
645
|
}
|
|
484
646
|
|
|
485
|
-
export function reviewContext(root, { run, since, all = false, write = false, newDoc } = {}) {
|
|
647
|
+
export function reviewContext(root, { run, since, all = false, write = false, newDoc, updateRun } = {}) {
|
|
486
648
|
root = realpathSync(root);
|
|
649
|
+
const { folder: contextFolder, index: indexName } = contextLocation(root);
|
|
487
650
|
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
651
|
if (since !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(since)) throw Error('--since needs YYYY-MM-DD.');
|
|
489
652
|
const { exists, components } = componentsOf(root);
|
|
@@ -503,6 +666,7 @@ export function reviewContext(root, { run, since, all = false, write = false, ne
|
|
|
503
666
|
const unmapped = [];
|
|
504
667
|
const retained = new Set([...record.contextDocs, ...(record.learning?.artifacts ?? []), ...(record.errorHistory?.artifacts ?? [])]);
|
|
505
668
|
for (const file of record.files) {
|
|
669
|
+
if (file.path.startsWith('.cyc/') || [indexName, `${contextFolder}/error-ledger.md`, `${contextFolder}/verify-recipe.md`, `${contextFolder}/recipes.json`].includes(file.path)) continue;
|
|
506
670
|
let mapped = false;
|
|
507
671
|
for (const component of components) {
|
|
508
672
|
if (!covered(component.covers, file.path)) continue;
|
|
@@ -511,7 +675,7 @@ export function reviewContext(root, { run, since, all = false, write = false, ne
|
|
|
511
675
|
if (!perComponent.has(key)) perComponent.set(key, { ...component, files: [] });
|
|
512
676
|
perComponent.get(key).files.push(file);
|
|
513
677
|
}
|
|
514
|
-
if (!mapped && !retained.has(file.path)) unmapped.push(file);
|
|
678
|
+
if (!mapped && !retained.has(file.path) && !file.path.startsWith('.cyc/')) unmapped.push(file);
|
|
515
679
|
}
|
|
516
680
|
const proposal = { runId: record.runId, date: record.date, goal: record.goal, playbook: record.playbook, contextDocsTouched: record.contextDocs,
|
|
517
681
|
components: [...perComponent.values()].map(component => {
|
|
@@ -533,6 +697,12 @@ export function reviewContext(root, { run, since, all = false, write = false, ne
|
|
|
533
697
|
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
698
|
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
699
|
if (!write) return result;
|
|
700
|
+
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.');
|
|
701
|
+
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] : [])])])];
|
|
702
|
+
return contextUpdate(root, updateRun, writePaths, state => {
|
|
703
|
+
const retention = retentionOf(state);
|
|
704
|
+
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.');
|
|
705
|
+
const staging = local(root, `.cyc/runs/${updateRun}/context-staging`);
|
|
536
706
|
const written = [];
|
|
537
707
|
for (const proposal of proposals) {
|
|
538
708
|
for (const component of proposal.components) {
|
|
@@ -542,7 +712,7 @@ export function reviewContext(root, { run, since, all = false, write = false, ne
|
|
|
542
712
|
const blocking = parsed.issues.filter(i => ['sections', 'last-change', 'title'].includes(i.rule));
|
|
543
713
|
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
714
|
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 }));
|
|
715
|
+
atomicWrite(local(root, component.doc), applyEntry(source, { entry: component.entry, lessons: component.lessons, lastChange }), staging);
|
|
546
716
|
recorded.set(proposal.runId, [...(recorded.get(proposal.runId) ?? []), component.doc]);
|
|
547
717
|
written.push({ doc: component.doc, runId: proposal.runId, written: true });
|
|
548
718
|
}
|
|
@@ -551,17 +721,19 @@ export function reviewContext(root, { run, since, all = false, write = false, ne
|
|
|
551
721
|
const title = newDoc.split('-').map((w, i) => i ? w : w[0].toUpperCase() + w.slice(1)).join(' ');
|
|
552
722
|
const source = existsSync(local(root, path)) ? read(root, path) : newDocSource(title, covers);
|
|
553
723
|
if (parseDoc(source, `${newDoc}.md`).history.some(e => e.run === proposal.runId)) continue;
|
|
554
|
-
|
|
724
|
+
mkdirSync(dirname(local(root, path)), { recursive: true });
|
|
725
|
+
atomicWrite(local(root, path), applyEntry(source, { entry, lessons, lastChange: `Last changed by AI: ${proposal.date} · run ${proposal.runId} · files: ${covers.join(', ')}` }), staging);
|
|
555
726
|
written.push({ doc: path, runId: proposal.runId, written: true, created: !proposal.newDoc.exists });
|
|
556
727
|
}
|
|
557
728
|
}
|
|
558
729
|
let index = null;
|
|
559
730
|
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);
|
|
731
|
+
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); }
|
|
732
|
+
index = refreshIndex(root, { staging });
|
|
562
733
|
}
|
|
563
734
|
const lint = lintContext(root, { git: false });
|
|
564
735
|
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 })) } };
|
|
736
|
+
});
|
|
565
737
|
}
|
|
566
738
|
|
|
567
739
|
// ---------------------------------------------------------------- measure: what the index path costs
|
|
@@ -571,6 +743,7 @@ const tokensEstimate = chars => Math.round(chars / 4);
|
|
|
571
743
|
|
|
572
744
|
export function measureContext(root, { paths = [], run } = {}) {
|
|
573
745
|
root = realpathSync(root);
|
|
746
|
+
const { folder: contextFolder, index: indexName } = contextLocation(root);
|
|
574
747
|
if (!Array.isArray(paths)) throw Error('Paths must be an array.');
|
|
575
748
|
const { exists, components } = componentsOf(root);
|
|
576
749
|
if (!exists) throw Error(`${indexName} does not exist; nothing to measure.`);
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { relative, resolve, isAbsolute, sep } from 'node:path';
|
|
3
|
+
import { digest } from './response-gate.mjs';
|
|
4
|
+
|
|
5
|
+
export const executionModes = ['native-codex', 'native-claude', 'cursor', 'standalone'];
|
|
6
|
+
export const conversationIdentity = (env = process.env) => [env.CYC_SESSION, env.CLAUDE_CODE_SESSION_ID, env.CODEX_THREAD_ID].find(v => /^[A-Za-z0-9_-]{4,80}$/.test(v ?? ''));
|
|
7
|
+
function setup(message) {
|
|
8
|
+
const error = new Error(message);
|
|
9
|
+
error.setup = { action: 'select-execution', modes: executionModes, instruction: 'Supply executionMode (CLI --mode) and the real conversationId when known; standalone is explicit no-hook work and cannot downgrade a live native request.' };
|
|
10
|
+
throw error;
|
|
11
|
+
}
|
|
12
|
+
export function resolveExecution(root, { executionMode, conversationId, session } = {}, env = process.env) {
|
|
13
|
+
if (executionMode !== undefined && !executionModes.includes(executionMode)) setup(`Unknown executionMode ${executionMode}.`);
|
|
14
|
+
const caller = conversationIdentity(env);
|
|
15
|
+
for (const value of [conversationId, session]) if (value !== undefined && !/^[A-Za-z0-9_-]{4,80}$/.test(value)) setup('Session must be 4-80 letters, digits, underscores or dashes; conversationId uses the same safe identity shape.');
|
|
16
|
+
const native = id => {
|
|
17
|
+
if (!id) return null;
|
|
18
|
+
for (const host of ['codex', 'claude', 'cursor']) {
|
|
19
|
+
const key = /^[a-f0-9]{32}$/.test(id) ? id : digest(`${host}:${id}`).slice(0, 32);
|
|
20
|
+
const path = resolve(root, '.cyc/runtime', `${key}.state.json`);
|
|
21
|
+
if (existsSync(path)) {
|
|
22
|
+
const state = JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, ''));
|
|
23
|
+
const observedHost = state.host ?? state.activation?.host;
|
|
24
|
+
if (observedHost && observedHost !== host) continue;
|
|
25
|
+
return { mode: host === 'cursor' ? 'cursor' : `native-${host}`, gateSession: key };
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return null;
|
|
29
|
+
};
|
|
30
|
+
const active = native(caller);
|
|
31
|
+
if (active && executionMode && executionMode !== active.mode) setup(`Active ${active.mode} request cannot use ${executionMode}.`);
|
|
32
|
+
if (active && conversationId && conversationId !== caller && native(conversationId)?.gateSession !== active.gateSession) setup('conversationId does not identify the active native request.');
|
|
33
|
+
const identity = conversationId ?? caller;
|
|
34
|
+
const observed = active ?? native(conversationId) ?? native(session) ?? native(caller);
|
|
35
|
+
if (observed && executionMode === 'standalone') setup(`Active ${observed.mode} context cannot use standalone.`);
|
|
36
|
+
const mode = executionMode ?? observed?.mode;
|
|
37
|
+
if (!mode) setup(/^[a-f0-9]{32}$/.test(session ?? '') ? `No hook state for session ${session}. Provide the current native context or choose an explicitly authorized execution mode.` : 'Execution capability is unknown; choose --mode standalone for explicitly authorized no-hook work, or provide the current native context.');
|
|
38
|
+
if (mode.startsWith('native-') && (!observed || observed.mode !== mode)) setup(`${mode} needs current native hook state for the supplied conversationId/session. Reload the host and use its injected context.`);
|
|
39
|
+
return { mode, conversationId: identity ?? null, workflowSession: session ?? null, gateSession: observed?.gateSession ?? null, hookActivation: 'unverified' };
|
|
40
|
+
}
|
|
41
|
+
export function artifactFiles(root, paths, label = 'Artifact') {
|
|
42
|
+
return paths.map(path => {
|
|
43
|
+
if (typeof path !== 'string' || !path) throw new Error(`${label} needs a regular-file path.`);
|
|
44
|
+
const absolute = resolve(root, path), realRoot = realpathSync(root);
|
|
45
|
+
const inside = target => { const rel = relative(realRoot, target); return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel); };
|
|
46
|
+
if (!inside(absolute)) throw new Error(`${label} leaves project: ${path}`);
|
|
47
|
+
const info = lstatSync(absolute);
|
|
48
|
+
if (!info.isFile() || !inside(realpathSync(absolute))) throw new Error(`${label} ${path} must be a regular file; directories are not expanded. List concrete files individually.`);
|
|
49
|
+
return { path, sha256: digest(readFileSync(absolute)) };
|
|
50
|
+
});
|
|
51
|
+
}
|
package/scripts/packet.mjs
CHANGED
|
@@ -3,16 +3,20 @@ import { randomUUID } from 'node:crypto';
|
|
|
3
3
|
import { dirname, resolve } from 'node:path';
|
|
4
4
|
import { checkPacket, checkResponse, digest, normalize } from './response-gate.mjs';
|
|
5
5
|
import { advisoryReason, blockingRuns, checkRuns, validateRequestWindow } from './run-gate.mjs';
|
|
6
|
+
import { resolveExecution, artifactFiles } from './execution.mjs';
|
|
6
7
|
|
|
7
8
|
// Write the delivery review packet for this session and run the same check the Stop hook runs,
|
|
8
9
|
// so a review that would be bounced is caught before the turn ends. The token comes from the
|
|
9
10
|
// session's own hook state; the agent never copies it. Claude and Codex Stop events carry the
|
|
10
11
|
// final reply, so the reply file is optional there: without it the gate checks the reply itself.
|
|
11
|
-
export function writePacket(root, { session, responseFile, status, blocker, advisory, passed = [], unmet = [], artifacts = [], reviewed = false }) {
|
|
12
|
+
export function writePacket(root, { session, executionMode, conversationId, responseFile, status, blocker, advisory, passed = [], unmet = [], artifacts = [], reviewed = false }) {
|
|
12
13
|
if (!session) throw new Error('--session is required: use the CYC session ID from the gate context (Cursor: your session tag).');
|
|
13
14
|
if (status !== undefined && !['ready', 'blocked'].includes(status)) throw new Error('--status must be ready or blocked.');
|
|
14
15
|
const runtime = resolve(root, '.cyc/runtime');
|
|
15
|
-
const
|
|
16
|
+
const execution = resolveExecution(root, { executionMode, conversationId, session });
|
|
17
|
+
if (execution.mode === 'standalone') throw new Error('Standalone delivery is generated by run finish; use --run ID and its delivery record instead of a native packet.');
|
|
18
|
+
const cursor = execution.mode === 'cursor';
|
|
19
|
+
if (!cursor) session = execution.gateSession;
|
|
16
20
|
if (cursor && !/^[a-z0-9-]{4,40}$/.test(session)) throw new Error('Session must be the 32-character CYC session ID or a Cursor tag of 4-40 lowercase letters, digits, or hyphens.');
|
|
17
21
|
// Under project presentation the Stop hook skips CYC's reply checks, so this does too.
|
|
18
22
|
// Cursor still needs the exact reply to find its session's packet.
|
|
@@ -40,6 +44,8 @@ export function writePacket(root, { session, responseFile, status, blocker, advi
|
|
|
40
44
|
if (!criterion?.trim() || !rest.join('::').trim()) throw new Error(`Check "${entry}" must be "criterion :: evidence".`);
|
|
41
45
|
return { criterion: criterion.trim(), result, evidence: rest.join('::').trim() };
|
|
42
46
|
});
|
|
47
|
+
const files = artifactFiles(root, artifacts);
|
|
48
|
+
if (responseFile) artifactFiles(root, [responseFile], 'Response file');
|
|
43
49
|
const response = responseFile ? normalize(readFileSync(resolve(root, responseFile), 'utf8')) : undefined;
|
|
44
50
|
// Without an explicit status the controller's record decides: a run of this request that ended
|
|
45
51
|
// short of complete makes this a blocked handoff, as does a blocker the agent names.
|
|
@@ -52,7 +58,7 @@ export function writePacket(root, { session, responseFile, status, blocker, advi
|
|
|
52
58
|
...(advisory !== undefined ? { advisory: advisory.trim() } : {}),
|
|
53
59
|
checks: [...parse(passed, 'passed'), ...parse(unmet, 'unmet')],
|
|
54
60
|
...(reviewed ? { humanReview: { answersRequest: true, understandable: true, visualAddsInformation: true, limitationsDisclosed: true }, reviewedAt: new Date().toISOString() } : {}),
|
|
55
|
-
artifacts:
|
|
61
|
+
artifacts: files
|
|
56
62
|
};
|
|
57
63
|
const path = resolve(runtime, cursor ? `cursor-${session}.review.json` : `${session}.review.json`);
|
|
58
64
|
publish(path, packet);
|
|
@@ -80,7 +86,16 @@ function publish(path, packet) {
|
|
|
80
86
|
// completed in this request. Cursor finds its packet by the exact reply, so it still uses cyc packet.
|
|
81
87
|
// recorded(packet): whether the run the packet names recorded exactly this packet. An earlier packet
|
|
82
88
|
// is merged only then, so a hand-written one cannot ride along with a genuine finish.
|
|
83
|
-
export function writeRunPacket(root, { session, runId, checks, artifacts, recorded = () => false }) {
|
|
89
|
+
export function writeRunPacket(root, { session, execution, evidence, runId, checks, artifacts, recorded = () => false }) {
|
|
90
|
+
const files = artifactFiles(root, artifacts);
|
|
91
|
+
if (execution?.mode === 'cursor') return { written: false, reason: `Cursor requires the exact reply: packet --mode cursor --session ${execution.workflowSession ?? session} --response FILE --reviewed.` };
|
|
92
|
+
if (execution?.mode === 'standalone') {
|
|
93
|
+
resolveExecution(root, { executionMode: 'standalone', conversationId: execution.conversationId ?? undefined, session: execution.workflowSession ?? undefined });
|
|
94
|
+
const packet = { version: 1, runId, execution, status: 'complete', checks, ...(evidence ? { evidence } : {}), artifacts: files, provenance: 'recorded-workflow-evidence', hookActivation: 'unverified', productReadiness: 'not-certified', writtenAt: new Date().toISOString() };
|
|
95
|
+
const path = `.cyc/runs/${runId}/delivery.json`;
|
|
96
|
+
publish(resolve(root, path), packet);
|
|
97
|
+
return { written: true, path, digest: runPacketDigest(packet), mode: 'standalone', reply: 'Standalone delivery evidence generated. No native packet or hook activation is claimed.' };
|
|
98
|
+
}
|
|
84
99
|
if (!/^[a-f0-9]{32}$/.test(session ?? '')) return { written: false, reason: 'This run has no Claude Code or Codex session; write the review with cyc packet.' };
|
|
85
100
|
const statePath = resolve(root, '.cyc/runtime', `${session}.state.json`);
|
|
86
101
|
if (!existsSync(statePath)) return { written: false, reason: `No hook state for session ${session}; write the review with cyc packet.` };
|
|
@@ -90,11 +105,11 @@ export function writeRunPacket(root, { session, runId, checks, artifacts, record
|
|
|
90
105
|
let earlier = null;
|
|
91
106
|
try { earlier = JSON.parse(readFileSync(path, 'utf8')); } catch { /* none yet */ }
|
|
92
107
|
const kept = earlier?.token === token && earlier.writtenBy === 'run finish' && recorded(earlier) ? earlier : null;
|
|
93
|
-
const files = artifacts.filter(file => { try { return statSync(resolve(root, file)).isFile(); } catch { return false; } });
|
|
94
108
|
const packet = {
|
|
95
109
|
token, status: 'ready', writtenBy: 'run finish', runId, runIds: [...new Set([...(kept?.runIds ?? []), runId])],
|
|
110
|
+
...(evidence ? { evidence } : {}),
|
|
96
111
|
checks: [...(kept?.checks ?? []).filter(check => !checks.some(item => item.criterion === check.criterion)), ...checks],
|
|
97
|
-
artifacts: [...(kept?.artifacts ?? []).filter(item => !files.
|
|
112
|
+
artifacts: [...(kept?.artifacts ?? []).filter(item => !files.some(file => file.path === item.path)), ...files],
|
|
98
113
|
writtenAt: new Date().toISOString()
|
|
99
114
|
};
|
|
100
115
|
publish(path, packet);
|