cyc-stack 0.0.0-stage → 0.6.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/.agents/plugins/marketplace.json +12 -0
- package/.claude-plugin/marketplace.json +14 -0
- package/.claude-plugin/plugin.json +17 -0
- package/.codex-plugin/plugin.json +33 -0
- package/.cursor-plugin/marketplace.json +13 -0
- package/.cursor-plugin/plugin.json +19 -0
- package/INSTALL.md +108 -0
- package/LICENSE +21 -0
- package/README.md +359 -2
- package/bin/cyc.mjs +285 -0
- package/catalog/playbooks.json +20 -0
- package/docs/README.md +30 -0
- package/docs/assets/cyc-method-library.svg +39 -0
- package/docs/assets/cyc-overview.svg +44 -0
- package/docs/assets/cyc-readme-banner-mobile.svg +31 -0
- package/docs/assets/cyc-readme-banner.svg +39 -0
- package/docs/assets/cyc-workflow-diagram.svg +415 -0
- package/docs/code-quality.md +42 -0
- package/docs/context.md +40 -0
- package/docs/cyc-method-map.md +58 -0
- package/docs/cyc-workflow.md +188 -0
- package/docs/engineering/code-standards.md +103 -0
- package/docs/engineering/domain-design.md +81 -0
- package/docs/engineering/failure-handling.md +99 -0
- package/docs/impact-analysis.md +70 -0
- package/docs/installation.md +196 -0
- package/docs/onboarding-recovery.md +75 -0
- package/docs/principles.md +49 -0
- package/docs/project-tools.md +108 -0
- package/docs/response-standard.md +202 -0
- package/docs/runtime.md +247 -0
- package/docs/skill-contract.md +70 -0
- package/docs/skill-craft.md +23 -0
- package/docs/validation.md +39 -0
- package/docs/work-assessments.md +102 -0
- package/hooks/claude.json +10 -0
- package/hooks/codex.json +28 -0
- package/hooks/cursor.json +8 -0
- package/methods/cyc-build/SKILL.md +65 -0
- package/methods/cyc-build/references/file-writes.md +11 -0
- package/methods/cyc-challenge/SKILL.md +48 -0
- package/methods/cyc-context/SKILL.md +76 -0
- package/methods/cyc-context/references/evidence.md +27 -0
- package/methods/cyc-context/references/templates.md +54 -0
- package/methods/cyc-context/scripts/evidence.mjs +61 -0
- package/methods/cyc-correct/SKILL.md +43 -0
- package/methods/cyc-deliver/SKILL.md +52 -0
- package/methods/cyc-design/SKILL.md +50 -0
- package/methods/cyc-design/frontend-design/SKILL.md +43 -0
- package/methods/cyc-design/frontend-design/references/color.md +77 -0
- package/methods/cyc-design/frontend-design/references/craft-rules.md +61 -0
- package/methods/cyc-design/frontend-design/references/decision-sheet.md +110 -0
- package/methods/cyc-design/frontend-design/references/experience-review.md +58 -0
- package/methods/cyc-design/frontend-design/references/generic-tells.md +76 -0
- package/methods/cyc-design/frontend-design/references/layout-archetypes.md +188 -0
- package/methods/cyc-design/frontend-design/references/reference-standards.md +38 -0
- package/methods/cyc-design/frontend-design/references/typography.md +51 -0
- package/methods/cyc-design/frontend-design/references/ux-foundations.md +45 -0
- package/methods/cyc-design/frontend-design/references/visual-material.md +42 -0
- package/methods/cyc-error-ledger/SKILL.md +53 -0
- package/methods/cyc-error-ledger/references/entry-format.md +38 -0
- package/methods/cyc-explore/SKILL.md +41 -0
- package/methods/cyc-frame/SKILL.md +49 -0
- package/methods/cyc-impact/SKILL.md +64 -0
- package/methods/cyc-reflect/SKILL.md +48 -0
- package/methods/cyc-remember/SKILL.md +53 -0
- package/methods/cyc-scout/SKILL.md +67 -0
- package/methods/cyc-setup/SKILL.md +60 -0
- package/methods/cyc-teach/SKILL.md +40 -0
- package/methods/cyc-understand/SKILL.md +40 -0
- package/methods/cyc-understand/references/diagnose.md +53 -0
- package/methods/cyc-verify/SKILL.md +84 -0
- package/methods/cyc-verify/references/recipe.md +53 -0
- package/package.json +93 -4
- package/plugin.json +40 -0
- package/rules/cyc-delivery.mdc +33 -0
- package/scripts/baseline-worker.mjs +10 -0
- package/scripts/catalog.mjs +29 -0
- package/scripts/check-response.mjs +13 -0
- package/scripts/claude-project-hook.mjs +12 -0
- package/scripts/context-review.mjs +600 -0
- package/scripts/host-activation.mjs +66 -0
- package/scripts/install.mjs +387 -0
- package/scripts/onboarding.mjs +110 -0
- package/scripts/packet.mjs +107 -0
- package/scripts/project-tools.mjs +196 -0
- package/scripts/recovery.mjs +66 -0
- package/scripts/response-gate.mjs +105 -0
- package/scripts/response-hook.mjs +237 -0
- package/scripts/response-mode.mjs +12 -0
- package/scripts/run-gate.mjs +264 -0
- package/scripts/runtime.mjs +1723 -0
- package/scripts/source-hash-worker.mjs +5 -0
- package/scripts/source-snapshot.mjs +405 -0
- package/scripts/test-output.mjs +258 -0
- package/scripts/work-review.mjs +257 -0
- package/skills/cyc/SKILL.md +130 -0
- package/skills/cyc/references/playbooks/bug-fix.md +13 -0
- package/skills/cyc/references/playbooks/evaluate.md +13 -0
- package/skills/cyc/references/playbooks/experience.md +7 -0
- package/skills/cyc/references/playbooks/explore.md +9 -0
- package/skills/cyc/references/playbooks/feature.md +14 -0
- package/skills/cyc/references/playbooks/handoff.md +11 -0
- package/skills/cyc/references/playbooks/investigation.md +7 -0
- package/skills/cyc/references/playbooks/performance.md +7 -0
- package/skills/cyc/references/playbooks/plan.md +11 -0
- package/skills/cyc/references/playbooks/refactor.md +12 -0
- package/skills/cyc/references/playbooks/reflect.md +11 -0
- package/skills/cyc/references/playbooks/resume.md +11 -0
- package/skills/cyc/references/playbooks/review.md +9 -0
- package/skills/cyc/references/playbooks/teach.md +11 -0
- package/skills/cyc/references/playbooks/verify.md +7 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { dirname, resolve } from 'node:path';
|
|
4
|
+
import { checkPacket, checkResponse, digest, normalize } from './response-gate.mjs';
|
|
5
|
+
import { advisoryReason, blockingRuns, checkRuns, validateRequestWindow } from './run-gate.mjs';
|
|
6
|
+
|
|
7
|
+
// Write the delivery review packet for this session and run the same check the Stop hook runs,
|
|
8
|
+
// so a review that would be bounced is caught before the turn ends. The token comes from the
|
|
9
|
+
// session's own hook state; the agent never copies it. Claude and Codex Stop events carry the
|
|
10
|
+
// 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
|
+
if (!session) throw new Error('--session is required: use the CYC session ID from the gate context (Cursor: your session tag).');
|
|
13
|
+
if (status !== undefined && !['ready', 'blocked'].includes(status)) throw new Error('--status must be ready or blocked.');
|
|
14
|
+
const runtime = resolve(root, '.cyc/runtime');
|
|
15
|
+
const cursor = !/^[a-f0-9]{32}$/.test(session);
|
|
16
|
+
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
|
+
// Under project presentation the Stop hook skips CYC's reply checks, so this does too.
|
|
18
|
+
// Cursor still needs the exact reply to find its session's packet.
|
|
19
|
+
const configPath = resolve(root, '.cyc/config.json');
|
|
20
|
+
const projectPresentation = existsSync(configPath) && JSON.parse(readFileSync(configPath, 'utf8').replace(/^\uFEFF/, '')).delivery?.presentation === 'project';
|
|
21
|
+
const replyChecks = !projectPresentation;
|
|
22
|
+
if (!responseFile && cursor) throw new Error('Cursor needs --response FILE, the exact final reply, to find this chat\'s packet.');
|
|
23
|
+
if (!reviewed && replyChecks) throw new Error('Pass --reviewed only after rereading the reply you will send: it answers the request, is understandable, its visual adds information, and it discloses limits.');
|
|
24
|
+
if (advisory !== undefined && !advisoryReason({ advisory })) throw new Error('--advisory needs the actual reason no controller run applies to this request\'s changes.');
|
|
25
|
+
let token = 'cursor';
|
|
26
|
+
let expanded = false;
|
|
27
|
+
let since;
|
|
28
|
+
let fingerprint;
|
|
29
|
+
if (!cursor) {
|
|
30
|
+
const statePath = resolve(runtime, `${session}.state.json`);
|
|
31
|
+
if (!existsSync(statePath)) throw new Error(`No hook state for session ${session}. Check the session ID in the gate context.`);
|
|
32
|
+
const state = JSON.parse(readFileSync(statePath, 'utf8'));
|
|
33
|
+
since = validateRequestWindow(state.updatedAt);
|
|
34
|
+
token = state.token;
|
|
35
|
+
expanded = state.characterLimitEnabled === false || state.expanded === true;
|
|
36
|
+
fingerprint = state.sourceFingerprint;
|
|
37
|
+
}
|
|
38
|
+
const parse = (entries, result) => entries.map(entry => {
|
|
39
|
+
const [criterion, ...rest] = entry.split('::');
|
|
40
|
+
if (!criterion?.trim() || !rest.join('::').trim()) throw new Error(`Check "${entry}" must be "criterion :: evidence".`);
|
|
41
|
+
return { criterion: criterion.trim(), result, evidence: rest.join('::').trim() };
|
|
42
|
+
});
|
|
43
|
+
const response = responseFile ? normalize(readFileSync(resolve(root, responseFile), 'utf8')) : undefined;
|
|
44
|
+
// Without an explicit status the controller's record decides: a run of this request that ended
|
|
45
|
+
// short of complete makes this a blocked handoff, as does a blocker the agent names.
|
|
46
|
+
const blocking = cursor ? [] : blockingRuns({ root, since, session });
|
|
47
|
+
status ??= blocker !== undefined || blocking.length ? 'blocked' : 'ready';
|
|
48
|
+
const packet = {
|
|
49
|
+
token, ...(response !== undefined ? { response } : {}), status,
|
|
50
|
+
...(status === 'blocked' && blocker !== undefined ? { blocker } : {}),
|
|
51
|
+
...(status === 'blocked' && blocking.length ? { blockedBy: blocking } : {}),
|
|
52
|
+
...(advisory !== undefined ? { advisory: advisory.trim() } : {}),
|
|
53
|
+
checks: [...parse(passed, 'passed'), ...parse(unmet, 'unmet')],
|
|
54
|
+
...(reviewed ? { humanReview: { answersRequest: true, understandable: true, visualAddsInformation: true, limitationsDisclosed: true }, reviewedAt: new Date().toISOString() } : {}),
|
|
55
|
+
artifacts: artifacts.map(path => ({ path, sha256: digest(readFileSync(resolve(root, path))) }))
|
|
56
|
+
};
|
|
57
|
+
const path = resolve(runtime, cursor ? `cursor-${session}.review.json` : `${session}.review.json`);
|
|
58
|
+
publish(path, packet);
|
|
59
|
+
const review =!replyChecks ? [] : response === undefined ? checkPacket({ packet, token, root }) : checkResponse({ response, packet, token, expanded, root, exactResponse: cursor });
|
|
60
|
+
const issues = [...review, ...(!cursor ? checkRuns({ root, since, packet, session, fingerprint }) : [])];
|
|
61
|
+
return { ok: issues.length === 0, packetPath: path, status, characters: response === undefined ? null : [...response].length,
|
|
62
|
+
...(status === 'blocked' ? { blockedBy: blocking, reply: `Start the reply with "Blocked:" or "Not ready:"${blocker !== undefined ? ` and include this blocker exactly: ${blocker}` : ' and say what stops completion'}.` } : {}),
|
|
63
|
+
...(replyChecks && response === undefined ? { replyChecks: 'at Stop: length, visual, and blocked-handoff prefix are checked on the reply you send; add --response FILE to check length and visual now' } : {}),
|
|
64
|
+
controllerPreflight: cursor ? 'unverified: run readiness with the actual request window' : 'checked for this hook request', issues };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function publish(path, packet) {
|
|
68
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
69
|
+
try { if (lstatSync(path).isSymbolicLink()) throw new Error('CYC review files cannot be symlinks.'); }
|
|
70
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
71
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
72
|
+
writeFileSync(temporary, JSON.stringify(packet, null, 2), { mode: 0o600 });
|
|
73
|
+
renameSync(temporary, path);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// After a completed run finish, Claude Code and Codex need no separate review step: the controller
|
|
77
|
+
// writes the packet from the run's record. It states only what the run recorded, each criterion's
|
|
78
|
+
// evidence and the hashes of the files it changed, and does not claim the agent reread its reply;
|
|
79
|
+
// the Stop gate checks the reply's length, visual and blocked prefix itself, and confirms the run
|
|
80
|
+
// completed in this request. Cursor finds its packet by the exact reply, so it still uses cyc packet.
|
|
81
|
+
// recorded(packet): whether the run the packet names recorded exactly this packet. An earlier packet
|
|
82
|
+
// 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 }) {
|
|
84
|
+
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
|
+
const statePath = resolve(root, '.cyc/runtime', `${session}.state.json`);
|
|
86
|
+
if (!existsSync(statePath)) return { written: false, reason: `No hook state for session ${session}; write the review with cyc packet.` };
|
|
87
|
+
const { token } = JSON.parse(readFileSync(statePath, 'utf8').replace(/^/, ''));
|
|
88
|
+
const path = resolve(root, '.cyc/runtime', `${session}.review.json`);
|
|
89
|
+
// A second run finished in the same request keeps the first run's checks and files.
|
|
90
|
+
let earlier = null;
|
|
91
|
+
try { earlier = JSON.parse(readFileSync(path, 'utf8')); } catch { /* none yet */ }
|
|
92
|
+
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
|
+
const packet = {
|
|
95
|
+
token, status: 'ready', writtenBy: 'run finish', runId, runIds: [...new Set([...(kept?.runIds ?? []), runId])],
|
|
96
|
+
checks: [...(kept?.checks ?? []).filter(check => !checks.some(item => item.criterion === check.criterion)), ...checks],
|
|
97
|
+
artifacts: [...(kept?.artifacts ?? []).filter(item => !files.includes(item.path)), ...files.map(file => ({ path: file, sha256: digest(readFileSync(resolve(root, file))) }))],
|
|
98
|
+
writtenAt: new Date().toISOString()
|
|
99
|
+
};
|
|
100
|
+
publish(path, packet);
|
|
101
|
+
// The run records this digest, and the gate accepts a finish packet only if it matches: a packet
|
|
102
|
+
// that merely claims run finish wrote it does not.
|
|
103
|
+
return { written: true, path: `.cyc/runtime/${session}.review.json`, digest: runPacketDigest(packet), reply: 'The review is written. Do not run cyc packet unless you change files after this finish; the Stop gate checks your reply\'s length and visual.' };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Over the parsed packet, so the gate can check the object it read without the file's bytes.
|
|
107
|
+
export const runPacketDigest = packet => digest(JSON.stringify(packet));
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, relative, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { atomicJSON, configuration, readRun, runCommands, sourceSnapshot } from './runtime.mjs';
|
|
7
|
+
|
|
8
|
+
const registryName = 'docs/context/recipes.json';
|
|
9
|
+
const indexName = 'docs/context/INDEX.md';
|
|
10
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
11
|
+
const text = value => typeof value === 'string' && value.trim().length > 0;
|
|
12
|
+
const helper = fileURLToPath(new URL('../methods/cyc-context/scripts/evidence.mjs', import.meta.url));
|
|
13
|
+
const idPattern = /^[a-z][a-z0-9-]{0,63}$/;
|
|
14
|
+
const recipeKinds = ['investigation', 'verification'];
|
|
15
|
+
|
|
16
|
+
function canonical(path, patterns = false) {
|
|
17
|
+
if (!text(path) || /[\\:\0]/.test(path) || (!patterns && /[*?\[\]{}]/.test(path)) || /[\[\]{}]/.test(path) || path.split('/').some(p => !p || p === '.' || p === '..')) throw Error(`Use canonical project-relative ${patterns ? 'patterns' : 'paths'}: ${path}`);
|
|
18
|
+
return path;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Reject linked ancestors even inside the project: receipts must remain excluded
|
|
22
|
+
// runtime files, and discovery must never follow context links to outside data.
|
|
23
|
+
function local(root, path) {
|
|
24
|
+
canonical(path);
|
|
25
|
+
let current = root;
|
|
26
|
+
for (const part of path.split('/')) {
|
|
27
|
+
current = join(current, part);
|
|
28
|
+
try { if (lstatSync(current).isSymbolicLink()) throw Error(`Linked path is not supported: ${path}`); }
|
|
29
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
30
|
+
}
|
|
31
|
+
return current;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function matches(pattern, path) {
|
|
35
|
+
canonical(pattern, true); canonical(path);
|
|
36
|
+
let regex = '';
|
|
37
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
38
|
+
if (pattern[i] === '*' && pattern[i + 1] === '*') { i++; if (pattern[i + 1] === '/') { i++; regex += '(?:.*/)?'; } else regex += '.*'; }
|
|
39
|
+
else if (pattern[i] === '*') regex += '[^/]*';
|
|
40
|
+
else if (pattern[i] === '?') regex += '[^/]';
|
|
41
|
+
else regex += pattern[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
42
|
+
}
|
|
43
|
+
const prefix = pattern.split(/[?*]/)[0].replace(/\/$/, '');
|
|
44
|
+
return new RegExp(`^${regex}$`).test(path) || (prefix && (prefix === path || prefix.startsWith(path + '/'))) || (!/[?*]/.test(pattern) && path.startsWith(pattern + '/'));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function selection(root, { paths = [], goal = '', run } = {}) {
|
|
48
|
+
if (!Array.isArray(paths)) throw Error('Paths must be an array.');
|
|
49
|
+
if (run) {
|
|
50
|
+
const state = readRun(root, run);
|
|
51
|
+
goal ||= state.goal;
|
|
52
|
+
if (!paths.length) {
|
|
53
|
+
const now = sourceSnapshot(root).files;
|
|
54
|
+
const before = state.initialSource?.files ?? {};
|
|
55
|
+
paths = [...new Set([...Object.keys(before), ...Object.keys(now)])].filter(p => before[p] !== now[p]);
|
|
56
|
+
if (!paths.length) paths = state.allowedPaths ?? [];
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
paths = [...new Set(paths.map(p => canonical(p)))];
|
|
60
|
+
const words = String(goal).toLowerCase().match(/[a-z0-9-]{3,}/g)?.filter(w => !['the', 'and', 'for', 'with', 'this', 'that', 'add', 'fix', 'change'].includes(w)) ?? [];
|
|
61
|
+
return { paths, goal, relevant: (covers, description) => paths.length ? covers.some(p => paths.some(path => matches(p, path))) : words.some(w => description.toLowerCase().includes(w)) };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function registry(root) {
|
|
65
|
+
const path = local(root, registryName);
|
|
66
|
+
if (!existsSync(path)) return { present: false, recipes: [], hash: null };
|
|
67
|
+
const bytes = readFileSync(path), document = JSON.parse(bytes.toString('utf8').replace(/^\uFEFF/, ''));
|
|
68
|
+
if (document?.schemaVersion !== 1 || !Array.isArray(document.recipes)) throw Error('Recipe registry needs schemaVersion 1 and a recipes array.');
|
|
69
|
+
const ids = new Set();
|
|
70
|
+
for (const recipe of document.recipes) {
|
|
71
|
+
if (!recipe || !idPattern.test(recipe.id ?? '') || ids.has(recipe.id) || !recipeKinds.includes(recipe.kind) || !text(recipe.description) || !text(recipe.expected) || !text(recipe.effects) || !text(recipe.command) || !Array.isArray(recipe.args) || recipe.args.some(a => typeof a !== 'string') || !Array.isArray(recipe.covers) || !recipe.covers.length || !Array.isArray(recipe.references) || !recipe.references.length || !Array.isArray(recipe.prerequisites) || recipe.prerequisites.some(p => !text(p))) throw Error('Each recipe needs a unique id, kind, description, covers, command/args, expected result, effects, prerequisites, and existing references.');
|
|
72
|
+
ids.add(recipe.id);
|
|
73
|
+
if (recipe.command.includes('\0') || recipe.args.some(arg => arg.includes('\0'))) throw Error('Recipe command/args cannot contain null bytes.');
|
|
74
|
+
recipe.covers.forEach(p => canonical(p, true));
|
|
75
|
+
for (const name of recipe.references) if (!lstatSync(local(root, name)).isFile()) throw Error(`Recipe reference is not a regular file: ${name}`);
|
|
76
|
+
if (recipe.timeoutMs !== undefined && (!Number.isSafeInteger(recipe.timeoutMs) || recipe.timeoutMs <= 0 || recipe.timeoutMs > 2147483647)) throw Error('Recipe timeoutMs must be between 1 and 2147483647.');
|
|
77
|
+
}
|
|
78
|
+
return { present: true, recipes: document.recipes, hash: hash(bytes) };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function receiptStatus(root, recipe, loaded, environment) {
|
|
82
|
+
const folder = local(root, `.cyc/runtime/recipes/${recipe.id}`);
|
|
83
|
+
if (!existsSync(folder)) return { status: 'unverified' };
|
|
84
|
+
const names = readdirSync(folder).filter(p => /^\d+-[a-f0-9-]+\.json$/.test(p)).sort();
|
|
85
|
+
if (!names.length) return { status: 'unverified' };
|
|
86
|
+
const receiptPath = `.cyc/runtime/recipes/${recipe.id}/${names.at(-1)}`;
|
|
87
|
+
try {
|
|
88
|
+
const receipt = JSON.parse(readFileSync(local(root, receiptPath), 'utf8'));
|
|
89
|
+
const result = receipt.results?.[0];
|
|
90
|
+
const current = environment();
|
|
91
|
+
if (receipt.schemaVersion !== 1 || receipt.recipeHash !== hash(JSON.stringify(recipe)) || receipt.registryHash !== loaded.hash || receipt.sourceHash !== current.sourceHash || receipt.configHash !== current.configHash) return { status: 'stale', receiptPath };
|
|
92
|
+
const passed = receipt.passed === true && receipt.sourceStable === true && receipt.definitionStable === true && receipt.configStable === true && receipt.results.length === 1 && result.id === recipe.id && result.command === recipe.command && JSON.stringify(result.args) === JSON.stringify(recipe.args) && result.passed === true && result.exitCode === 0 && !result.error;
|
|
93
|
+
return { status: passed ? 'passed' : 'failed', receiptPath, checkedAt: receipt.checkedAt };
|
|
94
|
+
} catch { return { status: 'invalid', receiptPath }; }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function configHash(root) {
|
|
98
|
+
const path = local(root, '.cyc/config.json');
|
|
99
|
+
return existsSync(path) ? hash(readFileSync(path)) : null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function recipesFor(root, options, selected, kind) {
|
|
103
|
+
const loaded = registry(root);
|
|
104
|
+
const state = options.run ? readRun(root, options.run) : null;
|
|
105
|
+
const required = state ? (state.requiresChecks ? state.commands : []) : configuration(root).commands;
|
|
106
|
+
let current;
|
|
107
|
+
const environment = () => current ??= { sourceHash: sourceSnapshot(root).hash, configHash: configHash(root) };
|
|
108
|
+
return { ok: true, registry: registryName, available: loaded.present, paths: selected.paths,
|
|
109
|
+
recipes: loaded.recipes.filter(r => (kind === undefined || r.kind === kind) && (options.all || selected.relevant(r.covers, `${r.id} ${r.description}`))).map(recipe => ({ ...recipe, configuredCommandIds: required.filter(c => c.command === recipe.command && JSON.stringify(c.args) === JSON.stringify(recipe.args)).map(c => c.id), receipt: receiptStatus(root, recipe, loaded, environment) })),
|
|
110
|
+
note: 'Discovery executes no project commands. Receipts are local diagnostic history, not task completion or current external-service proof.' };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function validateRecipeKind(kind) {
|
|
114
|
+
if (kind !== undefined && !recipeKinds.includes(kind)) throw Error('Recipe kind must be investigation or verification.');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function listRecipes(target, options = {}) {
|
|
118
|
+
validateRecipeKind(options.kind);
|
|
119
|
+
const root = realpathSync(target);
|
|
120
|
+
return recipesFor(root, options, selection(root, options), options.kind);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Discovery and context measurement must interpret the same local document links.
|
|
124
|
+
export function contextLinks(cell) {
|
|
125
|
+
return [...cell.matchAll(/\[[^\]]+\]\(([^)]+)\)/g)].map(match => {
|
|
126
|
+
const link = match[1].split('#')[0];
|
|
127
|
+
return !link || /^[a-z]+:/i.test(link) ? null : decodeURIComponent(link);
|
|
128
|
+
}).filter(Boolean);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function investigateProject(target, options = {}) {
|
|
132
|
+
validateRecipeKind(options.kind);
|
|
133
|
+
const root = realpathSync(target), selected = selection(root, options), limit = options.limit ?? 8;
|
|
134
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 50) throw Error('Limit must be between 1 and 50.');
|
|
135
|
+
if (!selected.paths.length && !text(selected.goal)) throw Error('Provide affected --path values, a --goal, or a --run.');
|
|
136
|
+
const index = local(root, indexName), warnings = [], found = [];
|
|
137
|
+
const links = cell => contextLinks(cell).map(link => {
|
|
138
|
+
const name = relative(root, resolve(dirname(index), link)).replaceAll('\\', '/');
|
|
139
|
+
return { path: name, exists: existsSync(local(root, name)) };
|
|
140
|
+
});
|
|
141
|
+
if (existsSync(index)) {
|
|
142
|
+
let header;
|
|
143
|
+
for (const line of readFileSync(index, 'utf8').split(/\r?\n/)) {
|
|
144
|
+
if (!/^\s*\|/.test(line)) { header = undefined; continue; }
|
|
145
|
+
const cells = line.trim().replace(/^\||\|$/g, '').split(/(?<!\\)\|/).map(c => c.trim().replaceAll('\\|', '|'));
|
|
146
|
+
if (cells.some(c => c.toLowerCase() === 'covers')) { header = cells.map(c => c.toLowerCase()); continue; }
|
|
147
|
+
if (!header || cells.every(c => /^:?-+:?$/.test(c))) continue;
|
|
148
|
+
if (cells.length !== header.length) { warnings.push('Skipped a malformed index row.'); continue; }
|
|
149
|
+
const covers = cells[header.indexOf('covers')].replaceAll('`', '').split(',').map(p => p.trim());
|
|
150
|
+
try {
|
|
151
|
+
covers.forEach(p => canonical(p === 'all' ? '**' : p, true));
|
|
152
|
+
if (!selected.relevant(covers.map(p => p === 'all' ? '**' : p), cells.join(' '))) continue;
|
|
153
|
+
found.push({ area: cells[0], covers, records: links(cells[header.indexOf('record') >= 0 ? header.indexOf('record') : header.indexOf('doc')]), evidence: header.includes('evidence') ? links(cells[header.indexOf('evidence')]) : [] });
|
|
154
|
+
} catch (error) { warnings.push(error.message); }
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const evidenceChecks = new Map();
|
|
158
|
+
const contexts = found.slice(0, limit).map(entry => ({ ...entry, evidence: entry.evidence.map(e => {
|
|
159
|
+
if (!e.exists || !e.path.endsWith('.json')) return e;
|
|
160
|
+
if (!evidenceChecks.has(e.path)) {
|
|
161
|
+
const checked = spawnSync(process.execPath, [helper, 'check', '--project', root, '--manifest', e.path], { encoding: 'utf8', windowsHide: true, timeout: 10000, maxBuffer: 1024 * 1024 });
|
|
162
|
+
try {
|
|
163
|
+
const result = JSON.parse(checked.stdout);
|
|
164
|
+
const drift = result.files?.filter(file => file.status !== 'unchanged');
|
|
165
|
+
evidenceChecks.set(e.path, drift ? { ...result, checkedFiles: result.files.length, files: drift.slice(0, limit), driftCount: drift.length, truncated: drift.length > limit } : result);
|
|
166
|
+
} catch { evidenceChecks.set(e.path, { status: 'invalid', error: checked.error?.message ?? 'Evidence helper returned no usable result.' }); }
|
|
167
|
+
}
|
|
168
|
+
return { ...e, check: evidenceChecks.get(e.path) };
|
|
169
|
+
}) }));
|
|
170
|
+
const recipes = recipesFor(root, options, selected, options.kind);
|
|
171
|
+
return { ok: true, projectRoot: root, paths: selected.paths, selection: selected.paths.length ? 'declared path matches' : 'goal words; confirm relevance', index: { path: indexName, exists: existsSync(index) }, contexts, totalContextMatches: found.length, truncated: found.length > limit, recipes: recipes.recipes.slice(0, limit), totalRecipeMatches: recipes.recipes.length, recipesTruncated: recipes.recipes.length > limit, recipeRegistryAvailable: recipes.available, warnings,
|
|
172
|
+
note: 'Paths and records are leads, not an exhaustive dependency map. Read matched records and inspect current consumers. Matching bytes do not establish semantic correctness. Project commands were not executed.' };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function runRecipe(target, id, { run } = {}) {
|
|
176
|
+
const root = realpathSync(target), loaded = registry(root), recipe = loaded.recipes.find(r => r.id === id);
|
|
177
|
+
if (!recipe) throw Error(`Unknown recipe: ${id}`);
|
|
178
|
+
if (run && readRun(root, run).status !== 'running') throw Error('Recipe execution associated with a run needs that run to be running.');
|
|
179
|
+
local(root, `.cyc/runtime/recipes/${id}`); // Validate receipt ancestors before execution.
|
|
180
|
+
const before = sourceSnapshot(root), configBefore = configHash(root);
|
|
181
|
+
if (before.skipped.length) throw Error('Recipe verification cannot cover linked source; inspect the links first.');
|
|
182
|
+
const results = runCommands(root, [recipe]);
|
|
183
|
+
let after, inspectionError, configAfter;
|
|
184
|
+
try { configAfter = configHash(root); after = sourceSnapshot(root); }
|
|
185
|
+
catch (error) { inspectionError = error.message; }
|
|
186
|
+
let definitionStable = false;
|
|
187
|
+
try { definitionStable = registry(root).hash === loaded.hash; } catch { /* preserve a failed receipt */ }
|
|
188
|
+
const configStable = !inspectionError && configAfter === configBefore;
|
|
189
|
+
const sourceStable = !!after && before.hash === after.hash && !after.skipped.length;
|
|
190
|
+
const receipt = { schemaVersion: 1, recipe: id, kind: recipe.kind, runId: run ?? null, checkedAt: new Date().toISOString(), registryHash: loaded.hash, recipeHash: hash(JSON.stringify(recipe)), sourceHash: after?.hash ?? null, configHash: configAfter ?? null, inspectionError, sourceStable, definitionStable, configStable,
|
|
191
|
+
passed: sourceStable && definitionStable && configStable && results.length === 1 && results.every(r => r.passed), results };
|
|
192
|
+
const receiptPath = `.cyc/runtime/recipes/${id}/${Date.now()}-${randomUUID()}.json`;
|
|
193
|
+
atomicJSON(local(root, receiptPath), receipt);
|
|
194
|
+
return { ok: receipt.passed, ...receipt, receiptPath, expected: recipe.expected,
|
|
195
|
+
note: 'Command results and source stability are diagnostic evidence. Interpret the expected behavior; run required controller verification and test proof separately.' };
|
|
196
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Presentation only: the controller owns transitions and completion decisions.
|
|
2
|
+
// Historical observations must never be promoted to current verification here.
|
|
3
|
+
export function recoveryGuidance(state, { sourceHash, guardIssues, inspectionError, lastCheck, engineVersion, workspaceOperation }) {
|
|
4
|
+
const stage = state.stages[state.stageIndex] ?? null;
|
|
5
|
+
const issues = guardIssues.protectedChanges.length || guardIssues.outOfScope.length;
|
|
6
|
+
const expired = Boolean(state.limits.maxDurationMs && Date.now() - Date.parse(state.startedAt) >= state.limits.maxDurationMs);
|
|
7
|
+
const exhausted = state.failures >= state.limits.maxAttempts || state.noProgress >= state.limits.maxNoProgress || expired;
|
|
8
|
+
const engineChanged = Boolean(state.engineVersion && state.engineVersion !== engineVersion);
|
|
9
|
+
const activeEvidence = state.status === 'complete' || (state.status === 'running' && !exhausted);
|
|
10
|
+
const current = Boolean(activeEvidence && !inspectionError && !issues && !engineChanged && state.verification?.passed && state.verification.sourceHash === sourceHash);
|
|
11
|
+
const lastEvent = state.history.findLast(item => ['attempt-failed', 'retry', 'blocked', 'guard-halt', 'exhausted', 'pause', 'resume', 'stop'].includes(item.type));
|
|
12
|
+
const verificationStatus = !state.requiresChecks ? 'not-required' : workspaceOperation ? 'unverified' : current ? 'passed' : activeEvidence && state.verification?.passed ? 'stale' : 'unverified';
|
|
13
|
+
const staleHandoffs = sourceHash ? ['verify', 'deliver'].filter(name => {
|
|
14
|
+
const handoff = state.handoffs.findLast(item => item.stage === name && item.status === 'passed');
|
|
15
|
+
return handoff && handoff.sourceHash !== sourceHash;
|
|
16
|
+
}) : [];
|
|
17
|
+
let nextAction;
|
|
18
|
+
const action = (kind, instruction) => { nextAction = { kind, instruction }; };
|
|
19
|
+
if (workspaceOperation?.publicationFailure) action('inspect-operation-commit',
|
|
20
|
+
`A controller outcome could not be published (${workspaceOperation.publicationFailure.stateCommitted ? 'run state was saved; generated review may be stale' : 'run state was not saved; earlier passing fields are not current evidence'}): ${workspaceOperation.publicationFailure.reason}. Preserve both locks and current files${workspaceOperation.backupPath ? ` plus candidate backup at ${workspaceOperation.backupPath}` : ''}. Confirm the owning operation stopped, inspect the retained record/manifest, compare and merge deliberately before operator cleanup. Do not trust an old review, resume automatically or reset the budget.`);
|
|
21
|
+
else if (state.status === 'halted' && state.proofRecovery) action('inspect-proof-restore',
|
|
22
|
+
`Proof halted after a source conflict or restoration failure. Preserve current files and candidate versions in ${state.proofRecovery.backupPath}. Inspect manifest.json and the listed conflicts, compare and merge deliberately; do not overwrite either version blindly. This run cannot resume or receive an automatic fresh budget.${state.proofRecovery.preservationError ? ` ${state.proofRecovery.preservationError}` : ''}`);
|
|
23
|
+
else if (workspaceOperation) action('wait-workspace',
|
|
24
|
+
`Another CYC operation owns this working folder (${workspaceOperation.operation ?? 'unknown'}${workspaceOperation.pid ? `; PID ${workspaceOperation.pid}` : ''}). Wait for it to finish, then inspect current files again. The next controller operation reclaims ${workspaceOperation.path} only if its process has ended on this machine and it records no commit in progress, test proof or failed publication; any other stale lock requires operator inspection. Do not remove an active lock or treat temporary source as the candidate.${workspaceOperation.reclaimGuard ? ` A reclaim guard at ${workspaceOperation.reclaimGuard.path}${workspaceOperation.reclaimGuard.pid ? ` from PID ${workspaceOperation.reclaimGuard.pid} (${workspaceOperation.reclaimGuard.alive ? 'still running' : 'no longer running'})` : ''} blocks automatic reclaim; once no CYC process is running in this project, remove it.` : ''}${workspaceOperation.backupPath && workspaceOperation.phase !== 'restored' ? ` If inspection confirms the owner stopped, preserve the locks, current files and candidate backup at ${workspaceOperation.backupPath}; read manifest.json, compare and merge deliberately before any lock cleanup. No automatic rollback or budget reset.` : ''}`);
|
|
25
|
+
else if (state.status === 'complete') action('review-complete', 'This run is complete as recorded. Review its evidence against current files; later changes need a separately scoped task, not a reset of this run.');
|
|
26
|
+
else if (['exhausted', 'halted', 'stopped'].includes(state.status) || exhausted) action('review-terminal',
|
|
27
|
+
`${expired ? 'The configured time budget has elapsed.' : 'This run cannot continue within its recorded state or budget.'} Review the existing changes, failure receipt and review document. Explain the unresolved issue and needed decision; do not retry, resume or automatically start a fresh budget.`);
|
|
28
|
+
else if (inspectionError) action('inspect-workspace', `Current source could not be inspected: ${inspectionError} Resolve that inspection problem before advancing.`);
|
|
29
|
+
else if (issues) action('review-guard', 'Protected files or paths outside the agreed scope changed. Inspect those changes with the existing work preserved. Do not automatically undo user edits, alter the scope or resume this run.');
|
|
30
|
+
else if (engineChanged) action('reload-engine', `This run started with CYC ${state.engineVersion}; the current engine is ${engineVersion}. Stop the old run, reload host skills, and explicitly decide how to continue in a new run with the old evidence retained.`);
|
|
31
|
+
else if (state.status === 'blocked') {
|
|
32
|
+
const blocker = state.history.findLast(item => item.type === 'blocked')?.reason ?? state.handoffs.at(-1)?.summary ?? 'The recorded prerequisite remains unresolved.';
|
|
33
|
+
action('resolve-blocker', `${blocker} Once the prerequisite is actually resolved, use run resume for this run and re-establish verification; resuming does not reset its budget.`);
|
|
34
|
+
} else if (state.status === 'paused') action('resume', 'Compare the retained checkpoint and current diff, preserving edits. When continuing this task, use run resume for this run. It retains the failure budget and invalidates previous verification.');
|
|
35
|
+
else if (state.requiresChecks && !state.commands.length) action('configure-checks', 'This run captured no verification commands. Preserve and stop it, inspect the project checks through onboarding, and configure approved commands before explicitly starting a new run. Do not change configuration beneath this run or invent a passing check.');
|
|
36
|
+
else if (staleHandoffs.length) action('refresh-review', `The recorded ${staleHandoffs.join(' and ')} handoff no longer matches current source. Retry the affected review stage with a reason, rerun applicable checks and refresh the handoff before completion. Passing commands alone do not refresh a stale review.`);
|
|
37
|
+
else if (lastCheck?.sourceStable === false && !state.verification && lastEvent?.type !== 'resume') action('inspect-source-change',
|
|
38
|
+
'Configured checks changed covered project files. Inspect changedPaths in the retained receipt, finalize intended generated files, and select a non-mutating verification approach through the normal project configuration process. Do not count passing command exits as verification of a stable candidate.');
|
|
39
|
+
else if (lastCheck && lastCheck.status !== 'passed' && !state.verification && lastEvent?.type !== 'resume') {
|
|
40
|
+
const failed = lastCheck.failedChecks ?? [];
|
|
41
|
+
const missing = failed.filter(check => check.errorCode === 'ENOENT');
|
|
42
|
+
const timedOut = failed.filter(check => check.errorCode === 'ETIMEDOUT');
|
|
43
|
+
action('inspect-check', missing.length ? `The executable could not be started for: ${missing.map(item => item.id).join(', ')}. Inspect the recorded executable and project setup instructions; do not infer a product defect or invent a replacement command.`
|
|
44
|
+
: timedOut.length ? `Checks timed out: ${timedOut.map(item => item.id).join(', ')}. Inspect the receipt and the expected service or workload before changing a timeout or retrying.`
|
|
45
|
+
: 'Inspect the last check receipt and reproduce the failure. Separate the observed result from its suspected cause; repair within scope or name the missing prerequisite. Do not classify an ordinary failing exit as an environment problem without evidence.');
|
|
46
|
+
} else if (lastEvent?.type === 'attempt-failed' && state.handoffs.at(-1)?.status === 'failed') action('inspect-failure',
|
|
47
|
+
`Inspect the failed ${state.handoffs.at(-1).stage} handoff: ${state.handoffs.at(-1).summary} Use its recorded evidence to choose the next hypothesis before retrying; retain the shared failure budget.`);
|
|
48
|
+
else if (state.requiresChecks && !current && ['verify', 'deliver', null].includes(stage)) action('verify',
|
|
49
|
+
'Current files do not have passing executable evidence. If a Verify handoff already passed, retry the affected stage with a reason first; then run verification and refresh the semantic review. Preserve the existing failure budget.');
|
|
50
|
+
else action('continue', stage ? `Continue the ${stage} stage with the original criteria. Inspect the existing handoff and current diff before editing; a stage result is not task completion.` : 'All stages are recorded. Use run complete to let the controller check freshness and completion conditions.');
|
|
51
|
+
return {
|
|
52
|
+
runId: state.id, status: state.status, goal: state.goal, stage, criteria: state.criteria,
|
|
53
|
+
remainingAttempts: Math.max(0, state.limits.maxAttempts - state.failures),
|
|
54
|
+
remainingUnchangedFailures: Math.max(0, state.limits.maxNoProgress - state.noProgress),
|
|
55
|
+
expired, engineChanged, guardIssues, staleHandoffs, inspectionError: inspectionError ?? null,
|
|
56
|
+
verification: { status: verificationStatus, detail: current ? 'Configured commands passed on current covered source; task criteria and semantic review still govern completion.' : 'Historical results are retained for diagnosis, not current completion evidence.' },
|
|
57
|
+
lastCheck, lastEvent: lastEvent ?? null,
|
|
58
|
+
...(state.proofRecovery ? { proofRecovery: state.proofRecovery } : {}),
|
|
59
|
+
...(workspaceOperation ? { workspaceOperation } : {}),
|
|
60
|
+
previousHandoff: state.handoffs.at(-1) ? { stage: state.handoffs.at(-1).stage, status: state.handoffs.at(-1).status, summary: state.handoffs.at(-1).summary, nextAction: state.handoffs.at(-1).nextAction } : null,
|
|
61
|
+
reviewPath: `.cyc/runs/${state.id}/review.md`,
|
|
62
|
+
acceptedFailures: state.acceptedFailures ?? [],
|
|
63
|
+
preservation: 'Recovery inspection changed no source files, run state, receipts or budgets. Existing files remain in place; this is not a backup or a claim that earlier commands had no side effects.',
|
|
64
|
+
nextAction
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFileSync, realpathSync, statSync } from 'node:fs';
|
|
3
|
+
import { isAbsolute, relative, resolve } from 'node:path';
|
|
4
|
+
|
|
5
|
+
// The reply and its packet copy are compared after the same normalization: line endings and the
|
|
6
|
+
// trailing whitespace a host or an editor adds, which carry no content.
|
|
7
|
+
export const normalize = text => text.replace(/\r\n/g, '\n').replace(/\s+$/, '');
|
|
8
|
+
export const digest = value => createHash('sha256').update(value).digest('hex');
|
|
9
|
+
const nonempty = value => typeof value === 'string' && value.trim().length > 0;
|
|
10
|
+
|
|
11
|
+
// The forms the gate recognizes, named in the correction so an agent picks one instead of guessing.
|
|
12
|
+
export const visualForms = 'a Markdown table, a mermaid block, an image with alternative text, or a labeled arrow flow of three or more steps (A → B → C; inside a fenced block also with ->, --> or ──►)';
|
|
13
|
+
|
|
14
|
+
export function hasVisual(text) {
|
|
15
|
+
// Structure detection only. Meaning and accurate rendering need review.
|
|
16
|
+
const table = /^\|[^\n]+\|\s*\n\|(?:\s*:?-{3,}:?\s*\|){2,}\s*\n\|[^\n]+\|/m;
|
|
17
|
+
const diagram = /```mermaid\s*\n(?:flowchart|graph|sequenceDiagram|stateDiagram|classDiagram|erDiagram|gantt|pie|timeline)[\s\S]+?\n```/;
|
|
18
|
+
const picture = /!\[[^\]\n]+\]\((?:<[^>\n]+>|[^)\n]+)\)/;
|
|
19
|
+
// A flow is three or more labeled steps; two words joined by an arrow is a phrase, not a diagram.
|
|
20
|
+
const flow = /^\s*[^\n→]{2,60}\s+→\s+[^\n→]{2,60}(?:\s+→\s+[^\n→]{2,60})+\s*$/m;
|
|
21
|
+
// Inside a fenced block the same shape may be drawn with ->, --> or ──►, which the correction once asked for and the gate refused.
|
|
22
|
+
const fencedFlow = /^[ \t]*[^\s][^\n]{0,58}?[ \t]+(?:->|-->|──►|→)[ \t]+[^\s][^\n]{0,58}?(?:[ \t]+(?:->|-->|──►|→)[ \t]+[^\s][^\n]{0,58}?)+[ \t]*$/m;
|
|
23
|
+
const fenced = [...text.matchAll(/```([^\n]*)\n([\s\S]*?)\n[ \t]*```/g)].some(([, info, body]) => !/^mermaid\b/.test(info.trim()) && fencedFlow.test(body));
|
|
24
|
+
return table.test(text) || diagram.test(text) || picture.test(text) || flow.test(text) || fenced;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// The reply's own checks, the same ones the Stop gate applies, on a draft: stateless, so an agent can
|
|
28
|
+
// run them before sending instead of learning the count from a rejection. Says how much to cut,
|
|
29
|
+
// because an agent cannot count its own reply and round 8's overshoots were all small.
|
|
30
|
+
export function checkReply(text, { expanded = false } = {}) {
|
|
31
|
+
const normalized = normalize(String(text ?? ''));
|
|
32
|
+
const characters = [...normalized].length;
|
|
33
|
+
const overBy = expanded ? 0 : Math.max(0, characters - 1000);
|
|
34
|
+
const visual = hasVisual(normalized);
|
|
35
|
+
const issues = [];
|
|
36
|
+
if (overBy > 0) issues.push(`Response has ${characters} characters; maximum is 1000: cut at least ${overBy}. Put detail in an artifact or wait for an expansion request.`);
|
|
37
|
+
if (!visual) issues.push(`Include one compact relevant visual: ${visualForms}.`);
|
|
38
|
+
return { characters, overBy, visual, issues };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// The gate checks the reply it actually received. A packet that copies the reply must match it
|
|
42
|
+
// exactly; `exactResponse` requires the copy (Cursor finds a session's packet by its text).
|
|
43
|
+
export function checkResponse({ response, packet, token, expanded = false, root, exactResponse = false }) {
|
|
44
|
+
const issues = [];
|
|
45
|
+
if (!nonempty(response)) return ['The final response is missing.'];
|
|
46
|
+
const text = normalize(response);
|
|
47
|
+
issues.push(...checkReply(text, { expanded }).issues);
|
|
48
|
+
if (!packet || typeof packet !== 'object') return [...issues, 'Write the session review packet before completion.'];
|
|
49
|
+
if ((exactResponse || packet.response !== undefined) && (typeof packet.response !== 'string' || normalize(packet.response) !== text)) issues.push('The review must cover the exact final response.');
|
|
50
|
+
return [...issues, ...checkPacket({ packet, token, root, text })];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Checks of the review itself. Without the reply text (a preflight before the reply is sent),
|
|
54
|
+
// the blocked-handoff prefix is left to the Stop gate, which has the reply.
|
|
55
|
+
export function checkPacket({ packet, token, root, text }) {
|
|
56
|
+
const issues = [];
|
|
57
|
+
if (!packet || typeof packet !== 'object') return ['Write the session review packet before completion.'];
|
|
58
|
+
if (!nonempty(token) || packet.token !== token) issues.push('Review token is missing or stale. Use this user request\'s token.');
|
|
59
|
+
if (!['ready', 'blocked'].includes(packet.status)) issues.push('Review status must be ready or blocked.');
|
|
60
|
+
if (!Array.isArray(packet.checks) || packet.checks.length === 0) {
|
|
61
|
+
issues.push('Record at least one task-specific acceptance check with actual evidence.');
|
|
62
|
+
} else {
|
|
63
|
+
for (const check of packet.checks) {
|
|
64
|
+
if (!check || !nonempty(check.criterion) || !nonempty(check.evidence) || !['passed', 'unmet'].includes(check.result)) {
|
|
65
|
+
issues.push('Each check needs a criterion, passed/unmet result, and evidence.');
|
|
66
|
+
} else if (packet.status === 'ready' && check.result !== 'passed') {
|
|
67
|
+
issues.push(`Repair the unmet criterion before claiming readiness: ${check.criterion}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// A packet run finish wrote states the run's record and claims no reread of the reply; the run
|
|
72
|
+
// gate confirms its runs completed in this request. Any other packet carries the affirmation.
|
|
73
|
+
if (packet.writtenBy !== 'run finish') {
|
|
74
|
+
for (const key of ['answersRequest', 'understandable', 'visualAddsInformation', 'limitationsDisclosed']) {
|
|
75
|
+
if (packet.humanReview?.[key] !== true) issues.push(`Complete the human-readiness review: ${key}.`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
// A blocked handoff names its blocker in the agent's words or by the controller runs that ended
|
|
79
|
+
// short of complete; the run gate confirms those runs belong to this request.
|
|
80
|
+
if (packet.status === 'blocked') {
|
|
81
|
+
const byRuns = Array.isArray(packet.blockedBy) && packet.blockedBy.length > 0;
|
|
82
|
+
if (!nonempty(packet.blocker) && !byRuns) issues.push('A blocked handoff needs its blocker: pass --blocker "<what stops completion>" to cyc packet, or record the run blocked with the controller and rerun cyc packet.');
|
|
83
|
+
else if (text !== undefined && !/^(?:\*\*)?(?:Blocked|Not ready):/i.test(text)) issues.push('A blocked handoff must start with Blocked: or Not ready:.');
|
|
84
|
+
// With recorded blocking runs the controller's record is the blocker, so extra agent text need not be repeated verbatim.
|
|
85
|
+
else if (text !== undefined && nonempty(packet.blocker) && !byRuns && !text.includes(packet.blocker)) issues.push(`A blocked handoff must disclose its exact blocker. Include the review's blocker text: ${packet.blocker}`);
|
|
86
|
+
}
|
|
87
|
+
if (!Array.isArray(packet.artifacts)) {
|
|
88
|
+
issues.push('List current deliverable artifacts and hashes, or [] for conversation-only work.');
|
|
89
|
+
} else {
|
|
90
|
+
for (const artifact of packet.artifacts) {
|
|
91
|
+
try {
|
|
92
|
+
if (!artifact || !nonempty(artifact.path) || !/^[a-f0-9]{64}$/.test(artifact.sha256 ?? '')) throw new Error('missing path or SHA-256');
|
|
93
|
+
const realRoot = realpathSync(root);
|
|
94
|
+
const target = realpathSync(resolve(realRoot, artifact.path));
|
|
95
|
+
const rel = relative(realRoot, target);
|
|
96
|
+
if (rel === '..' || rel.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`) || isAbsolute(rel)) throw new Error('artifact outside this project');
|
|
97
|
+
if (!statSync(target).isFile()) throw new Error('artifact is not a file');
|
|
98
|
+
if (digest(readFileSync(target)) !== artifact.sha256) throw new Error('artifact changed after review');
|
|
99
|
+
} catch (error) {
|
|
100
|
+
issues.push(`Artifact review invalid: ${artifact?.path ?? '(missing)'} (${error.message}).`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return issues;
|
|
105
|
+
}
|