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.
Files changed (111) hide show
  1. package/.agents/plugins/marketplace.json +12 -0
  2. package/.claude-plugin/marketplace.json +14 -0
  3. package/.claude-plugin/plugin.json +17 -0
  4. package/.codex-plugin/plugin.json +33 -0
  5. package/.cursor-plugin/marketplace.json +13 -0
  6. package/.cursor-plugin/plugin.json +19 -0
  7. package/INSTALL.md +153 -0
  8. package/LICENSE +21 -0
  9. package/README.md +436 -2
  10. package/bin/cyc.mjs +294 -0
  11. package/catalog/playbooks.json +20 -0
  12. package/docs/README.md +30 -0
  13. package/docs/assets/cyc-method-library.svg +39 -0
  14. package/docs/assets/cyc-overview.svg +44 -0
  15. package/docs/assets/cyc-readme-banner-mobile.svg +31 -0
  16. package/docs/assets/cyc-readme-banner.svg +39 -0
  17. package/docs/assets/cyc-workflow-diagram.svg +415 -0
  18. package/docs/code-quality.md +42 -0
  19. package/docs/context.md +40 -0
  20. package/docs/cyc-method-map.md +58 -0
  21. package/docs/cyc-workflow.md +188 -0
  22. package/docs/engineering/code-standards.md +103 -0
  23. package/docs/engineering/domain-design.md +81 -0
  24. package/docs/engineering/failure-handling.md +105 -0
  25. package/docs/impact-analysis.md +70 -0
  26. package/docs/installation.md +198 -0
  27. package/docs/onboarding-recovery.md +75 -0
  28. package/docs/principles.md +49 -0
  29. package/docs/project-tools.md +108 -0
  30. package/docs/response-standard.md +202 -0
  31. package/docs/runtime.md +249 -0
  32. package/docs/skill-contract.md +70 -0
  33. package/docs/skill-craft.md +23 -0
  34. package/docs/validation.md +39 -0
  35. package/docs/work-assessments.md +180 -0
  36. package/hooks/claude.json +10 -0
  37. package/hooks/codex.json +28 -0
  38. package/hooks/cursor.json +8 -0
  39. package/methods/cyc-build/SKILL.md +65 -0
  40. package/methods/cyc-build/references/file-writes.md +11 -0
  41. package/methods/cyc-challenge/SKILL.md +48 -0
  42. package/methods/cyc-context/SKILL.md +76 -0
  43. package/methods/cyc-context/references/evidence.md +27 -0
  44. package/methods/cyc-context/references/templates.md +54 -0
  45. package/methods/cyc-context/scripts/evidence.mjs +61 -0
  46. package/methods/cyc-correct/SKILL.md +43 -0
  47. package/methods/cyc-deliver/SKILL.md +52 -0
  48. package/methods/cyc-design/SKILL.md +50 -0
  49. package/methods/cyc-design/frontend-design/SKILL.md +43 -0
  50. package/methods/cyc-design/frontend-design/references/color.md +77 -0
  51. package/methods/cyc-design/frontend-design/references/craft-rules.md +61 -0
  52. package/methods/cyc-design/frontend-design/references/decision-sheet.md +110 -0
  53. package/methods/cyc-design/frontend-design/references/experience-review.md +58 -0
  54. package/methods/cyc-design/frontend-design/references/generic-tells.md +76 -0
  55. package/methods/cyc-design/frontend-design/references/layout-archetypes.md +188 -0
  56. package/methods/cyc-design/frontend-design/references/reference-standards.md +38 -0
  57. package/methods/cyc-design/frontend-design/references/typography.md +51 -0
  58. package/methods/cyc-design/frontend-design/references/ux-foundations.md +45 -0
  59. package/methods/cyc-design/frontend-design/references/visual-material.md +42 -0
  60. package/methods/cyc-error-ledger/SKILL.md +53 -0
  61. package/methods/cyc-error-ledger/references/entry-format.md +38 -0
  62. package/methods/cyc-explore/SKILL.md +41 -0
  63. package/methods/cyc-frame/SKILL.md +49 -0
  64. package/methods/cyc-impact/SKILL.md +64 -0
  65. package/methods/cyc-reflect/SKILL.md +48 -0
  66. package/methods/cyc-remember/SKILL.md +53 -0
  67. package/methods/cyc-scout/SKILL.md +67 -0
  68. package/methods/cyc-setup/SKILL.md +60 -0
  69. package/methods/cyc-teach/SKILL.md +40 -0
  70. package/methods/cyc-understand/SKILL.md +40 -0
  71. package/methods/cyc-understand/references/diagnose.md +53 -0
  72. package/methods/cyc-verify/SKILL.md +87 -0
  73. package/methods/cyc-verify/references/recipe.md +53 -0
  74. package/package.json +91 -4
  75. package/plugin.json +40 -0
  76. package/rules/cyc-delivery.mdc +33 -0
  77. package/scripts/baseline-worker.mjs +10 -0
  78. package/scripts/catalog.mjs +29 -0
  79. package/scripts/claude-project-hook.mjs +12 -0
  80. package/scripts/context-review.mjs +600 -0
  81. package/scripts/host-activation.mjs +66 -0
  82. package/scripts/install.mjs +387 -0
  83. package/scripts/onboarding.mjs +110 -0
  84. package/scripts/packet.mjs +107 -0
  85. package/scripts/project-tools.mjs +196 -0
  86. package/scripts/recovery.mjs +66 -0
  87. package/scripts/response-gate.mjs +105 -0
  88. package/scripts/response-hook.mjs +237 -0
  89. package/scripts/response-mode.mjs +12 -0
  90. package/scripts/run-gate.mjs +264 -0
  91. package/scripts/runtime.mjs +1832 -0
  92. package/scripts/source-hash-worker.mjs +5 -0
  93. package/scripts/source-snapshot.mjs +405 -0
  94. package/scripts/test-output.mjs +268 -0
  95. package/scripts/work-review.mjs +326 -0
  96. package/skills/cyc/SKILL.md +132 -0
  97. package/skills/cyc/references/playbooks/bug-fix.md +13 -0
  98. package/skills/cyc/references/playbooks/evaluate.md +13 -0
  99. package/skills/cyc/references/playbooks/experience.md +7 -0
  100. package/skills/cyc/references/playbooks/explore.md +9 -0
  101. package/skills/cyc/references/playbooks/feature.md +14 -0
  102. package/skills/cyc/references/playbooks/handoff.md +11 -0
  103. package/skills/cyc/references/playbooks/investigation.md +7 -0
  104. package/skills/cyc/references/playbooks/performance.md +7 -0
  105. package/skills/cyc/references/playbooks/plan.md +11 -0
  106. package/skills/cyc/references/playbooks/refactor.md +12 -0
  107. package/skills/cyc/references/playbooks/reflect.md +11 -0
  108. package/skills/cyc/references/playbooks/resume.md +11 -0
  109. package/skills/cyc/references/playbooks/review.md +9 -0
  110. package/skills/cyc/references/playbooks/teach.md +11 -0
  111. package/skills/cyc/references/playbooks/verify.md +7 -0
