cyc-stack 0.0.0-stage → 0.7.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 +153 -0
- package/LICENSE +21 -0
- package/README.md +436 -2
- package/bin/cyc.mjs +294 -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 +105 -0
- package/docs/impact-analysis.md +70 -0
- package/docs/installation.md +198 -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 +249 -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 +180 -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 +87 -0
- package/methods/cyc-verify/references/recipe.md +53 -0
- package/package.json +91 -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/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 +1832 -0
- package/scripts/source-hash-worker.mjs +5 -0
- package/scripts/source-snapshot.mjs +405 -0
- package/scripts/test-output.mjs +268 -0
- package/scripts/work-review.mjs +326 -0
- package/skills/cyc/SKILL.md +132 -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,66 @@
|
|
|
1
|
+
import {existsSync,lstatSync,readFileSync,realpathSync} from 'node:fs';
|
|
2
|
+
import {dirname,resolve} from 'node:path';
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
import {checkPacket,checkResponse,digest,normalize} from './response-gate.mjs';
|
|
5
|
+
|
|
6
|
+
const engine=dirname(fileURLToPath(import.meta.url));
|
|
7
|
+
const declarations={codex:'.codex/hooks.json',claude:'.claude/settings.json',cursor:'.cursor/hooks.json'};
|
|
8
|
+
function local(root,name){let path=root;for(const part of name.split('/')){path=resolve(path,part);try{if(lstatSync(path).isSymbolicLink())throw Error('Linked hook evidence is not supported.');}catch(error){if(error.code!=='ENOENT')throw error;}}return path;}
|
|
9
|
+
const fileHash=path=>existsSync(path)?digest(readFileSync(path)):null;
|
|
10
|
+
|
|
11
|
+
// Bind observations to the implementation actually executing, without claiming
|
|
12
|
+
// that editable local files are tamper-proof or a host trust attestation.
|
|
13
|
+
export function activationBinding(root,host){
|
|
14
|
+
const projectRoot=realpathSync(root);
|
|
15
|
+
const hookHash=digest(['host-activation.mjs','response-hook.mjs','response-gate.mjs','response-mode.mjs','run-gate.mjs','source-snapshot.mjs'].map(name=>`${name}\0${digest(readFileSync(resolve(engine,name)))}`).join('\0'));
|
|
16
|
+
return {schemaVersion:1,host,projectRoot,hookHash,configurationHash:fileHash(local(projectRoot,'.cyc/config.json')),declarationHash:fileHash(local(projectRoot,declarations[host]))};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function inspectHostActivation(target,{host='auto',session,token,env=process.env}={}){
|
|
20
|
+
const result={status:'unverified',reason:'host-required',host:null,promptObserved:false,completionObserved:false,canStartTask:false,
|
|
21
|
+
detail:'No host identity is available; local checks do not establish hook activation.',action:'Run onboard in the target host with --host and its native --session, using the request token supplied by the CYC gate.'};
|
|
22
|
+
try{
|
|
23
|
+
if(host==='auto')host=env.CODEX_THREAD_ID||env.CODEX_SESSION_ID?'codex':env.CLAUDE_SESSION_ID?'claude':null;
|
|
24
|
+
if(host!==null&&!Object.hasOwn(declarations,host))throw Error('Host must be auto, codex, claude, or cursor.');
|
|
25
|
+
result.host=host;if(!host)return result;
|
|
26
|
+
// Cursor uses a constant token and a separate response/tag correlation. Do not
|
|
27
|
+
// mistake that token for the rotating request identity used by these hosts.
|
|
28
|
+
if(host==='cursor')return {...result,reason:'cursor-correlation-required',detail:'Cursor activation needs its current conversation/tag and actual response/Stop observations; its constant token cannot establish this request.',action:'Use the Cursor rule and inspect the current conversation hook log; do not substitute a Codex session or invented tag.'};
|
|
29
|
+
session??=host==='codex'?env.CODEX_THREAD_ID??env.CODEX_SESSION_ID:env.CLAUDE_SESSION_ID;
|
|
30
|
+
if(typeof session!=='string'||!/^[A-Za-z0-9_-]{4,200}$/.test(session))return {...result,reason:'session-required',detail:'The current host session could not be identified.',action:'Use --session from the CYC gate context or the native host session ID. Do not choose a previous session file.'};
|
|
31
|
+
const key=/^[a-f0-9]{32}$/.test(session)?session:digest(`${host}:${session}`).slice(0,32);
|
|
32
|
+
const root=realpathSync(target),path=local(root,`.cyc/runtime/${key}.state.json`);
|
|
33
|
+
result.session=key;result.evidencePath=`.cyc/runtime/${key}.state.json`;
|
|
34
|
+
const declaration=local(root,declarations[host]);
|
|
35
|
+
result.projectDeclaration=existsSync(declaration)?'present':'not-found';
|
|
36
|
+
if(existsSync(declaration)){
|
|
37
|
+
const document=JSON.parse(readFileSync(declaration,'utf8'));
|
|
38
|
+
const events=['UserPromptSubmit','Stop'];
|
|
39
|
+
const declared=events.filter(event=>Array.isArray(document.hooks?.[event])&&document.hooks[event].some(group=>Array.isArray(group.hooks)&&group.hooks.some(handler=>typeof handler.command==='string'&&/(?:response-hook\.mjs|claude-hooks[\\/]cyc\.mjs)/.test(handler.command))));
|
|
40
|
+
// Unrelated project hooks may coexist with plugin hooks. Only diagnose a
|
|
41
|
+
// partial known project CYC integration; absent plugin sources stay unknown.
|
|
42
|
+
if(declared.length&&declared.length!==events.length)return {...result,status:'missing',reason:'hook-definition-missing',missingEvents:events.filter(event=>!declared.includes(event)),detail:'The project declares only part of the CYC hook pair.',action:'Restore both CYC prompt and Stop definitions, review/trust the exact updated hooks, and open a fresh session.'};
|
|
43
|
+
}
|
|
44
|
+
if(!existsSync(path))return {...result,status:'missing',reason:'prompt-not-observed',detail:'No CYC prompt-hook state exists for this host session. Hook files and successful commands are not activation evidence.',action:'Inspect this project’s exact hooks and host trust/settings, then open a fresh desktop session or reload the host. Expect a new CYC gate token; do not manually invoke the hook or invent a Cursor tag.'};
|
|
45
|
+
const state=JSON.parse(readFileSync(path,'utf8')),binding=activationBinding(root,host);
|
|
46
|
+
if(!state||!state.activation||Object.entries(binding).some(([k,v])=>state.activation[k]!==v)||!Number.isFinite(Date.parse(state.promptAt))||state.promptAt!==state.updatedAt||typeof state.token!=='string'||!state.token)return {...result,status:'stale',reason:'binding-mismatch',detail:'Hook state is legacy, belongs to another project/implementation, or predates changed configuration/hooks.',action:'Open a fresh session after inspecting and trusting the current hook definitions. Preserve the old evidence.'};
|
|
47
|
+
result.promptAt=state.promptAt;
|
|
48
|
+
if(typeof token!=='string'||!token)return {...result,reason:'request-token-required',detail:'Session history exists, but the current request token was not supplied. An older accepted turn cannot prove this prompt hook ran.',action:'Pass --token from this request’s injected CYC gate context. If that context is absent, report missing activation and reload; do not obtain a token from an old state/packet.'};
|
|
49
|
+
if(state.token!==token)return {...result,status:'stale',reason:'request-changed',detail:'The supplied request token does not match this session’s current prompt.',action:'Use the current injected gate context; never reuse another request’s token.'};
|
|
50
|
+
Object.assign(result,{promptObserved:true,canStartTask:true,status:'pending',reason:'completion-pending',detail:'This request’s prompt hook was observed; its completion hook has not accepted a response yet.',action:'Continue the authorized first task and write its exact review packet. Observe Stop after the turn ends; do not wait for your own completion before starting work.'});
|
|
51
|
+
if(state.lastDecision==='retry')return {...result,reason:'stop-rejected',completionObserved:true,decision:'retry',detail:'The completion hook rejected the previous draft. Repair its recorded issues without resetting the request or retry budget.'};
|
|
52
|
+
if(!state.lastDecision)return result;
|
|
53
|
+
if(state.stopToken!==state.token||!Number.isFinite(Date.parse(state.stoppedAt))||Date.parse(state.stoppedAt)<Date.parse(state.promptAt)||!/^[a-f0-9]{64}$/.test(state.stopResponseHash??''))return {...result,status:'stale',reason:'stop-identity-mismatch',canStartTask:false,detail:'A completion decision lacks matching request/response evidence.'};
|
|
54
|
+
if(state.lastDecision!=='ready')return {...result,status:'failed',reason:'completion-not-ready',completionObserved:true,decision:state.lastDecision,canStartTask:false,detail:'The hook ended with a blocked or not-ready handoff; do not report setup ready.'};
|
|
55
|
+
const config=existsSync(local(root,'.cyc/config.json'))?JSON.parse(readFileSync(local(root,'.cyc/config.json'),'utf8')):{};
|
|
56
|
+
if(config.delivery?.presentation!=='project'){
|
|
57
|
+
const packet=JSON.parse(readFileSync(local(root,`.cyc/runtime/${key}.review.json`),'utf8'));
|
|
58
|
+
// A packet without a copied reply is bound by the packet bytes the accepting Stop recorded.
|
|
59
|
+
const copied=packet.response!==undefined;
|
|
60
|
+
const bound=copied?typeof packet.response==='string'&&digest(normalize(packet.response))===state.stopResponseHash:typeof state.stopPacketHash==='string'&&state.stopPacketHash===digest(readFileSync(local(root,`.cyc/runtime/${key}.review.json`)));
|
|
61
|
+
const issues=copied?checkResponse({response:packet.response,packet,token,expanded:state.characterLimitEnabled===false||state.expanded===true,root}):checkPacket({packet,token,root});
|
|
62
|
+
if(!bound||packet.status!=='ready'||issues.length)return {...result,status:'stale',reason:'packet-changed',canStartTask:false,detail:'The current review/response/artifacts no longer match the accepted completion.'};
|
|
63
|
+
}
|
|
64
|
+
return {...result,status:'passed',reason:'completion-accepted',completionObserved:true,decision:'ready',stoppedAt:state.stoppedAt,detail:'Matching prompt and accepted Stop observations exist for this request and current hook/configuration bytes. This is local trace evidence, not independent certification.',action:'Continue with the user’s task. A new request must supply its own prompt token; other hosts/sessions remain unverified.'};
|
|
65
|
+
}catch(error){return {...result,status:'failed',reason:'invalid-evidence',detail:`Hook evidence could not be inspected: ${error.message}`,action:'Repair the reported evidence/configuration path and recheck in a fresh host session; do not replace it with fabricated state.'};}
|
|
66
|
+
}
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync, lstatSync, readFileSync, readdirSync, mkdirSync, writeFileSync, renameSync, unlinkSync, rmdirSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { dirname, resolve, relative, sep, join } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const sourceRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
7
|
+
const { version, files: releaseFiles } = JSON.parse(readFileSync(resolve(sourceRoot, 'package.json'), 'utf8'));
|
|
8
|
+
// Share npm's literal release selection; development directories never enter a project copy.
|
|
9
|
+
const engineFolders = new Set(['bin', 'scripts', 'skills', 'methods', 'catalog', 'docs', 'rules']);
|
|
10
|
+
const engineFiles = releaseFiles.filter(name => engineFolders.has(name.split('/')[0]));
|
|
11
|
+
const manifestPath = '.cyc/install-manifest.json';
|
|
12
|
+
const hostSpecs = {
|
|
13
|
+
codex: { path: '.codex/hooks.json', events: ['UserPromptSubmit', 'Stop'], skills: '.agents/skills' },
|
|
14
|
+
claude: { path: '.claude/settings.json', events: ['UserPromptSubmit', 'Stop'], skills: '.claude/skills', files: { 'scripts/claude-hooks/cyc.mjs': 'scripts/claude-project-hook.mjs' } },
|
|
15
|
+
// Cursor reads .agents/skills; its hooks need the response event to see the final text.
|
|
16
|
+
cursor: { path: '.cursor/hooks.json', events: ['beforeSubmitPrompt', 'afterAgentResponse', 'stop'], skills: '.agents/skills', files: { '.cursor/rules/cyc-delivery.mdc': 'rules/cyc-delivery.mdc' } }
|
|
17
|
+
};
|
|
18
|
+
const hostPaths = Object.fromEntries(Object.entries(hostSpecs).map(([host, spec]) => [host, spec.path]));
|
|
19
|
+
const digest = value => createHash('sha256').update(value).digest('hex');
|
|
20
|
+
// A project's linter can reach CYC's files: ESLint flat config lints dot-folders such as
|
|
21
|
+
// .cyc/engine, and the Claude launcher sits in the project's scripts/. CYC's style is not the
|
|
22
|
+
// project's, so each installed script turns lint rules off for itself (after any shebang).
|
|
23
|
+
// An installed engine can install CYC elsewhere; its files already carry the header.
|
|
24
|
+
const lintExempt = (name, bytes) => {
|
|
25
|
+
if (!/\.(?:mjs|cjs|js)$/.test(name)) return bytes;
|
|
26
|
+
const source = bytes.toString('utf8');
|
|
27
|
+
const shebang = source.startsWith('#!') ? source.slice(0, source.indexOf('\n') + 1) : '';
|
|
28
|
+
const body = source.slice(shebang.length);
|
|
29
|
+
return body.startsWith('/* eslint-disable */\n') ? bytes : Buffer.from(`${shebang}/* eslint-disable */\n${body}`);
|
|
30
|
+
};
|
|
31
|
+
const json = value => Buffer.from(`${JSON.stringify(value, null, 2)}\n`);
|
|
32
|
+
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
33
|
+
const defaults = { schemaVersion: 1, verification: { commands: [] }, limits: { maxAttempts: 3, maxNoProgress: 2 } };
|
|
34
|
+
const noChecksWarning = 'No verification commands are configured. Code playbooks (feature, bug-fix, refactor, performance, verify, experience) refuse to start until .cyc/config.json lists the project\'s real checks; /cyc runs Setup to add them before the first run.';
|
|
35
|
+
|
|
36
|
+
function project(target) {
|
|
37
|
+
const path = resolve(target);
|
|
38
|
+
if (!existsSync(path) || !lstatSync(path).isDirectory()) throw new Error('Target must be an existing project directory.');
|
|
39
|
+
return realpathSync(path);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Never follow a destination symlink/junction or a path outside the requested project.
|
|
43
|
+
function safePath(root, name) {
|
|
44
|
+
if (typeof name !== 'string' || name.includes('\\') || name.split('/').some(p => !p || p === '.' || p === '..')) throw new Error(`Unsafe managed path: ${name}`);
|
|
45
|
+
const path = resolve(root, name);
|
|
46
|
+
const rel = relative(root, path);
|
|
47
|
+
if (!rel || rel.startsWith(`..${sep}`) || rel === '..' || resolve(name) === name) throw new Error(`Path escapes project: ${name}`);
|
|
48
|
+
let current = root;
|
|
49
|
+
for (const part of rel.split(sep)) {
|
|
50
|
+
current = join(current, part);
|
|
51
|
+
try { if (lstatSync(current).isSymbolicLink()) throw new Error(`Refusing symlink/junction: ${name}`); }
|
|
52
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
53
|
+
}
|
|
54
|
+
return path;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function read(root, name) {
|
|
58
|
+
const path = safePath(root, name);
|
|
59
|
+
if (!existsSync(path)) return null;
|
|
60
|
+
if (!lstatSync(path).isFile()) throw new Error(`Expected a file: ${name}`);
|
|
61
|
+
return readFileSync(path);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function parse(buffer, name) {
|
|
65
|
+
try { const value = JSON.parse(buffer.toString('utf8').replace(/^\uFEFF/, '')); if (!object(value)) throw new Error(); return value; }
|
|
66
|
+
catch { throw new Error(`Invalid JSON object: ${name}`); }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function validConfig(value) {
|
|
70
|
+
if (value.schemaVersion !== 1 || !object(value.verification) || !Array.isArray(value.verification.commands) || !object(value.limits)) return false;
|
|
71
|
+
return ['maxAttempts', 'maxNoProgress'].every(k => Number.isSafeInteger(value.limits[k]) && value.limits[k] > 0)
|
|
72
|
+
&& (value.limits.maxDurationMs === undefined || value.limits.maxDurationMs === null || (Number.isSafeInteger(value.limits.maxDurationMs) && value.limits.maxDurationMs > 0));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function manifest(root) {
|
|
76
|
+
const bytes = read(root, manifestPath);
|
|
77
|
+
if (!bytes) return null;
|
|
78
|
+
const value = parse(bytes, manifestPath);
|
|
79
|
+
if (value.schemaVersion !== 1 || value.owner !== 'cycstack' || !object(value.files) || !object(value.hooks)) throw new Error('Invalid CYC installation manifest.');
|
|
80
|
+
for (const [name, hash] of Object.entries(value.files)) {
|
|
81
|
+
if (!(name.startsWith('.cyc/engine/') || /^\.(?:agents|claude)\/skills\/cyc(?:-[a-z0-9-]+)?\//.test(name) || ['.cyc/config.json', '.cyc/.gitignore', '.cursor/rules/cyc-delivery.mdc', 'scripts/claude-hooks/cyc.mjs'].includes(name)) || !/^[a-f0-9]{64}$/.test(hash)) throw new Error('Invalid managed file in manifest.');
|
|
82
|
+
safePath(root, name);
|
|
83
|
+
}
|
|
84
|
+
for (const [host, info] of Object.entries(value.hooks)) {
|
|
85
|
+
if (!hostPaths[host] || !object(info) || !object(info.entry) || !object(info.original)) throw new Error('Invalid host entry in manifest.');
|
|
86
|
+
}
|
|
87
|
+
return value;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function walk(directory, prefix = '') {
|
|
91
|
+
if (!existsSync(directory)) return [];
|
|
92
|
+
return readdirSync(directory, { withFileTypes: true }).flatMap(item => {
|
|
93
|
+
if (item.isSymbolicLink()) throw new Error(`Distribution must not contain symlinks: ${item.name}`);
|
|
94
|
+
const name = `${prefix}${item.name}`;
|
|
95
|
+
if (item.isDirectory()) return walk(join(directory, item.name), `${name}/`);
|
|
96
|
+
return item.isFile() ? [[name, readFileSync(join(directory, item.name))]] : [];
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
function hookEntry(root, host) {
|
|
102
|
+
// 60 seconds: the Stop path allows up to 17 s of git calls plus hashing, and a hook the host kills
|
|
103
|
+
// never reaches the gate's own fail-closed handler.
|
|
104
|
+
if (host === 'claude') return { hooks: [{ type: 'command', command: 'node "$CLAUDE_PROJECT_DIR/scripts/claude-hooks/cyc.mjs"', shell: 'bash', timeout: 60 }] };
|
|
105
|
+
// A fixed bootstrap works in cmd and POSIX shells. Paths come from the host event,
|
|
106
|
+
// never shell interpolation; clones and nested working directories need no reinstall.
|
|
107
|
+
const bootstrap = `const f=require('node:fs'),p=require('node:path');const b=f.readFileSync(0);const i=JSON.parse(b.toString('utf8').replace(/^\\uFEFF/,''));let d=p.resolve(i.cwd||(i.workspace_roots||[])[0]||process.env.CLAUDE_PROJECT_DIR||process.env.CURSOR_PROJECT_DIR||process.cwd());while(!f.existsSync(p.join(d,'.cyc/engine/scripts/response-hook.mjs'))){const n=p.dirname(d);if(n===d)throw Error('CYC engine not found for hook project');d=n;}const r=require('node:child_process').spawnSync(process.execPath,[p.join(d,'.cyc/engine/scripts/response-hook.mjs'),'${host}','--project',d],{input:b,stdio:['pipe','inherit','inherit'],windowsHide:true});process.exit(r.status===null?1:r.status);`;
|
|
108
|
+
const command = `node -e "${bootstrap}"`;
|
|
109
|
+
// Cursor entries are flat; loop_limit allows three corrections plus the NOT READY notice.
|
|
110
|
+
if (host === 'cursor') return { command, timeout: 60, loop_limit: 4 };
|
|
111
|
+
return { hooks: [{ type: 'command', command, timeout: 60 }] };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function validateHooks(value, path, events = ['UserPromptSubmit', 'Stop']) {
|
|
115
|
+
if (value.hooks !== undefined && !object(value.hooks)) throw new Error(`Invalid hooks object: ${path}`);
|
|
116
|
+
for (const event of events) if (value.hooks?.[event] !== undefined && !Array.isArray(value.hooks[event])) throw new Error(`Invalid ${event} hook list: ${path}`);
|
|
117
|
+
}
|
|
118
|
+
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
119
|
+
function removeOwnedEntry(entries, entry) {
|
|
120
|
+
const index = entries.findLastIndex(value => same(value, entry));
|
|
121
|
+
return index < 0 ? entries : entries.filter((_, position) => position !== index);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function referencesEngine(value) {
|
|
125
|
+
if (Array.isArray(value)) return value.some(referencesEngine);
|
|
126
|
+
if (!object(value)) return false;
|
|
127
|
+
if (typeof value.command === 'string' && /scripts[\\/]claude-hooks[\\/]cyc\.mjs\b/i.test(value.command)) return true;
|
|
128
|
+
if (typeof value.command === 'string' && /(?:^|[\\/])\.cyc[\\/]engine(?:[\\/]|\b)/i.test(value.command)) return true;
|
|
129
|
+
// Relative commands may begin after a quote or executable, rather than a slash.
|
|
130
|
+
if (typeof value.command === 'string' && /(?:^|[\s"'])\.cyc[\\/]engine(?:[\\/]|\b)/i.test(value.command)) return true;
|
|
131
|
+
return Object.values(value).some(referencesEngine);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function commit(root, operations) {
|
|
135
|
+
const originals = new Map();
|
|
136
|
+
const createdDirectories = [];
|
|
137
|
+
const applied = [];
|
|
138
|
+
try {
|
|
139
|
+
for (const op of operations) {
|
|
140
|
+
const path = safePath(root, op.path);
|
|
141
|
+
originals.set(op.path, read(root, op.path));
|
|
142
|
+
let parent = dirname(path);
|
|
143
|
+
const missing = [];
|
|
144
|
+
while (parent !== root && !existsSync(parent)) { missing.push(parent); parent = dirname(parent); }
|
|
145
|
+
for (const dir of missing.reverse()) { mkdirSync(dir); createdDirectories.push(dir); }
|
|
146
|
+
if (op.content === null) unlinkSync(path);
|
|
147
|
+
else {
|
|
148
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
149
|
+
try { writeFileSync(temporary, op.content); renameSync(temporary, path); }
|
|
150
|
+
finally { if (existsSync(temporary)) unlinkSync(temporary); }
|
|
151
|
+
}
|
|
152
|
+
applied.push(op.path);
|
|
153
|
+
}
|
|
154
|
+
} catch (error) {
|
|
155
|
+
const failures = [];
|
|
156
|
+
for (const name of applied.reverse()) {
|
|
157
|
+
try { const bytes = originals.get(name); const path = safePath(root, name); if (bytes === null) unlinkSync(path); else writeFileSync(path, bytes); }
|
|
158
|
+
catch (failure) { failures.push(`${name}: ${failure.message}`); }
|
|
159
|
+
}
|
|
160
|
+
for (const dir of createdDirectories.reverse()) { try { rmdirSync(dir); } catch { /* nonempty or already removed */ } }
|
|
161
|
+
throw new Error(`${error.message}${failures.length ? `; rollback incomplete: ${failures.join('; ')}` : '; changes rolled back'}`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const legacyDurationMs = 900000;
|
|
166
|
+
function activeRuns(root) {
|
|
167
|
+
const directory = join(root, '.cyc', 'runs');
|
|
168
|
+
if (!existsSync(directory)) return [];
|
|
169
|
+
return readdirSync(directory, { withFileTypes: true }).filter(entry => entry.isDirectory()).filter(entry => {
|
|
170
|
+
try { return JSON.parse(readFileSync(join(directory, entry.name, 'state.json'), 'utf8')).status === 'running'; } catch { return false; }
|
|
171
|
+
}).map(entry => entry.name);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function result(action, root) { return { ok: true, action, projectRoot: root, hosts: [], changes: [], warnings: [], conflicts: [] }; }
|
|
175
|
+
|
|
176
|
+
export function installProject(target, { hosts = ['codex', 'claude'], dryRun = false } = {}) {
|
|
177
|
+
let root = resolve(target);
|
|
178
|
+
const out = result('install', root);
|
|
179
|
+
try {
|
|
180
|
+
root = project(target); out.projectRoot = root;
|
|
181
|
+
if (!Array.isArray(hosts) || !hosts.length || hosts.some(h => !hostPaths[h])) throw new Error('hosts must contain codex, claude, and/or cursor.');
|
|
182
|
+
const old = manifest(root);
|
|
183
|
+
const selected = [...new Set([...Object.keys(old?.hooks ?? {}), ...hosts])]; out.hosts = selected;
|
|
184
|
+
const desired = new Map();
|
|
185
|
+
for (const name of engineFiles) {
|
|
186
|
+
const source = resolve(sourceRoot, name);
|
|
187
|
+
const info = lstatSync(source);
|
|
188
|
+
if (info.isSymbolicLink()) throw new Error(`Distribution must not contain symlinks: ${name}`);
|
|
189
|
+
const entries = info.isDirectory() ? walk(source).map(([entry, bytes]) => [`${name}/${entry}`, bytes]) : [[name, readFileSync(source)]];
|
|
190
|
+
for (const [entry, bytes] of entries) desired.set(`.cyc/engine/${entry}`, lintExempt(entry, bytes));
|
|
191
|
+
}
|
|
192
|
+
desired.set('.cyc/engine/README.md', readFileSync(resolve(sourceRoot, 'README.md')));
|
|
193
|
+
desired.set('.cyc/engine/INSTALL.md', readFileSync(resolve(sourceRoot, 'INSTALL.md')));
|
|
194
|
+
// The engine copy is a distributed copy of the code, so it carries the license its README links to.
|
|
195
|
+
// A source without one (an older copy) still installs; the install test asserts this source ships it.
|
|
196
|
+
if (existsSync(resolve(sourceRoot, 'LICENSE'))) desired.set('.cyc/engine/LICENSE', readFileSync(resolve(sourceRoot, 'LICENSE')));
|
|
197
|
+
desired.set('.cyc/engine/package.json', json({ name: 'cyc-local-engine', version, private: true, type: 'module', files: engineFiles }));
|
|
198
|
+
// ESLint 10 reads the config nearest each file, so this keeps a project's lint off the whole
|
|
199
|
+
// engine without the unused-directive warnings the per-file headers can raise.
|
|
200
|
+
desired.set('.cyc/engine/eslint.config.mjs', lintExempt('eslint.config.mjs', Buffer.from("// CYC's engine is not this project's source; the project's lint rules do not apply here.\nexport default [{ ignores: ['**/*'] }];\n")));
|
|
201
|
+
const skills = walk(resolve(sourceRoot, 'skills'));
|
|
202
|
+
if (!skills.some(([name]) => name.endsWith('/SKILL.md'))) throw new Error('Distribution has no skills.');
|
|
203
|
+
for (const host of selected) for (const [name, bytes] of skills) {
|
|
204
|
+
if (!/^cyc(?:-[a-z0-9-]+)?\//.test(name)) throw new Error(`Skill must use the CYC namespace: ${name}`);
|
|
205
|
+
const adjusted = name.endsWith('.md') ? Buffer.from(bytes.toString('utf8').replace(/\.\.\/\.\.\/(docs|catalog|scripts|bin|methods|evals)\//g, '../../../.cyc/engine/$1/')) : bytes;
|
|
206
|
+
desired.set(`${hostSpecs[host].skills}/${name}`, adjusted);
|
|
207
|
+
}
|
|
208
|
+
for (const host of selected) for (const [target, source] of Object.entries(hostSpecs[host].files ?? {})) desired.set(target, lintExempt(target, readFileSync(resolve(sourceRoot, source))));
|
|
209
|
+
const config = read(root, '.cyc/config.json');
|
|
210
|
+
if (config && !validConfig(parse(config, '.cyc/config.json'))) throw new Error('Invalid CYC project config schema.');
|
|
211
|
+
if (!config) desired.set('.cyc/config.json', json(defaults));
|
|
212
|
+
else if (!old) throw new Error('Unowned .cyc/config.json already exists; refusing to adopt or overwrite it.');
|
|
213
|
+
desired.set('.cyc/.gitignore', Buffer.from('runtime/\nruns/\n'));
|
|
214
|
+
const next = { schemaVersion: 1, owner: 'cycstack', version, files: {}, hooks: {} };
|
|
215
|
+
const operations = [];
|
|
216
|
+
for (const [name, content] of desired) {
|
|
217
|
+
const current = read(root, name); const ownedHash = old?.files[name];
|
|
218
|
+
if (current && (!ownedHash || digest(current) !== ownedHash)) out.conflicts.push({ path: name, reason: ownedHash ? 'Installed file was modified; preserve it and resolve before updating.' : 'Existing file is not owned by CYC.' });
|
|
219
|
+
else if (!current || !current.equals(content)) operations.push({ path: name, content });
|
|
220
|
+
next.files[name] = digest(content);
|
|
221
|
+
}
|
|
222
|
+
// Config is user-editable and preserved on update. Keep its original ownership hash.
|
|
223
|
+
if (config && old?.files['.cyc/config.json']) next.files['.cyc/config.json'] = old.files['.cyc/config.json'];
|
|
224
|
+
// Early installers wrote a 15-minute run limit into every new config. CYC no longer uses a
|
|
225
|
+
// clock, so remove that exact legacy value on update. Never rewrite config under an active run:
|
|
226
|
+
// the controller protects it, and changing it would halt the run.
|
|
227
|
+
const parsedConfig = config ? parse(config, '.cyc/config.json') : null;
|
|
228
|
+
if (old && parsedConfig?.limits?.maxDurationMs === legacyDurationMs) {
|
|
229
|
+
if (activeRuns(root).length) out.warnings.push('Legacy 15-minute run limit (limits.maxDurationMs: 900000) left in place because a CYC run is active. Rerun this update after the run ends to remove it.');
|
|
230
|
+
else {
|
|
231
|
+
delete parsedConfig.limits.maxDurationMs;
|
|
232
|
+
operations.push({ path: '.cyc/config.json', content: json(parsedConfig) });
|
|
233
|
+
out.warnings.push('Removed the legacy 15-minute run limit (limits.maxDurationMs: 900000) from .cyc/config.json. Runs are now bounded by failed attempts, not time. Add limits.maxDurationMs back if you want a deadline.');
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
for (const [name, hash] of Object.entries(old?.files ?? {})) if (!desired.has(name) && name !== '.cyc/config.json') {
|
|
237
|
+
const current = read(root, name);
|
|
238
|
+
if (current && digest(current) === hash) operations.push({ path: name, content: null });
|
|
239
|
+
else if (current) {
|
|
240
|
+
next.files[name] = hash;
|
|
241
|
+
if (/^\.(?:agents|claude)\/skills\/cyc-[^/]+\//.test(name)) out.conflicts.push({ path: name, reason: 'Customized legacy supporting skill. Preserve and migrate its changes to the internal methods before updating; no files changed.' });
|
|
242
|
+
else out.warnings.push(`Preserved modified obsolete file: ${name}`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
for (const host of selected) {
|
|
246
|
+
const name = hostPaths[host]; const bytes = read(root, name); const value = bytes ? parse(bytes, name) : {};
|
|
247
|
+
const events = hostSpecs[host].events; validateHooks(value, name, events);
|
|
248
|
+
const prior = old?.hooks[host]; const entry = hookEntry(root, host);
|
|
249
|
+
if ((value.hooks?.[host === 'cursor' ? 'stop' : 'Stop'] ?? []).some(item => !same(item, prior?.entry))) out.warnings.push(`${host}: existing Stop hooks preserved. If another hook owns reply formatting, set delivery.presentation to "project" in .cyc/config.json; CYC still checks controller completion.`);
|
|
250
|
+
const original = prior?.original ?? { existed: Boolean(bytes), hooksExisted: Object.hasOwn(value, 'hooks'), versionExisted: Object.hasOwn(value, 'version'), events: Object.fromEntries(events.map(e => [e, Object.hasOwn(value.hooks ?? {}, e)])) };
|
|
251
|
+
if (host === 'cursor') value.version ??= 1;
|
|
252
|
+
value.hooks ??= {};
|
|
253
|
+
for (const event of events) {
|
|
254
|
+
const entries = value.hooks[event] ?? [];
|
|
255
|
+
if (prior && !entries.some(e => same(e, prior.entry))) out.conflicts.push({ path: name, reason: `${event}: owned hook was removed or modified.` });
|
|
256
|
+
value.hooks[event] = [...(prior ? removeOwnedEntry(entries, prior.entry) : entries), entry];
|
|
257
|
+
}
|
|
258
|
+
const content = json(value); if (!bytes || !bytes.equals(content)) operations.push({ path: name, content });
|
|
259
|
+
next.hooks[host] = { entry, original };
|
|
260
|
+
}
|
|
261
|
+
next.files = Object.fromEntries(Object.entries(next.files).sort(([a], [b]) => a.localeCompare(b)));
|
|
262
|
+
const oldBytes = read(root, manifestPath); const newBytes = json(next);
|
|
263
|
+
if (!oldBytes || !oldBytes.equals(newBytes)) operations.push({ path: manifestPath, content: newBytes });
|
|
264
|
+
out.changes = operations.map(op => ({ path: op.path, action: op.content === null ? 'remove' : read(root, op.path) ? 'update' : 'create' }));
|
|
265
|
+
out.ok = !out.conflicts.length; out.dryRun = dryRun;
|
|
266
|
+
if (!(config ? parse(config, '.cyc/config.json') : defaults).verification.commands.length) out.warnings.push(noChecksWarning);
|
|
267
|
+
out.warnings.push('Host hook trust and session reload are not verified. Restart/reload the host and check a real session.');
|
|
268
|
+
if (out.ok && !dryRun) commit(root, operations);
|
|
269
|
+
} catch (error) { out.ok = false; out.error = error.message; }
|
|
270
|
+
return out;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function uninstallProject(target, { dryRun = false } = {}) {
|
|
274
|
+
let root = resolve(target); const out = result('uninstall', root);
|
|
275
|
+
try {
|
|
276
|
+
root = project(target); out.projectRoot = root; const old = manifest(root);
|
|
277
|
+
if (!old) { out.warnings.push('No CYC installation manifest found; nothing removed.'); return out; }
|
|
278
|
+
const operations = []; out.hosts = Object.keys(old.hooks);
|
|
279
|
+
for (const [host, info] of Object.entries(old.hooks)) {
|
|
280
|
+
const name = hostPaths[host]; const bytes = read(root, name); if (!bytes) continue;
|
|
281
|
+
const value = parse(bytes, name); const events = hostSpecs[host].events; validateHooks(value, name, events);
|
|
282
|
+
for (const event of events) if (Array.isArray(value.hooks?.[event])) {
|
|
283
|
+
const before = value.hooks[event]; value.hooks[event] = removeOwnedEntry(before, info.entry);
|
|
284
|
+
if (before.length === value.hooks[event].length) out.warnings.push(`Preserved missing or modified ${host} ${event} hook.`);
|
|
285
|
+
if (!value.hooks[event].length && !info.original.events[event]) delete value.hooks[event];
|
|
286
|
+
}
|
|
287
|
+
if (value.hooks && !Object.keys(value.hooks).length && !info.original.hooksExisted) delete value.hooks;
|
|
288
|
+
if (host === 'cursor' && !value.hooks && !info.original.versionExisted) delete value.version;
|
|
289
|
+
if (referencesEngine(value.hooks)) out.conflicts.push({ path: name, reason: 'A preserved hook still references the CYC engine or launcher. Remove or adapt that hook before uninstalling; no files were changed.' });
|
|
290
|
+
const content = !Object.keys(value).length && !info.original.existed ? null : json(value);
|
|
291
|
+
if (content === null || !content.equals(bytes)) operations.push({ path: name, content });
|
|
292
|
+
}
|
|
293
|
+
// A user may have copied an engine command into a host CYC did not install.
|
|
294
|
+
for (const [host, name] of Object.entries(hostPaths)) if (!old.hooks[host]) {
|
|
295
|
+
const bytes = read(root, name); if (!bytes) continue;
|
|
296
|
+
const value = parse(bytes, name); validateHooks(value, name, hostSpecs[host].events);
|
|
297
|
+
if (referencesEngine(value.hooks)) out.conflicts.push({ path: name, reason: 'An unmanaged host hook references the CYC engine or launcher. Remove or adapt that hook before uninstalling; no files were changed.' });
|
|
298
|
+
}
|
|
299
|
+
if (out.conflicts.length) {
|
|
300
|
+
out.ok = false; out.dryRun = dryRun;
|
|
301
|
+
return out;
|
|
302
|
+
}
|
|
303
|
+
const retainedRecords = ['.cyc/runtime', '.cyc/runs'].some(name => existsSync(safePath(root, name)));
|
|
304
|
+
for (const [name, hash] of Object.entries(old.files)) {
|
|
305
|
+
const bytes = read(root, name); if (!bytes) continue;
|
|
306
|
+
if (name === '.cyc/.gitignore' && retainedRecords && digest(bytes) === hash) {
|
|
307
|
+
out.warnings.push('Preserved .cyc/.gitignore alongside retained runtime/run records; its existing ignore rules remain in effect.');
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
if (digest(bytes) === hash) operations.push({ path: name, content: null });
|
|
311
|
+
else out.warnings.push(`Preserved modified file: ${name}`);
|
|
312
|
+
}
|
|
313
|
+
operations.push({ path: manifestPath, content: null });
|
|
314
|
+
out.changes = operations.map(op => ({ path: op.path, action: op.content === null ? 'remove' : 'update' })); out.dryRun = dryRun;
|
|
315
|
+
if (!dryRun) commit(root, operations);
|
|
316
|
+
out.warnings.push('Runtime records and user-modified files are retained. Reload the AI host to stop previously loaded hooks.');
|
|
317
|
+
} catch (error) { out.ok = false; out.error = error.message; }
|
|
318
|
+
return out;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
export function doctorProject(target) {
|
|
322
|
+
let root = resolve(target);
|
|
323
|
+
const out = { ok: true, projectRoot: root, checks: [], activation: { codex: 'unverified', claude: 'unverified', cursor: 'unverified' } };
|
|
324
|
+
const check = (name, ok, detail) => { out.checks.push({ name, ok, detail }); if (!ok) out.ok = false; };
|
|
325
|
+
try {
|
|
326
|
+
root = project(target); out.projectRoot = root;
|
|
327
|
+
check('node', Number(process.versions.node.split('.')[0]) >= 20, process.versions.node);
|
|
328
|
+
safePath(root, '.cyc/runtime/probe');
|
|
329
|
+
check('runtime location', true, 'Project-local runtime path contains no symlink or junction.');
|
|
330
|
+
const config = read(root, '.cyc/config.json'); check('config', Boolean(config && validConfig(parse(config, '.cyc/config.json'))), '.cyc/config.json');
|
|
331
|
+
const duration = config ? parse(config, '.cyc/config.json').limits?.maxDurationMs : undefined;
|
|
332
|
+
if (duration) out.checks.push({ name: 'run time limit', ok: true, detail: `Runs stop after ${Math.round(duration / 60000)} minutes (limits.maxDurationMs). ${duration === legacyDurationMs ? 'This is the legacy default from an early install; rerun init after active runs finish to remove it.' : 'Remove it for no clock.'}` });
|
|
333
|
+
const installed = manifest(root); check('manifest', Boolean(installed), manifestPath);
|
|
334
|
+
if (installed) {
|
|
335
|
+
out.version = installed.version ?? 'unknown (legacy manifest)';
|
|
336
|
+
for (const [host, info] of Object.entries(installed.hooks)) {
|
|
337
|
+
const bytes = read(root, hostPaths[host]); const value = bytes ? parse(bytes, hostPaths[host]) : {}; validateHooks(value, hostPaths[host], hostSpecs[host].events);
|
|
338
|
+
// Three different repairs, so name which one: an entry absent from an event (reinstall), an
|
|
339
|
+
// entry edited by hand (reinstall or keep the edit), or an installed entry the engine has since
|
|
340
|
+
// changed (rerun init). Each is checked against the manifest's record of what was installed.
|
|
341
|
+
const missing = hostSpecs[host].events.filter(event => !value.hooks?.[event]?.some(e => same(e, info.entry)));
|
|
342
|
+
const edited = missing.filter(event => value.hooks?.[event]?.some(referencesEngine));
|
|
343
|
+
const stale = !same(info.entry, hookEntry(root, host));
|
|
344
|
+
const detail = !missing.length && !stale ? 'Configuration only; host trust and real-session activation are unverified.'
|
|
345
|
+
: [
|
|
346
|
+
...(edited.length ? [`modified by hand in ${hostPaths[host]} (${edited.join(', ')}): rerun init to restore it, or keep your edit and expect this notice`] : []),
|
|
347
|
+
...(missing.filter(event => !edited.includes(event)).length ? [`missing from ${hostPaths[host]} (${missing.filter(event => !edited.includes(event)).join(', ')}): rerun init`] : []),
|
|
348
|
+
...(stale ? ['out of date: the engine\'s hook entry changed since this install; rerun init'] : [])
|
|
349
|
+
].join('; ');
|
|
350
|
+
check(`${host} hooks`, !missing.length && !stale, detail);
|
|
351
|
+
}
|
|
352
|
+
const changed = Object.entries(installed.files).filter(([name, hash]) => { const bytes = read(root, name); return !bytes || (name !== '.cyc/config.json' && digest(bytes) !== hash); }).map(([name]) => name);
|
|
353
|
+
check('installed files', !changed.length, changed.length ? changed.join(', ') : 'Owned distribution files match their recorded hashes.');
|
|
354
|
+
}
|
|
355
|
+
} catch (error) { check('inspection', false, error.message); }
|
|
356
|
+
return out;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// Plugin route: the plugin supplies skills, hooks, and engine; a project only opts in.
|
|
360
|
+
export function activateProject(target, { dryRun = false } = {}) {
|
|
361
|
+
const out = result('activate', null);
|
|
362
|
+
try {
|
|
363
|
+
const root = project(target); out.projectRoot = root;
|
|
364
|
+
const operations = [];
|
|
365
|
+
const config = read(root, '.cyc/config.json');
|
|
366
|
+
if (config && !validConfig(parse(config, '.cyc/config.json'))) throw new Error('Invalid CYC project config schema.');
|
|
367
|
+
if (!config) operations.push({ path: '.cyc/config.json', content: json(defaults) });
|
|
368
|
+
if (!read(root, '.cyc/.gitignore')) operations.push({ path: '.cyc/.gitignore', content: Buffer.from('runtime/\nruns/\n') });
|
|
369
|
+
out.changes = operations.map(op => ({ path: op.path, action: 'create' }));
|
|
370
|
+
if (!dryRun) for (const op of operations) { const path = safePath(root, op.path); mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, op.content); }
|
|
371
|
+
out.dryRun = dryRun;
|
|
372
|
+
out.warnings.push('Activated for plugin hooks.');
|
|
373
|
+
if (!(config ? parse(config, '.cyc/config.json') : defaults).verification.commands.length) out.warnings.push(noChecksWarning);
|
|
374
|
+
} catch (error) { out.ok = false; out.error = error.message; }
|
|
375
|
+
return out;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// Pick hosts from what the project already uses; fall back to all three.
|
|
379
|
+
export function detectHosts(target) {
|
|
380
|
+
const root = project(target);
|
|
381
|
+
const has = name => existsSync(join(root, name));
|
|
382
|
+
const hosts = [];
|
|
383
|
+
if (has('.claude') || has('CLAUDE.md')) hosts.push('claude');
|
|
384
|
+
if (has('.codex') || has('.agents') || has('AGENTS.md')) hosts.push('codex');
|
|
385
|
+
if (has('.cursor') || has('.cursorrules')) hosts.push('cursor');
|
|
386
|
+
return hosts.length ? hosts : Object.keys(hostSpecs);
|
|
387
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { doctorProject } from './install.mjs';
|
|
4
|
+
import { atomicJSON, configuration, projectFile, runCommands, sourceSnapshot } from './runtime.mjs';
|
|
5
|
+
import { digest } from './response-gate.mjs';
|
|
6
|
+
import { inspectHostActivation } from './host-activation.mjs';
|
|
7
|
+
|
|
8
|
+
const receiptName = '.cyc/runtime/onboarding-checks.json';
|
|
9
|
+
const configName = '.cyc/config.json';
|
|
10
|
+
|
|
11
|
+
// Locate evidence for the host agent to interpret. Never infer, configure or execute
|
|
12
|
+
// a command merely because its name looks like a test.
|
|
13
|
+
function evidenceSources(root) {
|
|
14
|
+
const names = ['.gitlab-ci.yml', 'package.json', 'Makefile', 'pyproject.toml', 'go.mod', 'Cargo.toml', 'README.md', 'docs/context/INDEX.md', 'docs/context/recipes.json', 'docs/context/verify-recipe.md'];
|
|
15
|
+
const workflows = projectFile(root, '.github/workflows');
|
|
16
|
+
if (existsSync(workflows)) {
|
|
17
|
+
for (const entry of readdirSync(workflows, { withFileTypes: true })) {
|
|
18
|
+
if (entry.isFile() && /\.ya?ml$/.test(entry.name)) names.unshift(`.github/workflows/${entry.name}`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return names.filter(name => existsSync(projectFile(root, name))).sort();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function inspectChecks(root, config, verify) {
|
|
25
|
+
const configPath = projectFile(root, configName);
|
|
26
|
+
const path = projectFile(root, receiptName);
|
|
27
|
+
const configHash = digest(readFileSync(configPath));
|
|
28
|
+
const before = sourceSnapshot(root);
|
|
29
|
+
let receipt;
|
|
30
|
+
if (verify) {
|
|
31
|
+
if (before.skipped.length) throw new Error('Setup verification cannot cover linked source. Inspect the project links before running checks.');
|
|
32
|
+
const results = runCommands(root, config.commands);
|
|
33
|
+
const after = sourceSnapshot(root);
|
|
34
|
+
const configStable = digest(readFileSync(configPath)) === configHash;
|
|
35
|
+
receipt = { schemaVersion: 1, checkedAt: new Date().toISOString(), configHash, sourceHash: after.hash,
|
|
36
|
+
sourceStable: before.hash === after.hash, configStable,
|
|
37
|
+
passed: configStable && before.hash === after.hash && !after.skipped.length && results.every(item => item.passed), results };
|
|
38
|
+
atomicJSON(path, receipt);
|
|
39
|
+
} else {
|
|
40
|
+
try { receipt = JSON.parse(readFileSync(path, 'utf8')); } catch { /* absent or malformed is unverified */ }
|
|
41
|
+
}
|
|
42
|
+
if (!receipt || receipt.schemaVersion !== 1 || typeof receipt.checkedAt !== 'string'
|
|
43
|
+
|| !Array.isArray(receipt.results) || receipt.results.length !== config.commands.length
|
|
44
|
+
|| !config.commands.every((command, index) => {
|
|
45
|
+
const result = receipt.results[index];
|
|
46
|
+
return result?.id === command.id && result.command === command.command
|
|
47
|
+
&& JSON.stringify(result.args) === JSON.stringify(command.args) && typeof result.passed === 'boolean';
|
|
48
|
+
})) return { status: 'unverified', detail: 'Configured checks have no usable setup receipt. Review their purpose and side effects, then run onboard --verify.' };
|
|
49
|
+
const now = verify ? sourceSnapshot(root) : before;
|
|
50
|
+
const status = receipt.configHash !== digest(readFileSync(configPath)) || receipt.sourceHash !== now.hash || now.skipped.length ? 'stale'
|
|
51
|
+
: receipt.passed === true && receipt.sourceStable === true && receipt.configStable === true
|
|
52
|
+
&& receipt.results.every(item => item.passed && item.exitCode === 0 && !item.error) ? 'passed' : 'failed';
|
|
53
|
+
return { status, receiptPath: receiptName, checkedAt: receipt.checkedAt,
|
|
54
|
+
detail: status === 'passed' ? 'Configured commands passed on this covered source. This does not establish task completion or host activation.'
|
|
55
|
+
: status === 'stale' ? 'The project or configuration changed since setup checks. Run onboard --verify again after reviewing the commands.'
|
|
56
|
+
: 'Setup checks failed or changed project files/configuration. Inspect the receipt; do not weaken checks to finish setup.',
|
|
57
|
+
results: receipt.results.map(({ id, passed, exitCode, error, errorCode }) => ({ id, passed, exitCode, error, errorCode })) };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function onboardProject(target, { verify = false, host = 'auto', session, token, env = process.env } = {}) {
|
|
61
|
+
const root = resolve(target);
|
|
62
|
+
const report = { ok: true, projectRoot: root, installation: 'missing', steps: [], evidenceSources: [], commands: [] };
|
|
63
|
+
const add = (id, status, detail, action, extra = {}) => {
|
|
64
|
+
report.steps.push({ id, status, detail, action, ...extra });
|
|
65
|
+
if (['missing', 'failed'].includes(status)) report.ok = false;
|
|
66
|
+
};
|
|
67
|
+
let phase = 'installation';
|
|
68
|
+
try {
|
|
69
|
+
report.evidenceSources = evidenceSources(root);
|
|
70
|
+
const configPath = projectFile(root, configName);
|
|
71
|
+
if (existsSync(projectFile(root, '.cyc/install-manifest.json'))) {
|
|
72
|
+
report.installation = 'project';
|
|
73
|
+
const diagnostics = doctorProject(root);
|
|
74
|
+
add('installation', diagnostics.ok ? 'passed' : 'failed', diagnostics.ok ? 'Project installation files and configuration are intact.' : 'Project installation needs attention.',
|
|
75
|
+
'Inspect doctor findings and resolve owned-file conflicts without overwriting customized files.', { diagnostics });
|
|
76
|
+
} else if (existsSync(configPath)) {
|
|
77
|
+
report.installation = 'config-only';
|
|
78
|
+
add('installation', 'passed', 'Project configuration exists; no project installation manifest. Plugin availability still needs confirmation in the host.', 'Use the connected CYC plugin or install a project copy.');
|
|
79
|
+
} else {
|
|
80
|
+
add('installation', 'missing', 'This project has no CYC configuration.', 'Use /cyc Set up CYC for this project. Preview init for a project install, or activate when the host already supplies the plugin.');
|
|
81
|
+
}
|
|
82
|
+
phase = 'configuration';
|
|
83
|
+
if (Number(process.versions.node.split('.')[0]) < 20) throw new Error('CYC requires Node.js 20 or later.');
|
|
84
|
+
const config = configuration(root);
|
|
85
|
+
report.commands = config.commands;
|
|
86
|
+
add('configuration', config.commands.length ? 'passed' : 'missing', config.commands.length ? 'Verification commands are configured; their relevance needs project review.' : 'No project verification commands are configured.',
|
|
87
|
+
'Read the discovered CI and project files, recommend the relevant existing checks with reasons, and configure approved commands. If no checks exist, explain the gap and propose one bounded behavior check.');
|
|
88
|
+
phase = 'checks';
|
|
89
|
+
if (config.commands.length && report.steps.every(step => step.status === 'passed')) {
|
|
90
|
+
const { status, detail, ...evidence } = inspectChecks(root, config, verify);
|
|
91
|
+
add('checks', status, detail, 'Inspect command results; after addressing the cause or prerequisite, run onboard --verify. Existing failures remain failures.', evidence);
|
|
92
|
+
} else add('checks', 'unverified', 'Checks cannot run until installation and configuration are usable.', 'Resolve the preceding setup step first.');
|
|
93
|
+
} catch (error) {
|
|
94
|
+
add(phase, 'failed', error.message, phase === 'configuration' ? 'Repair project configuration before running checks. Preserve any active run and do not change its captured configuration.' : 'Inspect the reported path or error; preserve existing project files.');
|
|
95
|
+
}
|
|
96
|
+
const activation = inspectHostActivation(root, { host, session, token, env });
|
|
97
|
+
const { status, detail, action, ...evidence } = activation;
|
|
98
|
+
add('host', status, detail, action, evidence);
|
|
99
|
+
// Exit 0 must never be mistaken for successful setup while hooks are missing
|
|
100
|
+
// or only historical. Prompt-only evidence can still permit the first task.
|
|
101
|
+
report.ready = report.steps.every(step => step.status === 'passed');
|
|
102
|
+
report.canStartTask = report.steps.filter(step => step.id !== 'host').every(step => step.status === 'passed') && activation.canStartTask;
|
|
103
|
+
report.ok &&= report.ready;
|
|
104
|
+
add('first-task', 'pending', 'Setup checks are not a completed feature or evidence of user understanding.',
|
|
105
|
+
'Use the user’s requested bounded task, or recommend one from inspected project evidence. Explain success criteria and use the normal Scout → Build → Verify → Deliver flow. Ask before selecting unrelated product changes.');
|
|
106
|
+
const next = report.steps.find(step => step.status !== 'passed');
|
|
107
|
+
report.nextAction = { step: next.id, instruction: next.action };
|
|
108
|
+
report.note = 'Inspection is read-only. --verify explicitly executes configured commands, which may have project-defined side effects, and saves a diagnostic receipt. The host agent recommends checks and confirms actual live observations.';
|
|
109
|
+
return report;
|
|
110
|
+
}
|