@@ -0,0 +1,237 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const engineRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
7
+ let root = engineRoot;
8
+ const host = process.argv[2];
9
+ const prefix = 'CYC_GATE_CONTINUE:';
10
+ const emit = object => console.log(JSON.stringify(object));
11
+ const bullets = items => items.map(item => `- ${item}`).join('\n');
12
+ // Every conversation leaves a state and a review file; a project that runs for months collects
13
+ // hundreds. At each prompt the gate removes its own files older than 14 days, never the current
14
+ // conversation's, and nothing else under .cyc/runtime: drafts, FINISH.json and check output stay.
15
+ const gateFile = /^(?:[a-f0-9]{32}\.(?:state|review)\.json|[a-f0-9]{32}\.state\.json\.corrupt-[^/\\]+|cursor(?:-[a-z0-9-]{4,40})?\.review\.json|[^/\\]+\.tmp)$/;
16
+ function pruneGateFiles(runtime, key) {
17
+ const cutoff = Date.now() - 14 * 24 * 60 * 60 * 1000;
18
+ let names;
19
+ try { names = readdirSync(runtime); } catch { return; }
20
+ for (const name of names) {
21
+ if (name.startsWith(key) || !gateFile.test(name)) continue;
22
+ const path = resolve(runtime, name);
23
+ try { const info = lstatSync(path); if (info.isFile() && info.mtimeMs < cutoff) unlinkSync(path); } catch { /* another process may hold or have removed it; the next prompt tries again */ }
24
+ }
25
+ }
26
+ // Windows editors may save JSON with a byte-order mark; it is not part of the document.
27
+ const load = path => existsSync(path) ? JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, '')) : null;
28
+ function save(path, value) {
29
+ const temporary = `${path}.${randomUUID()}.tmp`;
30
+ writeFileSync(temporary, JSON.stringify(value, null, 2), { mode: 0o600 });
31
+ renameSync(temporary, path);
32
+ }
33
+
34
+ // Host adapters translate each host's hook protocol into three events:
35
+ // prompt (a user request starts), response (final text observed), and stop.
36
+ const adapters = {
37
+ claude: {
38
+ event: { UserPromptSubmit: 'prompt', Stop: 'stop' },
39
+ session: input => input.session_id,
40
+ cwd: input => input.cwd,
41
+ context: text => ({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: text } }),
42
+ block: reason => ({ decision: 'block', reason }),
43
+ halt: message => ({ continue: false, stopReason: message, systemMessage: message })
44
+ },
45
+ // Cursor cannot inject prompt context and its stop event omits the final text,
46
+ // so the text comes from afterAgentResponse and instructions come from a rule file.
47
+ cursor: {
48
+ event: { beforeSubmitPrompt: 'prompt', afterAgentResponse: 'response', stop: 'stop' },
49
+ session: input => input.conversation_id,
50
+ cwd: input => (Array.isArray(input.workspace_roots) && input.workspace_roots[0]) || process.env.CURSOR_PROJECT_DIR || input.cwd,
51
+ context: () => ({ continue: true }),
52
+ block: reason => ({ followup_message: reason }),
53
+ halt: message => ({ followup_message: `${message} Tell the user this response was not certified by the CYC gate.` })
54
+ }
55
+ };
56
+ adapters.codex = adapters.claude;
57
+ const adapter = adapters[host];
58
+
59
+ let event;
60
+ let statePath = null;
61
+ try {
62
+ if (!adapter) throw new Error('Unknown host identifier.');
63
+ const input = JSON.parse(readFileSync(0, 'utf8').replace(/^\uFEFF/, ''));
64
+ event = adapter.event[input.hook_event_name];
65
+ if (!event) throw new Error('Unsupported hook event.');
66
+ // Imported here rather than statically: a missing module must reach the handler below.
67
+ // A crashed hook is a non-blocking error to the host, which would silently skip the gate.
68
+ const [{ checkResponse, digest, normalize }, { allowsLongResponse, lengthCommand }, { changeFingerprint, checkRuns }, { activationBinding }] = await Promise.all(
69
+ ['./response-gate.mjs', './response-mode.mjs', './run-gate.mjs', './host-activation.mjs'].map(module => import(module)));
70
+ // Cursor also runs Claude Code hooks from .claude/settings.json. Let the Cursor adapter own Cursor sessions.
71
+ if (host !== 'cursor' && (process.env.CURSOR_PROJECT_DIR || input.cursor_version || input.conversation_id)) { emit({}); process.exit(0); }
72
+ const session = adapter.session(input);
73
+ if (typeof session !== 'string' || !session) throw new Error('Missing session identifier.');
74
+ const projectIndex = process.argv.indexOf('--project');
75
+ const cwd = adapter.cwd(input);
76
+ if (projectIndex >= 0) {
77
+ if (!process.argv[projectIndex + 1]) throw new Error('--project needs a path.');
78
+ root = resolve(process.argv[projectIndex + 1]);
79
+ } else if (process.env.CYC_PROJECT_ROOT) root = resolve(process.env.CYC_PROJECT_ROOT);
80
+ else if (typeof cwd === 'string') {
81
+ let cursor = resolve(cwd);
82
+ while (true) {
83
+ if (existsSync(resolve(cursor, '.cyc/config.json'))) { root = cursor; break; }
84
+ const parent = dirname(cursor);
85
+ if (parent === cursor) break;
86
+ cursor = parent;
87
+ }
88
+ }
89
+ // Plugin installs are user-wide. Stay silent unless this project activated CYC,
90
+ // and defer to project-installed hooks so a session is never gated twice.
91
+ if (process.argv.includes('--plugin')) {
92
+ const manifest = resolve(root, '.cyc/install-manifest.json');
93
+ const projectHooks = existsSync(manifest) && (() => { try { return Boolean(JSON.parse(readFileSync(manifest, 'utf8')).hooks?.[host]); } catch { return false; } })();
94
+ if (root === engineRoot || !existsSync(resolve(root, '.cyc/config.json')) || projectHooks) { emit({}); process.exit(0); }
95
+ }
96
+ root = realpathSync(root);
97
+ const config = load(resolve(root, '.cyc/config.json')) ?? {};
98
+ const presentation = config.delivery?.presentation ?? 'cyc';
99
+ if (!['cyc', 'project'].includes(presentation)) throw new Error('delivery.presentation must be cyc or project.');
100
+ const defaultCharacterLimitEnabled = config.delivery?.defaultCharacterLimitEnabled ?? true;
101
+ if (typeof defaultCharacterLimitEnabled !== 'boolean') throw new Error('delivery.defaultCharacterLimitEnabled must be a boolean.');
102
+ const runtime = resolve(root, '.cyc/runtime');
103
+ for (const path of [resolve(root, '.cyc'), runtime]) {
104
+ try { if (lstatSync(path).isSymbolicLink()) throw new Error('CYC runtime cannot be a symlink or junction.'); }
105
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
106
+ }
107
+ mkdirSync(runtime, { recursive: true });
108
+ const key = digest(`${host}:${session}`).slice(0, 32);
109
+ statePath = resolve(runtime, `${key}.state.json`);
110
+ // Cursor agents cannot learn their conversation ID. Each picks its own session tag and writes
111
+ // .cyc/runtime/cursor-<tag>.review.json; the hook finds its packet by freshness and exact text.
112
+ let packetPath = resolve(runtime, host === 'cursor' ? 'cursor-<your-session-tag>.review.json' : `${key}.review.json`);
113
+ for (const path of [statePath, packetPath]) {
114
+ try { if (lstatSync(path).isSymbolicLink()) throw new Error('CYC state/review files cannot be symlinks.'); }
115
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
116
+ }
117
+ let state;
118
+ try { state = load(statePath); } catch (error) {
119
+ // A state file that cannot be parsed (a partial write, a stray edit) must not wedge the session:
120
+ // the next prompt sets it aside and starts a fresh request. Stop stays strict and names the file.
121
+ if (event !== 'prompt') throw new Error(`${error.message} in ${statePath}`);
122
+ renameSync(statePath, `${statePath}.corrupt-${randomUUID()}`);
123
+ state = null;
124
+ }
125
+
126
+ const context = () => presentation === 'project' ? `CYC uses project reply formatting. Follow the existing project response rules; no CYC length, visual or review-packet requirement applies. CYC session ID: ${key}. Pass --session ${key} to run start. Controller runs must complete or end with an honest Blocked: or Not ready: handoff. Project ledger lookup: ${config.context?.ledgerPath ?? "use the existing project ledger, otherwise docs/context/error-ledger.md"}. Use run next ledgerPath for authorized failure recording.` : `CYC delivery gate: persistent 1000-character limit is ${state.characterLimitEnabled === false ? 'OFF' : 'ON'} for this conversation. ${allowsLongResponse(state) ? 'No character cap for this response; use as much detail as useful.' : 'Final response must be <=1000 characters including Markdown.'} One-turn expansion: ${state.expanded}. A meaningful visual and all readiness checks remain required. Standalone user commands: limit on, limit off, limit status. Confirm the setting when the user requests a toggle or status. Read ${resolve(engineRoot, 'docs/response-standard.md')}. ${host === 'cursor' ? `Before finishing, write the evidence-backed review to ${packetPath}, including the exact response. Review token: ${state.token}.` : `Before finishing, the evidence-backed review must be at ${packetPath}: a completed \`run finish\` writes it for you. Without one (no run, a blocked handoff, or files changed after finish), \`node "${resolve(engineRoot, 'bin/cyc.mjs')}" packet --session ${key} --passed "criterion :: evidence" --reviewed\` writes it and runs this gate's checks. Review token: ${state.token}. The Stop gate checks your final reply itself: draft it in .cyc/runtime/reply.md, run \`node "${resolve(engineRoot, 'bin/cyc.mjs')}" check-reply .cyc/runtime/reply.md --session ${key}\` to see its character count and visual, and send it unchanged.`}${host === 'cursor' ? '' : ` CYC session ID: ${key}. Pass --session ${key} to \`cyc run start\` so parallel conversations stay independent.`} Fix unmet criteria in the work, not just its description. A blocked handoff must disclose the blocker and cannot claim completion.`;
127
+
128
+ if (event === 'prompt') {
129
+ if (typeof input.prompt !== 'string') throw new Error('Missing user prompt.');
130
+ // Codex and Cursor submit a Stop continuation as another user prompt. Preserve its budget.
131
+ const continuation = state?.pendingReason && input.prompt === state.pendingReason;
132
+ if (!continuation) {
133
+ const command = lengthCommand(input.prompt);
134
+ const characterLimitEnabled = command === 'off' ? false : command === 'on' ? true : state?.characterLimitEnabled ?? defaultCharacterLimitEnabled;
135
+ state = {
136
+ activation: activationBinding(root, host),
137
+ promptAt: new Date().toISOString(),
138
+ token: host === 'cursor' ? 'cursor' : randomUUID(),
139
+ characterLimitEnabled,
140
+ expanded: /^(?:expand[.!]?|\/cyc-expand(?:\s+[\s\S]*)?)$/i.test(input.prompt.trim()),
141
+ attempts: 0,
142
+ pendingReason: null,
143
+ updatedAt: null,
144
+ sourceFingerprint: changeFingerprint(root)
145
+ };
146
+ state.updatedAt = state.promptAt;
147
+ save(statePath, state);
148
+ }
149
+ pruneGateFiles(runtime, key);
150
+ emit(adapter.context(context()));
151
+ } else if (event === 'response') {
152
+ if (state && typeof input.text === 'string') { state.lastResponse = input.text; save(statePath, state); }
153
+ emit({});
154
+ } else {
155
+ // A Cursor stop after an abort or error cannot continue; nothing to certify.
156
+ if (host === 'cursor' && input.status && input.status !== 'completed') { emit({}); process.exit(0); }
157
+ // Also supports a session whose initial prompt preceded installation.
158
+ if (!state) {
159
+ state = { token: host === 'cursor' ? 'cursor' : randomUUID(), characterLimitEnabled: defaultCharacterLimitEnabled, expanded: false, attempts: 0, pendingReason: null };
160
+ }
161
+ const response = host === 'cursor' ? state.lastResponse : input.last_assistant_message;
162
+ let packet = null;
163
+ if (host === 'cursor') {
164
+ // Prefer the fresh packet whose text matches this conversation's reply; otherwise report on the newest.
165
+ const since = Date.parse(state.updatedAt ?? '') || 0;
166
+ const candidates = readdirSync(runtime).filter(name => /^cursor(?:-[a-z0-9-]{4,40})?\.review\.json$/.test(name))
167
+ .map(name => ({ name, path: resolve(runtime, name), mtime: statSync(resolve(runtime, name)).mtimeMs }))
168
+ .filter(item => !lstatSync(item.path).isSymbolicLink())
169
+ .sort((a, b) => b.mtime - a.mtime)
170
+ .map(item => { try { return { ...item, packet: JSON.parse(readFileSync(item.path, 'utf8')) }; } catch { return null; } })
171
+ .filter(Boolean);
172
+ const match = candidates.find(item => item.mtime >= since && typeof response === 'string' && typeof item.packet?.response === 'string' && normalize(item.packet.response) === normalize(response));
173
+ const chosen = match ?? candidates[0];
174
+ if (chosen) {
175
+ packetPath = chosen.path;
176
+ packet = chosen.mtime >= since ? chosen.packet : { ...chosen.packet, token: 'stale' };
177
+ const tag = /^cursor-([a-z0-9-]{4,40})\.review\.json$/.exec(chosen.name)?.[1];
178
+ if (match && tag) state.sessionTag = tag;
179
+ }
180
+ } else {
181
+ try { packet = load(packetPath); } catch { packet = null; }
182
+ }
183
+ // A packet that does not copy the reply is tied to the reply by when it was written: after a
184
+ // rejected Stop, the revised reply needs a review written after the rejection.
185
+ const packetHash = host !== 'cursor' && existsSync(packetPath) ? digest(readFileSync(packetPath)) : null;
186
+ // A packet run finish wrote says nothing about the reply's text, so a revision needs no new one.
187
+ const reviewedAgain = presentation === 'project' || packet?.response !== undefined || packet?.writtenBy === 'run finish' || !packetHash || packetHash !== state.rejectedPacketHash;
188
+ if (presentation === 'project') packet = {
189
+ status: typeof response === 'string' && /^(Blocked:|Not ready:)/i.test(response.trim()) ? 'blocked' : 'ready',
190
+ ...(packet?.token === state.token && typeof packet.advisory === 'string' ? { advisory: packet.advisory } : {})
191
+ };
192
+ const issues = [
193
+ ...(presentation === 'project' && host === 'cursor' && !state.sessionTag ? ['Write the Cursor session identity packet with the exact response and your run session tag.'] : []),
194
+ ...(presentation === 'project' ? [] : checkResponse({ response, packet, token: state.token, expanded: allowsLongResponse(state), root, exactResponse: host === 'cursor' })),
195
+ ...checkRuns({ root, since: state.updatedAt, packet, session: host === 'cursor' ? state.sessionTag : key, fingerprint: state.sourceFingerprint }),
196
+ ...(reviewedAgain ? [] : ['Review the revised reply: run cyc packet --reviewed again after rereading it. A review written before the rejected reply does not cover the new one.'])
197
+ ];
198
+ state.stoppedAt = new Date().toISOString();
199
+ state.stopToken = state.token;
200
+ state.stopResponseHash = typeof response === 'string' ? digest(normalize(response)) : null;
201
+ if (!issues.length) {
202
+ state.pendingReason = null;
203
+ state.lastDecision = packet.status;
204
+ state.stopPacketHash = packetHash;
205
+ save(statePath, state);
206
+ emit({});
207
+ } else if (state.attempts >= 3) {
208
+ state.lastDecision = 'not-ready';
209
+ state.pendingReason = null;
210
+ save(statePath, state);
211
+ emit(adapter.halt(`CYC NOT READY: three correction passes exhausted. No completion certification was issued. Remaining issues:\n${bullets(issues)}`));
212
+ } else {
213
+ state.lastDecision = 'retry';
214
+ state.rejectedPacketHash = packetHash;
215
+ state.attempts += 1;
216
+ // Say now that the revision needs a new review, rather than on the next Stop: a packet that
217
+ // does not copy the reply covers a revised reply only if it is rewritten after this rejection.
218
+ const rereview = presentation !== 'project' && host !== 'cursor' && packet && packet.response === undefined && packet.writtenBy !== 'run finish' && reviewedAgain
219
+ ? [`After revising, rerun cyc packet --session ${key} --reviewed before you stop: the review written before this rejection does not cover the revised reply.`] : [];
220
+ // The prompt already carried the full instructions this request; a correction repeats only
221
+ // what the revision needs. Round 8 paid a model turn per correction on a 1.8 KB message.
222
+ const pointer = presentation === 'project' ? [] : [`Draft the revised reply in .cyc/runtime/reply.md and check it with node "${resolve(engineRoot, 'bin/cyc.mjs')}" check-reply .cyc/runtime/reply.md --session ${key} before sending it unchanged. Packet: ${packetPath}; token ${state.token}.`];
223
+ state.pendingReason = `${prefix} Correction ${state.attempts}/3. Revise the reply:\n${bullets([...issues, ...rereview, ...pointer])}\nIf an external constraint prevents completion, produce an honest blocked handoff. Do not alter the gate or its state to pass.`;
224
+ save(statePath, state);
225
+ emit(adapter.block(state.pendingReason));
226
+ }
227
+ }
228
+ } catch (error) {
229
+ // A gate fault never refuses the user's request; the Stop that follows still cannot certify.
230
+ const where = statePath ? ` State file: ${statePath}.` : '';
231
+ if (event === 'prompt') emit(adapter.context(`CYC delivery gate could not prepare this request (${error.message}).${where} Tell the user the CYC hook needs repair; this response cannot be certified until it is fixed.`));
232
+ else if (event === 'response') emit({});
233
+ else {
234
+ const message = `CYC NOT READY: delivery gate could not run (${error.message}).${where} Repair the hook before claiming verification.`;
235
+ emit(adapter ? adapter.halt(message) : { continue: false, stopReason: message, systemMessage: message });
236
+ }
237
+ }
@@ -0,0 +1,12 @@
1
+ // Only explicit, standalone user commands change a persistent preference.
2
+ export function lengthCommand(prompt) {
3
+ const text = prompt.trim();
4
+ const short = /^(?:limit|\/cyc-limit)\s+(on|off|status)[.!]?$/i.exec(text);
5
+ if (short) return short[1].toLowerCase();
6
+ const natural = /^(?:please\s+)?turn\s+(on|off)\s+(?:the\s+)?(?:1,?000|thousand)[ -]character\s+limit[.!]?$/i.exec(text);
7
+ return natural?.[1].toLowerCase() ?? null;
8
+ }
9
+
10
+ export function allowsLongResponse(state) {
11
+ return state.characterLimitEnabled === false || state.expanded === true;
12
+ }
@@ -0,0 +1,264 @@
1
+ import { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync } from 'node:fs';
2
+ import { dirname, relative, resolve, sep } from 'node:path';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { digest } from './response-gate.mjs';
5
+ import { controllerPath, sourceSnapshot } from './source-snapshot.mjs';
6
+
7
+ // Connects the delivery gate to controller runs. A run counts only if this session owns it
8
+ // (or it is an unowned legacy run) and it was touched during the current request, so parallel
9
+ // conversations in one folder never block each other.
10
+ const lastActivity = run => Math.max(Date.parse(run.startedAt) || 0, ...(run.history ?? []).map(item => Date.parse(item.time) || 0));
11
+
12
+ function gitTop(root) {
13
+ let ancestor = resolve(root);
14
+ while (!existsSync(resolve(ancestor, '.git')) && dirname(ancestor) !== ancestor) ancestor = dirname(ancestor);
15
+ return existsSync(resolve(ancestor, '.git')) ? ancestor : null;
16
+ }
17
+
18
+ export function touchedRuns(root, since, session, others) {
19
+ const roots = new Set([resolve(root)]);
20
+ // Git provides registered checkout locations; never crawl arbitrary sibling directories.
21
+ // Without that listing, still check this checkout's runs rather than refusing every Stop.
22
+ if (session && gitTop(root)) {
23
+ const result = spawnSync('git', ['-C', root, 'worktree', 'list', '--porcelain', '-z'], { encoding: 'utf8', windowsHide: true, timeout: 2000, maxBuffer: 1024 * 1024 });
24
+ if (result.status === 0) {
25
+ for (const field of result.stdout.split('\0')) if (field.startsWith('worktree ')) roots.add(resolve(field.slice(9)));
26
+ }
27
+ }
28
+ return [...roots].flatMap(location => localRuns(location, since, session, location === resolve(root), location === resolve(root) ? others : undefined));
29
+ }
30
+
31
+ // Untracked files beyond this count (unignored dependencies or build output) are compared as one
32
+ // digest of their paths, which keeps the hook fast and its state small.
33
+ const untrackedLimit = 5000;
34
+ // Without optional locks Git never rewrites .git/index, so a concurrent git add or commit is safe.
35
+ const git = (root, args, timeout = 5000) => spawnSync('git', ['--no-optional-locks', '-C', root, ...args], { encoding: 'utf8', windowsHide: true, timeout, maxBuffer: 64 * 1024 * 1024 });
36
+ const projectPath = (root, top, path) => relative(resolve(root), resolve(top, path)).split(sep).join('/');
37
+
38
+ function signature(path, tracked, deadline = Date.now() + changeCheckDeadlineMs) {
39
+ try {
40
+ const stat = lstatSync(path);
41
+ if (stat.isSymbolicLink()) return digest(`symlink:${readlinkSync(path)}`);
42
+ // A submodule or nested repository: what changed inside it, read with what remains of the
43
+ // budget. A reading it could not finish is passed up as 'unavailable', never hashed as content.
44
+ if (stat.isDirectory()) {
45
+ if (!existsSync(resolve(path, '.git'))) return 'directory';
46
+ const nested = changeFingerprint(path, { deadlineMs: Math.max(1, deadline - Date.now()) });
47
+ return nested?.unavailable ? 'unavailable' : digest(JSON.stringify(nested));
48
+ }
49
+ if (!stat.isFile()) return 'not-a-file';
50
+ // Tracked edits are few and compared by content. Untracked files can be numerous, so size
51
+ // and modification time are enough to notice that one changed.
52
+ return tracked && stat.size <= 8 * 1024 * 1024 ? digest(readFileSync(path)) : `stat:${stat.size}:${stat.mtimeMs}`;
53
+ } catch (error) { return error.code === 'ENOENT' ? 'deleted' : `unreadable:${error.code}`; }
54
+ }
55
+
56
+ // What a request changes, compared between its prompt and its Stop. With Git: the checked-out
57
+ // commit and the files Git reports as changed. Without Git: the controller's own source selection.
58
+ // Null when neither can be read, which skips the comparison rather than blocking. A reading that
59
+ // does not finish within its deadline is `unavailable`: the hook has its own time limit from the
60
+ // host, and a hook the host kills never reaches the gate, so a slow reading must be reported, not
61
+ // waited for and not skipped.
62
+ const changeCheckDeadlineMs = 6000;
63
+ export function changeFingerprint(root, { deadlineMs = changeCheckDeadlineMs } = {}) {
64
+ const deadline = Date.now() + deadlineMs;
65
+ const unavailable = what => ({ method: 'git', unavailable: `${what} did not finish within ${Math.ceil(deadlineMs / 1000)} s` });
66
+ const top = gitTop(root);
67
+ if (!top) {
68
+ try { return { method: 'snapshot', files: sourceSnapshot(root, { signatures: 'stat' }).files }; } catch { return null; }
69
+ }
70
+ const result = git(root, ['status', '--porcelain=v2', '--branch', '-z', '--untracked-files=all', '--no-renames', '--', '.'], Math.max(1, Math.min(5000, deadline - Date.now())));
71
+ if (result.error?.code === 'ETIMEDOUT') return unavailable('git status');
72
+ if (result.status !== 0) return null;
73
+ let head = null;
74
+ const tracked = [];
75
+ const untracked = [];
76
+ for (const entry of result.stdout.split('\0')) {
77
+ if (entry.startsWith('# branch.oid ')) head = entry.slice(13);
78
+ else if (entry.startsWith('1 ')) tracked.push(entry.split(' ').slice(8).join(' '));
79
+ else if (entry.startsWith('u ')) tracked.push(entry.split(' ').slice(10).join(' '));
80
+ else if (entry.startsWith('? ')) untracked.push(entry.slice(2));
81
+ }
82
+ // Porcelain paths are relative to the repository root, not to this project.
83
+ const local = paths => paths.map(path => [projectPath(root, top, path), resolve(top, path)]).filter(([path]) => !controllerPath(path));
84
+ const files = {};
85
+ for (const [path, absolute] of local(tracked)) {
86
+ if (Date.now() > deadline) return unavailable('hashing the changed files');
87
+ files[path] = signature(absolute, true, deadline);
88
+ if (files[path] === 'unavailable') return unavailable(`reading the nested repository ${path}`);
89
+ }
90
+ const added = local(untracked);
91
+ if (added.length > untrackedLimit) return { method: 'git', head, files, untracked: { count: added.length, digest: digest(added.map(([path]) => path).sort().join('\0')) } };
92
+ for (const [path, absolute] of added) {
93
+ if (Date.now() > deadline) return unavailable('reading the untracked files');
94
+ files[path] = signature(absolute, false, deadline);
95
+ if (files[path] === 'unavailable') return unavailable(`reading the nested repository ${path}`);
96
+ }
97
+ return { method: 'git', head, files };
98
+ }
99
+
100
+ // A commit made during the request leaves its files clean again; Git still knows what it changed.
101
+ function committedPaths(root, from, to) {
102
+ const top = gitTop(root);
103
+ const result = from === '(initial)'
104
+ ? git(root, ['ls-tree', '-r', '-z', '--name-only', '--full-name', to, '--', '.'])
105
+ : git(root, ['diff', '--no-relative', '--name-only', '-z', from, to, '--', '.']);
106
+ if (result.status !== 0) return [`commits ${from.slice(0, 7)}..${to.slice(0, 7)}`];
107
+ return result.stdout.split('\0').filter(Boolean).map(path => projectPath(root, top, path)).filter(path => !controllerPath(path));
108
+ }
109
+
110
+ function changedPaths(root, before, after) {
111
+ if (!before?.files || !after?.files || before.method !== after.method) return [];
112
+ const changed = new Set([...Object.keys(before.files), ...Object.keys(after.files)].filter(path => before.files[path] !== after.files[path]));
113
+ if (before.untracked?.digest !== after.untracked?.digest) changed.add(`${(after.untracked ?? before.untracked).count} untracked files`);
114
+ if (before.head && after.head && before.head !== after.head && after.head !== '(initial)') for (const path of committedPaths(root, before.head, after.head)) changed.add(path);
115
+ // Committing, resetting or staging moves files in and out of Git's list without changing them.
116
+ // A path changed only if its working-tree content differs from the prompt: its recorded
117
+ // signature, or, for a path clean then, its blob in the commit checked out at the prompt.
118
+ const same = before.method === 'git' ? sameAsCommit(root, before.head, [...changed].filter(path => before.files[path] === undefined)) : new Set();
119
+ const unchanged = path => before.files[path] === undefined ? same.has(path)
120
+ : (after.files[path] ?? signature(resolve(root, path), !before.files[path].startsWith('stat:'))) === before.files[path];
121
+ return [...changed].filter(path => !unchanged(path)).sort();
122
+ }
123
+
124
+ // Paths whose working-tree blob equals their blob in `head`, in two batched Git calls.
125
+ function sameAsCommit(root, head, paths) {
126
+ const files = paths.filter(path => { try { return lstatSync(resolve(root, path)).isFile(); } catch { return false; } });
127
+ if (!head || head === '(initial)' || !files.length) return new Set();
128
+ const top = gitTop(root);
129
+ const run = (args, input) => spawnSync('git', ['--no-optional-locks', '-C', root, ...args], { input, encoding: 'utf8', windowsHide: true, timeout: 5000, maxBuffer: 16 * 1024 * 1024 });
130
+ const current = run(['hash-object', '--stdin-paths'], files.join('\n') + '\n');
131
+ const recorded = run(['cat-file', '--batch-check=%(objectname)'], files.map(path => `${head}:${relative(top, resolve(root, path)).split(sep).join('/')}`).join('\n') + '\n');
132
+ if (current.status !== 0 || recorded.status !== 0) return new Set();
133
+ const now = current.stdout.trim().split('\n');
134
+ const then = recorded.stdout.trim().split('\n');
135
+ return new Set(files.filter((path, index) => now[index] && now[index] === then[index]));
136
+ }
137
+
138
+ export const advisoryReason = packet => typeof packet?.advisory === 'string' && packet.advisory.trim() && !/^<[\s\S]*>$/.test(packet.advisory.trim()) ? packet.advisory.trim() : null;
139
+
140
+ // A request that changed project files owes a controller run. A blocked handoff claims nothing;
141
+ // an advisory reason records why no run applies, such as an explanation, a copy edit, or setup.
142
+ // Another conversation's run touched during this request accounts for the files in its scope.
143
+ function changeIssues(root, before, runs, others, packet, session) {
144
+ if (!before || runs.length || packet?.status === 'blocked' || advisoryReason(packet)) return [];
145
+ const flag = session ? ` --session ${session}` : '';
146
+ const after = changeFingerprint(root);
147
+ // A reading that could not finish is said so: the gate cannot tell whether files changed, and a
148
+ // silent pass here is what a killed hook would also produce.
149
+ const unavailable = before.unavailable ?? after?.unavailable;
150
+ if (unavailable) return [`The change check could not complete (${unavailable}), so the gate cannot tell whether project files changed during this request. Run code changes through run start${flag} and run finish, deliver an honest blocked handoff, or, when no project files changed or no run applies, record why with cyc packet${flag} --advisory "<reason>".`];
151
+ const covered = path => others.some(run => !run.allowedPaths?.length || run.allowedPaths.some(prefix => path === prefix || path.startsWith(`${prefix}/`)));
152
+ const changed = changedPaths(root, before, after).filter(path => !covered(path));
153
+ if (!changed.length) return [];
154
+ const shown = changed.slice(0, 5).join(', ') + (changed.length > 5 ? ` and ${changed.length - 5} more` : '');
155
+ return [`Project files changed during this request without a CYC run for this session (${shown}). Run code changes through run start${flag} and run finish, deliver an honest blocked handoff, or, when no run applies (an explanation, a copy edit, or setup), record why with cyc packet${flag} --advisory "<reason>". Keep reply drafts under .cyc/runtime/.`];
156
+ }
157
+
158
+ function localRuns(root, since, session, includeLegacy, others) {
159
+ const sinceMs = Date.parse(since ?? '');
160
+ const directory = resolve(root, '.cyc/runs');
161
+ if (!Number.isFinite(sinceMs) || !existsSync(directory) || lstatSync(directory).isSymbolicLink()) return [];
162
+ const runs = [];
163
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
164
+ if (!entry.isDirectory() || !/^[a-z0-9-]{1,80}$/.test(entry.name)) continue;
165
+ const path = resolve(directory, entry.name, 'state.json');
166
+ if (!existsSync(path) || lstatSync(path).isSymbolicLink()) continue;
167
+ let run;
168
+ try { run = JSON.parse(readFileSync(path, 'utf8')); } catch { continue; }
169
+ if (!run || typeof run.status !== 'string' || !Array.isArray(run.stages) || lastActivity(run) < sinceMs) continue;
170
+ if (run.session ? run.session === session : includeLegacy) runs.push(run);
171
+ else others?.push(run);
172
+ }
173
+ return runs;
174
+ }
175
+
176
+ export function checkRuns({ root, since, packet, session, fingerprint, now = Date.now() }) {
177
+ const others = [];
178
+ const runs = touchedRuns(root, since, session, others);
179
+ return [...runIssues(runs, packet, now, session), ...changeIssues(root, fingerprint, runs, others, packet, session)];
180
+ }
181
+
182
+ const expired = (run, now) => now - Date.parse(run.startedAt) >= (run.limits?.maxDurationMs ?? Infinity);
183
+ // Ended short of complete: what a blocked handoff reports. A run still within its budget is not
184
+ // a blocker; it has to finish or be recorded blocked first.
185
+ const unfinished = (run, now) => run.status !== 'complete' && !(run.status === 'running' && !expired(run, now));
186
+ const endedAs = run => run.status === 'running' ? 'past its time budget' : run.status;
187
+ // Why a run stopped, in the controller's record: the reason and files logged by the latest status
188
+ // change. Pause and stop log no reason, and a resume clears an earlier one.
189
+ function stopReason(run) {
190
+ const event = run.history?.findLast(item => ['blocked', 'guard-halt', 'exhausted', 'pause', 'stop', 'resume'].includes(item.type));
191
+ if (!event || event.type === 'resume') return null;
192
+ const files = [...(event?.protectedChanges ?? []), ...(event?.outOfScope ?? [])];
193
+ return [event?.reason, files.length ? `Files: ${files.join(', ')}.` : ''].filter(Boolean).join(' ') || null;
194
+ }
195
+
196
+ // The runs that make this request a blocked handoff, so the agent never retypes the controller's record.
197
+ export function blockingRuns({ root, since, session, now = Date.now() }) {
198
+ return touchedRuns(root, since, session).filter(run => unfinished(run, now))
199
+ .map(run => ({ run: run.id, status: endedAs(run), ...(stopReason(run) ? { reason: stopReason(run) } : {}) }));
200
+ }
201
+
202
+ function runIssues(runs, packet, now, session) {
203
+ const issues = [];
204
+ const flag = session ? ` --session ${session}` : '';
205
+ // Claude Code and Codex packets (32-character keys) take the blocked status from the run;
206
+ // Cursor packets have no request window, so they state it.
207
+ const repair = /^[a-f0-9]{32}$/.test(session ?? '') ? `rerun cyc packet${flag} without --status ready, which marks the review blocked from this run,` : `rerun cyc packet${flag} with --status blocked --blocker "<what stops completion>"`;
208
+ for (const run of runs) {
209
+ const label = `CYC run ${run.id} (${run.playbook})`;
210
+ const stage = run.stages[run.stageIndex] ?? 'none';
211
+ if (run.status === 'running' && !expired(run, now)) {
212
+ issues.push(`${label} is still running at stage "${stage}". Continue the loop until verification passes and run complete succeeds, or record it as blocked, paused, or stopped with the controller and deliver an honest blocked handoff.`);
213
+ } else if (run.status !== 'complete' && packet?.status !== 'blocked') {
214
+ issues.push(`${label} ended this request ${endedAs(run)}, not complete. Deliver a blocked handoff: ${repair} and start the reply with "Blocked:" or "Not ready:" saying what stops completion.`);
215
+ }
216
+ }
217
+ // A review run finish wrote vouches only for runs of this request that completed, and the run
218
+ // that wrote it recorded its digest; a packet that only claims run finish wrote it is refused.
219
+ // The writer is named by runId; runIds lists every run whose checks it carries. The writer must be
220
+ // the latest finish in this request to write a packet, so an older genuine packet restored over
221
+ // a newer one is refused too.
222
+ if (packet?.writtenBy === 'run finish') {
223
+ const redo = `Write the review with cyc packet${flag} --reviewed after rereading your reply.`;
224
+ const named = [...new Set([packet.runId, ...(Array.isArray(packet.runIds) ? packet.runIds : [])])];
225
+ for (const id of named) {
226
+ if (runs.find(item => item.id === id)?.status !== 'complete') issues.push(`The review says run finish wrote it, but run ${id ?? '(missing)'} is not a run of this request that completed. ${redo}`);
227
+ }
228
+ const writer = runs.find(item => item.id === packet.runId);
229
+ // Over the packet as parsed, as finish computed it (scripts/packet.mjs runPacketDigest).
230
+ if (writer?.status === 'complete' && writer.reviewPacket?.digest !== digest(JSON.stringify(packet))) issues.push(`The review says run finish wrote it, but it does not match what run ${packet.runId} recorded. ${redo}`);
231
+ const latest = runs.filter(item => item.reviewPacket?.writtenAt).sort((a, b) => Date.parse(a.reviewPacket.writtenAt) - Date.parse(b.reviewPacket.writtenAt)).at(-1);
232
+ if (writer?.status === 'complete' && latest && latest.id !== writer.id) issues.push(`The review is the packet run ${writer.id} wrote, but run ${latest.id} finished later and wrote its own. ${redo}`);
233
+ }
234
+ // A review that names its blocking runs must name unfinished runs of this request.
235
+ for (const entry of Array.isArray(packet?.blockedBy) ? packet.blockedBy : []) {
236
+ const run = runs.find(item => item.id === entry?.run);
237
+ if (!run || !unfinished(run, now)) issues.push(`The review names run ${entry?.run ?? '(missing)'} as its blocker, but that is not an unfinished run of this request. Rerun cyc packet${flag} to record the current runs.`);
238
+ }
239
+ return issues;
240
+ }
241
+
242
+ // Diagnostic only: this inspects controller status, not source freshness or host activation.
243
+ export function sessionReadiness({ root, session, since, now = Date.now() }) {
244
+ if (typeof session !== 'string' || !/^[A-Za-z0-9_-]{4,80}$/.test(session)) throw new Error('Use the current --session ID (4-80 letters, digits, dashes or underscores).');
245
+ const statePath = resolve(root, '.cyc/runtime', `${session}.state.json`);
246
+ let requestWindow = 'explicit';
247
+ if (existsSync(statePath)) {
248
+ if (lstatSync(statePath).isSymbolicLink()) throw new Error('CYC state files cannot be symlinks.');
249
+ if (since !== undefined) throw new Error('Do not override an existing hook request window with --since.');
250
+ since = JSON.parse(readFileSync(statePath, 'utf8')).updatedAt;
251
+ requestWindow = 'hook-state';
252
+ }
253
+ validateRequestWindow(since, now);
254
+ const runs = touchedRuns(root, since, session);
255
+ const issues = runIssues(runs, { status: 'ready' }, now, session);
256
+ return { ok: issues.length === 0, scope: 'controller-status-only', session, since, requestWindow, hostActivation: 'unverified', runs: runs.map(run => ({ id: run.id, status: run.status, stage: run.stages[run.stageIndex] ?? null })), issues,
257
+ limitation: 'This read-only diagnostic does not certify source freshness, task quality, hook activation or delivery. An explicit window may omit work if chosen incorrectly; the Stop hook owns its actual request window.' };
258
+ }
259
+
260
+ export function validateRequestWindow(value, now = Date.now()) {
261
+ const match = typeof value === 'string' && /^(\d{4}-\d{2}-\d{2})T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,3})?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.exec(value);
262
+ if (!match || !Number.isFinite(Date.parse(value)) || Date.parse(value) > now || new Date(`${match[1]}T00:00:00.000Z`).toISOString().slice(0, 10) !== match[1]) throw new Error('No valid request window. Use active hook state or --since with a non-future ISO timestamp for an explicit diagnostic.');
263
+ return value;
264
+ }